diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4052b9f --- /dev/null +++ b/.gitignore @@ -0,0 +1,52 @@ +bam +.bam +config.lua +datasrc/__pycache__ +datasrc/*.pyc +objs +src/game/generated + +crapnet* +config_store* +config_retrieve* +dilate* +fake_server* +map_resave* +map_version* +mastersrv* +packetgen* +teeworlds* +teeworlds_srv* +tileset_border* +twping* +versionsrv* + +Debug +bam +buildlog.txt +bam.exe +*.bat +.cproject +.project +*.dtb +*.log +*.exe +*.res +*.patch +*.prefs +*.lnk +*.pdb +*.sdf +*.sln +*.suo +*.swp +*.vcxproj +*.filters +*.user +*.cmd +.settings +*.opensdf +*.pyc +*.dll + +DDNet* diff --git a/README.md b/README.md new file mode 100644 index 0000000..e0b1180 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +#TeeWare mod +================================ + +A Teeworlds mod based on DDNet, with WarioWare-style gameplay revolving around fast-paced "microgames". diff --git a/autoexec_server.cfg b/autoexec_server.cfg new file mode 100644 index 0000000..c0edab5 --- /dev/null +++ b/autoexec_server.cfg @@ -0,0 +1,191 @@ +# +# autoexec_server.cfg +# +# See http://ddnet.tw/settingscommands for all available settings. +# Everything following a # is considered a comment and ignored by the server. +# When an option can be enabled or disabled, it's enabled with 1, disabled with 0. +# + + + +# GENERAL OPTIONS +# --------------- + +# Server port (only port range 8303-8310 show up in LAN tab) +sv_port 8303 + +# Server name +sv_name "warioware test" + +# Password for joining the server, empty for no password +password "" + +# rcon (F2) passwords for admin. If you don't set one, a random one will be +# created and shown in the terminal window of the server. +sv_rcon_password "poprocks" + +# rcon (F2) password for moderator. If you don't set one, none exists. +sv_rcon_mod_password "" + +# rcon (F2) password for helper. If you don't set one, none exists. +sv_rcon_helper_password "" + +# Map to start server with +sv_map "WarioWare" + +# Whether this is a test server and rcon cheats are allowed. Also indicated in +# the server type, which is: +# - "DDraceNetwork" for 0 (no cheats) and +# - "TestDDraceNetwo" for 1 (cheats) +sv_test_cmds 1 + +# Register server (make it public) +sv_register 1 + + + +# ADVANCED OPTIONS +# ---------------- + +# File where server log will be stored +logfile "autoexec_server.log" + +# Folder where map records will be saved +sv_score_folder "records" + +# Max players on server +sv_max_clients 32 + +# Max players with the same IP address +sv_max_clients_per_ip 4 + +# Tournament mode - when enabled players joins the server as spectator +sv_tournament_mode 0 + +# Whether players can pause their character and make it disappear with the /spec command +sv_pauseable 0 + +# Allow /rescue (also /r) command so players can teleport themselves out of freeze +sv_rescue 0 +# Number of seconds inbetween two rescues +sv_rescue_delay 5 + +# Enable ranks after rcon cheats have been used +sv_rank_cheats 1 + + + +# SERVER CUSTOMIZATION +# -------------------- + +# Message on chat displayed when joining +sv_welcome "" + +# File which will have the announcements (each one in new line) +sv_announcement_filename "announcement.txt" + +# Number of minutes before next announcement will be displayed (from the announcement file) +sv_announcement_interval 120 + +# Whether announcements will be displayed in their order or choosen randomly +sv_announcement_random 0 + +# Message of the day to display when joining the server (use "\n" to create new line) +sv_motd "testing warioware mod" + +# Use default DDRace rules +sv_ddrace_rules 0 + +# Own rules (up to 10 lines) +sv_rules_line1 "no moslems" +sv_rules_line2 "NO MOSLEMS" +sv_rules_line3 "N O M O S L E M S" + +# Reset physics tunes after a map change +sv_tune_reset 1 + +# Reset DDRace tunes after a map change +sv_ddrace_tune_reset 1 + +# Use a config file to execute whenever a map is changed +sv_reset_file "reset.cfg" + + + +# CUSTOM VOTES +# ------------ + +# Format: add_vote "[vote name]" "[command 1]; [command 2]; [command 3]; [...]" +# Example: add_vote "Close server" "sv_name Private DDNet server; password My secret password" +# +# To create empty line in votes just use space in name of vote and command +# "info". Every "empty line" vote should have different number of spaces in its +# name, because each vote text has to be unique. +# Example: add_vote " " "info" +# +# You can learn more about tunes on http://ddnet.tw/settingscommands/#tunings + +add_vote "Who's the biggest troll?" "bigtroll" + + +# ADDITIONAL COMMANDS PERMISSIONS +# ------------------------------- + +# You can see all commands which are accessible for specific authentication-levels by using "access_status" +# Format: access_status [0: admin, 1: moderator, 2: helper or 3: user] +# +# Format: access_level [command] [0: admin, 1: moderator, 2: helper or 3: user] +# Where 0 means only accessible for admin, 1 gives access to moderator and 2 gives access to helper +# Example: mod_command ban 1 + +# Non-default commands to which moderators and helpers will have access +access_level left 2 +access_level right 2 +access_level up 2 +access_level down 2 +access_level super 2 +access_level unsuper 2 +access_level tele 2 +access_level totele 2 +access_level totelecp 2 +access_level logout 2 +access_level ninja 2 +access_level grenade 2 +access_level shotgun 2 +access_level rifle 2 +access_level weapons 2 +access_level unweapons 2 +access_level unrifle 2 +access_level unshotgun 2 +access_level ungrenade 2 +access_level unsolo 2 +access_level undeep 2 +access_level status 2 + +# commands for moderators only +access_level ban 1 +access_level unban 1 +access_level ban_range 1 +access_level unban_range 1 +access_level unban_all 1 +access_level bans 1 +access_level bans_save 1 +access_level kick 1 +access_level force_vote 1 + + + +# SPECIAL BROADCAST-SUGGESTION FOR PLAYERS +# ---------------------------------------- + +# Broadcast to display for players without DDNet client +sv_client_suggestion "Get DDNet client from DDNet.tw to use all features on DDNet!" + +# Broadcast to display for players with a very old version of DDNet client +sv_client_suggestion_old "Your DDNet client is old, update it on DDNet.tw!" + +# Broadcast to display for players with known botting client +sv_client_suggestion_bot "Your client has bots and can be remote controlled!\nPlease use another client like DDNet client from DDNet.tw" + + +sv_emoticon_delay 0 \ No newline at end of file diff --git a/bam.lua b/bam.lua new file mode 100644 index 0000000..2eea1ba --- /dev/null +++ b/bam.lua @@ -0,0 +1,627 @@ +CheckVersion("0.4") + +target_family = os.getenv("TARGET_FAMILY") +if target_family then + family = target_family +end +target_platform = os.getenv("TARGET_PLATFORM") +if target_platform then + platform = target_platform +end +target_arch = os.getenv("TARGET_ARCH") +if target_arch then + arch = target_arch +end + +Import("configure.lua") +Import("other/sdl/sdl.lua") +Import("other/freetype/freetype.lua") +Import("other/curl/curl.lua") +Import("other/opus/opusfile.lua") +Import("other/opus/opus.lua") +Import("other/opus/ogg.lua") +Import("other/mysql/mysql.lua") + +--- Setup Config ------- +config = NewConfig() +config:Add(OptCCompiler("compiler")) +config:Add(OptTestCompileC("stackprotector", "int main(){return 0;}", "-fstack-protector -fstack-protector-all")) +config:Add(OptTestCompileC("minmacosxsdk", "int main(){return 0;}", "-mmacosx-version-min=10.7 -isysroot /Developer/SDKs/MacOSX10.7.sdk")) +config:Add(OptTestCompileC("macosxppc", "int main(){return 0;}", "-arch ppc")) +config:Add(OptLibrary("zlib", "zlib.h", false)) +config:Add(SDL.OptFind("sdl", true)) +config:Add(FreeType.OptFind("freetype", true)) +config:Add(Curl.OptFind("curl", true)) +config:Add(Opusfile.OptFind("opusfile", true)) +config:Add(Opus.OptFind("opus", true)) +config:Add(Ogg.OptFind("ogg", true)) +config:Add(Mysql.OptFind("mysql", false)) +config:Add(OptString("websockets", false)) +config:Finalize("config.lua") + +-- data compiler +function Script(name) + if family == "windows" and target_family ~= "windows" then + return str_replace(name, "/", "\\") + end + return "python " .. name +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) .. " " + end + + cmd = cmd .. " > " .. output + + AddJob(output, "cmd5 " .. output, cmd) + for index, inname in ipairs(inputs) do + AddDependency(output, inname) + end + AddDependency(output, "scripts/cmd5.py") + return output +end + +--[[ +function DuplicateDirectoryStructure(orgpath, srcpath, dstpath) + for _,v in pairs(CollectDirs(srcpath .. "/")) do + MakeDirectory(dstpath .. "/" .. string.sub(v, string.len(orgpath)+2)) + DuplicateDirectoryStructure(orgpath, v, dstpath) + end +end + +DuplicateDirectoryStructure("src", "src", "objs") +]] + +function ResCompile(scriptfile) + windres = os.getenv("WINDRES") + if not windres then + windres = "windres" + end + + scriptfile = Path(scriptfile) + if config.compiler.driver == "cl" then + output = PathBase(scriptfile) .. ".res" + AddJob(output, "rc " .. scriptfile, "rc /fo " .. output .. " " .. scriptfile) + elseif config.compiler.driver == "gcc" then + output = PathBase(scriptfile) .. ".coff" + AddJob(output, windres .. " " .. scriptfile, windres .. " -i " .. scriptfile .. " -o " .. output) + end + + AddDependency(output, scriptfile) + return output +end + +function Dat2c(datafile, sourcefile, arrayname) + datafile = Path(datafile) + sourcefile = Path(sourcefile) + + AddJob( + sourcefile, + "dat2c " .. PathFilename(sourcefile) .. " = " .. PathFilename(datafile), + Script("scripts/dat2c.py").. "\" " .. sourcefile .. " " .. datafile .. " " .. arrayname + ) + AddDependency(sourcefile, datafile) + return sourcefile +end + +function ContentCompile(action, output) + output = Path(output) + AddJob( + output, + action .. " > " .. output, + --Script("datasrc/compile.py") .. "\" ".. Path(output) .. " " .. action + Script("datasrc/compile.py") .. " " .. action .. " > " .. Path(output) + ) + AddDependency(output, Path("datasrc/content.py")) -- do this more proper + AddDependency(output, Path("datasrc/network.py")) + AddDependency(output, Path("datasrc/compile.py")) + AddDependency(output, Path("datasrc/datatypes.py")) + return output +end + +-- Content Compile +network_source = ContentCompile("network_source", "src/game/generated/protocol.cpp") +network_header = ContentCompile("network_header", "src/game/generated/protocol.h") +client_content_source = ContentCompile("client_content_source", "src/game/generated/client_data.cpp") +client_content_header = ContentCompile("client_content_header", "src/game/generated/client_data.h") +server_content_source = ContentCompile("server_content_source", "src/game/generated/server_data.cpp") +server_content_header = ContentCompile("server_content_header", "src/game/generated/server_data.h") + +AddDependency(network_source, network_header) +AddDependency(client_content_source, client_content_header) +AddDependency(server_content_source, server_content_header) + +nethash = CHash("src/game/generated/nethash.cpp", "src/engine/shared/protocol.h", "src/game/generated/protocol.h", "src/game/tuning.h", "src/game/gamecore.cpp", network_header) + +client_link_other = {} +client_depends = {} +server_link_other = {} +server_sql_depends = {} + +if family == "windows" then + if platform == "win32" then + table.insert(client_depends, CopyToDirectory(".", "other/freetype/lib32/freetype.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/sdl/lib32/SDL.dll")) + + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib32/libcurl.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib32/libeay32.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib32/libidn-11.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib32/ssleay32.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib32/zlib1.dll")) + + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib32/libwinpthread-1.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib32/libgcc_s_sjlj-1.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib32/libogg-0.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib32/libopus-0.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib32/libopusfile-0.dll")) + else + table.insert(client_depends, CopyToDirectory(".", "other/freetype/lib64/freetype.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/sdl/lib64/SDL.dll")) + + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib64/libcurl.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib64/libeay32.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib64/ssleay32.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/curl/windows/lib64/zlib1.dll")) + + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib64/libwinpthread-1.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib64/libgcc_s_seh-1.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib64/libogg-0.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib64/libopus-0.dll")) + table.insert(client_depends, CopyToDirectory(".", "other/opus/windows/lib64/libopusfile-0.dll")) + end + table.insert(server_sql_depends, CopyToDirectory(".", "other/mysql/vc2005libs/mysqlcppconn.dll")) + table.insert(server_sql_depends, CopyToDirectory(".", "other/mysql/vc2005libs/libmysql.dll")) + + if config.compiler.driver == "cl" then + client_link_other = {ResCompile("other/icons/teeworlds_cl.rc")} + server_link_other = {ResCompile("other/icons/teeworlds_srv_cl.rc")} + elseif config.compiler.driver == "gcc" then + client_link_other = {ResCompile("other/icons/teeworlds_gcc.rc")} + server_link_other = {ResCompile("other/icons/teeworlds_srv_gcc.rc")} + end +end + +function Intermediate_Output(settings, input) + return "objs/" .. string.sub(PathBase(input), string.len("src/")+1) .. settings.config_ext +end + +function build(settings) + -- apply compiler settings + config.compiler:Apply(settings) + + --settings.objdir = Path("objs") + settings.cc.Output = Intermediate_Output + + cc = os.getenv("CC") + if cc then + settings.cc.exe_c = cc + end + cxx = os.getenv("CXX") + if cxx then + settings.cc.exe_cxx = cxx + settings.link.exe = cxx + settings.dll.exe = cxx + end + cflags = os.getenv("CFLAGS") + if cflags then + settings.cc.flags:Add(cflags) + end + ldflags = os.getenv("LDFLAGS") + if ldflags then + settings.link.flags:Add(ldflags) + end + + if config.websockets.value then + settings.cc.defines:Add("WEBSOCKETS") + end + + if config.compiler.driver == "cl" then + settings.cc.flags:Add("/wd4244") + settings.cc.flags:Add("/EHsc") + else + settings.cc.flags:Add("-Wall") + if family == "windows" then + if config.compiler.driver == "gcc" then + settings.link.flags:Add("-static-libgcc") + settings.link.flags:Add("-static-libstdc++") + --settings.cc.flags:Add("-std=c++11") + end + -- disable visibility attribute support for gcc on windows + settings.cc.defines:Add("NO_VIZ") + elseif platform == "macosx" then + settings.cc.flags:Add("-mmacosx-version-min=10.7") + settings.link.flags:Add("-mmacosx-version-min=10.7") + settings.cc.flags:Add("-stdlib=libc++") + settings.link.flags:Add("-stdlib=libc++") + if config.minmacosxsdk.value == 1 then + settings.cc.flags:Add("-isysroot /Developer/SDKs/MacOSX10.7.sdk") + settings.link.flags:Add("-isysroot /Developer/SDKs/MacOSX10.7.sdk") + end + elseif config.stackprotector.value == 1 then + settings.cc.flags:Add("-fstack-protector", "-fstack-protector-all") + settings.link.flags:Add("-fstack-protector", "-fstack-protector-all") + end + end + + settings.cc.includes:Add("src") + settings.cc.includes:Add("src/engine/external") + + -- set some platform specific settings + if family == "unix" then + if platform == "macosx" then + settings.link.frameworks:Add("Carbon") + settings.link.frameworks:Add("AppKit") + settings.link.libs:Add("crypto") + else + settings.link.libs:Add("pthread") + end + + if platform == "solaris" then + settings.link.flags:Add("-lsocket") + settings.link.flags:Add("-lnsl") + end + elseif family == "windows" then + settings.link.libs:Add("gdi32") + settings.link.libs:Add("user32") + settings.link.libs:Add("ws2_32") + settings.link.libs:Add("ole32") + settings.link.libs:Add("shell32") + settings.link.libs:Add("advapi32") + end + + -- compile zlib if needed + if config.zlib.value == 1 then + settings.link.libs:Add("z") + if config.zlib.include_path then + settings.cc.includes:Add(config.zlib.include_path) + end + zlib = {} + else + zlib = Compile(settings, Collect("src/engine/external/zlib/*.c")) + settings.cc.includes:Add("src/engine/external/zlib") + end + + -- build the small libraries + wavpack = Compile(settings, Collect("src/engine/external/wavpack/*.c")) + pnglite = Compile(settings, Collect("src/engine/external/pnglite/*.c")) + jsonparser = Compile(settings, Collect("src/engine/external/json-parser/*.c")) + md5 = Compile(settings, "src/engine/external/md5/md5.c") + if config.websockets.value then + libwebsockets = Compile(settings, Collect("src/engine/external/libwebsockets/*.c")) + end + + -- build game components + engine_settings = settings:Copy() + server_settings = engine_settings:Copy() + client_settings = engine_settings:Copy() + launcher_settings = engine_settings:Copy() + + if family == "unix" 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.cc.flags:Add("-I/opt/X11/include") + else + client_settings.link.libs:Add("X11") + client_settings.link.libs:Add("GL") + client_settings.link.libs:Add("GLU") + end + + elseif family == "windows" then + if arch == "amd64" then + client_settings.link.libpath:Add("other/curl/windows/lib64") + else + client_settings.link.libpath:Add("other/curl/windows/lib32") + end + client_settings.link.libs:Add("opengl32") + client_settings.link.libs:Add("glu32") + client_settings.link.libs:Add("winmm") + client_settings.link.libs:Add("libopusfile-0") + client_settings.link.libs:Add("curl") + if string.find(settings.config_name, "sql") then + server_settings.link.libpath:Add("other/mysql/vc2005libs") + server_settings.link.libs:Add("mysqlcppconn") + end + end + + config.sdl:Apply(client_settings) + config.freetype:Apply(client_settings) + config.curl:Apply(client_settings) + config.opusfile:Apply(client_settings) + config.opus:Apply(client_settings) + config.ogg:Apply(client_settings) + + if family == "unix" and (platform == "macosx" or platform == "linux") then + engine_settings.link.libs:Add("dl") + server_settings.link.libs:Add("dl") + client_settings.link.libs:Add("dl") + launcher_settings.link.libs:Add("dl") + end + + 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")) + twping = Compile(settings, Collect("src/twping/*.cpp")) + game_shared = Compile(settings, Collect("src/game/*.cpp"), nethash, network_source) + game_client = Compile(client_settings, CollectRecursive("src/game/client/*.cpp"), client_content_source) + game_server = Compile(settings, CollectRecursive("src/game/server/*.cpp"), server_content_source) + game_editor = Compile(settings, Collect("src/game/editor/*.cpp")) + + -- build tools (TODO: fix this so we don't get double _d_d stuff) + tools_src = Collect("src/tools/*.cpp", "src/tools/*.c") + + client_notification = {} + client_osxlaunch = {} + server_osxlaunch = {} + if platform == "macosx" then + notification_settings = client_settings:Copy() + notification_settings.cc.flags:Add("-x objective-c++") + client_notification = Compile(notification_settings, "src/osx/notification.m") + 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, md5) + end + + -- build client, server, version server and master server + client_exe = Link(client_settings, "DDNet", game_shared, game_client, + engine, client, game_editor, zlib, pnglite, wavpack, + client_link_other, client_osxlaunch, jsonparser, libwebsockets, md5, client_notification) + + server_exe = Link(server_settings, "DDNet-Server", engine, server, + game_shared, game_server, zlib, server_link_other, libwebsockets, md5) + + serverlaunch = {} + if platform == "macosx" then + serverlaunch = Link(launcher_settings, "serverlaunch", server_osxlaunch) + end + + versionserver_exe = Link(server_settings, "versionsrv", versionserver, + engine, zlib, libwebsockets, md5) + + masterserver_exe = Link(server_settings, "mastersrv", masterserver, + engine, zlib, md5) + + twping_exe = Link(server_settings, "twping", twping, + engine, zlib, md5) + + -- make targets + c = PseudoTarget("client".."_"..settings.config_name, client_exe, client_depends) + if string.find(settings.config_name, "sql") then + s = PseudoTarget("server".."_"..settings.config_name, server_exe, serverlaunch, server_sql_depends) + else + s = PseudoTarget("server".."_"..settings.config_name, server_exe, serverlaunch) + end + g = PseudoTarget("game".."_"..settings.config_name, client_exe, server_exe) + + v = PseudoTarget("versionserver".."_"..settings.config_name, versionserver_exe) + m = PseudoTarget("masterserver".."_"..settings.config_name, masterserver_exe) + t = PseudoTarget("tools".."_"..settings.config_name, tools) + p = PseudoTarget("twping".."_"..settings.config_name, twping_exe) + + all = PseudoTarget(settings.config_name, c, s, v, m, t, p) + return all +end + + +debug_settings = NewSettings() +debug_settings.config_name = "debug" +debug_settings.config_ext = "_d" +debug_settings.debug = 1 +debug_settings.optimize = 0 +debug_settings.cc.defines:Add("CONF_DEBUG") + +debug_sql_settings = NewSettings() +debug_sql_settings.config_name = "sql_debug" +debug_sql_settings.config_ext = "_sql_d" +debug_sql_settings.debug = 1 +debug_sql_settings.optimize = 0 +debug_sql_settings.cc.defines:Add("CONF_DEBUG", "CONF_SQL") + +release_settings = NewSettings() +release_settings.config_name = "release" +release_settings.config_ext = "" +release_settings.debug = 0 +release_settings.optimize = 1 +release_settings.cc.defines:Add("CONF_RELEASE") + +release_sql_settings = NewSettings() +release_sql_settings.config_name = "sql_release" +release_sql_settings.config_ext = "_sql" +release_sql_settings.debug = 0 +release_sql_settings.optimize = 1 +release_sql_settings.cc.defines:Add("CONF_RELEASE", "CONF_SQL") + +config.mysql:Apply(debug_sql_settings) +config.mysql:Apply(release_sql_settings) + +if platform == "macosx" then + debug_settings_ppc = debug_settings:Copy() + debug_settings_ppc.config_name = "debug_ppc" + debug_settings_ppc.config_ext = "_ppc_d" + debug_settings_ppc.cc.flags:Add("-arch ppc") + debug_settings_ppc.link.flags:Add("-arch ppc") + debug_settings_ppc.cc.defines:Add("CONF_DEBUG") + + debug_sql_settings_ppc = debug_sql_settings:Copy() + debug_sql_settings_ppc.config_name = "sql_debug_ppc" + debug_sql_settings_ppc.config_ext = "_sql_ppc_d" + debug_sql_settings_ppc.cc.flags:Add("-arch ppc") + debug_sql_settings_ppc.link.flags:Add("-arch ppc") + debug_sql_settings_ppc.cc.defines:Add("CONF_DEBUG", "CONF_SQL") + + release_settings_ppc = release_settings:Copy() + release_settings_ppc.config_name = "release_ppc" + release_settings_ppc.config_ext = "_ppc" + release_settings_ppc.cc.flags:Add("-arch ppc") + release_settings_ppc.link.flags:Add("-arch ppc") + release_settings_ppc.cc.defines:Add("CONF_RELEASE") + + release_sql_settings_ppc = release_sql_settings:Copy() + release_sql_settings_ppc.config_name = "sql_release_ppc" + release_sql_settings_ppc.config_ext = "_sql_ppc" + release_sql_settings_ppc.cc.flags:Add("-arch ppc") + release_sql_settings_ppc.link.flags:Add("-arch ppc") + release_sql_settings_ppc.cc.defines:Add("CONF_RELEASE", "CONF_SQL") + + ppc_d = build(debug_settings_ppc) + ppc_r = build(release_settings_ppc) + sql_ppc_d = build(debug_sql_settings_ppc) + sql_ppc_r = build(release_sql_settings_ppc) + + if arch == "ia32" or arch == "amd64" then + debug_settings_x86 = debug_settings:Copy() + debug_settings_x86.config_name = "debug_x86" + debug_settings_x86.config_ext = "_x86_d" + debug_settings_x86.cc.flags:Add("-arch i386") + debug_settings_x86.link.flags:Add("-arch i386") + debug_settings_x86.cc.defines:Add("CONF_DEBUG") + + debug_sql_settings_x86 = debug_sql_settings:Copy() + debug_sql_settings_x86.config_name = "sql_debug_x86" + debug_sql_settings_x86.config_ext = "_sql_x86_d" + debug_sql_settings_x86.cc.flags:Add("-arch i386") + debug_sql_settings_x86.link.flags:Add("-arch i386") + debug_sql_settings_x86.cc.defines:Add("CONF_DEBUG", "CONF_SQL") + + release_settings_x86 = release_settings:Copy() + release_settings_x86.config_name = "release_x86" + release_settings_x86.config_ext = "_x86" + release_settings_x86.cc.flags:Add("-arch i386") + release_settings_x86.link.flags:Add("-arch i386") + release_settings_x86.cc.defines:Add("CONF_RELEASE") + + release_sql_settings_x86 = release_sql_settings:Copy() + release_sql_settings_x86.config_name = "sql_release_x86" + release_sql_settings_x86.config_ext = "_sql_x86" + release_sql_settings_x86.cc.flags:Add("-arch i386") + release_sql_settings_x86.link.flags:Add("-arch i386") + release_sql_settings_x86.cc.defines:Add("CONF_RELEASE", "CONF_SQL") + + x86_d = build(debug_settings_x86) + sql_x86_d = build(debug_sql_settings_x86) + x86_r = build(release_settings_x86) + sql_x86_r = build(release_sql_settings_x86) + end + + if arch == "amd64" then + debug_settings_x86_64 = debug_settings:Copy() + debug_settings_x86_64.config_name = "debug_x86_64" + debug_settings_x86_64.config_ext = "_x86_64_d" + debug_settings_x86_64.cc.flags:Add("-arch x86_64") + debug_settings_x86_64.link.flags:Add("-arch x86_64") + debug_settings_x86_64.cc.defines:Add("CONF_DEBUG") + + debug_sql_settings_x86_64 = debug_sql_settings:Copy() + debug_sql_settings_x86_64.config_name = "sql_debug_x86_64" + debug_sql_settings_x86_64.config_ext = "_sql_x86_64_d" + debug_sql_settings_x86_64.cc.flags:Add("-arch x86_64") + debug_sql_settings_x86_64.link.flags:Add("-arch x86_64") + debug_sql_settings_x86_64.cc.defines:Add("CONF_DEBUG", "CONF_SQL") + + release_settings_x86_64 = release_settings:Copy() + release_settings_x86_64.config_name = "release_x86_64" + release_settings_x86_64.config_ext = "_x86_64" + release_settings_x86_64.cc.flags:Add("-arch x86_64") + release_settings_x86_64.link.flags:Add("-arch x86_64") + release_settings_x86_64.cc.defines:Add("CONF_RELEASE") + + release_sql_settings_x86_64 = release_sql_settings:Copy() + release_sql_settings_x86_64.config_name = "sql_release_x86_64" + release_sql_settings_x86_64.config_ext = "_sql_x86_64" + release_sql_settings_x86_64.cc.flags:Add("-arch x86_64") + release_sql_settings_x86_64.link.flags:Add("-arch x86_64") + release_sql_settings_x86_64.cc.defines:Add("CONF_RELEASE", "CONF_SQL") + + x86_64_d = build(debug_settings_x86_64) + sql_x86_64_d = build(debug_sql_settings_x86_64) + x86_64_r = build(release_settings_x86_64) + sql_x86_64_r = build(release_sql_settings_x86_64) + end + + DefaultTarget("game_debug_x86") + + if config.macosxppc.value == 1 then + if arch == "ia32" then + PseudoTarget("release", ppc_r, x86_r) + PseudoTarget("debug", ppc_d, x86_d) + PseudoTarget("server_release", "server_release_ppc", "server_release_x86") + PseudoTarget("server_debug", "server_debug_ppc", "server_debug_x86") + PseudoTarget("client_release", "client_release_ppc", "client_release_x86") + PseudoTarget("client_debug", "client_debug_ppc", "client_debug_x86") + PseudoTarget("sql_release", sql_ppc_r, sql_x86_r) + PseudoTarget("sql_debug", sql_ppc_d, sql_x86_d) + PseudoTarget("server_sql_release", "server_sql_release_ppc", "server_sql_release_x86") + PseudoTarget("server_sql_debug", "server_sql_debug_ppc", "server_sql_debug_x86") + elseif arch == "amd64" then + PseudoTarget("release", ppc_r, x86_r, x86_64_r) + PseudoTarget("debug", ppc_d, x86_d, x86_64_d) + PseudoTarget("server_release", "server_release_ppc", "server_release_x86", "server_release_x86_64") + PseudoTarget("server_debug", "server_debug_ppc", "server_debug_x86", "server_debug_x86_64") + PseudoTarget("client_release", "client_release_ppc", "client_release_x86", "client_release_x86_64") + PseudoTarget("client_debug", "client_debug_ppc", "client_debug_x86", "client_debug_x86_64") + PseudoTarget("sql_release", sql_ppc_r, sql_x86_r, sql_x86_64_r) + PseudoTarget("sql_debug", sql_ppc_d, sql_x86_d, sql_x86_64_d) + PseudoTarget("server_sql_release", "server_sql_release_ppc", "server_sql_release_x86", "server_sql_release_x86_64") + PseudoTarget("server_sql_debug", "server_sql_debug_ppc", "server_sql_debug_x86", "server_sql_debug_x86_64") + else + PseudoTarget("release", ppc_r) + PseudoTarget("debug", ppc_d) + PseudoTarget("server_release", "server_release_ppc") + PseudoTarget("server_debug", "server_debug_ppc") + PseudoTarget("client_release", "client_release_ppc") + PseudoTarget("client_debug", "client_debug_ppc") + PseudoTarget("sql_release", sql_ppc_r) + PseudoTarget("sql_debug", sql_ppc_d) + PseudoTarget("server_sql_release", "server_sql_release_ppc") + PseudoTarget("server_sql_debug", "server_sql_debug_ppc") + end + else + if arch == "ia32" then + PseudoTarget("release", x86_r) + PseudoTarget("debug", x86_d) + PseudoTarget("server_release", "server_release_x86") + PseudoTarget("server_debug", "server_debug_x86") + PseudoTarget("client_release", "client_release_x86") + PseudoTarget("client_debug", "client_debug_x86") + PseudoTarget("sql_release", sql_x86_r) + PseudoTarget("sql_debug", sql_x86_d) + PseudoTarget("server_sql_release", "server_sql_release_x86") + PseudoTarget("server_sql_debug", "server_sql_debug_x86") + elseif arch == "amd64" then + PseudoTarget("release", x86_r, x86_64_r) + PseudoTarget("debug", x86_d, x86_64_d) + PseudoTarget("server_release", "server_release_x86", "server_release_x86_64") + PseudoTarget("server_debug", "server_debug_x86", "server_debug_x86_64") + PseudoTarget("client_release", "client_release_x86", "client_release_x86_64") + PseudoTarget("client_debug", "client_debug_x86", "client_debug_x86_64") + PseudoTarget("sql_release", sql_x86_r, sql_x86_64_r) + PseudoTarget("sql_debug", sql_x86_d, sql_x86_64_d) + PseudoTarget("server_sql_release", "server_sql_release_x86", "server_sql_release_x86_64") + PseudoTarget("server_sql_debug", "server_sql_debug_x86", "server_sql_debug_x86_64") + end + end +else + build(debug_settings) + build(debug_sql_settings) + build(release_settings) + build(release_sql_settings) + DefaultTarget("game_debug") +end diff --git a/circle.yml b/circle.yml new file mode 100644 index 0000000..f3357ff --- /dev/null +++ b/circle.yml @@ -0,0 +1,18 @@ +dependencies: + pre: + - | + sudo apt-get update; sudo apt-get build-dep teeworlds + + if [ ! -x ~/bam/bam ]; then + git clone https://github.com/matricks/bam ~/bam/ + cd ~/bam; ./make_unix.sh + fi + + cache_directories: + - "~/bam/" + +## Customize test commands +test: + override: + - | + ../bam/bam release diff --git a/configure.lua b/configure.lua new file mode 100644 index 0000000..f06b77d --- /dev/null +++ b/configure.lua @@ -0,0 +1,504 @@ + +--[[@GROUP Configuration@END]]-- + +--[[@FUNCTION + TODO +@END]]-- +function NewConfig(on_configured_callback) + local config = {} + + 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 + v:Apply(s) + end + return s + end + + config.Add = function(self, o) + 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 + valuestr = option[name] + elseif type(option[name]) == type(true) then + valuestr = "false" + if option[name] then + valuestr = "true" + end + elseif type(option[name]) == type("") then + valuestr = "'"..option[name].."'" + else + error("option "..name.." have a value of type ".. type(option[name]).." that can't be saved") + end + self.file:write(option.name.."."..name.." = ".. valuestr.."\n") + end + + -- 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 = {} + mt.__index = function(t, key) + local v = rawget(t, key) + if v ~= nil then return v end + error("there is no configuration option named '" .. key .. "'") + end + + setmetatable(options_table, mt) + + -- Process the options + options_func() + + -- Copy the options + for k,v in pairs(self.options) do + if options_table[v.name] then + for k2,v2 in pairs(options_table[v.name]) do + v[k2] = v2 + end + v.auto_detected = false + end + end + else + print("error: no '"..filename.."' found") + print("") + print("run 'bam config' to generate") + print("run 'bam config help' for configuration options") + print("") + os.exit(1) + end + end + + config.Config = function(self, filename) + print("") + print("configuration:") + if _bam_targets[1] == "print" then + self:Load(filename) + self:Print() + print("") + print("notes:") + self:OnConfigured() + print("") + else + self:Autodetect() + print("") + print("notes:") + if self:OnConfigured() then + self:Save(filename) + end + print("") + end + + end + + config.Autodetect = function(self) + for k,v in pairs(self.options) do + v:Check(self.settings) + print(v:FormatDisplay()) + self[v.name] = v + end + end + + config.PrintHelp = function(self) + print("options:") + for k,v in pairs(self.options) do + if v.PrintHelp then + v:PrintHelp() + end + end + end + + config.Finalize = function(self, filename) + if _bam_targets[0] == "config" then + if _bam_targets[1] == "help" then + self:PrintHelp() + os.exit(0) + end + + self:Config(filename) + + os.exit(0) + end + + self:Load(filename) + bam_update_globalstamp(filename) + end + + return config +end + + +-- Helper functions -------------------------------------- +function DefaultOptionDisplay(option) + if not option.value then return "no" end + if option.value == 1 or option.value == true then return "yes" end + return option.value +end + +function IsNegativeTerm(s) + if s == "no" then return true end + if s == "false" then return true end + if s == "off" then return true end + if s == "disable" then return true end + if s == "0" then return true end + return false +end + +function IsPositiveTerm(s) + if s == "yes" then return true end + if s == "true" then return true end + if s == "on" then return true end + if s == "enable" then return true end + if s == "1" then return true end + return false +end + +function MakeOption(name, value, check, save, display, printhelp) + local o = {} + o.name = name + o.value = value + o.Check = check + o.Save = save + o.auto_detected = true + o.FormatDisplay = function(self) + local a = "SET" + 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 + return o +end + + +-- Test Compile C -------------------------------------- +function OptTestCompileC(name, source, compileoptions, desc) + local check = function(option, settings) + option.value = false + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif IsPositiveTerm(ScriptArgs[option.name]) then + option.value = true + else + error(ScriptArgs[option.name].." is not a valid value for option "..option.name) + end + option.auto_detected = false + else + if CTestCompile(settings, option.source, option.compileoptions) then + option.value = true + 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 + o.compileoptions = compileoptions + return o +end + + +-- OptToggle -------------------------------------- +function OptToggle(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif IsPositiveTerm(ScriptArgs[option.name]) then + option.value = true + else + error(ScriptArgs[option.name].." is not a valid value for option "..option.name) + 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 +end + +-- OptInteger -------------------------------------- +function OptInteger(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + 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 +end + + +-- OptString -------------------------------------- +function OptString(name, default_value, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + 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 +end + +-- Find Compiler -------------------------------------- +--[[@FUNCTION + TODO +@END]]-- +function OptCCompiler(name, default_driver, default_c, default_cxx, desc) + local check = function(option, settings) + if ScriptArgs[option.name] then + -- set compile driver + option.driver = ScriptArgs[option.name] + + -- set c compiler + if ScriptArgs[option.name..".c"] then + option.c_compiler = ScriptArgs[option.name..".c"] + end + + -- set c+= compiler + 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 + -- TODO: test if we can find the compiler + else + if ExecuteSilent("cl") == 0 then + option.driver = "cl" + elseif ExecuteSilent("g++ -v") == 0 then + option.driver = "gcc" + elseif ExecuteSilent("clang++ -v") == 0 then + option.driver = "clang" + else + error("no c/c++ compiler found") + end + end + --setup_compiler(option.value) + end + + local apply = function(option, settings) + if option.driver == "cl" then + SetDriversCL(settings) + elseif option.driver == "gcc" then + SetDriversGCC(settings) + elseif option.driver == "clang" then + SetDriversClang(settings) + else + error(option.driver.." is not a known c/c++ compile driver") + end + + if option.c_compiler then settings.cc.exe_c = option.c_compiler end + if option.cxx_compiler then settings.cc.exe_cxx = option.cxx_compiler end + end + + local save = function(option, output) + output:option(option, "driver") + output:option(option, "c_compiler") + output:option(option, "cxx_compiler") + end + + local printhelp = function(option) + local a = "" + if option.desc then a = "for "..option.desc end + print("\t"..option.name.."=gcc|cl|clang") + print("\t\twhat c/c++ compile driver to use"..a) + print("\t"..option.name..".c=FILENAME") + print("\t\twhat c compiler executable to use"..a) + print("\t"..option.name..".cxx=FILENAME") + print("\t\twhat c++ compiler executable to use"..a) + end + + local display = function(option) + local s = option.driver + if option.c_compiler then s = s .. " c="..option.c_compiler end + 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 + o.c_compiler = false + o.cxx_compiler = false + + if default_driver then o.driver = default_driver end + if default_c then o.c_compiler = default_c end + if default_cxx then o.cxx_compiler = default_cxx end + + o.Apply = apply + return o +end + +-- Option Library -------------------------------------- +--[[@FUNCTION + TODO +@END]]-- +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 "" + end + + for k,v in pairs(paths) do + if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "-I"..v) then + return v + end + end + + return false + end + + if ScriptArgs[option.name] then + if IsNegativeTerm(ScriptArgs[option.name]) then + option.value = false + elseif ScriptArgs[option.name] == "system" then + option.value = true + else + option.value = true + option.include_path = ScriptArgs[option.name] + end + option.auto_detected = false + else + option.include_path = check_compile_include(option.header, {}) + if option.include_path == false then + if option.required then + print(name.." library not found and is required") + error("required library not found") + end + else + option.value = true + option.include_path = false + 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 + return option.include_path + else + return "(in system path)" + end + else + return "not found" + end + end + + local printhelp = function(option) + 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 + o.desc = desc + return o +end + diff --git a/datasrc/compile.py b/datasrc/compile.py new file mode 100644 index 0000000..088e500 --- /dev/null +++ b/datasrc/compile.py @@ -0,0 +1,318 @@ +import os, imp, sys +from datatypes import * +import content +import network + +def create_enum_table(names, num): + lines = [] + lines += ["enum", "{"] + lines += ["\t%s=0,"%names[0]] + for name in names[1:]: + lines += ["\t%s,"%name] + lines += ["\t%s" % num, "};"] + return lines + +def create_flags_table(names): + lines = [] + lines += ["enum", "{"] + i = 0 + for name in names: + lines += ["\t%s = 1<<%d," % (name,i)] + i += 1 + lines += ["};"] + return lines + +def EmitEnum(names, num): + print("enum") + print("{") + print("\t%s=0," % names[0]) + for name in names[1:]: + print("\t%s," % name) + print("\t%s" % num) + print("};") + +def EmitFlags(names, num): + print("enum") + print("{") + i = 0 + for name in names: + print("\t%s = 1<<%d," % (name,i)) + i += 1 + print("};") + +gen_network_header = False +gen_network_source = False +gen_client_content_header = False +gen_client_content_source = False +gen_server_content_header = False +gen_server_content_source = False + +if "network_header" in sys.argv: gen_network_header = True +if "network_source" in sys.argv: gen_network_source = True +if "client_content_header" in sys.argv: gen_client_content_header = True +if "client_content_source" in sys.argv: gen_client_content_source = True +if "server_content_header" in sys.argv: gen_server_content_header = True +if "server_content_source" in sys.argv: gen_server_content_source = True + +if gen_client_content_header: + print("#ifndef CLIENT_CONTENT_HEADER") + print("#define CLIENT_CONTENT_HEADER") + +if gen_server_content_header: + print("#ifndef SERVER_CONTENT_HEADER") + print("#define SERVER_CONTENT_HEADER") + + +if gen_client_content_header or gen_server_content_header: + # emit the type declarations + contentlines = open("datasrc/content.py", "rb").readlines() + order = [] + for line in contentlines: + line = line.strip() + if line[:6] == "class ".encode() and "(Struct)".encode() in line: + order += [line.split()[1].split("(".encode())[0].decode("ascii")] + for name in order: + EmitTypeDeclaration(content.__dict__[name]) + + # the container pointer + print('extern CDataContainer *g_pData;') + + # enums + EmitEnum(["IMAGE_%s"%i.name.value.upper() for i in content.container.images.items], "NUM_IMAGES") + EmitEnum(["ANIM_%s"%i.name.value.upper() for i in content.container.animations.items], "NUM_ANIMS") + EmitEnum(["SPRITE_%s"%i.name.value.upper() for i in content.container.sprites.items], "NUM_SPRITES") + +if gen_client_content_source or gen_server_content_source: + if gen_client_content_source: + print('#include "client_data.h"') + if gen_server_content_source: + print('#include "server_data.h"') + EmitDefinition(content.container, "datacontainer") + print('CDataContainer *g_pData = &datacontainer;') + +# 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("") + + 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") + + print(""" + +class CNetObjHandler +{ + const char *m_pMsgFailedOn; + const char *m_pObjCorrectedOn; + 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(); + + int ValidateObj(int Type, void *pData, int Size); + const char *GetObjName(int Type); + int GetObjSize(int Type); + int NumObjCorrections(); + const char *CorrectedObjOn(); + + const char *GetMsgName(int Type); + void *SecureUnpackMsg(int Type, CUnpacker *pUnpacker); + const char *FailedMsgOn(); +}; + +""") + + print("#endif // GAME_GENERATED_PROTOCOL_H") + + +if gen_network_source: + # create names + lines = [] + + lines += ['#include '] + lines += ['#include '] + lines += ['#include "protocol.h"'] + + lines += ['CNetObjHandler::CNetObjHandler()'] + lines += ['{'] + lines += ['\tm_pMsgFailedOn = "";'] + lines += ['\tm_pObjCorrectedOn = "";'] + lines += ['\tm_NumObjCorrections = 0;'] + lines += ['}'] + lines += [''] + lines += ['int CNetObjHandler::NumObjCorrections() { return m_NumObjCorrections; }'] + lines += ['const char *CNetObjHandler::CorrectedObjOn() { return m_pObjCorrectedOn; }'] + lines += ['const char *CNetObjHandler::FailedMsgOn() { return m_pMsgFailedOn; }'] + lines += [''] + lines += [''] + lines += [''] + lines += [''] + lines += [''] + + lines += ['static const int max_int = 0x7fffffff;'] + + lines += ['int CNetObjHandler::ClampInt(const char *pErrorMsg, int Value, int Min, int Max)'] + lines += ['{'] + lines += ['\tif(Value < Min) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Min; }'] + lines += ['\tif(Value > Max) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Max; }'] + lines += ['\treturn Value;'] + lines += ['}'] + + lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"] + lines += ['\t"invalid",'] + lines += ['\t"%s",' % o.name for o in network.Objects] + lines += ['\t""', "};", ""] + + lines += ["int CNetObjHandler::ms_aObjSizes[] = {"] + lines += ['\t0,'] + lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects] + lines += ['\t0', "};", ""] + + + lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {'] + lines += ['\t"invalid",'] + for msg in network.Messages: + lines += ['\t"%s",' % msg.name] + lines += ['\t""'] + lines += ['};'] + lines += [''] + + lines += ['const char *CNetObjHandler::GetObjName(int Type)'] + lines += ['{'] + lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return "(out of range)";'] + lines += ['\treturn ms_apObjNames[Type];'] + lines += ['};'] + lines += [''] + + lines += ['int CNetObjHandler::GetObjSize(int Type)'] + lines += ['{'] + lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return 0;'] + 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) + + if 0: + for item in network.Objects: + for line in item.emit_validate(): + print(line) + print("") + + # create validate tables + lines = [] + lines += ['static int validate_invalid(void *data, int size) { return -1; }'] + lines += ["typedef int(*VALIDATEFUNC)(void *data, int size);"] + lines += ["static VALIDATEFUNC validate_funcs[] = {"] + lines += ['\tvalidate_invalid,'] + lines += ['\tvalidate_%s,' % o.name for o in network.Objects] + lines += ["\t0x0", "};", ""] + + lines += ["int netobj_validate(int type, void *data, int size)"] + lines += ["{"] + lines += ["\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;"] + lines += ["\treturn validate_funcs[type](data, size);"] + lines += ["};", ""] + + lines = [] + lines += ['int CNetObjHandler::ValidateObj(int Type, void *pData, int Size)'] + lines += ['{'] + lines += ['\tswitch(Type)'] + lines += ['\t{'] + + for item in network.Objects: + for line in item.emit_validate(): + lines += ["\t" + line] + lines += ['\t'] + lines += ['\t}'] + lines += ['\treturn -1;'] + lines += ['};'] + lines += [''] + + #int Validate(int Type, void *pData, int Size); + + if 0: + for item in network.Messages: + for line in item.emit_unpack(): + print(line) + print("") + + lines += ['static void *secure_unpack_invalid(CUnpacker *pUnpacker) { return 0; }'] + lines += ['typedef void *(*SECUREUNPACKFUNC)(CUnpacker *pUnpacker);'] + lines += ['static SECUREUNPACKFUNC secure_unpack_funcs[] = {'] + lines += ['\tsecure_unpack_invalid,'] + for msg in network.Messages: + 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;'] + lines += ['\t}'] + lines += ['\t'] + lines += ['\tif(pUnpacker->Error())'] + lines += ['\t\tm_pMsgFailedOn = "(unpack error)";'] + lines += ['\t'] + lines += ['\tif(m_pMsgFailedOn)'] + lines += ['\t\treturn 0;'] + lines += ['\tm_pMsgFailedOn = "";'] + lines += ['\treturn m_aMsgData;'] + lines += ['};'] + lines += [''] + + + 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 new file mode 100644 index 0000000..a96d8e9 --- /dev/null +++ b/datasrc/content.py @@ -0,0 +1,537 @@ +import copy +from datatypes import * + +class Sound(Struct): + def __init__(self, filename=""): + Struct.__init__(self, "CDataSound") + self.id = Int(0) + self.filename = String(filename) + +class SoundSet(Struct): + def __init__(self, name="", files=[]): + Struct.__init__(self, "CDataSoundset") + self.name = String(name) + self.sounds = Array(Sound()) + self.last = Int(-1) + for name in files: + self.sounds.Add(Sound(name)) + +class Image(Struct): + def __init__(self, name="", filename=""): + Struct.__init__(self, "CDataImage") + 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, "CDataSpriteset") + self.image = Pointer(Image, image) # TODO + self.gridx = Int(gridx) + self.gridy = Int(gridy) + +class Sprite(Struct): + def __init__(self, name="", Set=None, x=0, y=0, w=0, h=0): + Struct.__init__(self, "CDataSprite") + self.name = String(name) + self.set = Pointer(SpriteSet, Set) # TODO + self.x = Int(x) + self.y = Int(y) + self.w = Int(w) + self.h = Int(h) + +class Pickup(Struct): + def __init__(self, name="", respawntime=15, spawndelay=0): + Struct.__init__(self, "CDataPickupspec") + self.name = String(name) + self.respawntime = Int(respawntime) + self.spawndelay = Int(spawndelay) + +class AnimKeyframe(Struct): + def __init__(self, time=0, x=0, y=0, angle=0): + Struct.__init__(self, "CAnimKeyframe") + self.time = Float(time) + self.x = Float(x) + self.y = Float(y) + self.angle = Float(angle) + +class AnimSequence(Struct): + def __init__(self): + Struct.__init__(self, "CAnimSequence") + self.frames = Array(AnimKeyframe()) + +class Animation(Struct): + def __init__(self, name=""): + Struct.__init__(self, "CAnimation") + self.name = String(name) + self.body = AnimSequence() + self.back_foot = AnimSequence() + self.front_foot = AnimSequence() + self.attach = AnimSequence() + +class WeaponSpec(Struct): + def __init__(self, container=None, name=""): + Struct.__init__(self, "CDataWeaponspec") + self.name = String(name) + self.sprite_body = Pointer(Sprite, Sprite()) + self.sprite_cursor = Pointer(Sprite, Sprite()) + 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) + self.damage = Int(1) + + self.offsetx = Float(0) + self.offsety = Float(0) + self.muzzleoffsetx = Float(0) + self.muzzleoffsety = Float(0) + self.muzzleduration = Float(5) + + # dig out sprites if we have a container + if container: + for sprite in container.sprites.items: + if sprite.name.value == "weapon_"+name+"_body": self.sprite_body.Set(sprite) + elif sprite.name.value == "weapon_"+name+"_cursor": self.sprite_cursor.Set(sprite) + elif sprite.name.value == "weapon_"+name+"_proj": self.sprite_proj.Set(sprite) + elif "weapon_"+name+"_muzzle" in sprite.name.value: + self.sprite_muzzles.Add(Pointer(Sprite, sprite)) + +class Weapon_Hammer(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecHammer") + self.base = Pointer(WeaponSpec, WeaponSpec()) + +class Weapon_Gun(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecGun") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(1.25) + self.speed = Float(2200) + self.lifetime = Float(2.0) + +class Weapon_Shotgun(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecShotgun") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(1.25) + self.speed = Float(2200) + self.speeddiff = Float(0.8) + self.lifetime = Float(0.25) + +class Weapon_Grenade(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecGrenade") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.curvature = Float(7.0) + self.speed = Float(1000) + self.lifetime = Float(2.0) + +class Weapon_Rifle(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecRifle") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.reach = Float(800.0) + 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, "CDataWeaponspecNinja") + self.base = Pointer(WeaponSpec, WeaponSpec()) + self.duration = Int(15000) + self.movetime = Int(200) + self.velocity = Int(50) + +class Weapons(Struct): + def __init__(self): + Struct.__init__(self, "CDataWeaponspecs") + self.hammer = Weapon_Hammer() + self.gun = Weapon_Gun() + self.shotgun = Weapon_Shotgun() + self.grenade = Weapon_Grenade() + self.rifle = Weapon_Rifle() + self.ninja = Weapon_Ninja() + self.id = Array(WeaponSpec()) + +class DataContainer(Struct): + def __init__(self): + Struct.__init__(self, "CDataContainer") + self.sounds = Array(SoundSet()) + self.images = Array(Image()) + self.pickups = Array(Pickup()) + self.spritesets = Array(SpriteSet()) + self.sprites = Array(Sprite()) + self.animations = Array(Animation()) + self.weapons = Weapons() + +def FileList(format, num): + return [format%(x+1) for x in range(0,num)] + +container = DataContainer() +container.sounds.Add(SoundSet("gun_fire", FileList("audio/wp_gun_fire-%02d.wv", 3))) +container.sounds.Add(SoundSet("shotgun_fire", FileList("audio/wp_shotty_fire-%02d.wv", 3))) + +container.sounds.Add(SoundSet("grenade_fire", FileList("audio/wp_flump_launch-%02d.wv", 3))) +container.sounds.Add(SoundSet("hammer_fire", FileList("audio/wp_hammer_swing-%02d.wv", 3))) +container.sounds.Add(SoundSet("hammer_hit", FileList("audio/wp_hammer_hit-%02d.wv", 3))) +container.sounds.Add(SoundSet("ninja_fire", FileList("audio/wp_ninja_attack-%02d.wv", 3))) +container.sounds.Add(SoundSet("grenade_explode", FileList("audio/wp_flump_explo-%02d.wv", 3))) +container.sounds.Add(SoundSet("ninja_hit", FileList("audio/wp_ninja_hit-%02d.wv", 3))) +container.sounds.Add(SoundSet("rifle_fire", FileList("audio/wp_rifle_fire-%02d.wv", 3))) +container.sounds.Add(SoundSet("rifle_bounce", FileList("audio/wp_rifle_bnce-%02d.wv", 3))) +container.sounds.Add(SoundSet("weapon_switch", FileList("audio/wp_switch-%02d.wv", 3))) + +container.sounds.Add(SoundSet("player_pain_short", FileList("audio/vo_teefault_pain_short-%02d.wv", 12))) +container.sounds.Add(SoundSet("player_pain_long", FileList("audio/vo_teefault_pain_long-%02d.wv", 2))) + +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_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))) +container.sounds.Add(SoundSet("tee_cry", FileList("audio/vo_teefault_cry-%02d.wv", 2))) + +container.sounds.Add(SoundSet("hook_loop", FileList("audio/hook_loop-%02d.wv", 2))) + +container.sounds.Add(SoundSet("hook_attach_ground", FileList("audio/hook_attach-%02d.wv", 3))) +container.sounds.Add(SoundSet("hook_attach_player", FileList("audio/foley_body_impact-%02d.wv", 3))) +container.sounds.Add(SoundSet("hook_noattach", FileList("audio/hook_noattach-%02d.wv", 2))) +container.sounds.Add(SoundSet("pickup_health", FileList("audio/sfx_pickup_hrt-%02d.wv", 2))) +container.sounds.Add(SoundSet("pickup_armor", FileList("audio/sfx_pickup_arm-%02d.wv", 4))) + +container.sounds.Add(SoundSet("pickup_grenade", ["audio/sfx_pickup_launcher.wv"])) +container.sounds.Add(SoundSet("pickup_shotgun", ["audio/sfx_pickup_sg.wv"])) +container.sounds.Add(SoundSet("pickup_ninja", ["audio/sfx_pickup_ninja.wv"])) +container.sounds.Add(SoundSet("weapon_spawn", FileList("audio/sfx_spawn_wpn-%02d.wv", 3))) +container.sounds.Add(SoundSet("weapon_noammo", FileList("audio/wp_noammo-%02d.wv", 5))) + +container.sounds.Add(SoundSet("hit", FileList("audio/sfx_hit_weak-%02d.wv", 2))) + +container.sounds.Add(SoundSet("chat_server", ["audio/sfx_msg-server.wv"])) +container.sounds.Add(SoundSet("chat_client", ["audio/sfx_msg-client.wv"])) +container.sounds.Add(SoundSet("chat_highlight", ["audio/sfx_msg-highlight.wv"])) +container.sounds.Add(SoundSet("ctf_drop", ["audio/sfx_ctf_drop.wv"])) +container.sounds.Add(SoundSet("ctf_return", ["audio/sfx_ctf_rtn.wv"])) +container.sounds.Add(SoundSet("ctf_grab_pl", ["audio/sfx_ctf_grab_pl.wv"])) +container.sounds.Add(SoundSet("ctf_grab_en", ["audio/sfx_ctf_grab_en.wv"])) +container.sounds.Add(SoundSet("ctf_capture", ["audio/sfx_ctf_cap_pl.wv"])) + +container.sounds.Add(SoundSet("menu", ["audio/music_menu.wv"])) + +image_null = Image("null", "") +image_particles = Image("particles", "particles.png") +image_game = Image("game", "game.png") +image_browseicons = Image("browseicons", "browse_icons.png") +image_emoticons = Image("emoticons", "emoticons.png") +image_speedup_arrow = Image("speedup_arrow", "editor/speed_arrow.png") +image_demobuttons = Image("demobuttons", "demo_buttons.png") +image_fileicons = Image("fileicons", "file_icons.png") +image_guibuttons = Image("guibuttons", "gui_buttons.png") +image_guiicons = Image("guiicons", "gui_icons.png") +image_arrow = Image("arrow", "arrow.png") +image_demobuttons2 = Image("demobuttons2", "demo_buttons2.png") +image_audio_source = Image("audio_source", "editor/audio_source.png") + +container.images.Add(image_null) +container.images.Add(image_game) +container.images.Add(image_particles) +container.images.Add(Image("cursor", "gui_cursor.png")) +container.images.Add(Image("banner", "gui_logo.png")) +container.images.Add(image_emoticons) +container.images.Add(image_browseicons) +container.images.Add(Image("console_bg", "console.png")) +container.images.Add(Image("console_bar", "console_bar.png")) +container.images.Add(image_speedup_arrow) +container.images.Add(image_demobuttons) +container.images.Add(image_fileicons) +container.images.Add(image_guibuttons) +container.images.Add(image_guiicons) +container.images.Add(image_arrow) +container.images.Add(image_demobuttons2) +container.images.Add(image_audio_source) + +container.pickups.Add(Pickup("health")) +container.pickups.Add(Pickup("armor")) +container.pickups.Add(Pickup("weapon")) +container.pickups.Add(Pickup("ninja", 90, 90)) + +set_particles = SpriteSet("particles", image_particles, 8, 8) +set_game = SpriteSet("game", image_game, 32, 16) +set_tee = SpriteSet("tee", image_null, 8, 4) +set_browseicons = SpriteSet("browseicons", image_browseicons, 4, 1) +set_emoticons = SpriteSet("emoticons", image_emoticons, 4, 4) +set_speedup_arrow = SpriteSet("speedup_arrow", image_speedup_arrow, 1, 1) +set_demobuttons = SpriteSet("demobuttons", image_demobuttons, 5, 1) +set_fileicons = SpriteSet("fileicons", image_fileicons, 8, 1) +set_guibuttons = SpriteSet("guibuttons", image_guibuttons, 12, 4) +set_guiicons = SpriteSet("guiicons", image_guiicons, 8, 2) +set_demobuttons2 = SpriteSet("demobuttons2", image_demobuttons2, 3, 1) +set_audio_source = SpriteSet("audio_source", image_audio_source, 1, 1) + +container.spritesets.Add(set_particles) +container.spritesets.Add(set_game) +container.spritesets.Add(set_tee) +container.spritesets.Add(set_browseicons) +container.spritesets.Add(set_emoticons) +container.spritesets.Add(set_speedup_arrow) +container.spritesets.Add(set_demobuttons) +container.spritesets.Add(set_fileicons) +container.spritesets.Add(set_guibuttons) +container.spritesets.Add(set_guiicons) +container.spritesets.Add(set_demobuttons2) +container.spritesets.Add(set_audio_source) + +container.sprites.Add(Sprite("part_slice", set_particles, 0,0,1,1)) +container.sprites.Add(Sprite("part_ball", set_particles, 1,0,1,1)) +container.sprites.Add(Sprite("part_splat01", set_particles, 2,0,1,1)) +container.sprites.Add(Sprite("part_splat02", set_particles, 3,0,1,1)) +container.sprites.Add(Sprite("part_splat03", set_particles, 4,0,1,1)) + +container.sprites.Add(Sprite("part_smoke", set_particles, 0,1,1,1)) +container.sprites.Add(Sprite("part_shell", set_particles, 0,2,2,2)) +container.sprites.Add(Sprite("part_expl01", set_particles, 0,4,4,4)) +container.sprites.Add(Sprite("part_airjump", set_particles, 2,2,2,2)) +container.sprites.Add(Sprite("part_hit01", set_particles, 4,1,2,2)) + +container.sprites.Add(Sprite("health_full", set_game, 21,0,2,2)) +container.sprites.Add(Sprite("health_empty", set_game, 23,0,2,2)) +container.sprites.Add(Sprite("armor_full", set_game, 21,2,2,2)) +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)) +container.sprites.Add(Sprite("part4", set_game, 7,1,1,1)) +container.sprites.Add(Sprite("part5", set_game, 8,0,1,1)) +container.sprites.Add(Sprite("part6", set_game, 8,1,1,1)) +container.sprites.Add(Sprite("part7", set_game, 9,0,2,2)) +container.sprites.Add(Sprite("part8", set_game, 11,0,2,2)) +container.sprites.Add(Sprite("part9", set_game, 13,0,2,2)) + +container.sprites.Add(Sprite("weapon_gun_body", set_game, 2,4,4,2)) +container.sprites.Add(Sprite("weapon_gun_cursor", set_game, 0,4,2,2)) +container.sprites.Add(Sprite("weapon_gun_proj", set_game, 6,4,2,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle1", set_game, 8,4,3,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle2", set_game, 12,4,3,2)) +container.sprites.Add(Sprite("weapon_gun_muzzle3", set_game, 16,4,3,2)) + +container.sprites.Add(Sprite("weapon_shotgun_body", set_game, 2,6,8,2)) +container.sprites.Add(Sprite("weapon_shotgun_cursor", set_game, 0,6,2,2)) +container.sprites.Add(Sprite("weapon_shotgun_proj", set_game, 10,6,2,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle1", set_game, 12,6,3,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle2", set_game, 16,6,3,2)) +container.sprites.Add(Sprite("weapon_shotgun_muzzle3", set_game, 20,6,3,2)) + +container.sprites.Add(Sprite("weapon_grenade_body", set_game, 2,8,7,2)) +container.sprites.Add(Sprite("weapon_grenade_cursor", set_game, 0,8,2,2)) +container.sprites.Add(Sprite("weapon_grenade_proj", set_game, 10,8,2,2)) + +container.sprites.Add(Sprite("weapon_hammer_body", set_game, 2,1,4,3)) +container.sprites.Add(Sprite("weapon_hammer_cursor", set_game, 0,0,2,2)) +container.sprites.Add(Sprite("weapon_hammer_proj", set_game, 0,0,0,0)) + +container.sprites.Add(Sprite("weapon_ninja_body", set_game, 2,10,8,2)) +container.sprites.Add(Sprite("weapon_ninja_cursor", set_game, 0,10,2,2)) +container.sprites.Add(Sprite("weapon_ninja_proj", set_game, 0,0,0,0)) + +container.sprites.Add(Sprite("weapon_rifle_body", set_game, 2,12,7,3)) +container.sprites.Add(Sprite("weapon_rifle_cursor", set_game, 0,12,2,2)) +container.sprites.Add(Sprite("weapon_rifle_proj", set_game, 10,12,2,2)) + +container.sprites.Add(Sprite("hook_chain", set_game, 2,0,1,1)) +container.sprites.Add(Sprite("hook_head", set_game, 3,0,2,1)) + +container.sprites.Add(Sprite("weapon_ninja_muzzle1", set_game, 25,0,7,4)) +container.sprites.Add(Sprite("weapon_ninja_muzzle2", set_game, 25,4,7,4)) +container.sprites.Add(Sprite("weapon_ninja_muzzle3", set_game, 25,8,7,4)) + +container.sprites.Add(Sprite("pickup_health", set_game, 10,2,2,2)) +container.sprites.Add(Sprite("pickup_armor", set_game, 12,2,2,2)) +container.sprites.Add(Sprite("pickup_weapon", set_game, 3,0,6,2)) +container.sprites.Add(Sprite("pickup_ninja", set_game, 2,10,8,2)) + +container.sprites.Add(Sprite("flag_blue", set_game, 12,8,4,8)) +container.sprites.Add(Sprite("flag_red", set_game, 16,8,4,8)) + +container.sprites.Add(Sprite("tee_body", set_tee, 0,0,3,3)) +container.sprites.Add(Sprite("tee_body_outline", set_tee, 3,0,3,3)) +container.sprites.Add(Sprite("tee_foot", set_tee, 6,1,2,1)) +container.sprites.Add(Sprite("tee_foot_outline", set_tee, 6,2,2,1)) +container.sprites.Add(Sprite("tee_hand", set_tee, 6,0,1,1)) +container.sprites.Add(Sprite("tee_hand_outline", set_tee, 7,0,1,1)) +container.sprites.Add(Sprite("tee_eye_normal", set_tee, 2,3,1,1)) +container.sprites.Add(Sprite("tee_eye_angry", set_tee, 3,3,1,1)) +container.sprites.Add(Sprite("tee_eye_pain", set_tee, 4,3,1,1)) +container.sprites.Add(Sprite("tee_eye_happy", set_tee, 5,3,1,1)) +container.sprites.Add(Sprite("tee_eye_dead", set_tee, 6,3,1,1)) +container.sprites.Add(Sprite("tee_eye_surprise", set_tee, 7,3,1,1)) + +container.sprites.Add(Sprite("oop", set_emoticons, 0, 0, 1, 1)) +container.sprites.Add(Sprite("exclamation", set_emoticons, 1, 0, 1, 1)) +container.sprites.Add(Sprite("hearts", set_emoticons, 2, 0, 1, 1)) +container.sprites.Add(Sprite("drop", set_emoticons, 3, 0, 1, 1)) +container.sprites.Add(Sprite("dotdot", set_emoticons, 0, 1, 1, 1)) +container.sprites.Add(Sprite("music", set_emoticons, 1, 1, 1, 1)) +container.sprites.Add(Sprite("sorry", set_emoticons, 2, 1, 1, 1)) +container.sprites.Add(Sprite("ghost", set_emoticons, 3, 1, 1, 1)) +container.sprites.Add(Sprite("sushi", set_emoticons, 0, 2, 1, 1)) +container.sprites.Add(Sprite("splattee", set_emoticons, 1, 2, 1, 1)) +container.sprites.Add(Sprite("deviltee", set_emoticons, 2, 2, 1, 1)) +container.sprites.Add(Sprite("zomg", set_emoticons, 3, 2, 1, 1)) +container.sprites.Add(Sprite("zzz", set_emoticons, 0, 3, 1, 1)) +container.sprites.Add(Sprite("wtf", set_emoticons, 1, 3, 1, 1)) +container.sprites.Add(Sprite("eyes", set_emoticons, 2, 3, 1, 1)) +container.sprites.Add(Sprite("question", set_emoticons, 3, 3, 1, 1)) + +container.sprites.Add(Sprite("browse_lock", set_browseicons, 0,0,1,1)) +container.sprites.Add(Sprite("browse_heart", set_browseicons, 1,0,1,1)) +container.sprites.Add(Sprite("browse_unpure", set_browseicons, 3,0,1,1)) + +container.sprites.Add(Sprite("speedup_arrow", set_speedup_arrow, 0,0,1,1)) + +container.sprites.Add(Sprite("demobutton_play", set_demobuttons, 0,0,1,1)) +container.sprites.Add(Sprite("demobutton_pause", set_demobuttons, 1,0,1,1)) +container.sprites.Add(Sprite("demobutton_stop", set_demobuttons, 2,0,1,1)) +container.sprites.Add(Sprite("demobutton_slower", set_demobuttons, 3,0,1,1)) +container.sprites.Add(Sprite("demobutton_faster", set_demobuttons, 4,0,1,1)) + +container.sprites.Add(Sprite("demobutton_slice_begin", set_demobuttons2, 0,0,1,1)) +container.sprites.Add(Sprite("demobutton_slice_end", set_demobuttons2, 1,0,1,1)) + +container.sprites.Add(Sprite("file_demo1", set_fileicons, 0,0,1,1)) +container.sprites.Add(Sprite("file_demo2", set_fileicons, 1,0,1,1)) +container.sprites.Add(Sprite("file_folder", set_fileicons, 2,0,1,1)) +container.sprites.Add(Sprite("file_map1", set_fileicons, 5,0,1,1)) +container.sprites.Add(Sprite("file_map2", set_fileicons, 6,0,1,1)) + +container.sprites.Add(Sprite("guibutton_off", set_guibuttons, 0,0,4,4)) +container.sprites.Add(Sprite("guibutton_on", set_guibuttons, 4,0,4,4)) +container.sprites.Add(Sprite("guibutton_hover", set_guibuttons, 8,0,4,4)) + +container.sprites.Add(Sprite("guiicon_mute", set_guiicons, 0,0,4,2)) +container.sprites.Add(Sprite("guiicon_friend", set_guiicons, 4,0,4,2)) + +container.sprites.Add(Sprite("audio_source", set_audio_source, 0,0,1,1)) + +anim = Animation("base") +anim.body.frames.Add(AnimKeyframe(0, 0, -4, 0)) +anim.back_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) +container.animations.Add(anim) + +anim = Animation("idle") +anim.back_foot.frames.Add(AnimKeyframe(0, -7, 0, 0)) +anim.front_foot.frames.Add(AnimKeyframe(0, 7, 0, 0)) +container.animations.Add(anim) + +anim = Animation("inair") +anim.back_foot.frames.Add(AnimKeyframe(0, -3, 0, -0.1)) +anim.front_foot.frames.Add(AnimKeyframe(0, 3, 0, -0.1)) +container.animations.Add(anim) + +anim = Animation("walk") +anim.body.frames.Add(AnimKeyframe(0.0, 0, 0, 0)) +anim.body.frames.Add(AnimKeyframe(0.2, 0,-1, 0)) +anim.body.frames.Add(AnimKeyframe(0.4, 0, 0, 0)) +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.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.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(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(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(1.00, 0, 0, -0.25)) +container.animations.Add(anim) + +weapon = WeaponSpec(container, "hammer") +weapon.firedelay.Set(125) +weapon.damage.Set(3) +weapon.visual_size.Set(96) +weapon.offsetx.Set(4) +weapon.offsety.Set(-20) +container.weapons.hammer.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "gun") +weapon.firedelay.Set(125) +weapon.ammoregentime.Set(500) +weapon.visual_size.Set(64) +weapon.offsetx.Set(32) +weapon.offsety.Set(4) +weapon.muzzleoffsetx.Set(50) +weapon.muzzleoffsety.Set(6) +container.weapons.gun.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "shotgun") +weapon.firedelay.Set(500) +weapon.visual_size.Set(96) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +weapon.muzzleoffsetx.Set(70) +weapon.muzzleoffsety.Set(6) +container.weapons.shotgun.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "grenade") +weapon.firedelay.Set(500) # TODO: fix this +weapon.visual_size.Set(96) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +container.weapons.grenade.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "rifle") +weapon.firedelay.Set(800) +weapon.visual_size.Set(92) +weapon.damage.Set(5) +weapon.offsetx.Set(24) +weapon.offsety.Set(-2) +container.weapons.rifle.base.Set(weapon) +container.weapons.id.Add(weapon) + +weapon = WeaponSpec(container, "ninja") +weapon.firedelay.Set(800) +weapon.damage.Set(9) +weapon.visual_size.Set(96) +weapon.offsetx.Set(0) +weapon.offsety.Set(0) +weapon.muzzleoffsetx.Set(40) +weapon.muzzleoffsety.Set(-4) +container.weapons.ninja.base.Set(weapon) +container.weapons.id.Add(weapon) diff --git a/datasrc/datatypes.py b/datasrc/datatypes.py new file mode 100644 index 0000000..3d45d6c --- /dev/null +++ b/datasrc/datatypes.py @@ -0,0 +1,337 @@ +import sys + +GlobalIdCounter = 0 +def GetID(): + global GlobalIdCounter + GlobalIdCounter += 1 + return GlobalIdCounter +def GetUID(): + return "x%d"%GetID() + +def FixCasing(Str): + NewStr = "" + NextUpperCase = True + for c in Str: + if NextUpperCase: + NextUpperCase = False + NewStr += c.upper() + else: + if c == "_": + NextUpperCase = True + else: + NewStr += c.lower() + return NewStr + +def FormatName(type, name): + if "*" in type: + return "m_p" + FixCasing(name) + if "[]" in type: + return "m_a" + FixCasing(name) + return "m_" + FixCasing(name) + +class BaseType: + def __init__(self, type_name): + 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): + self._target_name = target_name + return [] + def EmitDefinition(self, name): + return [] + +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) + def Members(self): + def sorter(a): + return a.var.ID() + m = [] + for name in self.__dict__: + if name[0] == "_": + continue + m += [MemberType(name, self.__dict__[name])] + try: + m.sort(key = sorter) + except: + for v in m: + print(v.name, v.var) + sys.exit(-1) + return m + + def EmitTypeDeclaration(self, name): + lines = [] + lines += ["struct " + self.TypeName()] + lines += ["{"] + for member in self.Members(): + lines += ["\t"+l for l in member.var.EmitDeclaration(member.name)] + lines += ["};"] + return lines + + def EmitPreDefinition(self, target_name): + BaseType.EmitPreDefinition(self, target_name) + lines = [] + for member in self.Members(): + lines += member.var.EmitPreDefinition(target_name+"."+member.name) + return lines + def EmitDefinition(self, name): + lines = ["/* %s */ {" % self.TargetName()] + for member in self.Members(): + lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] + lines += ["}"] + return lines + +class Array(BaseType): + def __init__(self, type): + BaseType.__init__(self, type.TypeName()) + self.type = type + self.items = [] + def Add(self, instance): + if instance.TypeName() != self.type.TypeName(): + error("bah") + self.items += [instance] + def EmitDeclaration(self, name): + return ["int m_Num%s;"%(FixCasing(name)), + "%s *%s;"%(self.TypeName(), FormatName("[]", name))] + def EmitPreDefinition(self, target_name): + BaseType.EmitPreDefinition(self, target_name) + + lines = [] + i = 0 + 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: + itemlines = item.EmitDefinition("") + lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","] + lines += ["};"] + else: + lines += ["static %s *%s = 0;"%(self.TypeName(), self.Identifyer())] + + return lines + def EmitDefinition(self, name): + return [str(len(self.items))+","+self.Identifyer()] + +# Basic Types + +class Int(BaseType): + def __init__(self, value): + BaseType.__init__(self, "int") + self.value = value + def Set(self, value): + self.value = value + 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") + self.value = value + def Set(self, value): + self.value = value + def EmitDefinition(self, name): + return ["%ff"%self.value] + #return ["%d /* %s */"%(self.value, self._target_name)] + +class String(BaseType): + def __init__(self, value): + BaseType.__init__(self, "const char*") + self.value = value + def Set(self, value): + self.value = value + def EmitDefinition(self, name): + return ['"'+self.value+'"'] + +class Pointer(BaseType): + def __init__(self, type, target): + BaseType.__init__(self, "%s*"%type().TypeName()) + self.target = target + def Set(self, target): + self.target = target + def EmitDefinition(self, name): + return ["&"+self.target.TargetName()] + +# helper functions + +def EmitTypeDeclaration(root): + for l in root().EmitTypeDeclaration(""): + print(l) + +def EmitDefinition(root, name): + for l in root.EmitPreDefinition(name): + print(l) + print("%s %s = " % (root.TypeName(), name)) + for l in root.EmitDefinition(name): + print(l) + print(";") + +# Network stuff after this + +class Object: + pass + +class Enum: + def __init__(self, name, values): + self.name = name + self.values = values + +class Flags: + def __init__(self, name, values): + self.name = name + self.values = values + +class NetObject: + def __init__(self, name, variables): + l = name.split(":") + self.name = l[0] + self.base = "" + if len(l) > 1: + self.base = l[1] + self.base_struct_name = "CNetObj_%s" % self.base + self.struct_name = "CNetObj_%s" % self.name + self.enum_name = "NETOBJTYPE_%s" % self.name.upper() + self.variables = variables + def emit_declaration(self): + if self.base: + lines = ["struct %s : public %s"%(self.struct_name,self.base_struct_name), "{"] + else: + lines = ["struct %s"%self.struct_name, "{"] + for v in self.variables: + lines += ["\t"+line for line in v.emit_declaration()] + lines += ["};"] + return lines + def emit_validate(self): + lines = ["case %s:" % self.enum_name] + lines += ["{"] + lines += ["\t%s *pObj = (%s *)pData;"%(self.struct_name, self.struct_name)] + lines += ["\tif(sizeof(*pObj) != Size) return -1;"] + for v in self.variables: + lines += ["\t"+line for line in v.emit_validate()] + lines += ["\treturn 0;"] + lines += ["}"] + return lines + + +class NetEvent(NetObject): + def __init__(self, name, variables): + NetObject.__init__(self, name, variables) + self.base_struct_name = "CNetEvent_%s" % self.base + self.struct_name = "CNetEvent_%s" % self.name + self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() + +class NetMessage(NetObject): + def __init__(self, name, variables): + NetObject.__init__(self, name, variables) + self.base_struct_name = "CNetMsg_%s" % self.base + self.struct_name = "CNetMsg_%s" % self.name + self.enum_name = "NETMSGTYPE_%s" % self.name.upper() + def emit_unpack(self): + lines = [] + lines += ["case %s:" % self.enum_name] + lines += ["{"] + lines += ["\t%s *pMsg = (%s *)m_aMsgData;" % (self.struct_name, self.struct_name)] + lines += ["\t(void)pMsg;"] + for v in self.variables: + lines += ["\t"+line for line in v.emit_unpack()] + for v in self.variables: + lines += ["\t"+line for line in v.emit_unpack_check()] + lines += ["} break;"] + return lines + def emit_declaration(self): + extra = [] + extra += ["\tint MsgID() const { return %s; }" % self.enum_name] + extra += ["\t"] + extra += ["\tbool Pack(CMsgPacker *pPacker)"] + extra += ["\t{"] + #extra += ["\t\tmsg_pack_start(%s, flags);"%self.enum_name] + for v in self.variables: + 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): + self.name = name + def emit_declaration(self): + return [] + def emit_validate(self): + return [] + def emit_pack(self): + return [] + def emit_unpack(self): + return [] + def emit_unpack_check(self): + return [] + +class NetString(NetVariable): + def emit_declaration(self): + return ["const char *%s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetString();" % self.name] + def emit_pack(self): + return ["pPacker->AddString(%s, -1);" % self.name] + +class NetStringHalfStrict(NetVariable): + def emit_declaration(self): + return ["const char *%s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC);" % self.name] + def emit_pack(self): + return ["pPacker->AddString(%s, -1);" % self.name] + +class NetStringStrict(NetVariable): + def emit_declaration(self): + return ["const char *%s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);" % self.name] + def emit_pack(self): + return ["pPacker->AddString(%s, -1);" % self.name] + +class NetIntAny(NetVariable): + def emit_declaration(self): + return ["int %s;"%self.name] + def emit_unpack(self): + return ["pMsg->%s = pUnpacker->GetInt();" % self.name] + def emit_pack(self): + return ["pPacker->AddInt(%s);" % self.name] + +class NetIntRange(NetIntAny): + def __init__(self, name, min, max): + NetIntAny.__init__(self,name) + self.min = str(min) + self.max = str(max) + def emit_validate(self): + return ["pObj->%s = ClampInt(\"%s\", pObj->%s, %s, %s);"%(self.name, self.name, self.name, self.min, self.max)] + def emit_unpack_check(self): + return ["if(pMsg->%s < %s || pMsg->%s > %s) { m_pMsgFailedOn = \"%s\"; break; }" % (self.name, self.min, self.name, self.max, self.name)] + +class NetBool(NetIntRange): + def __init__(self, name): + NetIntRange.__init__(self,name,0,1) + +class NetTick(NetIntAny): + def __init__(self, name): + NetIntAny.__init__(self,name) diff --git a/datasrc/network.py b/datasrc/network.py new file mode 100644 index 0000000..b6cd131 --- /dev/null +++ b/datasrc/network.py @@ -0,0 +1,369 @@ +from datatypes import * + +Emotes = ["NORMAL", "PAIN", "HAPPY", "SURPRISE", "ANGRY", "BLINK"] +PlayerFlags = ["PLAYING", "IN_MENU", "CHATTING", "SCOREBOARD", "AIM"] +GameFlags = ["TEAMS", "FLAGS"] +GameStateFlags = ["GAMEOVER", "SUDDENDEATH", "PAUSED"] + +Emoticons = ["OOP", "EXCLAMATION", "HEARTS", "DROP", "DOTDOT", "MUSIC", "SORRY", "GHOST", "SUSHI", "SPLATTEE", "DEVILTEE", "ZOMG", "ZZZ", "WTF", "EYES", "QUESTION"] + +Powerups = ["HEALTH", "ARMOR", "WEAPON", "NINJA"] + +RawHeader = ''' + +#include + +enum +{ + INPUT_STATE_MASK=0x3f +}; + +enum +{ + TEAM_SPECTATORS=-1, + TEAM_RED, + TEAM_BLUE, + + FLAG_MISSING=-3, + FLAG_ATSTAND, + FLAG_TAKEN, + + SPEC_FREEVIEW=-1, + SPEC_FOLLOW=-2, +}; +''' + +RawSource = ''' +#include +#include "protocol.h" +''' + +Enums = [ + Enum("EMOTE", Emotes), + Enum("POWERUP", Powerups), + Enum("EMOTICON", Emoticons) +] + +Flags = [ + Flags("PLAYERFLAG", PlayerFlags), + Flags("GAMEFLAG", GameFlags), + Flags("GAMESTATEFLAG", GameStateFlags) +] + +Objects = [ + + NetObject("PlayerInput", [ + NetIntAny("m_Direction"), + NetIntAny("m_TargetX"), + NetIntAny("m_TargetY"), + + NetIntAny("m_Jump"), + NetIntAny("m_Fire"), + NetIntAny("m_Hook"), + + NetIntRange("m_PlayerFlags", 0, 256), + + NetIntAny("m_WantedWeapon"), + NetIntAny("m_NextWeapon"), + NetIntAny("m_PrevWeapon"), + ]), + + NetObject("Projectile", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_VelX"), + NetIntAny("m_VelY"), + + NetIntRange("m_Type", 0, 'NUM_WEAPONS-1'), + NetTick("m_StartTick"), + ]), + + NetObject("Laser", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_FromX"), + NetIntAny("m_FromY"), + + NetTick("m_StartTick"), + ]), + + NetObject("Pickup", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + + NetIntRange("m_Type", 0, 'max_int'), + NetIntRange("m_Subtype", 0, 'max_int'), + ]), + + NetObject("Flag", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + + NetIntRange("m_Team", 'TEAM_RED', 'TEAM_BLUE') + ]), + + NetObject("GameInfo", [ + NetIntRange("m_GameFlags", 0, 256), + NetIntRange("m_GameStateFlags", 0, 256), + NetTick("m_RoundStartTick"), + NetIntRange("m_WarmupTimer", 0, 'max_int'), + + NetIntRange("m_ScoreLimit", 0, 'max_int'), + NetIntRange("m_TimeLimit", 0, 'max_int'), + + NetIntRange("m_RoundNum", 0, 'max_int'), + NetIntRange("m_RoundCurrent", 0, 'max_int'), + ]), + + NetObject("GameData", [ + NetIntAny("m_TeamscoreRed"), + NetIntAny("m_TeamscoreBlue"), + + NetIntRange("m_FlagCarrierRed", 'FLAG_MISSING', 'MAX_CLIENTS-1'), + NetIntRange("m_FlagCarrierBlue", 'FLAG_MISSING', 'MAX_CLIENTS-1'), + ]), + + NetObject("CharacterCore", [ + NetIntAny("m_Tick"), + NetIntAny("m_X"), + NetIntAny("m_Y"), + NetIntAny("m_VelX"), + NetIntAny("m_VelY"), + + NetIntAny("m_Angle"), + NetIntRange("m_Direction", -1, 1), + + NetIntRange("m_Jumped", 0, 3), + NetIntRange("m_HookedPlayer", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_HookState", -1, 5), + NetTick("m_HookTick"), + + NetIntAny("m_HookX"), + NetIntAny("m_HookY"), + NetIntAny("m_HookDx"), + NetIntAny("m_HookDy"), + ]), + + NetObject("Character:CharacterCore", [ + NetIntRange("m_PlayerFlags", 0, 256), + NetIntRange("m_Health", 0, 10), + NetIntRange("m_Armor", 0, 10), + NetIntRange("m_AmmoCount", 0, 10), + NetIntRange("m_Weapon", 0, 'NUM_WEAPONS-1'), + NetIntRange("m_Emote", 0, len(Emotes)), + NetIntRange("m_AttackTick", 0, 'max_int'), + ]), + + NetObject("PlayerInfo", [ + NetIntRange("m_Local", 0, 1), + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + + NetIntAny("m_Score"), + NetIntAny("m_Latency"), + ]), + + NetObject("ClientInfo", [ + # 4*4 = 16 charachters + NetIntAny("m_Name0"), NetIntAny("m_Name1"), NetIntAny("m_Name2"), + NetIntAny("m_Name3"), + + # 4*3 = 12 charachters + NetIntAny("m_Clan0"), NetIntAny("m_Clan1"), NetIntAny("m_Clan2"), + + NetIntAny("m_Country"), + + # 4*6 = 24 charachters + NetIntAny("m_Skin0"), NetIntAny("m_Skin1"), NetIntAny("m_Skin2"), + NetIntAny("m_Skin3"), NetIntAny("m_Skin4"), NetIntAny("m_Skin5"), + + NetIntRange("m_UseCustomColor", 0, 1), + + NetIntAny("m_ColorBody"), + NetIntAny("m_ColorFeet"), + ]), + + NetObject("SpectatorInfo", [ + NetIntRange("m_SpectatorID", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'), + NetIntAny("m_X"), + NetIntAny("m_Y"), + ]), + + ## Events + + NetEvent("Common", [ + NetIntAny("m_X"), + NetIntAny("m_Y"), + ]), + + + NetEvent("Explosion:Common", []), + NetEvent("Spawn:Common", []), + NetEvent("HammerHit:Common", []), + + NetEvent("Death:Common", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + ]), + + NetEvent("SoundGlobal:Common", [ #TODO 0.7: remove me + NetIntRange("m_SoundID", 0, 'NUM_SOUNDS-1'), + ]), + + NetEvent("SoundWorld:Common", [ + NetIntRange("m_SoundID", 0, 'NUM_SOUNDS-1'), + ]), + + NetEvent("DamageInd:Common", [ + NetIntAny("m_Angle"), + ]), +] + +Messages = [ + + ### Server messages + NetMessage("Sv_Motd", [ + NetString("m_pMessage"), + ]), + + NetMessage("Sv_Broadcast", [ + NetString("m_pMessage"), + ]), + + NetMessage("Sv_Chat", [ + NetIntRange("m_Team", -2, 3), + NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), + NetStringHalfStrict("m_pMessage"), + ]), + + NetMessage("Sv_KillMsg", [ + NetIntRange("m_Killer", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Victim", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Weapon", -3, 'NUM_WEAPONS-1'), + NetIntAny("m_ModeSpecial"), + ]), + + NetMessage("Sv_SoundGlobal", [ + NetIntRange("m_SoundID", 0, 'NUM_SOUNDS-1'), + ]), + + NetMessage("Sv_TuneParams", []), + NetMessage("Sv_ExtraProjectile", []), + NetMessage("Sv_ReadyToEnter", []), + + NetMessage("Sv_WeaponPickup", [ + NetIntRange("m_Weapon", 0, 'NUM_WEAPONS-1'), + ]), + + NetMessage("Sv_Emoticon", [ + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + NetIntRange("m_Emoticon", 0, 'NUM_EMOTICONS-1'), + ]), + + NetMessage("Sv_VoteClearOptions", [ + ]), + + NetMessage("Sv_VoteOptionListAdd", [ + NetIntRange("m_NumOptions", 1, 15), + NetStringStrict("m_pDescription0"), NetStringStrict("m_pDescription1"), NetStringStrict("m_pDescription2"), + NetStringStrict("m_pDescription3"), NetStringStrict("m_pDescription4"), NetStringStrict("m_pDescription5"), + NetStringStrict("m_pDescription6"), NetStringStrict("m_pDescription7"), NetStringStrict("m_pDescription8"), + NetStringStrict("m_pDescription9"), NetStringStrict("m_pDescription10"), NetStringStrict("m_pDescription11"), + NetStringStrict("m_pDescription12"), NetStringStrict("m_pDescription13"), NetStringStrict("m_pDescription14"), + ]), + + NetMessage("Sv_VoteOptionAdd", [ + NetStringStrict("m_pDescription"), + ]), + + NetMessage("Sv_VoteOptionRemove", [ + NetStringStrict("m_pDescription"), + ]), + + NetMessage("Sv_VoteSet", [ + NetIntRange("m_Timeout", 0, 60), + NetStringStrict("m_pDescription"), + NetStringStrict("m_pReason"), + ]), + + NetMessage("Sv_VoteStatus", [ + NetIntRange("m_Yes", 0, 'MAX_CLIENTS'), + NetIntRange("m_No", 0, 'MAX_CLIENTS'), + NetIntRange("m_Pass", 0, 'MAX_CLIENTS'), + NetIntRange("m_Total", 0, 'MAX_CLIENTS'), + ]), + + ### Client messages + NetMessage("Cl_Say", [ + NetBool("m_Team"), + NetStringHalfStrict("m_pMessage"), + ]), + + NetMessage("Cl_SetTeam", [ + NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), + ]), + + NetMessage("Cl_SetSpectatorMode", [ + NetIntRange("m_SpectatorID", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'), + ]), + + NetMessage("Cl_StartInfo", [ + NetStringStrict("m_pName"), + NetStringStrict("m_pClan"), + NetIntAny("m_Country"), + NetStringStrict("m_pSkin"), + NetBool("m_UseCustomColor"), + NetIntAny("m_ColorBody"), + NetIntAny("m_ColorFeet"), + ]), + + NetMessage("Cl_ChangeInfo", [ + NetStringStrict("m_pName"), + NetStringStrict("m_pClan"), + NetIntAny("m_Country"), + NetStringStrict("m_pSkin"), + NetBool("m_UseCustomColor"), + NetIntAny("m_ColorBody"), + NetIntAny("m_ColorFeet"), + ]), + + NetMessage("Cl_Kill", []), + + NetMessage("Cl_Emoticon", [ + NetIntRange("m_Emoticon", 0, 'NUM_EMOTICONS-1'), + ]), + + NetMessage("Cl_Vote", [ + NetIntRange("m_Vote", -1, 1), + ]), + + NetMessage("Cl_CallVote", [ + NetStringStrict("m_Type"), + NetStringStrict("m_Value"), + NetStringStrict("m_Reason"), + ]), + + NetMessage("Cl_IsDDNet", []), + + NetMessage("Sv_DDRaceTime", [ + NetIntAny("m_Time"), + NetIntAny("m_Check"), + NetIntRange("m_Finish", 0, 1), + ]), + + NetMessage("Sv_Record", [ + NetIntAny("m_ServerTimeBest"), + NetIntAny("m_PlayerTimeBest"), + ]), + + NetMessage("Sv_PlayerTime", [ + NetIntAny("m_Time"), + NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), + ]), + + NetMessage("Sv_TeamsState", []), + + NetMessage("Cl_ShowOthers", [ + NetBool("m_Show"), + ]) +# Can't add any NetMessages here! +] diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..00910ed --- /dev/null +++ b/license.txt @@ -0,0 +1,35 @@ +Teeworlds Copyright (C) 2007-2014 Magnus Auvinen +DDRace Copyright (C) 2010-2011 Shereef Marzouk +DDNet Copyright (C) 2013-2015 Dennis Felsing + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +------------------------------------------------------------------------ + +All content under 'data' except the font (which has its own license) is +released under CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/). + +------------------------------------------------------------------------ + +IMPORTANT NOTE! The source under src/engine/external are stripped +libraries with their own licenses. Mostly BSD or zlib/libpng license but +check the individual libraries. + +------------------------------------------------------------------------ + +With that being said, contact us if there is anything you want to do +that the license does not permit. diff --git a/maps/WarioWare.map b/maps/WarioWare.map new file mode 100644 index 0000000..1ad02a4 Binary files /dev/null and b/maps/WarioWare.map differ diff --git a/other/curl/curl.lua b/other/curl/curl.lua new file mode 100644 index 0000000..67e52ea --- /dev/null +++ b/other/curl/curl.lua @@ -0,0 +1,94 @@ +Curl = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.lib_path = nil + + if IsNegativeTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = false + elseif IsPositiveTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = true + end + + if family ~= "windows" and ExecuteSilent("pkg-config libcurl") == 0 then + option.value = true + if option.use_pkgconfig == nil then + option.use_pkgconfig = true + end + end + + if option.use_pkgconfig == nil then + option.use_pkgconfig = false + end + + if platform == "win32" then + option.value = true + elseif platform == "win64" then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "32") then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "64") then + option.value = true + elseif platform == "linux" and arch == "ia32" then + option.value = true + elseif platform == "linux" and arch == "amd64" then + option.value = true + end + end + + local apply = function(option, settings) + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config --cflags libcurl`") + settings.link.flags:Add("`pkg-config --libs libcurl`") + else + settings.cc.includes:Add(Curl.basepath .. "/include") + + if family ~= "windows" then + settings.link.libs:Add("curl") + settings.link.libs:Add("ssl") + settings.link.libs:Add("crypto") + end + + if platform == "win32" then + settings.link.libpath:Add("other/curl/windows/lib32") + elseif platform == "win64" then + settings.link.libpath:Add("other/curl/windows/lib64") + elseif platform == "macosx" and string.find(settings.config_name, "32") then + settings.link.libpath:Add("other/curl/mac/lib32") + elseif platform == "macosx" and string.find(settings.config_name, "64") then + settings.link.libpath:Add("other/curl/mac/lib64") + elseif platform == "linux" then + settings.link.libpath:Add("other/curl/linux/lib64") + settings.link.libpath:Add("other/curl/linux/lib32") + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + return "using bundled libs" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/curl/include/README b/other/curl/include/README new file mode 100644 index 0000000..3e52a1d --- /dev/null +++ b/other/curl/include/README @@ -0,0 +1,55 @@ + _ _ ____ _ + ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + +Include files for libcurl, external users. + +They're all placed in the curl subdirectory here for better fit in any kind +of environment. You must include files from here using... + + #include + +... style and point the compiler's include path to the directory holding the +curl subdirectory. It makes it more likely to survive future modifications. + +NOTE FOR LIBCURL HACKERS + +The following notes apply to libcurl version 7.19.0 and later. + +* The distributed curl/curlbuild.h file is only intended to be used on systems + which can not run the also distributed configure script. + +* The distributed curlbuild.h file is generated as a copy of curlbuild.h.dist + when the libcurl source code distribution archive file is originally created. + +* If you check out from git on a non-configure platform, you must run the + appropriate buildconf* script to set up curlbuild.h and other local files + before being able of compiling the library. + +* On systems capable of running the configure script, the configure process + will overwrite the distributed include/curl/curlbuild.h file with one that + is suitable and specific to the library being configured and built, which + is generated from the include/curl/curlbuild.h.in template file. + +* If you intend to distribute an already compiled libcurl library you _MUST_ + also distribute along with it the generated curl/curlbuild.h which has been + used to compile it. Otherwise the library will be of no use for the users of + the library that you have built. It is _your_ responsibility to provide this + file. No one at the cURL project can know how you have built the library. + +* File curl/curlbuild.h includes platform and configuration dependent info, + and must not be modified by anyone. Configure script generates it for you. + +* We cannot assume anything else but very basic compiler features being + present. While libcurl requires an ANSI C compiler to build, some of the + earlier ANSI compilers clearly can't deal with some preprocessor operators. + +* Newlines must remain unix-style for older compilers' sake. + +* Comments must be written in the old-style /* unnested C-fashion */ + +To figure out how to do good and portable checks for features, operating +systems or specific hardwarare, a very good resource is Bjorn Reese's +collection at http://predef.sf.net/ diff --git a/other/curl/include/config-win32.h b/other/curl/include/config-win32.h new file mode 100644 index 0000000..744e022 --- /dev/null +++ b/other/curl/include/config-win32.h @@ -0,0 +1,734 @@ +#ifndef HEADER_CURL_CONFIG_WIN32_H +#define HEADER_CURL_CONFIG_WIN32_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* ================================================================ */ +/* Hand crafted config file for Windows */ +/* ================================================================ */ + +/* ---------------------------------------------------------------- */ +/* HEADER FILES */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the header file. */ +/* #define HAVE_ARPA_INET_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_CRYPTO_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_ERRNO_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_ERR_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__POCC__) +#define HAVE_GETOPT_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1800) +#define HAVE_INTTYPES_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_IO_H 1 + +/* Define if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define if you need header even with header file. */ +#if !defined(__SALFORDC__) && !defined(__POCC__) +#define NEED_MALLOC_H 1 +#endif + +/* Define if you have the header file. */ +/* #define HAVE_NETDB_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_NETINET_IN_H 1 */ + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_PROCESS_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_SIGNAL_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_SGTTY_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SSL_H 1 */ + +/* Define to 1 if you have the header file. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1800) +#define HAVE_STDBOOL_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_SYS_PARAM_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SELECT_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKET_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_SYS_SOCKIO_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define if you have the header file. */ +/* #define HAVE_SYS_TIME_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define if you have the header file. */ +#ifndef __BORLANDC__ +#define HAVE_SYS_UTIME_H 1 +#endif + +/* Define if you have the header file. */ +/* #define HAVE_TERMIO_H 1 */ + +/* Define if you have the header file. */ +/* #define HAVE_TERMIOS_H 1 */ + +/* Define if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define if you have the header file. */ +#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__POCC__) +#define HAVE_UNISTD_H 1 +#endif + +/* Define if you have the header file. */ +#define HAVE_WINDOWS_H 1 + +/* Define if you have the header file. */ +#define HAVE_WINSOCK_H 1 + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WINSOCK2_H 1 +#endif + +/* Define if you have the header file. */ +#ifndef __SALFORDC__ +#define HAVE_WS2TCPIP_H 1 +#endif + +/* ---------------------------------------------------------------- */ +/* OTHER HEADER INFO */ +/* ---------------------------------------------------------------- */ + +/* Define if sig_atomic_t is an available typedef. */ +#define HAVE_SIG_ATOMIC_T 1 + +/* Define if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define if you can safely include both and . */ +/* #define TIME_WITH_SYS_TIME 1 */ + +/* Define to 1 if bool is an available type. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1800) +#define HAVE_BOOL_T 1 +#endif + +/* ---------------------------------------------------------------- */ +/* FUNCTIONS */ +/* ---------------------------------------------------------------- */ + +/* Define if you have the closesocket function. */ +#define HAVE_CLOSESOCKET 1 + +/* Define if you don't have vprintf but do have _doprnt. */ +/* #define HAVE_DOPRNT 1 */ + +/* Define if you have the ftruncate function. */ +#define HAVE_FTRUNCATE 1 + +/* Define if you have the gethostbyaddr function. */ +#define HAVE_GETHOSTBYADDR 1 + +/* Define if you have the gethostname function. */ +#define HAVE_GETHOSTNAME 1 + +/* Define if you have the getpass function. */ +/* #define HAVE_GETPASS 1 */ + +/* Define if you have the getservbyname function. */ +#define HAVE_GETSERVBYNAME 1 + +/* Define if you have the getprotobyname function. */ +#define HAVE_GETPROTOBYNAME + +/* Define if you have the gettimeofday function. */ +/* #define HAVE_GETTIMEOFDAY 1 */ + +/* Define if you have the inet_addr function. */ +#define HAVE_INET_ADDR 1 + +/* Define if you have the ioctlsocket function. */ +#define HAVE_IOCTLSOCKET 1 + +/* Define if you have a working ioctlsocket FIONBIO function. */ +#define HAVE_IOCTLSOCKET_FIONBIO 1 + +/* Define if you have the perror function. */ +#define HAVE_PERROR 1 + +/* Define if you have the RAND_screen function when using SSL. */ +#define HAVE_RAND_SCREEN 1 + +/* Define if you have the `RAND_status' function when using SSL. */ +#define HAVE_RAND_STATUS 1 + +/* Define if you have the `CRYPTO_cleanup_all_ex_data' function. + This is present in OpenSSL versions after 0.9.6b */ +#define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1 + +/* Define if you have the select function. */ +#define HAVE_SELECT 1 + +/* Define if you have the setlocale function. */ +#define HAVE_SETLOCALE 1 + +/* Define if you have the setmode function. */ +#define HAVE_SETMODE 1 + +/* Define if you have the setvbuf function. */ +#define HAVE_SETVBUF 1 + +/* Define if you have the socket function. */ +#define HAVE_SOCKET 1 + +/* Define if you have the strcasecmp function. */ +/* #define HAVE_STRCASECMP 1 */ + +/* Define if you have the strdup function. */ +#define HAVE_STRDUP 1 + +/* Define if you have the strftime function. */ +#define HAVE_STRFTIME 1 + +/* Define if you have the stricmp function. */ +#define HAVE_STRICMP 1 + +/* Define if you have the strncasecmp function. */ +/* #define HAVE_STRNCASECMP 1 */ + +/* Define if you have the strnicmp function. */ +#define HAVE_STRNICMP 1 + +/* Define if you have the strstr function. */ +#define HAVE_STRSTR 1 + +/* Define if you have the strtoll function. */ +#if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__POCC__) || \ + (defined(_MSC_VER) && (_MSC_VER >= 1800)) +#define HAVE_STRTOLL 1 +#endif + +/* Define if you have the tcgetattr function. */ +/* #define HAVE_TCGETATTR 1 */ + +/* Define if you have the tcsetattr function. */ +/* #define HAVE_TCSETATTR 1 */ + +/* Define if you have the utime function. */ +#ifndef __BORLANDC__ +#define HAVE_UTIME 1 +#endif + +/* Define to the type qualifier of arg 1 for getnameinfo. */ +#define GETNAMEINFO_QUAL_ARG1 const + +/* Define to the type of arg 1 for getnameinfo. */ +#define GETNAMEINFO_TYPE_ARG1 struct sockaddr * + +/* Define to the type of arg 2 for getnameinfo. */ +#define GETNAMEINFO_TYPE_ARG2 socklen_t + +/* Define to the type of args 4 and 6 for getnameinfo. */ +#define GETNAMEINFO_TYPE_ARG46 DWORD + +/* Define to the type of arg 7 for getnameinfo. */ +#define GETNAMEINFO_TYPE_ARG7 int + +/* Define if you have the recv function. */ +#define HAVE_RECV 1 + +/* Define to the type of arg 1 for recv. */ +#define RECV_TYPE_ARG1 SOCKET + +/* Define to the type of arg 2 for recv. */ +#define RECV_TYPE_ARG2 char * + +/* Define to the type of arg 3 for recv. */ +#define RECV_TYPE_ARG3 int + +/* Define to the type of arg 4 for recv. */ +#define RECV_TYPE_ARG4 int + +/* Define to the function return type for recv. */ +#define RECV_TYPE_RETV int + +/* Define if you have the recvfrom function. */ +#define HAVE_RECVFROM 1 + +/* Define to the type of arg 1 for recvfrom. */ +#define RECVFROM_TYPE_ARG1 SOCKET + +/* Define to the type pointed by arg 2 for recvfrom. */ +#define RECVFROM_TYPE_ARG2 char + +/* Define to the type of arg 3 for recvfrom. */ +#define RECVFROM_TYPE_ARG3 int + +/* Define to the type of arg 4 for recvfrom. */ +#define RECVFROM_TYPE_ARG4 int + +/* Define to the type pointed by arg 5 for recvfrom. */ +#define RECVFROM_TYPE_ARG5 struct sockaddr + +/* Define to the type pointed by arg 6 for recvfrom. */ +#define RECVFROM_TYPE_ARG6 int + +/* Define to the function return type for recvfrom. */ +#define RECVFROM_TYPE_RETV int + +/* Define if you have the send function. */ +#define HAVE_SEND 1 + +/* Define to the type of arg 1 for send. */ +#define SEND_TYPE_ARG1 SOCKET + +/* Define to the type qualifier of arg 2 for send. */ +#define SEND_QUAL_ARG2 const + +/* Define to the type of arg 2 for send. */ +#define SEND_TYPE_ARG2 char * + +/* Define to the type of arg 3 for send. */ +#define SEND_TYPE_ARG3 int + +/* Define to the type of arg 4 for send. */ +#define SEND_TYPE_ARG4 int + +/* Define to the function return type for send. */ +#define SEND_TYPE_RETV int + +/* ---------------------------------------------------------------- */ +/* TYPEDEF REPLACEMENTS */ +/* ---------------------------------------------------------------- */ + +/* Define if in_addr_t is not an available 'typedefed' type. */ +#define in_addr_t unsigned long + +/* Define to the return type of signal handlers (int or void). */ +#define RETSIGTYPE void + +/* Define if ssize_t is not an available 'typedefed' type. */ +#ifndef _SSIZE_T_DEFINED +# if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || \ + defined(__POCC__) || \ + defined(__MINGW32__) +# elif defined(_WIN64) +# define _SSIZE_T_DEFINED +# define ssize_t __int64 +# else +# define _SSIZE_T_DEFINED +# define ssize_t int +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* TYPE SIZES */ +/* ---------------------------------------------------------------- */ + +/* Define to the size of `int', as computed by sizeof. */ +#define SIZEOF_INT 4 + +/* Define to the size of `long double', as computed by sizeof. */ +#define SIZEOF_LONG_DOUBLE 16 + +/* Define to the size of `long long', as computed by sizeof. */ +/* #define SIZEOF_LONG_LONG 8 */ + +/* Define to the size of `short', as computed by sizeof. */ +#define SIZEOF_SHORT 2 + +/* Define to the size of `size_t', as computed by sizeof. */ +#if defined(_WIN64) +# define SIZEOF_SIZE_T 8 +#else +# define SIZEOF_SIZE_T 4 +#endif + +/* ---------------------------------------------------------------- */ +/* BSD-style lwIP TCP/IP stack SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to use BSD-style lwIP TCP/IP stack. */ +/* #define USE_LWIPSOCK 1 */ + +#ifdef USE_LWIPSOCK +# undef USE_WINSOCK +# undef HAVE_WINSOCK_H +# undef HAVE_WINSOCK2_H +# undef HAVE_WS2TCPIP_H +# undef HAVE_ERRNO_H +# undef HAVE_GETHOSTNAME +# undef HAVE_GETNAMEINFO +# undef LWIP_POSIX_SOCKETS_IO_NAMES +# undef RECV_TYPE_ARG1 +# undef RECV_TYPE_ARG3 +# undef SEND_TYPE_ARG1 +# undef SEND_TYPE_ARG3 +# define HAVE_FREEADDRINFO +# define HAVE_GETADDRINFO +# define HAVE_GETHOSTBYNAME +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GETHOSTBYNAME_R_6 +# define LWIP_POSIX_SOCKETS_IO_NAMES 0 +# define RECV_TYPE_ARG1 int +# define RECV_TYPE_ARG3 size_t +# define SEND_TYPE_ARG1 int +# define SEND_TYPE_ARG3 size_t +#endif + +/* ---------------------------------------------------------------- */ +/* Watt-32 tcp/ip SPECIFIC */ +/* ---------------------------------------------------------------- */ + +#ifdef USE_WATT32 + #include + #undef byte + #undef word + #undef USE_WINSOCK + #undef HAVE_WINSOCK_H + #undef HAVE_WINSOCK2_H + #undef HAVE_WS2TCPIP_H + #define HAVE_GETADDRINFO + #define HAVE_GETNAMEINFO + #define HAVE_SYS_IOCTL_H + #define HAVE_SYS_SOCKET_H + #define HAVE_NETINET_IN_H + #define HAVE_NETDB_H + #define HAVE_ARPA_INET_H + #define HAVE_FREEADDRINFO + #define SOCKET int +#endif + + +/* ---------------------------------------------------------------- */ +/* COMPILER SPECIFIC */ +/* ---------------------------------------------------------------- */ + +/* Define to nothing if compiler does not support 'const' qualifier. */ +/* #define const */ + +/* Define to nothing if compiler does not support 'volatile' qualifier. */ +/* #define volatile */ + +/* Windows should not have HAVE_GMTIME_R defined */ +/* #undef HAVE_GMTIME_R */ + +/* Define if the compiler supports C99 variadic macro style. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define HAVE_VARIADIC_MACROS_C99 1 +#endif + +/* Define if the compiler supports the 'long long' data type. */ +#if defined(__MINGW32__) || defined(__WATCOMC__) || \ + (defined(_MSC_VER) && (_MSC_VER >= 1310)) +#define HAVE_LONGLONG 1 +#endif + +/* Define to avoid VS2005 complaining about portable C functions. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define _CRT_SECURE_NO_DEPRECATE 1 +#define _CRT_NONSTDC_NO_DEPRECATE 1 +#endif + +/* VS2005 and later dafault size for time_t is 64-bit, unless + _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +# ifndef _USE_32BIT_TIME_T +# define SIZEOF_TIME_T 8 +# else +# define SIZEOF_TIME_T 4 +# endif +#endif + +/* Define some minimum and default build targets for Visual Studio */ +#if defined(_MSC_VER) + /* Officially, Microsoft's Windows SDK versions 6.X does not support Windows + 2000 as a supported build target. VS2008 default installations provides + an embedded Windows SDK v6.0A along with the claim that Windows 2000 is a + valid build target for VS2008. Popular belief is that binaries built with + VS2008 using Windows SDK versions v6.X and Windows 2000 as a build target + are functional. */ +# define VS2008_MIN_TARGET 0x0500 + + /* The minimum build target for VS2012 is Vista unless Update 1 is installed + and the v110_xp toolset is choosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_MIN_TARGET 0x0501 +# else +# define VS2012_MIN_TARGET 0x0600 +# endif + + /* VS2008 default build target is Windows Vista. We override default target + to be Windows XP. */ +# define VS2008_DEF_TARGET 0x0501 + + /* VS2012 default build target is Windows Vista unless Update 1 is installed + and the v110_xp toolset is choosen. */ +# if defined(_USING_V110_SDK71_) +# define VS2012_DEF_TARGET 0x0501 +# else +# define VS2012_DEF_TARGET 0x0600 +# endif +#endif + +/* VS2008 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_MSC_VER <= 1600) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2008_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2008_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2008_MIN_TARGET) || (WINVER < VS2008_MIN_TARGET) +# error VS2008 does not support Windows build targets prior to Windows 2000 +# endif +#endif + +/* VS2012 default target settings and minimum build target check. */ +#if defined(_MSC_VER) && (_MSC_VER >= 1700) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT VS2012_DEF_TARGET +# endif +# ifndef WINVER +# define WINVER VS2012_DEF_TARGET +# endif +# if (_WIN32_WINNT < VS2012_MIN_TARGET) || (WINVER < VS2012_MIN_TARGET) +# if defined(_USING_V110_SDK71_) +# error VS2012 does not support Windows build targets prior to Windows XP +# else +# error VS2012 does not support Windows build targets prior to Windows \ +Vista +# endif +# endif +#endif + +/* When no build target is specified Pelles C 5.00 and later default build + target is Windows Vista. We override default target to be Windows 2000. */ +#if defined(__POCC__) && (__POCC__ >= 500) +# ifndef _WIN32_WINNT +# define _WIN32_WINNT 0x0500 +# endif +# ifndef WINVER +# define WINVER 0x0500 +# endif +#endif + +/* Availability of freeaddrinfo, getaddrinfo and getnameinfo functions is + quite convoluted, compiler dependent and even build target dependent. */ +#if defined(HAVE_WS2TCPIP_H) +# if defined(__POCC__) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETADDRINFO_THREADSAFE 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETADDRINFO_THREADSAFE 1 +# define HAVE_GETNAMEINFO 1 +# elif defined(_MSC_VER) && (_MSC_VER >= 1200) +# define HAVE_FREEADDRINFO 1 +# define HAVE_GETADDRINFO 1 +# define HAVE_GETADDRINFO_THREADSAFE 1 +# define HAVE_GETNAMEINFO 1 +# endif +#endif + +#if defined(__POCC__) +# ifndef _MSC_VER +# error Microsoft extensions /Ze compiler option is required +# endif +# ifndef __POCC__OLDNAMES +# error Compatibility names /Go compiler option is required +# endif +#endif + +/* ---------------------------------------------------------------- */ +/* STRUCT RELATED */ +/* ---------------------------------------------------------------- */ + +/* Define if you have struct sockaddr_storage. */ +#if !defined(__SALFORDC__) && !defined(__BORLANDC__) +#define HAVE_STRUCT_SOCKADDR_STORAGE 1 +#endif + +/* Define if you have struct timeval. */ +#define HAVE_STRUCT_TIMEVAL 1 + +/* Define if struct sockaddr_in6 has the sin6_scope_id member. */ +#define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 + +#if HAVE_WINSOCK2_H && defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) +#define HAVE_STRUCT_POLLFD 1 +#endif + +/* ---------------------------------------------------------------- */ +/* LARGE FILE SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(_MSC_VER) && !defined(_WIN32_WCE) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define USE_WIN32_LARGE_FILES +# else +# define USE_WIN32_SMALL_FILES +# endif +#endif + +#if defined(__MINGW32__) && !defined(USE_WIN32_LARGE_FILES) +# define USE_WIN32_LARGE_FILES +#endif + +#if defined(__WATCOMC__) && !defined(USE_WIN32_LARGE_FILES) +# define USE_WIN32_LARGE_FILES +#endif + +#if defined(__POCC__) +# undef USE_WIN32_LARGE_FILES +#endif + +#if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES) +# define USE_WIN32_SMALL_FILES +#endif + +/* ---------------------------------------------------------------- */ +/* DNS RESOLVER SPECIALTY */ +/* ---------------------------------------------------------------- */ + +/* + * Undefine both USE_ARES and USE_THREADS_WIN32 for synchronous DNS. + */ + +/* Define to enable c-ares asynchronous DNS lookups. */ +/* #define USE_ARES 1 */ + +/* Default define to enable threaded asynchronous DNS lookups. */ +#if !defined(USE_SYNC_DNS) && !defined(USE_ARES) && \ + !defined(USE_THREADS_WIN32) +# define USE_THREADS_WIN32 1 +#endif + +#if defined(USE_ARES) && defined(USE_THREADS_WIN32) +# error "Only one DNS lookup specialty may be defined at most" +#endif + +/* ---------------------------------------------------------------- */ +/* LDAP SUPPORT */ +/* ---------------------------------------------------------------- */ + +#if defined(CURL_HAS_NOVELL_LDAPSDK) || defined(CURL_HAS_MOZILLA_LDAPSDK) +#undef CURL_LDAP_WIN +#define HAVE_LDAP_SSL_H 1 +#define HAVE_LDAP_URL_PARSE 1 +#elif defined(CURL_HAS_OPENLDAP_LDAPSDK) +#undef CURL_LDAP_WIN +#define HAVE_LDAP_URL_PARSE 1 +#else +#undef HAVE_LDAP_URL_PARSE +#define CURL_LDAP_WIN 1 +#endif + +#if defined(__WATCOMC__) && defined(CURL_LDAP_WIN) +#if __WATCOMC__ < 1280 +#define WINBERAPI __declspec(cdecl) +#define WINLDAPAPI __declspec(cdecl) +#endif +#endif + +#if defined(__POCC__) && defined(CURL_LDAP_WIN) +# define CURL_DISABLE_LDAP 1 +#endif + +/* Define to use the Windows crypto library. */ +#if !defined(USE_SSLEAY) && !defined(USE_NSS) +#define USE_WIN32_CRYPTO +#endif + +/* ---------------------------------------------------------------- */ +/* ADDITIONAL DEFINITIONS */ +/* ---------------------------------------------------------------- */ + +/* Define cpu-machine-OS */ +#undef OS +#if defined(_M_IX86) || defined(__i386__) /* x86 (MSVC or gcc) */ +#define OS "i386-pc-win32" +#elif defined(_M_X64) || defined(__x86_64__) /* x86_64 (MSVC >=2005 or gcc) */ +#define OS "x86_64-pc-win32" +#elif defined(_M_IA64) /* Itanium */ +#define OS "ia64-pc-win32" +#else +#define OS "unknown-pc-win32" +#endif + +/* Name of package */ +#define PACKAGE "curl" + +/* If you want to build curl with the built-in manual */ +#define USE_MANUAL 1 + +#if defined(__POCC__) || (USE_IPV6) +# define ENABLE_IPV6 1 +#endif + +#endif /* HEADER_CURL_CONFIG_WIN32_H */ diff --git a/other/curl/include/curl/curl.h b/other/curl/include/curl/curl.h new file mode 100644 index 0000000..44b1b7e --- /dev/null +++ b/other/curl/include/curl/curl.h @@ -0,0 +1,2352 @@ +#ifndef __CURL_CURL_H +#define __CURL_CURL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* + * If you have libcurl problems, all docs and details are found here: + * http://curl.haxx.se/libcurl/ + * + * curl-library mailing list subscription and unsubscription web interface: + * http://cool.haxx.se/mailman/listinfo/curl-library/ + */ + +#include "curlver.h" /* libcurl version defines */ +#include "curlbuild.h" /* libcurl build definitions */ +#include "curlrules.h" /* libcurl rules enforcement */ + +/* + * Define WIN32 when build target is Win32 API + */ + +#if (defined(_WIN32) || defined(__WIN32__)) && \ + !defined(WIN32) && !defined(__SYMBIAN32__) +#define WIN32 +#endif + +#include +#include + +#if defined(__FreeBSD__) && (__FreeBSD__ >= 2) +/* Needed for __FreeBSD_version symbol definition */ +#include +#endif + +/* The include stuff here below is mainly for time_t! */ +#include +#include + +#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) +#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || defined(__LWIP_OPT_H__)) +/* The check above prevents the winsock2 inclusion if winsock.h already was + included, since they can't co-exist without problems */ +#include +#include +#endif +#endif + +/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish + libc5-based Linux systems. Only include it on systems that are known to + require it! */ +#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ + defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ + defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ + (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) +#include +#endif + +#if !defined(WIN32) && !defined(_WIN32_WCE) +#include +#endif + +#if !defined(WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) +#include +#endif + +#ifdef __BEOS__ +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void CURL; + +/* + * libcurl external API function linkage decorations. + */ + +#ifdef CURL_STATICLIB +# define CURL_EXTERN +#elif defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__) +# if defined(BUILDING_LIBCURL) +# define CURL_EXTERN __declspec(dllexport) +# else +# define CURL_EXTERN __declspec(dllimport) +# endif +#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) +# define CURL_EXTERN CURL_EXTERN_SYMBOL +#else +# define CURL_EXTERN +#endif + +#ifndef curl_socket_typedef +/* socket typedef */ +#if defined(WIN32) && !defined(__LWIP_OPT_H__) +typedef SOCKET curl_socket_t; +#define CURL_SOCKET_BAD INVALID_SOCKET +#else +typedef int curl_socket_t; +#define CURL_SOCKET_BAD -1 +#endif +#define curl_socket_typedef +#endif /* curl_socket_typedef */ + +struct curl_httppost { + struct curl_httppost *next; /* next entry in the list */ + char *name; /* pointer to allocated name */ + long namelength; /* length of name length */ + char *contents; /* pointer to allocated data contents */ + long contentslength; /* length of contents field */ + char *buffer; /* pointer to allocated buffer contents */ + long bufferlength; /* length of buffer field */ + char *contenttype; /* Content-Type */ + struct curl_slist* contentheader; /* list of extra headers for this form */ + struct curl_httppost *more; /* if one field name has more than one + file, this link should link to following + files */ + long flags; /* as defined below */ +#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */ +#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */ +#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer + do not free in formfree */ +#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer + do not free in formfree */ +#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */ +#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */ +#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the + regular read callback to get the data + and pass the given pointer as custom + pointer */ + + char *showfilename; /* The file name to show. If not set, the + actual file name will be used (if this + is a file part) */ + void *userp; /* custom pointer used for + HTTPPOST_CALLBACK posts */ +}; + +/* This is the CURLOPT_PROGRESSFUNCTION callback proto. It is now considered + deprecated but was the only choice up until 7.31.0 */ +typedef int (*curl_progress_callback)(void *clientp, + double dltotal, + double dlnow, + double ultotal, + double ulnow); + +/* This is the CURLOPT_XFERINFOFUNCTION callback proto. It was introduced in + 7.32.0, it avoids floating point and provides more detailed information. */ +typedef int (*curl_xferinfo_callback)(void *clientp, + curl_off_t dltotal, + curl_off_t dlnow, + curl_off_t ultotal, + curl_off_t ulnow); + +#ifndef CURL_MAX_WRITE_SIZE + /* Tests have proven that 20K is a very bad buffer size for uploads on + Windows, while 16K for some odd reason performed a lot better. + We do the ifndef check to allow this value to easier be changed at build + time for those who feel adventurous. The practical minimum is about + 400 bytes since libcurl uses a buffer of this size as a scratch area + (unrelated to network send operations). */ +#define CURL_MAX_WRITE_SIZE 16384 +#endif + +#ifndef CURL_MAX_HTTP_HEADER +/* The only reason to have a max limit for this is to avoid the risk of a bad + server feeding libcurl with a never-ending header that will cause reallocs + infinitely */ +#define CURL_MAX_HTTP_HEADER (100*1024) +#endif + +/* This is a magic return code for the write callback that, when returned, + will signal libcurl to pause receiving on the current transfer. */ +#define CURL_WRITEFUNC_PAUSE 0x10000001 + +typedef size_t (*curl_write_callback)(char *buffer, + size_t size, + size_t nitems, + void *outstream); + + + +/* enumeration of file types */ +typedef enum { + CURLFILETYPE_FILE = 0, + CURLFILETYPE_DIRECTORY, + CURLFILETYPE_SYMLINK, + CURLFILETYPE_DEVICE_BLOCK, + CURLFILETYPE_DEVICE_CHAR, + CURLFILETYPE_NAMEDPIPE, + CURLFILETYPE_SOCKET, + CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ + + CURLFILETYPE_UNKNOWN /* should never occur */ +} curlfiletype; + +#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) +#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) +#define CURLFINFOFLAG_KNOWN_TIME (1<<2) +#define CURLFINFOFLAG_KNOWN_PERM (1<<3) +#define CURLFINFOFLAG_KNOWN_UID (1<<4) +#define CURLFINFOFLAG_KNOWN_GID (1<<5) +#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) +#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) + +/* Content of this structure depends on information which is known and is + achievable (e.g. by FTP LIST parsing). Please see the url_easy_setopt(3) man + page for callbacks returning this structure -- some fields are mandatory, + some others are optional. The FLAG field has special meaning. */ +struct curl_fileinfo { + char *filename; + curlfiletype filetype; + time_t time; + unsigned int perm; + int uid; + int gid; + curl_off_t size; + long int hardlinks; + + struct { + /* If some of these fields is not NULL, it is a pointer to b_data. */ + char *time; + char *perm; + char *user; + char *group; + char *target; /* pointer to the target filename of a symlink */ + } strings; + + unsigned int flags; + + /* used internally */ + char * b_data; + size_t b_size; + size_t b_used; +}; + +/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ +#define CURL_CHUNK_BGN_FUNC_OK 0 +#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ +#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ + +/* if splitting of data transfer is enabled, this callback is called before + download of an individual chunk started. Note that parameter "remains" works + only for FTP wildcard downloading (for now), otherwise is not used */ +typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, + void *ptr, + int remains); + +/* return codes for CURLOPT_CHUNK_END_FUNCTION */ +#define CURL_CHUNK_END_FUNC_OK 0 +#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ + +/* If splitting of data transfer is enabled this callback is called after + download of an individual chunk finished. + Note! After this callback was set then it have to be called FOR ALL chunks. + Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. + This is the reason why we don't need "transfer_info" parameter in this + callback and we are not interested in "remains" parameter too. */ +typedef long (*curl_chunk_end_callback)(void *ptr); + +/* return codes for FNMATCHFUNCTION */ +#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ +#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ +#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ + +/* callback type for wildcard downloading pattern matching. If the + string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ +typedef int (*curl_fnmatch_callback)(void *ptr, + const char *pattern, + const char *string); + +/* These are the return codes for the seek callbacks */ +#define CURL_SEEKFUNC_OK 0 +#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ +#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so + libcurl might try other means instead */ +typedef int (*curl_seek_callback)(void *instream, + curl_off_t offset, + int origin); /* 'whence' */ + +/* This is a return code for the read callback that, when returned, will + signal libcurl to immediately abort the current transfer. */ +#define CURL_READFUNC_ABORT 0x10000000 +/* This is a return code for the read callback that, when returned, will + signal libcurl to pause sending data on the current transfer. */ +#define CURL_READFUNC_PAUSE 0x10000001 + +typedef size_t (*curl_read_callback)(char *buffer, + size_t size, + size_t nitems, + void *instream); + +typedef enum { + CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ + CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ + CURLSOCKTYPE_LAST /* never use */ +} curlsocktype; + +/* The return code from the sockopt_callback can signal information back + to libcurl: */ +#define CURL_SOCKOPT_OK 0 +#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return + CURLE_ABORTED_BY_CALLBACK */ +#define CURL_SOCKOPT_ALREADY_CONNECTED 2 + +typedef int (*curl_sockopt_callback)(void *clientp, + curl_socket_t curlfd, + curlsocktype purpose); + +struct curl_sockaddr { + int family; + int socktype; + int protocol; + unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it + turned really ugly and painful on the systems that + lack this type */ + struct sockaddr addr; +}; + +typedef curl_socket_t +(*curl_opensocket_callback)(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address); + +typedef int +(*curl_closesocket_callback)(void *clientp, curl_socket_t item); + +typedef enum { + CURLIOE_OK, /* I/O operation successful */ + CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ + CURLIOE_FAILRESTART, /* failed to restart the read */ + CURLIOE_LAST /* never use */ +} curlioerr; + +typedef enum { + CURLIOCMD_NOP, /* no operation */ + CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ + CURLIOCMD_LAST /* never use */ +} curliocmd; + +typedef curlioerr (*curl_ioctl_callback)(CURL *handle, + int cmd, + void *clientp); + +/* + * The following typedef's are signatures of malloc, free, realloc, strdup and + * calloc respectively. Function pointers of these types can be passed to the + * curl_global_init_mem() function to set user defined memory management + * callback routines. + */ +typedef void *(*curl_malloc_callback)(size_t size); +typedef void (*curl_free_callback)(void *ptr); +typedef void *(*curl_realloc_callback)(void *ptr, size_t size); +typedef char *(*curl_strdup_callback)(const char *str); +typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); + +/* the kind of data that is passed to information_callback*/ +typedef enum { + CURLINFO_TEXT = 0, + CURLINFO_HEADER_IN, /* 1 */ + CURLINFO_HEADER_OUT, /* 2 */ + CURLINFO_DATA_IN, /* 3 */ + CURLINFO_DATA_OUT, /* 4 */ + CURLINFO_SSL_DATA_IN, /* 5 */ + CURLINFO_SSL_DATA_OUT, /* 6 */ + CURLINFO_END +} curl_infotype; + +typedef int (*curl_debug_callback) + (CURL *handle, /* the handle/transfer this concerns */ + curl_infotype type, /* what kind of data */ + char *data, /* points to the data */ + size_t size, /* size of the data pointed to */ + void *userptr); /* whatever the user please */ + +/* All possible error codes from all sorts of curl functions. Future versions + may return other values, stay prepared. + + Always add new return codes last. Never *EVER* remove any. The return + codes must remain the same! + */ + +typedef enum { + CURLE_OK = 0, + CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ + CURLE_FAILED_INIT, /* 2 */ + CURLE_URL_MALFORMAT, /* 3 */ + CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for + 7.17.0, reused in April 2011 for 7.21.5] */ + CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ + CURLE_COULDNT_RESOLVE_HOST, /* 6 */ + CURLE_COULDNT_CONNECT, /* 7 */ + CURLE_FTP_WEIRD_SERVER_REPLY, /* 8 */ + CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server + due to lack of access - when login fails + this is not returned. */ + CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for + 7.15.4, reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ + CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server + [was obsoleted in August 2007 for 7.17.0, + reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ + CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ + CURLE_FTP_CANT_GET_HOST, /* 15 */ + CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. + [was obsoleted in August 2007 for 7.17.0, + reused in July 2014 for 7.38.0] */ + CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ + CURLE_PARTIAL_FILE, /* 18 */ + CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ + CURLE_OBSOLETE20, /* 20 - NOT USED */ + CURLE_QUOTE_ERROR, /* 21 - quote command failure */ + CURLE_HTTP_RETURNED_ERROR, /* 22 */ + CURLE_WRITE_ERROR, /* 23 */ + CURLE_OBSOLETE24, /* 24 - NOT USED */ + CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ + CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ + CURLE_OUT_OF_MEMORY, /* 27 */ + /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error + instead of a memory allocation error if CURL_DOES_CONVERSIONS + is defined + */ + CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ + CURLE_OBSOLETE29, /* 29 - NOT USED */ + CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ + CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ + CURLE_OBSOLETE32, /* 32 - NOT USED */ + CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ + CURLE_HTTP_POST_ERROR, /* 34 */ + CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ + CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ + CURLE_FILE_COULDNT_READ_FILE, /* 37 */ + CURLE_LDAP_CANNOT_BIND, /* 38 */ + CURLE_LDAP_SEARCH_FAILED, /* 39 */ + CURLE_OBSOLETE40, /* 40 - NOT USED */ + CURLE_FUNCTION_NOT_FOUND, /* 41 */ + CURLE_ABORTED_BY_CALLBACK, /* 42 */ + CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ + CURLE_OBSOLETE44, /* 44 - NOT USED */ + CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ + CURLE_OBSOLETE46, /* 46 - NOT USED */ + CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */ + CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ + CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */ + CURLE_OBSOLETE50, /* 50 - NOT USED */ + CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint + wasn't verified fine */ + CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ + CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ + CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as + default */ + CURLE_SEND_ERROR, /* 55 - failed sending network data */ + CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ + CURLE_OBSOLETE57, /* 57 - NOT IN USE */ + CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ + CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ + CURLE_SSL_CACERT, /* 60 - problem with the CA cert (path?) */ + CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ + CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ + CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ + CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ + CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind + that failed */ + CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ + CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not + accepted and we failed to login */ + CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ + CURLE_TFTP_PERM, /* 69 - permission problem on server */ + CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ + CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ + CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ + CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ + CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ + CURLE_CONV_FAILED, /* 75 - conversion failed */ + CURLE_CONV_REQD, /* 76 - caller must register conversion + callbacks using curl_easy_setopt options + CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOPT_CONV_TO_NETWORK_FUNCTION, and + CURLOPT_CONV_FROM_UTF8_FUNCTION */ + CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing + or wrong format */ + CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ + CURLE_SSH, /* 79 - error from the SSH layer, somewhat + generic so the error message will be of + interest when this has happened */ + + CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL + connection */ + CURLE_AGAIN, /* 81 - socket is not ready for send/recv, + wait till it's ready and try again (Added + in 7.18.2) */ + CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or + wrong format (Added in 7.19.0) */ + CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in + 7.19.0) */ + CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ + CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ + CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ + CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ + CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ + CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the + session will be queued */ + CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not + match */ + CURL_LAST /* never use! */ +} CURLcode; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Previously obsolete error code re-used in 7.38.0 */ +#define CURLE_OBSOLETE16 CURLE_HTTP2 + +/* Previously obsolete error codes re-used in 7.24.0 */ +#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED +#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT + +/* compatibility with older names */ +#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING + +/* The following were added in 7.21.5, April 2011 */ +#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION + +/* The following were added in 7.17.1 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION + +/* The following were added in 7.17.0 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ +#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 +#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 +#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 +#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 +#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 +#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 +#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 +#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 +#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 +#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 +#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 +#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN + +#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED +#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE +#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR +#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL +#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS +#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR +#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED + +/* The following were added earlier */ + +#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT + +#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR +#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED +#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED + +#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE +#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME + +/* This was the error code 50 in 7.7.3 and a few earlier versions, this + is no longer used by libcurl but is instead #defined here only to not + make programs break */ +#define CURLE_ALREADY_COMPLETE 99999 + +/* Provide defines for really old option names */ +#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ +#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ +#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA + +/* Since long deprecated options with no code in the lib that does anything + with them. */ +#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 +#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 + +#endif /*!CURL_NO_OLDIES*/ + +/* This prototype applies to all conversion callbacks */ +typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); + +typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ + void *ssl_ctx, /* actually an + OpenSSL SSL_CTX */ + void *userptr); + +typedef enum { + CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use + CONNECT HTTP/1.1 */ + CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT + HTTP/1.0 */ + CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already + in 7.10 */ + CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ + CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ + CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the + host name rather than the IP address. added + in 7.18.0 */ +} curl_proxytype; /* this enum was added in 7.10 */ + +/* + * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: + * + * CURLAUTH_NONE - No HTTP authentication + * CURLAUTH_BASIC - HTTP Basic authentication (default) + * CURLAUTH_DIGEST - HTTP Digest authentication + * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication + * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) + * CURLAUTH_NTLM - HTTP NTLM authentication + * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour + * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper + * CURLAUTH_ONLY - Use together with a single other type to force no + * authentication or just that single type + * CURLAUTH_ANY - All fine types set + * CURLAUTH_ANYSAFE - All fine types except Basic + */ + +#define CURLAUTH_NONE ((unsigned long)0) +#define CURLAUTH_BASIC (((unsigned long)1)<<0) +#define CURLAUTH_DIGEST (((unsigned long)1)<<1) +#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2) +/* Deprecated since the advent of CURLAUTH_NEGOTIATE */ +#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE +#define CURLAUTH_NTLM (((unsigned long)1)<<3) +#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) +#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) +#define CURLAUTH_ONLY (((unsigned long)1)<<31) +#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) +#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) + +#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ +#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ +#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ +#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ +#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ +#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ +#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */ +#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY + +#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ +#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ +#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ + +#define CURL_ERROR_SIZE 256 + +enum curl_khtype { + CURLKHTYPE_UNKNOWN, + CURLKHTYPE_RSA1, + CURLKHTYPE_RSA, + CURLKHTYPE_DSS +}; + +struct curl_khkey { + const char *key; /* points to a zero-terminated string encoded with base64 + if len is zero, otherwise to the "raw" data */ + size_t len; + enum curl_khtype keytype; +}; + +/* this is the set of return values expected from the curl_sshkeycallback + callback */ +enum curl_khstat { + CURLKHSTAT_FINE_ADD_TO_FILE, + CURLKHSTAT_FINE, + CURLKHSTAT_REJECT, /* reject the connection, return an error */ + CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so + this causes a CURLE_DEFER error but otherwise the + connection will be left intact etc */ + CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ +}; + +/* this is the set of status codes pass in to the callback */ +enum curl_khmatch { + CURLKHMATCH_OK, /* match */ + CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ + CURLKHMATCH_MISSING, /* no matching host/key found */ + CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ +}; + +typedef int + (*curl_sshkeycallback) (CURL *easy, /* easy handle */ + const struct curl_khkey *knownkey, /* known */ + const struct curl_khkey *foundkey, /* found */ + enum curl_khmatch, /* libcurl's view on the keys */ + void *clientp); /* custom pointer passed from app */ + +/* parameter for the CURLOPT_USE_SSL option */ +typedef enum { + CURLUSESSL_NONE, /* do not attempt to use SSL */ + CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ + CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ + CURLUSESSL_ALL, /* SSL for all communication or fail */ + CURLUSESSL_LAST /* not an option, never use */ +} curl_usessl; + +/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ + +/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the + name of improving interoperability with older servers. Some SSL libraries + have introduced work-arounds for this flaw but those work-arounds sometimes + make the SSL communication fail. To regain functionality with those broken + servers, a user can this way allow the vulnerability back. */ +#define CURLSSLOPT_ALLOW_BEAST (1<<0) + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2009 */ + +#define CURLFTPSSL_NONE CURLUSESSL_NONE +#define CURLFTPSSL_TRY CURLUSESSL_TRY +#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL +#define CURLFTPSSL_ALL CURLUSESSL_ALL +#define CURLFTPSSL_LAST CURLUSESSL_LAST +#define curl_ftpssl curl_usessl +#endif /*!CURL_NO_OLDIES*/ + +/* parameter for the CURLOPT_FTP_SSL_CCC option */ +typedef enum { + CURLFTPSSL_CCC_NONE, /* do not send CCC */ + CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ + CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ + CURLFTPSSL_CCC_LAST /* not an option, never use */ +} curl_ftpccc; + +/* parameter for the CURLOPT_FTPSSLAUTH option */ +typedef enum { + CURLFTPAUTH_DEFAULT, /* let libcurl decide */ + CURLFTPAUTH_SSL, /* use "AUTH SSL" */ + CURLFTPAUTH_TLS, /* use "AUTH TLS" */ + CURLFTPAUTH_LAST /* not an option, never use */ +} curl_ftpauth; + +/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ +typedef enum { + CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ + CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD + again if MKD succeeded, for SFTP this does + similar magic */ + CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD + again even if MKD failed! */ + CURLFTP_CREATE_DIR_LAST /* not an option, never use */ +} curl_ftpcreatedir; + +/* parameter for the CURLOPT_FTP_FILEMETHOD option */ +typedef enum { + CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ + CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ + CURLFTPMETHOD_NOCWD, /* no CWD at all */ + CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ + CURLFTPMETHOD_LAST /* not an option, never use */ +} curl_ftpmethod; + +/* bitmask defines for CURLOPT_HEADEROPT */ +#define CURLHEADER_UNIFIED 0 +#define CURLHEADER_SEPARATE (1<<0) + +/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ +#define CURLPROTO_HTTP (1<<0) +#define CURLPROTO_HTTPS (1<<1) +#define CURLPROTO_FTP (1<<2) +#define CURLPROTO_FTPS (1<<3) +#define CURLPROTO_SCP (1<<4) +#define CURLPROTO_SFTP (1<<5) +#define CURLPROTO_TELNET (1<<6) +#define CURLPROTO_LDAP (1<<7) +#define CURLPROTO_LDAPS (1<<8) +#define CURLPROTO_DICT (1<<9) +#define CURLPROTO_FILE (1<<10) +#define CURLPROTO_TFTP (1<<11) +#define CURLPROTO_IMAP (1<<12) +#define CURLPROTO_IMAPS (1<<13) +#define CURLPROTO_POP3 (1<<14) +#define CURLPROTO_POP3S (1<<15) +#define CURLPROTO_SMTP (1<<16) +#define CURLPROTO_SMTPS (1<<17) +#define CURLPROTO_RTSP (1<<18) +#define CURLPROTO_RTMP (1<<19) +#define CURLPROTO_RTMPT (1<<20) +#define CURLPROTO_RTMPE (1<<21) +#define CURLPROTO_RTMPTE (1<<22) +#define CURLPROTO_RTMPS (1<<23) +#define CURLPROTO_RTMPTS (1<<24) +#define CURLPROTO_GOPHER (1<<25) +#define CURLPROTO_SMB (1<<26) +#define CURLPROTO_SMBS (1<<27) +#define CURLPROTO_ALL (~0) /* enable everything */ + +/* long may be 32 or 64 bits, but we should never depend on anything else + but 32 */ +#define CURLOPTTYPE_LONG 0 +#define CURLOPTTYPE_OBJECTPOINT 10000 +#define CURLOPTTYPE_FUNCTIONPOINT 20000 +#define CURLOPTTYPE_OFF_T 30000 + +/* name is uppercase CURLOPT_, + type is one of the defined CURLOPTTYPE_ + number is unique identifier */ +#ifdef CINIT +#undef CINIT +#endif + +#ifdef CURL_ISOCPP +#define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu +#else +/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ +#define LONG CURLOPTTYPE_LONG +#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT +#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT +#define OFF_T CURLOPTTYPE_OFF_T +#define CINIT(name,type,number) CURLOPT_/**/name = type + number +#endif + +/* + * This macro-mania below setups the CURLOPT_[what] enum, to be used with + * curl_easy_setopt(). The first argument in the CINIT() macro is the [what] + * word. + */ + +typedef enum { + /* This is the FILE * or void * the regular output should be written to. */ + CINIT(WRITEDATA, OBJECTPOINT, 1), + + /* The full URL to get/put */ + CINIT(URL, OBJECTPOINT, 2), + + /* Port number to connect to, if other than default. */ + CINIT(PORT, LONG, 3), + + /* Name of proxy to use. */ + CINIT(PROXY, OBJECTPOINT, 4), + + /* "user:password;options" to use when fetching. */ + CINIT(USERPWD, OBJECTPOINT, 5), + + /* "user:password" to use with proxy. */ + CINIT(PROXYUSERPWD, OBJECTPOINT, 6), + + /* Range to get, specified as an ASCII string. */ + CINIT(RANGE, OBJECTPOINT, 7), + + /* not used */ + + /* Specified file stream to upload from (use as input): */ + CINIT(READDATA, OBJECTPOINT, 9), + + /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE + * bytes big. If this is not used, error messages go to stderr instead: */ + CINIT(ERRORBUFFER, OBJECTPOINT, 10), + + /* Function that will be called to store the output (instead of fwrite). The + * parameters will use fwrite() syntax, make sure to follow them. */ + CINIT(WRITEFUNCTION, FUNCTIONPOINT, 11), + + /* Function that will be called to read the input (instead of fread). The + * parameters will use fread() syntax, make sure to follow them. */ + CINIT(READFUNCTION, FUNCTIONPOINT, 12), + + /* Time-out the read operation after this amount of seconds */ + CINIT(TIMEOUT, LONG, 13), + + /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about + * how large the file being sent really is. That allows better error + * checking and better verifies that the upload was successful. -1 means + * unknown size. + * + * For large file support, there is also a _LARGE version of the key + * which takes an off_t type, allowing platforms with larger off_t + * sizes to handle larger files. See below for INFILESIZE_LARGE. + */ + CINIT(INFILESIZE, LONG, 14), + + /* POST static input fields. */ + CINIT(POSTFIELDS, OBJECTPOINT, 15), + + /* Set the referrer page (needed by some CGIs) */ + CINIT(REFERER, OBJECTPOINT, 16), + + /* Set the FTP PORT string (interface name, named or numerical IP address) + Use i.e '-' to use default address. */ + CINIT(FTPPORT, OBJECTPOINT, 17), + + /* Set the User-Agent string (examined by some CGIs) */ + CINIT(USERAGENT, OBJECTPOINT, 18), + + /* If the download receives less than "low speed limit" bytes/second + * during "low speed time" seconds, the operations is aborted. + * You could i.e if you have a pretty high speed connection, abort if + * it is less than 2000 bytes/sec during 20 seconds. + */ + + /* Set the "low speed limit" */ + CINIT(LOW_SPEED_LIMIT, LONG, 19), + + /* Set the "low speed time" */ + CINIT(LOW_SPEED_TIME, LONG, 20), + + /* Set the continuation offset. + * + * Note there is also a _LARGE version of this key which uses + * off_t types, allowing for large file offsets on platforms which + * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. + */ + CINIT(RESUME_FROM, LONG, 21), + + /* Set cookie in request: */ + CINIT(COOKIE, OBJECTPOINT, 22), + + /* This points to a linked list of headers, struct curl_slist kind. This + list is also used for RTSP (in spite of its name) */ + CINIT(HTTPHEADER, OBJECTPOINT, 23), + + /* This points to a linked list of post entries, struct curl_httppost */ + CINIT(HTTPPOST, OBJECTPOINT, 24), + + /* name of the file keeping your private SSL-certificate */ + CINIT(SSLCERT, OBJECTPOINT, 25), + + /* password for the SSL or SSH private key */ + CINIT(KEYPASSWD, OBJECTPOINT, 26), + + /* send TYPE parameter? */ + CINIT(CRLF, LONG, 27), + + /* send linked-list of QUOTE commands */ + CINIT(QUOTE, OBJECTPOINT, 28), + + /* send FILE * or void * to store headers to, if you use a callback it + is simply passed to the callback unmodified */ + CINIT(HEADERDATA, OBJECTPOINT, 29), + + /* point to a file to read the initial cookies from, also enables + "cookie awareness" */ + CINIT(COOKIEFILE, OBJECTPOINT, 31), + + /* What version to specifically try to use. + See CURL_SSLVERSION defines below. */ + CINIT(SSLVERSION, LONG, 32), + + /* What kind of HTTP time condition to use, see defines */ + CINIT(TIMECONDITION, LONG, 33), + + /* Time to use with the above condition. Specified in number of seconds + since 1 Jan 1970 */ + CINIT(TIMEVALUE, LONG, 34), + + /* 35 = OBSOLETE */ + + /* Custom request, for customizing the get command like + HTTP: DELETE, TRACE and others + FTP: to use a different list command + */ + CINIT(CUSTOMREQUEST, OBJECTPOINT, 36), + + /* HTTP request, for odd commands like DELETE, TRACE and others */ + CINIT(STDERR, OBJECTPOINT, 37), + + /* 38 is not used */ + + /* send linked-list of post-transfer QUOTE commands */ + CINIT(POSTQUOTE, OBJECTPOINT, 39), + + CINIT(OBSOLETE40, OBJECTPOINT, 40), /* OBSOLETE, do not use! */ + + CINIT(VERBOSE, LONG, 41), /* talk a lot */ + CINIT(HEADER, LONG, 42), /* throw the header out too */ + CINIT(NOPROGRESS, LONG, 43), /* shut off the progress meter */ + CINIT(NOBODY, LONG, 44), /* use HEAD to get http document */ + CINIT(FAILONERROR, LONG, 45), /* no output on http error codes >= 400 */ + CINIT(UPLOAD, LONG, 46), /* this is an upload */ + CINIT(POST, LONG, 47), /* HTTP POST method */ + CINIT(DIRLISTONLY, LONG, 48), /* bare names when listing directories */ + + CINIT(APPEND, LONG, 50), /* Append instead of overwrite on upload! */ + + /* Specify whether to read the user+password from the .netrc or the URL. + * This must be one of the CURL_NETRC_* enums below. */ + CINIT(NETRC, LONG, 51), + + CINIT(FOLLOWLOCATION, LONG, 52), /* use Location: Luke! */ + + CINIT(TRANSFERTEXT, LONG, 53), /* transfer data in text/ASCII format */ + CINIT(PUT, LONG, 54), /* HTTP PUT */ + + /* 55 = OBSOLETE */ + + /* DEPRECATED + * Function that will be called instead of the internal progress display + * function. This function should be defined as the curl_progress_callback + * prototype defines. */ + CINIT(PROGRESSFUNCTION, FUNCTIONPOINT, 56), + + /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION + callbacks */ + CINIT(PROGRESSDATA, OBJECTPOINT, 57), +#define CURLOPT_XFERINFODATA CURLOPT_PROGRESSDATA + + /* We want the referrer field set automatically when following locations */ + CINIT(AUTOREFERER, LONG, 58), + + /* Port of the proxy, can be set in the proxy string as well with: + "[host]:[port]" */ + CINIT(PROXYPORT, LONG, 59), + + /* size of the POST input data, if strlen() is not good to use */ + CINIT(POSTFIELDSIZE, LONG, 60), + + /* tunnel non-http operations through a HTTP proxy */ + CINIT(HTTPPROXYTUNNEL, LONG, 61), + + /* Set the interface string to use as outgoing network interface */ + CINIT(INTERFACE, OBJECTPOINT, 62), + + /* Set the krb4/5 security level, this also enables krb4/5 awareness. This + * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string + * is set but doesn't match one of these, 'private' will be used. */ + CINIT(KRBLEVEL, OBJECTPOINT, 63), + + /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ + CINIT(SSL_VERIFYPEER, LONG, 64), + + /* The CApath or CAfile used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CINIT(CAINFO, OBJECTPOINT, 65), + + /* 66 = OBSOLETE */ + /* 67 = OBSOLETE */ + + /* Maximum number of http redirects to follow */ + CINIT(MAXREDIRS, LONG, 68), + + /* Pass a long set to 1 to get the date of the requested document (if + possible)! Pass a zero to shut it off. */ + CINIT(FILETIME, LONG, 69), + + /* This points to a linked list of telnet options */ + CINIT(TELNETOPTIONS, OBJECTPOINT, 70), + + /* Max amount of cached alive connections */ + CINIT(MAXCONNECTS, LONG, 71), + + CINIT(OBSOLETE72, LONG, 72), /* OBSOLETE, do not use! */ + + /* 73 = OBSOLETE */ + + /* Set to explicitly use a new connection for the upcoming transfer. + Do not use this unless you're absolutely sure of this, as it makes the + operation slower and is less friendly for the network. */ + CINIT(FRESH_CONNECT, LONG, 74), + + /* Set to explicitly forbid the upcoming transfer's connection to be re-used + when done. Do not use this unless you're absolutely sure of this, as it + makes the operation slower and is less friendly for the network. */ + CINIT(FORBID_REUSE, LONG, 75), + + /* Set to a file name that contains random data for libcurl to use to + seed the random engine when doing SSL connects. */ + CINIT(RANDOM_FILE, OBJECTPOINT, 76), + + /* Set to the Entropy Gathering Daemon socket pathname */ + CINIT(EGDSOCKET, OBJECTPOINT, 77), + + /* Time-out connect operations after this amount of seconds, if connects are + OK within this time, then fine... This only aborts the connect phase. */ + CINIT(CONNECTTIMEOUT, LONG, 78), + + /* Function that will be called to store headers (instead of fwrite). The + * parameters will use fwrite() syntax, make sure to follow them. */ + CINIT(HEADERFUNCTION, FUNCTIONPOINT, 79), + + /* Set this to force the HTTP request to get back to GET. Only really usable + if POST, PUT or a custom request have been used first. + */ + CINIT(HTTPGET, LONG, 80), + + /* Set if we should verify the Common name from the peer certificate in ssl + * handshake, set 1 to check existence, 2 to ensure that it matches the + * provided hostname. */ + CINIT(SSL_VERIFYHOST, LONG, 81), + + /* Specify which file name to write all known cookies in after completed + operation. Set file name to "-" (dash) to make it go to stdout. */ + CINIT(COOKIEJAR, OBJECTPOINT, 82), + + /* Specify which SSL ciphers to use */ + CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83), + + /* Specify which HTTP version to use! This must be set to one of the + CURL_HTTP_VERSION* enums set below. */ + CINIT(HTTP_VERSION, LONG, 84), + + /* Specifically switch on or off the FTP engine's use of the EPSV command. By + default, that one will always be attempted before the more traditional + PASV command. */ + CINIT(FTP_USE_EPSV, LONG, 85), + + /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ + CINIT(SSLCERTTYPE, OBJECTPOINT, 86), + + /* name of the file keeping your private SSL-key */ + CINIT(SSLKEY, OBJECTPOINT, 87), + + /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ + CINIT(SSLKEYTYPE, OBJECTPOINT, 88), + + /* crypto engine for the SSL-sub system */ + CINIT(SSLENGINE, OBJECTPOINT, 89), + + /* set the crypto engine for the SSL-sub system as default + the param has no meaning... + */ + CINIT(SSLENGINE_DEFAULT, LONG, 90), + + /* Non-zero value means to use the global dns cache */ + CINIT(DNS_USE_GLOBAL_CACHE, LONG, 91), /* DEPRECATED, do not use! */ + + /* DNS cache timeout */ + CINIT(DNS_CACHE_TIMEOUT, LONG, 92), + + /* send linked-list of pre-transfer QUOTE commands */ + CINIT(PREQUOTE, OBJECTPOINT, 93), + + /* set the debug function */ + CINIT(DEBUGFUNCTION, FUNCTIONPOINT, 94), + + /* set the data for the debug function */ + CINIT(DEBUGDATA, OBJECTPOINT, 95), + + /* mark this as start of a cookie session */ + CINIT(COOKIESESSION, LONG, 96), + + /* The CApath directory used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CINIT(CAPATH, OBJECTPOINT, 97), + + /* Instruct libcurl to use a smaller receive buffer */ + CINIT(BUFFERSIZE, LONG, 98), + + /* Instruct libcurl to not use any signal/alarm handlers, even when using + timeouts. This option is useful for multi-threaded applications. + See libcurl-the-guide for more background information. */ + CINIT(NOSIGNAL, LONG, 99), + + /* Provide a CURLShare for mutexing non-ts data */ + CINIT(SHARE, OBJECTPOINT, 100), + + /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), + CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */ + CINIT(PROXYTYPE, LONG, 101), + + /* Set the Accept-Encoding string. Use this to tell a server you would like + the response to be compressed. Before 7.21.6, this was known as + CURLOPT_ENCODING */ + CINIT(ACCEPT_ENCODING, OBJECTPOINT, 102), + + /* Set pointer to private data */ + CINIT(PRIVATE, OBJECTPOINT, 103), + + /* Set aliases for HTTP 200 in the HTTP Response header */ + CINIT(HTTP200ALIASES, OBJECTPOINT, 104), + + /* Continue to send authentication (user+password) when following locations, + even when hostname changed. This can potentially send off the name + and password to whatever host the server decides. */ + CINIT(UNRESTRICTED_AUTH, LONG, 105), + + /* Specifically switch on or off the FTP engine's use of the EPRT command ( + it also disables the LPRT attempt). By default, those ones will always be + attempted before the good old traditional PORT command. */ + CINIT(FTP_USE_EPRT, LONG, 106), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_USERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CINIT(HTTPAUTH, LONG, 107), + + /* Set the ssl context callback function, currently only for OpenSSL ssl_ctx + in second argument. The function must be matching the + curl_ssl_ctx_callback proto. */ + CINIT(SSL_CTX_FUNCTION, FUNCTIONPOINT, 108), + + /* Set the userdata for the ssl context callback function's third + argument */ + CINIT(SSL_CTX_DATA, OBJECTPOINT, 109), + + /* FTP Option that causes missing dirs to be created on the remote server. + In 7.19.4 we introduced the convenience enums for this option using the + CURLFTP_CREATE_DIR prefix. + */ + CINIT(FTP_CREATE_MISSING_DIRS, LONG, 110), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CINIT(PROXYAUTH, LONG, 111), + + /* FTP option that changes the timeout, in seconds, associated with + getting a response. This is different from transfer timeout time and + essentially places a demand on the FTP server to acknowledge commands + in a timely manner. */ + CINIT(FTP_RESPONSE_TIMEOUT, LONG, 112), +#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT + + /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to + tell libcurl to resolve names to those IP versions only. This only has + affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */ + CINIT(IPRESOLVE, LONG, 113), + + /* Set this option to limit the size of a file that will be downloaded from + an HTTP or FTP server. + + Note there is also _LARGE version which adds large file support for + platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ + CINIT(MAXFILESIZE, LONG, 114), + + /* See the comment for INFILESIZE above, but in short, specifies + * the size of the file being uploaded. -1 means unknown. + */ + CINIT(INFILESIZE_LARGE, OFF_T, 115), + + /* Sets the continuation offset. There is also a LONG version of this; + * look above for RESUME_FROM. + */ + CINIT(RESUME_FROM_LARGE, OFF_T, 116), + + /* Sets the maximum size of data that will be downloaded from + * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. + */ + CINIT(MAXFILESIZE_LARGE, OFF_T, 117), + + /* Set this option to the file name of your .netrc file you want libcurl + to parse (using the CURLOPT_NETRC option). If not set, libcurl will do + a poor attempt to find the user's home directory and check for a .netrc + file in there. */ + CINIT(NETRC_FILE, OBJECTPOINT, 118), + + /* Enable SSL/TLS for FTP, pick one of: + CURLUSESSL_TRY - try using SSL, proceed anyway otherwise + CURLUSESSL_CONTROL - SSL for the control connection or fail + CURLUSESSL_ALL - SSL for all communication or fail + */ + CINIT(USE_SSL, LONG, 119), + + /* The _LARGE version of the standard POSTFIELDSIZE option */ + CINIT(POSTFIELDSIZE_LARGE, OFF_T, 120), + + /* Enable/disable the TCP Nagle algorithm */ + CINIT(TCP_NODELAY, LONG, 121), + + /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 123 OBSOLETE. Gone in 7.16.0 */ + /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 127 OBSOLETE. Gone in 7.16.0 */ + /* 128 OBSOLETE. Gone in 7.16.0 */ + + /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option + can be used to change libcurl's default action which is to first try + "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK + response has been received. + + Available parameters are: + CURLFTPAUTH_DEFAULT - let libcurl decide + CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS + CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL + */ + CINIT(FTPSSLAUTH, LONG, 129), + + CINIT(IOCTLFUNCTION, FUNCTIONPOINT, 130), + CINIT(IOCTLDATA, OBJECTPOINT, 131), + + /* 132 OBSOLETE. Gone in 7.16.0 */ + /* 133 OBSOLETE. Gone in 7.16.0 */ + + /* zero terminated string for pass on to the FTP server when asked for + "account" info */ + CINIT(FTP_ACCOUNT, OBJECTPOINT, 134), + + /* feed cookies into cookie engine */ + CINIT(COOKIELIST, OBJECTPOINT, 135), + + /* ignore Content-Length */ + CINIT(IGNORE_CONTENT_LENGTH, LONG, 136), + + /* Set to non-zero to skip the IP address received in a 227 PASV FTP server + response. Typically used for FTP-SSL purposes but is not restricted to + that. libcurl will then instead use the same IP address it used for the + control connection. */ + CINIT(FTP_SKIP_PASV_IP, LONG, 137), + + /* Select "file method" to use when doing FTP, see the curl_ftpmethod + above. */ + CINIT(FTP_FILEMETHOD, LONG, 138), + + /* Local port number to bind the socket to */ + CINIT(LOCALPORT, LONG, 139), + + /* Number of ports to try, including the first one set with LOCALPORT. + Thus, setting it to 1 will make no additional attempts but the first. + */ + CINIT(LOCALPORTRANGE, LONG, 140), + + /* no transfer, set up connection and let application use the socket by + extracting it with CURLINFO_LASTSOCKET */ + CINIT(CONNECT_ONLY, LONG, 141), + + /* Function that will be called to convert from the + network encoding (instead of using the iconv calls in libcurl) */ + CINIT(CONV_FROM_NETWORK_FUNCTION, FUNCTIONPOINT, 142), + + /* Function that will be called to convert to the + network encoding (instead of using the iconv calls in libcurl) */ + CINIT(CONV_TO_NETWORK_FUNCTION, FUNCTIONPOINT, 143), + + /* Function that will be called to convert from UTF8 + (instead of using the iconv calls in libcurl) + Note that this is used only for SSL certificate processing */ + CINIT(CONV_FROM_UTF8_FUNCTION, FUNCTIONPOINT, 144), + + /* if the connection proceeds too quickly then need to slow it down */ + /* limit-rate: maximum number of bytes per second to send or receive */ + CINIT(MAX_SEND_SPEED_LARGE, OFF_T, 145), + CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146), + + /* Pointer to command string to send if USER/PASS fails. */ + CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147), + + /* callback function for setting socket options */ + CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148), + CINIT(SOCKOPTDATA, OBJECTPOINT, 149), + + /* set to 0 to disable session ID re-use for this transfer, default is + enabled (== 1) */ + CINIT(SSL_SESSIONID_CACHE, LONG, 150), + + /* allowed SSH authentication methods */ + CINIT(SSH_AUTH_TYPES, LONG, 151), + + /* Used by scp/sftp to do public/private key authentication */ + CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152), + CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153), + + /* Send CCC (Clear Command Channel) after authentication */ + CINIT(FTP_SSL_CCC, LONG, 154), + + /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ + CINIT(TIMEOUT_MS, LONG, 155), + CINIT(CONNECTTIMEOUT_MS, LONG, 156), + + /* set to zero to disable the libcurl's decoding and thus pass the raw body + data to the application even when it is encoded/compressed */ + CINIT(HTTP_TRANSFER_DECODING, LONG, 157), + CINIT(HTTP_CONTENT_DECODING, LONG, 158), + + /* Permission used when creating new files and directories on the remote + server for protocols that support it, SFTP/SCP/FILE */ + CINIT(NEW_FILE_PERMS, LONG, 159), + CINIT(NEW_DIRECTORY_PERMS, LONG, 160), + + /* Set the behaviour of POST when redirecting. Values must be set to one + of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ + CINIT(POSTREDIR, LONG, 161), + + /* used by scp/sftp to verify the host's public key */ + CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162), + + /* Callback function for opening socket (instead of socket(2)). Optionally, + callback is able change the address or refuse to connect returning + CURL_SOCKET_BAD. The callback should have type + curl_opensocket_callback */ + CINIT(OPENSOCKETFUNCTION, FUNCTIONPOINT, 163), + CINIT(OPENSOCKETDATA, OBJECTPOINT, 164), + + /* POST volatile input fields. */ + CINIT(COPYPOSTFIELDS, OBJECTPOINT, 165), + + /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ + CINIT(PROXY_TRANSFER_MODE, LONG, 166), + + /* Callback function for seeking in the input stream */ + CINIT(SEEKFUNCTION, FUNCTIONPOINT, 167), + CINIT(SEEKDATA, OBJECTPOINT, 168), + + /* CRL file */ + CINIT(CRLFILE, OBJECTPOINT, 169), + + /* Issuer certificate */ + CINIT(ISSUERCERT, OBJECTPOINT, 170), + + /* (IPv6) Address scope */ + CINIT(ADDRESS_SCOPE, LONG, 171), + + /* Collect certificate chain info and allow it to get retrievable with + CURLINFO_CERTINFO after the transfer is complete. */ + CINIT(CERTINFO, LONG, 172), + + /* "name" and "pwd" to use when fetching. */ + CINIT(USERNAME, OBJECTPOINT, 173), + CINIT(PASSWORD, OBJECTPOINT, 174), + + /* "name" and "pwd" to use with Proxy when fetching. */ + CINIT(PROXYUSERNAME, OBJECTPOINT, 175), + CINIT(PROXYPASSWORD, OBJECTPOINT, 176), + + /* Comma separated list of hostnames defining no-proxy zones. These should + match both hostnames directly, and hostnames within a domain. For + example, local.com will match local.com and www.local.com, but NOT + notlocal.com or www.notlocal.com. For compatibility with other + implementations of this, .local.com will be considered to be the same as + local.com. A single * is the only valid wildcard, and effectively + disables the use of proxy. */ + CINIT(NOPROXY, OBJECTPOINT, 177), + + /* block size for TFTP transfers */ + CINIT(TFTP_BLKSIZE, LONG, 178), + + /* Socks Service */ + CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179), + + /* Socks Service */ + CINIT(SOCKS5_GSSAPI_NEC, LONG, 180), + + /* set the bitmask for the protocols that are allowed to be used for the + transfer, which thus helps the app which takes URLs from users or other + external inputs and want to restrict what protocol(s) to deal + with. Defaults to CURLPROTO_ALL. */ + CINIT(PROTOCOLS, LONG, 181), + + /* set the bitmask for the protocols that libcurl is allowed to follow to, + as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs + to be set in both bitmasks to be allowed to get redirected to. Defaults + to all protocols except FILE and SCP. */ + CINIT(REDIR_PROTOCOLS, LONG, 182), + + /* set the SSH knownhost file name to use */ + CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183), + + /* set the SSH host key callback, must point to a curl_sshkeycallback + function */ + CINIT(SSH_KEYFUNCTION, FUNCTIONPOINT, 184), + + /* set the SSH host key callback custom pointer */ + CINIT(SSH_KEYDATA, OBJECTPOINT, 185), + + /* set the SMTP mail originator */ + CINIT(MAIL_FROM, OBJECTPOINT, 186), + + /* set the SMTP mail receiver(s) */ + CINIT(MAIL_RCPT, OBJECTPOINT, 187), + + /* FTP: send PRET before PASV */ + CINIT(FTP_USE_PRET, LONG, 188), + + /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ + CINIT(RTSP_REQUEST, LONG, 189), + + /* The RTSP session identifier */ + CINIT(RTSP_SESSION_ID, OBJECTPOINT, 190), + + /* The RTSP stream URI */ + CINIT(RTSP_STREAM_URI, OBJECTPOINT, 191), + + /* The Transport: header to use in RTSP requests */ + CINIT(RTSP_TRANSPORT, OBJECTPOINT, 192), + + /* Manually initialize the client RTSP CSeq for this handle */ + CINIT(RTSP_CLIENT_CSEQ, LONG, 193), + + /* Manually initialize the server RTSP CSeq for this handle */ + CINIT(RTSP_SERVER_CSEQ, LONG, 194), + + /* The stream to pass to INTERLEAVEFUNCTION. */ + CINIT(INTERLEAVEDATA, OBJECTPOINT, 195), + + /* Let the application define a custom write method for RTP data */ + CINIT(INTERLEAVEFUNCTION, FUNCTIONPOINT, 196), + + /* Turn on wildcard matching */ + CINIT(WILDCARDMATCH, LONG, 197), + + /* Directory matching callback called before downloading of an + individual file (chunk) started */ + CINIT(CHUNK_BGN_FUNCTION, FUNCTIONPOINT, 198), + + /* Directory matching callback called after the file (chunk) + was downloaded, or skipped */ + CINIT(CHUNK_END_FUNCTION, FUNCTIONPOINT, 199), + + /* Change match (fnmatch-like) callback for wildcard matching */ + CINIT(FNMATCH_FUNCTION, FUNCTIONPOINT, 200), + + /* Let the application define custom chunk data pointer */ + CINIT(CHUNK_DATA, OBJECTPOINT, 201), + + /* FNMATCH_FUNCTION user pointer */ + CINIT(FNMATCH_DATA, OBJECTPOINT, 202), + + /* send linked-list of name:port:address sets */ + CINIT(RESOLVE, OBJECTPOINT, 203), + + /* Set a username for authenticated TLS */ + CINIT(TLSAUTH_USERNAME, OBJECTPOINT, 204), + + /* Set a password for authenticated TLS */ + CINIT(TLSAUTH_PASSWORD, OBJECTPOINT, 205), + + /* Set authentication type for authenticated TLS */ + CINIT(TLSAUTH_TYPE, OBJECTPOINT, 206), + + /* Set to 1 to enable the "TE:" header in HTTP requests to ask for + compressed transfer-encoded responses. Set to 0 to disable the use of TE: + in outgoing requests. The current default is 0, but it might change in a + future libcurl release. + + libcurl will ask for the compressed methods it knows of, and if that + isn't any, it will not ask for transfer-encoding at all even if this + option is set to 1. + + */ + CINIT(TRANSFER_ENCODING, LONG, 207), + + /* Callback function for closing socket (instead of close(2)). The callback + should have type curl_closesocket_callback */ + CINIT(CLOSESOCKETFUNCTION, FUNCTIONPOINT, 208), + CINIT(CLOSESOCKETDATA, OBJECTPOINT, 209), + + /* allow GSSAPI credential delegation */ + CINIT(GSSAPI_DELEGATION, LONG, 210), + + /* Set the name servers to use for DNS resolution */ + CINIT(DNS_SERVERS, OBJECTPOINT, 211), + + /* Time-out accept operations (currently for FTP only) after this amount + of miliseconds. */ + CINIT(ACCEPTTIMEOUT_MS, LONG, 212), + + /* Set TCP keepalive */ + CINIT(TCP_KEEPALIVE, LONG, 213), + + /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ + CINIT(TCP_KEEPIDLE, LONG, 214), + CINIT(TCP_KEEPINTVL, LONG, 215), + + /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ + CINIT(SSL_OPTIONS, LONG, 216), + + /* Set the SMTP auth originator */ + CINIT(MAIL_AUTH, OBJECTPOINT, 217), + + /* Enable/disable SASL initial response */ + CINIT(SASL_IR, LONG, 218), + + /* Function that will be called instead of the internal progress display + * function. This function should be defined as the curl_xferinfo_callback + * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ + CINIT(XFERINFOFUNCTION, FUNCTIONPOINT, 219), + + /* The XOAUTH2 bearer token */ + CINIT(XOAUTH2_BEARER, OBJECTPOINT, 220), + + /* Set the interface string to use as outgoing network + * interface for DNS requests. + * Only supported by the c-ares DNS backend */ + CINIT(DNS_INTERFACE, OBJECTPOINT, 221), + + /* Set the local IPv4 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CINIT(DNS_LOCAL_IP4, OBJECTPOINT, 222), + + /* Set the local IPv4 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CINIT(DNS_LOCAL_IP6, OBJECTPOINT, 223), + + /* Set authentication options directly */ + CINIT(LOGIN_OPTIONS, OBJECTPOINT, 224), + + /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ + CINIT(SSL_ENABLE_NPN, LONG, 225), + + /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */ + CINIT(SSL_ENABLE_ALPN, LONG, 226), + + /* Time to wait for a response to a HTTP request containing an + * Expect: 100-continue header before sending the data anyway. */ + CINIT(EXPECT_100_TIMEOUT_MS, LONG, 227), + + /* This points to a linked list of headers used for proxy requests only, + struct curl_slist kind */ + CINIT(PROXYHEADER, OBJECTPOINT, 228), + + /* Pass in a bitmask of "header options" */ + CINIT(HEADEROPT, LONG, 229), + + /* The public key in DER form used to validate the peer public key + this option is used only if SSL_VERIFYPEER is true */ + CINIT(PINNEDPUBLICKEY, OBJECTPOINT, 230), + + /* Path to Unix domain socket */ + CINIT(UNIX_SOCKET_PATH, OBJECTPOINT, 231), + + CURLOPT_LASTENTRY /* the last unused */ +} CURLoption; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2011 */ + +/* This was added in version 7.19.1 */ +#define CURLOPT_POST301 CURLOPT_POSTREDIR + +/* These are scheduled to disappear by 2009 */ + +/* The following were added in 7.17.0 */ +#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_FTPAPPEND CURLOPT_APPEND +#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY +#define CURLOPT_FTP_SSL CURLOPT_USE_SSL + +/* The following were added earlier */ + +#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL + +#else +/* This is set if CURL_NO_OLDIES is defined at compile-time */ +#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ +#endif + + + /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host + name resolves addresses using more than one IP protocol version, this + option might be handy to force libcurl to use a specific IP version. */ +#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP + versions that your system allows */ +#define CURL_IPRESOLVE_V4 1 /* resolve to IPv4 addresses */ +#define CURL_IPRESOLVE_V6 2 /* resolve to IPv6 addresses */ + + /* three convenient "aliases" that follow the name scheme better */ +#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER + + /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ +enum { + CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd + like the library to choose the best possible + for us! */ + CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ + CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ + CURL_HTTP_VERSION_2_0, /* please use HTTP 2.0 in the request */ + + CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ +}; + +/* + * Public API enums for RTSP requests + */ +enum { + CURL_RTSPREQ_NONE, /* first in list */ + CURL_RTSPREQ_OPTIONS, + CURL_RTSPREQ_DESCRIBE, + CURL_RTSPREQ_ANNOUNCE, + CURL_RTSPREQ_SETUP, + CURL_RTSPREQ_PLAY, + CURL_RTSPREQ_PAUSE, + CURL_RTSPREQ_TEARDOWN, + CURL_RTSPREQ_GET_PARAMETER, + CURL_RTSPREQ_SET_PARAMETER, + CURL_RTSPREQ_RECORD, + CURL_RTSPREQ_RECEIVE, + CURL_RTSPREQ_LAST /* last in list */ +}; + + /* These enums are for use with the CURLOPT_NETRC option. */ +enum CURL_NETRC_OPTION { + CURL_NETRC_IGNORED, /* The .netrc will never be read. + * This is the default. */ + CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred + * to one in the .netrc. */ + CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. + * Unless one is set programmatically, the .netrc + * will be queried. */ + CURL_NETRC_LAST +}; + +enum { + CURL_SSLVERSION_DEFAULT, + CURL_SSLVERSION_TLSv1, /* TLS 1.x */ + CURL_SSLVERSION_SSLv2, + CURL_SSLVERSION_SSLv3, + CURL_SSLVERSION_TLSv1_0, + CURL_SSLVERSION_TLSv1_1, + CURL_SSLVERSION_TLSv1_2, + + CURL_SSLVERSION_LAST /* never use, keep last */ +}; + +enum CURL_TLSAUTH { + CURL_TLSAUTH_NONE, + CURL_TLSAUTH_SRP, + CURL_TLSAUTH_LAST /* never use, keep last */ +}; + +/* symbols to use with CURLOPT_POSTREDIR. + CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 + can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 + | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ + +#define CURL_REDIR_GET_ALL 0 +#define CURL_REDIR_POST_301 1 +#define CURL_REDIR_POST_302 2 +#define CURL_REDIR_POST_303 4 +#define CURL_REDIR_POST_ALL \ + (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) + +typedef enum { + CURL_TIMECOND_NONE, + + CURL_TIMECOND_IFMODSINCE, + CURL_TIMECOND_IFUNMODSINCE, + CURL_TIMECOND_LASTMOD, + + CURL_TIMECOND_LAST +} curl_TimeCond; + + +/* curl_strequal() and curl_strnequal() are subject for removal in a future + libcurl, see lib/README.curlx for details */ +CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2); +CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n); + +/* name is uppercase CURLFORM_ */ +#ifdef CFINIT +#undef CFINIT +#endif + +#ifdef CURL_ISOCPP +#define CFINIT(name) CURLFORM_ ## name +#else +/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ +#define CFINIT(name) CURLFORM_/**/name +#endif + +typedef enum { + CFINIT(NOTHING), /********* the first one is unused ************/ + + /* */ + CFINIT(COPYNAME), + CFINIT(PTRNAME), + CFINIT(NAMELENGTH), + CFINIT(COPYCONTENTS), + CFINIT(PTRCONTENTS), + CFINIT(CONTENTSLENGTH), + CFINIT(FILECONTENT), + CFINIT(ARRAY), + CFINIT(OBSOLETE), + CFINIT(FILE), + + CFINIT(BUFFER), + CFINIT(BUFFERPTR), + CFINIT(BUFFERLENGTH), + + CFINIT(CONTENTTYPE), + CFINIT(CONTENTHEADER), + CFINIT(FILENAME), + CFINIT(END), + CFINIT(OBSOLETE2), + + CFINIT(STREAM), + + CURLFORM_LASTENTRY /* the last unused */ +} CURLformoption; + +#undef CFINIT /* done */ + +/* structure to be used as parameter for CURLFORM_ARRAY */ +struct curl_forms { + CURLformoption option; + const char *value; +}; + +/* use this for multipart formpost building */ +/* Returns code for curl_formadd() + * + * Returns: + * CURL_FORMADD_OK on success + * CURL_FORMADD_MEMORY if the FormInfo allocation fails + * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form + * CURL_FORMADD_NULL if a null pointer was given for a char + * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed + * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used + * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) + * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated + * CURL_FORMADD_MEMORY if some allocation for string copying failed. + * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array + * + ***************************************************************************/ +typedef enum { + CURL_FORMADD_OK, /* first, no error */ + + CURL_FORMADD_MEMORY, + CURL_FORMADD_OPTION_TWICE, + CURL_FORMADD_NULL, + CURL_FORMADD_UNKNOWN_OPTION, + CURL_FORMADD_INCOMPLETE, + CURL_FORMADD_ILLEGAL_ARRAY, + CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ + + CURL_FORMADD_LAST /* last */ +} CURLFORMcode; + +/* + * NAME curl_formadd() + * + * DESCRIPTION + * + * Pretty advanced function for building multi-part formposts. Each invoke + * adds one part that together construct a full post. Then use + * CURLOPT_HTTPPOST to send it off to libcurl. + */ +CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...); + +/* + * callback function for curl_formget() + * The void *arg pointer will be the one passed as second argument to + * curl_formget(). + * The character buffer passed to it must not be freed. + * Should return the buffer length passed to it as the argument "len" on + * success. + */ +typedef size_t (*curl_formget_callback)(void *arg, const char *buf, + size_t len); + +/* + * NAME curl_formget() + * + * DESCRIPTION + * + * Serialize a curl_httppost struct built with curl_formadd(). + * Accepts a void pointer as second argument which will be passed to + * the curl_formget_callback function. + * Returns 0 on success. + */ +CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append); +/* + * NAME curl_formfree() + * + * DESCRIPTION + * + * Free a multipart formpost previously built with curl_formadd(). + */ +CURL_EXTERN void curl_formfree(struct curl_httppost *form); + +/* + * NAME curl_getenv() + * + * DESCRIPTION + * + * Returns a malloc()'ed string that MUST be curl_free()ed after usage is + * complete. DEPRECATED - see lib/README.curlx + */ +CURL_EXTERN char *curl_getenv(const char *variable); + +/* + * NAME curl_version() + * + * DESCRIPTION + * + * Returns a static ascii string of the libcurl version. + */ +CURL_EXTERN char *curl_version(void); + +/* + * NAME curl_easy_escape() + * + * DESCRIPTION + * + * Escapes URL strings (converts all letters consider illegal in URLs to their + * %XX versions). This function returns a new allocated string or NULL if an + * error occurred. + */ +CURL_EXTERN char *curl_easy_escape(CURL *handle, + const char *string, + int length); + +/* the previous version: */ +CURL_EXTERN char *curl_escape(const char *string, + int length); + + +/* + * NAME curl_easy_unescape() + * + * DESCRIPTION + * + * Unescapes URL encoding in strings (converts all %XX codes to their 8bit + * versions). This function returns a new allocated string or NULL if an error + * occurred. + * Conversion Note: On non-ASCII platforms the ASCII %XX codes are + * converted into the host encoding. + */ +CURL_EXTERN char *curl_easy_unescape(CURL *handle, + const char *string, + int length, + int *outlength); + +/* the previous version */ +CURL_EXTERN char *curl_unescape(const char *string, + int length); + +/* + * NAME curl_free() + * + * DESCRIPTION + * + * Provided for de-allocation in the same translation unit that did the + * allocation. Added in libcurl 7.10 + */ +CURL_EXTERN void curl_free(void *p); + +/* + * NAME curl_global_init() + * + * DESCRIPTION + * + * curl_global_init() should be invoked exactly once for each application that + * uses libcurl and before any call of other libcurl functions. + * + * This function is not thread-safe! + */ +CURL_EXTERN CURLcode curl_global_init(long flags); + +/* + * NAME curl_global_init_mem() + * + * DESCRIPTION + * + * curl_global_init() or curl_global_init_mem() should be invoked exactly once + * for each application that uses libcurl. This function can be used to + * initialize libcurl and set user defined memory management callback + * functions. Users can implement memory management routines to check for + * memory leaks, check for mis-use of the curl library etc. User registered + * callback routines with be invoked by this library instead of the system + * memory management routines like malloc, free etc. + */ +CURL_EXTERN CURLcode curl_global_init_mem(long flags, + curl_malloc_callback m, + curl_free_callback f, + curl_realloc_callback r, + curl_strdup_callback s, + curl_calloc_callback c); + +/* + * NAME curl_global_cleanup() + * + * DESCRIPTION + * + * curl_global_cleanup() should be invoked exactly once for each application + * that uses libcurl + */ +CURL_EXTERN void curl_global_cleanup(void); + +/* linked-list structure for the CURLOPT_QUOTE option (and other) */ +struct curl_slist { + char *data; + struct curl_slist *next; +}; + +/* + * NAME curl_slist_append() + * + * DESCRIPTION + * + * Appends a string to a linked list. If no list exists, it will be created + * first. Returns the new list, after appending. + */ +CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, + const char *); + +/* + * NAME curl_slist_free_all() + * + * DESCRIPTION + * + * free a previously built curl_slist. + */ +CURL_EXTERN void curl_slist_free_all(struct curl_slist *); + +/* + * NAME curl_getdate() + * + * DESCRIPTION + * + * Returns the time, in seconds since 1 Jan 1970 of the time string given in + * the first argument. The time argument in the second parameter is unused + * and should be set to NULL. + */ +CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); + +/* info about the certificate chain, only for OpenSSL builds. Asked + for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ +struct curl_certinfo { + int num_of_certs; /* number of certificates with information */ + struct curl_slist **certinfo; /* for each index in this array, there's a + linked list with textual information in the + format "name: value" */ +}; + +/* enum for the different supported SSL backends */ +typedef enum { + CURLSSLBACKEND_NONE = 0, + CURLSSLBACKEND_OPENSSL = 1, + CURLSSLBACKEND_GNUTLS = 2, + CURLSSLBACKEND_NSS = 3, + CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ + CURLSSLBACKEND_GSKIT = 5, + CURLSSLBACKEND_POLARSSL = 6, + CURLSSLBACKEND_CYASSL = 7, + CURLSSLBACKEND_SCHANNEL = 8, + CURLSSLBACKEND_DARWINSSL = 9, + CURLSSLBACKEND_AXTLS = 10 +} curl_sslbackend; + +/* Information about the SSL library used and the respective internal SSL + handle, which can be used to obtain further information regarding the + connection. Asked for with CURLINFO_TLS_SESSION. */ +struct curl_tlssessioninfo { + curl_sslbackend backend; + void *internals; +}; + +#define CURLINFO_STRING 0x100000 +#define CURLINFO_LONG 0x200000 +#define CURLINFO_DOUBLE 0x300000 +#define CURLINFO_SLIST 0x400000 +#define CURLINFO_MASK 0x0fffff +#define CURLINFO_TYPEMASK 0xf00000 + +typedef enum { + CURLINFO_NONE, /* first, never use this */ + CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, + CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, + CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, + CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, + CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, + CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, + CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, + CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, + CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, + CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, + CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, + CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, + CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, + CURLINFO_FILETIME = CURLINFO_LONG + 14, + CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, + CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, + CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, + CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, + CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, + CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, + CURLINFO_PRIVATE = CURLINFO_STRING + 21, + CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, + CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, + CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, + CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, + CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, + CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, + CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, + CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, + CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, + CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, + CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, + CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, + CURLINFO_CERTINFO = CURLINFO_SLIST + 34, + CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, + CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, + CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, + CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, + CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, + CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, + CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, + CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, + CURLINFO_TLS_SESSION = CURLINFO_SLIST + 43, + /* Fill in new entries below here! */ + + CURLINFO_LASTONE = 43 +} CURLINFO; + +/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as + CURLINFO_HTTP_CODE */ +#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE + +typedef enum { + CURLCLOSEPOLICY_NONE, /* first, never use this */ + + CURLCLOSEPOLICY_OLDEST, + CURLCLOSEPOLICY_LEAST_RECENTLY_USED, + CURLCLOSEPOLICY_LEAST_TRAFFIC, + CURLCLOSEPOLICY_SLOWEST, + CURLCLOSEPOLICY_CALLBACK, + + CURLCLOSEPOLICY_LAST /* last, never use this */ +} curl_closepolicy; + +#define CURL_GLOBAL_SSL (1<<0) +#define CURL_GLOBAL_WIN32 (1<<1) +#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) +#define CURL_GLOBAL_NOTHING 0 +#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL +#define CURL_GLOBAL_ACK_EINTR (1<<2) + + +/***************************************************************************** + * Setup defines, protos etc for the sharing stuff. + */ + +/* Different data locks for a single share */ +typedef enum { + CURL_LOCK_DATA_NONE = 0, + /* CURL_LOCK_DATA_SHARE is used internally to say that + * the locking is just made to change the internal state of the share + * itself. + */ + CURL_LOCK_DATA_SHARE, + CURL_LOCK_DATA_COOKIE, + CURL_LOCK_DATA_DNS, + CURL_LOCK_DATA_SSL_SESSION, + CURL_LOCK_DATA_CONNECT, + CURL_LOCK_DATA_LAST +} curl_lock_data; + +/* Different lock access types */ +typedef enum { + CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ + CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ + CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ + CURL_LOCK_ACCESS_LAST /* never use */ +} curl_lock_access; + +typedef void (*curl_lock_function)(CURL *handle, + curl_lock_data data, + curl_lock_access locktype, + void *userptr); +typedef void (*curl_unlock_function)(CURL *handle, + curl_lock_data data, + void *userptr); + +typedef void CURLSH; + +typedef enum { + CURLSHE_OK, /* all is fine */ + CURLSHE_BAD_OPTION, /* 1 */ + CURLSHE_IN_USE, /* 2 */ + CURLSHE_INVALID, /* 3 */ + CURLSHE_NOMEM, /* 4 out of memory */ + CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ + CURLSHE_LAST /* never use */ +} CURLSHcode; + +typedef enum { + CURLSHOPT_NONE, /* don't use */ + CURLSHOPT_SHARE, /* specify a data type to share */ + CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ + CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ + CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ + CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock + callback functions */ + CURLSHOPT_LAST /* never use */ +} CURLSHoption; + +CURL_EXTERN CURLSH *curl_share_init(void); +CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); +CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); + +/**************************************************************************** + * Structures for querying information about the curl library at runtime. + */ + +typedef enum { + CURLVERSION_FIRST, + CURLVERSION_SECOND, + CURLVERSION_THIRD, + CURLVERSION_FOURTH, + CURLVERSION_LAST /* never actually use this */ +} CURLversion; + +/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by + basically all programs ever that want to get version information. It is + meant to be a built-in version number for what kind of struct the caller + expects. If the struct ever changes, we redefine the NOW to another enum + from above. */ +#define CURLVERSION_NOW CURLVERSION_FOURTH + +typedef struct { + CURLversion age; /* age of the returned struct */ + const char *version; /* LIBCURL_VERSION */ + unsigned int version_num; /* LIBCURL_VERSION_NUM */ + const char *host; /* OS/host/cpu/machine when configured */ + int features; /* bitmask, see defines below */ + const char *ssl_version; /* human readable string */ + long ssl_version_num; /* not used anymore, always 0 */ + const char *libz_version; /* human readable string */ + /* protocols is terminated by an entry with a NULL protoname */ + const char * const *protocols; + + /* The fields below this were added in CURLVERSION_SECOND */ + const char *ares; + int ares_num; + + /* This field was added in CURLVERSION_THIRD */ + const char *libidn; + + /* These field were added in CURLVERSION_FOURTH */ + + /* Same as '_libiconv_version' if built with HAVE_ICONV */ + int iconv_ver_num; + + const char *libssh_version; /* human readable string */ + +} curl_version_info_data; + +#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ +#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported + (deprecated) */ +#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ +#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ +#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ +#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported + (deprecated) */ +#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ +#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ +#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ +#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ +#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are + supported */ +#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ +#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ +#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */ +#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ +#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper + is suported */ +#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ +#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ +#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ +#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ + + /* + * NAME curl_version_info() + * + * DESCRIPTION + * + * This function returns a pointer to a static copy of the version info + * struct. See above. + */ +CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); + +/* + * NAME curl_easy_strerror() + * + * DESCRIPTION + * + * The curl_easy_strerror function may be used to turn a CURLcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_easy_strerror(CURLcode); + +/* + * NAME curl_share_strerror() + * + * DESCRIPTION + * + * The curl_share_strerror function may be used to turn a CURLSHcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_share_strerror(CURLSHcode); + +/* + * NAME curl_easy_pause() + * + * DESCRIPTION + * + * The curl_easy_pause function pauses or unpauses transfers. Select the new + * state by setting the bitmask, use the convenience defines below. + * + */ +CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); + +#define CURLPAUSE_RECV (1<<0) +#define CURLPAUSE_RECV_CONT (0) + +#define CURLPAUSE_SEND (1<<2) +#define CURLPAUSE_SEND_CONT (0) + +#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) +#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) + +#ifdef __cplusplus +} +#endif + +/* unfortunately, the easy.h and multi.h include files need options and info + stuff before they can be included! */ +#include "easy.h" /* nothing in curl is fun without the easy stuff */ +#include "multi.h" + +/* the typechecker doesn't work in C++ (yet) */ +#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ + ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ + !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) +#include "typecheck-gcc.h" +#else +#if defined(__STDC__) && (__STDC__ >= 1) +/* This preprocessor magic that replaces a call with the exact same call is + only done to make sure application authors pass exactly three arguments + to these functions. */ +#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) +#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) +#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) +#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) +#endif /* __STDC__ >= 1 */ +#endif /* gcc >= 4.3 && !__cplusplus */ + +#endif /* __CURL_CURL_H */ diff --git a/other/curl/include/curl/curlbuild.h b/other/curl/include/curl/curlbuild.h new file mode 100644 index 0000000..f09419a --- /dev/null +++ b/other/curl/include/curl/curlbuild.h @@ -0,0 +1,585 @@ +#ifndef __CURL_CURLBUILD_H +#define __CURL_CURLBUILD_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2013, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* ================================================================ */ +/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */ +/* ================================================================ */ + +/* + * NOTE 1: + * ------- + * + * See file include/curl/curlbuild.h.in, run configure, and forget + * that this file exists it is only used for non-configure systems. + * But you can keep reading if you want ;-) + * + */ + +/* ================================================================ */ +/* NOTES FOR NON-CONFIGURE SYSTEMS */ +/* ================================================================ */ + +/* + * NOTE 1: + * ------- + * + * Nothing in this file is intended to be modified or adjusted by the + * curl library user nor by the curl library builder. + * + * If you think that something actually needs to be changed, adjusted + * or fixed in this file, then, report it on the libcurl development + * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ + * + * Try to keep one section per platform, compiler and architecture, + * otherwise, if an existing section is reused for a different one and + * later on the original is adjusted, probably the piggybacking one can + * be adversely changed. + * + * In order to differentiate between platforms/compilers/architectures + * use only compiler built in predefined preprocessor symbols. + * + * This header file shall only export symbols which are 'curl' or 'CURL' + * prefixed, otherwise public name space would be polluted. + * + * NOTE 2: + * ------- + * + * For any given platform/compiler curl_off_t must be typedef'ed to a + * 64-bit wide signed integral data type. The width of this data type + * must remain constant and independent of any possible large file + * support settings. + * + * As an exception to the above, curl_off_t shall be typedef'ed to a + * 32-bit wide signed integral data type if there is no 64-bit type. + * + * As a general rule, curl_off_t shall not be mapped to off_t. This + * rule shall only be violated if off_t is the only 64-bit data type + * available and the size of off_t is independent of large file support + * settings. Keep your build on the safe side avoiding an off_t gating. + * If you have a 64-bit off_t then take for sure that another 64-bit + * data type exists, dig deeper and you will find it. + * + * NOTE 3: + * ------- + * + * Right now you might be staring at file include/curl/curlbuild.h.dist or + * at file include/curl/curlbuild.h, this is due to the following reason: + * file include/curl/curlbuild.h.dist is renamed to include/curl/curlbuild.h + * when the libcurl source code distribution archive file is created. + * + * File include/curl/curlbuild.h.dist is not included in the distribution + * archive. File include/curl/curlbuild.h is not present in the git tree. + * + * The distributed include/curl/curlbuild.h file is only intended to be used + * on systems which can not run the also distributed configure script. + * + * On systems capable of running the configure script, the configure process + * will overwrite the distributed include/curl/curlbuild.h file with one that + * is suitable and specific to the library being configured and built, which + * is generated from the include/curl/curlbuild.h.in template file. + * + * If you check out from git on a non-configure platform, you must run the + * appropriate buildconf* script to set up curlbuild.h and other local files. + * + */ + +/* ================================================================ */ +/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */ +/* ================================================================ */ + +#ifdef CURL_SIZEOF_LONG +# error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T +# error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_SOCKLEN_T +# error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_OFF_T +# error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_T +# error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_TU +# error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined +#endif + +#ifdef CURL_FORMAT_OFF_T +# error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_OFF_T +# error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_T +# error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_TU +# error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined +#endif + +/* ================================================================ */ +/* EXTERNAL INTERFACE SETTINGS FOR NON-CONFIGURE SYSTEMS ONLY */ +/* ================================================================ */ + +#if defined(__DJGPP__) || defined(__GO32__) +# if defined(__DJGPP__) && (__DJGPP__ > 1) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__SALFORDC__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__BORLANDC__) +# if (__BORLANDC__ < 0x520) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__TURBOC__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__WATCOMC__) +# if defined(__386__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__POCC__) +# if (__POCC__ < 280) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# elif defined(_MSC_VER) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__LCC__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__SYMBIAN32__) +# if defined(__EABI__) /* Treat all ARM compilers equally */ +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__CW32__) +# pragma longlong on +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__VC32__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__MWERKS__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(_WIN32_WCE) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__MINGW32__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__VMS) +# if defined(__VAX) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +#elif defined(__OS400__) +# if defined(__ILEC400__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(__MVS__) +# if defined(__IBMC__) || defined(__IBMCPP__) +# if defined(_ILP32) +# define CURL_SIZEOF_LONG 4 +# elif defined(_LP64) +# define CURL_SIZEOF_LONG 8 +# endif +# if defined(_LONG_LONG) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(__370__) +# if defined(__IBMC__) || defined(__IBMCPP__) +# if defined(_ILP32) +# define CURL_SIZEOF_LONG 4 +# elif defined(_LP64) +# define CURL_SIZEOF_LONG 8 +# endif +# if defined(_LONG_LONG) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(TPF) +# define CURL_SIZEOF_LONG 8 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +/* ===================================== */ +/* KEEP MSVC THE PENULTIMATE ENTRY */ +/* ===================================== */ + +#elif defined(_MSC_VER) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_FORMAT_OFF_T "%I64d" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 4 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 + +/* ===================================== */ +/* KEEP GENERIC GCC THE LAST ENTRY */ +/* ===================================== */ + +#elif defined(__GNUC__) +# if defined(__ILP32__) || \ + defined(__i386__) || defined(__ppc__) || defined(__arm__) || defined(__sparc__) +# define CURL_SIZEOF_LONG 4 +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_FORMAT_OFF_T "%lld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__LP64__) || \ + defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) +# define CURL_SIZEOF_LONG 8 +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_FORMAT_OFF_T "%ld" +# define CURL_SIZEOF_CURL_OFF_T 8 +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_SIZEOF_CURL_SOCKLEN_T 4 +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#else +# error "Unknown non-configure build target!" + Error Compilation_aborted_Unknown_non_configure_build_target +#endif + +/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ +/* sys/types.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_TYPES_H +# include +#endif + +/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */ +/* sys/socket.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_SOCKET_H +# include +#endif + +/* Data type definition of curl_socklen_t. */ + +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T + typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; +#endif + +/* Data type definition of curl_off_t. */ + +#ifdef CURL_TYPEOF_CURL_OFF_T + typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; +#endif + +#endif /* __CURL_CURLBUILD_H */ diff --git a/other/curl/include/curl/curlbuild.h.cmake b/other/curl/include/curl/curlbuild.h.cmake new file mode 100644 index 0000000..60bc7a7 --- /dev/null +++ b/other/curl/include/curl/curlbuild.h.cmake @@ -0,0 +1,197 @@ +#ifndef __CURL_CURLBUILD_H +#define __CURL_CURLBUILD_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2008, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* ================================================================ */ +/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */ +/* ================================================================ */ + +/* + * NOTE 1: + * ------- + * + * Nothing in this file is intended to be modified or adjusted by the + * curl library user nor by the curl library builder. + * + * If you think that something actually needs to be changed, adjusted + * or fixed in this file, then, report it on the libcurl development + * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ + * + * This header file shall only export symbols which are 'curl' or 'CURL' + * prefixed, otherwise public name space would be polluted. + * + * NOTE 2: + * ------- + * + * Right now you might be staring at file include/curl/curlbuild.h.in or + * at file include/curl/curlbuild.h, this is due to the following reason: + * + * On systems capable of running the configure script, the configure process + * will overwrite the distributed include/curl/curlbuild.h file with one that + * is suitable and specific to the library being configured and built, which + * is generated from the include/curl/curlbuild.h.in template file. + * + */ + +/* ================================================================ */ +/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */ +/* ================================================================ */ + +#ifdef CURL_SIZEOF_LONG +#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T +#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_SOCKLEN_T +#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_OFF_T +#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_T +#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_TU +#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined +#endif + +#ifdef CURL_FORMAT_OFF_T +#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_OFF_T +#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_T +#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_TU +#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined +#endif + +/* ================================================================ */ +/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */ +/* ================================================================ */ + +/* Configure process defines this to 1 when it finds out that system */ +/* header file ws2tcpip.h must be included by the external interface. */ +#cmakedefine CURL_PULL_WS2TCPIP_H +#ifdef CURL_PULL_WS2TCPIP_H +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/types.h must be included by the external interface. */ +#cmakedefine CURL_PULL_SYS_TYPES_H +#ifdef CURL_PULL_SYS_TYPES_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file stdint.h must be included by the external interface. */ +#cmakedefine CURL_PULL_STDINT_H +#ifdef CURL_PULL_STDINT_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file inttypes.h must be included by the external interface. */ +#cmakedefine CURL_PULL_INTTYPES_H +#ifdef CURL_PULL_INTTYPES_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/socket.h must be included by the external interface. */ +#cmakedefine CURL_PULL_SYS_SOCKET_H +#ifdef CURL_PULL_SYS_SOCKET_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/poll.h must be included by the external interface. */ +#cmakedefine CURL_PULL_SYS_POLL_H +#ifdef CURL_PULL_SYS_POLL_H +# include +#endif + +/* The size of `long', as computed by sizeof. */ +#define CURL_SIZEOF_LONG ${CURL_SIZEOF_LONG} + +/* Integral data type used for curl_socklen_t. */ +#define CURL_TYPEOF_CURL_SOCKLEN_T ${CURL_TYPEOF_CURL_SOCKLEN_T} + +/* The size of `curl_socklen_t', as computed by sizeof. */ +#define CURL_SIZEOF_CURL_SOCKLEN_T ${CURL_SIZEOF_CURL_SOCKLEN_T} + +/* Data type definition of curl_socklen_t. */ +typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; + +/* Signed integral data type used for curl_off_t. */ +#define CURL_TYPEOF_CURL_OFF_T ${CURL_TYPEOF_CURL_OFF_T} + +/* Data type definition of curl_off_t. */ +typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; + +/* curl_off_t formatting string directive without "%" conversion specifier. */ +#define CURL_FORMAT_CURL_OFF_T "${CURL_FORMAT_CURL_OFF_T}" + +/* unsigned curl_off_t formatting string without "%" conversion specifier. */ +#define CURL_FORMAT_CURL_OFF_TU "${CURL_FORMAT_CURL_OFF_TU}" + +/* curl_off_t formatting string directive with "%" conversion specifier. */ +#define CURL_FORMAT_OFF_T "${CURL_FORMAT_OFF_T}" + +/* The size of `curl_off_t', as computed by sizeof. */ +#define CURL_SIZEOF_CURL_OFF_T ${CURL_SIZEOF_CURL_OFF_T} + +/* curl_off_t constant suffix. */ +#define CURL_SUFFIX_CURL_OFF_T ${CURL_SUFFIX_CURL_OFF_T} + +/* unsigned curl_off_t constant suffix. */ +#define CURL_SUFFIX_CURL_OFF_TU ${CURL_SUFFIX_CURL_OFF_TU} + +#endif /* __CURL_CURLBUILD_H */ diff --git a/other/curl/include/curl/curlbuild.h.in b/other/curl/include/curl/curlbuild.h.in new file mode 100644 index 0000000..e29f195 --- /dev/null +++ b/other/curl/include/curl/curlbuild.h.in @@ -0,0 +1,197 @@ +#ifndef __CURL_CURLBUILD_H +#define __CURL_CURLBUILD_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* ================================================================ */ +/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */ +/* ================================================================ */ + +/* + * NOTE 1: + * ------- + * + * Nothing in this file is intended to be modified or adjusted by the + * curl library user nor by the curl library builder. + * + * If you think that something actually needs to be changed, adjusted + * or fixed in this file, then, report it on the libcurl development + * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ + * + * This header file shall only export symbols which are 'curl' or 'CURL' + * prefixed, otherwise public name space would be polluted. + * + * NOTE 2: + * ------- + * + * Right now you might be staring at file include/curl/curlbuild.h.in or + * at file include/curl/curlbuild.h, this is due to the following reason: + * + * On systems capable of running the configure script, the configure process + * will overwrite the distributed include/curl/curlbuild.h file with one that + * is suitable and specific to the library being configured and built, which + * is generated from the include/curl/curlbuild.h.in template file. + * + */ + +/* ================================================================ */ +/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */ +/* ================================================================ */ + +#ifdef CURL_SIZEOF_LONG +#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T +#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_SOCKLEN_T +#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined +#endif + +#ifdef CURL_TYPEOF_CURL_OFF_T +#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_T +#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_FORMAT_CURL_OFF_TU +#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined +#endif + +#ifdef CURL_FORMAT_OFF_T +#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined +#endif + +#ifdef CURL_SIZEOF_CURL_OFF_T +#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_T +#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined +#endif + +#ifdef CURL_SUFFIX_CURL_OFF_TU +#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined +#endif + +/* ================================================================ */ +/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */ +/* ================================================================ */ + +/* Configure process defines this to 1 when it finds out that system */ +/* header file ws2tcpip.h must be included by the external interface. */ +#undef CURL_PULL_WS2TCPIP_H +#ifdef CURL_PULL_WS2TCPIP_H +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/types.h must be included by the external interface. */ +#undef CURL_PULL_SYS_TYPES_H +#ifdef CURL_PULL_SYS_TYPES_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file stdint.h must be included by the external interface. */ +#undef CURL_PULL_STDINT_H +#ifdef CURL_PULL_STDINT_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file inttypes.h must be included by the external interface. */ +#undef CURL_PULL_INTTYPES_H +#ifdef CURL_PULL_INTTYPES_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/socket.h must be included by the external interface. */ +#undef CURL_PULL_SYS_SOCKET_H +#ifdef CURL_PULL_SYS_SOCKET_H +# include +#endif + +/* Configure process defines this to 1 when it finds out that system */ +/* header file sys/poll.h must be included by the external interface. */ +#undef CURL_PULL_SYS_POLL_H +#ifdef CURL_PULL_SYS_POLL_H +# include +#endif + +/* The size of `long', as computed by sizeof. */ +#undef CURL_SIZEOF_LONG + +/* Integral data type used for curl_socklen_t. */ +#undef CURL_TYPEOF_CURL_SOCKLEN_T + +/* The size of `curl_socklen_t', as computed by sizeof. */ +#undef CURL_SIZEOF_CURL_SOCKLEN_T + +/* Data type definition of curl_socklen_t. */ +typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; + +/* Signed integral data type used for curl_off_t. */ +#undef CURL_TYPEOF_CURL_OFF_T + +/* Data type definition of curl_off_t. */ +typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; + +/* curl_off_t formatting string directive without "%" conversion specifier. */ +#undef CURL_FORMAT_CURL_OFF_T + +/* unsigned curl_off_t formatting string without "%" conversion specifier. */ +#undef CURL_FORMAT_CURL_OFF_TU + +/* curl_off_t formatting string directive with "%" conversion specifier. */ +#undef CURL_FORMAT_OFF_T + +/* The size of `curl_off_t', as computed by sizeof. */ +#undef CURL_SIZEOF_CURL_OFF_T + +/* curl_off_t constant suffix. */ +#undef CURL_SUFFIX_CURL_OFF_T + +/* unsigned curl_off_t constant suffix. */ +#undef CURL_SUFFIX_CURL_OFF_TU + +#endif /* __CURL_CURLBUILD_H */ diff --git a/other/curl/include/curl/curlrules.h b/other/curl/include/curl/curlrules.h new file mode 100644 index 0000000..7c2ede3 --- /dev/null +++ b/other/curl/include/curl/curlrules.h @@ -0,0 +1,262 @@ +#ifndef __CURL_CURLRULES_H +#define __CURL_CURLRULES_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* ================================================================ */ +/* COMPILE TIME SANITY CHECKS */ +/* ================================================================ */ + +/* + * NOTE 1: + * ------- + * + * All checks done in this file are intentionally placed in a public + * header file which is pulled by curl/curl.h when an application is + * being built using an already built libcurl library. Additionally + * this file is also included and used when building the library. + * + * If compilation fails on this file it is certainly sure that the + * problem is elsewhere. It could be a problem in the curlbuild.h + * header file, or simply that you are using different compilation + * settings than those used to build the library. + * + * Nothing in this file is intended to be modified or adjusted by the + * curl library user nor by the curl library builder. + * + * Do not deactivate any check, these are done to make sure that the + * library is properly built and used. + * + * You can find further help on the libcurl development mailing list: + * http://cool.haxx.se/mailman/listinfo/curl-library/ + * + * NOTE 2 + * ------ + * + * Some of the following compile time checks are based on the fact + * that the dimension of a constant array can not be a negative one. + * In this way if the compile time verification fails, the compilation + * will fail issuing an error. The error description wording is compiler + * dependent but it will be quite similar to one of the following: + * + * "negative subscript or subscript is too large" + * "array must have at least one element" + * "-1 is an illegal array size" + * "size of array is negative" + * + * If you are building an application which tries to use an already + * built libcurl library and you are getting this kind of errors on + * this file, it is a clear indication that there is a mismatch between + * how the library was built and how you are trying to use it for your + * application. Your already compiled or binary library provider is the + * only one who can give you the details you need to properly use it. + */ + +/* + * Verify that some macros are actually defined. + */ + +#ifndef CURL_SIZEOF_LONG +# error "CURL_SIZEOF_LONG definition is missing!" + Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing +#endif + +#ifndef CURL_TYPEOF_CURL_SOCKLEN_T +# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!" + Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing +#endif + +#ifndef CURL_SIZEOF_CURL_SOCKLEN_T +# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!" + Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing +#endif + +#ifndef CURL_TYPEOF_CURL_OFF_T +# error "CURL_TYPEOF_CURL_OFF_T definition is missing!" + Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing +#endif + +#ifndef CURL_FORMAT_CURL_OFF_T +# error "CURL_FORMAT_CURL_OFF_T definition is missing!" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing +#endif + +#ifndef CURL_FORMAT_CURL_OFF_TU +# error "CURL_FORMAT_CURL_OFF_TU definition is missing!" + Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing +#endif + +#ifndef CURL_FORMAT_OFF_T +# error "CURL_FORMAT_OFF_T definition is missing!" + Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing +#endif + +#ifndef CURL_SIZEOF_CURL_OFF_T +# error "CURL_SIZEOF_CURL_OFF_T definition is missing!" + Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing +#endif + +#ifndef CURL_SUFFIX_CURL_OFF_T +# error "CURL_SUFFIX_CURL_OFF_T definition is missing!" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing +#endif + +#ifndef CURL_SUFFIX_CURL_OFF_TU +# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!" + Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing +#endif + +/* + * Macros private to this header file. + */ + +#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1 + +#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1 + +/* + * Verify that the size previously defined and expected for long + * is the same as the one reported by sizeof() at compile time. + */ + +typedef char + __curl_rule_01__ + [CurlchkszEQ(long, CURL_SIZEOF_LONG)]; + +/* + * Verify that the size previously defined and expected for + * curl_off_t is actually the the same as the one reported + * by sizeof() at compile time. + */ + +typedef char + __curl_rule_02__ + [CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)]; + +/* + * Verify at compile time that the size of curl_off_t as reported + * by sizeof() is greater or equal than the one reported for long + * for the current compilation. + */ + +typedef char + __curl_rule_03__ + [CurlchkszGE(curl_off_t, long)]; + +/* + * Verify that the size previously defined and expected for + * curl_socklen_t is actually the the same as the one reported + * by sizeof() at compile time. + */ + +typedef char + __curl_rule_04__ + [CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)]; + +/* + * Verify at compile time that the size of curl_socklen_t as reported + * by sizeof() is greater or equal than the one reported for int for + * the current compilation. + */ + +typedef char + __curl_rule_05__ + [CurlchkszGE(curl_socklen_t, int)]; + +/* ================================================================ */ +/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */ +/* ================================================================ */ + +/* + * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow + * these to be visible and exported by the external libcurl interface API, + * while also making them visible to the library internals, simply including + * curl_setup.h, without actually needing to include curl.h internally. + * If some day this section would grow big enough, all this should be moved + * to its own header file. + */ + +/* + * Figure out if we can use the ## preprocessor operator, which is supported + * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ + * or __cplusplus so we need to carefully check for them too. + */ + +#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ + defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ + defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ + defined(__ILEC400__) + /* This compiler is believed to have an ISO compatible preprocessor */ +#define CURL_ISOCPP +#else + /* This compiler is believed NOT to have an ISO compatible preprocessor */ +#undef CURL_ISOCPP +#endif + +/* + * Macros for minimum-width signed and unsigned curl_off_t integer constants. + */ + +#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) +# define __CURL_OFF_T_C_HLPR2(x) x +# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x) +# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ + __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) +# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ + __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) +#else +# ifdef CURL_ISOCPP +# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix +# else +# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix +# endif +# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix) +# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) +# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) +#endif + +/* + * Get rid of macros private to this header file. + */ + +#undef CurlchkszEQ +#undef CurlchkszGE + +/* + * Get rid of macros not intended to exist beyond this point. + */ + +#undef CURL_PULL_WS2TCPIP_H +#undef CURL_PULL_SYS_TYPES_H +#undef CURL_PULL_SYS_SOCKET_H +#undef CURL_PULL_SYS_POLL_H +#undef CURL_PULL_STDINT_H +#undef CURL_PULL_INTTYPES_H + +#undef CURL_TYPEOF_CURL_SOCKLEN_T +#undef CURL_TYPEOF_CURL_OFF_T + +#ifdef CURL_NO_OLDIES +#undef CURL_FORMAT_OFF_T /* not required since 7.19.0 - obsoleted in 7.20.0 */ +#endif + +#endif /* __CURL_CURLRULES_H */ diff --git a/other/curl/include/curl/curlver.h b/other/curl/include/curl/curlver.h new file mode 100644 index 0000000..ccdafc1 --- /dev/null +++ b/other/curl/include/curl/curlver.h @@ -0,0 +1,69 @@ +#ifndef __CURL_CURLVER_H +#define __CURL_CURLVER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2015, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* This header file contains nothing but libcurl version info, generated by + a script at release-time. This was made its own header file in 7.11.2 */ + +/* This is the global package copyright */ +#define LIBCURL_COPYRIGHT "1996 - 2015 Daniel Stenberg, ." + +/* This is the version number of the libcurl package from which this header + file origins: */ +#define LIBCURL_VERSION "7.40.0" + +/* The numeric version number is also available "in parts" by using these + defines: */ +#define LIBCURL_VERSION_MAJOR 7 +#define LIBCURL_VERSION_MINOR 40 +#define LIBCURL_VERSION_PATCH 0 + +/* This is the numeric version of the libcurl version number, meant for easier + parsing and comparions by programs. The LIBCURL_VERSION_NUM define will + always follow this syntax: + + 0xXXYYZZ + + Where XX, YY and ZZ are the main version, release and patch numbers in + hexadecimal (using 8 bits each). All three numbers are always represented + using two digits. 1.2 would appear as "0x010200" while version 9.11.7 + appears as "0x090b07". + + This 6-digit (24 bits) hexadecimal number does not show pre-release number, + and it is always a greater number in a more recent release. It makes + comparisons with greater than and less than work. +*/ +#define LIBCURL_VERSION_NUM 0x072800 + +/* + * This is the date and time when the full source package was created. The + * timestamp is not stored in git, as the timestamp is properly set in the + * tarballs by the maketgz script. + * + * The format of the date should follow this template: + * + * "Mon Feb 12 11:35:33 UTC 2007" + */ +#define LIBCURL_TIMESTAMP "Thu Jan 8 08:17:17 UTC 2015" + +#endif /* __CURL_CURLVER_H */ diff --git a/other/curl/include/curl/easy.h b/other/curl/include/curl/easy.h new file mode 100644 index 0000000..c1e3e76 --- /dev/null +++ b/other/curl/include/curl/easy.h @@ -0,0 +1,102 @@ +#ifndef __CURL_EASY_H +#define __CURL_EASY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2008, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#ifdef __cplusplus +extern "C" { +#endif + +CURL_EXTERN CURL *curl_easy_init(void); +CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); +CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); +CURL_EXTERN void curl_easy_cleanup(CURL *curl); + +/* + * NAME curl_easy_getinfo() + * + * DESCRIPTION + * + * Request internal information from the curl session with this function. The + * third argument MUST be a pointer to a long, a pointer to a char * or a + * pointer to a double (as the documentation describes elsewhere). The data + * pointed to will be filled in accordingly and can be relied upon only if the + * function returns CURLE_OK. This function is intended to get used *AFTER* a + * performed transfer, all results from this function are undefined until the + * transfer is completed. + */ +CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); + + +/* + * NAME curl_easy_duphandle() + * + * DESCRIPTION + * + * Creates a new curl session handle with the same options set for the handle + * passed in. Duplicating a handle could only be a matter of cloning data and + * options, internal state info and things like persistent connections cannot + * be transferred. It is useful in multithreaded applications when you can run + * curl_easy_duphandle() for each new thread to avoid a series of identical + * curl_easy_setopt() invokes in every thread. + */ +CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl); + +/* + * NAME curl_easy_reset() + * + * DESCRIPTION + * + * Re-initializes a CURL handle to the default values. This puts back the + * handle to the same state as it was in when it was just created. + * + * It does keep: live connections, the Session ID cache, the DNS cache and the + * cookies. + */ +CURL_EXTERN void curl_easy_reset(CURL *curl); + +/* + * NAME curl_easy_recv() + * + * DESCRIPTION + * + * Receives data from the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, + size_t *n); + +/* + * NAME curl_easy_send() + * + * DESCRIPTION + * + * Sends data over the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, + size_t buflen, size_t *n); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/other/curl/include/curl/mprintf.h b/other/curl/include/curl/mprintf.h new file mode 100644 index 0000000..cc9e7f5 --- /dev/null +++ b/other/curl/include/curl/mprintf.h @@ -0,0 +1,81 @@ +#ifndef __CURL_MPRINTF_H +#define __CURL_MPRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2013, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include +#include /* needed for FILE */ + +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +CURL_EXTERN int curl_mprintf(const char *format, ...); +CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); +CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); +CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, + const char *format, ...); +CURL_EXTERN int curl_mvprintf(const char *format, va_list args); +CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); +CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); +CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, + const char *format, va_list args); +CURL_EXTERN char *curl_maprintf(const char *format, ...); +CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); + +#ifdef _MPRINTF_REPLACE +# undef printf +# undef fprintf +# undef sprintf +# undef vsprintf +# undef snprintf +# undef vprintf +# undef vfprintf +# undef vsnprintf +# undef aprintf +# undef vaprintf +# define printf curl_mprintf +# define fprintf curl_mfprintf +#ifdef CURLDEBUG +/* When built with CURLDEBUG we define away the sprintf functions since we + don't want internal code to be using them */ +# define sprintf sprintf_was_used +# define vsprintf vsprintf_was_used +#else +# define sprintf curl_msprintf +# define vsprintf curl_mvsprintf +#endif +# define snprintf curl_msnprintf +# define vprintf curl_mvprintf +# define vfprintf curl_mvfprintf +# define vsnprintf curl_mvsnprintf +# define aprintf curl_maprintf +# define vaprintf curl_mvaprintf +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __CURL_MPRINTF_H */ diff --git a/other/curl/include/curl/multi.h b/other/curl/include/curl/multi.h new file mode 100644 index 0000000..3c4acb0 --- /dev/null +++ b/other/curl/include/curl/multi.h @@ -0,0 +1,399 @@ +#ifndef __CURL_MULTI_H +#define __CURL_MULTI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2013, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +/* + This is an "external" header file. Don't give away any internals here! + + GOALS + + o Enable a "pull" interface. The application that uses libcurl decides where + and when to ask libcurl to get/send data. + + o Enable multiple simultaneous transfers in the same thread without making it + complicated for the application. + + o Enable the application to select() on its own file descriptors and curl's + file descriptors simultaneous easily. + +*/ + +/* + * This header file should not really need to include "curl.h" since curl.h + * itself includes this file and we expect user applications to do #include + * without the need for especially including multi.h. + * + * For some reason we added this include here at one point, and rather than to + * break existing (wrongly written) libcurl applications, we leave it as-is + * but with this warning attached. + */ +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void CURLM; + +typedef enum { + CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or + curl_multi_socket*() soon */ + CURLM_OK, + CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ + CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ + CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ + CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ + CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ + CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ + CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was + attempted to get added - again */ + CURLM_LAST +} CURLMcode; + +/* just to make code nicer when using curl_multi_socket() you can now check + for CURLM_CALL_MULTI_SOCKET too in the same style it works for + curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ +#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM + +typedef enum { + CURLMSG_NONE, /* first, not used */ + CURLMSG_DONE, /* This easy handle has completed. 'result' contains + the CURLcode of the transfer */ + CURLMSG_LAST /* last, not used */ +} CURLMSG; + +struct CURLMsg { + CURLMSG msg; /* what this message means */ + CURL *easy_handle; /* the handle it concerns */ + union { + void *whatever; /* message-specific data */ + CURLcode result; /* return code for transfer */ + } data; +}; +typedef struct CURLMsg CURLMsg; + +/* Based on poll(2) structure and values. + * We don't use pollfd and POLL* constants explicitly + * to cover platforms without poll(). */ +#define CURL_WAIT_POLLIN 0x0001 +#define CURL_WAIT_POLLPRI 0x0002 +#define CURL_WAIT_POLLOUT 0x0004 + +struct curl_waitfd { + curl_socket_t fd; + short events; + short revents; /* not supported yet */ +}; + +/* + * Name: curl_multi_init() + * + * Desc: inititalize multi-style curl usage + * + * Returns: a new CURLM handle to use in all 'curl_multi' functions. + */ +CURL_EXTERN CURLM *curl_multi_init(void); + +/* + * Name: curl_multi_add_handle() + * + * Desc: add a standard curl handle to the multi stack + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, + CURL *curl_handle); + + /* + * Name: curl_multi_remove_handle() + * + * Desc: removes a curl handle from the multi stack again + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, + CURL *curl_handle); + + /* + * Name: curl_multi_fdset() + * + * Desc: Ask curl for its fd_set sets. The app can use these to select() or + * poll() on. We want curl_multi_perform() called as soon as one of + * them are ready. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, + fd_set *read_fd_set, + fd_set *write_fd_set, + fd_set *exc_fd_set, + int *max_fd); + +/* + * Name: curl_multi_wait() + * + * Desc: Poll on all fds within a CURLM set as well as any + * additional fds passed to the function. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret); + + /* + * Name: curl_multi_perform() + * + * Desc: When the app thinks there's data available for curl it calls this + * function to read/write whatever there is right now. This returns + * as soon as the reads and writes are done. This function does not + * require that there actually is data available for reading or that + * data can be written, it can be called just in case. It returns + * the number of handles that still transfer data in the second + * argument's integer-pointer. + * + * Returns: CURLMcode type, general multi error code. *NOTE* that this only + * returns errors etc regarding the whole multi stack. There might + * still have occurred problems on invidual transfers even when this + * returns OK. + */ +CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, + int *running_handles); + + /* + * Name: curl_multi_cleanup() + * + * Desc: Cleans up and removes a whole multi stack. It does not free or + * touch any individual easy handles in any way. We need to define + * in what state those handles will be if this function is called + * in the middle of a transfer. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); + +/* + * Name: curl_multi_info_read() + * + * Desc: Ask the multi handle if there's any messages/informationals from + * the individual transfers. Messages include informationals such as + * error code from the transfer or just the fact that a transfer is + * completed. More details on these should be written down as well. + * + * Repeated calls to this function will return a new struct each + * time, until a special "end of msgs" struct is returned as a signal + * that there is no more to get at this point. + * + * The data the returned pointer points to will not survive calling + * curl_multi_cleanup(). + * + * The 'CURLMsg' struct is meant to be very simple and only contain + * very basic informations. If more involved information is wanted, + * we will provide the particular "transfer handle" in that struct + * and that should/could/would be used in subsequent + * curl_easy_getinfo() calls (or similar). The point being that we + * must never expose complex structs to applications, as then we'll + * undoubtably get backwards compatibility problems in the future. + * + * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out + * of structs. It also writes the number of messages left in the + * queue (after this read) in the integer the second argument points + * to. + */ +CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, + int *msgs_in_queue); + +/* + * Name: curl_multi_strerror() + * + * Desc: The curl_multi_strerror function may be used to turn a CURLMcode + * value into the equivalent human readable error string. This is + * useful for printing meaningful error messages. + * + * Returns: A pointer to a zero-terminated error message. + */ +CURL_EXTERN const char *curl_multi_strerror(CURLMcode); + +/* + * Name: curl_multi_socket() and + * curl_multi_socket_all() + * + * Desc: An alternative version of curl_multi_perform() that allows the + * application to pass in one of the file descriptors that have been + * detected to have "action" on them and let libcurl perform. + * See man page for details. + */ +#define CURL_POLL_NONE 0 +#define CURL_POLL_IN 1 +#define CURL_POLL_OUT 2 +#define CURL_POLL_INOUT 3 +#define CURL_POLL_REMOVE 4 + +#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD + +#define CURL_CSELECT_IN 0x01 +#define CURL_CSELECT_OUT 0x02 +#define CURL_CSELECT_ERR 0x04 + +typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ + curl_socket_t s, /* socket */ + int what, /* see above */ + void *userp, /* private callback + pointer */ + void *socketp); /* private socket + pointer */ +/* + * Name: curl_multi_timer_callback + * + * Desc: Called by libcurl whenever the library detects a change in the + * maximum number of milliseconds the app is allowed to wait before + * curl_multi_socket() or curl_multi_perform() must be called + * (to allow libcurl's timed events to take place). + * + * Returns: The callback should return zero. + */ +typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ + long timeout_ms, /* see above */ + void *userp); /* private callback + pointer */ + +CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, + int *running_handles); + +CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, + curl_socket_t s, + int ev_bitmask, + int *running_handles); + +CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, + int *running_handles); + +#ifndef CURL_ALLOW_OLD_MULTI_SOCKET +/* This macro below was added in 7.16.3 to push users who recompile to use + the new curl_multi_socket_action() instead of the old curl_multi_socket() +*/ +#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) +#endif + +/* + * Name: curl_multi_timeout() + * + * Desc: Returns the maximum number of milliseconds the app is allowed to + * wait before curl_multi_socket() or curl_multi_perform() must be + * called (to allow libcurl's timed events to take place). + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, + long *milliseconds); + +#undef CINIT /* re-using the same name as in curl.h */ + +#ifdef CURL_ISOCPP +#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num +#else +/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ +#define LONG CURLOPTTYPE_LONG +#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT +#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT +#define OFF_T CURLOPTTYPE_OFF_T +#define CINIT(name,type,number) CURLMOPT_/**/name = type + number +#endif + +typedef enum { + /* This is the socket callback function pointer */ + CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1), + + /* This is the argument passed to the socket callback */ + CINIT(SOCKETDATA, OBJECTPOINT, 2), + + /* set to 1 to enable pipelining for this multi handle */ + CINIT(PIPELINING, LONG, 3), + + /* This is the timer callback function pointer */ + CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4), + + /* This is the argument passed to the timer callback */ + CINIT(TIMERDATA, OBJECTPOINT, 5), + + /* maximum number of entries in the connection cache */ + CINIT(MAXCONNECTS, LONG, 6), + + /* maximum number of (pipelining) connections to one host */ + CINIT(MAX_HOST_CONNECTIONS, LONG, 7), + + /* maximum number of requests in a pipeline */ + CINIT(MAX_PIPELINE_LENGTH, LONG, 8), + + /* a connection with a content-length longer than this + will not be considered for pipelining */ + CINIT(CONTENT_LENGTH_PENALTY_SIZE, OFF_T, 9), + + /* a connection with a chunk length longer than this + will not be considered for pipelining */ + CINIT(CHUNK_LENGTH_PENALTY_SIZE, OFF_T, 10), + + /* a list of site names(+port) that are blacklisted from + pipelining */ + CINIT(PIPELINING_SITE_BL, OBJECTPOINT, 11), + + /* a list of server types that are blacklisted from + pipelining */ + CINIT(PIPELINING_SERVER_BL, OBJECTPOINT, 12), + + /* maximum number of open connections in total */ + CINIT(MAX_TOTAL_CONNECTIONS, LONG, 13), + + CURLMOPT_LASTENTRY /* the last unused */ +} CURLMoption; + + +/* + * Name: curl_multi_setopt() + * + * Desc: Sets options for the multi handle. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, + CURLMoption option, ...); + + +/* + * Name: curl_multi_assign() + * + * Desc: This function sets an association in the multi handle between the + * given socket and a private pointer of the application. This is + * (only) useful for curl_multi_socket uses. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, + curl_socket_t sockfd, void *sockp); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/other/curl/include/curl/stdcheaders.h b/other/curl/include/curl/stdcheaders.h new file mode 100644 index 0000000..ad82ef6 --- /dev/null +++ b/other/curl/include/curl/stdcheaders.h @@ -0,0 +1,33 @@ +#ifndef __STDC_HEADERS_H +#define __STDC_HEADERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2010, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include + +size_t fread (void *, size_t, size_t, FILE *); +size_t fwrite (const void *, size_t, size_t, FILE *); + +int strcasecmp(const char *, const char *); +int strncasecmp(const char *, const char *, size_t); + +#endif /* __STDC_HEADERS_H */ diff --git a/other/curl/include/curl/typecheck-gcc.h b/other/curl/include/curl/typecheck-gcc.h new file mode 100644 index 0000000..69d41a2 --- /dev/null +++ b/other/curl/include/curl/typecheck-gcc.h @@ -0,0 +1,610 @@ +#ifndef __CURL_TYPECHECK_GCC_H +#define __CURL_TYPECHECK_GCC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* wraps curl_easy_setopt() with typechecking */ + +/* To add a new kind of warning, add an + * if(_curl_is_sometype_option(_curl_opt)) + * if(!_curl_is_sometype(value)) + * _curl_easy_setopt_err_sometype(); + * block and define _curl_is_sometype_option, _curl_is_sometype and + * _curl_easy_setopt_err_sometype below + * + * NOTE: We use two nested 'if' statements here instead of the && operator, in + * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x + * when compiling with -Wlogical-op. + * + * To add an option that uses the same type as an existing option, you'll just + * need to extend the appropriate _curl_*_option macro + */ +#define curl_easy_setopt(handle, option, value) \ +__extension__ ({ \ + __typeof__ (option) _curl_opt = option; \ + if(__builtin_constant_p(_curl_opt)) { \ + if(_curl_is_long_option(_curl_opt)) \ + if(!_curl_is_long(value)) \ + _curl_easy_setopt_err_long(); \ + if(_curl_is_off_t_option(_curl_opt)) \ + if(!_curl_is_off_t(value)) \ + _curl_easy_setopt_err_curl_off_t(); \ + if(_curl_is_string_option(_curl_opt)) \ + if(!_curl_is_string(value)) \ + _curl_easy_setopt_err_string(); \ + if(_curl_is_write_cb_option(_curl_opt)) \ + if(!_curl_is_write_cb(value)) \ + _curl_easy_setopt_err_write_callback(); \ + if((_curl_opt) == CURLOPT_READFUNCTION) \ + if(!_curl_is_read_cb(value)) \ + _curl_easy_setopt_err_read_cb(); \ + if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ + if(!_curl_is_ioctl_cb(value)) \ + _curl_easy_setopt_err_ioctl_cb(); \ + if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ + if(!_curl_is_sockopt_cb(value)) \ + _curl_easy_setopt_err_sockopt_cb(); \ + if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ + if(!_curl_is_opensocket_cb(value)) \ + _curl_easy_setopt_err_opensocket_cb(); \ + if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ + if(!_curl_is_progress_cb(value)) \ + _curl_easy_setopt_err_progress_cb(); \ + if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ + if(!_curl_is_debug_cb(value)) \ + _curl_easy_setopt_err_debug_cb(); \ + if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ + if(!_curl_is_ssl_ctx_cb(value)) \ + _curl_easy_setopt_err_ssl_ctx_cb(); \ + if(_curl_is_conv_cb_option(_curl_opt)) \ + if(!_curl_is_conv_cb(value)) \ + _curl_easy_setopt_err_conv_cb(); \ + if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ + if(!_curl_is_seek_cb(value)) \ + _curl_easy_setopt_err_seek_cb(); \ + if(_curl_is_cb_data_option(_curl_opt)) \ + if(!_curl_is_cb_data(value)) \ + _curl_easy_setopt_err_cb_data(); \ + if((_curl_opt) == CURLOPT_ERRORBUFFER) \ + if(!_curl_is_error_buffer(value)) \ + _curl_easy_setopt_err_error_buffer(); \ + if((_curl_opt) == CURLOPT_STDERR) \ + if(!_curl_is_FILE(value)) \ + _curl_easy_setopt_err_FILE(); \ + if(_curl_is_postfields_option(_curl_opt)) \ + if(!_curl_is_postfields(value)) \ + _curl_easy_setopt_err_postfields(); \ + if((_curl_opt) == CURLOPT_HTTPPOST) \ + if(!_curl_is_arr((value), struct curl_httppost)) \ + _curl_easy_setopt_err_curl_httpost(); \ + if(_curl_is_slist_option(_curl_opt)) \ + if(!_curl_is_arr((value), struct curl_slist)) \ + _curl_easy_setopt_err_curl_slist(); \ + if((_curl_opt) == CURLOPT_SHARE) \ + if(!_curl_is_ptr((value), CURLSH)) \ + _curl_easy_setopt_err_CURLSH(); \ + } \ + curl_easy_setopt(handle, _curl_opt, value); \ +}) + +/* wraps curl_easy_getinfo() with typechecking */ +/* FIXME: don't allow const pointers */ +#define curl_easy_getinfo(handle, info, arg) \ +__extension__ ({ \ + __typeof__ (info) _curl_info = info; \ + if(__builtin_constant_p(_curl_info)) { \ + if(_curl_is_string_info(_curl_info)) \ + if(!_curl_is_arr((arg), char *)) \ + _curl_easy_getinfo_err_string(); \ + if(_curl_is_long_info(_curl_info)) \ + if(!_curl_is_arr((arg), long)) \ + _curl_easy_getinfo_err_long(); \ + if(_curl_is_double_info(_curl_info)) \ + if(!_curl_is_arr((arg), double)) \ + _curl_easy_getinfo_err_double(); \ + if(_curl_is_slist_info(_curl_info)) \ + if(!_curl_is_arr((arg), struct curl_slist *)) \ + _curl_easy_getinfo_err_curl_slist(); \ + } \ + curl_easy_getinfo(handle, _curl_info, arg); \ +}) + +/* TODO: typechecking for curl_share_setopt() and curl_multi_setopt(), + * for now just make sure that the functions are called with three + * arguments + */ +#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) +#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) + + +/* the actual warnings, triggered by calling the _curl_easy_setopt_err* + * functions */ + +/* To define a new warning, use _CURL_WARNING(identifier, "message") */ +#define _CURL_WARNING(id, message) \ + static void __attribute__((__warning__(message))) \ + __attribute__((__unused__)) __attribute__((__noinline__)) \ + id(void) { __asm__(""); } + +_CURL_WARNING(_curl_easy_setopt_err_long, + "curl_easy_setopt expects a long argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_curl_off_t, + "curl_easy_setopt expects a curl_off_t argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_string, + "curl_easy_setopt expects a " + "string (char* or char[]) argument for this option" + ) +_CURL_WARNING(_curl_easy_setopt_err_write_callback, + "curl_easy_setopt expects a curl_write_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_read_cb, + "curl_easy_setopt expects a curl_read_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_ioctl_cb, + "curl_easy_setopt expects a curl_ioctl_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_sockopt_cb, + "curl_easy_setopt expects a curl_sockopt_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_opensocket_cb, + "curl_easy_setopt expects a " + "curl_opensocket_callback argument for this option" + ) +_CURL_WARNING(_curl_easy_setopt_err_progress_cb, + "curl_easy_setopt expects a curl_progress_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_debug_cb, + "curl_easy_setopt expects a curl_debug_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_ssl_ctx_cb, + "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_conv_cb, + "curl_easy_setopt expects a curl_conv_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_seek_cb, + "curl_easy_setopt expects a curl_seek_callback argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_cb_data, + "curl_easy_setopt expects a " + "private data pointer as argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_error_buffer, + "curl_easy_setopt expects a " + "char buffer of CURL_ERROR_SIZE as argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_FILE, + "curl_easy_setopt expects a FILE* argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_postfields, + "curl_easy_setopt expects a void* or char* argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_curl_httpost, + "curl_easy_setopt expects a struct curl_httppost* argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_curl_slist, + "curl_easy_setopt expects a struct curl_slist* argument for this option") +_CURL_WARNING(_curl_easy_setopt_err_CURLSH, + "curl_easy_setopt expects a CURLSH* argument for this option") + +_CURL_WARNING(_curl_easy_getinfo_err_string, + "curl_easy_getinfo expects a pointer to char * for this info") +_CURL_WARNING(_curl_easy_getinfo_err_long, + "curl_easy_getinfo expects a pointer to long for this info") +_CURL_WARNING(_curl_easy_getinfo_err_double, + "curl_easy_getinfo expects a pointer to double for this info") +_CURL_WARNING(_curl_easy_getinfo_err_curl_slist, + "curl_easy_getinfo expects a pointer to struct curl_slist * for this info") + +/* groups of curl_easy_setops options that take the same type of argument */ + +/* To add a new option to one of the groups, just add + * (option) == CURLOPT_SOMETHING + * to the or-expression. If the option takes a long or curl_off_t, you don't + * have to do anything + */ + +/* evaluates to true if option takes a long argument */ +#define _curl_is_long_option(option) \ + (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) + +#define _curl_is_off_t_option(option) \ + ((option) > CURLOPTTYPE_OFF_T) + +/* evaluates to true if option takes a char* argument */ +#define _curl_is_string_option(option) \ + ((option) == CURLOPT_URL || \ + (option) == CURLOPT_PROXY || \ + (option) == CURLOPT_INTERFACE || \ + (option) == CURLOPT_NETRC_FILE || \ + (option) == CURLOPT_USERPWD || \ + (option) == CURLOPT_USERNAME || \ + (option) == CURLOPT_PASSWORD || \ + (option) == CURLOPT_PROXYUSERPWD || \ + (option) == CURLOPT_PROXYUSERNAME || \ + (option) == CURLOPT_PROXYPASSWORD || \ + (option) == CURLOPT_NOPROXY || \ + (option) == CURLOPT_ACCEPT_ENCODING || \ + (option) == CURLOPT_REFERER || \ + (option) == CURLOPT_USERAGENT || \ + (option) == CURLOPT_COOKIE || \ + (option) == CURLOPT_COOKIEFILE || \ + (option) == CURLOPT_COOKIEJAR || \ + (option) == CURLOPT_COOKIELIST || \ + (option) == CURLOPT_FTPPORT || \ + (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ + (option) == CURLOPT_FTP_ACCOUNT || \ + (option) == CURLOPT_RANGE || \ + (option) == CURLOPT_CUSTOMREQUEST || \ + (option) == CURLOPT_SSLCERT || \ + (option) == CURLOPT_SSLCERTTYPE || \ + (option) == CURLOPT_SSLKEY || \ + (option) == CURLOPT_SSLKEYTYPE || \ + (option) == CURLOPT_KEYPASSWD || \ + (option) == CURLOPT_SSLENGINE || \ + (option) == CURLOPT_CAINFO || \ + (option) == CURLOPT_CAPATH || \ + (option) == CURLOPT_RANDOM_FILE || \ + (option) == CURLOPT_EGDSOCKET || \ + (option) == CURLOPT_SSL_CIPHER_LIST || \ + (option) == CURLOPT_KRBLEVEL || \ + (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ + (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ + (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ + (option) == CURLOPT_CRLFILE || \ + (option) == CURLOPT_ISSUERCERT || \ + (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ + (option) == CURLOPT_SSH_KNOWNHOSTS || \ + (option) == CURLOPT_MAIL_FROM || \ + (option) == CURLOPT_RTSP_SESSION_ID || \ + (option) == CURLOPT_RTSP_STREAM_URI || \ + (option) == CURLOPT_RTSP_TRANSPORT || \ + (option) == CURLOPT_XOAUTH2_BEARER || \ + (option) == CURLOPT_DNS_SERVERS || \ + (option) == CURLOPT_DNS_INTERFACE || \ + (option) == CURLOPT_DNS_LOCAL_IP4 || \ + (option) == CURLOPT_DNS_LOCAL_IP6 || \ + (option) == CURLOPT_LOGIN_OPTIONS || \ + 0) + +/* evaluates to true if option takes a curl_write_callback argument */ +#define _curl_is_write_cb_option(option) \ + ((option) == CURLOPT_HEADERFUNCTION || \ + (option) == CURLOPT_WRITEFUNCTION) + +/* evaluates to true if option takes a curl_conv_callback argument */ +#define _curl_is_conv_cb_option(option) \ + ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) + +/* evaluates to true if option takes a data argument to pass to a callback */ +#define _curl_is_cb_data_option(option) \ + ((option) == CURLOPT_WRITEDATA || \ + (option) == CURLOPT_READDATA || \ + (option) == CURLOPT_IOCTLDATA || \ + (option) == CURLOPT_SOCKOPTDATA || \ + (option) == CURLOPT_OPENSOCKETDATA || \ + (option) == CURLOPT_PROGRESSDATA || \ + (option) == CURLOPT_HEADERDATA || \ + (option) == CURLOPT_DEBUGDATA || \ + (option) == CURLOPT_SSL_CTX_DATA || \ + (option) == CURLOPT_SEEKDATA || \ + (option) == CURLOPT_PRIVATE || \ + (option) == CURLOPT_SSH_KEYDATA || \ + (option) == CURLOPT_INTERLEAVEDATA || \ + (option) == CURLOPT_CHUNK_DATA || \ + (option) == CURLOPT_FNMATCH_DATA || \ + 0) + +/* evaluates to true if option takes a POST data argument (void* or char*) */ +#define _curl_is_postfields_option(option) \ + ((option) == CURLOPT_POSTFIELDS || \ + (option) == CURLOPT_COPYPOSTFIELDS || \ + 0) + +/* evaluates to true if option takes a struct curl_slist * argument */ +#define _curl_is_slist_option(option) \ + ((option) == CURLOPT_HTTPHEADER || \ + (option) == CURLOPT_HTTP200ALIASES || \ + (option) == CURLOPT_QUOTE || \ + (option) == CURLOPT_POSTQUOTE || \ + (option) == CURLOPT_PREQUOTE || \ + (option) == CURLOPT_TELNETOPTIONS || \ + (option) == CURLOPT_MAIL_RCPT || \ + 0) + +/* groups of curl_easy_getinfo infos that take the same type of argument */ + +/* evaluates to true if info expects a pointer to char * argument */ +#define _curl_is_string_info(info) \ + (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG) + +/* evaluates to true if info expects a pointer to long argument */ +#define _curl_is_long_info(info) \ + (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) + +/* evaluates to true if info expects a pointer to double argument */ +#define _curl_is_double_info(info) \ + (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) + +/* true if info expects a pointer to struct curl_slist * argument */ +#define _curl_is_slist_info(info) \ + (CURLINFO_SLIST < (info)) + + +/* typecheck helpers -- check whether given expression has requested type*/ + +/* For pointers, you can use the _curl_is_ptr/_curl_is_arr macros, + * otherwise define a new macro. Search for __builtin_types_compatible_p + * in the GCC manual. + * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is + * the actual expression passed to the curl_easy_setopt macro. This + * means that you can only apply the sizeof and __typeof__ operators, no + * == or whatsoever. + */ + +/* XXX: should evaluate to true iff expr is a pointer */ +#define _curl_is_any_ptr(expr) \ + (sizeof(expr) == sizeof(void*)) + +/* evaluates to true if expr is NULL */ +/* XXX: must not evaluate expr, so this check is not accurate */ +#define _curl_is_NULL(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) + +/* evaluates to true if expr is type*, const type* or NULL */ +#define _curl_is_ptr(expr, type) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), type *) || \ + __builtin_types_compatible_p(__typeof__(expr), const type *)) + +/* evaluates to true if expr is one of type[], type*, NULL or const type* */ +#define _curl_is_arr(expr, type) \ + (_curl_is_ptr((expr), type) || \ + __builtin_types_compatible_p(__typeof__(expr), type [])) + +/* evaluates to true if expr is a string */ +#define _curl_is_string(expr) \ + (_curl_is_arr((expr), char) || \ + _curl_is_arr((expr), signed char) || \ + _curl_is_arr((expr), unsigned char)) + +/* evaluates to true if expr is a long (no matter the signedness) + * XXX: for now, int is also accepted (and therefore short and char, which + * are promoted to int when passed to a variadic function) */ +#define _curl_is_long(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), long) || \ + __builtin_types_compatible_p(__typeof__(expr), signed long) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ + __builtin_types_compatible_p(__typeof__(expr), int) || \ + __builtin_types_compatible_p(__typeof__(expr), signed int) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ + __builtin_types_compatible_p(__typeof__(expr), short) || \ + __builtin_types_compatible_p(__typeof__(expr), signed short) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ + __builtin_types_compatible_p(__typeof__(expr), char) || \ + __builtin_types_compatible_p(__typeof__(expr), signed char) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned char)) + +/* evaluates to true if expr is of type curl_off_t */ +#define _curl_is_off_t(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) + +/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ +/* XXX: also check size of an char[] array? */ +#define _curl_is_error_buffer(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), char *) || \ + __builtin_types_compatible_p(__typeof__(expr), char[])) + +/* evaluates to true if expr is of type (const) void* or (const) FILE* */ +#if 0 +#define _curl_is_cb_data(expr) \ + (_curl_is_ptr((expr), void) || \ + _curl_is_ptr((expr), FILE)) +#else /* be less strict */ +#define _curl_is_cb_data(expr) \ + _curl_is_any_ptr(expr) +#endif + +/* evaluates to true if expr is of type FILE* */ +#define _curl_is_FILE(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), FILE *)) + +/* evaluates to true if expr can be passed as POST data (void* or char*) */ +#define _curl_is_postfields(expr) \ + (_curl_is_ptr((expr), void) || \ + _curl_is_arr((expr), char)) + +/* FIXME: the whole callback checking is messy... + * The idea is to tolerate char vs. void and const vs. not const + * pointers in arguments at least + */ +/* helper: __builtin_types_compatible_p distinguishes between functions and + * function pointers, hide it */ +#define _curl_callback_compatible(func, type) \ + (__builtin_types_compatible_p(__typeof__(func), type) || \ + __builtin_types_compatible_p(__typeof__(func), type*)) + +/* evaluates to true if expr is of type curl_read_callback or "similar" */ +#define _curl_is_read_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), __typeof__(fread)) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_read_callback) || \ + _curl_callback_compatible((expr), _curl_read_callback1) || \ + _curl_callback_compatible((expr), _curl_read_callback2) || \ + _curl_callback_compatible((expr), _curl_read_callback3) || \ + _curl_callback_compatible((expr), _curl_read_callback4) || \ + _curl_callback_compatible((expr), _curl_read_callback5) || \ + _curl_callback_compatible((expr), _curl_read_callback6)) +typedef size_t (_curl_read_callback1)(char *, size_t, size_t, void*); +typedef size_t (_curl_read_callback2)(char *, size_t, size_t, const void*); +typedef size_t (_curl_read_callback3)(char *, size_t, size_t, FILE*); +typedef size_t (_curl_read_callback4)(void *, size_t, size_t, void*); +typedef size_t (_curl_read_callback5)(void *, size_t, size_t, const void*); +typedef size_t (_curl_read_callback6)(void *, size_t, size_t, FILE*); + +/* evaluates to true if expr is of type curl_write_callback or "similar" */ +#define _curl_is_write_cb(expr) \ + (_curl_is_read_cb(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), __typeof__(fwrite)) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_write_callback) || \ + _curl_callback_compatible((expr), _curl_write_callback1) || \ + _curl_callback_compatible((expr), _curl_write_callback2) || \ + _curl_callback_compatible((expr), _curl_write_callback3) || \ + _curl_callback_compatible((expr), _curl_write_callback4) || \ + _curl_callback_compatible((expr), _curl_write_callback5) || \ + _curl_callback_compatible((expr), _curl_write_callback6)) +typedef size_t (_curl_write_callback1)(const char *, size_t, size_t, void*); +typedef size_t (_curl_write_callback2)(const char *, size_t, size_t, + const void*); +typedef size_t (_curl_write_callback3)(const char *, size_t, size_t, FILE*); +typedef size_t (_curl_write_callback4)(const void *, size_t, size_t, void*); +typedef size_t (_curl_write_callback5)(const void *, size_t, size_t, + const void*); +typedef size_t (_curl_write_callback6)(const void *, size_t, size_t, FILE*); + +/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ +#define _curl_is_ioctl_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_ioctl_callback) || \ + _curl_callback_compatible((expr), _curl_ioctl_callback1) || \ + _curl_callback_compatible((expr), _curl_ioctl_callback2) || \ + _curl_callback_compatible((expr), _curl_ioctl_callback3) || \ + _curl_callback_compatible((expr), _curl_ioctl_callback4)) +typedef curlioerr (_curl_ioctl_callback1)(CURL *, int, void*); +typedef curlioerr (_curl_ioctl_callback2)(CURL *, int, const void*); +typedef curlioerr (_curl_ioctl_callback3)(CURL *, curliocmd, void*); +typedef curlioerr (_curl_ioctl_callback4)(CURL *, curliocmd, const void*); + +/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ +#define _curl_is_sockopt_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_sockopt_callback) || \ + _curl_callback_compatible((expr), _curl_sockopt_callback1) || \ + _curl_callback_compatible((expr), _curl_sockopt_callback2)) +typedef int (_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); +typedef int (_curl_sockopt_callback2)(const void *, curl_socket_t, + curlsocktype); + +/* evaluates to true if expr is of type curl_opensocket_callback or + "similar" */ +#define _curl_is_opensocket_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_opensocket_callback) ||\ + _curl_callback_compatible((expr), _curl_opensocket_callback1) || \ + _curl_callback_compatible((expr), _curl_opensocket_callback2) || \ + _curl_callback_compatible((expr), _curl_opensocket_callback3) || \ + _curl_callback_compatible((expr), _curl_opensocket_callback4)) +typedef curl_socket_t (_curl_opensocket_callback1) + (void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (_curl_opensocket_callback2) + (void *, curlsocktype, const struct curl_sockaddr *); +typedef curl_socket_t (_curl_opensocket_callback3) + (const void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (_curl_opensocket_callback4) + (const void *, curlsocktype, const struct curl_sockaddr *); + +/* evaluates to true if expr is of type curl_progress_callback or "similar" */ +#define _curl_is_progress_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_progress_callback) || \ + _curl_callback_compatible((expr), _curl_progress_callback1) || \ + _curl_callback_compatible((expr), _curl_progress_callback2)) +typedef int (_curl_progress_callback1)(void *, + double, double, double, double); +typedef int (_curl_progress_callback2)(const void *, + double, double, double, double); + +/* evaluates to true if expr is of type curl_debug_callback or "similar" */ +#define _curl_is_debug_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_debug_callback) || \ + _curl_callback_compatible((expr), _curl_debug_callback1) || \ + _curl_callback_compatible((expr), _curl_debug_callback2) || \ + _curl_callback_compatible((expr), _curl_debug_callback3) || \ + _curl_callback_compatible((expr), _curl_debug_callback4) || \ + _curl_callback_compatible((expr), _curl_debug_callback5) || \ + _curl_callback_compatible((expr), _curl_debug_callback6) || \ + _curl_callback_compatible((expr), _curl_debug_callback7) || \ + _curl_callback_compatible((expr), _curl_debug_callback8)) +typedef int (_curl_debug_callback1) (CURL *, + curl_infotype, char *, size_t, void *); +typedef int (_curl_debug_callback2) (CURL *, + curl_infotype, char *, size_t, const void *); +typedef int (_curl_debug_callback3) (CURL *, + curl_infotype, const char *, size_t, void *); +typedef int (_curl_debug_callback4) (CURL *, + curl_infotype, const char *, size_t, const void *); +typedef int (_curl_debug_callback5) (CURL *, + curl_infotype, unsigned char *, size_t, void *); +typedef int (_curl_debug_callback6) (CURL *, + curl_infotype, unsigned char *, size_t, const void *); +typedef int (_curl_debug_callback7) (CURL *, + curl_infotype, const unsigned char *, size_t, void *); +typedef int (_curl_debug_callback8) (CURL *, + curl_infotype, const unsigned char *, size_t, const void *); + +/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ +/* this is getting even messier... */ +#define _curl_is_ssl_ctx_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_ssl_ctx_callback) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback1) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback2) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback3) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback4) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback5) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback6) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback7) || \ + _curl_callback_compatible((expr), _curl_ssl_ctx_callback8)) +typedef CURLcode (_curl_ssl_ctx_callback1)(CURL *, void *, void *); +typedef CURLcode (_curl_ssl_ctx_callback2)(CURL *, void *, const void *); +typedef CURLcode (_curl_ssl_ctx_callback3)(CURL *, const void *, void *); +typedef CURLcode (_curl_ssl_ctx_callback4)(CURL *, const void *, const void *); +#ifdef HEADER_SSL_H +/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX + * this will of course break if we're included before OpenSSL headers... + */ +typedef CURLcode (_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *); +typedef CURLcode (_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *); +typedef CURLcode (_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *); +typedef CURLcode (_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX, + const void *); +#else +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; +#endif + +/* evaluates to true if expr is of type curl_conv_callback or "similar" */ +#define _curl_is_conv_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_conv_callback) || \ + _curl_callback_compatible((expr), _curl_conv_callback1) || \ + _curl_callback_compatible((expr), _curl_conv_callback2) || \ + _curl_callback_compatible((expr), _curl_conv_callback3) || \ + _curl_callback_compatible((expr), _curl_conv_callback4)) +typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); +typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); +typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); +typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); + +/* evaluates to true if expr is of type curl_seek_callback or "similar" */ +#define _curl_is_seek_cb(expr) \ + (_curl_is_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), curl_seek_callback) || \ + _curl_callback_compatible((expr), _curl_seek_callback1) || \ + _curl_callback_compatible((expr), _curl_seek_callback2)) +typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); +typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); + + +#endif /* __CURL_TYPECHECK_GCC_H */ diff --git a/other/curl/include/libssh2_config.h b/other/curl/include/libssh2_config.h new file mode 100644 index 0000000..4e2ae29 --- /dev/null +++ b/other/curl/include/libssh2_config.h @@ -0,0 +1,42 @@ +#ifndef LIBSSH2_CONFIG_H +#define LIBSSH2_CONFIG_H + +#ifndef WIN32 +#define WIN32 +#endif +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif /* _CRT_SECURE_NO_DEPRECATE */ +#include +#include +#include + +#ifdef __MINGW32__ +#define HAVE_UNISTD_H +#define HAVE_INTTYPES_H +#define HAVE_SYS_TIME_H +#define HAVE_GETTIMEOFDAY +#endif + +#define HAVE_WINSOCK2_H +#define HAVE_IOCTLSOCKET +#define HAVE_SELECT + +#ifdef _MSC_VER +#define snprintf _snprintf +#if _MSC_VER < 1500 +#define vsnprintf _vsnprintf +#endif +#define strdup _strdup +#define strncasecmp _strnicmp +#define strcasecmp _stricmp +#else +#define strncasecmp strnicmp +#define strcasecmp stricmp +#endif /* _MSC_VER */ + +/* Enable newer diffie-hellman-group-exchange-sha1 syntax */ +#define LIBSSH2_DH_GEX_NEW 1 + +#endif /* LIBSSH2_CONFIG_H */ + diff --git a/other/curl/mac/lib32/libcurl.a b/other/curl/mac/lib32/libcurl.a new file mode 100644 index 0000000..b09c6c6 Binary files /dev/null and b/other/curl/mac/lib32/libcurl.a differ diff --git a/other/curl/mac/lib64/libcurl.a b/other/curl/mac/lib64/libcurl.a new file mode 100644 index 0000000..519cec8 Binary files /dev/null and b/other/curl/mac/lib64/libcurl.a differ diff --git a/other/curl/windows/lib32/curl.lib b/other/curl/windows/lib32/curl.lib new file mode 100644 index 0000000..a82cdc0 Binary files /dev/null and b/other/curl/windows/lib32/curl.lib differ diff --git a/other/freetype/VERSION b/other/freetype/VERSION new file mode 100644 index 0000000..f041bc6 --- /dev/null +++ b/other/freetype/VERSION @@ -0,0 +1 @@ +2.4.8 diff --git a/other/freetype/freetype.lua b/other/freetype/freetype.lua new file mode 100644 index 0000000..3c7f918 --- /dev/null +++ b/other/freetype/freetype.lua @@ -0,0 +1,71 @@ +FreeType = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.use_pkgconfig = false + option.use_winlib = 0 + option.lib_path = nil + + if family ~= "windows" and ExecuteSilent("pkg-config freetype2") == 0 then + option.value = true + option.use_pkgconfig = true + end + + if platform == "win32" then + option.value = true + option.use_winlib = 32 + elseif platform == "win64" then + option.value = true + option.use_winlib = 64 + end + end + + local apply = function(option, settings) + -- include path + settings.cc.includes:Add(FreeType.basepath .. "/include") + + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config freetype2 --cflags`") + settings.link.flags:Add("`pkg-config freetype2 --libs`") + + elseif option.use_winlib > 0 then + if option.use_winlib == 32 then + settings.link.libpath:Add(FreeType.basepath .. "/lib32") + else + settings.link.libpath:Add(FreeType.basepath .. "/lib64") + end + settings.link.libs:Add("freetype") + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + output:option(option, "use_winlib") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + if option.use_winlib == 32 then return "using supplied win32 libraries" end + if option.use_winlib == 64 then return "using supplied win64 libraries" end + return "using unknown method" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/freetype/include/freetype/config/ftconfig.h b/other/freetype/include/freetype/config/ftconfig.h new file mode 100644 index 0000000..a9e767c --- /dev/null +++ b/other/freetype/include/freetype/config/ftconfig.h @@ -0,0 +1,566 @@ +/***************************************************************************/ +/* */ +/* ftconfig.h */ +/* */ +/* ANSI-specific configuration file (specification only). */ +/* */ +/* Copyright 1996-2004, 2006-2008, 2010-2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This header file contains a number of macro definitions that are used */ + /* by the rest of the engine. Most of the macros here are automatically */ + /* determined at compile time, and you should not need to change it to */ + /* port FreeType, except to compile the library with a non-ANSI */ + /* compiler. */ + /* */ + /* Note however that if some specific modifications are needed, we */ + /* advise you to place a modified copy in your build directory. */ + /* */ + /* The build directory is usually `freetype/builds/', and */ + /* contains system-specific files that are always included first when */ + /* building the library. */ + /* */ + /* This ANSI version should stay in `include/freetype/config'. */ + /* */ + /*************************************************************************/ + +#ifndef __FTCONFIG_H__ +#define __FTCONFIG_H__ + +#include +#include FT_CONFIG_OPTIONS_H +#include FT_CONFIG_STANDARD_LIBRARY_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* PLATFORM-SPECIFIC CONFIGURATION MACROS */ + /* */ + /* These macros can be toggled to suit a specific system. The current */ + /* ones are defaults used to compile FreeType in an ANSI C environment */ + /* (16bit compilers are also supported). Copy this file to your own */ + /* `freetype/builds/' directory, and edit it to port the engine. */ + /* */ + /*************************************************************************/ + + + /* There are systems (like the Texas Instruments 'C54x) where a `char' */ + /* has 16 bits. ANSI C says that sizeof(char) is always 1. Since an */ + /* `int' has 16 bits also for this system, sizeof(int) gives 1 which */ + /* is probably unexpected. */ + /* */ + /* `CHAR_BIT' (defined in limits.h) gives the number of bits in a */ + /* `char' type. */ + +#ifndef FT_CHAR_BIT +#define FT_CHAR_BIT CHAR_BIT +#endif + + + /* The size of an `int' type. */ +#if FT_UINT_MAX == 0xFFFFUL +#define FT_SIZEOF_INT (16 / FT_CHAR_BIT) +#elif FT_UINT_MAX == 0xFFFFFFFFUL +#define FT_SIZEOF_INT (32 / FT_CHAR_BIT) +#elif FT_UINT_MAX > 0xFFFFFFFFUL && FT_UINT_MAX == 0xFFFFFFFFFFFFFFFFUL +#define FT_SIZEOF_INT (64 / FT_CHAR_BIT) +#else +#error "Unsupported size of `int' type!" +#endif + + /* The size of a `long' type. A five-byte `long' (as used e.g. on the */ + /* DM642) is recognized but avoided. */ +#if FT_ULONG_MAX == 0xFFFFFFFFUL +#define FT_SIZEOF_LONG (32 / FT_CHAR_BIT) +#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFUL +#define FT_SIZEOF_LONG (32 / FT_CHAR_BIT) +#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFFFFFFFUL +#define FT_SIZEOF_LONG (64 / FT_CHAR_BIT) +#else +#error "Unsupported size of `long' type!" +#endif + + + /* FT_UNUSED is a macro used to indicate that a given parameter is not */ + /* used -- this is only used to get rid of unpleasant compiler warnings */ +#ifndef FT_UNUSED +#define FT_UNUSED( arg ) ( (arg) = (arg) ) +#endif + + + /*************************************************************************/ + /* */ + /* AUTOMATIC CONFIGURATION MACROS */ + /* */ + /* These macros are computed from the ones defined above. Don't touch */ + /* their definition, unless you know precisely what you are doing. No */ + /* porter should need to mess with them. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* Mac support */ + /* */ + /* This is the only necessary change, so it is defined here instead */ + /* providing a new configuration file. */ + /* */ +#if ( defined( __APPLE__ ) && !defined( DARWIN_NO_CARBON ) ) || \ + ( defined( __MWERKS__ ) && defined( macintosh ) ) + /* no Carbon frameworks for 64bit 10.4.x */ + /* AvailabilityMacros.h is available since Mac OS X 10.2, */ + /* so guess the system version by maximum errno before inclusion */ +#include +#ifdef ECANCELED /* defined since 10.2 */ +#include "AvailabilityMacros.h" +#endif +#if defined( __LP64__ ) && \ + ( MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4 ) +#define DARWIN_NO_CARBON 1 +#else +#define FT_MACINTOSH 1 +#endif + +#elif defined( __SC__ ) || defined( __MRC__ ) + /* Classic MacOS compilers */ +#include "ConditionalMacros.h" +#if TARGET_OS_MAC +#define FT_MACINTOSH 1 +#endif + +#endif + + + /*************************************************************************/ + /* */ + /*
*/ + /* basic_types */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* */ + /* FT_Int16 */ + /* */ + /* */ + /* A typedef for a 16bit signed integer type. */ + /* */ + typedef signed short FT_Int16; + + + /*************************************************************************/ + /* */ + /* */ + /* FT_UInt16 */ + /* */ + /* */ + /* A typedef for a 16bit unsigned integer type. */ + /* */ + typedef unsigned short FT_UInt16; + + /* */ + + + /* this #if 0 ... #endif clause is for documentation purposes */ +#if 0 + + /*************************************************************************/ + /* */ + /* */ + /* FT_Int32 */ + /* */ + /* */ + /* A typedef for a 32bit signed integer type. The size depends on */ + /* the configuration. */ + /* */ + typedef signed XXX FT_Int32; + + + /*************************************************************************/ + /* */ + /* */ + /* FT_UInt32 */ + /* */ + /* A typedef for a 32bit unsigned integer type. The size depends on */ + /* the configuration. */ + /* */ + typedef unsigned XXX FT_UInt32; + + /* */ + +#endif + +#if FT_SIZEOF_INT == (32 / FT_CHAR_BIT) + + typedef signed int FT_Int32; + typedef unsigned int FT_UInt32; + +#elif FT_SIZEOF_LONG == (32 / FT_CHAR_BIT) + + typedef signed long FT_Int32; + typedef unsigned long FT_UInt32; + +#else +#error "no 32bit type found -- please check your configuration files" +#endif + + + /* look up an integer type that is at least 32 bits */ +#if FT_SIZEOF_INT >= (32 / FT_CHAR_BIT) + + typedef int FT_Fast; + typedef unsigned int FT_UFast; + +#elif FT_SIZEOF_LONG >= (32 / FT_CHAR_BIT) + + typedef long FT_Fast; + typedef unsigned long FT_UFast; + +#endif + + + /* determine whether we have a 64-bit int type for platforms without */ + /* Autoconf */ +#if FT_SIZEOF_LONG == (64 / FT_CHAR_BIT) + + /* FT_LONG64 must be defined if a 64-bit type is available */ +#define FT_LONG64 +#define FT_INT64 long + +#elif defined( _MSC_VER ) && _MSC_VER >= 900 /* Visual C++ (and Intel C++) */ + + /* this compiler provides the __int64 type */ +#define FT_LONG64 +#define FT_INT64 __int64 + +#elif defined( __BORLANDC__ ) /* Borland C++ */ + + /* XXXX: We should probably check the value of __BORLANDC__ in order */ + /* to test the compiler version. */ + + /* this compiler provides the __int64 type */ +#define FT_LONG64 +#define FT_INT64 __int64 + +#elif defined( __WATCOMC__ ) /* Watcom C++ */ + + /* Watcom doesn't provide 64-bit data types */ + +#elif defined( __MWERKS__ ) /* Metrowerks CodeWarrior */ + +#define FT_LONG64 +#define FT_INT64 long long int + +#elif defined( __GNUC__ ) + + /* GCC provides the `long long' type */ +#define FT_LONG64 +#define FT_INT64 long long int + +#endif /* FT_SIZEOF_LONG == (64 / FT_CHAR_BIT) */ + + + /*************************************************************************/ + /* */ + /* A 64-bit data type will create compilation problems if you compile */ + /* in strict ANSI mode. To avoid them, we disable its use if __STDC__ */ + /* is defined. You can however ignore this rule by defining the */ + /* FT_CONFIG_OPTION_FORCE_INT64 configuration macro. */ + /* */ +#if defined( FT_LONG64 ) && !defined( FT_CONFIG_OPTION_FORCE_INT64 ) + +#ifdef __STDC__ + + /* undefine the 64-bit macros in strict ANSI compilation mode */ +#undef FT_LONG64 +#undef FT_INT64 + +#endif /* __STDC__ */ + +#endif /* FT_LONG64 && !FT_CONFIG_OPTION_FORCE_INT64 */ + + +#define FT_BEGIN_STMNT do { +#define FT_END_STMNT } while ( 0 ) +#define FT_DUMMY_STMNT FT_BEGIN_STMNT FT_END_STMNT + + +#ifndef FT_CONFIG_OPTION_NO_ASSEMBLER + /* Provide assembler fragments for performance-critical functions. */ + /* These must be defined `static __inline__' with GCC. */ + +#if defined( __CC_ARM ) || defined( __ARMCC__ ) /* RVCT */ +#define FT_MULFIX_ASSEMBLER FT_MulFix_arm + + /* documentation is in freetype.h */ + + static __inline FT_Int32 + FT_MulFix_arm( FT_Int32 a, + FT_Int32 b ) + { + register FT_Int32 t, t2; + + + __asm + { + smull t2, t, b, a /* (lo=t2,hi=t) = a*b */ + mov a, t, asr #31 /* a = (hi >> 31) */ + add a, a, #0x8000 /* a += 0x8000 */ + adds t2, t2, a /* t2 += a */ + adc t, t, #0 /* t += carry */ + mov a, t2, lsr #16 /* a = t2 >> 16 */ + orr a, a, t, lsl #16 /* a |= t << 16 */ + } + return a; + } + +#endif /* __CC_ARM || __ARMCC__ */ + + +#ifdef __GNUC__ + +#if defined( __arm__ ) && !defined( __thumb__ ) && \ + !( defined( __CC_ARM ) || defined( __ARMCC__ ) ) +#define FT_MULFIX_ASSEMBLER FT_MulFix_arm + + /* documentation is in freetype.h */ + + static __inline__ FT_Int32 + FT_MulFix_arm( FT_Int32 a, + FT_Int32 b ) + { + register FT_Int32 t, t2; + + + __asm__ __volatile__ ( + "smull %1, %2, %4, %3\n\t" /* (lo=%1,hi=%2) = a*b */ + "mov %0, %2, asr #31\n\t" /* %0 = (hi >> 31) */ + "add %0, %0, #0x8000\n\t" /* %0 += 0x8000 */ + "adds %1, %1, %0\n\t" /* %1 += %0 */ + "adc %2, %2, #0\n\t" /* %2 += carry */ + "mov %0, %1, lsr #16\n\t" /* %0 = %1 >> 16 */ + "orr %0, %0, %2, lsl #16\n\t" /* %0 |= %2 << 16 */ + : "=r"(a), "=&r"(t2), "=&r"(t) + : "r"(a), "r"(b) ); + return a; + } + +#endif /* __arm__ && !__thumb__ && !( __CC_ARM || __ARMCC__ ) */ + +#if defined( __i386__ ) +#define FT_MULFIX_ASSEMBLER FT_MulFix_i386 + + /* documentation is in freetype.h */ + + static __inline__ FT_Int32 + FT_MulFix_i386( FT_Int32 a, + FT_Int32 b ) + { + register FT_Int32 result; + + + __asm__ __volatile__ ( + "imul %%edx\n" + "movl %%edx, %%ecx\n" + "sarl $31, %%ecx\n" + "addl $0x8000, %%ecx\n" + "addl %%ecx, %%eax\n" + "adcl $0, %%edx\n" + "shrl $16, %%eax\n" + "shll $16, %%edx\n" + "addl %%edx, %%eax\n" + : "=a"(result), "=d"(b) + : "a"(a), "d"(b) + : "%ecx", "cc" ); + return result; + } + +#endif /* i386 */ + +#endif /* __GNUC__ */ + + +#ifdef _MSC_VER /* Visual C++ */ + +#ifdef _M_IX86 + +#define FT_MULFIX_ASSEMBLER FT_MulFix_i386 + + /* documentation is in freetype.h */ + + static __inline FT_Int32 + FT_MulFix_i386( FT_Int32 a, + FT_Int32 b ) + { + register FT_Int32 result; + + __asm + { + mov eax, a + mov edx, b + imul edx + mov ecx, edx + sar ecx, 31 + add ecx, 8000h + add eax, ecx + adc edx, 0 + shr eax, 16 + shl edx, 16 + add eax, edx + mov result, eax + } + return result; + } + +#endif /* _M_IX86 */ + +#endif /* _MSC_VER */ + +#endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */ + + +#ifdef FT_CONFIG_OPTION_INLINE_MULFIX +#ifdef FT_MULFIX_ASSEMBLER +#define FT_MULFIX_INLINED FT_MULFIX_ASSEMBLER +#endif +#endif + + +#ifdef FT_MAKE_OPTION_SINGLE_OBJECT + +#define FT_LOCAL( x ) static x +#define FT_LOCAL_DEF( x ) static x + +#else + +#ifdef __cplusplus +#define FT_LOCAL( x ) extern "C" x +#define FT_LOCAL_DEF( x ) extern "C" x +#else +#define FT_LOCAL( x ) extern x +#define FT_LOCAL_DEF( x ) x +#endif + +#endif /* FT_MAKE_OPTION_SINGLE_OBJECT */ + + +#ifndef FT_BASE + +#ifdef __cplusplus +#define FT_BASE( x ) extern "C" x +#else +#define FT_BASE( x ) extern x +#endif + +#endif /* !FT_BASE */ + + +#ifndef FT_BASE_DEF + +#ifdef __cplusplus +#define FT_BASE_DEF( x ) x +#else +#define FT_BASE_DEF( x ) x +#endif + +#endif /* !FT_BASE_DEF */ + + +#ifndef FT_EXPORT + +#ifdef __cplusplus +#define FT_EXPORT( x ) extern "C" x +#else +#define FT_EXPORT( x ) extern x +#endif + +#endif /* !FT_EXPORT */ + + +#ifndef FT_EXPORT_DEF + +#ifdef __cplusplus +#define FT_EXPORT_DEF( x ) extern "C" x +#else +#define FT_EXPORT_DEF( x ) extern x +#endif + +#endif /* !FT_EXPORT_DEF */ + + +#ifndef FT_EXPORT_VAR + +#ifdef __cplusplus +#define FT_EXPORT_VAR( x ) extern "C" x +#else +#define FT_EXPORT_VAR( x ) extern x +#endif + +#endif /* !FT_EXPORT_VAR */ + + /* The following macros are needed to compile the library with a */ + /* C++ compiler and with 16bit compilers. */ + /* */ + + /* This is special. Within C++, you must specify `extern "C"' for */ + /* functions which are used via function pointers, and you also */ + /* must do that for structures which contain function pointers to */ + /* assure C linkage -- it's not possible to have (local) anonymous */ + /* functions which are accessed by (global) function pointers. */ + /* */ + /* */ + /* FT_CALLBACK_DEF is used to _define_ a callback function. */ + /* */ + /* FT_CALLBACK_TABLE is used to _declare_ a constant variable that */ + /* contains pointers to callback functions. */ + /* */ + /* FT_CALLBACK_TABLE_DEF is used to _define_ a constant variable */ + /* that contains pointers to callback functions. */ + /* */ + /* */ + /* Some 16bit compilers have to redefine these macros to insert */ + /* the infamous `_cdecl' or `__fastcall' declarations. */ + /* */ +#ifndef FT_CALLBACK_DEF +#ifdef __cplusplus +#define FT_CALLBACK_DEF( x ) extern "C" x +#else +#define FT_CALLBACK_DEF( x ) static x +#endif +#endif /* FT_CALLBACK_DEF */ + +#ifndef FT_CALLBACK_TABLE +#ifdef __cplusplus +#define FT_CALLBACK_TABLE extern "C" +#define FT_CALLBACK_TABLE_DEF extern "C" +#else +#define FT_CALLBACK_TABLE extern +#define FT_CALLBACK_TABLE_DEF /* nothing */ +#endif +#endif /* FT_CALLBACK_TABLE */ + + +FT_END_HEADER + + +#endif /* __FTCONFIG_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/config/ftheader.h b/other/freetype/include/freetype/config/ftheader.h new file mode 100644 index 0000000..2a7b8c4 --- /dev/null +++ b/other/freetype/include/freetype/config/ftheader.h @@ -0,0 +1,793 @@ +/***************************************************************************/ +/* */ +/* ftheader.h */ +/* */ +/* Build macros of the FreeType 2 library. */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +#ifndef __FT_HEADER_H__ +#define __FT_HEADER_H__ + + + /*@***********************************************************************/ + /* */ + /* */ + /* FT_BEGIN_HEADER */ + /* */ + /* */ + /* This macro is used in association with @FT_END_HEADER in header */ + /* files to ensure that the declarations within are properly */ + /* encapsulated in an `extern "C" { .. }' block when included from a */ + /* C++ compiler. */ + /* */ +#ifdef __cplusplus +#define FT_BEGIN_HEADER extern "C" { +#else +#define FT_BEGIN_HEADER /* nothing */ +#endif + + + /*@***********************************************************************/ + /* */ + /* */ + /* FT_END_HEADER */ + /* */ + /* */ + /* This macro is used in association with @FT_BEGIN_HEADER in header */ + /* files to ensure that the declarations within are properly */ + /* encapsulated in an `extern "C" { .. }' block when included from a */ + /* C++ compiler. */ + /* */ +#ifdef __cplusplus +#define FT_END_HEADER } +#else +#define FT_END_HEADER /* nothing */ +#endif + + + /*************************************************************************/ + /* */ + /* Aliases for the FreeType 2 public and configuration files. */ + /* */ + /*************************************************************************/ + + /*************************************************************************/ + /* */ + /*
*/ + /* header_file_macros */ + /* */ + /* */ + /* Header File Macros */ + /* */ + /* <Abstract> */ + /* Macro definitions used to #include specific header files. */ + /* */ + /* <Description> */ + /* The following macros are defined to the name of specific */ + /* FreeType~2 header files. They can be used directly in #include */ + /* statements as in: */ + /* */ + /* { */ + /* #include FT_FREETYPE_H */ + /* #include FT_MULTIPLE_MASTERS_H */ + /* #include FT_GLYPH_H */ + /* } */ + /* */ + /* There are several reasons why we are now using macros to name */ + /* public header files. The first one is that such macros are not */ + /* limited to the infamous 8.3~naming rule required by DOS (and */ + /* `FT_MULTIPLE_MASTERS_H' is a lot more meaningful than `ftmm.h'). */ + /* */ + /* The second reason is that it allows for more flexibility in the */ + /* way FreeType~2 is installed on a given system. */ + /* */ + /*************************************************************************/ + + + /* configuration files */ + + /************************************************************************* + * + * @macro: + * FT_CONFIG_CONFIG_H + * + * @description: + * A macro used in #include statements to name the file containing + * FreeType~2 configuration data. + * + */ +#ifndef FT_CONFIG_CONFIG_H +#define FT_CONFIG_CONFIG_H <freetype/config/ftconfig.h> +#endif + + + /************************************************************************* + * + * @macro: + * FT_CONFIG_STANDARD_LIBRARY_H + * + * @description: + * A macro used in #include statements to name the file containing + * FreeType~2 interface to the standard C library functions. + * + */ +#ifndef FT_CONFIG_STANDARD_LIBRARY_H +#define FT_CONFIG_STANDARD_LIBRARY_H <freetype/config/ftstdlib.h> +#endif + + + /************************************************************************* + * + * @macro: + * FT_CONFIG_OPTIONS_H + * + * @description: + * A macro used in #include statements to name the file containing + * FreeType~2 project-specific configuration options. + * + */ +#ifndef FT_CONFIG_OPTIONS_H +#define FT_CONFIG_OPTIONS_H <freetype/config/ftoption.h> +#endif + + + /************************************************************************* + * + * @macro: + * FT_CONFIG_MODULES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * list of FreeType~2 modules that are statically linked to new library + * instances in @FT_Init_FreeType. + * + */ +#ifndef FT_CONFIG_MODULES_H +#define FT_CONFIG_MODULES_H <freetype/config/ftmodule.h> +#endif + + /* */ + + /* public headers */ + + /************************************************************************* + * + * @macro: + * FT_FREETYPE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * base FreeType~2 API. + * + */ +#define FT_FREETYPE_H <freetype/freetype.h> + + + /************************************************************************* + * + * @macro: + * FT_ERRORS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * list of FreeType~2 error codes (and messages). + * + * It is included by @FT_FREETYPE_H. + * + */ +#define FT_ERRORS_H <freetype/fterrors.h> + + + /************************************************************************* + * + * @macro: + * FT_MODULE_ERRORS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * list of FreeType~2 module error offsets (and messages). + * + */ +#define FT_MODULE_ERRORS_H <freetype/ftmoderr.h> + + + /************************************************************************* + * + * @macro: + * FT_SYSTEM_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 interface to low-level operations (i.e., memory management + * and stream i/o). + * + * It is included by @FT_FREETYPE_H. + * + */ +#define FT_SYSTEM_H <freetype/ftsystem.h> + + + /************************************************************************* + * + * @macro: + * FT_IMAGE_H + * + * @description: + * A macro used in #include statements to name the file containing type + * definitions related to glyph images (i.e., bitmaps, outlines, + * scan-converter parameters). + * + * It is included by @FT_FREETYPE_H. + * + */ +#define FT_IMAGE_H <freetype/ftimage.h> + + + /************************************************************************* + * + * @macro: + * FT_TYPES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * basic data types defined by FreeType~2. + * + * It is included by @FT_FREETYPE_H. + * + */ +#define FT_TYPES_H <freetype/fttypes.h> + + + /************************************************************************* + * + * @macro: + * FT_LIST_H + * + * @description: + * A macro used in #include statements to name the file containing the + * list management API of FreeType~2. + * + * (Most applications will never need to include this file.) + * + */ +#define FT_LIST_H <freetype/ftlist.h> + + + /************************************************************************* + * + * @macro: + * FT_OUTLINE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * scalable outline management API of FreeType~2. + * + */ +#define FT_OUTLINE_H <freetype/ftoutln.h> + + + /************************************************************************* + * + * @macro: + * FT_SIZES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * API which manages multiple @FT_Size objects per face. + * + */ +#define FT_SIZES_H <freetype/ftsizes.h> + + + /************************************************************************* + * + * @macro: + * FT_MODULE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * module management API of FreeType~2. + * + */ +#define FT_MODULE_H <freetype/ftmodapi.h> + + + /************************************************************************* + * + * @macro: + * FT_RENDER_H + * + * @description: + * A macro used in #include statements to name the file containing the + * renderer module management API of FreeType~2. + * + */ +#define FT_RENDER_H <freetype/ftrender.h> + + + /************************************************************************* + * + * @macro: + * FT_TYPE1_TABLES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * types and API specific to the Type~1 format. + * + */ +#define FT_TYPE1_TABLES_H <freetype/t1tables.h> + + + /************************************************************************* + * + * @macro: + * FT_TRUETYPE_IDS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * enumeration values which identify name strings, languages, encodings, + * etc. This file really contains a _large_ set of constant macro + * definitions, taken from the TrueType and OpenType specifications. + * + */ +#define FT_TRUETYPE_IDS_H <freetype/ttnameid.h> + + + /************************************************************************* + * + * @macro: + * FT_TRUETYPE_TABLES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * types and API specific to the TrueType (as well as OpenType) format. + * + */ +#define FT_TRUETYPE_TABLES_H <freetype/tttables.h> + + + /************************************************************************* + * + * @macro: + * FT_TRUETYPE_TAGS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of TrueType four-byte `tags' which identify blocks in + * SFNT-based font formats (i.e., TrueType and OpenType). + * + */ +#define FT_TRUETYPE_TAGS_H <freetype/tttags.h> + + + /************************************************************************* + * + * @macro: + * FT_BDF_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which accesses BDF-specific strings from a + * face. + * + */ +#define FT_BDF_H <freetype/ftbdf.h> + + + /************************************************************************* + * + * @macro: + * FT_CID_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which access CID font information from a + * face. + * + */ +#define FT_CID_H <freetype/ftcid.h> + + + /************************************************************************* + * + * @macro: + * FT_GZIP_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which supports gzip-compressed files. + * + */ +#define FT_GZIP_H <freetype/ftgzip.h> + + + /************************************************************************* + * + * @macro: + * FT_LZW_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which supports LZW-compressed files. + * + */ +#define FT_LZW_H <freetype/ftlzw.h> + + + /************************************************************************* + * + * @macro: + * FT_BZIP2_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which supports bzip2-compressed files. + * + */ +#define FT_BZIP2_H <freetype/ftbzip2.h> + + + /************************************************************************* + * + * @macro: + * FT_WINFONTS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * definitions of an API which supports Windows FNT files. + * + */ +#define FT_WINFONTS_H <freetype/ftwinfnt.h> + + + /************************************************************************* + * + * @macro: + * FT_GLYPH_H + * + * @description: + * A macro used in #include statements to name the file containing the + * API of the optional glyph management component. + * + */ +#define FT_GLYPH_H <freetype/ftglyph.h> + + + /************************************************************************* + * + * @macro: + * FT_BITMAP_H + * + * @description: + * A macro used in #include statements to name the file containing the + * API of the optional bitmap conversion component. + * + */ +#define FT_BITMAP_H <freetype/ftbitmap.h> + + + /************************************************************************* + * + * @macro: + * FT_BBOX_H + * + * @description: + * A macro used in #include statements to name the file containing the + * API of the optional exact bounding box computation routines. + * + */ +#define FT_BBOX_H <freetype/ftbbox.h> + + + /************************************************************************* + * + * @macro: + * FT_CACHE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * API of the optional FreeType~2 cache sub-system. + * + */ +#define FT_CACHE_H <freetype/ftcache.h> + + + /************************************************************************* + * + * @macro: + * FT_CACHE_IMAGE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * `glyph image' API of the FreeType~2 cache sub-system. + * + * It is used to define a cache for @FT_Glyph elements. You can also + * use the API defined in @FT_CACHE_SMALL_BITMAPS_H if you only need to + * store small glyph bitmaps, as it will use less memory. + * + * This macro is deprecated. Simply include @FT_CACHE_H to have all + * glyph image-related cache declarations. + * + */ +#define FT_CACHE_IMAGE_H FT_CACHE_H + + + /************************************************************************* + * + * @macro: + * FT_CACHE_SMALL_BITMAPS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * `small bitmaps' API of the FreeType~2 cache sub-system. + * + * It is used to define a cache for small glyph bitmaps in a relatively + * memory-efficient way. You can also use the API defined in + * @FT_CACHE_IMAGE_H if you want to cache arbitrary glyph images, + * including scalable outlines. + * + * This macro is deprecated. Simply include @FT_CACHE_H to have all + * small bitmaps-related cache declarations. + * + */ +#define FT_CACHE_SMALL_BITMAPS_H FT_CACHE_H + + + /************************************************************************* + * + * @macro: + * FT_CACHE_CHARMAP_H + * + * @description: + * A macro used in #include statements to name the file containing the + * `charmap' API of the FreeType~2 cache sub-system. + * + * This macro is deprecated. Simply include @FT_CACHE_H to have all + * charmap-based cache declarations. + * + */ +#define FT_CACHE_CHARMAP_H FT_CACHE_H + + + /************************************************************************* + * + * @macro: + * FT_MAC_H + * + * @description: + * A macro used in #include statements to name the file containing the + * Macintosh-specific FreeType~2 API. The latter is used to access + * fonts embedded in resource forks. + * + * This header file must be explicitly included by client applications + * compiled on the Mac (note that the base API still works though). + * + */ +#define FT_MAC_H <freetype/ftmac.h> + + + /************************************************************************* + * + * @macro: + * FT_MULTIPLE_MASTERS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * optional multiple-masters management API of FreeType~2. + * + */ +#define FT_MULTIPLE_MASTERS_H <freetype/ftmm.h> + + + /************************************************************************* + * + * @macro: + * FT_SFNT_NAMES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * optional FreeType~2 API which accesses embedded `name' strings in + * SFNT-based font formats (i.e., TrueType and OpenType). + * + */ +#define FT_SFNT_NAMES_H <freetype/ftsnames.h> + + + /************************************************************************* + * + * @macro: + * FT_OPENTYPE_VALIDATE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * optional FreeType~2 API which validates OpenType tables (BASE, GDEF, + * GPOS, GSUB, JSTF). + * + */ +#define FT_OPENTYPE_VALIDATE_H <freetype/ftotval.h> + + + /************************************************************************* + * + * @macro: + * FT_GX_VALIDATE_H + * + * @description: + * A macro used in #include statements to name the file containing the + * optional FreeType~2 API which validates TrueTypeGX/AAT tables (feat, + * mort, morx, bsln, just, kern, opbd, trak, prop). + * + */ +#define FT_GX_VALIDATE_H <freetype/ftgxval.h> + + + /************************************************************************* + * + * @macro: + * FT_PFR_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which accesses PFR-specific data. + * + */ +#define FT_PFR_H <freetype/ftpfr.h> + + + /************************************************************************* + * + * @macro: + * FT_STROKER_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which provides functions to stroke outline paths. + */ +#define FT_STROKER_H <freetype/ftstroke.h> + + + /************************************************************************* + * + * @macro: + * FT_SYNTHESIS_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which performs artificial obliquing and emboldening. + */ +#define FT_SYNTHESIS_H <freetype/ftsynth.h> + + + /************************************************************************* + * + * @macro: + * FT_XFREE86_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which provides functions specific to the XFree86 and + * X.Org X11 servers. + */ +#define FT_XFREE86_H <freetype/ftxf86.h> + + + /************************************************************************* + * + * @macro: + * FT_TRIGONOMETRY_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which performs trigonometric computations (e.g., + * cosines and arc tangents). + */ +#define FT_TRIGONOMETRY_H <freetype/fttrigon.h> + + + /************************************************************************* + * + * @macro: + * FT_LCD_FILTER_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which performs color filtering for subpixel rendering. + */ +#define FT_LCD_FILTER_H <freetype/ftlcdfil.h> + + + /************************************************************************* + * + * @macro: + * FT_UNPATENTED_HINTING_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which performs color filtering for subpixel rendering. + */ +#define FT_UNPATENTED_HINTING_H <freetype/ttunpat.h> + + + /************************************************************************* + * + * @macro: + * FT_INCREMENTAL_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which performs color filtering for subpixel rendering. + */ +#define FT_INCREMENTAL_H <freetype/ftincrem.h> + + + /************************************************************************* + * + * @macro: + * FT_GASP_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which returns entries from the TrueType GASP table. + */ +#define FT_GASP_H <freetype/ftgasp.h> + + + /************************************************************************* + * + * @macro: + * FT_ADVANCES_H + * + * @description: + * A macro used in #include statements to name the file containing the + * FreeType~2 API which returns individual and ranged glyph advances. + */ +#define FT_ADVANCES_H <freetype/ftadvanc.h> + + + /* */ + +#define FT_ERROR_DEFINITIONS_H <freetype/fterrdef.h> + + + /* The internals of the cache sub-system are no longer exposed. We */ + /* default to FT_CACHE_H at the moment just in case, but we know of */ + /* no rogue client that uses them. */ + /* */ +#define FT_CACHE_MANAGER_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_MRU_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_MANAGER_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_CACHE_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_GLYPH_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_IMAGE_H <freetype/ftcache.h> +#define FT_CACHE_INTERNAL_SBITS_H <freetype/ftcache.h> + + +#define FT_INCREMENTAL_H <freetype/ftincrem.h> + +#define FT_TRUETYPE_UNPATENTED_H <freetype/ttunpat.h> + + + /* + * Include internal headers definitions from <freetype/internal/...> + * only when building the library. + */ +#ifdef FT2_BUILD_LIBRARY +#define FT_INTERNAL_INTERNAL_H <freetype/internal/internal.h> +#include FT_INTERNAL_INTERNAL_H +#endif /* FT2_BUILD_LIBRARY */ + + +#endif /* __FT2_BUILD_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/config/ftmodule.h b/other/freetype/include/freetype/config/ftmodule.h new file mode 100644 index 0000000..76d271a --- /dev/null +++ b/other/freetype/include/freetype/config/ftmodule.h @@ -0,0 +1,32 @@ +/* + * This file registers the FreeType modules compiled into the library. + * + * If you use GNU make, this file IS NOT USED! Instead, it is created in + * the objects directory (normally `<topdir>/objs/') based on information + * from `<topdir>/modules.cfg'. + * + * Please read `docs/INSTALL.ANY' and `docs/CUSTOMIZE' how to compile + * FreeType without GNU make. + * + */ + +FT_USE_MODULE( FT_Module_Class, autofit_module_class ) +FT_USE_MODULE( FT_Driver_ClassRec, tt_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, t1_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, cff_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, t1cid_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, pfr_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, t42_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, winfnt_driver_class ) +FT_USE_MODULE( FT_Driver_ClassRec, pcf_driver_class ) +FT_USE_MODULE( FT_Module_Class, psaux_module_class ) +FT_USE_MODULE( FT_Module_Class, psnames_module_class ) +FT_USE_MODULE( FT_Module_Class, pshinter_module_class ) +FT_USE_MODULE( FT_Renderer_Class, ft_raster1_renderer_class ) +FT_USE_MODULE( FT_Module_Class, sfnt_module_class ) +FT_USE_MODULE( FT_Renderer_Class, ft_smooth_renderer_class ) +FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcd_renderer_class ) +FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcdv_renderer_class ) +FT_USE_MODULE( FT_Driver_ClassRec, bdf_driver_class ) + +/* EOF */ diff --git a/other/freetype/include/freetype/config/ftoption.h b/other/freetype/include/freetype/config/ftoption.h new file mode 100644 index 0000000..250c95d --- /dev/null +++ b/other/freetype/include/freetype/config/ftoption.h @@ -0,0 +1,807 @@ +/***************************************************************************/ +/* */ +/* ftoption.h */ +/* */ +/* User-selectable configuration macros (specification only). */ +/* */ +/* Copyright 1996-2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTOPTION_H__ +#define __FTOPTION_H__ + + +#include <ft2build.h> + + +FT_BEGIN_HEADER + + /*************************************************************************/ + /* */ + /* USER-SELECTABLE CONFIGURATION MACROS */ + /* */ + /* This file contains the default configuration macro definitions for */ + /* a standard build of the FreeType library. There are three ways to */ + /* use this file to build project-specific versions of the library: */ + /* */ + /* - You can modify this file by hand, but this is not recommended in */ + /* cases where you would like to build several versions of the */ + /* library from a single source directory. */ + /* */ + /* - You can put a copy of this file in your build directory, more */ + /* precisely in `$BUILD/freetype/config/ftoption.h', where `$BUILD' */ + /* is the name of a directory that is included _before_ the FreeType */ + /* include path during compilation. */ + /* */ + /* The default FreeType Makefiles and Jamfiles use the build */ + /* directory `builds/<system>' by default, but you can easily change */ + /* that for your own projects. */ + /* */ + /* - Copy the file <ft2build.h> to `$BUILD/ft2build.h' and modify it */ + /* slightly to pre-define the macro FT_CONFIG_OPTIONS_H used to */ + /* locate this file during the build. For example, */ + /* */ + /* #define FT_CONFIG_OPTIONS_H <myftoptions.h> */ + /* #include <freetype/config/ftheader.h> */ + /* */ + /* will use `$BUILD/myftoptions.h' instead of this file for macro */ + /* definitions. */ + /* */ + /* Note also that you can similarly pre-define the macro */ + /* FT_CONFIG_MODULES_H used to locate the file listing of the modules */ + /* that are statically linked to the library at compile time. By */ + /* default, this file is <freetype/config/ftmodule.h>. */ + /* */ + /* We highly recommend using the third method whenever possible. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** G E N E R A L F R E E T Y P E 2 C O N F I G U R A T I O N ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* Uncomment the line below if you want to activate sub-pixel rendering */ + /* (a.k.a. LCD rendering, or ClearType) in this build of the library. */ + /* */ + /* Note that this feature is covered by several Microsoft patents */ + /* and should not be activated in any default build of the library. */ + /* */ + /* This macro has no impact on the FreeType API, only on its */ + /* _implementation_. For example, using FT_RENDER_MODE_LCD when calling */ + /* FT_Render_Glyph still generates a bitmap that is 3 times wider than */ + /* the original size in case this macro isn't defined; however, each */ + /* triplet of subpixels has R=G=B. */ + /* */ + /* This is done to allow FreeType clients to run unmodified, forcing */ + /* them to display normal gray-level anti-aliased glyphs. */ + /* */ +/* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ + + + /*************************************************************************/ + /* */ + /* Many compilers provide a non-ANSI 64-bit data type that can be used */ + /* by FreeType to speed up some computations. However, this will create */ + /* some problems when compiling the library in strict ANSI mode. */ + /* */ + /* For this reason, the use of 64-bit integers is normally disabled when */ + /* the __STDC__ macro is defined. You can however disable this by */ + /* defining the macro FT_CONFIG_OPTION_FORCE_INT64 here. */ + /* */ + /* For most compilers, this will only create compilation warnings when */ + /* building the library. */ + /* */ + /* ObNote: The compiler-specific 64-bit integers are detected in the */ + /* file `ftconfig.h' either statically or through the */ + /* `configure' script on supported platforms. */ + /* */ +#undef FT_CONFIG_OPTION_FORCE_INT64 + + + /*************************************************************************/ + /* */ + /* If this macro is defined, do not try to use an assembler version of */ + /* performance-critical functions (e.g. FT_MulFix). You should only do */ + /* that to verify that the assembler function works properly, or to */ + /* execute benchmark tests of the various implementations. */ +/* #define FT_CONFIG_OPTION_NO_ASSEMBLER */ + + + /*************************************************************************/ + /* */ + /* If this macro is defined, try to use an inlined assembler version of */ + /* the `FT_MulFix' function, which is a `hotspot' when loading and */ + /* hinting glyphs, and which should be executed as fast as possible. */ + /* */ + /* Note that if your compiler or CPU is not supported, this will default */ + /* to the standard and portable implementation found in `ftcalc.c'. */ + /* */ +#define FT_CONFIG_OPTION_INLINE_MULFIX + + + /*************************************************************************/ + /* */ + /* LZW-compressed file support. */ + /* */ + /* FreeType now handles font files that have been compressed with the */ + /* `compress' program. This is mostly used to parse many of the PCF */ + /* files that come with various X11 distributions. The implementation */ + /* uses NetBSD's `zopen' to partially uncompress the file on the fly */ + /* (see src/lzw/ftgzip.c). */ + /* */ + /* Define this macro if you want to enable this `feature'. */ + /* */ +#define FT_CONFIG_OPTION_USE_LZW + + + /*************************************************************************/ + /* */ + /* Gzip-compressed file support. */ + /* */ + /* FreeType now handles font files that have been compressed with the */ + /* `gzip' program. This is mostly used to parse many of the PCF files */ + /* that come with XFree86. The implementation uses `zlib' to */ + /* partially uncompress the file on the fly (see src/gzip/ftgzip.c). */ + /* */ + /* Define this macro if you want to enable this `feature'. See also */ + /* the macro FT_CONFIG_OPTION_SYSTEM_ZLIB below. */ + /* */ +#define FT_CONFIG_OPTION_USE_ZLIB + + + /*************************************************************************/ + /* */ + /* ZLib library selection */ + /* */ + /* This macro is only used when FT_CONFIG_OPTION_USE_ZLIB is defined. */ + /* It allows FreeType's `ftgzip' component to link to the system's */ + /* installation of the ZLib library. This is useful on systems like */ + /* Unix or VMS where it generally is already available. */ + /* */ + /* If you let it undefined, the component will use its own copy */ + /* of the zlib sources instead. These have been modified to be */ + /* included directly within the component and *not* export external */ + /* function names. This allows you to link any program with FreeType */ + /* _and_ ZLib without linking conflicts. */ + /* */ + /* Do not #undef this macro here since the build system might define */ + /* it for certain configurations only. */ + /* */ +/* #define FT_CONFIG_OPTION_SYSTEM_ZLIB */ + + + /*************************************************************************/ + /* */ + /* Bzip2-compressed file support. */ + /* */ + /* FreeType now handles font files that have been compressed with the */ + /* `bzip2' program. This is mostly used to parse many of the PCF */ + /* files that come with XFree86. The implementation uses `libbz2' to */ + /* partially uncompress the file on the fly (see src/bzip2/ftbzip2.c). */ + /* Contrary to gzip, bzip2 currently is not included and need to use */ + /* the system available bzip2 implementation. */ + /* */ + /* Define this macro if you want to enable this `feature'. */ + /* */ +/* #define FT_CONFIG_OPTION_USE_BZIP2 */ + + + /*************************************************************************/ + /* */ + /* Define to disable the use of file stream functions and types, FILE, */ + /* fopen() etc. Enables the use of smaller system libraries on embedded */ + /* systems that have multiple system libraries, some with or without */ + /* file stream support, in the cases where file stream support is not */ + /* necessary such as memory loading of font files. */ + /* */ +/* #define FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */ + + + /*************************************************************************/ + /* */ + /* DLL export compilation */ + /* */ + /* When compiling FreeType as a DLL, some systems/compilers need a */ + /* special keyword in front OR after the return type of function */ + /* declarations. */ + /* */ + /* Two macros are used within the FreeType source code to define */ + /* exported library functions: FT_EXPORT and FT_EXPORT_DEF. */ + /* */ + /* FT_EXPORT( return_type ) */ + /* */ + /* is used in a function declaration, as in */ + /* */ + /* FT_EXPORT( FT_Error ) */ + /* FT_Init_FreeType( FT_Library* alibrary ); */ + /* */ + /* */ + /* FT_EXPORT_DEF( return_type ) */ + /* */ + /* is used in a function definition, as in */ + /* */ + /* FT_EXPORT_DEF( FT_Error ) */ + /* FT_Init_FreeType( FT_Library* alibrary ) */ + /* { */ + /* ... some code ... */ + /* return FT_Err_Ok; */ + /* } */ + /* */ + /* You can provide your own implementation of FT_EXPORT and */ + /* FT_EXPORT_DEF here if you want. If you leave them undefined, they */ + /* will be later automatically defined as `extern return_type' to */ + /* allow normal compilation. */ + /* */ + /* Do not #undef these macros here since the build system might define */ + /* them for certain configurations only. */ + /* */ +/* #define FT_EXPORT(x) extern x */ +/* #define FT_EXPORT_DEF(x) x */ +#define FT_EXPORT(x) __declspec(dllexport) x +#define FT_EXPORT_DEF(x) __declspec(dllexport) x + + + /*************************************************************************/ + /* */ + /* Glyph Postscript Names handling */ + /* */ + /* By default, FreeType 2 is compiled with the `psnames' module. This */ + /* module is in charge of converting a glyph name string into a */ + /* Unicode value, or return a Macintosh standard glyph name for the */ + /* use with the TrueType `post' table. */ + /* */ + /* Undefine this macro if you do not want `psnames' compiled in your */ + /* build of FreeType. This has the following effects: */ + /* */ + /* - The TrueType driver will provide its own set of glyph names, */ + /* if you build it to support postscript names in the TrueType */ + /* `post' table. */ + /* */ + /* - The Type 1 driver will not be able to synthesize a Unicode */ + /* charmap out of the glyphs found in the fonts. */ + /* */ + /* You would normally undefine this configuration macro when building */ + /* a version of FreeType that doesn't contain a Type 1 or CFF driver. */ + /* */ +#define FT_CONFIG_OPTION_POSTSCRIPT_NAMES + + + /*************************************************************************/ + /* */ + /* Postscript Names to Unicode Values support */ + /* */ + /* By default, FreeType 2 is built with the `PSNames' module compiled */ + /* in. Among other things, the module is used to convert a glyph name */ + /* into a Unicode value. This is especially useful in order to */ + /* synthesize on the fly a Unicode charmap from the CFF/Type 1 driver */ + /* through a big table named the `Adobe Glyph List' (AGL). */ + /* */ + /* Undefine this macro if you do not want the Adobe Glyph List */ + /* compiled in your `PSNames' module. The Type 1 driver will not be */ + /* able to synthesize a Unicode charmap out of the glyphs found in the */ + /* fonts. */ + /* */ +#define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST + + + /*************************************************************************/ + /* */ + /* Support for Mac fonts */ + /* */ + /* Define this macro if you want support for outline fonts in Mac */ + /* format (mac dfont, mac resource, macbinary containing a mac */ + /* resource) on non-Mac platforms. */ + /* */ + /* Note that the `FOND' resource isn't checked. */ + /* */ +#define FT_CONFIG_OPTION_MAC_FONTS + + + /*************************************************************************/ + /* */ + /* Guessing methods to access embedded resource forks */ + /* */ + /* Enable extra Mac fonts support on non-Mac platforms (e.g. */ + /* GNU/Linux). */ + /* */ + /* Resource forks which include fonts data are stored sometimes in */ + /* locations which users or developers don't expected. In some cases, */ + /* resource forks start with some offset from the head of a file. In */ + /* other cases, the actual resource fork is stored in file different */ + /* from what the user specifies. If this option is activated, */ + /* FreeType tries to guess whether such offsets or different file */ + /* names must be used. */ + /* */ + /* Note that normal, direct access of resource forks is controlled via */ + /* the FT_CONFIG_OPTION_MAC_FONTS option. */ + /* */ +#ifdef FT_CONFIG_OPTION_MAC_FONTS +#define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK +#endif + + + /*************************************************************************/ + /* */ + /* Allow the use of FT_Incremental_Interface to load typefaces that */ + /* contain no glyph data, but supply it via a callback function. */ + /* This is required by clients supporting document formats which */ + /* supply font data incrementally as the document is parsed, such */ + /* as the Ghostscript interpreter for the PostScript language. */ + /* */ +#define FT_CONFIG_OPTION_INCREMENTAL + + + /*************************************************************************/ + /* */ + /* The size in bytes of the render pool used by the scan-line converter */ + /* to do all of its work. */ + /* */ + /* This must be greater than 4KByte if you use FreeType to rasterize */ + /* glyphs; otherwise, you may set it to zero to avoid unnecessary */ + /* allocation of the render pool. */ + /* */ +#define FT_RENDER_POOL_SIZE 16384L + + + /*************************************************************************/ + /* */ + /* FT_MAX_MODULES */ + /* */ + /* The maximum number of modules that can be registered in a single */ + /* FreeType library object. 32 is the default. */ + /* */ +#define FT_MAX_MODULES 32 + + + /*************************************************************************/ + /* */ + /* Debug level */ + /* */ + /* FreeType can be compiled in debug or trace mode. In debug mode, */ + /* errors are reported through the `ftdebug' component. In trace */ + /* mode, additional messages are sent to the standard output during */ + /* execution. */ + /* */ + /* Define FT_DEBUG_LEVEL_ERROR to build the library in debug mode. */ + /* Define FT_DEBUG_LEVEL_TRACE to build it in trace mode. */ + /* */ + /* Don't define any of these macros to compile in `release' mode! */ + /* */ + /* Do not #undef these macros here since the build system might define */ + /* them for certain configurations only. */ + /* */ +/* #define FT_DEBUG_LEVEL_ERROR */ +/* #define FT_DEBUG_LEVEL_TRACE */ + + + /*************************************************************************/ + /* */ + /* Autofitter debugging */ + /* */ + /* If FT_DEBUG_AUTOFIT is defined, FreeType provides some means to */ + /* control the autofitter behaviour for debugging purposes with global */ + /* boolean variables (consequently, you should *never* enable this */ + /* while compiling in `release' mode): */ + /* */ + /* _af_debug_disable_horz_hints */ + /* _af_debug_disable_vert_hints */ + /* _af_debug_disable_blue_hints */ + /* */ + /* Additionally, the following functions provide dumps of various */ + /* internal autofit structures to stdout (using `printf'): */ + /* */ + /* af_glyph_hints_dump_points */ + /* af_glyph_hints_dump_segments */ + /* af_glyph_hints_dump_edges */ + /* */ + /* As an argument, they use another global variable: */ + /* */ + /* _af_debug_hints */ + /* */ + /* Please have a look at the `ftgrid' demo program to see how those */ + /* variables and macros should be used. */ + /* */ + /* Do not #undef these macros here since the build system might define */ + /* them for certain configurations only. */ + /* */ +/* #define FT_DEBUG_AUTOFIT */ + + + /*************************************************************************/ + /* */ + /* Memory Debugging */ + /* */ + /* FreeType now comes with an integrated memory debugger that is */ + /* capable of detecting simple errors like memory leaks or double */ + /* deletes. To compile it within your build of the library, you */ + /* should define FT_DEBUG_MEMORY here. */ + /* */ + /* Note that the memory debugger is only activated at runtime when */ + /* when the _environment_ variable `FT2_DEBUG_MEMORY' is defined also! */ + /* */ + /* Do not #undef this macro here since the build system might define */ + /* it for certain configurations only. */ + /* */ +/* #define FT_DEBUG_MEMORY */ + + + /*************************************************************************/ + /* */ + /* Module errors */ + /* */ + /* If this macro is set (which is _not_ the default), the higher byte */ + /* of an error code gives the module in which the error has occurred, */ + /* while the lower byte is the real error code. */ + /* */ + /* Setting this macro makes sense for debugging purposes only, since */ + /* it would break source compatibility of certain programs that use */ + /* FreeType 2. */ + /* */ + /* More details can be found in the files ftmoderr.h and fterrors.h. */ + /* */ +#undef FT_CONFIG_OPTION_USE_MODULE_ERRORS + + + /*************************************************************************/ + /* */ + /* Position Independent Code */ + /* */ + /* If this macro is set (which is _not_ the default), FreeType2 will */ + /* avoid creating constants that require address fixups. Instead the */ + /* constants will be moved into a struct and additional intialization */ + /* code will be used. */ + /* */ + /* Setting this macro is needed for systems that prohibit address */ + /* fixups, such as BREW. */ + /* */ +/* #define FT_CONFIG_OPTION_PIC */ + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** S F N T D R I V E R C O N F I G U R A T I O N ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_EMBEDDED_BITMAPS if you want to support */ + /* embedded bitmaps in all formats using the SFNT module (namely */ + /* TrueType & OpenType). */ + /* */ +#define TT_CONFIG_OPTION_EMBEDDED_BITMAPS + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_POSTSCRIPT_NAMES if you want to be able to */ + /* load and enumerate the glyph Postscript names in a TrueType or */ + /* OpenType file. */ + /* */ + /* Note that when you do not compile the `PSNames' module by undefining */ + /* the above FT_CONFIG_OPTION_POSTSCRIPT_NAMES, the `sfnt' module will */ + /* contain additional code used to read the PS Names table from a font. */ + /* */ + /* (By default, the module uses `PSNames' to extract glyph names.) */ + /* */ +#define TT_CONFIG_OPTION_POSTSCRIPT_NAMES + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_SFNT_NAMES if your applications need to */ + /* access the internal name table in a SFNT-based format like TrueType */ + /* or OpenType. The name table contains various strings used to */ + /* describe the font, like family name, copyright, version, etc. It */ + /* does not contain any glyph name though. */ + /* */ + /* Accessing SFNT names is done through the functions declared in */ + /* `freetype/ftsnames.h'. */ + /* */ +#define TT_CONFIG_OPTION_SFNT_NAMES + + + /*************************************************************************/ + /* */ + /* TrueType CMap support */ + /* */ + /* Here you can fine-tune which TrueType CMap table format shall be */ + /* supported. */ +#define TT_CONFIG_CMAP_FORMAT_0 +#define TT_CONFIG_CMAP_FORMAT_2 +#define TT_CONFIG_CMAP_FORMAT_4 +#define TT_CONFIG_CMAP_FORMAT_6 +#define TT_CONFIG_CMAP_FORMAT_8 +#define TT_CONFIG_CMAP_FORMAT_10 +#define TT_CONFIG_CMAP_FORMAT_12 +#define TT_CONFIG_CMAP_FORMAT_13 +#define TT_CONFIG_CMAP_FORMAT_14 + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** T R U E T Y P E D R I V E R C O N F I G U R A T I O N ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_BYTECODE_INTERPRETER if you want to compile */ + /* a bytecode interpreter in the TrueType driver. */ + /* */ + /* By undefining this, you will only compile the code necessary to load */ + /* TrueType glyphs without hinting. */ + /* */ + /* Do not #undef this macro here, since the build system might */ + /* define it for certain configurations only. */ + /* */ +#define TT_CONFIG_OPTION_BYTECODE_INTERPRETER + + + /*************************************************************************/ + /* */ + /* If you define TT_CONFIG_OPTION_UNPATENTED_HINTING, a special version */ + /* of the TrueType bytecode interpreter is used that doesn't implement */ + /* any of the patented opcodes and algorithms. The patents related to */ + /* TrueType hinting have expired worldwide since May 2010; this option */ + /* is now deprecated. */ + /* */ + /* Note that the TT_CONFIG_OPTION_UNPATENTED_HINTING macro is *ignored* */ + /* if you define TT_CONFIG_OPTION_BYTECODE_INTERPRETER; in other words, */ + /* either define TT_CONFIG_OPTION_BYTECODE_INTERPRETER or */ + /* TT_CONFIG_OPTION_UNPATENTED_HINTING but not both at the same time. */ + /* */ + /* This macro is only useful for a small number of font files (mostly */ + /* for Asian scripts) that require bytecode interpretation to properly */ + /* load glyphs. For all other fonts, this produces unpleasant results, */ + /* thus the unpatented interpreter is never used to load glyphs from */ + /* TrueType fonts unless one of the following two options is used. */ + /* */ + /* - The unpatented interpreter is explicitly activated by the user */ + /* through the FT_PARAM_TAG_UNPATENTED_HINTING parameter tag */ + /* when opening the FT_Face. */ + /* */ + /* - FreeType detects that the FT_Face corresponds to one of the */ + /* `trick' fonts (e.g., `Mingliu') it knows about. The font engine */ + /* contains a hard-coded list of font names and other matching */ + /* parameters (see function `tt_face_init' in file */ + /* `src/truetype/ttobjs.c'). */ + /* */ + /* Here a sample code snippet for using FT_PARAM_TAG_UNPATENTED_HINTING. */ + /* */ + /* { */ + /* FT_Parameter parameter; */ + /* FT_Open_Args open_args; */ + /* */ + /* */ + /* parameter.tag = FT_PARAM_TAG_UNPATENTED_HINTING; */ + /* */ + /* open_args.flags = FT_OPEN_PATHNAME | FT_OPEN_PARAMS; */ + /* open_args.pathname = my_font_pathname; */ + /* open_args.num_params = 1; */ + /* open_args.params = ¶meter; */ + /* */ + /* error = FT_Open_Face( library, &open_args, index, &face ); */ + /* ... */ + /* } */ + /* */ +/* #define TT_CONFIG_OPTION_UNPATENTED_HINTING */ + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_INTERPRETER_SWITCH to compile the TrueType */ + /* bytecode interpreter with a huge switch statement, rather than a call */ + /* table. This results in smaller and faster code for a number of */ + /* architectures. */ + /* */ + /* Note however that on some compiler/processor combinations, undefining */ + /* this macro will generate faster, though larger, code. */ + /* */ +#define TT_CONFIG_OPTION_INTERPRETER_SWITCH + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED to compile the */ + /* TrueType glyph loader to use Apple's definition of how to handle */ + /* component offsets in composite glyphs. */ + /* */ + /* Apple and MS disagree on the default behavior of component offsets */ + /* in composites. Apple says that they should be scaled by the scaling */ + /* factors in the transformation matrix (roughly, it's more complex) */ + /* while MS says they should not. OpenType defines two bits in the */ + /* composite flags array which can be used to disambiguate, but old */ + /* fonts will not have them. */ + /* */ + /* http://www.microsoft.com/typography/otspec/glyf.htm */ + /* http://fonts.apple.com/TTRefMan/RM06/Chap6glyf.html */ + /* */ +#undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_GX_VAR_SUPPORT if you want to include */ + /* support for Apple's distortable font technology (fvar, gvar, cvar, */ + /* and avar tables). This has many similarities to Type 1 Multiple */ + /* Masters support. */ + /* */ +#define TT_CONFIG_OPTION_GX_VAR_SUPPORT + + + /*************************************************************************/ + /* */ + /* Define TT_CONFIG_OPTION_BDF if you want to include support for */ + /* an embedded `BDF ' table within SFNT-based bitmap formats. */ + /* */ +#define TT_CONFIG_OPTION_BDF + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** T Y P E 1 D R I V E R C O N F I G U R A T I O N ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* T1_MAX_DICT_DEPTH is the maximal depth of nest dictionaries and */ + /* arrays in the Type 1 stream (see t1load.c). A minimum of 4 is */ + /* required. */ + /* */ +#define T1_MAX_DICT_DEPTH 5 + + + /*************************************************************************/ + /* */ + /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine */ + /* calls during glyph loading. */ + /* */ +#define T1_MAX_SUBRS_CALLS 16 + + + /*************************************************************************/ + /* */ + /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity. A */ + /* minimum of 16 is required. */ + /* */ + /* The Chinese font MingTiEG-Medium (CNS 11643 character set) needs 256. */ + /* */ +#define T1_MAX_CHARSTRINGS_OPERANDS 256 + + + /*************************************************************************/ + /* */ + /* Define this configuration macro if you want to prevent the */ + /* compilation of `t1afm', which is in charge of reading Type 1 AFM */ + /* files into an existing face. Note that if set, the T1 driver will be */ + /* unable to produce kerning distances. */ + /* */ +#undef T1_CONFIG_OPTION_NO_AFM + + + /*************************************************************************/ + /* */ + /* Define this configuration macro if you want to prevent the */ + /* compilation of the Multiple Masters font support in the Type 1 */ + /* driver. */ + /* */ +#undef T1_CONFIG_OPTION_NO_MM_SUPPORT + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** A U T O F I T M O D U L E C O N F I G U R A T I O N ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* Compile autofit module with CJK (Chinese, Japanese, Korean) script */ + /* support. */ + /* */ +#define AF_CONFIG_OPTION_CJK + + /*************************************************************************/ + /* */ + /* Compile autofit module with Indic script support. */ + /* */ +#define AF_CONFIG_OPTION_INDIC + + /*************************************************************************/ + /* */ + /* Compile autofit module with warp hinting. The idea of the warping */ + /* code is to slightly scale and shift a glyph within a single dimension */ + /* so that as much of its segments are aligned (more or less) on the */ + /* grid. To find out the optimal scaling and shifting value, various */ + /* parameter combinations are tried and scored. */ + /* */ + /* This experimental option is only active if the render mode is */ + /* FT_RENDER_MODE_LIGHT. */ + /* */ +/* #define AF_CONFIG_OPTION_USE_WARPER */ + + /* */ + + + /* + * Define this variable if you want to keep the layout of internal + * structures that was used prior to FreeType 2.2. This also compiles in + * a few obsolete functions to avoid linking problems on typical Unix + * distributions. + * + * For embedded systems or building a new distribution from scratch, it + * is recommended to disable the macro since it reduces the library's code + * size and activates a few memory-saving optimizations as well. + */ +#define FT_CONFIG_OPTION_OLD_INTERNALS + + + /* + * To detect legacy cache-lookup call from a rogue client (<= 2.1.7), + * we restrict the number of charmaps in a font. The current API of + * FTC_CMapCache_Lookup() takes cmap_index & charcode, but old API + * takes charcode only. To determine the passed value is for cmap_index + * or charcode, the possible cmap_index is restricted not to exceed + * the minimum possible charcode by a rogue client. It is also very + * unlikely that a rogue client is interested in Unicode values 0 to 15. + * + * NOTE: The original threshold was 4 deduced from popular number of + * cmap subtables in UCS-4 TrueType fonts, but now it is not + * irregular for OpenType fonts to have more than 4 subtables, + * because variation selector subtables are available for Apple + * and Microsoft platforms. + */ + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS +#define FT_MAX_CHARMAP_CACHEABLE 15 +#endif + + + /* + * This macro is defined if either unpatented or native TrueType + * hinting is requested by the definitions above. + */ +#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER +#define TT_USE_BYTECODE_INTERPRETER +#undef TT_CONFIG_OPTION_UNPATENTED_HINTING +#elif defined TT_CONFIG_OPTION_UNPATENTED_HINTING +#define TT_USE_BYTECODE_INTERPRETER +#endif + +FT_END_HEADER + + +#endif /* __FTOPTION_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/config/ftstdlib.h b/other/freetype/include/freetype/config/ftstdlib.h new file mode 100644 index 0000000..11d5d0e --- /dev/null +++ b/other/freetype/include/freetype/config/ftstdlib.h @@ -0,0 +1,174 @@ +/***************************************************************************/ +/* */ +/* ftstdlib.h */ +/* */ +/* ANSI-specific library and header configuration file (specification */ +/* only). */ +/* */ +/* Copyright 2002-2007, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file is used to group all #includes to the ANSI C library that */ + /* FreeType normally requires. It also defines macros to rename the */ + /* standard functions within the FreeType source code. */ + /* */ + /* Load a file which defines __FTSTDLIB_H__ before this one to override */ + /* it. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTSTDLIB_H__ +#define __FTSTDLIB_H__ + + +#include <stddef.h> + +#define ft_ptrdiff_t ptrdiff_t + + + /**********************************************************************/ + /* */ + /* integer limits */ + /* */ + /* UINT_MAX and ULONG_MAX are used to automatically compute the size */ + /* of `int' and `long' in bytes at compile-time. So far, this works */ + /* for all platforms the library has been tested on. */ + /* */ + /* Note that on the extremely rare platforms that do not provide */ + /* integer types that are _exactly_ 16 and 32 bits wide (e.g. some */ + /* old Crays where `int' is 36 bits), we do not make any guarantee */ + /* about the correct behaviour of FT2 with all fonts. */ + /* */ + /* In these case, `ftconfig.h' will refuse to compile anyway with a */ + /* message like `couldn't find 32-bit type' or something similar. */ + /* */ + /**********************************************************************/ + + +#include <limits.h> + +#define FT_CHAR_BIT CHAR_BIT +#define FT_USHORT_MAX USHRT_MAX +#define FT_INT_MAX INT_MAX +#define FT_INT_MIN INT_MIN +#define FT_UINT_MAX UINT_MAX +#define FT_ULONG_MAX ULONG_MAX + + + /**********************************************************************/ + /* */ + /* character and string processing */ + /* */ + /**********************************************************************/ + + +#include <string.h> + +#define ft_memchr memchr +#define ft_memcmp memcmp +#define ft_memcpy memcpy +#define ft_memmove memmove +#define ft_memset memset +#define ft_strcat strcat +#define ft_strcmp strcmp +#define ft_strcpy strcpy +#define ft_strlen strlen +#define ft_strncmp strncmp +#define ft_strncpy strncpy +#define ft_strrchr strrchr +#define ft_strstr strstr + + + /**********************************************************************/ + /* */ + /* file handling */ + /* */ + /**********************************************************************/ + + +#include <stdio.h> + +#define FT_FILE FILE +#define ft_fclose fclose +#define ft_fopen fopen +#define ft_fread fread +#define ft_fseek fseek +#define ft_ftell ftell +#define ft_sprintf sprintf + + + /**********************************************************************/ + /* */ + /* sorting */ + /* */ + /**********************************************************************/ + + +#include <stdlib.h> + +#define ft_qsort qsort + + + /**********************************************************************/ + /* */ + /* memory allocation */ + /* */ + /**********************************************************************/ + + +#define ft_scalloc calloc +#define ft_sfree free +#define ft_smalloc malloc +#define ft_srealloc realloc + + + /**********************************************************************/ + /* */ + /* miscellaneous */ + /* */ + /**********************************************************************/ + + +#define ft_atol atol +#define ft_labs labs + + + /**********************************************************************/ + /* */ + /* execution control */ + /* */ + /**********************************************************************/ + + +#include <setjmp.h> + +#define ft_jmp_buf jmp_buf /* note: this cannot be a typedef since */ + /* jmp_buf is defined as a macro */ + /* on certain platforms */ + +#define ft_longjmp longjmp +#define ft_setjmp( b ) setjmp( *(jmp_buf*) &(b) ) /* same thing here */ + + + /* the following is only used for debugging purposes, i.e., if */ + /* FT_DEBUG_LEVEL_ERROR or FT_DEBUG_LEVEL_TRACE are defined */ + +#include <stdarg.h> + + +#endif /* __FTSTDLIB_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/freetype.h b/other/freetype/include/freetype/freetype.h new file mode 100644 index 0000000..f1f55f0 --- /dev/null +++ b/other/freetype/include/freetype/freetype.h @@ -0,0 +1,3921 @@ +/***************************************************************************/ +/* */ +/* freetype.h */ +/* */ +/* FreeType high-level API and common types (specification only). */ +/* */ +/* Copyright 1996-2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef FT_FREETYPE_H +#error "`ft2build.h' hasn't been included yet!" +#error "Please always use macros to include FreeType header files." +#error "Example:" +#error " #include <ft2build.h>" +#error " #include FT_FREETYPE_H" +#endif + + +#ifndef __FREETYPE_H__ +#define __FREETYPE_H__ + + +#include <ft2build.h> +#include FT_CONFIG_CONFIG_H +#include FT_ERRORS_H +#include FT_TYPES_H + + +FT_BEGIN_HEADER + + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* user_allocation */ + /* */ + /* <Title> */ + /* User allocation */ + /* */ + /* <Abstract> */ + /* How client applications should allocate FreeType data structures. */ + /* */ + /* <Description> */ + /* FreeType assumes that structures allocated by the user and passed */ + /* as arguments are zeroed out except for the actual data. In other */ + /* words, it is recommended to use `calloc' (or variants of it) */ + /* instead of `malloc' for allocation. */ + /* */ + /*************************************************************************/ + + + + /*************************************************************************/ + /*************************************************************************/ + /* */ + /* B A S I C T Y P E S */ + /* */ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* base_interface */ + /* */ + /* <Title> */ + /* Base Interface */ + /* */ + /* <Abstract> */ + /* The FreeType~2 base font interface. */ + /* */ + /* <Description> */ + /* This section describes the public high-level API of FreeType~2. */ + /* */ + /* <Order> */ + /* FT_Library */ + /* FT_Face */ + /* FT_Size */ + /* FT_GlyphSlot */ + /* FT_CharMap */ + /* FT_Encoding */ + /* */ + /* FT_FaceRec */ + /* */ + /* FT_FACE_FLAG_SCALABLE */ + /* FT_FACE_FLAG_FIXED_SIZES */ + /* FT_FACE_FLAG_FIXED_WIDTH */ + /* FT_FACE_FLAG_HORIZONTAL */ + /* FT_FACE_FLAG_VERTICAL */ + /* FT_FACE_FLAG_SFNT */ + /* FT_FACE_FLAG_KERNING */ + /* FT_FACE_FLAG_MULTIPLE_MASTERS */ + /* FT_FACE_FLAG_GLYPH_NAMES */ + /* FT_FACE_FLAG_EXTERNAL_STREAM */ + /* FT_FACE_FLAG_FAST_GLYPHS */ + /* FT_FACE_FLAG_HINTER */ + /* */ + /* FT_STYLE_FLAG_BOLD */ + /* FT_STYLE_FLAG_ITALIC */ + /* */ + /* FT_SizeRec */ + /* FT_Size_Metrics */ + /* */ + /* FT_GlyphSlotRec */ + /* FT_Glyph_Metrics */ + /* FT_SubGlyph */ + /* */ + /* FT_Bitmap_Size */ + /* */ + /* FT_Init_FreeType */ + /* FT_Done_FreeType */ + /* */ + /* FT_New_Face */ + /* FT_Done_Face */ + /* FT_New_Memory_Face */ + /* FT_Open_Face */ + /* FT_Open_Args */ + /* FT_Parameter */ + /* FT_Attach_File */ + /* FT_Attach_Stream */ + /* */ + /* FT_Set_Char_Size */ + /* FT_Set_Pixel_Sizes */ + /* FT_Request_Size */ + /* FT_Select_Size */ + /* FT_Size_Request_Type */ + /* FT_Size_Request */ + /* FT_Set_Transform */ + /* FT_Load_Glyph */ + /* FT_Get_Char_Index */ + /* FT_Get_Name_Index */ + /* FT_Load_Char */ + /* */ + /* FT_OPEN_MEMORY */ + /* FT_OPEN_STREAM */ + /* FT_OPEN_PATHNAME */ + /* FT_OPEN_DRIVER */ + /* FT_OPEN_PARAMS */ + /* */ + /* FT_LOAD_DEFAULT */ + /* FT_LOAD_RENDER */ + /* FT_LOAD_MONOCHROME */ + /* FT_LOAD_LINEAR_DESIGN */ + /* FT_LOAD_NO_SCALE */ + /* FT_LOAD_NO_HINTING */ + /* FT_LOAD_NO_BITMAP */ + /* FT_LOAD_CROP_BITMAP */ + /* */ + /* FT_LOAD_VERTICAL_LAYOUT */ + /* FT_LOAD_IGNORE_TRANSFORM */ + /* FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH */ + /* FT_LOAD_FORCE_AUTOHINT */ + /* FT_LOAD_NO_RECURSE */ + /* FT_LOAD_PEDANTIC */ + /* */ + /* FT_LOAD_TARGET_NORMAL */ + /* FT_LOAD_TARGET_LIGHT */ + /* FT_LOAD_TARGET_MONO */ + /* FT_LOAD_TARGET_LCD */ + /* FT_LOAD_TARGET_LCD_V */ + /* */ + /* FT_Render_Glyph */ + /* FT_Render_Mode */ + /* FT_Get_Kerning */ + /* FT_Kerning_Mode */ + /* FT_Get_Track_Kerning */ + /* FT_Get_Glyph_Name */ + /* FT_Get_Postscript_Name */ + /* */ + /* FT_CharMapRec */ + /* FT_Select_Charmap */ + /* FT_Set_Charmap */ + /* FT_Get_Charmap_Index */ + /* */ + /* FT_FSTYPE_INSTALLABLE_EMBEDDING */ + /* FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING */ + /* FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING */ + /* FT_FSTYPE_EDITABLE_EMBEDDING */ + /* FT_FSTYPE_NO_SUBSETTING */ + /* FT_FSTYPE_BITMAP_EMBEDDING_ONLY */ + /* */ + /* FT_Get_FSType_Flags */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Glyph_Metrics */ + /* */ + /* <Description> */ + /* A structure used to model the metrics of a single glyph. The */ + /* values are expressed in 26.6 fractional pixel format; if the flag */ + /* @FT_LOAD_NO_SCALE has been used while loading the glyph, values */ + /* are expressed in font units instead. */ + /* */ + /* <Fields> */ + /* width :: */ + /* The glyph's width. */ + /* */ + /* height :: */ + /* The glyph's height. */ + /* */ + /* horiBearingX :: */ + /* Left side bearing for horizontal layout. */ + /* */ + /* horiBearingY :: */ + /* Top side bearing for horizontal layout. */ + /* */ + /* horiAdvance :: */ + /* Advance width for horizontal layout. */ + /* */ + /* vertBearingX :: */ + /* Left side bearing for vertical layout. */ + /* */ + /* vertBearingY :: */ + /* Top side bearing for vertical layout. Larger positive values */ + /* mean further below the vertical glyph origin. */ + /* */ + /* vertAdvance :: */ + /* Advance height for vertical layout. Positive values mean the */ + /* glyph has a positive advance downward. */ + /* */ + /* <Note> */ + /* If not disabled with @FT_LOAD_NO_HINTING, the values represent */ + /* dimensions of the hinted glyph (in case hinting is applicable). */ + /* */ + typedef struct FT_Glyph_Metrics_ + { + FT_Pos width; + FT_Pos height; + + FT_Pos horiBearingX; + FT_Pos horiBearingY; + FT_Pos horiAdvance; + + FT_Pos vertBearingX; + FT_Pos vertBearingY; + FT_Pos vertAdvance; + + } FT_Glyph_Metrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Bitmap_Size */ + /* */ + /* <Description> */ + /* This structure models the metrics of a bitmap strike (i.e., a set */ + /* of glyphs for a given point size and resolution) in a bitmap font. */ + /* It is used for the `available_sizes' field of @FT_Face. */ + /* */ + /* <Fields> */ + /* height :: The vertical distance, in pixels, between two */ + /* consecutive baselines. It is always positive. */ + /* */ + /* width :: The average width, in pixels, of all glyphs in the */ + /* strike. */ + /* */ + /* size :: The nominal size of the strike in 26.6 fractional */ + /* points. This field is not very useful. */ + /* */ + /* x_ppem :: The horizontal ppem (nominal width) in 26.6 fractional */ + /* pixels. */ + /* */ + /* y_ppem :: The vertical ppem (nominal height) in 26.6 fractional */ + /* pixels. */ + /* */ + /* <Note> */ + /* Windows FNT: */ + /* The nominal size given in a FNT font is not reliable. Thus when */ + /* the driver finds it incorrect, it sets `size' to some calculated */ + /* values and sets `x_ppem' and `y_ppem' to the pixel width and */ + /* height given in the font, respectively. */ + /* */ + /* TrueType embedded bitmaps: */ + /* `size', `width', and `height' values are not contained in the */ + /* bitmap strike itself. They are computed from the global font */ + /* parameters. */ + /* */ + typedef struct FT_Bitmap_Size_ + { + FT_Short height; + FT_Short width; + + FT_Pos size; + + FT_Pos x_ppem; + FT_Pos y_ppem; + + } FT_Bitmap_Size; + + + /*************************************************************************/ + /*************************************************************************/ + /* */ + /* O B J E C T C L A S S E S */ + /* */ + /*************************************************************************/ + /*************************************************************************/ + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Library */ + /* */ + /* <Description> */ + /* A handle to a FreeType library instance. Each `library' is */ + /* completely independent from the others; it is the `root' of a set */ + /* of objects like fonts, faces, sizes, etc. */ + /* */ + /* It also embeds a memory manager (see @FT_Memory), as well as a */ + /* scan-line converter object (see @FT_Raster). */ + /* */ + /* For multi-threading applications each thread should have its own */ + /* FT_Library object. */ + /* */ + /* <Note> */ + /* Library objects are normally created by @FT_Init_FreeType, and */ + /* destroyed with @FT_Done_FreeType. */ + /* */ + typedef struct FT_LibraryRec_ *FT_Library; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Module */ + /* */ + /* <Description> */ + /* A handle to a given FreeType module object. Each module can be a */ + /* font driver, a renderer, or anything else that provides services */ + /* to the formers. */ + /* */ + typedef struct FT_ModuleRec_* FT_Module; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Driver */ + /* */ + /* <Description> */ + /* A handle to a given FreeType font driver object. Each font driver */ + /* is a special module capable of creating faces from font files. */ + /* */ + typedef struct FT_DriverRec_* FT_Driver; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Renderer */ + /* */ + /* <Description> */ + /* A handle to a given FreeType renderer. A renderer is a special */ + /* module in charge of converting a glyph image to a bitmap, when */ + /* necessary. Each renderer supports a given glyph image format, and */ + /* one or more target surface depths. */ + /* */ + typedef struct FT_RendererRec_* FT_Renderer; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Face */ + /* */ + /* <Description> */ + /* A handle to a given typographic face object. A face object models */ + /* a given typeface, in a given style. */ + /* */ + /* <Note> */ + /* Each face object also owns a single @FT_GlyphSlot object, as well */ + /* as one or more @FT_Size objects. */ + /* */ + /* Use @FT_New_Face or @FT_Open_Face to create a new face object from */ + /* a given filepathname or a custom input stream. */ + /* */ + /* Use @FT_Done_Face to destroy it (along with its slot and sizes). */ + /* */ + /* <Also> */ + /* See @FT_FaceRec for the publicly accessible fields of a given face */ + /* object. */ + /* */ + typedef struct FT_FaceRec_* FT_Face; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Size */ + /* */ + /* <Description> */ + /* A handle to an object used to model a face scaled to a given */ + /* character size. */ + /* */ + /* <Note> */ + /* Each @FT_Face has an _active_ @FT_Size object that is used by */ + /* functions like @FT_Load_Glyph to determine the scaling */ + /* transformation which is used to load and hint glyphs and metrics. */ + /* */ + /* You can use @FT_Set_Char_Size, @FT_Set_Pixel_Sizes, */ + /* @FT_Request_Size or even @FT_Select_Size to change the content */ + /* (i.e., the scaling values) of the active @FT_Size. */ + /* */ + /* You can use @FT_New_Size to create additional size objects for a */ + /* given @FT_Face, but they won't be used by other functions until */ + /* you activate it through @FT_Activate_Size. Only one size can be */ + /* activated at any given time per face. */ + /* */ + /* <Also> */ + /* See @FT_SizeRec for the publicly accessible fields of a given size */ + /* object. */ + /* */ + typedef struct FT_SizeRec_* FT_Size; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_GlyphSlot */ + /* */ + /* <Description> */ + /* A handle to a given `glyph slot'. A slot is a container where it */ + /* is possible to load any of the glyphs contained in its parent */ + /* face. */ + /* */ + /* In other words, each time you call @FT_Load_Glyph or */ + /* @FT_Load_Char, the slot's content is erased by the new glyph data, */ + /* i.e., the glyph's metrics, its image (bitmap or outline), and */ + /* other control information. */ + /* */ + /* <Also> */ + /* See @FT_GlyphSlotRec for the publicly accessible glyph fields. */ + /* */ + typedef struct FT_GlyphSlotRec_* FT_GlyphSlot; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_CharMap */ + /* */ + /* <Description> */ + /* A handle to a given character map. A charmap is used to translate */ + /* character codes in a given encoding into glyph indexes for its */ + /* parent's face. Some font formats may provide several charmaps per */ + /* font. */ + /* */ + /* Each face object owns zero or more charmaps, but only one of them */ + /* can be `active' and used by @FT_Get_Char_Index or @FT_Load_Char. */ + /* */ + /* The list of available charmaps in a face is available through the */ + /* `face->num_charmaps' and `face->charmaps' fields of @FT_FaceRec. */ + /* */ + /* The currently active charmap is available as `face->charmap'. */ + /* You should call @FT_Set_Charmap to change it. */ + /* */ + /* <Note> */ + /* When a new face is created (either through @FT_New_Face or */ + /* @FT_Open_Face), the library looks for a Unicode charmap within */ + /* the list and automatically activates it. */ + /* */ + /* <Also> */ + /* See @FT_CharMapRec for the publicly accessible fields of a given */ + /* character map. */ + /* */ + typedef struct FT_CharMapRec_* FT_CharMap; + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_ENC_TAG */ + /* */ + /* <Description> */ + /* This macro converts four-letter tags into an unsigned long. It is */ + /* used to define `encoding' identifiers (see @FT_Encoding). */ + /* */ + /* <Note> */ + /* Since many 16-bit compilers don't like 32-bit enumerations, you */ + /* should redefine this macro in case of problems to something like */ + /* this: */ + /* */ + /* { */ + /* #define FT_ENC_TAG( value, a, b, c, d ) value */ + /* } */ + /* */ + /* to get a simple enumeration without assigning special numbers. */ + /* */ + +#ifndef FT_ENC_TAG +#define FT_ENC_TAG( value, a, b, c, d ) \ + value = ( ( (FT_UInt32)(a) << 24 ) | \ + ( (FT_UInt32)(b) << 16 ) | \ + ( (FT_UInt32)(c) << 8 ) | \ + (FT_UInt32)(d) ) + +#endif /* FT_ENC_TAG */ + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Encoding */ + /* */ + /* <Description> */ + /* An enumeration used to specify character sets supported by */ + /* charmaps. Used in the @FT_Select_Charmap API function. */ + /* */ + /* <Note> */ + /* Despite the name, this enumeration lists specific character */ + /* repertories (i.e., charsets), and not text encoding methods (e.g., */ + /* UTF-8, UTF-16, etc.). */ + /* */ + /* Other encodings might be defined in the future. */ + /* */ + /* <Values> */ + /* FT_ENCODING_NONE :: */ + /* The encoding value~0 is reserved. */ + /* */ + /* FT_ENCODING_UNICODE :: */ + /* Corresponds to the Unicode character set. This value covers */ + /* all versions of the Unicode repertoire, including ASCII and */ + /* Latin-1. Most fonts include a Unicode charmap, but not all */ + /* of them. */ + /* */ + /* For example, if you want to access Unicode value U+1F028 (and */ + /* the font contains it), use value 0x1F028 as the input value for */ + /* @FT_Get_Char_Index. */ + /* */ + /* FT_ENCODING_MS_SYMBOL :: */ + /* Corresponds to the Microsoft Symbol encoding, used to encode */ + /* mathematical symbols in the 32..255 character code range. For */ + /* more information, see `http://www.ceviz.net/symbol.htm'. */ + /* */ + /* FT_ENCODING_SJIS :: */ + /* Corresponds to Japanese SJIS encoding. More info at */ + /* at `http://langsupport.japanreference.com/encoding.shtml'. */ + /* See note on multi-byte encodings below. */ + /* */ + /* FT_ENCODING_GB2312 :: */ + /* Corresponds to an encoding system for Simplified Chinese as used */ + /* used in mainland China. */ + /* */ + /* FT_ENCODING_BIG5 :: */ + /* Corresponds to an encoding system for Traditional Chinese as */ + /* used in Taiwan and Hong Kong. */ + /* */ + /* FT_ENCODING_WANSUNG :: */ + /* Corresponds to the Korean encoding system known as Wansung. */ + /* For more information see */ + /* `http://www.microsoft.com/typography/unicode/949.txt'. */ + /* */ + /* FT_ENCODING_JOHAB :: */ + /* The Korean standard character set (KS~C 5601-1992), which */ + /* corresponds to MS Windows code page 1361. This character set */ + /* includes all possible Hangeul character combinations. */ + /* */ + /* FT_ENCODING_ADOBE_LATIN_1 :: */ + /* Corresponds to a Latin-1 encoding as defined in a Type~1 */ + /* PostScript font. It is limited to 256 character codes. */ + /* */ + /* FT_ENCODING_ADOBE_STANDARD :: */ + /* Corresponds to the Adobe Standard encoding, as found in Type~1, */ + /* CFF, and OpenType/CFF fonts. It is limited to 256 character */ + /* codes. */ + /* */ + /* FT_ENCODING_ADOBE_EXPERT :: */ + /* Corresponds to the Adobe Expert encoding, as found in Type~1, */ + /* CFF, and OpenType/CFF fonts. It is limited to 256 character */ + /* codes. */ + /* */ + /* FT_ENCODING_ADOBE_CUSTOM :: */ + /* Corresponds to a custom encoding, as found in Type~1, CFF, and */ + /* OpenType/CFF fonts. It is limited to 256 character codes. */ + /* */ + /* FT_ENCODING_APPLE_ROMAN :: */ + /* Corresponds to the 8-bit Apple roman encoding. Many TrueType */ + /* and OpenType fonts contain a charmap for this encoding, since */ + /* older versions of Mac OS are able to use it. */ + /* */ + /* FT_ENCODING_OLD_LATIN_2 :: */ + /* This value is deprecated and was never used nor reported by */ + /* FreeType. Don't use or test for it. */ + /* */ + /* FT_ENCODING_MS_SJIS :: */ + /* Same as FT_ENCODING_SJIS. Deprecated. */ + /* */ + /* FT_ENCODING_MS_GB2312 :: */ + /* Same as FT_ENCODING_GB2312. Deprecated. */ + /* */ + /* FT_ENCODING_MS_BIG5 :: */ + /* Same as FT_ENCODING_BIG5. Deprecated. */ + /* */ + /* FT_ENCODING_MS_WANSUNG :: */ + /* Same as FT_ENCODING_WANSUNG. Deprecated. */ + /* */ + /* FT_ENCODING_MS_JOHAB :: */ + /* Same as FT_ENCODING_JOHAB. Deprecated. */ + /* */ + /* <Note> */ + /* By default, FreeType automatically synthesizes a Unicode charmap */ + /* for PostScript fonts, using their glyph names dictionaries. */ + /* However, it also reports the encodings defined explicitly in the */ + /* font file, for the cases when they are needed, with the Adobe */ + /* values as well. */ + /* */ + /* FT_ENCODING_NONE is set by the BDF and PCF drivers if the charmap */ + /* is neither Unicode nor ISO-8859-1 (otherwise it is set to */ + /* FT_ENCODING_UNICODE). Use @FT_Get_BDF_Charset_ID to find out */ + /* which encoding is really present. If, for example, the */ + /* `cs_registry' field is `KOI8' and the `cs_encoding' field is `R', */ + /* the font is encoded in KOI8-R. */ + /* */ + /* FT_ENCODING_NONE is always set (with a single exception) by the */ + /* winfonts driver. Use @FT_Get_WinFNT_Header and examine the */ + /* `charset' field of the @FT_WinFNT_HeaderRec structure to find out */ + /* which encoding is really present. For example, */ + /* @FT_WinFNT_ID_CP1251 (204) means Windows code page 1251 (for */ + /* Russian). */ + /* */ + /* FT_ENCODING_NONE is set if `platform_id' is @TT_PLATFORM_MACINTOSH */ + /* and `encoding_id' is not @TT_MAC_ID_ROMAN (otherwise it is set to */ + /* FT_ENCODING_APPLE_ROMAN). */ + /* */ + /* If `platform_id' is @TT_PLATFORM_MACINTOSH, use the function */ + /* @FT_Get_CMap_Language_ID to query the Mac language ID which may */ + /* be needed to be able to distinguish Apple encoding variants. See */ + /* */ + /* http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/README.TXT */ + /* */ + /* to get an idea how to do that. Basically, if the language ID */ + /* is~0, don't use it, otherwise subtract 1 from the language ID. */ + /* Then examine `encoding_id'. If, for example, `encoding_id' is */ + /* @TT_MAC_ID_ROMAN and the language ID (minus~1) is */ + /* `TT_MAC_LANGID_GREEK', it is the Greek encoding, not Roman. */ + /* @TT_MAC_ID_ARABIC with `TT_MAC_LANGID_FARSI' means the Farsi */ + /* variant the Arabic encoding. */ + /* */ + typedef enum FT_Encoding_ + { + FT_ENC_TAG( FT_ENCODING_NONE, 0, 0, 0, 0 ), + + FT_ENC_TAG( FT_ENCODING_MS_SYMBOL, 's', 'y', 'm', 'b' ), + FT_ENC_TAG( FT_ENCODING_UNICODE, 'u', 'n', 'i', 'c' ), + + FT_ENC_TAG( FT_ENCODING_SJIS, 's', 'j', 'i', 's' ), + FT_ENC_TAG( FT_ENCODING_GB2312, 'g', 'b', ' ', ' ' ), + FT_ENC_TAG( FT_ENCODING_BIG5, 'b', 'i', 'g', '5' ), + FT_ENC_TAG( FT_ENCODING_WANSUNG, 'w', 'a', 'n', 's' ), + FT_ENC_TAG( FT_ENCODING_JOHAB, 'j', 'o', 'h', 'a' ), + + /* for backwards compatibility */ + FT_ENCODING_MS_SJIS = FT_ENCODING_SJIS, + FT_ENCODING_MS_GB2312 = FT_ENCODING_GB2312, + FT_ENCODING_MS_BIG5 = FT_ENCODING_BIG5, + FT_ENCODING_MS_WANSUNG = FT_ENCODING_WANSUNG, + FT_ENCODING_MS_JOHAB = FT_ENCODING_JOHAB, + + FT_ENC_TAG( FT_ENCODING_ADOBE_STANDARD, 'A', 'D', 'O', 'B' ), + FT_ENC_TAG( FT_ENCODING_ADOBE_EXPERT, 'A', 'D', 'B', 'E' ), + FT_ENC_TAG( FT_ENCODING_ADOBE_CUSTOM, 'A', 'D', 'B', 'C' ), + FT_ENC_TAG( FT_ENCODING_ADOBE_LATIN_1, 'l', 'a', 't', '1' ), + + FT_ENC_TAG( FT_ENCODING_OLD_LATIN_2, 'l', 'a', 't', '2' ), + + FT_ENC_TAG( FT_ENCODING_APPLE_ROMAN, 'a', 'r', 'm', 'n' ) + + } FT_Encoding; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* ft_encoding_xxx */ + /* */ + /* <Description> */ + /* These constants are deprecated; use the corresponding @FT_Encoding */ + /* values instead. */ + /* */ +#define ft_encoding_none FT_ENCODING_NONE +#define ft_encoding_unicode FT_ENCODING_UNICODE +#define ft_encoding_symbol FT_ENCODING_MS_SYMBOL +#define ft_encoding_latin_1 FT_ENCODING_ADOBE_LATIN_1 +#define ft_encoding_latin_2 FT_ENCODING_OLD_LATIN_2 +#define ft_encoding_sjis FT_ENCODING_SJIS +#define ft_encoding_gb2312 FT_ENCODING_GB2312 +#define ft_encoding_big5 FT_ENCODING_BIG5 +#define ft_encoding_wansung FT_ENCODING_WANSUNG +#define ft_encoding_johab FT_ENCODING_JOHAB + +#define ft_encoding_adobe_standard FT_ENCODING_ADOBE_STANDARD +#define ft_encoding_adobe_expert FT_ENCODING_ADOBE_EXPERT +#define ft_encoding_adobe_custom FT_ENCODING_ADOBE_CUSTOM +#define ft_encoding_apple_roman FT_ENCODING_APPLE_ROMAN + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_CharMapRec */ + /* */ + /* <Description> */ + /* The base charmap structure. */ + /* */ + /* <Fields> */ + /* face :: A handle to the parent face object. */ + /* */ + /* encoding :: An @FT_Encoding tag identifying the charmap. Use */ + /* this with @FT_Select_Charmap. */ + /* */ + /* platform_id :: An ID number describing the platform for the */ + /* following encoding ID. This comes directly from */ + /* the TrueType specification and should be emulated */ + /* for other formats. */ + /* */ + /* encoding_id :: A platform specific encoding number. This also */ + /* comes from the TrueType specification and should be */ + /* emulated similarly. */ + /* */ + typedef struct FT_CharMapRec_ + { + FT_Face face; + FT_Encoding encoding; + FT_UShort platform_id; + FT_UShort encoding_id; + + } FT_CharMapRec; + + + /*************************************************************************/ + /*************************************************************************/ + /* */ + /* B A S E O B J E C T C L A S S E S */ + /* */ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Face_Internal */ + /* */ + /* <Description> */ + /* An opaque handle to an `FT_Face_InternalRec' structure, used to */ + /* model private data of a given @FT_Face object. */ + /* */ + /* This structure might change between releases of FreeType~2 and is */ + /* not generally available to client applications. */ + /* */ + typedef struct FT_Face_InternalRec_* FT_Face_Internal; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_FaceRec */ + /* */ + /* <Description> */ + /* FreeType root face class structure. A face object models a */ + /* typeface in a font file. */ + /* */ + /* <Fields> */ + /* num_faces :: The number of faces in the font file. Some */ + /* font formats can have multiple faces in */ + /* a font file. */ + /* */ + /* face_index :: The index of the face in the font file. It */ + /* is set to~0 if there is only one face in */ + /* the font file. */ + /* */ + /* face_flags :: A set of bit flags that give important */ + /* information about the face; see */ + /* @FT_FACE_FLAG_XXX for the details. */ + /* */ + /* style_flags :: A set of bit flags indicating the style of */ + /* the face; see @FT_STYLE_FLAG_XXX for the */ + /* details. */ + /* */ + /* num_glyphs :: The number of glyphs in the face. If the */ + /* face is scalable and has sbits (see */ + /* `num_fixed_sizes'), it is set to the number */ + /* of outline glyphs. */ + /* */ + /* For CID-keyed fonts, this value gives the */ + /* highest CID used in the font. */ + /* */ + /* family_name :: The face's family name. This is an ASCII */ + /* string, usually in English, which describes */ + /* the typeface's family (like `Times New */ + /* Roman', `Bodoni', `Garamond', etc). This */ + /* is a least common denominator used to list */ + /* fonts. Some formats (TrueType & OpenType) */ + /* provide localized and Unicode versions of */ + /* this string. Applications should use the */ + /* format specific interface to access them. */ + /* Can be NULL (e.g., in fonts embedded in a */ + /* PDF file). */ + /* */ + /* style_name :: The face's style name. This is an ASCII */ + /* string, usually in English, which describes */ + /* the typeface's style (like `Italic', */ + /* `Bold', `Condensed', etc). Not all font */ + /* formats provide a style name, so this field */ + /* is optional, and can be set to NULL. As */ + /* for `family_name', some formats provide */ + /* localized and Unicode versions of this */ + /* string. Applications should use the format */ + /* specific interface to access them. */ + /* */ + /* num_fixed_sizes :: The number of bitmap strikes in the face. */ + /* Even if the face is scalable, there might */ + /* still be bitmap strikes, which are called */ + /* `sbits' in that case. */ + /* */ + /* available_sizes :: An array of @FT_Bitmap_Size for all bitmap */ + /* strikes in the face. It is set to NULL if */ + /* there is no bitmap strike. */ + /* */ + /* num_charmaps :: The number of charmaps in the face. */ + /* */ + /* charmaps :: An array of the charmaps of the face. */ + /* */ + /* generic :: A field reserved for client uses. See the */ + /* @FT_Generic type description. */ + /* */ + /* bbox :: The font bounding box. Coordinates are */ + /* expressed in font units (see */ + /* `units_per_EM'). The box is large enough */ + /* to contain any glyph from the font. Thus, */ + /* `bbox.yMax' can be seen as the `maximal */ + /* ascender', and `bbox.yMin' as the `minimal */ + /* descender'. Only relevant for scalable */ + /* formats. */ + /* */ + /* Note that the bounding box might be off by */ + /* (at least) one pixel for hinted fonts. See */ + /* @FT_Size_Metrics for further discussion. */ + /* */ + /* units_per_EM :: The number of font units per EM square for */ + /* this face. This is typically 2048 for */ + /* TrueType fonts, and 1000 for Type~1 fonts. */ + /* Only relevant for scalable formats. */ + /* */ + /* ascender :: The typographic ascender of the face, */ + /* expressed in font units. For font formats */ + /* not having this information, it is set to */ + /* `bbox.yMax'. Only relevant for scalable */ + /* formats. */ + /* */ + /* descender :: The typographic descender of the face, */ + /* expressed in font units. For font formats */ + /* not having this information, it is set to */ + /* `bbox.yMin'. Note that this field is */ + /* usually negative. Only relevant for */ + /* scalable formats. */ + /* */ + /* height :: The height is the vertical distance */ + /* between two consecutive baselines, */ + /* expressed in font units. It is always */ + /* positive. Only relevant for scalable */ + /* formats. */ + /* */ + /* max_advance_width :: The maximal advance width, in font units, */ + /* for all glyphs in this face. This can be */ + /* used to make word wrapping computations */ + /* faster. Only relevant for scalable */ + /* formats. */ + /* */ + /* max_advance_height :: The maximal advance height, in font units, */ + /* for all glyphs in this face. This is only */ + /* relevant for vertical layouts, and is set */ + /* to `height' for fonts that do not provide */ + /* vertical metrics. Only relevant for */ + /* scalable formats. */ + /* */ + /* underline_position :: The position, in font units, of the */ + /* underline line for this face. It is the */ + /* center of the underlining stem. Only */ + /* relevant for scalable formats. */ + /* */ + /* underline_thickness :: The thickness, in font units, of the */ + /* underline for this face. Only relevant for */ + /* scalable formats. */ + /* */ + /* glyph :: The face's associated glyph slot(s). */ + /* */ + /* size :: The current active size for this face. */ + /* */ + /* charmap :: The current active charmap for this face. */ + /* */ + /* <Note> */ + /* Fields may be changed after a call to @FT_Attach_File or */ + /* @FT_Attach_Stream. */ + /* */ + typedef struct FT_FaceRec_ + { + FT_Long num_faces; + FT_Long face_index; + + FT_Long face_flags; + FT_Long style_flags; + + FT_Long num_glyphs; + + FT_String* family_name; + FT_String* style_name; + + FT_Int num_fixed_sizes; + FT_Bitmap_Size* available_sizes; + + FT_Int num_charmaps; + FT_CharMap* charmaps; + + FT_Generic generic; + + /*# The following member variables (down to `underline_thickness') */ + /*# are only relevant to scalable outlines; cf. @FT_Bitmap_Size */ + /*# for bitmap fonts. */ + FT_BBox bbox; + + FT_UShort units_per_EM; + FT_Short ascender; + FT_Short descender; + FT_Short height; + + FT_Short max_advance_width; + FT_Short max_advance_height; + + FT_Short underline_position; + FT_Short underline_thickness; + + FT_GlyphSlot glyph; + FT_Size size; + FT_CharMap charmap; + + /*@private begin */ + + FT_Driver driver; + FT_Memory memory; + FT_Stream stream; + + FT_ListRec sizes_list; + + FT_Generic autohint; + void* extensions; + + FT_Face_Internal internal; + + /*@private end */ + + } FT_FaceRec; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_FACE_FLAG_XXX */ + /* */ + /* <Description> */ + /* A list of bit flags used in the `face_flags' field of the */ + /* @FT_FaceRec structure. They inform client applications of */ + /* properties of the corresponding face. */ + /* */ + /* <Values> */ + /* FT_FACE_FLAG_SCALABLE :: */ + /* Indicates that the face contains outline glyphs. This doesn't */ + /* prevent bitmap strikes, i.e., a face can have both this and */ + /* and @FT_FACE_FLAG_FIXED_SIZES set. */ + /* */ + /* FT_FACE_FLAG_FIXED_SIZES :: */ + /* Indicates that the face contains bitmap strikes. See also the */ + /* `num_fixed_sizes' and `available_sizes' fields of @FT_FaceRec. */ + /* */ + /* FT_FACE_FLAG_FIXED_WIDTH :: */ + /* Indicates that the face contains fixed-width characters (like */ + /* Courier, Lucido, MonoType, etc.). */ + /* */ + /* FT_FACE_FLAG_SFNT :: */ + /* Indicates that the face uses the `sfnt' storage scheme. For */ + /* now, this means TrueType and OpenType. */ + /* */ + /* FT_FACE_FLAG_HORIZONTAL :: */ + /* Indicates that the face contains horizontal glyph metrics. This */ + /* should be set for all common formats. */ + /* */ + /* FT_FACE_FLAG_VERTICAL :: */ + /* Indicates that the face contains vertical glyph metrics. This */ + /* is only available in some formats, not all of them. */ + /* */ + /* FT_FACE_FLAG_KERNING :: */ + /* Indicates that the face contains kerning information. If set, */ + /* the kerning distance can be retrieved through the function */ + /* @FT_Get_Kerning. Otherwise the function always return the */ + /* vector (0,0). Note that FreeType doesn't handle kerning data */ + /* from the `GPOS' table (as present in some OpenType fonts). */ + /* */ + /* FT_FACE_FLAG_FAST_GLYPHS :: */ + /* THIS FLAG IS DEPRECATED. DO NOT USE OR TEST IT. */ + /* */ + /* FT_FACE_FLAG_MULTIPLE_MASTERS :: */ + /* Indicates that the font contains multiple masters and is capable */ + /* of interpolating between them. See the multiple-masters */ + /* specific API for details. */ + /* */ + /* FT_FACE_FLAG_GLYPH_NAMES :: */ + /* Indicates that the font contains glyph names that can be */ + /* retrieved through @FT_Get_Glyph_Name. Note that some TrueType */ + /* fonts contain broken glyph name tables. Use the function */ + /* @FT_Has_PS_Glyph_Names when needed. */ + /* */ + /* FT_FACE_FLAG_EXTERNAL_STREAM :: */ + /* Used internally by FreeType to indicate that a face's stream was */ + /* provided by the client application and should not be destroyed */ + /* when @FT_Done_Face is called. Don't read or test this flag. */ + /* */ + /* FT_FACE_FLAG_HINTER :: */ + /* Set if the font driver has a hinting machine of its own. For */ + /* example, with TrueType fonts, it makes sense to use data from */ + /* the SFNT `gasp' table only if the native TrueType hinting engine */ + /* (with the bytecode interpreter) is available and active. */ + /* */ + /* FT_FACE_FLAG_CID_KEYED :: */ + /* Set if the font is CID-keyed. In that case, the font is not */ + /* accessed by glyph indices but by CID values. For subsetted */ + /* CID-keyed fonts this has the consequence that not all index */ + /* values are a valid argument to FT_Load_Glyph. Only the CID */ + /* values for which corresponding glyphs in the subsetted font */ + /* exist make FT_Load_Glyph return successfully; in all other cases */ + /* you get an `FT_Err_Invalid_Argument' error. */ + /* */ + /* Note that CID-keyed fonts which are in an SFNT wrapper don't */ + /* have this flag set since the glyphs are accessed in the normal */ + /* way (using contiguous indices); the `CID-ness' isn't visible to */ + /* the application. */ + /* */ + /* FT_FACE_FLAG_TRICKY :: */ + /* Set if the font is `tricky', this is, it always needs the */ + /* font format's native hinting engine to get a reasonable result. */ + /* A typical example is the Chinese font `mingli.ttf' which uses */ + /* TrueType bytecode instructions to move and scale all of its */ + /* subglyphs. */ + /* */ + /* It is not possible to autohint such fonts using */ + /* @FT_LOAD_FORCE_AUTOHINT; it will also ignore */ + /* @FT_LOAD_NO_HINTING. You have to set both @FT_LOAD_NO_HINTING */ + /* and @FT_LOAD_NO_AUTOHINT to really disable hinting; however, you */ + /* probably never want this except for demonstration purposes. */ + /* */ + /* Currently, there are about a dozen TrueType fonts in the list of */ + /* tricky fonts; they are hard-coded in file `ttobjs.c'. */ + /* */ +#define FT_FACE_FLAG_SCALABLE ( 1L << 0 ) +#define FT_FACE_FLAG_FIXED_SIZES ( 1L << 1 ) +#define FT_FACE_FLAG_FIXED_WIDTH ( 1L << 2 ) +#define FT_FACE_FLAG_SFNT ( 1L << 3 ) +#define FT_FACE_FLAG_HORIZONTAL ( 1L << 4 ) +#define FT_FACE_FLAG_VERTICAL ( 1L << 5 ) +#define FT_FACE_FLAG_KERNING ( 1L << 6 ) +#define FT_FACE_FLAG_FAST_GLYPHS ( 1L << 7 ) +#define FT_FACE_FLAG_MULTIPLE_MASTERS ( 1L << 8 ) +#define FT_FACE_FLAG_GLYPH_NAMES ( 1L << 9 ) +#define FT_FACE_FLAG_EXTERNAL_STREAM ( 1L << 10 ) +#define FT_FACE_FLAG_HINTER ( 1L << 11 ) +#define FT_FACE_FLAG_CID_KEYED ( 1L << 12 ) +#define FT_FACE_FLAG_TRICKY ( 1L << 13 ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_HORIZONTAL( face ) + * + * @description: + * A macro that returns true whenever a face object contains + * horizontal metrics (this is true for all font formats though). + * + * @also: + * @FT_HAS_VERTICAL can be used to check for vertical metrics. + * + */ +#define FT_HAS_HORIZONTAL( face ) \ + ( face->face_flags & FT_FACE_FLAG_HORIZONTAL ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_VERTICAL( face ) + * + * @description: + * A macro that returns true whenever a face object contains vertical + * metrics. + * + */ +#define FT_HAS_VERTICAL( face ) \ + ( face->face_flags & FT_FACE_FLAG_VERTICAL ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_KERNING( face ) + * + * @description: + * A macro that returns true whenever a face object contains kerning + * data that can be accessed with @FT_Get_Kerning. + * + */ +#define FT_HAS_KERNING( face ) \ + ( face->face_flags & FT_FACE_FLAG_KERNING ) + + + /************************************************************************* + * + * @macro: + * FT_IS_SCALABLE( face ) + * + * @description: + * A macro that returns true whenever a face object contains a scalable + * font face (true for TrueType, Type~1, Type~42, CID, OpenType/CFF, + * and PFR font formats. + * + */ +#define FT_IS_SCALABLE( face ) \ + ( face->face_flags & FT_FACE_FLAG_SCALABLE ) + + + /************************************************************************* + * + * @macro: + * FT_IS_SFNT( face ) + * + * @description: + * A macro that returns true whenever a face object contains a font + * whose format is based on the SFNT storage scheme. This usually + * means: TrueType fonts, OpenType fonts, as well as SFNT-based embedded + * bitmap fonts. + * + * If this macro is true, all functions defined in @FT_SFNT_NAMES_H and + * @FT_TRUETYPE_TABLES_H are available. + * + */ +#define FT_IS_SFNT( face ) \ + ( face->face_flags & FT_FACE_FLAG_SFNT ) + + + /************************************************************************* + * + * @macro: + * FT_IS_FIXED_WIDTH( face ) + * + * @description: + * A macro that returns true whenever a face object contains a font face + * that contains fixed-width (or `monospace', `fixed-pitch', etc.) + * glyphs. + * + */ +#define FT_IS_FIXED_WIDTH( face ) \ + ( face->face_flags & FT_FACE_FLAG_FIXED_WIDTH ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_FIXED_SIZES( face ) + * + * @description: + * A macro that returns true whenever a face object contains some + * embedded bitmaps. See the `available_sizes' field of the + * @FT_FaceRec structure. + * + */ +#define FT_HAS_FIXED_SIZES( face ) \ + ( face->face_flags & FT_FACE_FLAG_FIXED_SIZES ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_FAST_GLYPHS( face ) + * + * @description: + * Deprecated. + * + */ +#define FT_HAS_FAST_GLYPHS( face ) 0 + + + /************************************************************************* + * + * @macro: + * FT_HAS_GLYPH_NAMES( face ) + * + * @description: + * A macro that returns true whenever a face object contains some glyph + * names that can be accessed through @FT_Get_Glyph_Name. + * + */ +#define FT_HAS_GLYPH_NAMES( face ) \ + ( face->face_flags & FT_FACE_FLAG_GLYPH_NAMES ) + + + /************************************************************************* + * + * @macro: + * FT_HAS_MULTIPLE_MASTERS( face ) + * + * @description: + * A macro that returns true whenever a face object contains some + * multiple masters. The functions provided by @FT_MULTIPLE_MASTERS_H + * are then available to choose the exact design you want. + * + */ +#define FT_HAS_MULTIPLE_MASTERS( face ) \ + ( face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS ) + + + /************************************************************************* + * + * @macro: + * FT_IS_CID_KEYED( face ) + * + * @description: + * A macro that returns true whenever a face object contains a CID-keyed + * font. See the discussion of @FT_FACE_FLAG_CID_KEYED for more + * details. + * + * If this macro is true, all functions defined in @FT_CID_H are + * available. + * + */ +#define FT_IS_CID_KEYED( face ) \ + ( face->face_flags & FT_FACE_FLAG_CID_KEYED ) + + + /************************************************************************* + * + * @macro: + * FT_IS_TRICKY( face ) + * + * @description: + * A macro that returns true whenever a face represents a `tricky' font. + * See the discussion of @FT_FACE_FLAG_TRICKY for more details. + * + */ +#define FT_IS_TRICKY( face ) \ + ( face->face_flags & FT_FACE_FLAG_TRICKY ) + + + /*************************************************************************/ + /* */ + /* <Const> */ + /* FT_STYLE_FLAG_XXX */ + /* */ + /* <Description> */ + /* A list of bit-flags used to indicate the style of a given face. */ + /* These are used in the `style_flags' field of @FT_FaceRec. */ + /* */ + /* <Values> */ + /* FT_STYLE_FLAG_ITALIC :: */ + /* Indicates that a given face style is italic or oblique. */ + /* */ + /* FT_STYLE_FLAG_BOLD :: */ + /* Indicates that a given face is bold. */ + /* */ + /* <Note> */ + /* The style information as provided by FreeType is very basic. More */ + /* details are beyond the scope and should be done on a higher level */ + /* (for example, by analyzing various fields of the `OS/2' table in */ + /* SFNT based fonts). */ + /* */ +#define FT_STYLE_FLAG_ITALIC ( 1 << 0 ) +#define FT_STYLE_FLAG_BOLD ( 1 << 1 ) + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Size_Internal */ + /* */ + /* <Description> */ + /* An opaque handle to an `FT_Size_InternalRec' structure, used to */ + /* model private data of a given @FT_Size object. */ + /* */ + typedef struct FT_Size_InternalRec_* FT_Size_Internal; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Size_Metrics */ + /* */ + /* <Description> */ + /* The size metrics structure gives the metrics of a size object. */ + /* */ + /* <Fields> */ + /* x_ppem :: The width of the scaled EM square in pixels, hence */ + /* the term `ppem' (pixels per EM). It is also */ + /* referred to as `nominal width'. */ + /* */ + /* y_ppem :: The height of the scaled EM square in pixels, */ + /* hence the term `ppem' (pixels per EM). It is also */ + /* referred to as `nominal height'. */ + /* */ + /* x_scale :: A 16.16 fractional scaling value used to convert */ + /* horizontal metrics from font units to 26.6 */ + /* fractional pixels. Only relevant for scalable */ + /* font formats. */ + /* */ + /* y_scale :: A 16.16 fractional scaling value used to convert */ + /* vertical metrics from font units to 26.6 */ + /* fractional pixels. Only relevant for scalable */ + /* font formats. */ + /* */ + /* ascender :: The ascender in 26.6 fractional pixels. See */ + /* @FT_FaceRec for the details. */ + /* */ + /* descender :: The descender in 26.6 fractional pixels. See */ + /* @FT_FaceRec for the details. */ + /* */ + /* height :: The height in 26.6 fractional pixels. See */ + /* @FT_FaceRec for the details. */ + /* */ + /* max_advance :: The maximal advance width in 26.6 fractional */ + /* pixels. See @FT_FaceRec for the details. */ + /* */ + /* <Note> */ + /* The scaling values, if relevant, are determined first during a */ + /* size changing operation. The remaining fields are then set by the */ + /* driver. For scalable formats, they are usually set to scaled */ + /* values of the corresponding fields in @FT_FaceRec. */ + /* */ + /* Note that due to glyph hinting, these values might not be exact */ + /* for certain fonts. Thus they must be treated as unreliable */ + /* with an error margin of at least one pixel! */ + /* */ + /* Indeed, the only way to get the exact metrics is to render _all_ */ + /* glyphs. As this would be a definite performance hit, it is up to */ + /* client applications to perform such computations. */ + /* */ + /* The FT_Size_Metrics structure is valid for bitmap fonts also. */ + /* */ + typedef struct FT_Size_Metrics_ + { + FT_UShort x_ppem; /* horizontal pixels per EM */ + FT_UShort y_ppem; /* vertical pixels per EM */ + + FT_Fixed x_scale; /* scaling values used to convert font */ + FT_Fixed y_scale; /* units to 26.6 fractional pixels */ + + FT_Pos ascender; /* ascender in 26.6 frac. pixels */ + FT_Pos descender; /* descender in 26.6 frac. pixels */ + FT_Pos height; /* text height in 26.6 frac. pixels */ + FT_Pos max_advance; /* max horizontal advance, in 26.6 pixels */ + + } FT_Size_Metrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_SizeRec */ + /* */ + /* <Description> */ + /* FreeType root size class structure. A size object models a face */ + /* object at a given size. */ + /* */ + /* <Fields> */ + /* face :: Handle to the parent face object. */ + /* */ + /* generic :: A typeless pointer, which is unused by the FreeType */ + /* library or any of its drivers. It can be used by */ + /* client applications to link their own data to each size */ + /* object. */ + /* */ + /* metrics :: Metrics for this size object. This field is read-only. */ + /* */ + typedef struct FT_SizeRec_ + { + FT_Face face; /* parent face object */ + FT_Generic generic; /* generic pointer for client uses */ + FT_Size_Metrics metrics; /* size metrics */ + FT_Size_Internal internal; + + } FT_SizeRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_SubGlyph */ + /* */ + /* <Description> */ + /* The subglyph structure is an internal object used to describe */ + /* subglyphs (for example, in the case of composites). */ + /* */ + /* <Note> */ + /* The subglyph implementation is not part of the high-level API, */ + /* hence the forward structure declaration. */ + /* */ + /* You can however retrieve subglyph information with */ + /* @FT_Get_SubGlyph_Info. */ + /* */ + typedef struct FT_SubGlyphRec_* FT_SubGlyph; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Slot_Internal */ + /* */ + /* <Description> */ + /* An opaque handle to an `FT_Slot_InternalRec' structure, used to */ + /* model private data of a given @FT_GlyphSlot object. */ + /* */ + typedef struct FT_Slot_InternalRec_* FT_Slot_Internal; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_GlyphSlotRec */ + /* */ + /* <Description> */ + /* FreeType root glyph slot class structure. A glyph slot is a */ + /* container where individual glyphs can be loaded, be they in */ + /* outline or bitmap format. */ + /* */ + /* <Fields> */ + /* library :: A handle to the FreeType library instance */ + /* this slot belongs to. */ + /* */ + /* face :: A handle to the parent face object. */ + /* */ + /* next :: In some cases (like some font tools), several */ + /* glyph slots per face object can be a good */ + /* thing. As this is rare, the glyph slots are */ + /* listed through a direct, single-linked list */ + /* using its `next' field. */ + /* */ + /* generic :: A typeless pointer which is unused by the */ + /* FreeType library or any of its drivers. It */ + /* can be used by client applications to link */ + /* their own data to each glyph slot object. */ + /* */ + /* metrics :: The metrics of the last loaded glyph in the */ + /* slot. The returned values depend on the last */ + /* load flags (see the @FT_Load_Glyph API */ + /* function) and can be expressed either in 26.6 */ + /* fractional pixels or font units. */ + /* */ + /* Note that even when the glyph image is */ + /* transformed, the metrics are not. */ + /* */ + /* linearHoriAdvance :: The advance width of the unhinted glyph. */ + /* Its value is expressed in 16.16 fractional */ + /* pixels, unless @FT_LOAD_LINEAR_DESIGN is set */ + /* when loading the glyph. This field can be */ + /* important to perform correct WYSIWYG layout. */ + /* Only relevant for outline glyphs. */ + /* */ + /* linearVertAdvance :: The advance height of the unhinted glyph. */ + /* Its value is expressed in 16.16 fractional */ + /* pixels, unless @FT_LOAD_LINEAR_DESIGN is set */ + /* when loading the glyph. This field can be */ + /* important to perform correct WYSIWYG layout. */ + /* Only relevant for outline glyphs. */ + /* */ + /* advance :: This shorthand is, depending on */ + /* @FT_LOAD_IGNORE_TRANSFORM, the transformed */ + /* advance width for the glyph (in 26.6 */ + /* fractional pixel format). As specified with */ + /* @FT_LOAD_VERTICAL_LAYOUT, it uses either the */ + /* `horiAdvance' or the `vertAdvance' value of */ + /* `metrics' field. */ + /* */ + /* format :: This field indicates the format of the image */ + /* contained in the glyph slot. Typically */ + /* @FT_GLYPH_FORMAT_BITMAP, */ + /* @FT_GLYPH_FORMAT_OUTLINE, or */ + /* @FT_GLYPH_FORMAT_COMPOSITE, but others are */ + /* possible. */ + /* */ + /* bitmap :: This field is used as a bitmap descriptor */ + /* when the slot format is */ + /* @FT_GLYPH_FORMAT_BITMAP. Note that the */ + /* address and content of the bitmap buffer can */ + /* change between calls of @FT_Load_Glyph and a */ + /* few other functions. */ + /* */ + /* bitmap_left :: This is the bitmap's left bearing expressed */ + /* in integer pixels. Of course, this is only */ + /* valid if the format is */ + /* @FT_GLYPH_FORMAT_BITMAP. */ + /* */ + /* bitmap_top :: This is the bitmap's top bearing expressed in */ + /* integer pixels. Remember that this is the */ + /* distance from the baseline to the top-most */ + /* glyph scanline, upwards y~coordinates being */ + /* *positive*. */ + /* */ + /* outline :: The outline descriptor for the current glyph */ + /* image if its format is */ + /* @FT_GLYPH_FORMAT_OUTLINE. Once a glyph is */ + /* loaded, `outline' can be transformed, */ + /* distorted, embolded, etc. However, it must */ + /* not be freed. */ + /* */ + /* num_subglyphs :: The number of subglyphs in a composite glyph. */ + /* This field is only valid for the composite */ + /* glyph format that should normally only be */ + /* loaded with the @FT_LOAD_NO_RECURSE flag. */ + /* For now this is internal to FreeType. */ + /* */ + /* subglyphs :: An array of subglyph descriptors for */ + /* composite glyphs. There are `num_subglyphs' */ + /* elements in there. Currently internal to */ + /* FreeType. */ + /* */ + /* control_data :: Certain font drivers can also return the */ + /* control data for a given glyph image (e.g. */ + /* TrueType bytecode, Type~1 charstrings, etc.). */ + /* This field is a pointer to such data. */ + /* */ + /* control_len :: This is the length in bytes of the control */ + /* data. */ + /* */ + /* other :: Really wicked formats can use this pointer to */ + /* present their own glyph image to client */ + /* applications. Note that the application */ + /* needs to know about the image format. */ + /* */ + /* lsb_delta :: The difference between hinted and unhinted */ + /* left side bearing while autohinting is */ + /* active. Zero otherwise. */ + /* */ + /* rsb_delta :: The difference between hinted and unhinted */ + /* right side bearing while autohinting is */ + /* active. Zero otherwise. */ + /* */ + /* <Note> */ + /* If @FT_Load_Glyph is called with default flags (see */ + /* @FT_LOAD_DEFAULT) the glyph image is loaded in the glyph slot in */ + /* its native format (e.g., an outline glyph for TrueType and Type~1 */ + /* formats). */ + /* */ + /* This image can later be converted into a bitmap by calling */ + /* @FT_Render_Glyph. This function finds the current renderer for */ + /* the native image's format, then invokes it. */ + /* */ + /* The renderer is in charge of transforming the native image through */ + /* the slot's face transformation fields, then converting it into a */ + /* bitmap that is returned in `slot->bitmap'. */ + /* */ + /* Note that `slot->bitmap_left' and `slot->bitmap_top' are also used */ + /* to specify the position of the bitmap relative to the current pen */ + /* position (e.g., coordinates (0,0) on the baseline). Of course, */ + /* `slot->format' is also changed to @FT_GLYPH_FORMAT_BITMAP. */ + /* */ + /* <Note> */ + /* Here a small pseudo code fragment which shows how to use */ + /* `lsb_delta' and `rsb_delta': */ + /* */ + /* { */ + /* FT_Pos origin_x = 0; */ + /* FT_Pos prev_rsb_delta = 0; */ + /* */ + /* */ + /* for all glyphs do */ + /* <compute kern between current and previous glyph and add it to */ + /* `origin_x'> */ + /* */ + /* <load glyph with `FT_Load_Glyph'> */ + /* */ + /* if ( prev_rsb_delta - face->glyph->lsb_delta >= 32 ) */ + /* origin_x -= 64; */ + /* else if ( prev_rsb_delta - face->glyph->lsb_delta < -32 ) */ + /* origin_x += 64; */ + /* */ + /* prev_rsb_delta = face->glyph->rsb_delta; */ + /* */ + /* <save glyph image, or render glyph, or ...> */ + /* */ + /* origin_x += face->glyph->advance.x; */ + /* endfor */ + /* } */ + /* */ + typedef struct FT_GlyphSlotRec_ + { + FT_Library library; + FT_Face face; + FT_GlyphSlot next; + FT_UInt reserved; /* retained for binary compatibility */ + FT_Generic generic; + + FT_Glyph_Metrics metrics; + FT_Fixed linearHoriAdvance; + FT_Fixed linearVertAdvance; + FT_Vector advance; + + FT_Glyph_Format format; + + FT_Bitmap bitmap; + FT_Int bitmap_left; + FT_Int bitmap_top; + + FT_Outline outline; + + FT_UInt num_subglyphs; + FT_SubGlyph subglyphs; + + void* control_data; + long control_len; + + FT_Pos lsb_delta; + FT_Pos rsb_delta; + + void* other; + + FT_Slot_Internal internal; + + } FT_GlyphSlotRec; + + + /*************************************************************************/ + /*************************************************************************/ + /* */ + /* F U N C T I O N S */ + /* */ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Init_FreeType */ + /* */ + /* <Description> */ + /* Initialize a new FreeType library object. The set of modules */ + /* that are registered by this function is determined at build time. */ + /* */ + /* <Output> */ + /* alibrary :: A handle to a new library object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* In case you want to provide your own memory allocating routines, */ + /* use @FT_New_Library instead, followed by a call to */ + /* @FT_Add_Default_Modules (or a series of calls to @FT_Add_Module). */ + /* */ + FT_EXPORT( FT_Error ) + FT_Init_FreeType( FT_Library *alibrary ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_FreeType */ + /* */ + /* <Description> */ + /* Destroy a given FreeType library object and all of its children, */ + /* including resources, drivers, faces, sizes, etc. */ + /* */ + /* <Input> */ + /* library :: A handle to the target library object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Done_FreeType( FT_Library library ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_OPEN_XXX */ + /* */ + /* <Description> */ + /* A list of bit-field constants used within the `flags' field of the */ + /* @FT_Open_Args structure. */ + /* */ + /* <Values> */ + /* FT_OPEN_MEMORY :: This is a memory-based stream. */ + /* */ + /* FT_OPEN_STREAM :: Copy the stream from the `stream' field. */ + /* */ + /* FT_OPEN_PATHNAME :: Create a new input stream from a C~path */ + /* name. */ + /* */ + /* FT_OPEN_DRIVER :: Use the `driver' field. */ + /* */ + /* FT_OPEN_PARAMS :: Use the `num_params' and `params' fields. */ + /* */ + /* ft_open_memory :: Deprecated; use @FT_OPEN_MEMORY instead. */ + /* */ + /* ft_open_stream :: Deprecated; use @FT_OPEN_STREAM instead. */ + /* */ + /* ft_open_pathname :: Deprecated; use @FT_OPEN_PATHNAME instead. */ + /* */ + /* ft_open_driver :: Deprecated; use @FT_OPEN_DRIVER instead. */ + /* */ + /* ft_open_params :: Deprecated; use @FT_OPEN_PARAMS instead. */ + /* */ + /* <Note> */ + /* The `FT_OPEN_MEMORY', `FT_OPEN_STREAM', and `FT_OPEN_PATHNAME' */ + /* flags are mutually exclusive. */ + /* */ +#define FT_OPEN_MEMORY 0x1 +#define FT_OPEN_STREAM 0x2 +#define FT_OPEN_PATHNAME 0x4 +#define FT_OPEN_DRIVER 0x8 +#define FT_OPEN_PARAMS 0x10 + +#define ft_open_memory FT_OPEN_MEMORY /* deprecated */ +#define ft_open_stream FT_OPEN_STREAM /* deprecated */ +#define ft_open_pathname FT_OPEN_PATHNAME /* deprecated */ +#define ft_open_driver FT_OPEN_DRIVER /* deprecated */ +#define ft_open_params FT_OPEN_PARAMS /* deprecated */ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Parameter */ + /* */ + /* <Description> */ + /* A simple structure used to pass more or less generic parameters to */ + /* @FT_Open_Face. */ + /* */ + /* <Fields> */ + /* tag :: A four-byte identification tag. */ + /* */ + /* data :: A pointer to the parameter data. */ + /* */ + /* <Note> */ + /* The ID and function of parameters are driver-specific. See the */ + /* various FT_PARAM_TAG_XXX flags for more information. */ + /* */ + typedef struct FT_Parameter_ + { + FT_ULong tag; + FT_Pointer data; + + } FT_Parameter; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Open_Args */ + /* */ + /* <Description> */ + /* A structure used to indicate how to open a new font file or */ + /* stream. A pointer to such a structure can be used as a parameter */ + /* for the functions @FT_Open_Face and @FT_Attach_Stream. */ + /* */ + /* <Fields> */ + /* flags :: A set of bit flags indicating how to use the */ + /* structure. */ + /* */ + /* memory_base :: The first byte of the file in memory. */ + /* */ + /* memory_size :: The size in bytes of the file in memory. */ + /* */ + /* pathname :: A pointer to an 8-bit file pathname. */ + /* */ + /* stream :: A handle to a source stream object. */ + /* */ + /* driver :: This field is exclusively used by @FT_Open_Face; */ + /* it simply specifies the font driver to use to open */ + /* the face. If set to~0, FreeType tries to load the */ + /* face with each one of the drivers in its list. */ + /* */ + /* num_params :: The number of extra parameters. */ + /* */ + /* params :: Extra parameters passed to the font driver when */ + /* opening a new face. */ + /* */ + /* <Note> */ + /* The stream type is determined by the contents of `flags' which */ + /* are tested in the following order by @FT_Open_Face: */ + /* */ + /* If the `FT_OPEN_MEMORY' bit is set, assume that this is a */ + /* memory file of `memory_size' bytes, located at `memory_address'. */ + /* The data are are not copied, and the client is responsible for */ + /* releasing and destroying them _after_ the corresponding call to */ + /* @FT_Done_Face. */ + /* */ + /* Otherwise, if the `FT_OPEN_STREAM' bit is set, assume that a */ + /* custom input stream `stream' is used. */ + /* */ + /* Otherwise, if the `FT_OPEN_PATHNAME' bit is set, assume that this */ + /* is a normal file and use `pathname' to open it. */ + /* */ + /* If the `FT_OPEN_DRIVER' bit is set, @FT_Open_Face only tries to */ + /* open the file with the driver whose handler is in `driver'. */ + /* */ + /* If the `FT_OPEN_PARAMS' bit is set, the parameters given by */ + /* `num_params' and `params' is used. They are ignored otherwise. */ + /* */ + /* Ideally, both the `pathname' and `params' fields should be tagged */ + /* as `const'; this is missing for API backwards compatibility. In */ + /* other words, applications should treat them as read-only. */ + /* */ + typedef struct FT_Open_Args_ + { + FT_UInt flags; + const FT_Byte* memory_base; + FT_Long memory_size; + FT_String* pathname; + FT_Stream stream; + FT_Module driver; + FT_Int num_params; + FT_Parameter* params; + + } FT_Open_Args; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Face */ + /* */ + /* <Description> */ + /* This function calls @FT_Open_Face to open a font by its pathname. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* pathname :: A path to the font file. */ + /* */ + /* face_index :: The index of the face within the font. The first */ + /* face has index~0. */ + /* */ + /* <Output> */ + /* aface :: A handle to a new face object. If `face_index' is */ + /* greater than or equal to zero, it must be non-NULL. */ + /* See @FT_Open_Face for more details. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Face( FT_Library library, + const char* filepathname, + FT_Long face_index, + FT_Face *aface ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Memory_Face */ + /* */ + /* <Description> */ + /* This function calls @FT_Open_Face to open a font which has been */ + /* loaded into memory. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* file_base :: A pointer to the beginning of the font data. */ + /* */ + /* file_size :: The size of the memory chunk used by the font data. */ + /* */ + /* face_index :: The index of the face within the font. The first */ + /* face has index~0. */ + /* */ + /* <Output> */ + /* aface :: A handle to a new face object. If `face_index' is */ + /* greater than or equal to zero, it must be non-NULL. */ + /* See @FT_Open_Face for more details. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* You must not deallocate the memory before calling @FT_Done_Face. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Memory_Face( FT_Library library, + const FT_Byte* file_base, + FT_Long file_size, + FT_Long face_index, + FT_Face *aface ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Open_Face */ + /* */ + /* <Description> */ + /* Create a face object from a given resource described by */ + /* @FT_Open_Args. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* args :: A pointer to an `FT_Open_Args' structure which must */ + /* be filled by the caller. */ + /* */ + /* face_index :: The index of the face within the font. The first */ + /* face has index~0. */ + /* */ + /* <Output> */ + /* aface :: A handle to a new face object. If `face_index' is */ + /* greater than or equal to zero, it must be non-NULL. */ + /* See note below. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* Unlike FreeType 1.x, this function automatically creates a glyph */ + /* slot for the face object which can be accessed directly through */ + /* `face->glyph'. */ + /* */ + /* FT_Open_Face can be used to quickly check whether the font */ + /* format of a given font resource is supported by FreeType. If the */ + /* `face_index' field is negative, the function's return value is~0 */ + /* if the font format is recognized, or non-zero otherwise; */ + /* the function returns a more or less empty face handle in `*aface' */ + /* (if `aface' isn't NULL). The only useful field in this special */ + /* case is `face->num_faces' which gives the number of faces within */ + /* the font file. After examination, the returned @FT_Face structure */ + /* should be deallocated with a call to @FT_Done_Face. */ + /* */ + /* Each new face object created with this function also owns a */ + /* default @FT_Size object, accessible as `face->size'. */ + /* */ + /* See the discussion of reference counters in the description of */ + /* @FT_Reference_Face. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Open_Face( FT_Library library, + const FT_Open_Args* args, + FT_Long face_index, + FT_Face *aface ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Attach_File */ + /* */ + /* <Description> */ + /* This function calls @FT_Attach_Stream to attach a file. */ + /* */ + /* <InOut> */ + /* face :: The target face object. */ + /* */ + /* <Input> */ + /* filepathname :: The pathname. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Attach_File( FT_Face face, + const char* filepathname ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Attach_Stream */ + /* */ + /* <Description> */ + /* `Attach' data to a face object. Normally, this is used to read */ + /* additional information for the face object. For example, you can */ + /* attach an AFM file that comes with a Type~1 font to get the */ + /* kerning values and other metrics. */ + /* */ + /* <InOut> */ + /* face :: The target face object. */ + /* */ + /* <Input> */ + /* parameters :: A pointer to @FT_Open_Args which must be filled by */ + /* the caller. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The meaning of the `attach' (i.e., what really happens when the */ + /* new file is read) is not fixed by FreeType itself. It really */ + /* depends on the font format (and thus the font driver). */ + /* */ + /* Client applications are expected to know what they are doing */ + /* when invoking this function. Most drivers simply do not implement */ + /* file attachments. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Attach_Stream( FT_Face face, + FT_Open_Args* parameters ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Reference_Face */ + /* */ + /* <Description> */ + /* A counter gets initialized to~1 at the time an @FT_Face structure */ + /* is created. This function increments the counter. @FT_Done_Face */ + /* then only destroys a face if the counter is~1, otherwise it simply */ + /* decrements the counter. */ + /* */ + /* This function helps in managing life-cycles of structures which */ + /* reference @FT_Face objects. */ + /* */ + /* <Input> */ + /* face :: A handle to a target face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Since> */ + /* 2.4.2 */ + /* */ + FT_EXPORT( FT_Error ) + FT_Reference_Face( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_Face */ + /* */ + /* <Description> */ + /* Discard a given face object, as well as all of its child slots and */ + /* sizes. */ + /* */ + /* <Input> */ + /* face :: A handle to a target face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* See the discussion of reference counters in the description of */ + /* @FT_Reference_Face. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Done_Face( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Select_Size */ + /* */ + /* <Description> */ + /* Select a bitmap strike. */ + /* */ + /* <InOut> */ + /* face :: A handle to a target face object. */ + /* */ + /* <Input> */ + /* strike_index :: The index of the bitmap strike in the */ + /* `available_sizes' field of @FT_FaceRec structure. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Select_Size( FT_Face face, + FT_Int strike_index ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Size_Request_Type */ + /* */ + /* <Description> */ + /* An enumeration type that lists the supported size request types. */ + /* */ + /* <Values> */ + /* FT_SIZE_REQUEST_TYPE_NOMINAL :: */ + /* The nominal size. The `units_per_EM' field of @FT_FaceRec is */ + /* used to determine both scaling values. */ + /* */ + /* FT_SIZE_REQUEST_TYPE_REAL_DIM :: */ + /* The real dimension. The sum of the the `ascender' and (minus */ + /* of) the `descender' fields of @FT_FaceRec are used to determine */ + /* both scaling values. */ + /* */ + /* FT_SIZE_REQUEST_TYPE_BBOX :: */ + /* The font bounding box. The width and height of the `bbox' field */ + /* of @FT_FaceRec are used to determine the horizontal and vertical */ + /* scaling value, respectively. */ + /* */ + /* FT_SIZE_REQUEST_TYPE_CELL :: */ + /* The `max_advance_width' field of @FT_FaceRec is used to */ + /* determine the horizontal scaling value; the vertical scaling */ + /* value is determined the same way as */ + /* @FT_SIZE_REQUEST_TYPE_REAL_DIM does. Finally, both scaling */ + /* values are set to the smaller one. This type is useful if you */ + /* want to specify the font size for, say, a window of a given */ + /* dimension and 80x24 cells. */ + /* */ + /* FT_SIZE_REQUEST_TYPE_SCALES :: */ + /* Specify the scaling values directly. */ + /* */ + /* <Note> */ + /* The above descriptions only apply to scalable formats. For bitmap */ + /* formats, the behaviour is up to the driver. */ + /* */ + /* See the note section of @FT_Size_Metrics if you wonder how size */ + /* requesting relates to scaling values. */ + /* */ + typedef enum FT_Size_Request_Type_ + { + FT_SIZE_REQUEST_TYPE_NOMINAL, + FT_SIZE_REQUEST_TYPE_REAL_DIM, + FT_SIZE_REQUEST_TYPE_BBOX, + FT_SIZE_REQUEST_TYPE_CELL, + FT_SIZE_REQUEST_TYPE_SCALES, + + FT_SIZE_REQUEST_TYPE_MAX + + } FT_Size_Request_Type; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Size_RequestRec */ + /* */ + /* <Description> */ + /* A structure used to model a size request. */ + /* */ + /* <Fields> */ + /* type :: See @FT_Size_Request_Type. */ + /* */ + /* width :: The desired width. */ + /* */ + /* height :: The desired height. */ + /* */ + /* horiResolution :: The horizontal resolution. If set to zero, */ + /* `width' is treated as a 26.6 fractional pixel */ + /* value. */ + /* */ + /* vertResolution :: The vertical resolution. If set to zero, */ + /* `height' is treated as a 26.6 fractional pixel */ + /* value. */ + /* */ + /* <Note> */ + /* If `width' is zero, then the horizontal scaling value is set equal */ + /* to the vertical scaling value, and vice versa. */ + /* */ + typedef struct FT_Size_RequestRec_ + { + FT_Size_Request_Type type; + FT_Long width; + FT_Long height; + FT_UInt horiResolution; + FT_UInt vertResolution; + + } FT_Size_RequestRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Size_Request */ + /* */ + /* <Description> */ + /* A handle to a size request structure. */ + /* */ + typedef struct FT_Size_RequestRec_ *FT_Size_Request; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Request_Size */ + /* */ + /* <Description> */ + /* Resize the scale of the active @FT_Size object in a face. */ + /* */ + /* <InOut> */ + /* face :: A handle to a target face object. */ + /* */ + /* <Input> */ + /* req :: A pointer to a @FT_Size_RequestRec. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* Although drivers may select the bitmap strike matching the */ + /* request, you should not rely on this if you intend to select a */ + /* particular bitmap strike. Use @FT_Select_Size instead in that */ + /* case. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Request_Size( FT_Face face, + FT_Size_Request req ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Char_Size */ + /* */ + /* <Description> */ + /* This function calls @FT_Request_Size to request the nominal size */ + /* (in points). */ + /* */ + /* <InOut> */ + /* face :: A handle to a target face object. */ + /* */ + /* <Input> */ + /* char_width :: The nominal width, in 26.6 fractional points. */ + /* */ + /* char_height :: The nominal height, in 26.6 fractional points. */ + /* */ + /* horz_resolution :: The horizontal resolution in dpi. */ + /* */ + /* vert_resolution :: The vertical resolution in dpi. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* If either the character width or height is zero, it is set equal */ + /* to the other value. */ + /* */ + /* If either the horizontal or vertical resolution is zero, it is set */ + /* equal to the other value. */ + /* */ + /* A character width or height smaller than 1pt is set to 1pt; if */ + /* both resolution values are zero, they are set to 72dpi. */ + /* */ + /* Don't use this function if you are using the FreeType cache API. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Char_Size( FT_Face face, + FT_F26Dot6 char_width, + FT_F26Dot6 char_height, + FT_UInt horz_resolution, + FT_UInt vert_resolution ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Pixel_Sizes */ + /* */ + /* <Description> */ + /* This function calls @FT_Request_Size to request the nominal size */ + /* (in pixels). */ + /* */ + /* <InOut> */ + /* face :: A handle to the target face object. */ + /* */ + /* <Input> */ + /* pixel_width :: The nominal width, in pixels. */ + /* */ + /* pixel_height :: The nominal height, in pixels. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Pixel_Sizes( FT_Face face, + FT_UInt pixel_width, + FT_UInt pixel_height ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Load_Glyph */ + /* */ + /* <Description> */ + /* A function used to load a single glyph into the glyph slot of a */ + /* face object. */ + /* */ + /* <InOut> */ + /* face :: A handle to the target face object where the glyph */ + /* is loaded. */ + /* */ + /* <Input> */ + /* glyph_index :: The index of the glyph in the font file. For */ + /* CID-keyed fonts (either in PS or in CFF format) */ + /* this argument specifies the CID value. */ + /* */ + /* load_flags :: A flag indicating what to load for this glyph. The */ + /* @FT_LOAD_XXX constants can be used to control the */ + /* glyph loading process (e.g., whether the outline */ + /* should be scaled, whether to load bitmaps or not, */ + /* whether to hint the outline, etc). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The loaded glyph may be transformed. See @FT_Set_Transform for */ + /* the details. */ + /* */ + /* For subsetted CID-keyed fonts, `FT_Err_Invalid_Argument' is */ + /* returned for invalid CID values (this is, for CID values which */ + /* don't have a corresponding glyph in the font). See the discussion */ + /* of the @FT_FACE_FLAG_CID_KEYED flag for more details. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Load_Glyph( FT_Face face, + FT_UInt glyph_index, + FT_Int32 load_flags ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Load_Char */ + /* */ + /* <Description> */ + /* A function used to load a single glyph into the glyph slot of a */ + /* face object, according to its character code. */ + /* */ + /* <InOut> */ + /* face :: A handle to a target face object where the glyph */ + /* is loaded. */ + /* */ + /* <Input> */ + /* char_code :: The glyph's character code, according to the */ + /* current charmap used in the face. */ + /* */ + /* load_flags :: A flag indicating what to load for this glyph. The */ + /* @FT_LOAD_XXX constants can be used to control the */ + /* glyph loading process (e.g., whether the outline */ + /* should be scaled, whether to load bitmaps or not, */ + /* whether to hint the outline, etc). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function simply calls @FT_Get_Char_Index and @FT_Load_Glyph. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Load_Char( FT_Face face, + FT_ULong char_code, + FT_Int32 load_flags ); + + + /************************************************************************* + * + * @enum: + * FT_LOAD_XXX + * + * @description: + * A list of bit-field constants used with @FT_Load_Glyph to indicate + * what kind of operations to perform during glyph loading. + * + * @values: + * FT_LOAD_DEFAULT :: + * Corresponding to~0, this value is used as the default glyph load + * operation. In this case, the following happens: + * + * 1. FreeType looks for a bitmap for the glyph corresponding to the + * face's current size. If one is found, the function returns. + * The bitmap data can be accessed from the glyph slot (see note + * below). + * + * 2. If no embedded bitmap is searched or found, FreeType looks for a + * scalable outline. If one is found, it is loaded from the font + * file, scaled to device pixels, then `hinted' to the pixel grid + * in order to optimize it. The outline data can be accessed from + * the glyph slot (see note below). + * + * Note that by default, the glyph loader doesn't render outlines into + * bitmaps. The following flags are used to modify this default + * behaviour to more specific and useful cases. + * + * FT_LOAD_NO_SCALE :: + * Don't scale the outline glyph loaded, but keep it in font units. + * + * This flag implies @FT_LOAD_NO_HINTING and @FT_LOAD_NO_BITMAP, and + * unsets @FT_LOAD_RENDER. + * + * FT_LOAD_NO_HINTING :: + * Disable hinting. This generally generates `blurrier' bitmap glyph + * when the glyph is rendered in any of the anti-aliased modes. See + * also the note below. + * + * This flag is implied by @FT_LOAD_NO_SCALE. + * + * FT_LOAD_RENDER :: + * Call @FT_Render_Glyph after the glyph is loaded. By default, the + * glyph is rendered in @FT_RENDER_MODE_NORMAL mode. This can be + * overridden by @FT_LOAD_TARGET_XXX or @FT_LOAD_MONOCHROME. + * + * This flag is unset by @FT_LOAD_NO_SCALE. + * + * FT_LOAD_NO_BITMAP :: + * Ignore bitmap strikes when loading. Bitmap-only fonts ignore this + * flag. + * + * @FT_LOAD_NO_SCALE always sets this flag. + * + * FT_LOAD_VERTICAL_LAYOUT :: + * Load the glyph for vertical text layout. _Don't_ use it as it is + * problematic currently. + * + * FT_LOAD_FORCE_AUTOHINT :: + * Indicates that the auto-hinter is preferred over the font's native + * hinter. See also the note below. + * + * FT_LOAD_CROP_BITMAP :: + * Indicates that the font driver should crop the loaded bitmap glyph + * (i.e., remove all space around its black bits). Not all drivers + * implement this. + * + * FT_LOAD_PEDANTIC :: + * Indicates that the font driver should perform pedantic verifications + * during glyph loading. This is mostly used to detect broken glyphs + * in fonts. By default, FreeType tries to handle broken fonts also. + * + * FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH :: + * Ignored. Deprecated. + * + * FT_LOAD_NO_RECURSE :: + * This flag is only used internally. It merely indicates that the + * font driver should not load composite glyphs recursively. Instead, + * it should set the `num_subglyph' and `subglyphs' values of the + * glyph slot accordingly, and set `glyph->format' to + * @FT_GLYPH_FORMAT_COMPOSITE. + * + * The description of sub-glyphs is not available to client + * applications for now. + * + * This flag implies @FT_LOAD_NO_SCALE and @FT_LOAD_IGNORE_TRANSFORM. + * + * FT_LOAD_IGNORE_TRANSFORM :: + * Indicates that the transform matrix set by @FT_Set_Transform should + * be ignored. + * + * FT_LOAD_MONOCHROME :: + * This flag is used with @FT_LOAD_RENDER to indicate that you want to + * render an outline glyph to a 1-bit monochrome bitmap glyph, with + * 8~pixels packed into each byte of the bitmap data. + * + * Note that this has no effect on the hinting algorithm used. You + * should rather use @FT_LOAD_TARGET_MONO so that the + * monochrome-optimized hinting algorithm is used. + * + * FT_LOAD_LINEAR_DESIGN :: + * Indicates that the `linearHoriAdvance' and `linearVertAdvance' + * fields of @FT_GlyphSlotRec should be kept in font units. See + * @FT_GlyphSlotRec for details. + * + * FT_LOAD_NO_AUTOHINT :: + * Disable auto-hinter. See also the note below. + * + * @note: + * By default, hinting is enabled and the font's native hinter (see + * @FT_FACE_FLAG_HINTER) is preferred over the auto-hinter. You can + * disable hinting by setting @FT_LOAD_NO_HINTING or change the + * precedence by setting @FT_LOAD_FORCE_AUTOHINT. You can also set + * @FT_LOAD_NO_AUTOHINT in case you don't want the auto-hinter to be + * used at all. + * + * See the description of @FT_FACE_FLAG_TRICKY for a special exception + * (affecting only a handful of Asian fonts). + * + * Besides deciding which hinter to use, you can also decide which + * hinting algorithm to use. See @FT_LOAD_TARGET_XXX for details. + * + */ +#define FT_LOAD_DEFAULT 0x0 +#define FT_LOAD_NO_SCALE 0x1 +#define FT_LOAD_NO_HINTING 0x2 +#define FT_LOAD_RENDER 0x4 +#define FT_LOAD_NO_BITMAP 0x8 +#define FT_LOAD_VERTICAL_LAYOUT 0x10 +#define FT_LOAD_FORCE_AUTOHINT 0x20 +#define FT_LOAD_CROP_BITMAP 0x40 +#define FT_LOAD_PEDANTIC 0x80 +#define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH 0x200 +#define FT_LOAD_NO_RECURSE 0x400 +#define FT_LOAD_IGNORE_TRANSFORM 0x800 +#define FT_LOAD_MONOCHROME 0x1000 +#define FT_LOAD_LINEAR_DESIGN 0x2000 +#define FT_LOAD_NO_AUTOHINT 0x8000U + + /* */ + + /* used internally only by certain font drivers! */ +#define FT_LOAD_ADVANCE_ONLY 0x100 +#define FT_LOAD_SBITS_ONLY 0x4000 + + + /************************************************************************** + * + * @enum: + * FT_LOAD_TARGET_XXX + * + * @description: + * A list of values that are used to select a specific hinting algorithm + * to use by the hinter. You should OR one of these values to your + * `load_flags' when calling @FT_Load_Glyph. + * + * Note that font's native hinters may ignore the hinting algorithm you + * have specified (e.g., the TrueType bytecode interpreter). You can set + * @FT_LOAD_FORCE_AUTOHINT to ensure that the auto-hinter is used. + * + * Also note that @FT_LOAD_TARGET_LIGHT is an exception, in that it + * always implies @FT_LOAD_FORCE_AUTOHINT. + * + * @values: + * FT_LOAD_TARGET_NORMAL :: + * This corresponds to the default hinting algorithm, optimized for + * standard gray-level rendering. For monochrome output, use + * @FT_LOAD_TARGET_MONO instead. + * + * FT_LOAD_TARGET_LIGHT :: + * A lighter hinting algorithm for non-monochrome modes. Many + * generated glyphs are more fuzzy but better resemble its original + * shape. A bit like rendering on Mac OS~X. + * + * As a special exception, this target implies @FT_LOAD_FORCE_AUTOHINT. + * + * FT_LOAD_TARGET_MONO :: + * Strong hinting algorithm that should only be used for monochrome + * output. The result is probably unpleasant if the glyph is rendered + * in non-monochrome modes. + * + * FT_LOAD_TARGET_LCD :: + * A variant of @FT_LOAD_TARGET_NORMAL optimized for horizontally + * decimated LCD displays. + * + * FT_LOAD_TARGET_LCD_V :: + * A variant of @FT_LOAD_TARGET_NORMAL optimized for vertically + * decimated LCD displays. + * + * @note: + * You should use only _one_ of the FT_LOAD_TARGET_XXX values in your + * `load_flags'. They can't be ORed. + * + * If @FT_LOAD_RENDER is also set, the glyph is rendered in the + * corresponding mode (i.e., the mode which matches the used algorithm + * best) unless @FT_LOAD_MONOCHROME is set. + * + * You can use a hinting algorithm that doesn't correspond to the same + * rendering mode. As an example, it is possible to use the `light' + * hinting algorithm and have the results rendered in horizontal LCD + * pixel mode, with code like + * + * { + * FT_Load_Glyph( face, glyph_index, + * load_flags | FT_LOAD_TARGET_LIGHT ); + * + * FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD ); + * } + * + */ +#define FT_LOAD_TARGET_( x ) ( (FT_Int32)( (x) & 15 ) << 16 ) + +#define FT_LOAD_TARGET_NORMAL FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL ) +#define FT_LOAD_TARGET_LIGHT FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT ) +#define FT_LOAD_TARGET_MONO FT_LOAD_TARGET_( FT_RENDER_MODE_MONO ) +#define FT_LOAD_TARGET_LCD FT_LOAD_TARGET_( FT_RENDER_MODE_LCD ) +#define FT_LOAD_TARGET_LCD_V FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V ) + + + /************************************************************************** + * + * @macro: + * FT_LOAD_TARGET_MODE + * + * @description: + * Return the @FT_Render_Mode corresponding to a given + * @FT_LOAD_TARGET_XXX value. + * + */ +#define FT_LOAD_TARGET_MODE( x ) ( (FT_Render_Mode)( ( (x) >> 16 ) & 15 ) ) + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Transform */ + /* */ + /* <Description> */ + /* A function used to set the transformation that is applied to glyph */ + /* images when they are loaded into a glyph slot through */ + /* @FT_Load_Glyph. */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Input> */ + /* matrix :: A pointer to the transformation's 2x2 matrix. Use~0 for */ + /* the identity matrix. */ + /* delta :: A pointer to the translation vector. Use~0 for the null */ + /* vector. */ + /* */ + /* <Note> */ + /* The transformation is only applied to scalable image formats after */ + /* the glyph has been loaded. It means that hinting is unaltered by */ + /* the transformation and is performed on the character size given in */ + /* the last call to @FT_Set_Char_Size or @FT_Set_Pixel_Sizes. */ + /* */ + /* Note that this also transforms the `face.glyph.advance' field, but */ + /* *not* the values in `face.glyph.metrics'. */ + /* */ + FT_EXPORT( void ) + FT_Set_Transform( FT_Face face, + FT_Matrix* matrix, + FT_Vector* delta ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Render_Mode */ + /* */ + /* <Description> */ + /* An enumeration type that lists the render modes supported by */ + /* FreeType~2. Each mode corresponds to a specific type of scanline */ + /* conversion performed on the outline. */ + /* */ + /* For bitmap fonts and embedded bitmaps the `bitmap->pixel_mode' */ + /* field in the @FT_GlyphSlotRec structure gives the format of the */ + /* returned bitmap. */ + /* */ + /* All modes except @FT_RENDER_MODE_MONO use 256 levels of opacity. */ + /* */ + /* <Values> */ + /* FT_RENDER_MODE_NORMAL :: */ + /* This is the default render mode; it corresponds to 8-bit */ + /* anti-aliased bitmaps. */ + /* */ + /* FT_RENDER_MODE_LIGHT :: */ + /* This is equivalent to @FT_RENDER_MODE_NORMAL. It is only */ + /* defined as a separate value because render modes are also used */ + /* indirectly to define hinting algorithm selectors. See */ + /* @FT_LOAD_TARGET_XXX for details. */ + /* */ + /* FT_RENDER_MODE_MONO :: */ + /* This mode corresponds to 1-bit bitmaps (with 2~levels of */ + /* opacity). */ + /* */ + /* FT_RENDER_MODE_LCD :: */ + /* This mode corresponds to horizontal RGB and BGR sub-pixel */ + /* displays like LCD screens. It produces 8-bit bitmaps that are */ + /* 3~times the width of the original glyph outline in pixels, and */ + /* which use the @FT_PIXEL_MODE_LCD mode. */ + /* */ + /* FT_RENDER_MODE_LCD_V :: */ + /* This mode corresponds to vertical RGB and BGR sub-pixel displays */ + /* (like PDA screens, rotated LCD displays, etc.). It produces */ + /* 8-bit bitmaps that are 3~times the height of the original */ + /* glyph outline in pixels and use the @FT_PIXEL_MODE_LCD_V mode. */ + /* */ + /* <Note> */ + /* The LCD-optimized glyph bitmaps produced by FT_Render_Glyph can be */ + /* filtered to reduce color-fringes by using @FT_Library_SetLcdFilter */ + /* (not active in the default builds). It is up to the caller to */ + /* either call @FT_Library_SetLcdFilter (if available) or do the */ + /* filtering itself. */ + /* */ + /* The selected render mode only affects vector glyphs of a font. */ + /* Embedded bitmaps often have a different pixel mode like */ + /* @FT_PIXEL_MODE_MONO. You can use @FT_Bitmap_Convert to transform */ + /* them into 8-bit pixmaps. */ + /* */ + typedef enum FT_Render_Mode_ + { + FT_RENDER_MODE_NORMAL = 0, + FT_RENDER_MODE_LIGHT, + FT_RENDER_MODE_MONO, + FT_RENDER_MODE_LCD, + FT_RENDER_MODE_LCD_V, + + FT_RENDER_MODE_MAX + + } FT_Render_Mode; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* ft_render_mode_xxx */ + /* */ + /* <Description> */ + /* These constants are deprecated. Use the corresponding */ + /* @FT_Render_Mode values instead. */ + /* */ + /* <Values> */ + /* ft_render_mode_normal :: see @FT_RENDER_MODE_NORMAL */ + /* ft_render_mode_mono :: see @FT_RENDER_MODE_MONO */ + /* */ +#define ft_render_mode_normal FT_RENDER_MODE_NORMAL +#define ft_render_mode_mono FT_RENDER_MODE_MONO + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Render_Glyph */ + /* */ + /* <Description> */ + /* Convert a given glyph image to a bitmap. It does so by inspecting */ + /* the glyph image format, finding the relevant renderer, and */ + /* invoking it. */ + /* */ + /* <InOut> */ + /* slot :: A handle to the glyph slot containing the image to */ + /* convert. */ + /* */ + /* <Input> */ + /* render_mode :: This is the render mode used to render the glyph */ + /* image into a bitmap. See @FT_Render_Mode for a */ + /* list of possible values. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Render_Glyph( FT_GlyphSlot slot, + FT_Render_Mode render_mode ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Kerning_Mode */ + /* */ + /* <Description> */ + /* An enumeration used to specify which kerning values to return in */ + /* @FT_Get_Kerning. */ + /* */ + /* <Values> */ + /* FT_KERNING_DEFAULT :: Return scaled and grid-fitted kerning */ + /* distances (value is~0). */ + /* */ + /* FT_KERNING_UNFITTED :: Return scaled but un-grid-fitted kerning */ + /* distances. */ + /* */ + /* FT_KERNING_UNSCALED :: Return the kerning vector in original font */ + /* units. */ + /* */ + typedef enum FT_Kerning_Mode_ + { + FT_KERNING_DEFAULT = 0, + FT_KERNING_UNFITTED, + FT_KERNING_UNSCALED + + } FT_Kerning_Mode; + + + /*************************************************************************/ + /* */ + /* <Const> */ + /* ft_kerning_default */ + /* */ + /* <Description> */ + /* This constant is deprecated. Please use @FT_KERNING_DEFAULT */ + /* instead. */ + /* */ +#define ft_kerning_default FT_KERNING_DEFAULT + + + /*************************************************************************/ + /* */ + /* <Const> */ + /* ft_kerning_unfitted */ + /* */ + /* <Description> */ + /* This constant is deprecated. Please use @FT_KERNING_UNFITTED */ + /* instead. */ + /* */ +#define ft_kerning_unfitted FT_KERNING_UNFITTED + + + /*************************************************************************/ + /* */ + /* <Const> */ + /* ft_kerning_unscaled */ + /* */ + /* <Description> */ + /* This constant is deprecated. Please use @FT_KERNING_UNSCALED */ + /* instead. */ + /* */ +#define ft_kerning_unscaled FT_KERNING_UNSCALED + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Kerning */ + /* */ + /* <Description> */ + /* Return the kerning vector between two glyphs of a same face. */ + /* */ + /* <Input> */ + /* face :: A handle to a source face object. */ + /* */ + /* left_glyph :: The index of the left glyph in the kern pair. */ + /* */ + /* right_glyph :: The index of the right glyph in the kern pair. */ + /* */ + /* kern_mode :: See @FT_Kerning_Mode for more information. */ + /* Determines the scale and dimension of the returned */ + /* kerning vector. */ + /* */ + /* <Output> */ + /* akerning :: The kerning vector. This is either in font units */ + /* or in pixels (26.6 format) for scalable formats, */ + /* and in pixels for fixed-sizes formats. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* Only horizontal layouts (left-to-right & right-to-left) are */ + /* supported by this method. Other layouts, or more sophisticated */ + /* kernings, are out of the scope of this API function -- they can be */ + /* implemented through format-specific interfaces. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Kerning( FT_Face face, + FT_UInt left_glyph, + FT_UInt right_glyph, + FT_UInt kern_mode, + FT_Vector *akerning ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Track_Kerning */ + /* */ + /* <Description> */ + /* Return the track kerning for a given face object at a given size. */ + /* */ + /* <Input> */ + /* face :: A handle to a source face object. */ + /* */ + /* point_size :: The point size in 16.16 fractional points. */ + /* */ + /* degree :: The degree of tightness. */ + /* */ + /* <Output> */ + /* akerning :: The kerning in 16.16 fractional points. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Track_Kerning( FT_Face face, + FT_Fixed point_size, + FT_Int degree, + FT_Fixed* akerning ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Glyph_Name */ + /* */ + /* <Description> */ + /* Retrieve the ASCII name of a given glyph in a face. This only */ + /* works for those faces where @FT_HAS_GLYPH_NAMES(face) returns~1. */ + /* */ + /* <Input> */ + /* face :: A handle to a source face object. */ + /* */ + /* glyph_index :: The glyph index. */ + /* */ + /* buffer_max :: The maximal number of bytes available in the */ + /* buffer. */ + /* */ + /* <Output> */ + /* buffer :: A pointer to a target buffer where the name is */ + /* copied to. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* An error is returned if the face doesn't provide glyph names or if */ + /* the glyph index is invalid. In all cases of failure, the first */ + /* byte of `buffer' is set to~0 to indicate an empty name. */ + /* */ + /* The glyph name is truncated to fit within the buffer if it is too */ + /* long. The returned string is always zero-terminated. */ + /* */ + /* Be aware that FreeType reorders glyph indices internally so that */ + /* glyph index~0 always corresponds to the `missing glyph' (called */ + /* `.notdef'). */ + /* */ + /* This function is not compiled within the library if the config */ + /* macro `FT_CONFIG_OPTION_NO_GLYPH_NAMES' is defined in */ + /* `include/freetype/config/ftoptions.h'. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Glyph_Name( FT_Face face, + FT_UInt glyph_index, + FT_Pointer buffer, + FT_UInt buffer_max ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Postscript_Name */ + /* */ + /* <Description> */ + /* Retrieve the ASCII PostScript name of a given face, if available. */ + /* This only works with PostScript and TrueType fonts. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Return> */ + /* A pointer to the face's PostScript name. NULL if unavailable. */ + /* */ + /* <Note> */ + /* The returned pointer is owned by the face and is destroyed with */ + /* it. */ + /* */ + FT_EXPORT( const char* ) + FT_Get_Postscript_Name( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Select_Charmap */ + /* */ + /* <Description> */ + /* Select a given charmap by its encoding tag (as listed in */ + /* `freetype.h'). */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Input> */ + /* encoding :: A handle to the selected encoding. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function returns an error if no charmap in the face */ + /* corresponds to the encoding queried here. */ + /* */ + /* Because many fonts contain more than a single cmap for Unicode */ + /* encoding, this function has some special code to select the one */ + /* which covers Unicode best (`best' in the sense that a UCS-4 cmap */ + /* is preferred to a UCS-2 cmap). It is thus preferable to */ + /* @FT_Set_Charmap in this case. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Select_Charmap( FT_Face face, + FT_Encoding encoding ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Charmap */ + /* */ + /* <Description> */ + /* Select a given charmap for character code to glyph index mapping. */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Input> */ + /* charmap :: A handle to the selected charmap. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function returns an error if the charmap is not part of */ + /* the face (i.e., if it is not listed in the `face->charmaps' */ + /* table). */ + /* */ + /* It also fails if a type~14 charmap is selected. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Charmap( FT_Face face, + FT_CharMap charmap ); + + + /************************************************************************* + * + * @function: + * FT_Get_Charmap_Index + * + * @description: + * Retrieve index of a given charmap. + * + * @input: + * charmap :: + * A handle to a charmap. + * + * @return: + * The index into the array of character maps within the face to which + * `charmap' belongs. If an error occurs, -1 is returned. + * + */ + FT_EXPORT( FT_Int ) + FT_Get_Charmap_Index( FT_CharMap charmap ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Char_Index */ + /* */ + /* <Description> */ + /* Return the glyph index of a given character code. This function */ + /* uses a charmap object to do the mapping. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* */ + /* charcode :: The character code. */ + /* */ + /* <Return> */ + /* The glyph index. 0~means `undefined character code'. */ + /* */ + /* <Note> */ + /* If you use FreeType to manipulate the contents of font files */ + /* directly, be aware that the glyph index returned by this function */ + /* doesn't always correspond to the internal indices used within */ + /* the file. This is done to ensure that value~0 always corresponds */ + /* to the `missing glyph'. */ + /* */ + FT_EXPORT( FT_UInt ) + FT_Get_Char_Index( FT_Face face, + FT_ULong charcode ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_First_Char */ + /* */ + /* <Description> */ + /* This function is used to return the first character code in the */ + /* current charmap of a given face. It also returns the */ + /* corresponding glyph index. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Output> */ + /* agindex :: Glyph index of first character code. 0~if charmap is */ + /* empty. */ + /* */ + /* <Return> */ + /* The charmap's first character code. */ + /* */ + /* <Note> */ + /* You should use this function with @FT_Get_Next_Char to be able to */ + /* parse all character codes available in a given charmap. The code */ + /* should look like this: */ + /* */ + /* { */ + /* FT_ULong charcode; */ + /* FT_UInt gindex; */ + /* */ + /* */ + /* charcode = FT_Get_First_Char( face, &gindex ); */ + /* while ( gindex != 0 ) */ + /* { */ + /* ... do something with (charcode,gindex) pair ... */ + /* */ + /* charcode = FT_Get_Next_Char( face, charcode, &gindex ); */ + /* } */ + /* } */ + /* */ + /* Note that `*agindex' is set to~0 if the charmap is empty. The */ + /* result itself can be~0 in two cases: if the charmap is empty or */ + /* if the value~0 is the first valid character code. */ + /* */ + FT_EXPORT( FT_ULong ) + FT_Get_First_Char( FT_Face face, + FT_UInt *agindex ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Next_Char */ + /* */ + /* <Description> */ + /* This function is used to return the next character code in the */ + /* current charmap of a given face following the value `char_code', */ + /* as well as the corresponding glyph index. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* char_code :: The starting character code. */ + /* */ + /* <Output> */ + /* agindex :: Glyph index of next character code. 0~if charmap */ + /* is empty. */ + /* */ + /* <Return> */ + /* The charmap's next character code. */ + /* */ + /* <Note> */ + /* You should use this function with @FT_Get_First_Char to walk */ + /* over all character codes available in a given charmap. See the */ + /* note for this function for a simple code example. */ + /* */ + /* Note that `*agindex' is set to~0 when there are no more codes in */ + /* the charmap. */ + /* */ + FT_EXPORT( FT_ULong ) + FT_Get_Next_Char( FT_Face face, + FT_ULong char_code, + FT_UInt *agindex ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Name_Index */ + /* */ + /* <Description> */ + /* Return the glyph index of a given glyph name. This function uses */ + /* driver specific objects to do the translation. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* */ + /* glyph_name :: The glyph name. */ + /* */ + /* <Return> */ + /* The glyph index. 0~means `undefined character code'. */ + /* */ + FT_EXPORT( FT_UInt ) + FT_Get_Name_Index( FT_Face face, + FT_String* glyph_name ); + + + /************************************************************************* + * + * @macro: + * FT_SUBGLYPH_FLAG_XXX + * + * @description: + * A list of constants used to describe subglyphs. Please refer to the + * TrueType specification for the meaning of the various flags. + * + * @values: + * FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS :: + * FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES :: + * FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID :: + * FT_SUBGLYPH_FLAG_SCALE :: + * FT_SUBGLYPH_FLAG_XY_SCALE :: + * FT_SUBGLYPH_FLAG_2X2 :: + * FT_SUBGLYPH_FLAG_USE_MY_METRICS :: + * + */ +#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS 1 +#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES 2 +#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID 4 +#define FT_SUBGLYPH_FLAG_SCALE 8 +#define FT_SUBGLYPH_FLAG_XY_SCALE 0x40 +#define FT_SUBGLYPH_FLAG_2X2 0x80 +#define FT_SUBGLYPH_FLAG_USE_MY_METRICS 0x200 + + + /************************************************************************* + * + * @func: + * FT_Get_SubGlyph_Info + * + * @description: + * Retrieve a description of a given subglyph. Only use it if + * `glyph->format' is @FT_GLYPH_FORMAT_COMPOSITE; an error is + * returned otherwise. + * + * @input: + * glyph :: + * The source glyph slot. + * + * sub_index :: + * The index of the subglyph. Must be less than + * `glyph->num_subglyphs'. + * + * @output: + * p_index :: + * The glyph index of the subglyph. + * + * p_flags :: + * The subglyph flags, see @FT_SUBGLYPH_FLAG_XXX. + * + * p_arg1 :: + * The subglyph's first argument (if any). + * + * p_arg2 :: + * The subglyph's second argument (if any). + * + * p_transform :: + * The subglyph transformation (if any). + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The values of `*p_arg1', `*p_arg2', and `*p_transform' must be + * interpreted depending on the flags returned in `*p_flags'. See the + * TrueType specification for details. + * + */ + FT_EXPORT( FT_Error ) + FT_Get_SubGlyph_Info( FT_GlyphSlot glyph, + FT_UInt sub_index, + FT_Int *p_index, + FT_UInt *p_flags, + FT_Int *p_arg1, + FT_Int *p_arg2, + FT_Matrix *p_transform ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_FSTYPE_XXX */ + /* */ + /* <Description> */ + /* A list of bit flags used in the `fsType' field of the OS/2 table */ + /* in a TrueType or OpenType font and the `FSType' entry in a */ + /* PostScript font. These bit flags are returned by */ + /* @FT_Get_FSType_Flags; they inform client applications of embedding */ + /* and subsetting restrictions associated with a font. */ + /* */ + /* See http://www.adobe.com/devnet/acrobat/pdfs/FontPolicies.pdf for */ + /* more details. */ + /* */ + /* <Values> */ + /* FT_FSTYPE_INSTALLABLE_EMBEDDING :: */ + /* Fonts with no fsType bit set may be embedded and permanently */ + /* installed on the remote system by an application. */ + /* */ + /* FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING :: */ + /* Fonts that have only this bit set must not be modified, embedded */ + /* or exchanged in any manner without first obtaining permission of */ + /* the font software copyright owner. */ + /* */ + /* FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING :: */ + /* If this bit is set, the font may be embedded and temporarily */ + /* loaded on the remote system. Documents containing Preview & */ + /* Print fonts must be opened `read-only'; no edits can be applied */ + /* to the document. */ + /* */ + /* FT_FSTYPE_EDITABLE_EMBEDDING :: */ + /* If this bit is set, the font may be embedded but must only be */ + /* installed temporarily on other systems. In contrast to Preview */ + /* & Print fonts, documents containing editable fonts may be opened */ + /* for reading, editing is permitted, and changes may be saved. */ + /* */ + /* FT_FSTYPE_NO_SUBSETTING :: */ + /* If this bit is set, the font may not be subsetted prior to */ + /* embedding. */ + /* */ + /* FT_FSTYPE_BITMAP_EMBEDDING_ONLY :: */ + /* If this bit is set, only bitmaps contained in the font may be */ + /* embedded; no outline data may be embedded. If there are no */ + /* bitmaps available in the font, then the font is unembeddable. */ + /* */ + /* <Note> */ + /* While the fsType flags can indicate that a font may be embedded, a */ + /* license with the font vendor may be separately required to use the */ + /* font in this way. */ + /* */ +#define FT_FSTYPE_INSTALLABLE_EMBEDDING 0x0000 +#define FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING 0x0002 +#define FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING 0x0004 +#define FT_FSTYPE_EDITABLE_EMBEDDING 0x0008 +#define FT_FSTYPE_NO_SUBSETTING 0x0100 +#define FT_FSTYPE_BITMAP_EMBEDDING_ONLY 0x0200 + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_FSType_Flags */ + /* */ + /* <Description> */ + /* Return the fsType flags for a font. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face object. */ + /* */ + /* <Return> */ + /* The fsType flags, @FT_FSTYPE_XXX. */ + /* */ + /* <Note> */ + /* Use this function rather than directly reading the `fs_type' field */ + /* in the @PS_FontInfoRec structure which is only guaranteed to */ + /* return the correct results for Type~1 fonts. */ + /* */ + /* <Since> */ + /* 2.3.8 */ + /* */ + FT_EXPORT( FT_UShort ) + FT_Get_FSType_Flags( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* glyph_variants */ + /* */ + /* <Title> */ + /* Glyph Variants */ + /* */ + /* <Abstract> */ + /* The FreeType~2 interface to Unicode Ideographic Variation */ + /* Sequences (IVS), using the SFNT cmap format~14. */ + /* */ + /* <Description> */ + /* Many CJK characters have variant forms. They are a sort of grey */ + /* area somewhere between being totally irrelevant and semantically */ + /* distinct; for this reason, the Unicode consortium decided to */ + /* introduce Ideographic Variation Sequences (IVS), consisting of a */ + /* Unicode base character and one of 240 variant selectors */ + /* (U+E0100-U+E01EF), instead of further extending the already huge */ + /* code range for CJK characters. */ + /* */ + /* An IVS is registered and unique; for further details please refer */ + /* to Unicode Technical Report #37, the Ideographic Variation */ + /* Database. To date (October 2007), the character with the most */ + /* variants is U+908A, having 8~such IVS. */ + /* */ + /* Adobe and MS decided to support IVS with a new cmap subtable */ + /* (format~14). It is an odd subtable because it is not a mapping of */ + /* input code points to glyphs, but contains lists of all variants */ + /* supported by the font. */ + /* */ + /* A variant may be either `default' or `non-default'. A default */ + /* variant is the one you will get for that code point if you look it */ + /* up in the standard Unicode cmap. A non-default variant is a */ + /* different glyph. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_GetCharVariantIndex */ + /* */ + /* <Description> */ + /* Return the glyph index of a given character code as modified by */ + /* the variation selector. */ + /* */ + /* <Input> */ + /* face :: */ + /* A handle to the source face object. */ + /* */ + /* charcode :: */ + /* The character code point in Unicode. */ + /* */ + /* variantSelector :: */ + /* The Unicode code point of the variation selector. */ + /* */ + /* <Return> */ + /* The glyph index. 0~means either `undefined character code', or */ + /* `undefined selector code', or `no variation selector cmap */ + /* subtable', or `current CharMap is not Unicode'. */ + /* */ + /* <Note> */ + /* If you use FreeType to manipulate the contents of font files */ + /* directly, be aware that the glyph index returned by this function */ + /* doesn't always correspond to the internal indices used within */ + /* the file. This is done to ensure that value~0 always corresponds */ + /* to the `missing glyph'. */ + /* */ + /* This function is only meaningful if */ + /* a) the font has a variation selector cmap sub table, */ + /* and */ + /* b) the current charmap has a Unicode encoding. */ + /* */ + /* <Since> */ + /* 2.3.6 */ + /* */ + FT_EXPORT( FT_UInt ) + FT_Face_GetCharVariantIndex( FT_Face face, + FT_ULong charcode, + FT_ULong variantSelector ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_GetCharVariantIsDefault */ + /* */ + /* <Description> */ + /* Check whether this variant of this Unicode character is the one to */ + /* be found in the `cmap'. */ + /* */ + /* <Input> */ + /* face :: */ + /* A handle to the source face object. */ + /* */ + /* charcode :: */ + /* The character codepoint in Unicode. */ + /* */ + /* variantSelector :: */ + /* The Unicode codepoint of the variation selector. */ + /* */ + /* <Return> */ + /* 1~if found in the standard (Unicode) cmap, 0~if found in the */ + /* variation selector cmap, or -1 if it is not a variant. */ + /* */ + /* <Note> */ + /* This function is only meaningful if the font has a variation */ + /* selector cmap subtable. */ + /* */ + /* <Since> */ + /* 2.3.6 */ + /* */ + FT_EXPORT( FT_Int ) + FT_Face_GetCharVariantIsDefault( FT_Face face, + FT_ULong charcode, + FT_ULong variantSelector ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_GetVariantSelectors */ + /* */ + /* <Description> */ + /* Return a zero-terminated list of Unicode variant selectors found */ + /* in the font. */ + /* */ + /* <Input> */ + /* face :: */ + /* A handle to the source face object. */ + /* */ + /* <Return> */ + /* A pointer to an array of selector code points, or NULL if there is */ + /* no valid variant selector cmap subtable. */ + /* */ + /* <Note> */ + /* The last item in the array is~0; the array is owned by the */ + /* @FT_Face object but can be overwritten or released on the next */ + /* call to a FreeType function. */ + /* */ + /* <Since> */ + /* 2.3.6 */ + /* */ + FT_EXPORT( FT_UInt32* ) + FT_Face_GetVariantSelectors( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_GetVariantsOfChar */ + /* */ + /* <Description> */ + /* Return a zero-terminated list of Unicode variant selectors found */ + /* for the specified character code. */ + /* */ + /* <Input> */ + /* face :: */ + /* A handle to the source face object. */ + /* */ + /* charcode :: */ + /* The character codepoint in Unicode. */ + /* */ + /* <Return> */ + /* A pointer to an array of variant selector code points which are */ + /* active for the given character, or NULL if the corresponding list */ + /* is empty. */ + /* */ + /* <Note> */ + /* The last item in the array is~0; the array is owned by the */ + /* @FT_Face object but can be overwritten or released on the next */ + /* call to a FreeType function. */ + /* */ + /* <Since> */ + /* 2.3.6 */ + /* */ + FT_EXPORT( FT_UInt32* ) + FT_Face_GetVariantsOfChar( FT_Face face, + FT_ULong charcode ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_GetCharsOfVariant */ + /* */ + /* <Description> */ + /* Return a zero-terminated list of Unicode character codes found for */ + /* the specified variant selector. */ + /* */ + /* <Input> */ + /* face :: */ + /* A handle to the source face object. */ + /* */ + /* variantSelector :: */ + /* The variant selector code point in Unicode. */ + /* */ + /* <Return> */ + /* A list of all the code points which are specified by this selector */ + /* (both default and non-default codes are returned) or NULL if there */ + /* is no valid cmap or the variant selector is invalid. */ + /* */ + /* <Note> */ + /* The last item in the array is~0; the array is owned by the */ + /* @FT_Face object but can be overwritten or released on the next */ + /* call to a FreeType function. */ + /* */ + /* <Since> */ + /* 2.3.6 */ + /* */ + FT_EXPORT( FT_UInt32* ) + FT_Face_GetCharsOfVariant( FT_Face face, + FT_ULong variantSelector ); + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* computations */ + /* */ + /* <Title> */ + /* Computations */ + /* */ + /* <Abstract> */ + /* Crunching fixed numbers and vectors. */ + /* */ + /* <Description> */ + /* This section contains various functions used to perform */ + /* computations on 16.16 fixed-float numbers or 2d vectors. */ + /* */ + /* <Order> */ + /* FT_MulDiv */ + /* FT_MulFix */ + /* FT_DivFix */ + /* FT_RoundFix */ + /* FT_CeilFix */ + /* FT_FloorFix */ + /* FT_Vector_Transform */ + /* FT_Matrix_Multiply */ + /* FT_Matrix_Invert */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_MulDiv */ + /* */ + /* <Description> */ + /* A very simple function used to perform the computation `(a*b)/c' */ + /* with maximal accuracy (it uses a 64-bit intermediate integer */ + /* whenever necessary). */ + /* */ + /* This function isn't necessarily as fast as some processor specific */ + /* operations, but is at least completely portable. */ + /* */ + /* <Input> */ + /* a :: The first multiplier. */ + /* b :: The second multiplier. */ + /* c :: The divisor. */ + /* */ + /* <Return> */ + /* The result of `(a*b)/c'. This function never traps when trying to */ + /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ + /* on the signs of `a' and `b'. */ + /* */ + FT_EXPORT( FT_Long ) + FT_MulDiv( FT_Long a, + FT_Long b, + FT_Long c ); + + + /* */ + + /* The following #if 0 ... #endif is for the documentation formatter, */ + /* hiding the internal `FT_MULFIX_INLINED' macro. */ + +#if 0 + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_MulFix */ + /* */ + /* <Description> */ + /* A very simple function used to perform the computation */ + /* `(a*b)/0x10000' with maximal accuracy. Most of the time this is */ + /* used to multiply a given value by a 16.16 fixed float factor. */ + /* */ + /* <Input> */ + /* a :: The first multiplier. */ + /* b :: The second multiplier. Use a 16.16 factor here whenever */ + /* possible (see note below). */ + /* */ + /* <Return> */ + /* The result of `(a*b)/0x10000'. */ + /* */ + /* <Note> */ + /* This function has been optimized for the case where the absolute */ + /* value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */ + /* As this happens mainly when scaling from notional units to */ + /* fractional pixels in FreeType, it resulted in noticeable speed */ + /* improvements between versions 2.x and 1.x. */ + /* */ + /* As a conclusion, always try to place a 16.16 factor as the */ + /* _second_ argument of this function; this can make a great */ + /* difference. */ + /* */ + FT_EXPORT( FT_Long ) + FT_MulFix( FT_Long a, + FT_Long b ); + + /* */ +#endif + +#ifdef FT_MULFIX_INLINED +#define FT_MulFix( a, b ) FT_MULFIX_INLINED( a, b ) +#else + FT_EXPORT( FT_Long ) + FT_MulFix( FT_Long a, + FT_Long b ); +#endif + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_DivFix */ + /* */ + /* <Description> */ + /* A very simple function used to perform the computation */ + /* `(a*0x10000)/b' with maximal accuracy. Most of the time, this is */ + /* used to divide a given value by a 16.16 fixed float factor. */ + /* */ + /* <Input> */ + /* a :: The first multiplier. */ + /* b :: The second multiplier. Use a 16.16 factor here whenever */ + /* possible (see note below). */ + /* */ + /* <Return> */ + /* The result of `(a*0x10000)/b'. */ + /* */ + /* <Note> */ + /* The optimization for FT_DivFix() is simple: If (a~<<~16) fits in */ + /* 32~bits, then the division is computed directly. Otherwise, we */ + /* use a specialized version of @FT_MulDiv. */ + /* */ + FT_EXPORT( FT_Long ) + FT_DivFix( FT_Long a, + FT_Long b ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_RoundFix */ + /* */ + /* <Description> */ + /* A very simple function used to round a 16.16 fixed number. */ + /* */ + /* <Input> */ + /* a :: The number to be rounded. */ + /* */ + /* <Return> */ + /* The result of `(a + 0x8000) & -0x10000'. */ + /* */ + FT_EXPORT( FT_Fixed ) + FT_RoundFix( FT_Fixed a ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_CeilFix */ + /* */ + /* <Description> */ + /* A very simple function used to compute the ceiling function of a */ + /* 16.16 fixed number. */ + /* */ + /* <Input> */ + /* a :: The number for which the ceiling function is to be computed. */ + /* */ + /* <Return> */ + /* The result of `(a + 0x10000 - 1) & -0x10000'. */ + /* */ + FT_EXPORT( FT_Fixed ) + FT_CeilFix( FT_Fixed a ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_FloorFix */ + /* */ + /* <Description> */ + /* A very simple function used to compute the floor function of a */ + /* 16.16 fixed number. */ + /* */ + /* <Input> */ + /* a :: The number for which the floor function is to be computed. */ + /* */ + /* <Return> */ + /* The result of `a & -0x10000'. */ + /* */ + FT_EXPORT( FT_Fixed ) + FT_FloorFix( FT_Fixed a ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Vector_Transform */ + /* */ + /* <Description> */ + /* Transform a single vector through a 2x2 matrix. */ + /* */ + /* <InOut> */ + /* vector :: The target vector to transform. */ + /* */ + /* <Input> */ + /* matrix :: A pointer to the source 2x2 matrix. */ + /* */ + /* <Note> */ + /* The result is undefined if either `vector' or `matrix' is invalid. */ + /* */ + FT_EXPORT( void ) + FT_Vector_Transform( FT_Vector* vec, + const FT_Matrix* matrix ); + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* version */ + /* */ + /* <Title> */ + /* FreeType Version */ + /* */ + /* <Abstract> */ + /* Functions and macros related to FreeType versions. */ + /* */ + /* <Description> */ + /* Note that those functions and macros are of limited use because */ + /* even a new release of FreeType with only documentation changes */ + /* increases the version number. */ + /* */ + /*************************************************************************/ + + + /************************************************************************* + * + * @enum: + * FREETYPE_XXX + * + * @description: + * These three macros identify the FreeType source code version. + * Use @FT_Library_Version to access them at runtime. + * + * @values: + * FREETYPE_MAJOR :: The major version number. + * FREETYPE_MINOR :: The minor version number. + * FREETYPE_PATCH :: The patch level. + * + * @note: + * The version number of FreeType if built as a dynamic link library + * with the `libtool' package is _not_ controlled by these three + * macros. + * + */ +#define FREETYPE_MAJOR 2 +#define FREETYPE_MINOR 4 +#define FREETYPE_PATCH 8 + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Library_Version */ + /* */ + /* <Description> */ + /* Return the version of the FreeType library being used. This is */ + /* useful when dynamically linking to the library, since one cannot */ + /* use the macros @FREETYPE_MAJOR, @FREETYPE_MINOR, and */ + /* @FREETYPE_PATCH. */ + /* */ + /* <Input> */ + /* library :: A source library handle. */ + /* */ + /* <Output> */ + /* amajor :: The major version number. */ + /* */ + /* aminor :: The minor version number. */ + /* */ + /* apatch :: The patch version number. */ + /* */ + /* <Note> */ + /* The reason why this function takes a `library' argument is because */ + /* certain programs implement library initialization in a custom way */ + /* that doesn't use @FT_Init_FreeType. */ + /* */ + /* In such cases, the library version might not be available before */ + /* the library object has been created. */ + /* */ + FT_EXPORT( void ) + FT_Library_Version( FT_Library library, + FT_Int *amajor, + FT_Int *aminor, + FT_Int *apatch ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_CheckTrueTypePatents */ + /* */ + /* <Description> */ + /* Parse all bytecode instructions of a TrueType font file to check */ + /* whether any of the patented opcodes are used. This is only useful */ + /* if you want to be able to use the unpatented hinter with */ + /* fonts that do *not* use these opcodes. */ + /* */ + /* Note that this function parses *all* glyph instructions in the */ + /* font file, which may be slow. */ + /* */ + /* <Input> */ + /* face :: A face handle. */ + /* */ + /* <Return> */ + /* 1~if this is a TrueType font that uses one of the patented */ + /* opcodes, 0~otherwise. */ + /* */ + /* <Note> */ + /* Since May 2010, TrueType hinting is no longer patented. */ + /* */ + /* <Since> */ + /* 2.3.5 */ + /* */ + FT_EXPORT( FT_Bool ) + FT_Face_CheckTrueTypePatents( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Face_SetUnpatentedHinting */ + /* */ + /* <Description> */ + /* Enable or disable the unpatented hinter for a given face. */ + /* Only enable it if you have determined that the face doesn't */ + /* use any patented opcodes (see @FT_Face_CheckTrueTypePatents). */ + /* */ + /* <Input> */ + /* face :: A face handle. */ + /* */ + /* value :: New boolean setting. */ + /* */ + /* <Return> */ + /* The old setting value. This will always be false if this is not */ + /* an SFNT font, or if the unpatented hinter is not compiled in this */ + /* instance of the library. */ + /* */ + /* <Note> */ + /* Since May 2010, TrueType hinting is no longer patented. */ + /* */ + /* <Since> */ + /* 2.3.5 */ + /* */ + FT_EXPORT( FT_Bool ) + FT_Face_SetUnpatentedHinting( FT_Face face, + FT_Bool value ); + + /* */ + + +FT_END_HEADER + +#endif /* __FREETYPE_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftadvanc.h b/other/freetype/include/freetype/ftadvanc.h new file mode 100644 index 0000000..b2451be --- /dev/null +++ b/other/freetype/include/freetype/ftadvanc.h @@ -0,0 +1,179 @@ +/***************************************************************************/ +/* */ +/* ftadvanc.h */ +/* */ +/* Quick computation of advance widths (specification only). */ +/* */ +/* Copyright 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTADVANC_H__ +#define __FTADVANC_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /************************************************************************** + * + * @section: + * quick_advance + * + * @title: + * Quick retrieval of advance values + * + * @abstract: + * Retrieve horizontal and vertical advance values without processing + * glyph outlines, if possible. + * + * @description: + * This section contains functions to quickly extract advance values + * without handling glyph outlines, if possible. + */ + + + /*************************************************************************/ + /* */ + /* <Const> */ + /* FT_ADVANCE_FLAG_FAST_ONLY */ + /* */ + /* <Description> */ + /* A bit-flag to be OR-ed with the `flags' parameter of the */ + /* @FT_Get_Advance and @FT_Get_Advances functions. */ + /* */ + /* If set, it indicates that you want these functions to fail if the */ + /* corresponding hinting mode or font driver doesn't allow for very */ + /* quick advance computation. */ + /* */ + /* Typically, glyphs which are either unscaled, unhinted, bitmapped, */ + /* or light-hinted can have their advance width computed very */ + /* quickly. */ + /* */ + /* Normal and bytecode hinted modes, which require loading, scaling, */ + /* and hinting of the glyph outline, are extremely slow by */ + /* comparison. */ + /* */ +#define FT_ADVANCE_FLAG_FAST_ONLY 0x20000000UL + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Advance */ + /* */ + /* <Description> */ + /* Retrieve the advance value of a given glyph outline in an */ + /* @FT_Face. By default, the unhinted advance is returned in font */ + /* units. */ + /* */ + /* <Input> */ + /* face :: The source @FT_Face handle. */ + /* */ + /* gindex :: The glyph index. */ + /* */ + /* load_flags :: A set of bit flags similar to those used when */ + /* calling @FT_Load_Glyph, used to determine what kind */ + /* of advances you need. */ + /* <Output> */ + /* padvance :: The advance value, in either font units or 16.16 */ + /* format. */ + /* */ + /* If @FT_LOAD_VERTICAL_LAYOUT is set, this is the */ + /* vertical advance corresponding to a vertical layout. */ + /* Otherwise, it is the horizontal advance in a */ + /* horizontal layout. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and */ + /* if the corresponding font backend doesn't have a quick way to */ + /* retrieve the advances. */ + /* */ + /* A scaled advance is returned in 16.16 format but isn't transformed */ + /* by the affine transformation specified by @FT_Set_Transform. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Advance( FT_Face face, + FT_UInt gindex, + FT_Int32 load_flags, + FT_Fixed *padvance ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Advances */ + /* */ + /* <Description> */ + /* Retrieve the advance values of several glyph outlines in an */ + /* @FT_Face. By default, the unhinted advances are returned in font */ + /* units. */ + /* */ + /* <Input> */ + /* face :: The source @FT_Face handle. */ + /* */ + /* start :: The first glyph index. */ + /* */ + /* count :: The number of advance values you want to retrieve. */ + /* */ + /* load_flags :: A set of bit flags similar to those used when */ + /* calling @FT_Load_Glyph. */ + /* */ + /* <Output> */ + /* padvance :: The advances, in either font units or 16.16 format. */ + /* This array must contain at least `count' elements. */ + /* */ + /* If @FT_LOAD_VERTICAL_LAYOUT is set, these are the */ + /* vertical advances corresponding to a vertical layout. */ + /* Otherwise, they are the horizontal advances in a */ + /* horizontal layout. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and */ + /* if the corresponding font backend doesn't have a quick way to */ + /* retrieve the advances. */ + /* */ + /* Scaled advances are returned in 16.16 format but aren't */ + /* transformed by the affine transformation specified by */ + /* @FT_Set_Transform. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Advances( FT_Face face, + FT_UInt start, + FT_UInt count, + FT_Int32 load_flags, + FT_Fixed *padvances ); + +/* */ + + +FT_END_HEADER + +#endif /* __FTADVANC_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftbbox.h b/other/freetype/include/freetype/ftbbox.h new file mode 100644 index 0000000..9766919 --- /dev/null +++ b/other/freetype/include/freetype/ftbbox.h @@ -0,0 +1,102 @@ +/***************************************************************************/ +/* */ +/* ftbbox.h */ +/* */ +/* FreeType exact bbox computation (specification). */ +/* */ +/* Copyright 1996-2001, 2003, 2007, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This component has a _single_ role: to compute exact outline bounding */ + /* boxes. */ + /* */ + /* It is separated from the rest of the engine for various technical */ + /* reasons. It may well be integrated in `ftoutln' later. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTBBOX_H__ +#define __FTBBOX_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* outline_processing */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Get_BBox */ + /* */ + /* <Description> */ + /* Compute the exact bounding box of an outline. This is slower */ + /* than computing the control box. However, it uses an advanced */ + /* algorithm which returns _very_ quickly when the two boxes */ + /* coincide. Otherwise, the outline Bézier arcs are traversed to */ + /* extract their extrema. */ + /* */ + /* <Input> */ + /* outline :: A pointer to the source outline. */ + /* */ + /* <Output> */ + /* abbox :: The outline's exact bounding box. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* If the font is tricky and the glyph has been loaded with */ + /* @FT_LOAD_NO_SCALE, the resulting BBox is meaningless. To get */ + /* reasonable values for the BBox it is necessary to load the glyph */ + /* at a large ppem value (so that the hinting instructions can */ + /* properly shift and scale the subglyphs), then extracting the BBox */ + /* which can be eventually converted back to font units. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Get_BBox( FT_Outline* outline, + FT_BBox *abbox ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTBBOX_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftbdf.h b/other/freetype/include/freetype/ftbdf.h new file mode 100644 index 0000000..4f8baf8 --- /dev/null +++ b/other/freetype/include/freetype/ftbdf.h @@ -0,0 +1,209 @@ +/***************************************************************************/ +/* */ +/* ftbdf.h */ +/* */ +/* FreeType API for accessing BDF-specific strings (specification). */ +/* */ +/* Copyright 2002, 2003, 2004, 2006, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTBDF_H__ +#define __FTBDF_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* bdf_fonts */ + /* */ + /* <Title> */ + /* BDF and PCF Files */ + /* */ + /* <Abstract> */ + /* BDF and PCF specific API. */ + /* */ + /* <Description> */ + /* This section contains the declaration of functions specific to BDF */ + /* and PCF fonts. */ + /* */ + /*************************************************************************/ + + + /********************************************************************** + * + * @enum: + * FT_PropertyType + * + * @description: + * A list of BDF property types. + * + * @values: + * BDF_PROPERTY_TYPE_NONE :: + * Value~0 is used to indicate a missing property. + * + * BDF_PROPERTY_TYPE_ATOM :: + * Property is a string atom. + * + * BDF_PROPERTY_TYPE_INTEGER :: + * Property is a 32-bit signed integer. + * + * BDF_PROPERTY_TYPE_CARDINAL :: + * Property is a 32-bit unsigned integer. + */ + typedef enum BDF_PropertyType_ + { + BDF_PROPERTY_TYPE_NONE = 0, + BDF_PROPERTY_TYPE_ATOM = 1, + BDF_PROPERTY_TYPE_INTEGER = 2, + BDF_PROPERTY_TYPE_CARDINAL = 3 + + } BDF_PropertyType; + + + /********************************************************************** + * + * @type: + * BDF_Property + * + * @description: + * A handle to a @BDF_PropertyRec structure to model a given + * BDF/PCF property. + */ + typedef struct BDF_PropertyRec_* BDF_Property; + + + /********************************************************************** + * + * @struct: + * BDF_PropertyRec + * + * @description: + * This structure models a given BDF/PCF property. + * + * @fields: + * type :: + * The property type. + * + * u.atom :: + * The atom string, if type is @BDF_PROPERTY_TYPE_ATOM. + * + * u.integer :: + * A signed integer, if type is @BDF_PROPERTY_TYPE_INTEGER. + * + * u.cardinal :: + * An unsigned integer, if type is @BDF_PROPERTY_TYPE_CARDINAL. + */ + typedef struct BDF_PropertyRec_ + { + BDF_PropertyType type; + union { + const char* atom; + FT_Int32 integer; + FT_UInt32 cardinal; + + } u; + + } BDF_PropertyRec; + + + /********************************************************************** + * + * @function: + * FT_Get_BDF_Charset_ID + * + * @description: + * Retrieve a BDF font character set identity, according to + * the BDF specification. + * + * @input: + * face :: + * A handle to the input face. + * + * @output: + * acharset_encoding :: + * Charset encoding, as a C~string, owned by the face. + * + * acharset_registry :: + * Charset registry, as a C~string, owned by the face. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with BDF faces, returning an error otherwise. + */ + FT_EXPORT( FT_Error ) + FT_Get_BDF_Charset_ID( FT_Face face, + const char* *acharset_encoding, + const char* *acharset_registry ); + + + /********************************************************************** + * + * @function: + * FT_Get_BDF_Property + * + * @description: + * Retrieve a BDF property from a BDF or PCF font file. + * + * @input: + * face :: A handle to the input face. + * + * name :: The property name. + * + * @output: + * aproperty :: The property. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function works with BDF _and_ PCF fonts. It returns an error + * otherwise. It also returns an error if the property is not in the + * font. + * + * A `property' is a either key-value pair within the STARTPROPERTIES + * ... ENDPROPERTIES block of a BDF font or a key-value pair from the + * `info->props' array within a `FontRec' structure of a PCF font. + * + * Integer properties are always stored as `signed' within PCF fonts; + * consequently, @BDF_PROPERTY_TYPE_CARDINAL is a possible return value + * for BDF fonts only. + * + * In case of error, `aproperty->type' is always set to + * @BDF_PROPERTY_TYPE_NONE. + */ + FT_EXPORT( FT_Error ) + FT_Get_BDF_Property( FT_Face face, + const char* prop_name, + BDF_PropertyRec *aproperty ); + + /* */ + +FT_END_HEADER + +#endif /* __FTBDF_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftbitmap.h b/other/freetype/include/freetype/ftbitmap.h new file mode 100644 index 0000000..9274236 --- /dev/null +++ b/other/freetype/include/freetype/ftbitmap.h @@ -0,0 +1,227 @@ +/***************************************************************************/ +/* */ +/* ftbitmap.h */ +/* */ +/* FreeType utility functions for bitmaps (specification). */ +/* */ +/* Copyright 2004, 2005, 2006, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTBITMAP_H__ +#define __FTBITMAP_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* bitmap_handling */ + /* */ + /* <Title> */ + /* Bitmap Handling */ + /* */ + /* <Abstract> */ + /* Handling FT_Bitmap objects. */ + /* */ + /* <Description> */ + /* This section contains functions for converting FT_Bitmap objects. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Bitmap_New */ + /* */ + /* <Description> */ + /* Initialize a pointer to an @FT_Bitmap structure. */ + /* */ + /* <InOut> */ + /* abitmap :: A pointer to the bitmap structure. */ + /* */ + FT_EXPORT( void ) + FT_Bitmap_New( FT_Bitmap *abitmap ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Bitmap_Copy */ + /* */ + /* <Description> */ + /* Copy a bitmap into another one. */ + /* */ + /* <Input> */ + /* library :: A handle to a library object. */ + /* */ + /* source :: A handle to the source bitmap. */ + /* */ + /* <Output> */ + /* target :: A handle to the target bitmap. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Bitmap_Copy( FT_Library library, + const FT_Bitmap *source, + FT_Bitmap *target); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Bitmap_Embolden */ + /* */ + /* <Description> */ + /* Embolden a bitmap. The new bitmap will be about `xStrength' */ + /* pixels wider and `yStrength' pixels higher. The left and bottom */ + /* borders are kept unchanged. */ + /* */ + /* <Input> */ + /* library :: A handle to a library object. */ + /* */ + /* xStrength :: How strong the glyph is emboldened horizontally. */ + /* Expressed in 26.6 pixel format. */ + /* */ + /* yStrength :: How strong the glyph is emboldened vertically. */ + /* Expressed in 26.6 pixel format. */ + /* */ + /* <InOut> */ + /* bitmap :: A handle to the target bitmap. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The current implementation restricts `xStrength' to be less than */ + /* or equal to~8 if bitmap is of pixel_mode @FT_PIXEL_MODE_MONO. */ + /* */ + /* If you want to embolden the bitmap owned by a @FT_GlyphSlotRec, */ + /* you should call @FT_GlyphSlot_Own_Bitmap on the slot first. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Bitmap_Embolden( FT_Library library, + FT_Bitmap* bitmap, + FT_Pos xStrength, + FT_Pos yStrength ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Bitmap_Convert */ + /* */ + /* <Description> */ + /* Convert a bitmap object with depth 1bpp, 2bpp, 4bpp, or 8bpp to a */ + /* bitmap object with depth 8bpp, making the number of used bytes per */ + /* line (a.k.a. the `pitch') a multiple of `alignment'. */ + /* */ + /* <Input> */ + /* library :: A handle to a library object. */ + /* */ + /* source :: The source bitmap. */ + /* */ + /* alignment :: The pitch of the bitmap is a multiple of this */ + /* parameter. Common values are 1, 2, or 4. */ + /* */ + /* <Output> */ + /* target :: The target bitmap. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* It is possible to call @FT_Bitmap_Convert multiple times without */ + /* calling @FT_Bitmap_Done (the memory is simply reallocated). */ + /* */ + /* Use @FT_Bitmap_Done to finally remove the bitmap object. */ + /* */ + /* The `library' argument is taken to have access to FreeType's */ + /* memory handling functions. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Bitmap_Convert( FT_Library library, + const FT_Bitmap *source, + FT_Bitmap *target, + FT_Int alignment ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_GlyphSlot_Own_Bitmap */ + /* */ + /* <Description> */ + /* Make sure that a glyph slot owns `slot->bitmap'. */ + /* */ + /* <Input> */ + /* slot :: The glyph slot. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function is to be used in combination with */ + /* @FT_Bitmap_Embolden. */ + /* */ + FT_EXPORT( FT_Error ) + FT_GlyphSlot_Own_Bitmap( FT_GlyphSlot slot ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Bitmap_Done */ + /* */ + /* <Description> */ + /* Destroy a bitmap object created with @FT_Bitmap_New. */ + /* */ + /* <Input> */ + /* library :: A handle to a library object. */ + /* */ + /* bitmap :: The bitmap object to be freed. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The `library' argument is taken to have access to FreeType's */ + /* memory handling functions. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Bitmap_Done( FT_Library library, + FT_Bitmap *bitmap ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTBITMAP_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftbzip2.h b/other/freetype/include/freetype/ftbzip2.h new file mode 100644 index 0000000..1bf81b1 --- /dev/null +++ b/other/freetype/include/freetype/ftbzip2.h @@ -0,0 +1,102 @@ +/***************************************************************************/ +/* */ +/* ftbzip2.h */ +/* */ +/* Bzip2-compressed stream support. */ +/* */ +/* Copyright 2010 by */ +/* Joel Klinghed. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTBZIP2_H__ +#define __FTBZIP2_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************/ + /* */ + /* <Section> */ + /* bzip2 */ + /* */ + /* <Title> */ + /* BZIP2 Streams */ + /* */ + /* <Abstract> */ + /* Using bzip2-compressed font files. */ + /* */ + /* <Description> */ + /* This section contains the declaration of Bzip2-specific functions. */ + /* */ + /*************************************************************************/ + + + /************************************************************************ + * + * @function: + * FT_Stream_OpenBzip2 + * + * @description: + * Open a new stream to parse bzip2-compressed font files. This is + * mainly used to support the compressed `*.pcf.bz2' fonts that come + * with XFree86. + * + * @input: + * stream :: + * The target embedding stream. + * + * source :: + * The source stream. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The source stream must be opened _before_ calling this function. + * + * Calling the internal function `FT_Stream_Close' on the new stream will + * *not* call `FT_Stream_Close' on the source stream. None of the stream + * objects will be released to the heap. + * + * The stream implementation is very basic and resets the decompression + * process each time seeking backwards is needed within the stream. + * + * In certain builds of the library, bzip2 compression recognition is + * automatically handled when calling @FT_New_Face or @FT_Open_Face. + * This means that if no font driver is capable of handling the raw + * compressed file, the library will try to open a bzip2 compressed stream + * from it and re-open the face with it. + * + * This function may return `FT_Err_Unimplemented_Feature' if your build + * of FreeType was not compiled with bzip2 support. + */ + FT_EXPORT( FT_Error ) + FT_Stream_OpenBzip2( FT_Stream stream, + FT_Stream source ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTBZIP2_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftcache.h b/other/freetype/include/freetype/ftcache.h new file mode 100644 index 0000000..6af5306 --- /dev/null +++ b/other/freetype/include/freetype/ftcache.h @@ -0,0 +1,1140 @@ +/***************************************************************************/ +/* */ +/* ftcache.h */ +/* */ +/* FreeType Cache subsystem (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTCACHE_H__ +#define __FTCACHE_H__ + + +#include <ft2build.h> +#include FT_GLYPH_H + + +FT_BEGIN_HEADER + + + /************************************************************************* + * + * <Section> + * cache_subsystem + * + * <Title> + * Cache Sub-System + * + * <Abstract> + * How to cache face, size, and glyph data with FreeType~2. + * + * <Description> + * This section describes the FreeType~2 cache sub-system, which is used + * to limit the number of concurrently opened @FT_Face and @FT_Size + * objects, as well as caching information like character maps and glyph + * images while limiting their maximum memory usage. + * + * Note that all types and functions begin with the `FTC_' prefix. + * + * The cache is highly portable and thus doesn't know anything about the + * fonts installed on your system, or how to access them. This implies + * the following scheme: + * + * First, available or installed font faces are uniquely identified by + * @FTC_FaceID values, provided to the cache by the client. Note that + * the cache only stores and compares these values, and doesn't try to + * interpret them in any way. + * + * Second, the cache calls, only when needed, a client-provided function + * to convert an @FTC_FaceID into a new @FT_Face object. The latter is + * then completely managed by the cache, including its termination + * through @FT_Done_Face. To monitor termination of face objects, the + * finalizer callback in the `generic' field of the @FT_Face object can + * be used, which might also be used to store the @FTC_FaceID of the + * face. + * + * Clients are free to map face IDs to anything else. The most simple + * usage is to associate them to a (pathname,face_index) pair that is + * used to call @FT_New_Face. However, more complex schemes are also + * possible. + * + * Note that for the cache to work correctly, the face ID values must be + * *persistent*, which means that the contents they point to should not + * change at runtime, or that their value should not become invalid. + * + * If this is unavoidable (e.g., when a font is uninstalled at runtime), + * you should call @FTC_Manager_RemoveFaceID as soon as possible, to let + * the cache get rid of any references to the old @FTC_FaceID it may + * keep internally. Failure to do so will lead to incorrect behaviour + * or even crashes. + * + * To use the cache, start with calling @FTC_Manager_New to create a new + * @FTC_Manager object, which models a single cache instance. You can + * then look up @FT_Face and @FT_Size objects with + * @FTC_Manager_LookupFace and @FTC_Manager_LookupSize, respectively. + * + * If you want to use the charmap caching, call @FTC_CMapCache_New, then + * later use @FTC_CMapCache_Lookup to perform the equivalent of + * @FT_Get_Char_Index, only much faster. + * + * If you want to use the @FT_Glyph caching, call @FTC_ImageCache, then + * later use @FTC_ImageCache_Lookup to retrieve the corresponding + * @FT_Glyph objects from the cache. + * + * If you need lots of small bitmaps, it is much more memory efficient + * to call @FTC_SBitCache_New followed by @FTC_SBitCache_Lookup. This + * returns @FTC_SBitRec structures, which are used to store small + * bitmaps directly. (A small bitmap is one whose metrics and + * dimensions all fit into 8-bit integers). + * + * We hope to also provide a kerning cache in the near future. + * + * + * <Order> + * FTC_Manager + * FTC_FaceID + * FTC_Face_Requester + * + * FTC_Manager_New + * FTC_Manager_Reset + * FTC_Manager_Done + * FTC_Manager_LookupFace + * FTC_Manager_LookupSize + * FTC_Manager_RemoveFaceID + * + * FTC_Node + * FTC_Node_Unref + * + * FTC_ImageCache + * FTC_ImageCache_New + * FTC_ImageCache_Lookup + * + * FTC_SBit + * FTC_SBitCache + * FTC_SBitCache_New + * FTC_SBitCache_Lookup + * + * FTC_CMapCache + * FTC_CMapCache_New + * FTC_CMapCache_Lookup + * + *************************************************************************/ + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** BASIC TYPE DEFINITIONS *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /************************************************************************* + * + * @type: FTC_FaceID + * + * @description: + * An opaque pointer type that is used to identity face objects. The + * contents of such objects is application-dependent. + * + * These pointers are typically used to point to a user-defined + * structure containing a font file path, and face index. + * + * @note: + * Never use NULL as a valid @FTC_FaceID. + * + * Face IDs are passed by the client to the cache manager, which calls, + * when needed, the @FTC_Face_Requester to translate them into new + * @FT_Face objects. + * + * If the content of a given face ID changes at runtime, or if the value + * becomes invalid (e.g., when uninstalling a font), you should + * immediately call @FTC_Manager_RemoveFaceID before any other cache + * function. + * + * Failure to do so will result in incorrect behaviour or even + * memory leaks and crashes. + */ + typedef FT_Pointer FTC_FaceID; + + + /************************************************************************ + * + * @functype: + * FTC_Face_Requester + * + * @description: + * A callback function provided by client applications. It is used by + * the cache manager to translate a given @FTC_FaceID into a new valid + * @FT_Face object, on demand. + * + * <Input> + * face_id :: + * The face ID to resolve. + * + * library :: + * A handle to a FreeType library object. + * + * req_data :: + * Application-provided request data (see note below). + * + * <Output> + * aface :: + * A new @FT_Face handle. + * + * <Return> + * FreeType error code. 0~means success. + * + * <Note> + * The third parameter `req_data' is the same as the one passed by the + * client when @FTC_Manager_New is called. + * + * The face requester should not perform funny things on the returned + * face object, like creating a new @FT_Size for it, or setting a + * transformation through @FT_Set_Transform! + */ + typedef FT_Error + (*FTC_Face_Requester)( FTC_FaceID face_id, + FT_Library library, + FT_Pointer request_data, + FT_Face* aface ); + + /* */ + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /* these macros are incompatible with LLP64, should not be used */ + +#define FT_POINTER_TO_ULONG( p ) ( (FT_ULong)(FT_Pointer)(p) ) + +#define FTC_FACE_ID_HASH( i ) \ + ((FT_UInt32)(( FT_POINTER_TO_ULONG( i ) >> 3 ) ^ \ + ( FT_POINTER_TO_ULONG( i ) << 7 ) ) ) + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** CACHE MANAGER OBJECT *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FTC_Manager */ + /* */ + /* <Description> */ + /* This object corresponds to one instance of the cache-subsystem. */ + /* It is used to cache one or more @FT_Face objects, along with */ + /* corresponding @FT_Size objects. */ + /* */ + /* The manager intentionally limits the total number of opened */ + /* @FT_Face and @FT_Size objects to control memory usage. See the */ + /* `max_faces' and `max_sizes' parameters of @FTC_Manager_New. */ + /* */ + /* The manager is also used to cache `nodes' of various types while */ + /* limiting their total memory usage. */ + /* */ + /* All limitations are enforced by keeping lists of managed objects */ + /* in most-recently-used order, and flushing old nodes to make room */ + /* for new ones. */ + /* */ + typedef struct FTC_ManagerRec_* FTC_Manager; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FTC_Node */ + /* */ + /* <Description> */ + /* An opaque handle to a cache node object. Each cache node is */ + /* reference-counted. A node with a count of~0 might be flushed */ + /* out of a full cache whenever a lookup request is performed. */ + /* */ + /* If you look up nodes, you have the ability to `acquire' them, */ + /* i.e., to increment their reference count. This will prevent the */ + /* node from being flushed out of the cache until you explicitly */ + /* `release' it (see @FTC_Node_Unref). */ + /* */ + /* See also @FTC_SBitCache_Lookup and @FTC_ImageCache_Lookup. */ + /* */ + typedef struct FTC_NodeRec_* FTC_Node; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Manager_New */ + /* */ + /* <Description> */ + /* Create a new cache manager. */ + /* */ + /* <Input> */ + /* library :: The parent FreeType library handle to use. */ + /* */ + /* max_faces :: Maximum number of opened @FT_Face objects managed by */ + /* this cache instance. Use~0 for defaults. */ + /* */ + /* max_sizes :: Maximum number of opened @FT_Size objects managed by */ + /* this cache instance. Use~0 for defaults. */ + /* */ + /* max_bytes :: Maximum number of bytes to use for cached data nodes. */ + /* Use~0 for defaults. Note that this value does not */ + /* account for managed @FT_Face and @FT_Size objects. */ + /* */ + /* requester :: An application-provided callback used to translate */ + /* face IDs into real @FT_Face objects. */ + /* */ + /* req_data :: A generic pointer that is passed to the requester */ + /* each time it is called (see @FTC_Face_Requester). */ + /* */ + /* <Output> */ + /* amanager :: A handle to a new manager object. 0~in case of */ + /* failure. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_Manager_New( FT_Library library, + FT_UInt max_faces, + FT_UInt max_sizes, + FT_ULong max_bytes, + FTC_Face_Requester requester, + FT_Pointer req_data, + FTC_Manager *amanager ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Manager_Reset */ + /* */ + /* <Description> */ + /* Empty a given cache manager. This simply gets rid of all the */ + /* currently cached @FT_Face and @FT_Size objects within the manager. */ + /* */ + /* <InOut> */ + /* manager :: A handle to the manager. */ + /* */ + FT_EXPORT( void ) + FTC_Manager_Reset( FTC_Manager manager ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Manager_Done */ + /* */ + /* <Description> */ + /* Destroy a given manager after emptying it. */ + /* */ + /* <Input> */ + /* manager :: A handle to the target cache manager object. */ + /* */ + FT_EXPORT( void ) + FTC_Manager_Done( FTC_Manager manager ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Manager_LookupFace */ + /* */ + /* <Description> */ + /* Retrieve the @FT_Face object that corresponds to a given face ID */ + /* through a cache manager. */ + /* */ + /* <Input> */ + /* manager :: A handle to the cache manager. */ + /* */ + /* face_id :: The ID of the face object. */ + /* */ + /* <Output> */ + /* aface :: A handle to the face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The returned @FT_Face object is always owned by the manager. You */ + /* should never try to discard it yourself. */ + /* */ + /* The @FT_Face object doesn't necessarily have a current size object */ + /* (i.e., face->size can be 0). If you need a specific `font size', */ + /* use @FTC_Manager_LookupSize instead. */ + /* */ + /* Never change the face's transformation matrix (i.e., never call */ + /* the @FT_Set_Transform function) on a returned face! If you need */ + /* to transform glyphs, do it yourself after glyph loading. */ + /* */ + /* When you perform a lookup, out-of-memory errors are detected */ + /* _within_ the lookup and force incremental flushes of the cache */ + /* until enough memory is released for the lookup to succeed. */ + /* */ + /* If a lookup fails with `FT_Err_Out_Of_Memory' the cache has */ + /* already been completely flushed, and still no memory was available */ + /* for the operation. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_Manager_LookupFace( FTC_Manager manager, + FTC_FaceID face_id, + FT_Face *aface ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FTC_ScalerRec */ + /* */ + /* <Description> */ + /* A structure used to describe a given character size in either */ + /* pixels or points to the cache manager. See */ + /* @FTC_Manager_LookupSize. */ + /* */ + /* <Fields> */ + /* face_id :: The source face ID. */ + /* */ + /* width :: The character width. */ + /* */ + /* height :: The character height. */ + /* */ + /* pixel :: A Boolean. If 1, the `width' and `height' fields are */ + /* interpreted as integer pixel character sizes. */ + /* Otherwise, they are expressed as 1/64th of points. */ + /* */ + /* x_res :: Only used when `pixel' is value~0 to indicate the */ + /* horizontal resolution in dpi. */ + /* */ + /* y_res :: Only used when `pixel' is value~0 to indicate the */ + /* vertical resolution in dpi. */ + /* */ + /* <Note> */ + /* This type is mainly used to retrieve @FT_Size objects through the */ + /* cache manager. */ + /* */ + typedef struct FTC_ScalerRec_ + { + FTC_FaceID face_id; + FT_UInt width; + FT_UInt height; + FT_Int pixel; + FT_UInt x_res; + FT_UInt y_res; + + } FTC_ScalerRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FTC_Scaler */ + /* */ + /* <Description> */ + /* A handle to an @FTC_ScalerRec structure. */ + /* */ + typedef struct FTC_ScalerRec_* FTC_Scaler; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Manager_LookupSize */ + /* */ + /* <Description> */ + /* Retrieve the @FT_Size object that corresponds to a given */ + /* @FTC_ScalerRec pointer through a cache manager. */ + /* */ + /* <Input> */ + /* manager :: A handle to the cache manager. */ + /* */ + /* scaler :: A scaler handle. */ + /* */ + /* <Output> */ + /* asize :: A handle to the size object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The returned @FT_Size object is always owned by the manager. You */ + /* should never try to discard it by yourself. */ + /* */ + /* You can access the parent @FT_Face object simply as `size->face' */ + /* if you need it. Note that this object is also owned by the */ + /* manager. */ + /* */ + /* <Note> */ + /* When you perform a lookup, out-of-memory errors are detected */ + /* _within_ the lookup and force incremental flushes of the cache */ + /* until enough memory is released for the lookup to succeed. */ + /* */ + /* If a lookup fails with `FT_Err_Out_Of_Memory' the cache has */ + /* already been completely flushed, and still no memory is available */ + /* for the operation. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_Manager_LookupSize( FTC_Manager manager, + FTC_Scaler scaler, + FT_Size *asize ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_Node_Unref */ + /* */ + /* <Description> */ + /* Decrement a cache node's internal reference count. When the count */ + /* reaches 0, it is not destroyed but becomes eligible for subsequent */ + /* cache flushes. */ + /* */ + /* <Input> */ + /* node :: The cache node handle. */ + /* */ + /* manager :: The cache manager handle. */ + /* */ + FT_EXPORT( void ) + FTC_Node_Unref( FTC_Node node, + FTC_Manager manager ); + + + /************************************************************************* + * + * @function: + * FTC_Manager_RemoveFaceID + * + * @description: + * A special function used to indicate to the cache manager that + * a given @FTC_FaceID is no longer valid, either because its + * content changed, or because it was deallocated or uninstalled. + * + * @input: + * manager :: + * The cache manager handle. + * + * face_id :: + * The @FTC_FaceID to be removed. + * + * @note: + * This function flushes all nodes from the cache corresponding to this + * `face_id', with the exception of nodes with a non-null reference + * count. + * + * Such nodes are however modified internally so as to never appear + * in later lookups with the same `face_id' value, and to be immediately + * destroyed when released by all their users. + * + */ + FT_EXPORT( void ) + FTC_Manager_RemoveFaceID( FTC_Manager manager, + FTC_FaceID face_id ); + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* cache_subsystem */ + /* */ + /*************************************************************************/ + + /************************************************************************* + * + * @type: + * FTC_CMapCache + * + * @description: + * An opaque handle used to model a charmap cache. This cache is to + * hold character codes -> glyph indices mappings. + * + */ + typedef struct FTC_CMapCacheRec_* FTC_CMapCache; + + + /************************************************************************* + * + * @function: + * FTC_CMapCache_New + * + * @description: + * Create a new charmap cache. + * + * @input: + * manager :: + * A handle to the cache manager. + * + * @output: + * acache :: + * A new cache handle. NULL in case of error. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * Like all other caches, this one will be destroyed with the cache + * manager. + * + */ + FT_EXPORT( FT_Error ) + FTC_CMapCache_New( FTC_Manager manager, + FTC_CMapCache *acache ); + + + /************************************************************************ + * + * @function: + * FTC_CMapCache_Lookup + * + * @description: + * Translate a character code into a glyph index, using the charmap + * cache. + * + * @input: + * cache :: + * A charmap cache handle. + * + * face_id :: + * The source face ID. + * + * cmap_index :: + * The index of the charmap in the source face. Any negative value + * means to use the cache @FT_Face's default charmap. + * + * char_code :: + * The character code (in the corresponding charmap). + * + * @return: + * Glyph index. 0~means `no glyph'. + * + */ + FT_EXPORT( FT_UInt ) + FTC_CMapCache_Lookup( FTC_CMapCache cache, + FTC_FaceID face_id, + FT_Int cmap_index, + FT_UInt32 char_code ); + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* cache_subsystem */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** IMAGE CACHE OBJECT *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /************************************************************************* + * + * @struct: + * FTC_ImageTypeRec + * + * @description: + * A structure used to model the type of images in a glyph cache. + * + * @fields: + * face_id :: + * The face ID. + * + * width :: + * The width in pixels. + * + * height :: + * The height in pixels. + * + * flags :: + * The load flags, as in @FT_Load_Glyph. + * + */ + typedef struct FTC_ImageTypeRec_ + { + FTC_FaceID face_id; + FT_Int width; + FT_Int height; + FT_Int32 flags; + + } FTC_ImageTypeRec; + + + /************************************************************************* + * + * @type: + * FTC_ImageType + * + * @description: + * A handle to an @FTC_ImageTypeRec structure. + * + */ + typedef struct FTC_ImageTypeRec_* FTC_ImageType; + + + /* */ + + +#define FTC_IMAGE_TYPE_COMPARE( d1, d2 ) \ + ( (d1)->face_id == (d2)->face_id && \ + (d1)->width == (d2)->width && \ + (d1)->flags == (d2)->flags ) + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /* this macro is incompatible with LLP64, should not be used */ + +#define FTC_IMAGE_TYPE_HASH( d ) \ + (FT_UFast)( FTC_FACE_ID_HASH( (d)->face_id ) ^ \ + ( (d)->width << 8 ) ^ (d)->height ^ \ + ( (d)->flags << 4 ) ) + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FTC_ImageCache */ + /* */ + /* <Description> */ + /* A handle to an glyph image cache object. They are designed to */ + /* hold many distinct glyph images while not exceeding a certain */ + /* memory threshold. */ + /* */ + typedef struct FTC_ImageCacheRec_* FTC_ImageCache; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_ImageCache_New */ + /* */ + /* <Description> */ + /* Create a new glyph image cache. */ + /* */ + /* <Input> */ + /* manager :: The parent manager for the image cache. */ + /* */ + /* <Output> */ + /* acache :: A handle to the new glyph image cache object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_ImageCache_New( FTC_Manager manager, + FTC_ImageCache *acache ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_ImageCache_Lookup */ + /* */ + /* <Description> */ + /* Retrieve a given glyph image from a glyph image cache. */ + /* */ + /* <Input> */ + /* cache :: A handle to the source glyph image cache. */ + /* */ + /* type :: A pointer to a glyph image type descriptor. */ + /* */ + /* gindex :: The glyph index to retrieve. */ + /* */ + /* <Output> */ + /* aglyph :: The corresponding @FT_Glyph object. 0~in case of */ + /* failure. */ + /* */ + /* anode :: Used to return the address of of the corresponding cache */ + /* node after incrementing its reference count (see note */ + /* below). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The returned glyph is owned and managed by the glyph image cache. */ + /* Never try to transform or discard it manually! You can however */ + /* create a copy with @FT_Glyph_Copy and modify the new one. */ + /* */ + /* If `anode' is _not_ NULL, it receives the address of the cache */ + /* node containing the glyph image, after increasing its reference */ + /* count. This ensures that the node (as well as the @FT_Glyph) will */ + /* always be kept in the cache until you call @FTC_Node_Unref to */ + /* `release' it. */ + /* */ + /* If `anode' is NULL, the cache node is left unchanged, which means */ + /* that the @FT_Glyph could be flushed out of the cache on the next */ + /* call to one of the caching sub-system APIs. Don't assume that it */ + /* is persistent! */ + /* */ + FT_EXPORT( FT_Error ) + FTC_ImageCache_Lookup( FTC_ImageCache cache, + FTC_ImageType type, + FT_UInt gindex, + FT_Glyph *aglyph, + FTC_Node *anode ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_ImageCache_LookupScaler */ + /* */ + /* <Description> */ + /* A variant of @FTC_ImageCache_Lookup that uses an @FTC_ScalerRec */ + /* to specify the face ID and its size. */ + /* */ + /* <Input> */ + /* cache :: A handle to the source glyph image cache. */ + /* */ + /* scaler :: A pointer to a scaler descriptor. */ + /* */ + /* load_flags :: The corresponding load flags. */ + /* */ + /* gindex :: The glyph index to retrieve. */ + /* */ + /* <Output> */ + /* aglyph :: The corresponding @FT_Glyph object. 0~in case of */ + /* failure. */ + /* */ + /* anode :: Used to return the address of of the corresponding */ + /* cache node after incrementing its reference count */ + /* (see note below). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The returned glyph is owned and managed by the glyph image cache. */ + /* Never try to transform or discard it manually! You can however */ + /* create a copy with @FT_Glyph_Copy and modify the new one. */ + /* */ + /* If `anode' is _not_ NULL, it receives the address of the cache */ + /* node containing the glyph image, after increasing its reference */ + /* count. This ensures that the node (as well as the @FT_Glyph) will */ + /* always be kept in the cache until you call @FTC_Node_Unref to */ + /* `release' it. */ + /* */ + /* If `anode' is NULL, the cache node is left unchanged, which means */ + /* that the @FT_Glyph could be flushed out of the cache on the next */ + /* call to one of the caching sub-system APIs. Don't assume that it */ + /* is persistent! */ + /* */ + /* Calls to @FT_Set_Char_Size and friends have no effect on cached */ + /* glyphs; you should always use the FreeType cache API instead. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_ImageCache_LookupScaler( FTC_ImageCache cache, + FTC_Scaler scaler, + FT_ULong load_flags, + FT_UInt gindex, + FT_Glyph *aglyph, + FTC_Node *anode ); + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FTC_SBit */ + /* */ + /* <Description> */ + /* A handle to a small bitmap descriptor. See the @FTC_SBitRec */ + /* structure for details. */ + /* */ + typedef struct FTC_SBitRec_* FTC_SBit; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FTC_SBitRec */ + /* */ + /* <Description> */ + /* A very compact structure used to describe a small glyph bitmap. */ + /* */ + /* <Fields> */ + /* width :: The bitmap width in pixels. */ + /* */ + /* height :: The bitmap height in pixels. */ + /* */ + /* left :: The horizontal distance from the pen position to the */ + /* left bitmap border (a.k.a. `left side bearing', or */ + /* `lsb'). */ + /* */ + /* top :: The vertical distance from the pen position (on the */ + /* baseline) to the upper bitmap border (a.k.a. `top */ + /* side bearing'). The distance is positive for upwards */ + /* y~coordinates. */ + /* */ + /* format :: The format of the glyph bitmap (monochrome or gray). */ + /* */ + /* max_grays :: Maximum gray level value (in the range 1 to~255). */ + /* */ + /* pitch :: The number of bytes per bitmap line. May be positive */ + /* or negative. */ + /* */ + /* xadvance :: The horizontal advance width in pixels. */ + /* */ + /* yadvance :: The vertical advance height in pixels. */ + /* */ + /* buffer :: A pointer to the bitmap pixels. */ + /* */ + typedef struct FTC_SBitRec_ + { + FT_Byte width; + FT_Byte height; + FT_Char left; + FT_Char top; + + FT_Byte format; + FT_Byte max_grays; + FT_Short pitch; + FT_Char xadvance; + FT_Char yadvance; + + FT_Byte* buffer; + + } FTC_SBitRec; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FTC_SBitCache */ + /* */ + /* <Description> */ + /* A handle to a small bitmap cache. These are special cache objects */ + /* used to store small glyph bitmaps (and anti-aliased pixmaps) in a */ + /* much more efficient way than the traditional glyph image cache */ + /* implemented by @FTC_ImageCache. */ + /* */ + typedef struct FTC_SBitCacheRec_* FTC_SBitCache; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_SBitCache_New */ + /* */ + /* <Description> */ + /* Create a new cache to store small glyph bitmaps. */ + /* */ + /* <Input> */ + /* manager :: A handle to the source cache manager. */ + /* */ + /* <Output> */ + /* acache :: A handle to the new sbit cache. NULL in case of error. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FTC_SBitCache_New( FTC_Manager manager, + FTC_SBitCache *acache ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_SBitCache_Lookup */ + /* */ + /* <Description> */ + /* Look up a given small glyph bitmap in a given sbit cache and */ + /* `lock' it to prevent its flushing from the cache until needed. */ + /* */ + /* <Input> */ + /* cache :: A handle to the source sbit cache. */ + /* */ + /* type :: A pointer to the glyph image type descriptor. */ + /* */ + /* gindex :: The glyph index. */ + /* */ + /* <Output> */ + /* sbit :: A handle to a small bitmap descriptor. */ + /* */ + /* anode :: Used to return the address of of the corresponding cache */ + /* node after incrementing its reference count (see note */ + /* below). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The small bitmap descriptor and its bit buffer are owned by the */ + /* cache and should never be freed by the application. They might */ + /* as well disappear from memory on the next cache lookup, so don't */ + /* treat them as persistent data. */ + /* */ + /* The descriptor's `buffer' field is set to~0 to indicate a missing */ + /* glyph bitmap. */ + /* */ + /* If `anode' is _not_ NULL, it receives the address of the cache */ + /* node containing the bitmap, after increasing its reference count. */ + /* This ensures that the node (as well as the image) will always be */ + /* kept in the cache until you call @FTC_Node_Unref to `release' it. */ + /* */ + /* If `anode' is NULL, the cache node is left unchanged, which means */ + /* that the bitmap could be flushed out of the cache on the next */ + /* call to one of the caching sub-system APIs. Don't assume that it */ + /* is persistent! */ + /* */ + FT_EXPORT( FT_Error ) + FTC_SBitCache_Lookup( FTC_SBitCache cache, + FTC_ImageType type, + FT_UInt gindex, + FTC_SBit *sbit, + FTC_Node *anode ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FTC_SBitCache_LookupScaler */ + /* */ + /* <Description> */ + /* A variant of @FTC_SBitCache_Lookup that uses an @FTC_ScalerRec */ + /* to specify the face ID and its size. */ + /* */ + /* <Input> */ + /* cache :: A handle to the source sbit cache. */ + /* */ + /* scaler :: A pointer to the scaler descriptor. */ + /* */ + /* load_flags :: The corresponding load flags. */ + /* */ + /* gindex :: The glyph index. */ + /* */ + /* <Output> */ + /* sbit :: A handle to a small bitmap descriptor. */ + /* */ + /* anode :: Used to return the address of of the corresponding */ + /* cache node after incrementing its reference count */ + /* (see note below). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The small bitmap descriptor and its bit buffer are owned by the */ + /* cache and should never be freed by the application. They might */ + /* as well disappear from memory on the next cache lookup, so don't */ + /* treat them as persistent data. */ + /* */ + /* The descriptor's `buffer' field is set to~0 to indicate a missing */ + /* glyph bitmap. */ + /* */ + /* If `anode' is _not_ NULL, it receives the address of the cache */ + /* node containing the bitmap, after increasing its reference count. */ + /* This ensures that the node (as well as the image) will always be */ + /* kept in the cache until you call @FTC_Node_Unref to `release' it. */ + /* */ + /* If `anode' is NULL, the cache node is left unchanged, which means */ + /* that the bitmap could be flushed out of the cache on the next */ + /* call to one of the caching sub-system APIs. Don't assume that it */ + /* is persistent! */ + /* */ + FT_EXPORT( FT_Error ) + FTC_SBitCache_LookupScaler( FTC_SBitCache cache, + FTC_Scaler scaler, + FT_ULong load_flags, + FT_UInt gindex, + FTC_SBit *sbit, + FTC_Node *anode ); + + + /* */ + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /*@***********************************************************************/ + /* */ + /* <Struct> */ + /* FTC_FontRec */ + /* */ + /* <Description> */ + /* A simple structure used to describe a given `font' to the cache */ + /* manager. Note that a `font' is the combination of a given face */ + /* with a given character size. */ + /* */ + /* <Fields> */ + /* face_id :: The ID of the face to use. */ + /* */ + /* pix_width :: The character width in integer pixels. */ + /* */ + /* pix_height :: The character height in integer pixels. */ + /* */ + typedef struct FTC_FontRec_ + { + FTC_FaceID face_id; + FT_UShort pix_width; + FT_UShort pix_height; + + } FTC_FontRec; + + + /* */ + + +#define FTC_FONT_COMPARE( f1, f2 ) \ + ( (f1)->face_id == (f2)->face_id && \ + (f1)->pix_width == (f2)->pix_width && \ + (f1)->pix_height == (f2)->pix_height ) + + /* this macro is incompatible with LLP64, should not be used */ +#define FTC_FONT_HASH( f ) \ + (FT_UInt32)( FTC_FACE_ID_HASH((f)->face_id) ^ \ + ((f)->pix_width << 8) ^ \ + ((f)->pix_height) ) + + typedef FTC_FontRec* FTC_Font; + + + FT_EXPORT( FT_Error ) + FTC_Manager_Lookup_Face( FTC_Manager manager, + FTC_FaceID face_id, + FT_Face *aface ); + + FT_EXPORT( FT_Error ) + FTC_Manager_Lookup_Size( FTC_Manager manager, + FTC_Font font, + FT_Face *aface, + FT_Size *asize ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /* */ + +FT_END_HEADER + +#endif /* __FTCACHE_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftchapters.h b/other/freetype/include/freetype/ftchapters.h new file mode 100644 index 0000000..6cdf54e --- /dev/null +++ b/other/freetype/include/freetype/ftchapters.h @@ -0,0 +1,104 @@ +/***************************************************************************/ +/* */ +/* This file defines the structure of the FreeType reference. */ +/* It is used by the python script which generates the HTML files. */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* <Chapter> */ +/* general_remarks */ +/* */ +/* <Title> */ +/* General Remarks */ +/* */ +/* <Sections> */ +/* user_allocation */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* <Chapter> */ +/* core_api */ +/* */ +/* <Title> */ +/* Core API */ +/* */ +/* <Sections> */ +/* version */ +/* basic_types */ +/* base_interface */ +/* glyph_variants */ +/* glyph_management */ +/* mac_specific */ +/* sizes_management */ +/* header_file_macros */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* <Chapter> */ +/* format_specific */ +/* */ +/* <Title> */ +/* Format-Specific API */ +/* */ +/* <Sections> */ +/* multiple_masters */ +/* truetype_tables */ +/* type1_tables */ +/* sfnt_names */ +/* bdf_fonts */ +/* cid_fonts */ +/* pfr_fonts */ +/* winfnt_fonts */ +/* font_formats */ +/* gasp_table */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* <Chapter> */ +/* cache_subsystem */ +/* */ +/* <Title> */ +/* Cache Sub-System */ +/* */ +/* <Sections> */ +/* cache_subsystem */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* <Chapter> */ +/* support_api */ +/* */ +/* <Title> */ +/* Support API */ +/* */ +/* <Sections> */ +/* computations */ +/* list_processing */ +/* outline_processing */ +/* quick_advance */ +/* bitmap_handling */ +/* raster */ +/* glyph_stroker */ +/* system_interface */ +/* module_management */ +/* gzip */ +/* lzw */ +/* bzip2 */ +/* lcd_filtering */ +/* */ +/***************************************************************************/ diff --git a/other/freetype/include/freetype/ftcid.h b/other/freetype/include/freetype/ftcid.h new file mode 100644 index 0000000..203a30c --- /dev/null +++ b/other/freetype/include/freetype/ftcid.h @@ -0,0 +1,166 @@ +/***************************************************************************/ +/* */ +/* ftcid.h */ +/* */ +/* FreeType API for accessing CID font information (specification). */ +/* */ +/* Copyright 2007, 2009 by Dereg Clegg, Michael Toftdal. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTCID_H__ +#define __FTCID_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* cid_fonts */ + /* */ + /* <Title> */ + /* CID Fonts */ + /* */ + /* <Abstract> */ + /* CID-keyed font specific API. */ + /* */ + /* <Description> */ + /* This section contains the declaration of CID-keyed font specific */ + /* functions. */ + /* */ + /*************************************************************************/ + + + /********************************************************************** + * + * @function: + * FT_Get_CID_Registry_Ordering_Supplement + * + * @description: + * Retrieve the Registry/Ordering/Supplement triple (also known as the + * "R/O/S") from a CID-keyed font. + * + * @input: + * face :: + * A handle to the input face. + * + * @output: + * registry :: + * The registry, as a C~string, owned by the face. + * + * ordering :: + * The ordering, as a C~string, owned by the face. + * + * supplement :: + * The supplement. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with CID faces, returning an error + * otherwise. + * + * @since: + * 2.3.6 + */ + FT_EXPORT( FT_Error ) + FT_Get_CID_Registry_Ordering_Supplement( FT_Face face, + const char* *registry, + const char* *ordering, + FT_Int *supplement); + + + /********************************************************************** + * + * @function: + * FT_Get_CID_Is_Internally_CID_Keyed + * + * @description: + * Retrieve the type of the input face, CID keyed or not. In + * constrast to the @FT_IS_CID_KEYED macro this function returns + * successfully also for CID-keyed fonts in an SNFT wrapper. + * + * @input: + * face :: + * A handle to the input face. + * + * @output: + * is_cid :: + * The type of the face as an @FT_Bool. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with CID faces and OpenType fonts, + * returning an error otherwise. + * + * @since: + * 2.3.9 + */ + FT_EXPORT( FT_Error ) + FT_Get_CID_Is_Internally_CID_Keyed( FT_Face face, + FT_Bool *is_cid ); + + + /********************************************************************** + * + * @function: + * FT_Get_CID_From_Glyph_Index + * + * @description: + * Retrieve the CID of the input glyph index. + * + * @input: + * face :: + * A handle to the input face. + * + * glyph_index :: + * The input glyph index. + * + * @output: + * cid :: + * The CID as an @FT_UInt. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with CID faces and OpenType fonts, + * returning an error otherwise. + * + * @since: + * 2.3.9 + */ + FT_EXPORT( FT_Error ) + FT_Get_CID_From_Glyph_Index( FT_Face face, + FT_UInt glyph_index, + FT_UInt *cid ); + + /* */ + +FT_END_HEADER + +#endif /* __FTCID_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/fterrdef.h b/other/freetype/include/freetype/fterrdef.h new file mode 100644 index 0000000..d4e7287 --- /dev/null +++ b/other/freetype/include/freetype/fterrdef.h @@ -0,0 +1,243 @@ +/***************************************************************************/ +/* */ +/* fterrdef.h */ +/* */ +/* FreeType error codes (specification). */ +/* */ +/* Copyright 2002, 2004, 2006, 2007, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** LIST OF ERROR CODES/MESSAGES *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + + + /* You need to define both FT_ERRORDEF_ and FT_NOERRORDEF_ before */ + /* including this file. */ + + + /* generic errors */ + + FT_NOERRORDEF_( Ok, 0x00, \ + "no error" ) + + FT_ERRORDEF_( Cannot_Open_Resource, 0x01, \ + "cannot open resource" ) + FT_ERRORDEF_( Unknown_File_Format, 0x02, \ + "unknown file format" ) + FT_ERRORDEF_( Invalid_File_Format, 0x03, \ + "broken file" ) + FT_ERRORDEF_( Invalid_Version, 0x04, \ + "invalid FreeType version" ) + FT_ERRORDEF_( Lower_Module_Version, 0x05, \ + "module version is too low" ) + FT_ERRORDEF_( Invalid_Argument, 0x06, \ + "invalid argument" ) + FT_ERRORDEF_( Unimplemented_Feature, 0x07, \ + "unimplemented feature" ) + FT_ERRORDEF_( Invalid_Table, 0x08, \ + "broken table" ) + FT_ERRORDEF_( Invalid_Offset, 0x09, \ + "broken offset within table" ) + FT_ERRORDEF_( Array_Too_Large, 0x0A, \ + "array allocation size too large" ) + + /* glyph/character errors */ + + FT_ERRORDEF_( Invalid_Glyph_Index, 0x10, \ + "invalid glyph index" ) + FT_ERRORDEF_( Invalid_Character_Code, 0x11, \ + "invalid character code" ) + FT_ERRORDEF_( Invalid_Glyph_Format, 0x12, \ + "unsupported glyph image format" ) + FT_ERRORDEF_( Cannot_Render_Glyph, 0x13, \ + "cannot render this glyph format" ) + FT_ERRORDEF_( Invalid_Outline, 0x14, \ + "invalid outline" ) + FT_ERRORDEF_( Invalid_Composite, 0x15, \ + "invalid composite glyph" ) + FT_ERRORDEF_( Too_Many_Hints, 0x16, \ + "too many hints" ) + FT_ERRORDEF_( Invalid_Pixel_Size, 0x17, \ + "invalid pixel size" ) + + /* handle errors */ + + FT_ERRORDEF_( Invalid_Handle, 0x20, \ + "invalid object handle" ) + FT_ERRORDEF_( Invalid_Library_Handle, 0x21, \ + "invalid library handle" ) + FT_ERRORDEF_( Invalid_Driver_Handle, 0x22, \ + "invalid module handle" ) + FT_ERRORDEF_( Invalid_Face_Handle, 0x23, \ + "invalid face handle" ) + FT_ERRORDEF_( Invalid_Size_Handle, 0x24, \ + "invalid size handle" ) + FT_ERRORDEF_( Invalid_Slot_Handle, 0x25, \ + "invalid glyph slot handle" ) + FT_ERRORDEF_( Invalid_CharMap_Handle, 0x26, \ + "invalid charmap handle" ) + FT_ERRORDEF_( Invalid_Cache_Handle, 0x27, \ + "invalid cache manager handle" ) + FT_ERRORDEF_( Invalid_Stream_Handle, 0x28, \ + "invalid stream handle" ) + + /* driver errors */ + + FT_ERRORDEF_( Too_Many_Drivers, 0x30, \ + "too many modules" ) + FT_ERRORDEF_( Too_Many_Extensions, 0x31, \ + "too many extensions" ) + + /* memory errors */ + + FT_ERRORDEF_( Out_Of_Memory, 0x40, \ + "out of memory" ) + FT_ERRORDEF_( Unlisted_Object, 0x41, \ + "unlisted object" ) + + /* stream errors */ + + FT_ERRORDEF_( Cannot_Open_Stream, 0x51, \ + "cannot open stream" ) + FT_ERRORDEF_( Invalid_Stream_Seek, 0x52, \ + "invalid stream seek" ) + FT_ERRORDEF_( Invalid_Stream_Skip, 0x53, \ + "invalid stream skip" ) + FT_ERRORDEF_( Invalid_Stream_Read, 0x54, \ + "invalid stream read" ) + FT_ERRORDEF_( Invalid_Stream_Operation, 0x55, \ + "invalid stream operation" ) + FT_ERRORDEF_( Invalid_Frame_Operation, 0x56, \ + "invalid frame operation" ) + FT_ERRORDEF_( Nested_Frame_Access, 0x57, \ + "nested frame access" ) + FT_ERRORDEF_( Invalid_Frame_Read, 0x58, \ + "invalid frame read" ) + + /* raster errors */ + + FT_ERRORDEF_( Raster_Uninitialized, 0x60, \ + "raster uninitialized" ) + FT_ERRORDEF_( Raster_Corrupted, 0x61, \ + "raster corrupted" ) + FT_ERRORDEF_( Raster_Overflow, 0x62, \ + "raster overflow" ) + FT_ERRORDEF_( Raster_Negative_Height, 0x63, \ + "negative height while rastering" ) + + /* cache errors */ + + FT_ERRORDEF_( Too_Many_Caches, 0x70, \ + "too many registered caches" ) + + /* TrueType and SFNT errors */ + + FT_ERRORDEF_( Invalid_Opcode, 0x80, \ + "invalid opcode" ) + FT_ERRORDEF_( Too_Few_Arguments, 0x81, \ + "too few arguments" ) + FT_ERRORDEF_( Stack_Overflow, 0x82, \ + "stack overflow" ) + FT_ERRORDEF_( Code_Overflow, 0x83, \ + "code overflow" ) + FT_ERRORDEF_( Bad_Argument, 0x84, \ + "bad argument" ) + FT_ERRORDEF_( Divide_By_Zero, 0x85, \ + "division by zero" ) + FT_ERRORDEF_( Invalid_Reference, 0x86, \ + "invalid reference" ) + FT_ERRORDEF_( Debug_OpCode, 0x87, \ + "found debug opcode" ) + FT_ERRORDEF_( ENDF_In_Exec_Stream, 0x88, \ + "found ENDF opcode in execution stream" ) + FT_ERRORDEF_( Nested_DEFS, 0x89, \ + "nested DEFS" ) + FT_ERRORDEF_( Invalid_CodeRange, 0x8A, \ + "invalid code range" ) + FT_ERRORDEF_( Execution_Too_Long, 0x8B, \ + "execution context too long" ) + FT_ERRORDEF_( Too_Many_Function_Defs, 0x8C, \ + "too many function definitions" ) + FT_ERRORDEF_( Too_Many_Instruction_Defs, 0x8D, \ + "too many instruction definitions" ) + FT_ERRORDEF_( Table_Missing, 0x8E, \ + "SFNT font table missing" ) + FT_ERRORDEF_( Horiz_Header_Missing, 0x8F, \ + "horizontal header (hhea) table missing" ) + FT_ERRORDEF_( Locations_Missing, 0x90, \ + "locations (loca) table missing" ) + FT_ERRORDEF_( Name_Table_Missing, 0x91, \ + "name table missing" ) + FT_ERRORDEF_( CMap_Table_Missing, 0x92, \ + "character map (cmap) table missing" ) + FT_ERRORDEF_( Hmtx_Table_Missing, 0x93, \ + "horizontal metrics (hmtx) table missing" ) + FT_ERRORDEF_( Post_Table_Missing, 0x94, \ + "PostScript (post) table missing" ) + FT_ERRORDEF_( Invalid_Horiz_Metrics, 0x95, \ + "invalid horizontal metrics" ) + FT_ERRORDEF_( Invalid_CharMap_Format, 0x96, \ + "invalid character map (cmap) format" ) + FT_ERRORDEF_( Invalid_PPem, 0x97, \ + "invalid ppem value" ) + FT_ERRORDEF_( Invalid_Vert_Metrics, 0x98, \ + "invalid vertical metrics" ) + FT_ERRORDEF_( Could_Not_Find_Context, 0x99, \ + "could not find context" ) + FT_ERRORDEF_( Invalid_Post_Table_Format, 0x9A, \ + "invalid PostScript (post) table format" ) + FT_ERRORDEF_( Invalid_Post_Table, 0x9B, \ + "invalid PostScript (post) table" ) + + /* CFF, CID, and Type 1 errors */ + + FT_ERRORDEF_( Syntax_Error, 0xA0, \ + "opcode syntax error" ) + FT_ERRORDEF_( Stack_Underflow, 0xA1, \ + "argument stack underflow" ) + FT_ERRORDEF_( Ignore, 0xA2, \ + "ignore" ) + FT_ERRORDEF_( No_Unicode_Glyph_Name, 0xA3, \ + "no Unicode glyph name found" ) + + /* BDF errors */ + + FT_ERRORDEF_( Missing_Startfont_Field, 0xB0, \ + "`STARTFONT' field missing" ) + FT_ERRORDEF_( Missing_Font_Field, 0xB1, \ + "`FONT' field missing" ) + FT_ERRORDEF_( Missing_Size_Field, 0xB2, \ + "`SIZE' field missing" ) + FT_ERRORDEF_( Missing_Fontboundingbox_Field, 0xB3, \ + "`FONTBOUNDINGBOX' field missing" ) + FT_ERRORDEF_( Missing_Chars_Field, 0xB4, \ + "`CHARS' field missing" ) + FT_ERRORDEF_( Missing_Startchar_Field, 0xB5, \ + "`STARTCHAR' field missing" ) + FT_ERRORDEF_( Missing_Encoding_Field, 0xB6, \ + "`ENCODING' field missing" ) + FT_ERRORDEF_( Missing_Bbx_Field, 0xB7, \ + "`BBX' field missing" ) + FT_ERRORDEF_( Bbx_Too_Big, 0xB8, \ + "`BBX' too big" ) + FT_ERRORDEF_( Corrupted_Font_Header, 0xB9, \ + "Font header corrupted or missing fields" ) + FT_ERRORDEF_( Corrupted_Font_Glyphs, 0xBA, \ + "Font glyphs corrupted or missing fields" ) + + +/* END */ diff --git a/other/freetype/include/freetype/fterrors.h b/other/freetype/include/freetype/fterrors.h new file mode 100644 index 0000000..6600dad --- /dev/null +++ b/other/freetype/include/freetype/fterrors.h @@ -0,0 +1,206 @@ +/***************************************************************************/ +/* */ +/* fterrors.h */ +/* */ +/* FreeType error code handling (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2004, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This special header file is used to define the handling of FT2 */ + /* enumeration constants. It can also be used to generate error message */ + /* strings with a small macro trick explained below. */ + /* */ + /* I - Error Formats */ + /* ----------------- */ + /* */ + /* The configuration macro FT_CONFIG_OPTION_USE_MODULE_ERRORS can be */ + /* defined in ftoption.h in order to make the higher byte indicate */ + /* the module where the error has happened (this is not compatible */ + /* with standard builds of FreeType 2). You can then use the macro */ + /* FT_ERROR_BASE macro to extract the generic error code from an */ + /* FT_Error value. */ + /* */ + /* */ + /* II - Error Message strings */ + /* -------------------------- */ + /* */ + /* The error definitions below are made through special macros that */ + /* allow client applications to build a table of error message strings */ + /* if they need it. The strings are not included in a normal build of */ + /* FreeType 2 to save space (most client applications do not use */ + /* them). */ + /* */ + /* To do so, you have to define the following macros before including */ + /* this file: */ + /* */ + /* FT_ERROR_START_LIST :: */ + /* This macro is called before anything else to define the start of */ + /* the error list. It is followed by several FT_ERROR_DEF calls */ + /* (see below). */ + /* */ + /* FT_ERROR_DEF( e, v, s ) :: */ + /* This macro is called to define one single error. */ + /* `e' is the error code identifier (e.g. FT_Err_Invalid_Argument). */ + /* `v' is the error numerical value. */ + /* `s' is the corresponding error string. */ + /* */ + /* FT_ERROR_END_LIST :: */ + /* This macro ends the list. */ + /* */ + /* Additionally, you have to undefine __FTERRORS_H__ before #including */ + /* this file. */ + /* */ + /* Here is a simple example: */ + /* */ + /* { */ + /* #undef __FTERRORS_H__ */ + /* #define FT_ERRORDEF( e, v, s ) { e, s }, */ + /* #define FT_ERROR_START_LIST { */ + /* #define FT_ERROR_END_LIST { 0, 0 } }; */ + /* */ + /* const struct */ + /* { */ + /* int err_code; */ + /* const char* err_msg; */ + /* } ft_errors[] = */ + /* */ + /* #include FT_ERRORS_H */ + /* } */ + /* */ + /*************************************************************************/ + + +#ifndef __FTERRORS_H__ +#define __FTERRORS_H__ + + + /* include module base error codes */ +#include FT_MODULE_ERRORS_H + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** SETUP MACROS *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + + +#undef FT_NEED_EXTERN_C + +#undef FT_ERR_XCAT +#undef FT_ERR_CAT + +#define FT_ERR_XCAT( x, y ) x ## y +#define FT_ERR_CAT( x, y ) FT_ERR_XCAT( x, y ) + + + /* FT_ERR_PREFIX is used as a prefix for error identifiers. */ + /* By default, we use `FT_Err_'. */ + /* */ +#ifndef FT_ERR_PREFIX +#define FT_ERR_PREFIX FT_Err_ +#endif + + + /* FT_ERR_BASE is used as the base for module-specific errors. */ + /* */ +#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS + +#ifndef FT_ERR_BASE +#define FT_ERR_BASE FT_Mod_Err_Base +#endif + +#else + +#undef FT_ERR_BASE +#define FT_ERR_BASE 0 + +#endif /* FT_CONFIG_OPTION_USE_MODULE_ERRORS */ + + + /* If FT_ERRORDEF is not defined, we need to define a simple */ + /* enumeration type. */ + /* */ +#ifndef FT_ERRORDEF + +#define FT_ERRORDEF( e, v, s ) e = v, +#define FT_ERROR_START_LIST enum { +#define FT_ERROR_END_LIST FT_ERR_CAT( FT_ERR_PREFIX, Max ) }; + +#ifdef __cplusplus +#define FT_NEED_EXTERN_C + extern "C" { +#endif + +#endif /* !FT_ERRORDEF */ + + + /* this macro is used to define an error */ +#define FT_ERRORDEF_( e, v, s ) \ + FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v + FT_ERR_BASE, s ) + + /* this is only used for <module>_Err_Ok, which must be 0! */ +#define FT_NOERRORDEF_( e, v, s ) \ + FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v, s ) + + +#ifdef FT_ERROR_START_LIST + FT_ERROR_START_LIST +#endif + + + /* now include the error codes */ +#include FT_ERROR_DEFINITIONS_H + + +#ifdef FT_ERROR_END_LIST + FT_ERROR_END_LIST +#endif + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** SIMPLE CLEANUP *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + +#ifdef FT_NEED_EXTERN_C + } +#endif + +#undef FT_ERROR_START_LIST +#undef FT_ERROR_END_LIST + +#undef FT_ERRORDEF +#undef FT_ERRORDEF_ +#undef FT_NOERRORDEF_ + +#undef FT_NEED_EXTERN_C +#undef FT_ERR_CONCAT +#undef FT_ERR_BASE + + /* FT_KEEP_ERR_PREFIX is needed for ftvalid.h */ +#ifndef FT_KEEP_ERR_PREFIX +#undef FT_ERR_PREFIX +#endif + +#endif /* __FTERRORS_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftgasp.h b/other/freetype/include/freetype/ftgasp.h new file mode 100644 index 0000000..5e978e5 --- /dev/null +++ b/other/freetype/include/freetype/ftgasp.h @@ -0,0 +1,128 @@ +/***************************************************************************/ +/* */ +/* ftgasp.h */ +/* */ +/* Access of TrueType's `gasp' table (specification). */ +/* */ +/* Copyright 2007, 2008, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef _FT_GASP_H_ +#define _FT_GASP_H_ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + + /*************************************************************************** + * + * @section: + * gasp_table + * + * @title: + * Gasp Table + * + * @abstract: + * Retrieving TrueType `gasp' table entries. + * + * @description: + * The function @FT_Get_Gasp can be used to query a TrueType or OpenType + * font for specific entries in its `gasp' table, if any. This is + * mainly useful when implementing native TrueType hinting with the + * bytecode interpreter to duplicate the Windows text rendering results. + */ + + /************************************************************************* + * + * @enum: + * FT_GASP_XXX + * + * @description: + * A list of values and/or bit-flags returned by the @FT_Get_Gasp + * function. + * + * @values: + * FT_GASP_NO_TABLE :: + * This special value means that there is no GASP table in this face. + * It is up to the client to decide what to do. + * + * FT_GASP_DO_GRIDFIT :: + * Grid-fitting and hinting should be performed at the specified ppem. + * This *really* means TrueType bytecode interpretation. If this bit + * is not set, no hinting gets applied. + * + * FT_GASP_DO_GRAY :: + * Anti-aliased rendering should be performed at the specified ppem. + * If not set, do monochrome rendering. + * + * FT_GASP_SYMMETRIC_SMOOTHING :: + * If set, smoothing along multiple axes must be used with ClearType. + * + * FT_GASP_SYMMETRIC_GRIDFIT :: + * Grid-fitting must be used with ClearType's symmetric smoothing. + * + * @note: + * The bit-flags `FT_GASP_DO_GRIDFIT' and `FT_GASP_DO_GRAY' are to be + * used for standard font rasterization only. Independently of that, + * `FT_GASP_SYMMETRIC_SMOOTHING' and `FT_GASP_SYMMETRIC_GRIDFIT' are to + * be used if ClearType is enabled (and `FT_GASP_DO_GRIDFIT' and + * `FT_GASP_DO_GRAY' are consequently ignored). + * + * `ClearType' is Microsoft's implementation of LCD rendering, partly + * protected by patents. + * + * @since: + * 2.3.0 + */ +#define FT_GASP_NO_TABLE -1 +#define FT_GASP_DO_GRIDFIT 0x01 +#define FT_GASP_DO_GRAY 0x02 +#define FT_GASP_SYMMETRIC_SMOOTHING 0x08 +#define FT_GASP_SYMMETRIC_GRIDFIT 0x10 + + + /************************************************************************* + * + * @func: + * FT_Get_Gasp + * + * @description: + * Read the `gasp' table from a TrueType or OpenType font file and + * return the entry corresponding to a given character pixel size. + * + * @input: + * face :: The source face handle. + * ppem :: The vertical character pixel size. + * + * @return: + * Bit flags (see @FT_GASP_XXX), or @FT_GASP_NO_TABLE if there is no + * `gasp' table in the face. + * + * @since: + * 2.3.0 + */ + FT_EXPORT( FT_Int ) + FT_Get_Gasp( FT_Face face, + FT_UInt ppem ); + +/* */ + +#endif /* _FT_GASP_H_ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftglyph.h b/other/freetype/include/freetype/ftglyph.h new file mode 100644 index 0000000..3de69f7 --- /dev/null +++ b/other/freetype/include/freetype/ftglyph.h @@ -0,0 +1,620 @@ +/***************************************************************************/ +/* */ +/* ftglyph.h */ +/* */ +/* FreeType convenience functions to handle glyphs (specification). */ +/* */ +/* Copyright 1996-2003, 2006, 2008, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file contains the definition of several convenience functions */ + /* that can be used by client applications to easily retrieve glyph */ + /* bitmaps and outlines from a given face. */ + /* */ + /* These functions should be optional if you are writing a font server */ + /* or text layout engine on top of FreeType. However, they are pretty */ + /* handy for many other simple uses of the library. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTGLYPH_H__ +#define __FTGLYPH_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* glyph_management */ + /* */ + /* <Title> */ + /* Glyph Management */ + /* */ + /* <Abstract> */ + /* Generic interface to manage individual glyph data. */ + /* */ + /* <Description> */ + /* This section contains definitions used to manage glyph data */ + /* through generic FT_Glyph objects. Each of them can contain a */ + /* bitmap, a vector outline, or even images in other formats. */ + /* */ + /*************************************************************************/ + + + /* forward declaration to a private type */ + typedef struct FT_Glyph_Class_ FT_Glyph_Class; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Glyph */ + /* */ + /* <Description> */ + /* Handle to an object used to model generic glyph images. It is a */ + /* pointer to the @FT_GlyphRec structure and can contain a glyph */ + /* bitmap or pointer. */ + /* */ + /* <Note> */ + /* Glyph objects are not owned by the library. You must thus release */ + /* them manually (through @FT_Done_Glyph) _before_ calling */ + /* @FT_Done_FreeType. */ + /* */ + typedef struct FT_GlyphRec_* FT_Glyph; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_GlyphRec */ + /* */ + /* <Description> */ + /* The root glyph structure contains a given glyph image plus its */ + /* advance width in 16.16 fixed float format. */ + /* */ + /* <Fields> */ + /* library :: A handle to the FreeType library object. */ + /* */ + /* clazz :: A pointer to the glyph's class. Private. */ + /* */ + /* format :: The format of the glyph's image. */ + /* */ + /* advance :: A 16.16 vector that gives the glyph's advance width. */ + /* */ + typedef struct FT_GlyphRec_ + { + FT_Library library; + const FT_Glyph_Class* clazz; + FT_Glyph_Format format; + FT_Vector advance; + + } FT_GlyphRec; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_BitmapGlyph */ + /* */ + /* <Description> */ + /* A handle to an object used to model a bitmap glyph image. This is */ + /* a sub-class of @FT_Glyph, and a pointer to @FT_BitmapGlyphRec. */ + /* */ + typedef struct FT_BitmapGlyphRec_* FT_BitmapGlyph; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_BitmapGlyphRec */ + /* */ + /* <Description> */ + /* A structure used for bitmap glyph images. This really is a */ + /* `sub-class' of @FT_GlyphRec. */ + /* */ + /* <Fields> */ + /* root :: The root @FT_Glyph fields. */ + /* */ + /* left :: The left-side bearing, i.e., the horizontal distance */ + /* from the current pen position to the left border of the */ + /* glyph bitmap. */ + /* */ + /* top :: The top-side bearing, i.e., the vertical distance from */ + /* the current pen position to the top border of the glyph */ + /* bitmap. This distance is positive for upwards~y! */ + /* */ + /* bitmap :: A descriptor for the bitmap. */ + /* */ + /* <Note> */ + /* You can typecast an @FT_Glyph to @FT_BitmapGlyph if you have */ + /* `glyph->format == FT_GLYPH_FORMAT_BITMAP'. This lets you access */ + /* the bitmap's contents easily. */ + /* */ + /* The corresponding pixel buffer is always owned by @FT_BitmapGlyph */ + /* and is thus created and destroyed with it. */ + /* */ + typedef struct FT_BitmapGlyphRec_ + { + FT_GlyphRec root; + FT_Int left; + FT_Int top; + FT_Bitmap bitmap; + + } FT_BitmapGlyphRec; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_OutlineGlyph */ + /* */ + /* <Description> */ + /* A handle to an object used to model an outline glyph image. This */ + /* is a sub-class of @FT_Glyph, and a pointer to @FT_OutlineGlyphRec. */ + /* */ + typedef struct FT_OutlineGlyphRec_* FT_OutlineGlyph; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_OutlineGlyphRec */ + /* */ + /* <Description> */ + /* A structure used for outline (vectorial) glyph images. This */ + /* really is a `sub-class' of @FT_GlyphRec. */ + /* */ + /* <Fields> */ + /* root :: The root @FT_Glyph fields. */ + /* */ + /* outline :: A descriptor for the outline. */ + /* */ + /* <Note> */ + /* You can typecast an @FT_Glyph to @FT_OutlineGlyph if you have */ + /* `glyph->format == FT_GLYPH_FORMAT_OUTLINE'. This lets you access */ + /* the outline's content easily. */ + /* */ + /* As the outline is extracted from a glyph slot, its coordinates are */ + /* expressed normally in 26.6 pixels, unless the flag */ + /* @FT_LOAD_NO_SCALE was used in @FT_Load_Glyph() or @FT_Load_Char(). */ + /* */ + /* The outline's tables are always owned by the object and are */ + /* destroyed with it. */ + /* */ + typedef struct FT_OutlineGlyphRec_ + { + FT_GlyphRec root; + FT_Outline outline; + + } FT_OutlineGlyphRec; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Glyph */ + /* */ + /* <Description> */ + /* A function used to extract a glyph image from a slot. Note that */ + /* the created @FT_Glyph object must be released with @FT_Done_Glyph. */ + /* */ + /* <Input> */ + /* slot :: A handle to the source glyph slot. */ + /* */ + /* <Output> */ + /* aglyph :: A handle to the glyph object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Glyph( FT_GlyphSlot slot, + FT_Glyph *aglyph ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Glyph_Copy */ + /* */ + /* <Description> */ + /* A function used to copy a glyph image. Note that the created */ + /* @FT_Glyph object must be released with @FT_Done_Glyph. */ + /* */ + /* <Input> */ + /* source :: A handle to the source glyph object. */ + /* */ + /* <Output> */ + /* target :: A handle to the target glyph object. 0~in case of */ + /* error. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Glyph_Copy( FT_Glyph source, + FT_Glyph *target ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Glyph_Transform */ + /* */ + /* <Description> */ + /* Transform a glyph image if its format is scalable. */ + /* */ + /* <InOut> */ + /* glyph :: A handle to the target glyph object. */ + /* */ + /* <Input> */ + /* matrix :: A pointer to a 2x2 matrix to apply. */ + /* */ + /* delta :: A pointer to a 2d vector to apply. Coordinates are */ + /* expressed in 1/64th of a pixel. */ + /* */ + /* <Return> */ + /* FreeType error code (if not 0, the glyph format is not scalable). */ + /* */ + /* <Note> */ + /* The 2x2 transformation matrix is also applied to the glyph's */ + /* advance vector. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Glyph_Transform( FT_Glyph glyph, + FT_Matrix* matrix, + FT_Vector* delta ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Glyph_BBox_Mode */ + /* */ + /* <Description> */ + /* The mode how the values of @FT_Glyph_Get_CBox are returned. */ + /* */ + /* <Values> */ + /* FT_GLYPH_BBOX_UNSCALED :: */ + /* Return unscaled font units. */ + /* */ + /* FT_GLYPH_BBOX_SUBPIXELS :: */ + /* Return unfitted 26.6 coordinates. */ + /* */ + /* FT_GLYPH_BBOX_GRIDFIT :: */ + /* Return grid-fitted 26.6 coordinates. */ + /* */ + /* FT_GLYPH_BBOX_TRUNCATE :: */ + /* Return coordinates in integer pixels. */ + /* */ + /* FT_GLYPH_BBOX_PIXELS :: */ + /* Return grid-fitted pixel coordinates. */ + /* */ + typedef enum FT_Glyph_BBox_Mode_ + { + FT_GLYPH_BBOX_UNSCALED = 0, + FT_GLYPH_BBOX_SUBPIXELS = 0, + FT_GLYPH_BBOX_GRIDFIT = 1, + FT_GLYPH_BBOX_TRUNCATE = 2, + FT_GLYPH_BBOX_PIXELS = 3 + + } FT_Glyph_BBox_Mode; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* ft_glyph_bbox_xxx */ + /* */ + /* <Description> */ + /* These constants are deprecated. Use the corresponding */ + /* @FT_Glyph_BBox_Mode values instead. */ + /* */ + /* <Values> */ + /* ft_glyph_bbox_unscaled :: See @FT_GLYPH_BBOX_UNSCALED. */ + /* ft_glyph_bbox_subpixels :: See @FT_GLYPH_BBOX_SUBPIXELS. */ + /* ft_glyph_bbox_gridfit :: See @FT_GLYPH_BBOX_GRIDFIT. */ + /* ft_glyph_bbox_truncate :: See @FT_GLYPH_BBOX_TRUNCATE. */ + /* ft_glyph_bbox_pixels :: See @FT_GLYPH_BBOX_PIXELS. */ + /* */ +#define ft_glyph_bbox_unscaled FT_GLYPH_BBOX_UNSCALED +#define ft_glyph_bbox_subpixels FT_GLYPH_BBOX_SUBPIXELS +#define ft_glyph_bbox_gridfit FT_GLYPH_BBOX_GRIDFIT +#define ft_glyph_bbox_truncate FT_GLYPH_BBOX_TRUNCATE +#define ft_glyph_bbox_pixels FT_GLYPH_BBOX_PIXELS + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Glyph_Get_CBox */ + /* */ + /* <Description> */ + /* Return a glyph's `control box'. The control box encloses all the */ + /* outline's points, including Bézier control points. Though it */ + /* coincides with the exact bounding box for most glyphs, it can be */ + /* slightly larger in some situations (like when rotating an outline */ + /* which contains Bézier outside arcs). */ + /* */ + /* Computing the control box is very fast, while getting the bounding */ + /* box can take much more time as it needs to walk over all segments */ + /* and arcs in the outline. To get the latter, you can use the */ + /* `ftbbox' component which is dedicated to this single task. */ + /* */ + /* <Input> */ + /* glyph :: A handle to the source glyph object. */ + /* */ + /* mode :: The mode which indicates how to interpret the returned */ + /* bounding box values. */ + /* */ + /* <Output> */ + /* acbox :: The glyph coordinate bounding box. Coordinates are */ + /* expressed in 1/64th of pixels if it is grid-fitted. */ + /* */ + /* <Note> */ + /* Coordinates are relative to the glyph origin, using the y~upwards */ + /* convention. */ + /* */ + /* If the glyph has been loaded with @FT_LOAD_NO_SCALE, `bbox_mode' */ + /* must be set to @FT_GLYPH_BBOX_UNSCALED to get unscaled font */ + /* units in 26.6 pixel format. The value @FT_GLYPH_BBOX_SUBPIXELS */ + /* is another name for this constant. */ + /* */ + /* If the font is tricky and the glyph has been loaded with */ + /* @FT_LOAD_NO_SCALE, the resulting CBox is meaningless. To get */ + /* reasonable values for the CBox it is necessary to load the glyph */ + /* at a large ppem value (so that the hinting instructions can */ + /* properly shift and scale the subglyphs), then extracting the CBox */ + /* which can be eventually converted back to font units. */ + /* */ + /* Note that the maximum coordinates are exclusive, which means that */ + /* one can compute the width and height of the glyph image (be it in */ + /* integer or 26.6 pixels) as: */ + /* */ + /* { */ + /* width = bbox.xMax - bbox.xMin; */ + /* height = bbox.yMax - bbox.yMin; */ + /* } */ + /* */ + /* Note also that for 26.6 coordinates, if `bbox_mode' is set to */ + /* @FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted, */ + /* which corresponds to: */ + /* */ + /* { */ + /* bbox.xMin = FLOOR(bbox.xMin); */ + /* bbox.yMin = FLOOR(bbox.yMin); */ + /* bbox.xMax = CEILING(bbox.xMax); */ + /* bbox.yMax = CEILING(bbox.yMax); */ + /* } */ + /* */ + /* To get the bbox in pixel coordinates, set `bbox_mode' to */ + /* @FT_GLYPH_BBOX_TRUNCATE. */ + /* */ + /* To get the bbox in grid-fitted pixel coordinates, set `bbox_mode' */ + /* to @FT_GLYPH_BBOX_PIXELS. */ + /* */ + FT_EXPORT( void ) + FT_Glyph_Get_CBox( FT_Glyph glyph, + FT_UInt bbox_mode, + FT_BBox *acbox ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Glyph_To_Bitmap */ + /* */ + /* <Description> */ + /* Convert a given glyph object to a bitmap glyph object. */ + /* */ + /* <InOut> */ + /* the_glyph :: A pointer to a handle to the target glyph. */ + /* */ + /* <Input> */ + /* render_mode :: An enumeration that describes how the data is */ + /* rendered. */ + /* */ + /* origin :: A pointer to a vector used to translate the glyph */ + /* image before rendering. Can be~0 (if no */ + /* translation). The origin is expressed in */ + /* 26.6 pixels. */ + /* */ + /* destroy :: A boolean that indicates that the original glyph */ + /* image should be destroyed by this function. It is */ + /* never destroyed in case of error. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function does nothing if the glyph format isn't scalable. */ + /* */ + /* The glyph image is translated with the `origin' vector before */ + /* rendering. */ + /* */ + /* The first parameter is a pointer to an @FT_Glyph handle, that will */ + /* be _replaced_ by this function (with newly allocated data). */ + /* Typically, you would use (omitting error handling): */ + /* */ + /* */ + /* { */ + /* FT_Glyph glyph; */ + /* FT_BitmapGlyph glyph_bitmap; */ + /* */ + /* */ + /* // load glyph */ + /* error = FT_Load_Char( face, glyph_index, FT_LOAD_DEFAUT ); */ + /* */ + /* // extract glyph image */ + /* error = FT_Get_Glyph( face->glyph, &glyph ); */ + /* */ + /* // convert to a bitmap (default render mode + destroying old) */ + /* if ( glyph->format != FT_GLYPH_FORMAT_BITMAP ) */ + /* { */ + /* error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, */ + /* 0, 1 ); */ + /* if ( error ) // `glyph' unchanged */ + /* ... */ + /* } */ + /* */ + /* // access bitmap content by typecasting */ + /* glyph_bitmap = (FT_BitmapGlyph)glyph; */ + /* */ + /* // do funny stuff with it, like blitting/drawing */ + /* ... */ + /* */ + /* // discard glyph image (bitmap or not) */ + /* FT_Done_Glyph( glyph ); */ + /* } */ + /* */ + /* */ + /* Here another example, again without error handling: */ + /* */ + /* */ + /* { */ + /* FT_Glyph glyphs[MAX_GLYPHS] */ + /* */ + /* */ + /* ... */ + /* */ + /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ + /* error = FT_Load_Glyph( face, idx, FT_LOAD_DEFAULT ) || */ + /* FT_Get_Glyph ( face->glyph, &glyph[idx] ); */ + /* */ + /* ... */ + /* */ + /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ + /* { */ + /* FT_Glyph bitmap = glyphs[idx]; */ + /* */ + /* */ + /* ... */ + /* */ + /* // after this call, `bitmap' no longer points into */ + /* // the `glyphs' array (and the old value isn't destroyed) */ + /* FT_Glyph_To_Bitmap( &bitmap, FT_RENDER_MODE_MONO, 0, 0 ); */ + /* */ + /* ... */ + /* */ + /* FT_Done_Glyph( bitmap ); */ + /* } */ + /* */ + /* ... */ + /* */ + /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ + /* FT_Done_Glyph( glyphs[idx] ); */ + /* } */ + /* */ + FT_EXPORT( FT_Error ) + FT_Glyph_To_Bitmap( FT_Glyph* the_glyph, + FT_Render_Mode render_mode, + FT_Vector* origin, + FT_Bool destroy ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_Glyph */ + /* */ + /* <Description> */ + /* Destroy a given glyph. */ + /* */ + /* <Input> */ + /* glyph :: A handle to the target glyph object. */ + /* */ + FT_EXPORT( void ) + FT_Done_Glyph( FT_Glyph glyph ); + + /* */ + + + /* other helpful functions */ + + /*************************************************************************/ + /* */ + /* <Section> */ + /* computations */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Matrix_Multiply */ + /* */ + /* <Description> */ + /* Perform the matrix operation `b = a*b'. */ + /* */ + /* <Input> */ + /* a :: A pointer to matrix `a'. */ + /* */ + /* <InOut> */ + /* b :: A pointer to matrix `b'. */ + /* */ + /* <Note> */ + /* The result is undefined if either `a' or `b' is zero. */ + /* */ + FT_EXPORT( void ) + FT_Matrix_Multiply( const FT_Matrix* a, + FT_Matrix* b ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Matrix_Invert */ + /* */ + /* <Description> */ + /* Invert a 2x2 matrix. Return an error if it can't be inverted. */ + /* */ + /* <InOut> */ + /* matrix :: A pointer to the target matrix. Remains untouched in */ + /* case of error. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Matrix_Invert( FT_Matrix* matrix ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTGLYPH_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftgxval.h b/other/freetype/include/freetype/ftgxval.h new file mode 100644 index 0000000..497015c --- /dev/null +++ b/other/freetype/include/freetype/ftgxval.h @@ -0,0 +1,358 @@ +/***************************************************************************/ +/* */ +/* ftgxval.h */ +/* */ +/* FreeType API for validating TrueTypeGX/AAT tables (specification). */ +/* */ +/* Copyright 2004, 2005, 2006 by */ +/* Masatake YAMATO, Redhat K.K, */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +/***************************************************************************/ +/* */ +/* gxvalid is derived from both gxlayout module and otvalid module. */ +/* Development of gxlayout is supported by the Information-technology */ +/* Promotion Agency(IPA), Japan. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTGXVAL_H__ +#define __FTGXVAL_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* gx_validation */ + /* */ + /* <Title> */ + /* TrueTypeGX/AAT Validation */ + /* */ + /* <Abstract> */ + /* An API to validate TrueTypeGX/AAT tables. */ + /* */ + /* <Description> */ + /* This section contains the declaration of functions to validate */ + /* some TrueTypeGX tables (feat, mort, morx, bsln, just, kern, opbd, */ + /* trak, prop, lcar). */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* */ + /* Warning: Use FT_VALIDATE_XXX to validate a table. */ + /* Following definitions are for gxvalid developers. */ + /* */ + /* */ + /*************************************************************************/ + +#define FT_VALIDATE_feat_INDEX 0 +#define FT_VALIDATE_mort_INDEX 1 +#define FT_VALIDATE_morx_INDEX 2 +#define FT_VALIDATE_bsln_INDEX 3 +#define FT_VALIDATE_just_INDEX 4 +#define FT_VALIDATE_kern_INDEX 5 +#define FT_VALIDATE_opbd_INDEX 6 +#define FT_VALIDATE_trak_INDEX 7 +#define FT_VALIDATE_prop_INDEX 8 +#define FT_VALIDATE_lcar_INDEX 9 +#define FT_VALIDATE_GX_LAST_INDEX FT_VALIDATE_lcar_INDEX + + + /************************************************************************* + * + * @macro: + * FT_VALIDATE_GX_LENGTH + * + * @description: + * The number of tables checked in this module. Use it as a parameter + * for the `table-length' argument of function @FT_TrueTypeGX_Validate. + */ +#define FT_VALIDATE_GX_LENGTH (FT_VALIDATE_GX_LAST_INDEX + 1) + + /* */ + + /* Up to 0x1000 is used by otvalid. + Ox2xxx is reserved for feature OT extension. */ +#define FT_VALIDATE_GX_START 0x4000 +#define FT_VALIDATE_GX_BITFIELD( tag ) \ + ( FT_VALIDATE_GX_START << FT_VALIDATE_##tag##_INDEX ) + + + /********************************************************************** + * + * @enum: + * FT_VALIDATE_GXXXX + * + * @description: + * A list of bit-field constants used with @FT_TrueTypeGX_Validate to + * indicate which TrueTypeGX/AAT Type tables should be validated. + * + * @values: + * FT_VALIDATE_feat :: + * Validate `feat' table. + * + * FT_VALIDATE_mort :: + * Validate `mort' table. + * + * FT_VALIDATE_morx :: + * Validate `morx' table. + * + * FT_VALIDATE_bsln :: + * Validate `bsln' table. + * + * FT_VALIDATE_just :: + * Validate `just' table. + * + * FT_VALIDATE_kern :: + * Validate `kern' table. + * + * FT_VALIDATE_opbd :: + * Validate `opbd' table. + * + * FT_VALIDATE_trak :: + * Validate `trak' table. + * + * FT_VALIDATE_prop :: + * Validate `prop' table. + * + * FT_VALIDATE_lcar :: + * Validate `lcar' table. + * + * FT_VALIDATE_GX :: + * Validate all TrueTypeGX tables (feat, mort, morx, bsln, just, kern, + * opbd, trak, prop and lcar). + * + */ + +#define FT_VALIDATE_feat FT_VALIDATE_GX_BITFIELD( feat ) +#define FT_VALIDATE_mort FT_VALIDATE_GX_BITFIELD( mort ) +#define FT_VALIDATE_morx FT_VALIDATE_GX_BITFIELD( morx ) +#define FT_VALIDATE_bsln FT_VALIDATE_GX_BITFIELD( bsln ) +#define FT_VALIDATE_just FT_VALIDATE_GX_BITFIELD( just ) +#define FT_VALIDATE_kern FT_VALIDATE_GX_BITFIELD( kern ) +#define FT_VALIDATE_opbd FT_VALIDATE_GX_BITFIELD( opbd ) +#define FT_VALIDATE_trak FT_VALIDATE_GX_BITFIELD( trak ) +#define FT_VALIDATE_prop FT_VALIDATE_GX_BITFIELD( prop ) +#define FT_VALIDATE_lcar FT_VALIDATE_GX_BITFIELD( lcar ) + +#define FT_VALIDATE_GX ( FT_VALIDATE_feat | \ + FT_VALIDATE_mort | \ + FT_VALIDATE_morx | \ + FT_VALIDATE_bsln | \ + FT_VALIDATE_just | \ + FT_VALIDATE_kern | \ + FT_VALIDATE_opbd | \ + FT_VALIDATE_trak | \ + FT_VALIDATE_prop | \ + FT_VALIDATE_lcar ) + + + /* */ + + /********************************************************************** + * + * @function: + * FT_TrueTypeGX_Validate + * + * @description: + * Validate various TrueTypeGX tables to assure that all offsets and + * indices are valid. The idea is that a higher-level library which + * actually does the text layout can access those tables without + * error checking (which can be quite time consuming). + * + * @input: + * face :: + * A handle to the input face. + * + * validation_flags :: + * A bit field which specifies the tables to be validated. See + * @FT_VALIDATE_GXXXX for possible values. + * + * table_length :: + * The size of the `tables' array. Normally, @FT_VALIDATE_GX_LENGTH + * should be passed. + * + * @output: + * tables :: + * The array where all validated sfnt tables are stored. + * The array itself must be allocated by a client. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with TrueTypeGX fonts, returning an error + * otherwise. + * + * After use, the application should deallocate the buffers pointed to by + * each `tables' element, by calling @FT_TrueTypeGX_Free. A NULL value + * indicates that the table either doesn't exist in the font, the + * application hasn't asked for validation, or the validator doesn't have + * the ability to validate the sfnt table. + */ + FT_EXPORT( FT_Error ) + FT_TrueTypeGX_Validate( FT_Face face, + FT_UInt validation_flags, + FT_Bytes tables[FT_VALIDATE_GX_LENGTH], + FT_UInt table_length ); + + + /* */ + + /********************************************************************** + * + * @function: + * FT_TrueTypeGX_Free + * + * @description: + * Free the buffer allocated by TrueTypeGX validator. + * + * @input: + * face :: + * A handle to the input face. + * + * table :: + * The pointer to the buffer allocated by + * @FT_TrueTypeGX_Validate. + * + * @note: + * This function must be used to free the buffer allocated by + * @FT_TrueTypeGX_Validate only. + */ + FT_EXPORT( void ) + FT_TrueTypeGX_Free( FT_Face face, + FT_Bytes table ); + + + /* */ + + /********************************************************************** + * + * @enum: + * FT_VALIDATE_CKERNXXX + * + * @description: + * A list of bit-field constants used with @FT_ClassicKern_Validate + * to indicate the classic kern dialect or dialects. If the selected + * type doesn't fit, @FT_ClassicKern_Validate regards the table as + * invalid. + * + * @values: + * FT_VALIDATE_MS :: + * Handle the `kern' table as a classic Microsoft kern table. + * + * FT_VALIDATE_APPLE :: + * Handle the `kern' table as a classic Apple kern table. + * + * FT_VALIDATE_CKERN :: + * Handle the `kern' as either classic Apple or Microsoft kern table. + */ +#define FT_VALIDATE_MS ( FT_VALIDATE_GX_START << 0 ) +#define FT_VALIDATE_APPLE ( FT_VALIDATE_GX_START << 1 ) + +#define FT_VALIDATE_CKERN ( FT_VALIDATE_MS | FT_VALIDATE_APPLE ) + + + /* */ + + /********************************************************************** + * + * @function: + * FT_ClassicKern_Validate + * + * @description: + * Validate classic (16-bit format) kern table to assure that the offsets + * and indices are valid. The idea is that a higher-level library which + * actually does the text layout can access those tables without error + * checking (which can be quite time consuming). + * + * The `kern' table validator in @FT_TrueTypeGX_Validate deals with both + * the new 32-bit format and the classic 16-bit format, while + * FT_ClassicKern_Validate only supports the classic 16-bit format. + * + * @input: + * face :: + * A handle to the input face. + * + * validation_flags :: + * A bit field which specifies the dialect to be validated. See + * @FT_VALIDATE_CKERNXXX for possible values. + * + * @output: + * ckern_table :: + * A pointer to the kern table. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * After use, the application should deallocate the buffers pointed to by + * `ckern_table', by calling @FT_ClassicKern_Free. A NULL value + * indicates that the table doesn't exist in the font. + */ + FT_EXPORT( FT_Error ) + FT_ClassicKern_Validate( FT_Face face, + FT_UInt validation_flags, + FT_Bytes *ckern_table ); + + + /* */ + + /********************************************************************** + * + * @function: + * FT_ClassicKern_Free + * + * @description: + * Free the buffer allocated by classic Kern validator. + * + * @input: + * face :: + * A handle to the input face. + * + * table :: + * The pointer to the buffer that is allocated by + * @FT_ClassicKern_Validate. + * + * @note: + * This function must be used to free the buffer allocated by + * @FT_ClassicKern_Validate only. + */ + FT_EXPORT( void ) + FT_ClassicKern_Free( FT_Face face, + FT_Bytes table ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTGXVAL_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftgzip.h b/other/freetype/include/freetype/ftgzip.h new file mode 100644 index 0000000..acbc4f0 --- /dev/null +++ b/other/freetype/include/freetype/ftgzip.h @@ -0,0 +1,102 @@ +/***************************************************************************/ +/* */ +/* ftgzip.h */ +/* */ +/* Gzip-compressed stream support. */ +/* */ +/* Copyright 2002, 2003, 2004, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTGZIP_H__ +#define __FTGZIP_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************/ + /* */ + /* <Section> */ + /* gzip */ + /* */ + /* <Title> */ + /* GZIP Streams */ + /* */ + /* <Abstract> */ + /* Using gzip-compressed font files. */ + /* */ + /* <Description> */ + /* This section contains the declaration of Gzip-specific functions. */ + /* */ + /*************************************************************************/ + + + /************************************************************************ + * + * @function: + * FT_Stream_OpenGzip + * + * @description: + * Open a new stream to parse gzip-compressed font files. This is + * mainly used to support the compressed `*.pcf.gz' fonts that come + * with XFree86. + * + * @input: + * stream :: + * The target embedding stream. + * + * source :: + * The source stream. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The source stream must be opened _before_ calling this function. + * + * Calling the internal function `FT_Stream_Close' on the new stream will + * *not* call `FT_Stream_Close' on the source stream. None of the stream + * objects will be released to the heap. + * + * The stream implementation is very basic and resets the decompression + * process each time seeking backwards is needed within the stream. + * + * In certain builds of the library, gzip compression recognition is + * automatically handled when calling @FT_New_Face or @FT_Open_Face. + * This means that if no font driver is capable of handling the raw + * compressed file, the library will try to open a gzipped stream from + * it and re-open the face with it. + * + * This function may return `FT_Err_Unimplemented_Feature' if your build + * of FreeType was not compiled with zlib support. + */ + FT_EXPORT( FT_Error ) + FT_Stream_OpenGzip( FT_Stream stream, + FT_Stream source ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTGZIP_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftimage.h b/other/freetype/include/freetype/ftimage.h new file mode 100644 index 0000000..04b5e04 --- /dev/null +++ b/other/freetype/include/freetype/ftimage.h @@ -0,0 +1,1313 @@ +/***************************************************************************/ +/* */ +/* ftimage.h */ +/* */ +/* FreeType glyph image formats and default raster interface */ +/* (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, */ +/* 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + /*************************************************************************/ + /* */ + /* Note: A `raster' is simply a scan-line converter, used to render */ + /* FT_Outlines into FT_Bitmaps. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTIMAGE_H__ +#define __FTIMAGE_H__ + + + /* _STANDALONE_ is from ftgrays.c */ +#ifndef _STANDALONE_ +#include <ft2build.h> +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* basic_types */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Pos */ + /* */ + /* <Description> */ + /* The type FT_Pos is used to store vectorial coordinates. Depending */ + /* on the context, these can represent distances in integer font */ + /* units, or 16.16, or 26.6 fixed float pixel coordinates. */ + /* */ + typedef signed long FT_Pos; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Vector */ + /* */ + /* <Description> */ + /* A simple structure used to store a 2D vector; coordinates are of */ + /* the FT_Pos type. */ + /* */ + /* <Fields> */ + /* x :: The horizontal coordinate. */ + /* y :: The vertical coordinate. */ + /* */ + typedef struct FT_Vector_ + { + FT_Pos x; + FT_Pos y; + + } FT_Vector; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_BBox */ + /* */ + /* <Description> */ + /* A structure used to hold an outline's bounding box, i.e., the */ + /* coordinates of its extrema in the horizontal and vertical */ + /* directions. */ + /* */ + /* <Fields> */ + /* xMin :: The horizontal minimum (left-most). */ + /* */ + /* yMin :: The vertical minimum (bottom-most). */ + /* */ + /* xMax :: The horizontal maximum (right-most). */ + /* */ + /* yMax :: The vertical maximum (top-most). */ + /* */ + /* <Note> */ + /* The bounding box is specified with the coordinates of the lower */ + /* left and the upper right corner. In PostScript, those values are */ + /* often called (llx,lly) and (urx,ury), respectively. */ + /* */ + /* If `yMin' is negative, this value gives the glyph's descender. */ + /* Otherwise, the glyph doesn't descend below the baseline. */ + /* Similarly, if `ymax' is positive, this value gives the glyph's */ + /* ascender. */ + /* */ + /* `xMin' gives the horizontal distance from the glyph's origin to */ + /* the left edge of the glyph's bounding box. If `xMin' is negative, */ + /* the glyph extends to the left of the origin. */ + /* */ + typedef struct FT_BBox_ + { + FT_Pos xMin, yMin; + FT_Pos xMax, yMax; + + } FT_BBox; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Pixel_Mode */ + /* */ + /* <Description> */ + /* An enumeration type used to describe the format of pixels in a */ + /* given bitmap. Note that additional formats may be added in the */ + /* future. */ + /* */ + /* <Values> */ + /* FT_PIXEL_MODE_NONE :: */ + /* Value~0 is reserved. */ + /* */ + /* FT_PIXEL_MODE_MONO :: */ + /* A monochrome bitmap, using 1~bit per pixel. Note that pixels */ + /* are stored in most-significant order (MSB), which means that */ + /* the left-most pixel in a byte has value 128. */ + /* */ + /* FT_PIXEL_MODE_GRAY :: */ + /* An 8-bit bitmap, generally used to represent anti-aliased glyph */ + /* images. Each pixel is stored in one byte. Note that the number */ + /* of `gray' levels is stored in the `num_grays' field of the */ + /* @FT_Bitmap structure (it generally is 256). */ + /* */ + /* FT_PIXEL_MODE_GRAY2 :: */ + /* A 2-bit per pixel bitmap, used to represent embedded */ + /* anti-aliased bitmaps in font files according to the OpenType */ + /* specification. We haven't found a single font using this */ + /* format, however. */ + /* */ + /* FT_PIXEL_MODE_GRAY4 :: */ + /* A 4-bit per pixel bitmap, representing embedded anti-aliased */ + /* bitmaps in font files according to the OpenType specification. */ + /* We haven't found a single font using this format, however. */ + /* */ + /* FT_PIXEL_MODE_LCD :: */ + /* An 8-bit bitmap, representing RGB or BGR decimated glyph images */ + /* used for display on LCD displays; the bitmap is three times */ + /* wider than the original glyph image. See also */ + /* @FT_RENDER_MODE_LCD. */ + /* */ + /* FT_PIXEL_MODE_LCD_V :: */ + /* An 8-bit bitmap, representing RGB or BGR decimated glyph images */ + /* used for display on rotated LCD displays; the bitmap is three */ + /* times taller than the original glyph image. See also */ + /* @FT_RENDER_MODE_LCD_V. */ + /* */ + typedef enum FT_Pixel_Mode_ + { + FT_PIXEL_MODE_NONE = 0, + FT_PIXEL_MODE_MONO, + FT_PIXEL_MODE_GRAY, + FT_PIXEL_MODE_GRAY2, + FT_PIXEL_MODE_GRAY4, + FT_PIXEL_MODE_LCD, + FT_PIXEL_MODE_LCD_V, + + FT_PIXEL_MODE_MAX /* do not remove */ + + } FT_Pixel_Mode; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* ft_pixel_mode_xxx */ + /* */ + /* <Description> */ + /* A list of deprecated constants. Use the corresponding */ + /* @FT_Pixel_Mode values instead. */ + /* */ + /* <Values> */ + /* ft_pixel_mode_none :: See @FT_PIXEL_MODE_NONE. */ + /* ft_pixel_mode_mono :: See @FT_PIXEL_MODE_MONO. */ + /* ft_pixel_mode_grays :: See @FT_PIXEL_MODE_GRAY. */ + /* ft_pixel_mode_pal2 :: See @FT_PIXEL_MODE_GRAY2. */ + /* ft_pixel_mode_pal4 :: See @FT_PIXEL_MODE_GRAY4. */ + /* */ +#define ft_pixel_mode_none FT_PIXEL_MODE_NONE +#define ft_pixel_mode_mono FT_PIXEL_MODE_MONO +#define ft_pixel_mode_grays FT_PIXEL_MODE_GRAY +#define ft_pixel_mode_pal2 FT_PIXEL_MODE_GRAY2 +#define ft_pixel_mode_pal4 FT_PIXEL_MODE_GRAY4 + + /* */ + +#if 0 + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Palette_Mode */ + /* */ + /* <Description> */ + /* THIS TYPE IS DEPRECATED. DO NOT USE IT! */ + /* */ + /* An enumeration type to describe the format of a bitmap palette, */ + /* used with ft_pixel_mode_pal4 and ft_pixel_mode_pal8. */ + /* */ + /* <Values> */ + /* ft_palette_mode_rgb :: The palette is an array of 3-byte RGB */ + /* records. */ + /* */ + /* ft_palette_mode_rgba :: The palette is an array of 4-byte RGBA */ + /* records. */ + /* */ + /* <Note> */ + /* As ft_pixel_mode_pal2, pal4 and pal8 are currently unused by */ + /* FreeType, these types are not handled by the library itself. */ + /* */ + typedef enum FT_Palette_Mode_ + { + ft_palette_mode_rgb = 0, + ft_palette_mode_rgba, + + ft_palette_mode_max /* do not remove */ + + } FT_Palette_Mode; + + /* */ + +#endif + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Bitmap */ + /* */ + /* <Description> */ + /* A structure used to describe a bitmap or pixmap to the raster. */ + /* Note that we now manage pixmaps of various depths through the */ + /* `pixel_mode' field. */ + /* */ + /* <Fields> */ + /* rows :: The number of bitmap rows. */ + /* */ + /* width :: The number of pixels in bitmap row. */ + /* */ + /* pitch :: The pitch's absolute value is the number of bytes */ + /* taken by one bitmap row, including padding. */ + /* However, the pitch is positive when the bitmap has */ + /* a `down' flow, and negative when it has an `up' */ + /* flow. In all cases, the pitch is an offset to add */ + /* to a bitmap pointer in order to go down one row. */ + /* */ + /* Note that `padding' means the alignment of a */ + /* bitmap to a byte border, and FreeType functions */ + /* normally align to the smallest possible integer */ + /* value. */ + /* */ + /* For the B/W rasterizer, `pitch' is always an even */ + /* number. */ + /* */ + /* To change the pitch of a bitmap (say, to make it a */ + /* multiple of 4), use @FT_Bitmap_Convert. */ + /* Alternatively, you might use callback functions to */ + /* directly render to the application's surface; see */ + /* the file `example2.cpp' in the tutorial for a */ + /* demonstration. */ + /* */ + /* buffer :: A typeless pointer to the bitmap buffer. This */ + /* value should be aligned on 32-bit boundaries in */ + /* most cases. */ + /* */ + /* num_grays :: This field is only used with */ + /* @FT_PIXEL_MODE_GRAY; it gives the number of gray */ + /* levels used in the bitmap. */ + /* */ + /* pixel_mode :: The pixel mode, i.e., how pixel bits are stored. */ + /* See @FT_Pixel_Mode for possible values. */ + /* */ + /* palette_mode :: This field is intended for paletted pixel modes; */ + /* it indicates how the palette is stored. Not */ + /* used currently. */ + /* */ + /* palette :: A typeless pointer to the bitmap palette; this */ + /* field is intended for paletted pixel modes. Not */ + /* used currently. */ + /* */ + /* <Note> */ + /* For now, the only pixel modes supported by FreeType are mono and */ + /* grays. However, drivers might be added in the future to support */ + /* more `colorful' options. */ + /* */ + typedef struct FT_Bitmap_ + { + int rows; + int width; + int pitch; + unsigned char* buffer; + short num_grays; + char pixel_mode; + char palette_mode; + void* palette; + + } FT_Bitmap; + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* outline_processing */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Outline */ + /* */ + /* <Description> */ + /* This structure is used to describe an outline to the scan-line */ + /* converter. */ + /* */ + /* <Fields> */ + /* n_contours :: The number of contours in the outline. */ + /* */ + /* n_points :: The number of points in the outline. */ + /* */ + /* points :: A pointer to an array of `n_points' @FT_Vector */ + /* elements, giving the outline's point coordinates. */ + /* */ + /* tags :: A pointer to an array of `n_points' chars, giving */ + /* each outline point's type. */ + /* */ + /* If bit~0 is unset, the point is `off' the curve, */ + /* i.e., a Bézier control point, while it is `on' if */ + /* set. */ + /* */ + /* Bit~1 is meaningful for `off' points only. If set, */ + /* it indicates a third-order Bézier arc control point; */ + /* and a second-order control point if unset. */ + /* */ + /* If bit~2 is set, bits 5-7 contain the drop-out mode */ + /* (as defined in the OpenType specification; the value */ + /* is the same as the argument to the SCANMODE */ + /* instruction). */ + /* */ + /* Bits 3 and~4 are reserved for internal purposes. */ + /* */ + /* contours :: An array of `n_contours' shorts, giving the end */ + /* point of each contour within the outline. For */ + /* example, the first contour is defined by the points */ + /* `0' to `contours[0]', the second one is defined by */ + /* the points `contours[0]+1' to `contours[1]', etc. */ + /* */ + /* flags :: A set of bit flags used to characterize the outline */ + /* and give hints to the scan-converter and hinter on */ + /* how to convert/grid-fit it. See @FT_OUTLINE_FLAGS. */ + /* */ + /* <Note> */ + /* The B/W rasterizer only checks bit~2 in the `tags' array for the */ + /* first point of each contour. The drop-out mode as given with */ + /* @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, and */ + /* @FT_OUTLINE_INCLUDE_STUBS in `flags' is then overridden. */ + /* */ + typedef struct FT_Outline_ + { + short n_contours; /* number of contours in glyph */ + short n_points; /* number of points in the glyph */ + + FT_Vector* points; /* the outline's points */ + char* tags; /* the points flags */ + short* contours; /* the contour end points */ + + int flags; /* outline masks */ + + } FT_Outline; + + /* Following limits must be consistent with */ + /* FT_Outline.{n_contours,n_points} */ +#define FT_OUTLINE_CONTOURS_MAX SHRT_MAX +#define FT_OUTLINE_POINTS_MAX SHRT_MAX + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_OUTLINE_FLAGS */ + /* */ + /* <Description> */ + /* A list of bit-field constants use for the flags in an outline's */ + /* `flags' field. */ + /* */ + /* <Values> */ + /* FT_OUTLINE_NONE :: */ + /* Value~0 is reserved. */ + /* */ + /* FT_OUTLINE_OWNER :: */ + /* If set, this flag indicates that the outline's field arrays */ + /* (i.e., `points', `flags', and `contours') are `owned' by the */ + /* outline object, and should thus be freed when it is destroyed. */ + /* */ + /* FT_OUTLINE_EVEN_ODD_FILL :: */ + /* By default, outlines are filled using the non-zero winding rule. */ + /* If set to 1, the outline will be filled using the even-odd fill */ + /* rule (only works with the smooth rasterizer). */ + /* */ + /* FT_OUTLINE_REVERSE_FILL :: */ + /* By default, outside contours of an outline are oriented in */ + /* clock-wise direction, as defined in the TrueType specification. */ + /* This flag is set if the outline uses the opposite direction */ + /* (typically for Type~1 fonts). This flag is ignored by the scan */ + /* converter. */ + /* */ + /* FT_OUTLINE_IGNORE_DROPOUTS :: */ + /* By default, the scan converter will try to detect drop-outs in */ + /* an outline and correct the glyph bitmap to ensure consistent */ + /* shape continuity. If set, this flag hints the scan-line */ + /* converter to ignore such cases. See below for more information. */ + /* */ + /* FT_OUTLINE_SMART_DROPOUTS :: */ + /* Select smart dropout control. If unset, use simple dropout */ + /* control. Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set. See */ + /* below for more information. */ + /* */ + /* FT_OUTLINE_INCLUDE_STUBS :: */ + /* If set, turn pixels on for `stubs', otherwise exclude them. */ + /* Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set. See below for */ + /* more information. */ + /* */ + /* FT_OUTLINE_HIGH_PRECISION :: */ + /* This flag indicates that the scan-line converter should try to */ + /* convert this outline to bitmaps with the highest possible */ + /* quality. It is typically set for small character sizes. Note */ + /* that this is only a hint that might be completely ignored by a */ + /* given scan-converter. */ + /* */ + /* FT_OUTLINE_SINGLE_PASS :: */ + /* This flag is set to force a given scan-converter to only use a */ + /* single pass over the outline to render a bitmap glyph image. */ + /* Normally, it is set for very large character sizes. It is only */ + /* a hint that might be completely ignored by a given */ + /* scan-converter. */ + /* */ + /* <Note> */ + /* The flags @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, */ + /* and @FT_OUTLINE_INCLUDE_STUBS are ignored by the smooth */ + /* rasterizer. */ + /* */ + /* There exists a second mechanism to pass the drop-out mode to the */ + /* B/W rasterizer; see the `tags' field in @FT_Outline. */ + /* */ + /* Please refer to the description of the `SCANTYPE' instruction in */ + /* the OpenType specification (in file `ttinst1.doc') how simple */ + /* drop-outs, smart drop-outs, and stubs are defined. */ + /* */ +#define FT_OUTLINE_NONE 0x0 +#define FT_OUTLINE_OWNER 0x1 +#define FT_OUTLINE_EVEN_ODD_FILL 0x2 +#define FT_OUTLINE_REVERSE_FILL 0x4 +#define FT_OUTLINE_IGNORE_DROPOUTS 0x8 +#define FT_OUTLINE_SMART_DROPOUTS 0x10 +#define FT_OUTLINE_INCLUDE_STUBS 0x20 + +#define FT_OUTLINE_HIGH_PRECISION 0x100 +#define FT_OUTLINE_SINGLE_PASS 0x200 + + + /************************************************************************* + * + * @enum: + * ft_outline_flags + * + * @description: + * These constants are deprecated. Please use the corresponding + * @FT_OUTLINE_FLAGS values. + * + * @values: + * ft_outline_none :: See @FT_OUTLINE_NONE. + * ft_outline_owner :: See @FT_OUTLINE_OWNER. + * ft_outline_even_odd_fill :: See @FT_OUTLINE_EVEN_ODD_FILL. + * ft_outline_reverse_fill :: See @FT_OUTLINE_REVERSE_FILL. + * ft_outline_ignore_dropouts :: See @FT_OUTLINE_IGNORE_DROPOUTS. + * ft_outline_high_precision :: See @FT_OUTLINE_HIGH_PRECISION. + * ft_outline_single_pass :: See @FT_OUTLINE_SINGLE_PASS. + */ +#define ft_outline_none FT_OUTLINE_NONE +#define ft_outline_owner FT_OUTLINE_OWNER +#define ft_outline_even_odd_fill FT_OUTLINE_EVEN_ODD_FILL +#define ft_outline_reverse_fill FT_OUTLINE_REVERSE_FILL +#define ft_outline_ignore_dropouts FT_OUTLINE_IGNORE_DROPOUTS +#define ft_outline_high_precision FT_OUTLINE_HIGH_PRECISION +#define ft_outline_single_pass FT_OUTLINE_SINGLE_PASS + + /* */ + +#define FT_CURVE_TAG( flag ) ( flag & 3 ) + +#define FT_CURVE_TAG_ON 1 +#define FT_CURVE_TAG_CONIC 0 +#define FT_CURVE_TAG_CUBIC 2 + +#define FT_CURVE_TAG_HAS_SCANMODE 4 + +#define FT_CURVE_TAG_TOUCH_X 8 /* reserved for the TrueType hinter */ +#define FT_CURVE_TAG_TOUCH_Y 16 /* reserved for the TrueType hinter */ + +#define FT_CURVE_TAG_TOUCH_BOTH ( FT_CURVE_TAG_TOUCH_X | \ + FT_CURVE_TAG_TOUCH_Y ) + +#define FT_Curve_Tag_On FT_CURVE_TAG_ON +#define FT_Curve_Tag_Conic FT_CURVE_TAG_CONIC +#define FT_Curve_Tag_Cubic FT_CURVE_TAG_CUBIC +#define FT_Curve_Tag_Touch_X FT_CURVE_TAG_TOUCH_X +#define FT_Curve_Tag_Touch_Y FT_CURVE_TAG_TOUCH_Y + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Outline_MoveToFunc */ + /* */ + /* <Description> */ + /* A function pointer type used to describe the signature of a `move */ + /* to' function during outline walking/decomposition. */ + /* */ + /* A `move to' is emitted to start a new contour in an outline. */ + /* */ + /* <Input> */ + /* to :: A pointer to the target point of the `move to'. */ + /* */ + /* user :: A typeless pointer which is passed from the caller of the */ + /* decomposition function. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + typedef int + (*FT_Outline_MoveToFunc)( const FT_Vector* to, + void* user ); + +#define FT_Outline_MoveTo_Func FT_Outline_MoveToFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Outline_LineToFunc */ + /* */ + /* <Description> */ + /* A function pointer type used to describe the signature of a `line */ + /* to' function during outline walking/decomposition. */ + /* */ + /* A `line to' is emitted to indicate a segment in the outline. */ + /* */ + /* <Input> */ + /* to :: A pointer to the target point of the `line to'. */ + /* */ + /* user :: A typeless pointer which is passed from the caller of the */ + /* decomposition function. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + typedef int + (*FT_Outline_LineToFunc)( const FT_Vector* to, + void* user ); + +#define FT_Outline_LineTo_Func FT_Outline_LineToFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Outline_ConicToFunc */ + /* */ + /* <Description> */ + /* A function pointer type used to describe the signature of a `conic */ + /* to' function during outline walking or decomposition. */ + /* */ + /* A `conic to' is emitted to indicate a second-order Bézier arc in */ + /* the outline. */ + /* */ + /* <Input> */ + /* control :: An intermediate control point between the last position */ + /* and the new target in `to'. */ + /* */ + /* to :: A pointer to the target end point of the conic arc. */ + /* */ + /* user :: A typeless pointer which is passed from the caller of */ + /* the decomposition function. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + typedef int + (*FT_Outline_ConicToFunc)( const FT_Vector* control, + const FT_Vector* to, + void* user ); + +#define FT_Outline_ConicTo_Func FT_Outline_ConicToFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Outline_CubicToFunc */ + /* */ + /* <Description> */ + /* A function pointer type used to describe the signature of a `cubic */ + /* to' function during outline walking or decomposition. */ + /* */ + /* A `cubic to' is emitted to indicate a third-order Bézier arc. */ + /* */ + /* <Input> */ + /* control1 :: A pointer to the first Bézier control point. */ + /* */ + /* control2 :: A pointer to the second Bézier control point. */ + /* */ + /* to :: A pointer to the target end point. */ + /* */ + /* user :: A typeless pointer which is passed from the caller of */ + /* the decomposition function. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + typedef int + (*FT_Outline_CubicToFunc)( const FT_Vector* control1, + const FT_Vector* control2, + const FT_Vector* to, + void* user ); + +#define FT_Outline_CubicTo_Func FT_Outline_CubicToFunc + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Outline_Funcs */ + /* */ + /* <Description> */ + /* A structure to hold various function pointers used during outline */ + /* decomposition in order to emit segments, conic, and cubic Béziers. */ + /* */ + /* <Fields> */ + /* move_to :: The `move to' emitter. */ + /* */ + /* line_to :: The segment emitter. */ + /* */ + /* conic_to :: The second-order Bézier arc emitter. */ + /* */ + /* cubic_to :: The third-order Bézier arc emitter. */ + /* */ + /* shift :: The shift that is applied to coordinates before they */ + /* are sent to the emitter. */ + /* */ + /* delta :: The delta that is applied to coordinates before they */ + /* are sent to the emitter, but after the shift. */ + /* */ + /* <Note> */ + /* The point coordinates sent to the emitters are the transformed */ + /* version of the original coordinates (this is important for high */ + /* accuracy during scan-conversion). The transformation is simple: */ + /* */ + /* { */ + /* x' = (x << shift) - delta */ + /* y' = (x << shift) - delta */ + /* } */ + /* */ + /* Set the values of `shift' and `delta' to~0 to get the original */ + /* point coordinates. */ + /* */ + typedef struct FT_Outline_Funcs_ + { + FT_Outline_MoveToFunc move_to; + FT_Outline_LineToFunc line_to; + FT_Outline_ConicToFunc conic_to; + FT_Outline_CubicToFunc cubic_to; + + int shift; + FT_Pos delta; + + } FT_Outline_Funcs; + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* basic_types */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_IMAGE_TAG */ + /* */ + /* <Description> */ + /* This macro converts four-letter tags to an unsigned long type. */ + /* */ + /* <Note> */ + /* Since many 16-bit compilers don't like 32-bit enumerations, you */ + /* should redefine this macro in case of problems to something like */ + /* this: */ + /* */ + /* { */ + /* #define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 ) value */ + /* } */ + /* */ + /* to get a simple enumeration without assigning special numbers. */ + /* */ +#ifndef FT_IMAGE_TAG +#define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 ) \ + value = ( ( (unsigned long)_x1 << 24 ) | \ + ( (unsigned long)_x2 << 16 ) | \ + ( (unsigned long)_x3 << 8 ) | \ + (unsigned long)_x4 ) +#endif /* FT_IMAGE_TAG */ + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Glyph_Format */ + /* */ + /* <Description> */ + /* An enumeration type used to describe the format of a given glyph */ + /* image. Note that this version of FreeType only supports two image */ + /* formats, even though future font drivers will be able to register */ + /* their own format. */ + /* */ + /* <Values> */ + /* FT_GLYPH_FORMAT_NONE :: */ + /* The value~0 is reserved. */ + /* */ + /* FT_GLYPH_FORMAT_COMPOSITE :: */ + /* The glyph image is a composite of several other images. This */ + /* format is _only_ used with @FT_LOAD_NO_RECURSE, and is used to */ + /* report compound glyphs (like accented characters). */ + /* */ + /* FT_GLYPH_FORMAT_BITMAP :: */ + /* The glyph image is a bitmap, and can be described as an */ + /* @FT_Bitmap. You generally need to access the `bitmap' field of */ + /* the @FT_GlyphSlotRec structure to read it. */ + /* */ + /* FT_GLYPH_FORMAT_OUTLINE :: */ + /* The glyph image is a vectorial outline made of line segments */ + /* and Bézier arcs; it can be described as an @FT_Outline; you */ + /* generally want to access the `outline' field of the */ + /* @FT_GlyphSlotRec structure to read it. */ + /* */ + /* FT_GLYPH_FORMAT_PLOTTER :: */ + /* The glyph image is a vectorial path with no inside and outside */ + /* contours. Some Type~1 fonts, like those in the Hershey family, */ + /* contain glyphs in this format. These are described as */ + /* @FT_Outline, but FreeType isn't currently capable of rendering */ + /* them correctly. */ + /* */ + typedef enum FT_Glyph_Format_ + { + FT_IMAGE_TAG( FT_GLYPH_FORMAT_NONE, 0, 0, 0, 0 ), + + FT_IMAGE_TAG( FT_GLYPH_FORMAT_COMPOSITE, 'c', 'o', 'm', 'p' ), + FT_IMAGE_TAG( FT_GLYPH_FORMAT_BITMAP, 'b', 'i', 't', 's' ), + FT_IMAGE_TAG( FT_GLYPH_FORMAT_OUTLINE, 'o', 'u', 't', 'l' ), + FT_IMAGE_TAG( FT_GLYPH_FORMAT_PLOTTER, 'p', 'l', 'o', 't' ) + + } FT_Glyph_Format; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* ft_glyph_format_xxx */ + /* */ + /* <Description> */ + /* A list of deprecated constants. Use the corresponding */ + /* @FT_Glyph_Format values instead. */ + /* */ + /* <Values> */ + /* ft_glyph_format_none :: See @FT_GLYPH_FORMAT_NONE. */ + /* ft_glyph_format_composite :: See @FT_GLYPH_FORMAT_COMPOSITE. */ + /* ft_glyph_format_bitmap :: See @FT_GLYPH_FORMAT_BITMAP. */ + /* ft_glyph_format_outline :: See @FT_GLYPH_FORMAT_OUTLINE. */ + /* ft_glyph_format_plotter :: See @FT_GLYPH_FORMAT_PLOTTER. */ + /* */ +#define ft_glyph_format_none FT_GLYPH_FORMAT_NONE +#define ft_glyph_format_composite FT_GLYPH_FORMAT_COMPOSITE +#define ft_glyph_format_bitmap FT_GLYPH_FORMAT_BITMAP +#define ft_glyph_format_outline FT_GLYPH_FORMAT_OUTLINE +#define ft_glyph_format_plotter FT_GLYPH_FORMAT_PLOTTER + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** R A S T E R D E F I N I T I O N S *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* A raster is a scan converter, in charge of rendering an outline into */ + /* a a bitmap. This section contains the public API for rasters. */ + /* */ + /* Note that in FreeType 2, all rasters are now encapsulated within */ + /* specific modules called `renderers'. See `freetype/ftrender.h' for */ + /* more details on renderers. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* raster */ + /* */ + /* <Title> */ + /* Scanline Converter */ + /* */ + /* <Abstract> */ + /* How vectorial outlines are converted into bitmaps and pixmaps. */ + /* */ + /* <Description> */ + /* This section contains technical definitions. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Raster */ + /* */ + /* <Description> */ + /* A handle (pointer) to a raster object. Each object can be used */ + /* independently to convert an outline into a bitmap or pixmap. */ + /* */ + typedef struct FT_RasterRec_* FT_Raster; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Span */ + /* */ + /* <Description> */ + /* A structure used to model a single span of gray (or black) pixels */ + /* when rendering a monochrome or anti-aliased bitmap. */ + /* */ + /* <Fields> */ + /* x :: The span's horizontal start position. */ + /* */ + /* len :: The span's length in pixels. */ + /* */ + /* coverage :: The span color/coverage, ranging from 0 (background) */ + /* to 255 (foreground). Only used for anti-aliased */ + /* rendering. */ + /* */ + /* <Note> */ + /* This structure is used by the span drawing callback type named */ + /* @FT_SpanFunc which takes the y~coordinate of the span as a */ + /* a parameter. */ + /* */ + /* The coverage value is always between 0 and 255. If you want less */ + /* gray values, the callback function has to reduce them. */ + /* */ + typedef struct FT_Span_ + { + short x; + unsigned short len; + unsigned char coverage; + + } FT_Span; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_SpanFunc */ + /* */ + /* <Description> */ + /* A function used as a call-back by the anti-aliased renderer in */ + /* order to let client applications draw themselves the gray pixel */ + /* spans on each scan line. */ + /* */ + /* <Input> */ + /* y :: The scanline's y~coordinate. */ + /* */ + /* count :: The number of spans to draw on this scanline. */ + /* */ + /* spans :: A table of `count' spans to draw on the scanline. */ + /* */ + /* user :: User-supplied data that is passed to the callback. */ + /* */ + /* <Note> */ + /* This callback allows client applications to directly render the */ + /* gray spans of the anti-aliased bitmap to any kind of surfaces. */ + /* */ + /* This can be used to write anti-aliased outlines directly to a */ + /* given background bitmap, and even perform translucency. */ + /* */ + /* Note that the `count' field cannot be greater than a fixed value */ + /* defined by the `FT_MAX_GRAY_SPANS' configuration macro in */ + /* `ftoption.h'. By default, this value is set to~32, which means */ + /* that if there are more than 32~spans on a given scanline, the */ + /* callback is called several times with the same `y' parameter in */ + /* order to draw all callbacks. */ + /* */ + /* Otherwise, the callback is only called once per scan-line, and */ + /* only for those scanlines that do have `gray' pixels on them. */ + /* */ + typedef void + (*FT_SpanFunc)( int y, + int count, + const FT_Span* spans, + void* user ); + +#define FT_Raster_Span_Func FT_SpanFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_BitTest_Func */ + /* */ + /* <Description> */ + /* THIS TYPE IS DEPRECATED. DO NOT USE IT. */ + /* */ + /* A function used as a call-back by the monochrome scan-converter */ + /* to test whether a given target pixel is already set to the drawing */ + /* `color'. These tests are crucial to implement drop-out control */ + /* per-se the TrueType spec. */ + /* */ + /* <Input> */ + /* y :: The pixel's y~coordinate. */ + /* */ + /* x :: The pixel's x~coordinate. */ + /* */ + /* user :: User-supplied data that is passed to the callback. */ + /* */ + /* <Return> */ + /* 1~if the pixel is `set', 0~otherwise. */ + /* */ + typedef int + (*FT_Raster_BitTest_Func)( int y, + int x, + void* user ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_BitSet_Func */ + /* */ + /* <Description> */ + /* THIS TYPE IS DEPRECATED. DO NOT USE IT. */ + /* */ + /* A function used as a call-back by the monochrome scan-converter */ + /* to set an individual target pixel. This is crucial to implement */ + /* drop-out control according to the TrueType specification. */ + /* */ + /* <Input> */ + /* y :: The pixel's y~coordinate. */ + /* */ + /* x :: The pixel's x~coordinate. */ + /* */ + /* user :: User-supplied data that is passed to the callback. */ + /* */ + /* <Return> */ + /* 1~if the pixel is `set', 0~otherwise. */ + /* */ + typedef void + (*FT_Raster_BitSet_Func)( int y, + int x, + void* user ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_RASTER_FLAG_XXX */ + /* */ + /* <Description> */ + /* A list of bit flag constants as used in the `flags' field of a */ + /* @FT_Raster_Params structure. */ + /* */ + /* <Values> */ + /* FT_RASTER_FLAG_DEFAULT :: This value is 0. */ + /* */ + /* FT_RASTER_FLAG_AA :: This flag is set to indicate that an */ + /* anti-aliased glyph image should be */ + /* generated. Otherwise, it will be */ + /* monochrome (1-bit). */ + /* */ + /* FT_RASTER_FLAG_DIRECT :: This flag is set to indicate direct */ + /* rendering. In this mode, client */ + /* applications must provide their own span */ + /* callback. This lets them directly */ + /* draw or compose over an existing bitmap. */ + /* If this bit is not set, the target */ + /* pixmap's buffer _must_ be zeroed before */ + /* rendering. */ + /* */ + /* Note that for now, direct rendering is */ + /* only possible with anti-aliased glyphs. */ + /* */ + /* FT_RASTER_FLAG_CLIP :: This flag is only used in direct */ + /* rendering mode. If set, the output will */ + /* be clipped to a box specified in the */ + /* `clip_box' field of the */ + /* @FT_Raster_Params structure. */ + /* */ + /* Note that by default, the glyph bitmap */ + /* is clipped to the target pixmap, except */ + /* in direct rendering mode where all spans */ + /* are generated if no clipping box is set. */ + /* */ +#define FT_RASTER_FLAG_DEFAULT 0x0 +#define FT_RASTER_FLAG_AA 0x1 +#define FT_RASTER_FLAG_DIRECT 0x2 +#define FT_RASTER_FLAG_CLIP 0x4 + + /* deprecated */ +#define ft_raster_flag_default FT_RASTER_FLAG_DEFAULT +#define ft_raster_flag_aa FT_RASTER_FLAG_AA +#define ft_raster_flag_direct FT_RASTER_FLAG_DIRECT +#define ft_raster_flag_clip FT_RASTER_FLAG_CLIP + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Raster_Params */ + /* */ + /* <Description> */ + /* A structure to hold the arguments used by a raster's render */ + /* function. */ + /* */ + /* <Fields> */ + /* target :: The target bitmap. */ + /* */ + /* source :: A pointer to the source glyph image (e.g., an */ + /* @FT_Outline). */ + /* */ + /* flags :: The rendering flags. */ + /* */ + /* gray_spans :: The gray span drawing callback. */ + /* */ + /* black_spans :: The black span drawing callback. UNIMPLEMENTED! */ + /* */ + /* bit_test :: The bit test callback. UNIMPLEMENTED! */ + /* */ + /* bit_set :: The bit set callback. UNIMPLEMENTED! */ + /* */ + /* user :: User-supplied data that is passed to each drawing */ + /* callback. */ + /* */ + /* clip_box :: An optional clipping box. It is only used in */ + /* direct rendering mode. Note that coordinates here */ + /* should be expressed in _integer_ pixels (and not in */ + /* 26.6 fixed-point units). */ + /* */ + /* <Note> */ + /* An anti-aliased glyph bitmap is drawn if the @FT_RASTER_FLAG_AA */ + /* bit flag is set in the `flags' field, otherwise a monochrome */ + /* bitmap is generated. */ + /* */ + /* If the @FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the */ + /* raster will call the `gray_spans' callback to draw gray pixel */ + /* spans, in the case of an aa glyph bitmap, it will call */ + /* `black_spans', and `bit_test' and `bit_set' in the case of a */ + /* monochrome bitmap. This allows direct composition over a */ + /* pre-existing bitmap through user-provided callbacks to perform the */ + /* span drawing/composition. */ + /* */ + /* Note that the `bit_test' and `bit_set' callbacks are required when */ + /* rendering a monochrome bitmap, as they are crucial to implement */ + /* correct drop-out control as defined in the TrueType specification. */ + /* */ + typedef struct FT_Raster_Params_ + { + const FT_Bitmap* target; + const void* source; + int flags; + FT_SpanFunc gray_spans; + FT_SpanFunc black_spans; /* doesn't work! */ + FT_Raster_BitTest_Func bit_test; /* doesn't work! */ + FT_Raster_BitSet_Func bit_set; /* doesn't work! */ + void* user; + FT_BBox clip_box; + + } FT_Raster_Params; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_NewFunc */ + /* */ + /* <Description> */ + /* A function used to create a new raster object. */ + /* */ + /* <Input> */ + /* memory :: A handle to the memory allocator. */ + /* */ + /* <Output> */ + /* raster :: A handle to the new raster object. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + /* <Note> */ + /* The `memory' parameter is a typeless pointer in order to avoid */ + /* un-wanted dependencies on the rest of the FreeType code. In */ + /* practice, it is an @FT_Memory object, i.e., a handle to the */ + /* standard FreeType memory allocator. However, this field can be */ + /* completely ignored by a given raster implementation. */ + /* */ + typedef int + (*FT_Raster_NewFunc)( void* memory, + FT_Raster* raster ); + +#define FT_Raster_New_Func FT_Raster_NewFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_DoneFunc */ + /* */ + /* <Description> */ + /* A function used to destroy a given raster object. */ + /* */ + /* <Input> */ + /* raster :: A handle to the raster object. */ + /* */ + typedef void + (*FT_Raster_DoneFunc)( FT_Raster raster ); + +#define FT_Raster_Done_Func FT_Raster_DoneFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_ResetFunc */ + /* */ + /* <Description> */ + /* FreeType provides an area of memory called the `render pool', */ + /* available to all registered rasters. This pool can be freely used */ + /* during a given scan-conversion but is shared by all rasters. Its */ + /* content is thus transient. */ + /* */ + /* This function is called each time the render pool changes, or just */ + /* after a new raster object is created. */ + /* */ + /* <Input> */ + /* raster :: A handle to the new raster object. */ + /* */ + /* pool_base :: The address in memory of the render pool. */ + /* */ + /* pool_size :: The size in bytes of the render pool. */ + /* */ + /* <Note> */ + /* Rasters can ignore the render pool and rely on dynamic memory */ + /* allocation if they want to (a handle to the memory allocator is */ + /* passed to the raster constructor). However, this is not */ + /* recommended for efficiency purposes. */ + /* */ + typedef void + (*FT_Raster_ResetFunc)( FT_Raster raster, + unsigned char* pool_base, + unsigned long pool_size ); + +#define FT_Raster_Reset_Func FT_Raster_ResetFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_SetModeFunc */ + /* */ + /* <Description> */ + /* This function is a generic facility to change modes or attributes */ + /* in a given raster. This can be used for debugging purposes, or */ + /* simply to allow implementation-specific `features' in a given */ + /* raster module. */ + /* */ + /* <Input> */ + /* raster :: A handle to the new raster object. */ + /* */ + /* mode :: A 4-byte tag used to name the mode or property. */ + /* */ + /* args :: A pointer to the new mode/property to use. */ + /* */ + typedef int + (*FT_Raster_SetModeFunc)( FT_Raster raster, + unsigned long mode, + void* args ); + +#define FT_Raster_Set_Mode_Func FT_Raster_SetModeFunc + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Raster_RenderFunc */ + /* */ + /* <Description> */ + /* Invoke a given raster to scan-convert a given glyph image into a */ + /* target bitmap. */ + /* */ + /* <Input> */ + /* raster :: A handle to the raster object. */ + /* */ + /* params :: A pointer to an @FT_Raster_Params structure used to */ + /* store the rendering parameters. */ + /* */ + /* <Return> */ + /* Error code. 0~means success. */ + /* */ + /* <Note> */ + /* The exact format of the source image depends on the raster's glyph */ + /* format defined in its @FT_Raster_Funcs structure. It can be an */ + /* @FT_Outline or anything else in order to support a large array of */ + /* glyph formats. */ + /* */ + /* Note also that the render function can fail and return a */ + /* `FT_Err_Unimplemented_Feature' error code if the raster used does */ + /* not support direct composition. */ + /* */ + /* XXX: For now, the standard raster doesn't support direct */ + /* composition but this should change for the final release (see */ + /* the files `demos/src/ftgrays.c' and `demos/src/ftgrays2.c' */ + /* for examples of distinct implementations which support direct */ + /* composition). */ + /* */ + typedef int + (*FT_Raster_RenderFunc)( FT_Raster raster, + const FT_Raster_Params* params ); + +#define FT_Raster_Render_Func FT_Raster_RenderFunc + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Raster_Funcs */ + /* */ + /* <Description> */ + /* A structure used to describe a given raster class to the library. */ + /* */ + /* <Fields> */ + /* glyph_format :: The supported glyph format for this raster. */ + /* */ + /* raster_new :: The raster constructor. */ + /* */ + /* raster_reset :: Used to reset the render pool within the raster. */ + /* */ + /* raster_render :: A function to render a glyph into a given bitmap. */ + /* */ + /* raster_done :: The raster destructor. */ + /* */ + typedef struct FT_Raster_Funcs_ + { + FT_Glyph_Format glyph_format; + FT_Raster_NewFunc raster_new; + FT_Raster_ResetFunc raster_reset; + FT_Raster_SetModeFunc raster_set_mode; + FT_Raster_RenderFunc raster_render; + FT_Raster_DoneFunc raster_done; + + } FT_Raster_Funcs; + + + /* */ + + +FT_END_HEADER + +#endif /* __FTIMAGE_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftincrem.h b/other/freetype/include/freetype/ftincrem.h new file mode 100644 index 0000000..aaf689f --- /dev/null +++ b/other/freetype/include/freetype/ftincrem.h @@ -0,0 +1,353 @@ +/***************************************************************************/ +/* */ +/* ftincrem.h */ +/* */ +/* FreeType incremental loading (specification). */ +/* */ +/* Copyright 2002, 2003, 2006, 2007, 2008, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTINCREM_H__ +#define __FTINCREM_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************** + * + * @section: + * incremental + * + * @title: + * Incremental Loading + * + * @abstract: + * Custom Glyph Loading. + * + * @description: + * This section contains various functions used to perform so-called + * `incremental' glyph loading. This is a mode where all glyphs loaded + * from a given @FT_Face are provided by the client application, + * + * Apart from that, all other tables are loaded normally from the font + * file. This mode is useful when FreeType is used within another + * engine, e.g., a PostScript Imaging Processor. + * + * To enable this mode, you must use @FT_Open_Face, passing an + * @FT_Parameter with the @FT_PARAM_TAG_INCREMENTAL tag and an + * @FT_Incremental_Interface value. See the comments for + * @FT_Incremental_InterfaceRec for an example. + * + */ + + + /*************************************************************************** + * + * @type: + * FT_Incremental + * + * @description: + * An opaque type describing a user-provided object used to implement + * `incremental' glyph loading within FreeType. This is used to support + * embedded fonts in certain environments (e.g., PostScript interpreters), + * where the glyph data isn't in the font file, or must be overridden by + * different values. + * + * @note: + * It is up to client applications to create and implement @FT_Incremental + * objects, as long as they provide implementations for the methods + * @FT_Incremental_GetGlyphDataFunc, @FT_Incremental_FreeGlyphDataFunc + * and @FT_Incremental_GetGlyphMetricsFunc. + * + * See the description of @FT_Incremental_InterfaceRec to understand how + * to use incremental objects with FreeType. + * + */ + typedef struct FT_IncrementalRec_* FT_Incremental; + + + /*************************************************************************** + * + * @struct: + * FT_Incremental_MetricsRec + * + * @description: + * A small structure used to contain the basic glyph metrics returned + * by the @FT_Incremental_GetGlyphMetricsFunc method. + * + * @fields: + * bearing_x :: + * Left bearing, in font units. + * + * bearing_y :: + * Top bearing, in font units. + * + * advance :: + * Horizontal component of glyph advance, in font units. + * + * advance_v :: + * Vertical component of glyph advance, in font units. + * + * @note: + * These correspond to horizontal or vertical metrics depending on the + * value of the `vertical' argument to the function + * @FT_Incremental_GetGlyphMetricsFunc. + * + */ + typedef struct FT_Incremental_MetricsRec_ + { + FT_Long bearing_x; + FT_Long bearing_y; + FT_Long advance; + FT_Long advance_v; /* since 2.3.12 */ + + } FT_Incremental_MetricsRec; + + + /*************************************************************************** + * + * @struct: + * FT_Incremental_Metrics + * + * @description: + * A handle to an @FT_Incremental_MetricsRec structure. + * + */ + typedef struct FT_Incremental_MetricsRec_* FT_Incremental_Metrics; + + + /*************************************************************************** + * + * @type: + * FT_Incremental_GetGlyphDataFunc + * + * @description: + * A function called by FreeType to access a given glyph's data bytes + * during @FT_Load_Glyph or @FT_Load_Char if incremental loading is + * enabled. + * + * Note that the format of the glyph's data bytes depends on the font + * file format. For TrueType, it must correspond to the raw bytes within + * the `glyf' table. For PostScript formats, it must correspond to the + * *unencrypted* charstring bytes, without any `lenIV' header. It is + * undefined for any other format. + * + * @input: + * incremental :: + * Handle to an opaque @FT_Incremental handle provided by the client + * application. + * + * glyph_index :: + * Index of relevant glyph. + * + * @output: + * adata :: + * A structure describing the returned glyph data bytes (which will be + * accessed as a read-only byte block). + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * If this function returns successfully the method + * @FT_Incremental_FreeGlyphDataFunc will be called later to release + * the data bytes. + * + * Nested calls to @FT_Incremental_GetGlyphDataFunc can happen for + * compound glyphs. + * + */ + typedef FT_Error + (*FT_Incremental_GetGlyphDataFunc)( FT_Incremental incremental, + FT_UInt glyph_index, + FT_Data* adata ); + + + /*************************************************************************** + * + * @type: + * FT_Incremental_FreeGlyphDataFunc + * + * @description: + * A function used to release the glyph data bytes returned by a + * successful call to @FT_Incremental_GetGlyphDataFunc. + * + * @input: + * incremental :: + * A handle to an opaque @FT_Incremental handle provided by the client + * application. + * + * data :: + * A structure describing the glyph data bytes (which will be accessed + * as a read-only byte block). + * + */ + typedef void + (*FT_Incremental_FreeGlyphDataFunc)( FT_Incremental incremental, + FT_Data* data ); + + + /*************************************************************************** + * + * @type: + * FT_Incremental_GetGlyphMetricsFunc + * + * @description: + * A function used to retrieve the basic metrics of a given glyph index + * before accessing its data. This is necessary because, in certain + * formats like TrueType, the metrics are stored in a different place from + * the glyph images proper. + * + * @input: + * incremental :: + * A handle to an opaque @FT_Incremental handle provided by the client + * application. + * + * glyph_index :: + * Index of relevant glyph. + * + * vertical :: + * If true, return vertical metrics. + * + * ametrics :: + * This parameter is used for both input and output. + * The original glyph metrics, if any, in font units. If metrics are + * not available all the values must be set to zero. + * + * @output: + * ametrics :: + * The replacement glyph metrics in font units. + * + */ + typedef FT_Error + (*FT_Incremental_GetGlyphMetricsFunc) + ( FT_Incremental incremental, + FT_UInt glyph_index, + FT_Bool vertical, + FT_Incremental_MetricsRec *ametrics ); + + + /************************************************************************** + * + * @struct: + * FT_Incremental_FuncsRec + * + * @description: + * A table of functions for accessing fonts that load data + * incrementally. Used in @FT_Incremental_InterfaceRec. + * + * @fields: + * get_glyph_data :: + * The function to get glyph data. Must not be null. + * + * free_glyph_data :: + * The function to release glyph data. Must not be null. + * + * get_glyph_metrics :: + * The function to get glyph metrics. May be null if the font does + * not provide overriding glyph metrics. + * + */ + typedef struct FT_Incremental_FuncsRec_ + { + FT_Incremental_GetGlyphDataFunc get_glyph_data; + FT_Incremental_FreeGlyphDataFunc free_glyph_data; + FT_Incremental_GetGlyphMetricsFunc get_glyph_metrics; + + } FT_Incremental_FuncsRec; + + + /*************************************************************************** + * + * @struct: + * FT_Incremental_InterfaceRec + * + * @description: + * A structure to be used with @FT_Open_Face to indicate that the user + * wants to support incremental glyph loading. You should use it with + * @FT_PARAM_TAG_INCREMENTAL as in the following example: + * + * { + * FT_Incremental_InterfaceRec inc_int; + * FT_Parameter parameter; + * FT_Open_Args open_args; + * + * + * // set up incremental descriptor + * inc_int.funcs = my_funcs; + * inc_int.object = my_object; + * + * // set up optional parameter + * parameter.tag = FT_PARAM_TAG_INCREMENTAL; + * parameter.data = &inc_int; + * + * // set up FT_Open_Args structure + * open_args.flags = FT_OPEN_PATHNAME | FT_OPEN_PARAMS; + * open_args.pathname = my_font_pathname; + * open_args.num_params = 1; + * open_args.params = ¶meter; // we use one optional argument + * + * // open the font + * error = FT_Open_Face( library, &open_args, index, &face ); + * ... + * } + * + */ + typedef struct FT_Incremental_InterfaceRec_ + { + const FT_Incremental_FuncsRec* funcs; + FT_Incremental object; + + } FT_Incremental_InterfaceRec; + + + /*************************************************************************** + * + * @type: + * FT_Incremental_Interface + * + * @description: + * A pointer to an @FT_Incremental_InterfaceRec structure. + * + */ + typedef FT_Incremental_InterfaceRec* FT_Incremental_Interface; + + + /*************************************************************************** + * + * @constant: + * FT_PARAM_TAG_INCREMENTAL + * + * @description: + * A constant used as the tag of @FT_Parameter structures to indicate + * an incremental loading object to be used by FreeType. + * + */ +#define FT_PARAM_TAG_INCREMENTAL FT_MAKE_TAG( 'i', 'n', 'c', 'r' ) + + /* */ + +FT_END_HEADER + +#endif /* __FTINCREM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftlcdfil.h b/other/freetype/include/freetype/ftlcdfil.h new file mode 100644 index 0000000..0b55ebe --- /dev/null +++ b/other/freetype/include/freetype/ftlcdfil.h @@ -0,0 +1,213 @@ +/***************************************************************************/ +/* */ +/* ftlcdfil.h */ +/* */ +/* FreeType API for color filtering of subpixel bitmap glyphs */ +/* (specification). */ +/* */ +/* Copyright 2006, 2007, 2008, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FT_LCD_FILTER_H__ +#define __FT_LCD_FILTER_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************** + * + * @section: + * lcd_filtering + * + * @title: + * LCD Filtering + * + * @abstract: + * Reduce color fringes of LCD-optimized bitmaps. + * + * @description: + * The @FT_Library_SetLcdFilter API can be used to specify a low-pass + * filter which is then applied to LCD-optimized bitmaps generated + * through @FT_Render_Glyph. This is useful to reduce color fringes + * which would occur with unfiltered rendering. + * + * Note that no filter is active by default, and that this function is + * *not* implemented in default builds of the library. You need to + * #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your `ftoption.h' file + * in order to activate it. + */ + + + /**************************************************************************** + * + * @enum: + * FT_LcdFilter + * + * @description: + * A list of values to identify various types of LCD filters. + * + * @values: + * FT_LCD_FILTER_NONE :: + * Do not perform filtering. When used with subpixel rendering, this + * results in sometimes severe color fringes. + * + * FT_LCD_FILTER_DEFAULT :: + * The default filter reduces color fringes considerably, at the cost + * of a slight blurriness in the output. + * + * FT_LCD_FILTER_LIGHT :: + * The light filter is a variant that produces less blurriness at the + * cost of slightly more color fringes than the default one. It might + * be better, depending on taste, your monitor, or your personal vision. + * + * FT_LCD_FILTER_LEGACY :: + * This filter corresponds to the original libXft color filter. It + * provides high contrast output but can exhibit really bad color + * fringes if glyphs are not extremely well hinted to the pixel grid. + * In other words, it only works well if the TrueType bytecode + * interpreter is enabled *and* high-quality hinted fonts are used. + * + * This filter is only provided for comparison purposes, and might be + * disabled or stay unsupported in the future. + * + * @since: + * 2.3.0 + */ + typedef enum FT_LcdFilter_ + { + FT_LCD_FILTER_NONE = 0, + FT_LCD_FILTER_DEFAULT = 1, + FT_LCD_FILTER_LIGHT = 2, + FT_LCD_FILTER_LEGACY = 16, + + FT_LCD_FILTER_MAX /* do not remove */ + + } FT_LcdFilter; + + + /************************************************************************** + * + * @func: + * FT_Library_SetLcdFilter + * + * @description: + * This function is used to apply color filtering to LCD decimated + * bitmaps, like the ones used when calling @FT_Render_Glyph with + * @FT_RENDER_MODE_LCD or @FT_RENDER_MODE_LCD_V. + * + * @input: + * library :: + * A handle to the target library instance. + * + * filter :: + * The filter type. + * + * You can use @FT_LCD_FILTER_NONE here to disable this feature, or + * @FT_LCD_FILTER_DEFAULT to use a default filter that should work + * well on most LCD screens. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This feature is always disabled by default. Clients must make an + * explicit call to this function with a `filter' value other than + * @FT_LCD_FILTER_NONE in order to enable it. + * + * Due to *PATENTS* covering subpixel rendering, this function doesn't + * do anything except returning `FT_Err_Unimplemented_Feature' if the + * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not + * defined in your build of the library, which should correspond to all + * default builds of FreeType. + * + * The filter affects glyph bitmaps rendered through @FT_Render_Glyph, + * @FT_Outline_Get_Bitmap, @FT_Load_Glyph, and @FT_Load_Char. + * + * It does _not_ affect the output of @FT_Outline_Render and + * @FT_Outline_Get_Bitmap. + * + * If this feature is activated, the dimensions of LCD glyph bitmaps are + * either larger or taller than the dimensions of the corresponding + * outline with regards to the pixel grid. For example, for + * @FT_RENDER_MODE_LCD, the filter adds up to 3~pixels to the left, and + * up to 3~pixels to the right. + * + * The bitmap offset values are adjusted correctly, so clients shouldn't + * need to modify their layout and glyph positioning code when enabling + * the filter. + * + * @since: + * 2.3.0 + */ + FT_EXPORT( FT_Error ) + FT_Library_SetLcdFilter( FT_Library library, + FT_LcdFilter filter ); + + + /************************************************************************** + * + * @func: + * FT_Library_SetLcdFilterWeights + * + * @description: + * Use this function to override the filter weights selected by + * @FT_Library_SetLcdFilter. By default, FreeType uses the quintuple + * (0x00, 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, + * 0x40, 0x70, 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and + * FT_LCD_FILTER_LEGACY. + * + * @input: + * library :: + * A handle to the target library instance. + * + * weights :: + * A pointer to an array; the function copies the first five bytes and + * uses them to specify the filter weights. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * Due to *PATENTS* covering subpixel rendering, this function doesn't + * do anything except returning `FT_Err_Unimplemented_Feature' if the + * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not + * defined in your build of the library, which should correspond to all + * default builds of FreeType. + * + * This function must be called after @FT_Library_SetLcdFilter to have + * any effect. + * + * @since: + * 2.4.0 + */ + FT_EXPORT( FT_Error ) + FT_Library_SetLcdFilterWeights( FT_Library library, + unsigned char *weights ); + + /* */ + + +FT_END_HEADER + +#endif /* __FT_LCD_FILTER_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftlist.h b/other/freetype/include/freetype/ftlist.h new file mode 100644 index 0000000..bb6f7f1 --- /dev/null +++ b/other/freetype/include/freetype/ftlist.h @@ -0,0 +1,277 @@ +/***************************************************************************/ +/* */ +/* ftlist.h */ +/* */ +/* Generic list support for FreeType (specification). */ +/* */ +/* Copyright 1996-2001, 2003, 2007, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file implements functions relative to list processing. Its */ + /* data structures are defined in `freetype.h'. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTLIST_H__ +#define __FTLIST_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* list_processing */ + /* */ + /* <Title> */ + /* List Processing */ + /* */ + /* <Abstract> */ + /* Simple management of lists. */ + /* */ + /* <Description> */ + /* This section contains various definitions related to list */ + /* processing using doubly-linked nodes. */ + /* */ + /* <Order> */ + /* FT_List */ + /* FT_ListNode */ + /* FT_ListRec */ + /* FT_ListNodeRec */ + /* */ + /* FT_List_Add */ + /* FT_List_Insert */ + /* FT_List_Find */ + /* FT_List_Remove */ + /* FT_List_Up */ + /* FT_List_Iterate */ + /* FT_List_Iterator */ + /* FT_List_Finalize */ + /* FT_List_Destructor */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Find */ + /* */ + /* <Description> */ + /* Find the list node for a given listed object. */ + /* */ + /* <Input> */ + /* list :: A pointer to the parent list. */ + /* data :: The address of the listed object. */ + /* */ + /* <Return> */ + /* List node. NULL if it wasn't found. */ + /* */ + FT_EXPORT( FT_ListNode ) + FT_List_Find( FT_List list, + void* data ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Add */ + /* */ + /* <Description> */ + /* Append an element to the end of a list. */ + /* */ + /* <InOut> */ + /* list :: A pointer to the parent list. */ + /* node :: The node to append. */ + /* */ + FT_EXPORT( void ) + FT_List_Add( FT_List list, + FT_ListNode node ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Insert */ + /* */ + /* <Description> */ + /* Insert an element at the head of a list. */ + /* */ + /* <InOut> */ + /* list :: A pointer to parent list. */ + /* node :: The node to insert. */ + /* */ + FT_EXPORT( void ) + FT_List_Insert( FT_List list, + FT_ListNode node ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Remove */ + /* */ + /* <Description> */ + /* Remove a node from a list. This function doesn't check whether */ + /* the node is in the list! */ + /* */ + /* <Input> */ + /* node :: The node to remove. */ + /* */ + /* <InOut> */ + /* list :: A pointer to the parent list. */ + /* */ + FT_EXPORT( void ) + FT_List_Remove( FT_List list, + FT_ListNode node ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Up */ + /* */ + /* <Description> */ + /* Move a node to the head/top of a list. Used to maintain LRU */ + /* lists. */ + /* */ + /* <InOut> */ + /* list :: A pointer to the parent list. */ + /* node :: The node to move. */ + /* */ + FT_EXPORT( void ) + FT_List_Up( FT_List list, + FT_ListNode node ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_List_Iterator */ + /* */ + /* <Description> */ + /* An FT_List iterator function which is called during a list parse */ + /* by @FT_List_Iterate. */ + /* */ + /* <Input> */ + /* node :: The current iteration list node. */ + /* */ + /* user :: A typeless pointer passed to @FT_List_Iterate. */ + /* Can be used to point to the iteration's state. */ + /* */ + typedef FT_Error + (*FT_List_Iterator)( FT_ListNode node, + void* user ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Iterate */ + /* */ + /* <Description> */ + /* Parse a list and calls a given iterator function on each element. */ + /* Note that parsing is stopped as soon as one of the iterator calls */ + /* returns a non-zero value. */ + /* */ + /* <Input> */ + /* list :: A handle to the list. */ + /* iterator :: An iterator function, called on each node of the list. */ + /* user :: A user-supplied field which is passed as the second */ + /* argument to the iterator. */ + /* */ + /* <Return> */ + /* The result (a FreeType error code) of the last iterator call. */ + /* */ + FT_EXPORT( FT_Error ) + FT_List_Iterate( FT_List list, + FT_List_Iterator iterator, + void* user ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_List_Destructor */ + /* */ + /* <Description> */ + /* An @FT_List iterator function which is called during a list */ + /* finalization by @FT_List_Finalize to destroy all elements in a */ + /* given list. */ + /* */ + /* <Input> */ + /* system :: The current system object. */ + /* */ + /* data :: The current object to destroy. */ + /* */ + /* user :: A typeless pointer passed to @FT_List_Iterate. It can */ + /* be used to point to the iteration's state. */ + /* */ + typedef void + (*FT_List_Destructor)( FT_Memory memory, + void* data, + void* user ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_List_Finalize */ + /* */ + /* <Description> */ + /* Destroy all elements in the list as well as the list itself. */ + /* */ + /* <Input> */ + /* list :: A handle to the list. */ + /* */ + /* destroy :: A list destructor that will be applied to each element */ + /* of the list. */ + /* */ + /* memory :: The current memory object which handles deallocation. */ + /* */ + /* user :: A user-supplied field which is passed as the last */ + /* argument to the destructor. */ + /* */ + /* <Note> */ + /* This function expects that all nodes added by @FT_List_Add or */ + /* @FT_List_Insert have been dynamically allocated. */ + /* */ + FT_EXPORT( void ) + FT_List_Finalize( FT_List list, + FT_List_Destructor destroy, + FT_Memory memory, + void* user ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTLIST_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftlzw.h b/other/freetype/include/freetype/ftlzw.h new file mode 100644 index 0000000..00d4016 --- /dev/null +++ b/other/freetype/include/freetype/ftlzw.h @@ -0,0 +1,99 @@ +/***************************************************************************/ +/* */ +/* ftlzw.h */ +/* */ +/* LZW-compressed stream support. */ +/* */ +/* Copyright 2004, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTLZW_H__ +#define __FTLZW_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************/ + /* */ + /* <Section> */ + /* lzw */ + /* */ + /* <Title> */ + /* LZW Streams */ + /* */ + /* <Abstract> */ + /* Using LZW-compressed font files. */ + /* */ + /* <Description> */ + /* This section contains the declaration of LZW-specific functions. */ + /* */ + /*************************************************************************/ + + /************************************************************************ + * + * @function: + * FT_Stream_OpenLZW + * + * @description: + * Open a new stream to parse LZW-compressed font files. This is + * mainly used to support the compressed `*.pcf.Z' fonts that come + * with XFree86. + * + * @input: + * stream :: The target embedding stream. + * + * source :: The source stream. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The source stream must be opened _before_ calling this function. + * + * Calling the internal function `FT_Stream_Close' on the new stream will + * *not* call `FT_Stream_Close' on the source stream. None of the stream + * objects will be released to the heap. + * + * The stream implementation is very basic and resets the decompression + * process each time seeking backwards is needed within the stream + * + * In certain builds of the library, LZW compression recognition is + * automatically handled when calling @FT_New_Face or @FT_Open_Face. + * This means that if no font driver is capable of handling the raw + * compressed file, the library will try to open a LZW stream from it + * and re-open the face with it. + * + * This function may return `FT_Err_Unimplemented_Feature' if your build + * of FreeType was not compiled with LZW support. + */ + FT_EXPORT( FT_Error ) + FT_Stream_OpenLZW( FT_Stream stream, + FT_Stream source ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTLZW_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftmac.h b/other/freetype/include/freetype/ftmac.h new file mode 100644 index 0000000..ab5bab5 --- /dev/null +++ b/other/freetype/include/freetype/ftmac.h @@ -0,0 +1,274 @@ +/***************************************************************************/ +/* */ +/* ftmac.h */ +/* */ +/* Additional Mac-specific API. */ +/* */ +/* Copyright 1996-2001, 2004, 2006, 2007 by */ +/* Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* NOTE: Include this file after <freetype/freetype.h> and after any */ +/* Mac-specific headers (because this header uses Mac types such as */ +/* Handle, FSSpec, FSRef, etc.) */ +/* */ +/***************************************************************************/ + + +#ifndef __FTMAC_H__ +#define __FTMAC_H__ + + +#include <ft2build.h> + + +FT_BEGIN_HEADER + + +/* gcc-3.4.1 and later can warn about functions tagged as deprecated */ +#ifndef FT_DEPRECATED_ATTRIBUTE +#if defined(__GNUC__) && \ + ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) +#define FT_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) +#else +#define FT_DEPRECATED_ATTRIBUTE +#endif +#endif + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* mac_specific */ + /* */ + /* <Title> */ + /* Mac Specific Interface */ + /* */ + /* <Abstract> */ + /* Only available on the Macintosh. */ + /* */ + /* <Description> */ + /* The following definitions are only available if FreeType is */ + /* compiled on a Macintosh. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Face_From_FOND */ + /* */ + /* <Description> */ + /* Create a new face object from a FOND resource. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* fond :: A FOND resource. */ + /* */ + /* face_index :: Only supported for the -1 `sanity check' special */ + /* case. */ + /* */ + /* <Output> */ + /* aface :: A handle to a new face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Notes> */ + /* This function can be used to create @FT_Face objects from fonts */ + /* that are installed in the system as follows. */ + /* */ + /* { */ + /* fond = GetResource( 'FOND', fontName ); */ + /* error = FT_New_Face_From_FOND( library, fond, 0, &face ); */ + /* } */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Face_From_FOND( FT_Library library, + Handle fond, + FT_Long face_index, + FT_Face *aface ) + FT_DEPRECATED_ATTRIBUTE; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_GetFile_From_Mac_Name */ + /* */ + /* <Description> */ + /* Return an FSSpec for the disk file containing the named font. */ + /* */ + /* <Input> */ + /* fontName :: Mac OS name of the font (e.g., Times New Roman */ + /* Bold). */ + /* */ + /* <Output> */ + /* pathSpec :: FSSpec to the file. For passing to */ + /* @FT_New_Face_From_FSSpec. */ + /* */ + /* face_index :: Index of the face. For passing to */ + /* @FT_New_Face_From_FSSpec. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_GetFile_From_Mac_Name( const char* fontName, + FSSpec* pathSpec, + FT_Long* face_index ) + FT_DEPRECATED_ATTRIBUTE; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_GetFile_From_Mac_ATS_Name */ + /* */ + /* <Description> */ + /* Return an FSSpec for the disk file containing the named font. */ + /* */ + /* <Input> */ + /* fontName :: Mac OS name of the font in ATS framework. */ + /* */ + /* <Output> */ + /* pathSpec :: FSSpec to the file. For passing to */ + /* @FT_New_Face_From_FSSpec. */ + /* */ + /* face_index :: Index of the face. For passing to */ + /* @FT_New_Face_From_FSSpec. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_GetFile_From_Mac_ATS_Name( const char* fontName, + FSSpec* pathSpec, + FT_Long* face_index ) + FT_DEPRECATED_ATTRIBUTE; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_GetFilePath_From_Mac_ATS_Name */ + /* */ + /* <Description> */ + /* Return a pathname of the disk file and face index for given font */ + /* name which is handled by ATS framework. */ + /* */ + /* <Input> */ + /* fontName :: Mac OS name of the font in ATS framework. */ + /* */ + /* <Output> */ + /* path :: Buffer to store pathname of the file. For passing */ + /* to @FT_New_Face. The client must allocate this */ + /* buffer before calling this function. */ + /* */ + /* maxPathSize :: Lengths of the buffer `path' that client allocated. */ + /* */ + /* face_index :: Index of the face. For passing to @FT_New_Face. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_GetFilePath_From_Mac_ATS_Name( const char* fontName, + UInt8* path, + UInt32 maxPathSize, + FT_Long* face_index ) + FT_DEPRECATED_ATTRIBUTE; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Face_From_FSSpec */ + /* */ + /* <Description> */ + /* Create a new face object from a given resource and typeface index */ + /* using an FSSpec to the font file. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* spec :: FSSpec to the font file. */ + /* */ + /* face_index :: The index of the face within the resource. The */ + /* first face has index~0. */ + /* <Output> */ + /* aface :: A handle to a new face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* @FT_New_Face_From_FSSpec is identical to @FT_New_Face except */ + /* it accepts an FSSpec instead of a path. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Face_From_FSSpec( FT_Library library, + const FSSpec *spec, + FT_Long face_index, + FT_Face *aface ) + FT_DEPRECATED_ATTRIBUTE; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Face_From_FSRef */ + /* */ + /* <Description> */ + /* Create a new face object from a given resource and typeface index */ + /* using an FSRef to the font file. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library resource. */ + /* */ + /* <Input> */ + /* spec :: FSRef to the font file. */ + /* */ + /* face_index :: The index of the face within the resource. The */ + /* first face has index~0. */ + /* <Output> */ + /* aface :: A handle to a new face object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* @FT_New_Face_From_FSRef is identical to @FT_New_Face except */ + /* it accepts an FSRef instead of a path. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Face_From_FSRef( FT_Library library, + const FSRef *ref, + FT_Long face_index, + FT_Face *aface ) + FT_DEPRECATED_ATTRIBUTE; + + /* */ + + +FT_END_HEADER + + +#endif /* __FTMAC_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftmm.h b/other/freetype/include/freetype/ftmm.h new file mode 100644 index 0000000..3aefb9e --- /dev/null +++ b/other/freetype/include/freetype/ftmm.h @@ -0,0 +1,378 @@ +/***************************************************************************/ +/* */ +/* ftmm.h */ +/* */ +/* FreeType Multiple Master font interface (specification). */ +/* */ +/* Copyright 1996-2001, 2003, 2004, 2006, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTMM_H__ +#define __FTMM_H__ + + +#include <ft2build.h> +#include FT_TYPE1_TABLES_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* multiple_masters */ + /* */ + /* <Title> */ + /* Multiple Masters */ + /* */ + /* <Abstract> */ + /* How to manage Multiple Masters fonts. */ + /* */ + /* <Description> */ + /* The following types and functions are used to manage Multiple */ + /* Master fonts, i.e., the selection of specific design instances by */ + /* setting design axis coordinates. */ + /* */ + /* George Williams has extended this interface to make it work with */ + /* both Type~1 Multiple Masters fonts and GX distortable (var) */ + /* fonts. Some of these routines only work with MM fonts, others */ + /* will work with both types. They are similar enough that a */ + /* consistent interface makes sense. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_MM_Axis */ + /* */ + /* <Description> */ + /* A simple structure used to model a given axis in design space for */ + /* Multiple Masters fonts. */ + /* */ + /* This structure can't be used for GX var fonts. */ + /* */ + /* <Fields> */ + /* name :: The axis's name. */ + /* */ + /* minimum :: The axis's minimum design coordinate. */ + /* */ + /* maximum :: The axis's maximum design coordinate. */ + /* */ + typedef struct FT_MM_Axis_ + { + FT_String* name; + FT_Long minimum; + FT_Long maximum; + + } FT_MM_Axis; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Multi_Master */ + /* */ + /* <Description> */ + /* A structure used to model the axes and space of a Multiple Masters */ + /* font. */ + /* */ + /* This structure can't be used for GX var fonts. */ + /* */ + /* <Fields> */ + /* num_axis :: Number of axes. Cannot exceed~4. */ + /* */ + /* num_designs :: Number of designs; should be normally 2^num_axis */ + /* even though the Type~1 specification strangely */ + /* allows for intermediate designs to be present. This */ + /* number cannot exceed~16. */ + /* */ + /* axis :: A table of axis descriptors. */ + /* */ + typedef struct FT_Multi_Master_ + { + FT_UInt num_axis; + FT_UInt num_designs; + FT_MM_Axis axis[T1_MAX_MM_AXIS]; + + } FT_Multi_Master; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Var_Axis */ + /* */ + /* <Description> */ + /* A simple structure used to model a given axis in design space for */ + /* Multiple Masters and GX var fonts. */ + /* */ + /* <Fields> */ + /* name :: The axis's name. */ + /* Not always meaningful for GX. */ + /* */ + /* minimum :: The axis's minimum design coordinate. */ + /* */ + /* def :: The axis's default design coordinate. */ + /* FreeType computes meaningful default values for MM; it */ + /* is then an integer value, not in 16.16 format. */ + /* */ + /* maximum :: The axis's maximum design coordinate. */ + /* */ + /* tag :: The axis's tag (the GX equivalent to `name'). */ + /* FreeType provides default values for MM if possible. */ + /* */ + /* strid :: The entry in `name' table (another GX version of */ + /* `name'). */ + /* Not meaningful for MM. */ + /* */ + typedef struct FT_Var_Axis_ + { + FT_String* name; + + FT_Fixed minimum; + FT_Fixed def; + FT_Fixed maximum; + + FT_ULong tag; + FT_UInt strid; + + } FT_Var_Axis; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Var_Named_Style */ + /* */ + /* <Description> */ + /* A simple structure used to model a named style in a GX var font. */ + /* */ + /* This structure can't be used for MM fonts. */ + /* */ + /* <Fields> */ + /* coords :: The design coordinates for this style. */ + /* This is an array with one entry for each axis. */ + /* */ + /* strid :: The entry in `name' table identifying this style. */ + /* */ + typedef struct FT_Var_Named_Style_ + { + FT_Fixed* coords; + FT_UInt strid; + + } FT_Var_Named_Style; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_MM_Var */ + /* */ + /* <Description> */ + /* A structure used to model the axes and space of a Multiple Masters */ + /* or GX var distortable font. */ + /* */ + /* Some fields are specific to one format and not to the other. */ + /* */ + /* <Fields> */ + /* num_axis :: The number of axes. The maximum value is~4 for */ + /* MM; no limit in GX. */ + /* */ + /* num_designs :: The number of designs; should be normally */ + /* 2^num_axis for MM fonts. Not meaningful for GX */ + /* (where every glyph could have a different */ + /* number of designs). */ + /* */ + /* num_namedstyles :: The number of named styles; only meaningful for */ + /* GX which allows certain design coordinates to */ + /* have a string ID (in the `name' table) */ + /* associated with them. The font can tell the */ + /* user that, for example, Weight=1.5 is `Bold'. */ + /* */ + /* axis :: A table of axis descriptors. */ + /* GX fonts contain slightly more data than MM. */ + /* */ + /* namedstyles :: A table of named styles. */ + /* Only meaningful with GX. */ + /* */ + typedef struct FT_MM_Var_ + { + FT_UInt num_axis; + FT_UInt num_designs; + FT_UInt num_namedstyles; + FT_Var_Axis* axis; + FT_Var_Named_Style* namedstyle; + + } FT_MM_Var; + + + /* */ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Multi_Master */ + /* */ + /* <Description> */ + /* Retrieve the Multiple Master descriptor of a given font. */ + /* */ + /* This function can't be used with GX fonts. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face. */ + /* */ + /* <Output> */ + /* amaster :: The Multiple Masters descriptor. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Multi_Master( FT_Face face, + FT_Multi_Master *amaster ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_MM_Var */ + /* */ + /* <Description> */ + /* Retrieve the Multiple Master/GX var descriptor of a given font. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face. */ + /* */ + /* <Output> */ + /* amaster :: The Multiple Masters/GX var descriptor. */ + /* Allocates a data structure, which the user must free */ + /* (a single call to FT_FREE will do it). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_MM_Var( FT_Face face, + FT_MM_Var* *amaster ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_MM_Design_Coordinates */ + /* */ + /* <Description> */ + /* For Multiple Masters fonts, choose an interpolated font design */ + /* through design coordinates. */ + /* */ + /* This function can't be used with GX fonts. */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face. */ + /* */ + /* <Input> */ + /* num_coords :: The number of design coordinates (must be equal to */ + /* the number of axes in the font). */ + /* */ + /* coords :: An array of design coordinates. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_MM_Design_Coordinates( FT_Face face, + FT_UInt num_coords, + FT_Long* coords ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Var_Design_Coordinates */ + /* */ + /* <Description> */ + /* For Multiple Master or GX Var fonts, choose an interpolated font */ + /* design through design coordinates. */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face. */ + /* */ + /* <Input> */ + /* num_coords :: The number of design coordinates (must be equal to */ + /* the number of axes in the font). */ + /* */ + /* coords :: An array of design coordinates. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Var_Design_Coordinates( FT_Face face, + FT_UInt num_coords, + FT_Fixed* coords ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_MM_Blend_Coordinates */ + /* */ + /* <Description> */ + /* For Multiple Masters and GX var fonts, choose an interpolated font */ + /* design through normalized blend coordinates. */ + /* */ + /* <InOut> */ + /* face :: A handle to the source face. */ + /* */ + /* <Input> */ + /* num_coords :: The number of design coordinates (must be equal to */ + /* the number of axes in the font). */ + /* */ + /* coords :: The design coordinates array (each element must be */ + /* between 0 and 1.0). */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_MM_Blend_Coordinates( FT_Face face, + FT_UInt num_coords, + FT_Fixed* coords ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Var_Blend_Coordinates */ + /* */ + /* <Description> */ + /* This is another name of @FT_Set_MM_Blend_Coordinates. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Var_Blend_Coordinates( FT_Face face, + FT_UInt num_coords, + FT_Fixed* coords ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTMM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftmodapi.h b/other/freetype/include/freetype/ftmodapi.h new file mode 100644 index 0000000..8f2e017 --- /dev/null +++ b/other/freetype/include/freetype/ftmodapi.h @@ -0,0 +1,483 @@ +/***************************************************************************/ +/* */ +/* ftmodapi.h */ +/* */ +/* FreeType modules public interface (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2006, 2008, 2009, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTMODAPI_H__ +#define __FTMODAPI_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* module_management */ + /* */ + /* <Title> */ + /* Module Management */ + /* */ + /* <Abstract> */ + /* How to add, upgrade, and remove modules from FreeType. */ + /* */ + /* <Description> */ + /* The definitions below are used to manage modules within FreeType. */ + /* Modules can be added, upgraded, and removed at runtime. */ + /* */ + /*************************************************************************/ + + + /* module bit flags */ +#define FT_MODULE_FONT_DRIVER 1 /* this module is a font driver */ +#define FT_MODULE_RENDERER 2 /* this module is a renderer */ +#define FT_MODULE_HINTER 4 /* this module is a glyph hinter */ +#define FT_MODULE_STYLER 8 /* this module is a styler */ + +#define FT_MODULE_DRIVER_SCALABLE 0x100 /* the driver supports */ + /* scalable fonts */ +#define FT_MODULE_DRIVER_NO_OUTLINES 0x200 /* the driver does not */ + /* support vector outlines */ +#define FT_MODULE_DRIVER_HAS_HINTER 0x400 /* the driver provides its */ + /* own hinter */ + + + /* deprecated values */ +#define ft_module_font_driver FT_MODULE_FONT_DRIVER +#define ft_module_renderer FT_MODULE_RENDERER +#define ft_module_hinter FT_MODULE_HINTER +#define ft_module_styler FT_MODULE_STYLER + +#define ft_module_driver_scalable FT_MODULE_DRIVER_SCALABLE +#define ft_module_driver_no_outlines FT_MODULE_DRIVER_NO_OUTLINES +#define ft_module_driver_has_hinter FT_MODULE_DRIVER_HAS_HINTER + + + typedef FT_Pointer FT_Module_Interface; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Module_Constructor */ + /* */ + /* <Description> */ + /* A function used to initialize (not create) a new module object. */ + /* */ + /* <Input> */ + /* module :: The module to initialize. */ + /* */ + typedef FT_Error + (*FT_Module_Constructor)( FT_Module module ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Module_Destructor */ + /* */ + /* <Description> */ + /* A function used to finalize (not destroy) a given module object. */ + /* */ + /* <Input> */ + /* module :: The module to finalize. */ + /* */ + typedef void + (*FT_Module_Destructor)( FT_Module module ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Module_Requester */ + /* */ + /* <Description> */ + /* A function used to query a given module for a specific interface. */ + /* */ + /* <Input> */ + /* module :: The module to finalize. */ + /* */ + /* name :: The name of the interface in the module. */ + /* */ + typedef FT_Module_Interface + (*FT_Module_Requester)( FT_Module module, + const char* name ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Module_Class */ + /* */ + /* <Description> */ + /* The module class descriptor. */ + /* */ + /* <Fields> */ + /* module_flags :: Bit flags describing the module. */ + /* */ + /* module_size :: The size of one module object/instance in */ + /* bytes. */ + /* */ + /* module_name :: The name of the module. */ + /* */ + /* module_version :: The version, as a 16.16 fixed number */ + /* (major.minor). */ + /* */ + /* module_requires :: The version of FreeType this module requires, */ + /* as a 16.16 fixed number (major.minor). Starts */ + /* at version 2.0, i.e., 0x20000. */ + /* */ + /* module_init :: The initializing function. */ + /* */ + /* module_done :: The finalizing function. */ + /* */ + /* get_interface :: The interface requesting function. */ + /* */ + typedef struct FT_Module_Class_ + { + FT_ULong module_flags; + FT_Long module_size; + const FT_String* module_name; + FT_Fixed module_version; + FT_Fixed module_requires; + + const void* module_interface; + + FT_Module_Constructor module_init; + FT_Module_Destructor module_done; + FT_Module_Requester get_interface; + + } FT_Module_Class; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Add_Module */ + /* */ + /* <Description> */ + /* Add a new module to a given library instance. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library object. */ + /* */ + /* <Input> */ + /* clazz :: A pointer to class descriptor for the module. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* An error will be returned if a module already exists by that name, */ + /* or if the module requires a version of FreeType that is too great. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Add_Module( FT_Library library, + const FT_Module_Class* clazz ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Module */ + /* */ + /* <Description> */ + /* Find a module by its name. */ + /* */ + /* <Input> */ + /* library :: A handle to the library object. */ + /* */ + /* module_name :: The module's name (as an ASCII string). */ + /* */ + /* <Return> */ + /* A module handle. 0~if none was found. */ + /* */ + /* <Note> */ + /* FreeType's internal modules aren't documented very well, and you */ + /* should look up the source code for details. */ + /* */ + FT_EXPORT( FT_Module ) + FT_Get_Module( FT_Library library, + const char* module_name ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Remove_Module */ + /* */ + /* <Description> */ + /* Remove a given module from a library instance. */ + /* */ + /* <InOut> */ + /* library :: A handle to a library object. */ + /* */ + /* <Input> */ + /* module :: A handle to a module object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The module object is destroyed by the function in case of success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Remove_Module( FT_Library library, + FT_Module module ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Reference_Library */ + /* */ + /* <Description> */ + /* A counter gets initialized to~1 at the time an @FT_Library */ + /* structure is created. This function increments the counter. */ + /* @FT_Done_Library then only destroys a library if the counter is~1, */ + /* otherwise it simply decrements the counter. */ + /* */ + /* This function helps in managing life-cycles of structures which */ + /* reference @FT_Library objects. */ + /* */ + /* <Input> */ + /* library :: A handle to a target library object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Since> */ + /* 2.4.2 */ + /* */ + FT_EXPORT( FT_Error ) + FT_Reference_Library( FT_Library library ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Library */ + /* */ + /* <Description> */ + /* This function is used to create a new FreeType library instance */ + /* from a given memory object. It is thus possible to use libraries */ + /* with distinct memory allocators within the same program. */ + /* */ + /* Normally, you would call this function (followed by a call to */ + /* @FT_Add_Default_Modules or a series of calls to @FT_Add_Module) */ + /* instead of @FT_Init_FreeType to initialize the FreeType library. */ + /* */ + /* Don't use @FT_Done_FreeType but @FT_Done_Library to destroy a */ + /* library instance. */ + /* */ + /* <Input> */ + /* memory :: A handle to the original memory object. */ + /* */ + /* <Output> */ + /* alibrary :: A pointer to handle of a new library object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* See the discussion of reference counters in the description of */ + /* @FT_Reference_Library. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Library( FT_Memory memory, + FT_Library *alibrary ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_Library */ + /* */ + /* <Description> */ + /* Discard a given library object. This closes all drivers and */ + /* discards all resource objects. */ + /* */ + /* <Input> */ + /* library :: A handle to the target library. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* See the discussion of reference counters in the description of */ + /* @FT_Reference_Library. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Done_Library( FT_Library library ); + +/* */ + + typedef void + (*FT_DebugHook_Func)( void* arg ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Debug_Hook */ + /* */ + /* <Description> */ + /* Set a debug hook function for debugging the interpreter of a font */ + /* format. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library object. */ + /* */ + /* <Input> */ + /* hook_index :: The index of the debug hook. You should use the */ + /* values defined in `ftobjs.h', e.g., */ + /* `FT_DEBUG_HOOK_TRUETYPE'. */ + /* */ + /* debug_hook :: The function used to debug the interpreter. */ + /* */ + /* <Note> */ + /* Currently, four debug hook slots are available, but only two (for */ + /* the TrueType and the Type~1 interpreter) are defined. */ + /* */ + /* Since the internal headers of FreeType are no longer installed, */ + /* the symbol `FT_DEBUG_HOOK_TRUETYPE' isn't available publicly. */ + /* This is a bug and will be fixed in a forthcoming release. */ + /* */ + FT_EXPORT( void ) + FT_Set_Debug_Hook( FT_Library library, + FT_UInt hook_index, + FT_DebugHook_Func debug_hook ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Add_Default_Modules */ + /* */ + /* <Description> */ + /* Add the set of default drivers to a given library object. */ + /* This is only useful when you create a library object with */ + /* @FT_New_Library (usually to plug a custom memory manager). */ + /* */ + /* <InOut> */ + /* library :: A handle to a new library object. */ + /* */ + FT_EXPORT( void ) + FT_Add_Default_Modules( FT_Library library ); + + + + /************************************************************************** + * + * @section: + * truetype_engine + * + * @title: + * The TrueType Engine + * + * @abstract: + * TrueType bytecode support. + * + * @description: + * This section contains a function used to query the level of TrueType + * bytecode support compiled in this version of the library. + * + */ + + + /************************************************************************** + * + * @enum: + * FT_TrueTypeEngineType + * + * @description: + * A list of values describing which kind of TrueType bytecode + * engine is implemented in a given FT_Library instance. It is used + * by the @FT_Get_TrueType_Engine_Type function. + * + * @values: + * FT_TRUETYPE_ENGINE_TYPE_NONE :: + * The library doesn't implement any kind of bytecode interpreter. + * + * FT_TRUETYPE_ENGINE_TYPE_UNPATENTED :: + * The library implements a bytecode interpreter that doesn't + * support the patented operations of the TrueType virtual machine. + * + * Its main use is to load certain Asian fonts which position and + * scale glyph components with bytecode instructions. It produces + * bad output for most other fonts. + * + * FT_TRUETYPE_ENGINE_TYPE_PATENTED :: + * The library implements a bytecode interpreter that covers + * the full instruction set of the TrueType virtual machine (this + * was governed by patents until May 2010, hence the name). + * + * @since: + * 2.2 + * + */ + typedef enum FT_TrueTypeEngineType_ + { + FT_TRUETYPE_ENGINE_TYPE_NONE = 0, + FT_TRUETYPE_ENGINE_TYPE_UNPATENTED, + FT_TRUETYPE_ENGINE_TYPE_PATENTED + + } FT_TrueTypeEngineType; + + + /************************************************************************** + * + * @func: + * FT_Get_TrueType_Engine_Type + * + * @description: + * Return an @FT_TrueTypeEngineType value to indicate which level of + * the TrueType virtual machine a given library instance supports. + * + * @input: + * library :: + * A library instance. + * + * @return: + * A value indicating which level is supported. + * + * @since: + * 2.2 + * + */ + FT_EXPORT( FT_TrueTypeEngineType ) + FT_Get_TrueType_Engine_Type( FT_Library library ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTMODAPI_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftmoderr.h b/other/freetype/include/freetype/ftmoderr.h new file mode 100644 index 0000000..1bf3b38 --- /dev/null +++ b/other/freetype/include/freetype/ftmoderr.h @@ -0,0 +1,156 @@ +/***************************************************************************/ +/* */ +/* ftmoderr.h */ +/* */ +/* FreeType module error offsets (specification). */ +/* */ +/* Copyright 2001, 2002, 2003, 2004, 2005, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file is used to define the FreeType module error offsets. */ + /* */ + /* The lower byte gives the error code, the higher byte gives the */ + /* module. The base module has error offset 0. For example, the error */ + /* `FT_Err_Invalid_File_Format' has value 0x003, the error */ + /* `TT_Err_Invalid_File_Format' has value 0x1103, the error */ + /* `T1_Err_Invalid_File_Format' has value 0x1203, etc. */ + /* */ + /* Undefine the macro FT_CONFIG_OPTION_USE_MODULE_ERRORS in ftoption.h */ + /* to make the higher byte always zero (disabling the module error */ + /* mechanism). */ + /* */ + /* It can also be used to create a module error message table easily */ + /* with something like */ + /* */ + /* { */ + /* #undef __FTMODERR_H__ */ + /* #define FT_MODERRDEF( e, v, s ) { FT_Mod_Err_ ## e, s }, */ + /* #define FT_MODERR_START_LIST { */ + /* #define FT_MODERR_END_LIST { 0, 0 } }; */ + /* */ + /* const struct */ + /* { */ + /* int mod_err_offset; */ + /* const char* mod_err_msg */ + /* } ft_mod_errors[] = */ + /* */ + /* #include FT_MODULE_ERRORS_H */ + /* } */ + /* */ + /* To use such a table, all errors must be ANDed with 0xFF00 to remove */ + /* the error code. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTMODERR_H__ +#define __FTMODERR_H__ + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** SETUP MACROS *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + + +#undef FT_NEED_EXTERN_C + +#ifndef FT_MODERRDEF + +#ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS +#define FT_MODERRDEF( e, v, s ) FT_Mod_Err_ ## e = v, +#else +#define FT_MODERRDEF( e, v, s ) FT_Mod_Err_ ## e = 0, +#endif + +#define FT_MODERR_START_LIST enum { +#define FT_MODERR_END_LIST FT_Mod_Err_Max }; + +#ifdef __cplusplus +#define FT_NEED_EXTERN_C + extern "C" { +#endif + +#endif /* !FT_MODERRDEF */ + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** LIST MODULE ERROR BASES *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + + +#ifdef FT_MODERR_START_LIST + FT_MODERR_START_LIST +#endif + + + FT_MODERRDEF( Base, 0x000, "base module" ) + FT_MODERRDEF( Autofit, 0x100, "autofitter module" ) + FT_MODERRDEF( BDF, 0x200, "BDF module" ) + FT_MODERRDEF( Bzip2, 0x300, "Bzip2 module" ) + FT_MODERRDEF( Cache, 0x400, "cache module" ) + FT_MODERRDEF( CFF, 0x500, "CFF module" ) + FT_MODERRDEF( CID, 0x600, "CID module" ) + FT_MODERRDEF( Gzip, 0x700, "Gzip module" ) + FT_MODERRDEF( LZW, 0x800, "LZW module" ) + FT_MODERRDEF( OTvalid, 0x900, "OpenType validation module" ) + FT_MODERRDEF( PCF, 0xA00, "PCF module" ) + FT_MODERRDEF( PFR, 0xB00, "PFR module" ) + FT_MODERRDEF( PSaux, 0xC00, "PS auxiliary module" ) + FT_MODERRDEF( PShinter, 0xD00, "PS hinter module" ) + FT_MODERRDEF( PSnames, 0xE00, "PS names module" ) + FT_MODERRDEF( Raster, 0xF00, "raster module" ) + FT_MODERRDEF( SFNT, 0x1000, "SFNT module" ) + FT_MODERRDEF( Smooth, 0x1100, "smooth raster module" ) + FT_MODERRDEF( TrueType, 0x1200, "TrueType module" ) + FT_MODERRDEF( Type1, 0x1300, "Type 1 module" ) + FT_MODERRDEF( Type42, 0x1400, "Type 42 module" ) + FT_MODERRDEF( Winfonts, 0x1500, "Windows FON/FNT module" ) + + +#ifdef FT_MODERR_END_LIST + FT_MODERR_END_LIST +#endif + + + /*******************************************************************/ + /*******************************************************************/ + /***** *****/ + /***** CLEANUP *****/ + /***** *****/ + /*******************************************************************/ + /*******************************************************************/ + + +#ifdef FT_NEED_EXTERN_C + } +#endif + +#undef FT_MODERR_START_LIST +#undef FT_MODERR_END_LIST +#undef FT_MODERRDEF +#undef FT_NEED_EXTERN_C + + +#endif /* __FTMODERR_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftotval.h b/other/freetype/include/freetype/ftotval.h new file mode 100644 index 0000000..027f2e8 --- /dev/null +++ b/other/freetype/include/freetype/ftotval.h @@ -0,0 +1,203 @@ +/***************************************************************************/ +/* */ +/* ftotval.h */ +/* */ +/* FreeType API for validating OpenType tables (specification). */ +/* */ +/* Copyright 2004, 2005, 2006, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +/***************************************************************************/ +/* */ +/* */ +/* Warning: This module might be moved to a different library in the */ +/* future to avoid a tight dependency between FreeType and the */ +/* OpenType specification. */ +/* */ +/* */ +/***************************************************************************/ + + +#ifndef __FTOTVAL_H__ +#define __FTOTVAL_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* ot_validation */ + /* */ + /* <Title> */ + /* OpenType Validation */ + /* */ + /* <Abstract> */ + /* An API to validate OpenType tables. */ + /* */ + /* <Description> */ + /* This section contains the declaration of functions to validate */ + /* some OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH). */ + /* */ + /*************************************************************************/ + + + /********************************************************************** + * + * @enum: + * FT_VALIDATE_OTXXX + * + * @description: + * A list of bit-field constants used with @FT_OpenType_Validate to + * indicate which OpenType tables should be validated. + * + * @values: + * FT_VALIDATE_BASE :: + * Validate BASE table. + * + * FT_VALIDATE_GDEF :: + * Validate GDEF table. + * + * FT_VALIDATE_GPOS :: + * Validate GPOS table. + * + * FT_VALIDATE_GSUB :: + * Validate GSUB table. + * + * FT_VALIDATE_JSTF :: + * Validate JSTF table. + * + * FT_VALIDATE_MATH :: + * Validate MATH table. + * + * FT_VALIDATE_OT :: + * Validate all OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH). + * + */ +#define FT_VALIDATE_BASE 0x0100 +#define FT_VALIDATE_GDEF 0x0200 +#define FT_VALIDATE_GPOS 0x0400 +#define FT_VALIDATE_GSUB 0x0800 +#define FT_VALIDATE_JSTF 0x1000 +#define FT_VALIDATE_MATH 0x2000 + +#define FT_VALIDATE_OT FT_VALIDATE_BASE | \ + FT_VALIDATE_GDEF | \ + FT_VALIDATE_GPOS | \ + FT_VALIDATE_GSUB | \ + FT_VALIDATE_JSTF | \ + FT_VALIDATE_MATH + + /* */ + + /********************************************************************** + * + * @function: + * FT_OpenType_Validate + * + * @description: + * Validate various OpenType tables to assure that all offsets and + * indices are valid. The idea is that a higher-level library which + * actually does the text layout can access those tables without + * error checking (which can be quite time consuming). + * + * @input: + * face :: + * A handle to the input face. + * + * validation_flags :: + * A bit field which specifies the tables to be validated. See + * @FT_VALIDATE_OTXXX for possible values. + * + * @output: + * BASE_table :: + * A pointer to the BASE table. + * + * GDEF_table :: + * A pointer to the GDEF table. + * + * GPOS_table :: + * A pointer to the GPOS table. + * + * GSUB_table :: + * A pointer to the GSUB table. + * + * JSTF_table :: + * A pointer to the JSTF table. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with OpenType fonts, returning an error + * otherwise. + * + * After use, the application should deallocate the five tables with + * @FT_OpenType_Free. A NULL value indicates that the table either + * doesn't exist in the font, or the application hasn't asked for + * validation. + */ + FT_EXPORT( FT_Error ) + FT_OpenType_Validate( FT_Face face, + FT_UInt validation_flags, + FT_Bytes *BASE_table, + FT_Bytes *GDEF_table, + FT_Bytes *GPOS_table, + FT_Bytes *GSUB_table, + FT_Bytes *JSTF_table ); + + /* */ + + /********************************************************************** + * + * @function: + * FT_OpenType_Free + * + * @description: + * Free the buffer allocated by OpenType validator. + * + * @input: + * face :: + * A handle to the input face. + * + * table :: + * The pointer to the buffer that is allocated by + * @FT_OpenType_Validate. + * + * @note: + * This function must be used to free the buffer allocated by + * @FT_OpenType_Validate only. + */ + FT_EXPORT( void ) + FT_OpenType_Free( FT_Face face, + FT_Bytes table ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTOTVAL_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftoutln.h b/other/freetype/include/freetype/ftoutln.h new file mode 100644 index 0000000..1cf3c3f --- /dev/null +++ b/other/freetype/include/freetype/ftoutln.h @@ -0,0 +1,540 @@ +/***************************************************************************/ +/* */ +/* ftoutln.h */ +/* */ +/* Support for the FT_Outline type used to store glyph shapes of */ +/* most scalable font formats (specification). */ +/* */ +/* Copyright 1996-2003, 2005-2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTOUTLN_H__ +#define __FTOUTLN_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* outline_processing */ + /* */ + /* <Title> */ + /* Outline Processing */ + /* */ + /* <Abstract> */ + /* Functions to create, transform, and render vectorial glyph images. */ + /* */ + /* <Description> */ + /* This section contains routines used to create and destroy scalable */ + /* glyph images known as `outlines'. These can also be measured, */ + /* transformed, and converted into bitmaps and pixmaps. */ + /* */ + /* <Order> */ + /* FT_Outline */ + /* FT_OUTLINE_FLAGS */ + /* FT_Outline_New */ + /* FT_Outline_Done */ + /* FT_Outline_Copy */ + /* FT_Outline_Translate */ + /* FT_Outline_Transform */ + /* FT_Outline_Embolden */ + /* FT_Outline_Reverse */ + /* FT_Outline_Check */ + /* */ + /* FT_Outline_Get_CBox */ + /* FT_Outline_Get_BBox */ + /* */ + /* FT_Outline_Get_Bitmap */ + /* FT_Outline_Render */ + /* */ + /* FT_Outline_Decompose */ + /* FT_Outline_Funcs */ + /* FT_Outline_MoveTo_Func */ + /* FT_Outline_LineTo_Func */ + /* FT_Outline_ConicTo_Func */ + /* FT_Outline_CubicTo_Func */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Decompose */ + /* */ + /* <Description> */ + /* Walk over an outline's structure to decompose it into individual */ + /* segments and Bézier arcs. This function also emits `move to' */ + /* operations to indicate the start of new contours in the outline. */ + /* */ + /* <Input> */ + /* outline :: A pointer to the source target. */ + /* */ + /* func_interface :: A table of `emitters', i.e., function pointers */ + /* called during decomposition to indicate path */ + /* operations. */ + /* */ + /* <InOut> */ + /* user :: A typeless pointer which is passed to each */ + /* emitter during the decomposition. It can be */ + /* used to store the state during the */ + /* decomposition. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Decompose( FT_Outline* outline, + const FT_Outline_Funcs* func_interface, + void* user ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_New */ + /* */ + /* <Description> */ + /* Create a new outline of a given size. */ + /* */ + /* <Input> */ + /* library :: A handle to the library object from where the */ + /* outline is allocated. Note however that the new */ + /* outline will *not* necessarily be *freed*, when */ + /* destroying the library, by @FT_Done_FreeType. */ + /* */ + /* numPoints :: The maximal number of points within the outline. */ + /* */ + /* numContours :: The maximal number of contours within the outline. */ + /* */ + /* <Output> */ + /* anoutline :: A handle to the new outline. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The reason why this function takes a `library' parameter is simply */ + /* to use the library's memory allocator. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_New( FT_Library library, + FT_UInt numPoints, + FT_Int numContours, + FT_Outline *anoutline ); + + + FT_EXPORT( FT_Error ) + FT_Outline_New_Internal( FT_Memory memory, + FT_UInt numPoints, + FT_Int numContours, + FT_Outline *anoutline ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Done */ + /* */ + /* <Description> */ + /* Destroy an outline created with @FT_Outline_New. */ + /* */ + /* <Input> */ + /* library :: A handle of the library object used to allocate the */ + /* outline. */ + /* */ + /* outline :: A pointer to the outline object to be discarded. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* If the outline's `owner' field is not set, only the outline */ + /* descriptor will be released. */ + /* */ + /* The reason why this function takes an `library' parameter is */ + /* simply to use ft_mem_free(). */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Done( FT_Library library, + FT_Outline* outline ); + + + FT_EXPORT( FT_Error ) + FT_Outline_Done_Internal( FT_Memory memory, + FT_Outline* outline ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Check */ + /* */ + /* <Description> */ + /* Check the contents of an outline descriptor. */ + /* */ + /* <Input> */ + /* outline :: A handle to a source outline. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Check( FT_Outline* outline ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Get_CBox */ + /* */ + /* <Description> */ + /* Return an outline's `control box'. The control box encloses all */ + /* the outline's points, including Bézier control points. Though it */ + /* coincides with the exact bounding box for most glyphs, it can be */ + /* slightly larger in some situations (like when rotating an outline */ + /* which contains Bézier outside arcs). */ + /* */ + /* Computing the control box is very fast, while getting the bounding */ + /* box can take much more time as it needs to walk over all segments */ + /* and arcs in the outline. To get the latter, you can use the */ + /* `ftbbox' component which is dedicated to this single task. */ + /* */ + /* <Input> */ + /* outline :: A pointer to the source outline descriptor. */ + /* */ + /* <Output> */ + /* acbox :: The outline's control box. */ + /* */ + /* <Note> */ + /* See @FT_Glyph_Get_CBox for a discussion of tricky fonts. */ + /* */ + FT_EXPORT( void ) + FT_Outline_Get_CBox( const FT_Outline* outline, + FT_BBox *acbox ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Translate */ + /* */ + /* <Description> */ + /* Apply a simple translation to the points of an outline. */ + /* */ + /* <InOut> */ + /* outline :: A pointer to the target outline descriptor. */ + /* */ + /* <Input> */ + /* xOffset :: The horizontal offset. */ + /* */ + /* yOffset :: The vertical offset. */ + /* */ + FT_EXPORT( void ) + FT_Outline_Translate( const FT_Outline* outline, + FT_Pos xOffset, + FT_Pos yOffset ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Copy */ + /* */ + /* <Description> */ + /* Copy an outline into another one. Both objects must have the */ + /* same sizes (number of points & number of contours) when this */ + /* function is called. */ + /* */ + /* <Input> */ + /* source :: A handle to the source outline. */ + /* */ + /* <Output> */ + /* target :: A handle to the target outline. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Copy( const FT_Outline* source, + FT_Outline *target ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Transform */ + /* */ + /* <Description> */ + /* Apply a simple 2x2 matrix to all of an outline's points. Useful */ + /* for applying rotations, slanting, flipping, etc. */ + /* */ + /* <InOut> */ + /* outline :: A pointer to the target outline descriptor. */ + /* */ + /* <Input> */ + /* matrix :: A pointer to the transformation matrix. */ + /* */ + /* <Note> */ + /* You can use @FT_Outline_Translate if you need to translate the */ + /* outline's points. */ + /* */ + FT_EXPORT( void ) + FT_Outline_Transform( const FT_Outline* outline, + const FT_Matrix* matrix ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Embolden */ + /* */ + /* <Description> */ + /* Embolden an outline. The new outline will be at most 4~times */ + /* `strength' pixels wider and higher. You may think of the left and */ + /* bottom borders as unchanged. */ + /* */ + /* Negative `strength' values to reduce the outline thickness are */ + /* possible also. */ + /* */ + /* <InOut> */ + /* outline :: A handle to the target outline. */ + /* */ + /* <Input> */ + /* strength :: How strong the glyph is emboldened. Expressed in */ + /* 26.6 pixel format. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The used algorithm to increase or decrease the thickness of the */ + /* glyph doesn't change the number of points; this means that certain */ + /* situations like acute angles or intersections are sometimes */ + /* handled incorrectly. */ + /* */ + /* If you need `better' metrics values you should call */ + /* @FT_Outline_Get_CBox or @FT_Outline_Get_BBox. */ + /* */ + /* Example call: */ + /* */ + /* { */ + /* FT_Load_Glyph( face, index, FT_LOAD_DEFAULT ); */ + /* if ( face->slot->format == FT_GLYPH_FORMAT_OUTLINE ) */ + /* FT_Outline_Embolden( &face->slot->outline, strength ); */ + /* } */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Embolden( FT_Outline* outline, + FT_Pos strength ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Reverse */ + /* */ + /* <Description> */ + /* Reverse the drawing direction of an outline. This is used to */ + /* ensure consistent fill conventions for mirrored glyphs. */ + /* */ + /* <InOut> */ + /* outline :: A pointer to the target outline descriptor. */ + /* */ + /* <Note> */ + /* This function toggles the bit flag @FT_OUTLINE_REVERSE_FILL in */ + /* the outline's `flags' field. */ + /* */ + /* It shouldn't be used by a normal client application, unless it */ + /* knows what it is doing. */ + /* */ + FT_EXPORT( void ) + FT_Outline_Reverse( FT_Outline* outline ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Get_Bitmap */ + /* */ + /* <Description> */ + /* Render an outline within a bitmap. The outline's image is simply */ + /* OR-ed to the target bitmap. */ + /* */ + /* <Input> */ + /* library :: A handle to a FreeType library object. */ + /* */ + /* outline :: A pointer to the source outline descriptor. */ + /* */ + /* <InOut> */ + /* abitmap :: A pointer to the target bitmap descriptor. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* This function does NOT CREATE the bitmap, it only renders an */ + /* outline image within the one you pass to it! Consequently, the */ + /* various fields in `abitmap' should be set accordingly. */ + /* */ + /* It will use the raster corresponding to the default glyph format. */ + /* */ + /* The value of the `num_grays' field in `abitmap' is ignored. If */ + /* you select the gray-level rasterizer, and you want less than 256 */ + /* gray levels, you have to use @FT_Outline_Render directly. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Get_Bitmap( FT_Library library, + FT_Outline* outline, + const FT_Bitmap *abitmap ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Outline_Render */ + /* */ + /* <Description> */ + /* Render an outline within a bitmap using the current scan-convert. */ + /* This function uses an @FT_Raster_Params structure as an argument, */ + /* allowing advanced features like direct composition, translucency, */ + /* etc. */ + /* */ + /* <Input> */ + /* library :: A handle to a FreeType library object. */ + /* */ + /* outline :: A pointer to the source outline descriptor. */ + /* */ + /* <InOut> */ + /* params :: A pointer to an @FT_Raster_Params structure used to */ + /* describe the rendering operation. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* You should know what you are doing and how @FT_Raster_Params works */ + /* to use this function. */ + /* */ + /* The field `params.source' will be set to `outline' before the scan */ + /* converter is called, which means that the value you give to it is */ + /* actually ignored. */ + /* */ + /* The gray-level rasterizer always uses 256 gray levels. If you */ + /* want less gray levels, you have to provide your own span callback. */ + /* See the @FT_RASTER_FLAG_DIRECT value of the `flags' field in the */ + /* @FT_Raster_Params structure for more details. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Outline_Render( FT_Library library, + FT_Outline* outline, + FT_Raster_Params* params ); + + + /************************************************************************** + * + * @enum: + * FT_Orientation + * + * @description: + * A list of values used to describe an outline's contour orientation. + * + * The TrueType and PostScript specifications use different conventions + * to determine whether outline contours should be filled or unfilled. + * + * @values: + * FT_ORIENTATION_TRUETYPE :: + * According to the TrueType specification, clockwise contours must + * be filled, and counter-clockwise ones must be unfilled. + * + * FT_ORIENTATION_POSTSCRIPT :: + * According to the PostScript specification, counter-clockwise contours + * must be filled, and clockwise ones must be unfilled. + * + * FT_ORIENTATION_FILL_RIGHT :: + * This is identical to @FT_ORIENTATION_TRUETYPE, but is used to + * remember that in TrueType, everything that is to the right of + * the drawing direction of a contour must be filled. + * + * FT_ORIENTATION_FILL_LEFT :: + * This is identical to @FT_ORIENTATION_POSTSCRIPT, but is used to + * remember that in PostScript, everything that is to the left of + * the drawing direction of a contour must be filled. + * + * FT_ORIENTATION_NONE :: + * The orientation cannot be determined. That is, different parts of + * the glyph have different orientation. + * + */ + typedef enum FT_Orientation_ + { + FT_ORIENTATION_TRUETYPE = 0, + FT_ORIENTATION_POSTSCRIPT = 1, + FT_ORIENTATION_FILL_RIGHT = FT_ORIENTATION_TRUETYPE, + FT_ORIENTATION_FILL_LEFT = FT_ORIENTATION_POSTSCRIPT, + FT_ORIENTATION_NONE + + } FT_Orientation; + + + /************************************************************************** + * + * @function: + * FT_Outline_Get_Orientation + * + * @description: + * This function analyzes a glyph outline and tries to compute its + * fill orientation (see @FT_Orientation). This is done by computing + * the direction of each global horizontal and/or vertical extrema + * within the outline. + * + * Note that this will return @FT_ORIENTATION_TRUETYPE for empty + * outlines. + * + * @input: + * outline :: + * A handle to the source outline. + * + * @return: + * The orientation. + * + */ + FT_EXPORT( FT_Orientation ) + FT_Outline_Get_Orientation( FT_Outline* outline ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTOUTLN_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftpfr.h b/other/freetype/include/freetype/ftpfr.h new file mode 100644 index 0000000..0b7b7d4 --- /dev/null +++ b/other/freetype/include/freetype/ftpfr.h @@ -0,0 +1,172 @@ +/***************************************************************************/ +/* */ +/* ftpfr.h */ +/* */ +/* FreeType API for accessing PFR-specific data (specification only). */ +/* */ +/* Copyright 2002, 2003, 2004, 2006, 2008, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTPFR_H__ +#define __FTPFR_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* pfr_fonts */ + /* */ + /* <Title> */ + /* PFR Fonts */ + /* */ + /* <Abstract> */ + /* PFR/TrueDoc specific API. */ + /* */ + /* <Description> */ + /* This section contains the declaration of PFR-specific functions. */ + /* */ + /*************************************************************************/ + + + /********************************************************************** + * + * @function: + * FT_Get_PFR_Metrics + * + * @description: + * Return the outline and metrics resolutions of a given PFR face. + * + * @input: + * face :: Handle to the input face. It can be a non-PFR face. + * + * @output: + * aoutline_resolution :: + * Outline resolution. This is equivalent to `face->units_per_EM' + * for non-PFR fonts. Optional (parameter can be NULL). + * + * ametrics_resolution :: + * Metrics resolution. This is equivalent to `outline_resolution' + * for non-PFR fonts. Optional (parameter can be NULL). + * + * ametrics_x_scale :: + * A 16.16 fixed-point number used to scale distance expressed + * in metrics units to device sub-pixels. This is equivalent to + * `face->size->x_scale', but for metrics only. Optional (parameter + * can be NULL). + * + * ametrics_y_scale :: + * Same as `ametrics_x_scale' but for the vertical direction. + * optional (parameter can be NULL). + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * If the input face is not a PFR, this function will return an error. + * However, in all cases, it will return valid values. + */ + FT_EXPORT( FT_Error ) + FT_Get_PFR_Metrics( FT_Face face, + FT_UInt *aoutline_resolution, + FT_UInt *ametrics_resolution, + FT_Fixed *ametrics_x_scale, + FT_Fixed *ametrics_y_scale ); + + + /********************************************************************** + * + * @function: + * FT_Get_PFR_Kerning + * + * @description: + * Return the kerning pair corresponding to two glyphs in a PFR face. + * The distance is expressed in metrics units, unlike the result of + * @FT_Get_Kerning. + * + * @input: + * face :: A handle to the input face. + * + * left :: Index of the left glyph. + * + * right :: Index of the right glyph. + * + * @output: + * avector :: A kerning vector. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function always return distances in original PFR metrics + * units. This is unlike @FT_Get_Kerning with the @FT_KERNING_UNSCALED + * mode, which always returns distances converted to outline units. + * + * You can use the value of the `x_scale' and `y_scale' parameters + * returned by @FT_Get_PFR_Metrics to scale these to device sub-pixels. + */ + FT_EXPORT( FT_Error ) + FT_Get_PFR_Kerning( FT_Face face, + FT_UInt left, + FT_UInt right, + FT_Vector *avector ); + + + /********************************************************************** + * + * @function: + * FT_Get_PFR_Advance + * + * @description: + * Return a given glyph advance, expressed in original metrics units, + * from a PFR font. + * + * @input: + * face :: A handle to the input face. + * + * gindex :: The glyph index. + * + * @output: + * aadvance :: The glyph advance in metrics units. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * You can use the `x_scale' or `y_scale' results of @FT_Get_PFR_Metrics + * to convert the advance to device sub-pixels (i.e., 1/64th of pixels). + */ + FT_EXPORT( FT_Error ) + FT_Get_PFR_Advance( FT_Face face, + FT_UInt gindex, + FT_Pos *aadvance ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTPFR_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftrender.h b/other/freetype/include/freetype/ftrender.h new file mode 100644 index 0000000..dd0229b --- /dev/null +++ b/other/freetype/include/freetype/ftrender.h @@ -0,0 +1,238 @@ +/***************************************************************************/ +/* */ +/* ftrender.h */ +/* */ +/* FreeType renderer modules public interface (specification). */ +/* */ +/* Copyright 1996-2001, 2005, 2006, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTRENDER_H__ +#define __FTRENDER_H__ + + +#include <ft2build.h> +#include FT_MODULE_H +#include FT_GLYPH_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* module_management */ + /* */ + /*************************************************************************/ + + + /* create a new glyph object */ + typedef FT_Error + (*FT_Glyph_InitFunc)( FT_Glyph glyph, + FT_GlyphSlot slot ); + + /* destroys a given glyph object */ + typedef void + (*FT_Glyph_DoneFunc)( FT_Glyph glyph ); + + typedef void + (*FT_Glyph_TransformFunc)( FT_Glyph glyph, + const FT_Matrix* matrix, + const FT_Vector* delta ); + + typedef void + (*FT_Glyph_GetBBoxFunc)( FT_Glyph glyph, + FT_BBox* abbox ); + + typedef FT_Error + (*FT_Glyph_CopyFunc)( FT_Glyph source, + FT_Glyph target ); + + typedef FT_Error + (*FT_Glyph_PrepareFunc)( FT_Glyph glyph, + FT_GlyphSlot slot ); + +/* deprecated */ +#define FT_Glyph_Init_Func FT_Glyph_InitFunc +#define FT_Glyph_Done_Func FT_Glyph_DoneFunc +#define FT_Glyph_Transform_Func FT_Glyph_TransformFunc +#define FT_Glyph_BBox_Func FT_Glyph_GetBBoxFunc +#define FT_Glyph_Copy_Func FT_Glyph_CopyFunc +#define FT_Glyph_Prepare_Func FT_Glyph_PrepareFunc + + + struct FT_Glyph_Class_ + { + FT_Long glyph_size; + FT_Glyph_Format glyph_format; + FT_Glyph_InitFunc glyph_init; + FT_Glyph_DoneFunc glyph_done; + FT_Glyph_CopyFunc glyph_copy; + FT_Glyph_TransformFunc glyph_transform; + FT_Glyph_GetBBoxFunc glyph_bbox; + FT_Glyph_PrepareFunc glyph_prepare; + }; + + + typedef FT_Error + (*FT_Renderer_RenderFunc)( FT_Renderer renderer, + FT_GlyphSlot slot, + FT_UInt mode, + const FT_Vector* origin ); + + typedef FT_Error + (*FT_Renderer_TransformFunc)( FT_Renderer renderer, + FT_GlyphSlot slot, + const FT_Matrix* matrix, + const FT_Vector* delta ); + + + typedef void + (*FT_Renderer_GetCBoxFunc)( FT_Renderer renderer, + FT_GlyphSlot slot, + FT_BBox* cbox ); + + + typedef FT_Error + (*FT_Renderer_SetModeFunc)( FT_Renderer renderer, + FT_ULong mode_tag, + FT_Pointer mode_ptr ); + +/* deprecated identifiers */ +#define FTRenderer_render FT_Renderer_RenderFunc +#define FTRenderer_transform FT_Renderer_TransformFunc +#define FTRenderer_getCBox FT_Renderer_GetCBoxFunc +#define FTRenderer_setMode FT_Renderer_SetModeFunc + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Renderer_Class */ + /* */ + /* <Description> */ + /* The renderer module class descriptor. */ + /* */ + /* <Fields> */ + /* root :: The root @FT_Module_Class fields. */ + /* */ + /* glyph_format :: The glyph image format this renderer handles. */ + /* */ + /* render_glyph :: A method used to render the image that is in a */ + /* given glyph slot into a bitmap. */ + /* */ + /* transform_glyph :: A method used to transform the image that is in */ + /* a given glyph slot. */ + /* */ + /* get_glyph_cbox :: A method used to access the glyph's cbox. */ + /* */ + /* set_mode :: A method used to pass additional parameters. */ + /* */ + /* raster_class :: For @FT_GLYPH_FORMAT_OUTLINE renderers only. */ + /* This is a pointer to its raster's class. */ + /* */ + typedef struct FT_Renderer_Class_ + { + FT_Module_Class root; + + FT_Glyph_Format glyph_format; + + FT_Renderer_RenderFunc render_glyph; + FT_Renderer_TransformFunc transform_glyph; + FT_Renderer_GetCBoxFunc get_glyph_cbox; + FT_Renderer_SetModeFunc set_mode; + + FT_Raster_Funcs* raster_class; + + } FT_Renderer_Class; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Renderer */ + /* */ + /* <Description> */ + /* Retrieve the current renderer for a given glyph format. */ + /* */ + /* <Input> */ + /* library :: A handle to the library object. */ + /* */ + /* format :: The glyph format. */ + /* */ + /* <Return> */ + /* A renderer handle. 0~if none found. */ + /* */ + /* <Note> */ + /* An error will be returned if a module already exists by that name, */ + /* or if the module requires a version of FreeType that is too great. */ + /* */ + /* To add a new renderer, simply use @FT_Add_Module. To retrieve a */ + /* renderer by its name, use @FT_Get_Module. */ + /* */ + FT_EXPORT( FT_Renderer ) + FT_Get_Renderer( FT_Library library, + FT_Glyph_Format format ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Set_Renderer */ + /* */ + /* <Description> */ + /* Set the current renderer to use, and set additional mode. */ + /* */ + /* <InOut> */ + /* library :: A handle to the library object. */ + /* */ + /* <Input> */ + /* renderer :: A handle to the renderer object. */ + /* */ + /* num_params :: The number of additional parameters. */ + /* */ + /* parameters :: Additional parameters. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* In case of success, the renderer will be used to convert glyph */ + /* images in the renderer's known format into bitmaps. */ + /* */ + /* This doesn't change the current renderer for other formats. */ + /* */ + /* Currently, only the B/W renderer, if compiled with */ + /* FT_RASTER_OPTION_ANTI_ALIASING (providing a 5-levels */ + /* anti-aliasing mode; this option must be set directly in */ + /* `ftraster.c' and is undefined by default) accepts a single tag */ + /* `pal5' to set its gray palette as a character string with */ + /* 5~elements. Consequently, the third and fourth argument are zero */ + /* normally. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Set_Renderer( FT_Library library, + FT_Renderer renderer, + FT_UInt num_params, + FT_Parameter* parameters ); + + + /* */ + + +FT_END_HEADER + +#endif /* __FTRENDER_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftsizes.h b/other/freetype/include/freetype/ftsizes.h new file mode 100644 index 0000000..3e548cc --- /dev/null +++ b/other/freetype/include/freetype/ftsizes.h @@ -0,0 +1,159 @@ +/***************************************************************************/ +/* */ +/* ftsizes.h */ +/* */ +/* FreeType size objects management (specification). */ +/* */ +/* Copyright 1996-2001, 2003, 2004, 2006, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* Typical application would normally not need to use these functions. */ + /* However, they have been placed in a public API for the rare cases */ + /* where they are needed. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTSIZES_H__ +#define __FTSIZES_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* sizes_management */ + /* */ + /* <Title> */ + /* Size Management */ + /* */ + /* <Abstract> */ + /* Managing multiple sizes per face. */ + /* */ + /* <Description> */ + /* When creating a new face object (e.g., with @FT_New_Face), an */ + /* @FT_Size object is automatically created and used to store all */ + /* pixel-size dependent information, available in the `face->size' */ + /* field. */ + /* */ + /* It is however possible to create more sizes for a given face, */ + /* mostly in order to manage several character pixel sizes of the */ + /* same font family and style. See @FT_New_Size and @FT_Done_Size. */ + /* */ + /* Note that @FT_Set_Pixel_Sizes and @FT_Set_Char_Size only */ + /* modify the contents of the current `active' size; you thus need */ + /* to use @FT_Activate_Size to change it. */ + /* */ + /* 99% of applications won't need the functions provided here, */ + /* especially if they use the caching sub-system, so be cautious */ + /* when using these. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Size */ + /* */ + /* <Description> */ + /* Create a new size object from a given face object. */ + /* */ + /* <Input> */ + /* face :: A handle to a parent face object. */ + /* */ + /* <Output> */ + /* asize :: A handle to a new size object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* You need to call @FT_Activate_Size in order to select the new size */ + /* for upcoming calls to @FT_Set_Pixel_Sizes, @FT_Set_Char_Size, */ + /* @FT_Load_Glyph, @FT_Load_Char, etc. */ + /* */ + FT_EXPORT( FT_Error ) + FT_New_Size( FT_Face face, + FT_Size* size ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_Size */ + /* */ + /* <Description> */ + /* Discard a given size object. Note that @FT_Done_Face */ + /* automatically discards all size objects allocated with */ + /* @FT_New_Size. */ + /* */ + /* <Input> */ + /* size :: A handle to a target size object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Done_Size( FT_Size size ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Activate_Size */ + /* */ + /* <Description> */ + /* Even though it is possible to create several size objects for a */ + /* given face (see @FT_New_Size for details), functions like */ + /* @FT_Load_Glyph or @FT_Load_Char only use the one which has been */ + /* activated last to determine the `current character pixel size'. */ + /* */ + /* This function can be used to `activate' a previously created size */ + /* object. */ + /* */ + /* <Input> */ + /* size :: A handle to a target size object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* If `face' is the size's parent face object, this function changes */ + /* the value of `face->size' to the input size handle. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Activate_Size( FT_Size size ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTSIZES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftsnames.h b/other/freetype/include/freetype/ftsnames.h new file mode 100644 index 0000000..485e4e1 --- /dev/null +++ b/other/freetype/include/freetype/ftsnames.h @@ -0,0 +1,200 @@ +/***************************************************************************/ +/* */ +/* ftsnames.h */ +/* */ +/* Simple interface to access SFNT name tables (which are used */ +/* to hold font names, copyright info, notices, etc.) (specification). */ +/* */ +/* This is _not_ used to retrieve glyph names! */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2006, 2009, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FT_SFNT_NAMES_H__ +#define __FT_SFNT_NAMES_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* sfnt_names */ + /* */ + /* <Title> */ + /* SFNT Names */ + /* */ + /* <Abstract> */ + /* Access the names embedded in TrueType and OpenType files. */ + /* */ + /* <Description> */ + /* The TrueType and OpenType specifications allow the inclusion of */ + /* a special `names table' in font files. This table contains */ + /* textual (and internationalized) information regarding the font, */ + /* like family name, copyright, version, etc. */ + /* */ + /* The definitions below are used to access them if available. */ + /* */ + /* Note that this has nothing to do with glyph names! */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_SfntName */ + /* */ + /* <Description> */ + /* A structure used to model an SFNT `name' table entry. */ + /* */ + /* <Fields> */ + /* platform_id :: The platform ID for `string'. */ + /* */ + /* encoding_id :: The encoding ID for `string'. */ + /* */ + /* language_id :: The language ID for `string'. */ + /* */ + /* name_id :: An identifier for `string'. */ + /* */ + /* string :: The `name' string. Note that its format differs */ + /* depending on the (platform,encoding) pair. It can */ + /* be a Pascal String, a UTF-16 one, etc. */ + /* */ + /* Generally speaking, the string is not */ + /* zero-terminated. Please refer to the TrueType */ + /* specification for details. */ + /* */ + /* string_len :: The length of `string' in bytes. */ + /* */ + /* <Note> */ + /* Possible values for `platform_id', `encoding_id', `language_id', */ + /* and `name_id' are given in the file `ttnameid.h'. For details */ + /* please refer to the TrueType or OpenType specification. */ + /* */ + /* See also @TT_PLATFORM_XXX, @TT_APPLE_ID_XXX, @TT_MAC_ID_XXX, */ + /* @TT_ISO_ID_XXX, and @TT_MS_ID_XXX. */ + /* */ + typedef struct FT_SfntName_ + { + FT_UShort platform_id; + FT_UShort encoding_id; + FT_UShort language_id; + FT_UShort name_id; + + FT_Byte* string; /* this string is *not* null-terminated! */ + FT_UInt string_len; /* in bytes */ + + } FT_SfntName; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Sfnt_Name_Count */ + /* */ + /* <Description> */ + /* Retrieve the number of name strings in the SFNT `name' table. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face. */ + /* */ + /* <Return> */ + /* The number of strings in the `name' table. */ + /* */ + FT_EXPORT( FT_UInt ) + FT_Get_Sfnt_Name_Count( FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Sfnt_Name */ + /* */ + /* <Description> */ + /* Retrieve a string of the SFNT `name' table for a given index. */ + /* */ + /* <Input> */ + /* face :: A handle to the source face. */ + /* */ + /* idx :: The index of the `name' string. */ + /* */ + /* <Output> */ + /* aname :: The indexed @FT_SfntName structure. */ + /* */ + /* <Return> */ + /* FreeType error code. 0~means success. */ + /* */ + /* <Note> */ + /* The `string' array returned in the `aname' structure is not */ + /* null-terminated. The application should deallocate it if it is no */ + /* longer in use. */ + /* */ + /* Use @FT_Get_Sfnt_Name_Count to get the total number of available */ + /* `name' table entries, then do a loop until you get the right */ + /* platform, encoding, and name ID. */ + /* */ + FT_EXPORT( FT_Error ) + FT_Get_Sfnt_Name( FT_Face face, + FT_UInt idx, + FT_SfntName *aname ); + + + /*************************************************************************** + * + * @constant: + * FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY + * + * @description: + * A constant used as the tag of @FT_Parameter structures to make + * FT_Open_Face() ignore preferred family subfamily names in `name' + * table since OpenType version 1.4. For backwards compatibility with + * legacy systems which has 4-face-per-family restriction. + * + */ +#define FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY FT_MAKE_TAG( 'i', 'g', 'p', 'f' ) + + + /*************************************************************************** + * + * @constant: + * FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY + * + * @description: + * A constant used as the tag of @FT_Parameter structures to make + * FT_Open_Face() ignore preferred subfamily names in `name' table since + * OpenType version 1.4. For backwards compatibility with legacy + * systems which has 4-face-per-family restriction. + * + */ +#define FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY FT_MAKE_TAG( 'i', 'g', 'p', 's' ) + + /* */ + + +FT_END_HEADER + +#endif /* __FT_SFNT_NAMES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftstroke.h b/other/freetype/include/freetype/ftstroke.h new file mode 100644 index 0000000..dbda6d2 --- /dev/null +++ b/other/freetype/include/freetype/ftstroke.h @@ -0,0 +1,741 @@ +/***************************************************************************/ +/* */ +/* ftstroke.h */ +/* */ +/* FreeType path stroker (specification). */ +/* */ +/* Copyright 2002-2006, 2008, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FT_STROKE_H__ +#define __FT_STROKE_H__ + +#include <ft2build.h> +#include FT_OUTLINE_H +#include FT_GLYPH_H + + +FT_BEGIN_HEADER + + + /************************************************************************ + * + * @section: + * glyph_stroker + * + * @title: + * Glyph Stroker + * + * @abstract: + * Generating bordered and stroked glyphs. + * + * @description: + * This component generates stroked outlines of a given vectorial + * glyph. It also allows you to retrieve the `outside' and/or the + * `inside' borders of the stroke. + * + * This can be useful to generate `bordered' glyph, i.e., glyphs + * displayed with a coloured (and anti-aliased) border around their + * shape. + */ + + + /************************************************************** + * + * @type: + * FT_Stroker + * + * @description: + * Opaque handler to a path stroker object. + */ + typedef struct FT_StrokerRec_* FT_Stroker; + + + /************************************************************** + * + * @enum: + * FT_Stroker_LineJoin + * + * @description: + * These values determine how two joining lines are rendered + * in a stroker. + * + * @values: + * FT_STROKER_LINEJOIN_ROUND :: + * Used to render rounded line joins. Circular arcs are used + * to join two lines smoothly. + * + * FT_STROKER_LINEJOIN_BEVEL :: + * Used to render beveled line joins. The outer corner of + * the joined lines is filled by enclosing the triangular + * region of the corner with a straight line between the + * outer corners of each stroke. + * + * FT_STROKER_LINEJOIN_MITER_FIXED :: + * Used to render mitered line joins, with fixed bevels if the + * miter limit is exceeded. The outer edges of the strokes + * for the two segments are extended until they meet at an + * angle. If the segments meet at too sharp an angle (such + * that the miter would extend from the intersection of the + * segments a distance greater than the product of the miter + * limit value and the border radius), then a bevel join (see + * above) is used instead. This prevents long spikes being + * created. FT_STROKER_LINEJOIN_MITER_FIXED generates a miter + * line join as used in PostScript and PDF. + * + * FT_STROKER_LINEJOIN_MITER_VARIABLE :: + * FT_STROKER_LINEJOIN_MITER :: + * Used to render mitered line joins, with variable bevels if + * the miter limit is exceeded. The intersection of the + * strokes is clipped at a line perpendicular to the bisector + * of the angle between the strokes, at the distance from the + * intersection of the segments equal to the product of the + * miter limit value and the border radius. This prevents + * long spikes being created. + * FT_STROKER_LINEJOIN_MITER_VARIABLE generates a mitered line + * join as used in XPS. FT_STROKER_LINEJOIN_MITER is an alias + * for FT_STROKER_LINEJOIN_MITER_VARIABLE, retained for + * backwards compatibility. + */ + typedef enum FT_Stroker_LineJoin_ + { + FT_STROKER_LINEJOIN_ROUND = 0, + FT_STROKER_LINEJOIN_BEVEL = 1, + FT_STROKER_LINEJOIN_MITER_VARIABLE = 2, + FT_STROKER_LINEJOIN_MITER = FT_STROKER_LINEJOIN_MITER_VARIABLE, + FT_STROKER_LINEJOIN_MITER_FIXED = 3 + + } FT_Stroker_LineJoin; + + + /************************************************************** + * + * @enum: + * FT_Stroker_LineCap + * + * @description: + * These values determine how the end of opened sub-paths are + * rendered in a stroke. + * + * @values: + * FT_STROKER_LINECAP_BUTT :: + * The end of lines is rendered as a full stop on the last + * point itself. + * + * FT_STROKER_LINECAP_ROUND :: + * The end of lines is rendered as a half-circle around the + * last point. + * + * FT_STROKER_LINECAP_SQUARE :: + * The end of lines is rendered as a square around the + * last point. + */ + typedef enum FT_Stroker_LineCap_ + { + FT_STROKER_LINECAP_BUTT = 0, + FT_STROKER_LINECAP_ROUND, + FT_STROKER_LINECAP_SQUARE + + } FT_Stroker_LineCap; + + + /************************************************************** + * + * @enum: + * FT_StrokerBorder + * + * @description: + * These values are used to select a given stroke border + * in @FT_Stroker_GetBorderCounts and @FT_Stroker_ExportBorder. + * + * @values: + * FT_STROKER_BORDER_LEFT :: + * Select the left border, relative to the drawing direction. + * + * FT_STROKER_BORDER_RIGHT :: + * Select the right border, relative to the drawing direction. + * + * @note: + * Applications are generally interested in the `inside' and `outside' + * borders. However, there is no direct mapping between these and the + * `left' and `right' ones, since this really depends on the glyph's + * drawing orientation, which varies between font formats. + * + * You can however use @FT_Outline_GetInsideBorder and + * @FT_Outline_GetOutsideBorder to get these. + */ + typedef enum FT_StrokerBorder_ + { + FT_STROKER_BORDER_LEFT = 0, + FT_STROKER_BORDER_RIGHT + + } FT_StrokerBorder; + + + /************************************************************** + * + * @function: + * FT_Outline_GetInsideBorder + * + * @description: + * Retrieve the @FT_StrokerBorder value corresponding to the + * `inside' borders of a given outline. + * + * @input: + * outline :: + * The source outline handle. + * + * @return: + * The border index. @FT_STROKER_BORDER_RIGHT for empty or invalid + * outlines. + */ + FT_EXPORT( FT_StrokerBorder ) + FT_Outline_GetInsideBorder( FT_Outline* outline ); + + + /************************************************************** + * + * @function: + * FT_Outline_GetOutsideBorder + * + * @description: + * Retrieve the @FT_StrokerBorder value corresponding to the + * `outside' borders of a given outline. + * + * @input: + * outline :: + * The source outline handle. + * + * @return: + * The border index. @FT_STROKER_BORDER_LEFT for empty or invalid + * outlines. + */ + FT_EXPORT( FT_StrokerBorder ) + FT_Outline_GetOutsideBorder( FT_Outline* outline ); + + + /************************************************************** + * + * @function: + * FT_Stroker_New + * + * @description: + * Create a new stroker object. + * + * @input: + * library :: + * FreeType library handle. + * + * @output: + * astroker :: + * A new stroker object handle. NULL in case of error. + * + * @return: + * FreeType error code. 0~means success. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_New( FT_Library library, + FT_Stroker *astroker ); + + + /************************************************************** + * + * @function: + * FT_Stroker_Set + * + * @description: + * Reset a stroker object's attributes. + * + * @input: + * stroker :: + * The target stroker handle. + * + * radius :: + * The border radius. + * + * line_cap :: + * The line cap style. + * + * line_join :: + * The line join style. + * + * miter_limit :: + * The miter limit for the FT_STROKER_LINEJOIN_MITER_FIXED and + * FT_STROKER_LINEJOIN_MITER_VARIABLE line join styles, + * expressed as 16.16 fixed point value. + * + * @note: + * The radius is expressed in the same units as the outline + * coordinates. + */ + FT_EXPORT( void ) + FT_Stroker_Set( FT_Stroker stroker, + FT_Fixed radius, + FT_Stroker_LineCap line_cap, + FT_Stroker_LineJoin line_join, + FT_Fixed miter_limit ); + + + /************************************************************** + * + * @function: + * FT_Stroker_Rewind + * + * @description: + * Reset a stroker object without changing its attributes. + * You should call this function before beginning a new + * series of calls to @FT_Stroker_BeginSubPath or + * @FT_Stroker_EndSubPath. + * + * @input: + * stroker :: + * The target stroker handle. + */ + FT_EXPORT( void ) + FT_Stroker_Rewind( FT_Stroker stroker ); + + + /************************************************************** + * + * @function: + * FT_Stroker_ParseOutline + * + * @description: + * A convenience function used to parse a whole outline with + * the stroker. The resulting outline(s) can be retrieved + * later by functions like @FT_Stroker_GetCounts and @FT_Stroker_Export. + * + * @input: + * stroker :: + * The target stroker handle. + * + * outline :: + * The source outline. + * + * opened :: + * A boolean. If~1, the outline is treated as an open path instead + * of a closed one. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * If `opened' is~0 (the default), the outline is treated as a closed + * path, and the stroker generates two distinct `border' outlines. + * + * If `opened' is~1, the outline is processed as an open path, and the + * stroker generates a single `stroke' outline. + * + * This function calls @FT_Stroker_Rewind automatically. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_ParseOutline( FT_Stroker stroker, + FT_Outline* outline, + FT_Bool opened ); + + + /************************************************************** + * + * @function: + * FT_Stroker_BeginSubPath + * + * @description: + * Start a new sub-path in the stroker. + * + * @input: + * stroker :: + * The target stroker handle. + * + * to :: + * A pointer to the start vector. + * + * open :: + * A boolean. If~1, the sub-path is treated as an open one. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function is useful when you need to stroke a path that is + * not stored as an @FT_Outline object. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_BeginSubPath( FT_Stroker stroker, + FT_Vector* to, + FT_Bool open ); + + + /************************************************************** + * + * @function: + * FT_Stroker_EndSubPath + * + * @description: + * Close the current sub-path in the stroker. + * + * @input: + * stroker :: + * The target stroker handle. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * You should call this function after @FT_Stroker_BeginSubPath. + * If the subpath was not `opened', this function `draws' a + * single line segment to the start position when needed. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_EndSubPath( FT_Stroker stroker ); + + + /************************************************************** + * + * @function: + * FT_Stroker_LineTo + * + * @description: + * `Draw' a single line segment in the stroker's current sub-path, + * from the last position. + * + * @input: + * stroker :: + * The target stroker handle. + * + * to :: + * A pointer to the destination point. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * You should call this function between @FT_Stroker_BeginSubPath and + * @FT_Stroker_EndSubPath. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_LineTo( FT_Stroker stroker, + FT_Vector* to ); + + + /************************************************************** + * + * @function: + * FT_Stroker_ConicTo + * + * @description: + * `Draw' a single quadratic Bézier in the stroker's current sub-path, + * from the last position. + * + * @input: + * stroker :: + * The target stroker handle. + * + * control :: + * A pointer to a Bézier control point. + * + * to :: + * A pointer to the destination point. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * You should call this function between @FT_Stroker_BeginSubPath and + * @FT_Stroker_EndSubPath. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_ConicTo( FT_Stroker stroker, + FT_Vector* control, + FT_Vector* to ); + + + /************************************************************** + * + * @function: + * FT_Stroker_CubicTo + * + * @description: + * `Draw' a single cubic Bézier in the stroker's current sub-path, + * from the last position. + * + * @input: + * stroker :: + * The target stroker handle. + * + * control1 :: + * A pointer to the first Bézier control point. + * + * control2 :: + * A pointer to second Bézier control point. + * + * to :: + * A pointer to the destination point. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * You should call this function between @FT_Stroker_BeginSubPath and + * @FT_Stroker_EndSubPath. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_CubicTo( FT_Stroker stroker, + FT_Vector* control1, + FT_Vector* control2, + FT_Vector* to ); + + + /************************************************************** + * + * @function: + * FT_Stroker_GetBorderCounts + * + * @description: + * Call this function once you have finished parsing your paths + * with the stroker. It returns the number of points and + * contours necessary to export one of the `border' or `stroke' + * outlines generated by the stroker. + * + * @input: + * stroker :: + * The target stroker handle. + * + * border :: + * The border index. + * + * @output: + * anum_points :: + * The number of points. + * + * anum_contours :: + * The number of contours. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * When an outline, or a sub-path, is `closed', the stroker generates + * two independent `border' outlines, named `left' and `right'. + * + * When the outline, or a sub-path, is `opened', the stroker merges + * the `border' outlines with caps. The `left' border receives all + * points, while the `right' border becomes empty. + * + * Use the function @FT_Stroker_GetCounts instead if you want to + * retrieve the counts associated to both borders. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_GetBorderCounts( FT_Stroker stroker, + FT_StrokerBorder border, + FT_UInt *anum_points, + FT_UInt *anum_contours ); + + + /************************************************************** + * + * @function: + * FT_Stroker_ExportBorder + * + * @description: + * Call this function after @FT_Stroker_GetBorderCounts to + * export the corresponding border to your own @FT_Outline + * structure. + * + * Note that this function appends the border points and + * contours to your outline, but does not try to resize its + * arrays. + * + * @input: + * stroker :: + * The target stroker handle. + * + * border :: + * The border index. + * + * outline :: + * The target outline handle. + * + * @note: + * Always call this function after @FT_Stroker_GetBorderCounts to + * get sure that there is enough room in your @FT_Outline object to + * receive all new data. + * + * When an outline, or a sub-path, is `closed', the stroker generates + * two independent `border' outlines, named `left' and `right' + * + * When the outline, or a sub-path, is `opened', the stroker merges + * the `border' outlines with caps. The `left' border receives all + * points, while the `right' border becomes empty. + * + * Use the function @FT_Stroker_Export instead if you want to + * retrieve all borders at once. + */ + FT_EXPORT( void ) + FT_Stroker_ExportBorder( FT_Stroker stroker, + FT_StrokerBorder border, + FT_Outline* outline ); + + + /************************************************************** + * + * @function: + * FT_Stroker_GetCounts + * + * @description: + * Call this function once you have finished parsing your paths + * with the stroker. It returns the number of points and + * contours necessary to export all points/borders from the stroked + * outline/path. + * + * @input: + * stroker :: + * The target stroker handle. + * + * @output: + * anum_points :: + * The number of points. + * + * anum_contours :: + * The number of contours. + * + * @return: + * FreeType error code. 0~means success. + */ + FT_EXPORT( FT_Error ) + FT_Stroker_GetCounts( FT_Stroker stroker, + FT_UInt *anum_points, + FT_UInt *anum_contours ); + + + /************************************************************** + * + * @function: + * FT_Stroker_Export + * + * @description: + * Call this function after @FT_Stroker_GetBorderCounts to + * export all borders to your own @FT_Outline structure. + * + * Note that this function appends the border points and + * contours to your outline, but does not try to resize its + * arrays. + * + * @input: + * stroker :: + * The target stroker handle. + * + * outline :: + * The target outline handle. + */ + FT_EXPORT( void ) + FT_Stroker_Export( FT_Stroker stroker, + FT_Outline* outline ); + + + /************************************************************** + * + * @function: + * FT_Stroker_Done + * + * @description: + * Destroy a stroker object. + * + * @input: + * stroker :: + * A stroker handle. Can be NULL. + */ + FT_EXPORT( void ) + FT_Stroker_Done( FT_Stroker stroker ); + + + /************************************************************** + * + * @function: + * FT_Glyph_Stroke + * + * @description: + * Stroke a given outline glyph object with a given stroker. + * + * @inout: + * pglyph :: + * Source glyph handle on input, new glyph handle on output. + * + * @input: + * stroker :: + * A stroker handle. + * + * destroy :: + * A Boolean. If~1, the source glyph object is destroyed + * on success. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The source glyph is untouched in case of error. + */ + FT_EXPORT( FT_Error ) + FT_Glyph_Stroke( FT_Glyph *pglyph, + FT_Stroker stroker, + FT_Bool destroy ); + + + /************************************************************** + * + * @function: + * FT_Glyph_StrokeBorder + * + * @description: + * Stroke a given outline glyph object with a given stroker, but + * only return either its inside or outside border. + * + * @inout: + * pglyph :: + * Source glyph handle on input, new glyph handle on output. + * + * @input: + * stroker :: + * A stroker handle. + * + * inside :: + * A Boolean. If~1, return the inside border, otherwise + * the outside border. + * + * destroy :: + * A Boolean. If~1, the source glyph object is destroyed + * on success. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The source glyph is untouched in case of error. + */ + FT_EXPORT( FT_Error ) + FT_Glyph_StrokeBorder( FT_Glyph *pglyph, + FT_Stroker stroker, + FT_Bool inside, + FT_Bool destroy ); + + /* */ + +FT_END_HEADER + +#endif /* __FT_STROKE_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftsynth.h b/other/freetype/include/freetype/ftsynth.h new file mode 100644 index 0000000..a068b79 --- /dev/null +++ b/other/freetype/include/freetype/ftsynth.h @@ -0,0 +1,80 @@ +/***************************************************************************/ +/* */ +/* ftsynth.h */ +/* */ +/* FreeType synthesizing code for emboldening and slanting */ +/* (specification). */ +/* */ +/* Copyright 2000-2001, 2003, 2006, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /********* *********/ + /********* WARNING, THIS IS ALPHA CODE! THIS API *********/ + /********* IS DUE TO CHANGE UNTIL STRICTLY NOTIFIED BY THE *********/ + /********* FREETYPE DEVELOPMENT TEAM *********/ + /********* *********/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /* Main reason for not lifting the functions in this module to a */ + /* `standard' API is that the used parameters for emboldening and */ + /* slanting are not configurable. Consider the functions as a */ + /* code resource which should be copied into the application and */ + /* adapted to the particular needs. */ + + +#ifndef __FTSYNTH_H__ +#define __FTSYNTH_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /* Embolden a glyph by a `reasonable' value (which is highly a matter of */ + /* taste). This function is actually a convenience function, providing */ + /* a wrapper for @FT_Outline_Embolden and @FT_Bitmap_Embolden. */ + /* */ + /* For emboldened outlines the metrics are estimates only; if you need */ + /* precise values you should call @FT_Outline_Get_CBox. */ + FT_EXPORT( void ) + FT_GlyphSlot_Embolden( FT_GlyphSlot slot ); + + /* Slant an outline glyph to the right by about 12 degrees. */ + FT_EXPORT( void ) + FT_GlyphSlot_Oblique( FT_GlyphSlot slot ); + + /* */ + +FT_END_HEADER + +#endif /* __FTSYNTH_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftsystem.h b/other/freetype/include/freetype/ftsystem.h new file mode 100644 index 0000000..e07460c --- /dev/null +++ b/other/freetype/include/freetype/ftsystem.h @@ -0,0 +1,347 @@ +/***************************************************************************/ +/* */ +/* ftsystem.h */ +/* */ +/* FreeType low-level system interface definition (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2005, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTSYSTEM_H__ +#define __FTSYSTEM_H__ + + +#include <ft2build.h> + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* system_interface */ + /* */ + /* <Title> */ + /* System Interface */ + /* */ + /* <Abstract> */ + /* How FreeType manages memory and i/o. */ + /* */ + /* <Description> */ + /* This section contains various definitions related to memory */ + /* management and i/o access. You need to understand this */ + /* information if you want to use a custom memory manager or you own */ + /* i/o streams. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* M E M O R Y M A N A G E M E N T */ + /* */ + /*************************************************************************/ + + + /************************************************************************* + * + * @type: + * FT_Memory + * + * @description: + * A handle to a given memory manager object, defined with an + * @FT_MemoryRec structure. + * + */ + typedef struct FT_MemoryRec_* FT_Memory; + + + /************************************************************************* + * + * @functype: + * FT_Alloc_Func + * + * @description: + * A function used to allocate `size' bytes from `memory'. + * + * @input: + * memory :: + * A handle to the source memory manager. + * + * size :: + * The size in bytes to allocate. + * + * @return: + * Address of new memory block. 0~in case of failure. + * + */ + typedef void* + (*FT_Alloc_Func)( FT_Memory memory, + long size ); + + + /************************************************************************* + * + * @functype: + * FT_Free_Func + * + * @description: + * A function used to release a given block of memory. + * + * @input: + * memory :: + * A handle to the source memory manager. + * + * block :: + * The address of the target memory block. + * + */ + typedef void + (*FT_Free_Func)( FT_Memory memory, + void* block ); + + + /************************************************************************* + * + * @functype: + * FT_Realloc_Func + * + * @description: + * A function used to re-allocate a given block of memory. + * + * @input: + * memory :: + * A handle to the source memory manager. + * + * cur_size :: + * The block's current size in bytes. + * + * new_size :: + * The block's requested new size. + * + * block :: + * The block's current address. + * + * @return: + * New block address. 0~in case of memory shortage. + * + * @note: + * In case of error, the old block must still be available. + * + */ + typedef void* + (*FT_Realloc_Func)( FT_Memory memory, + long cur_size, + long new_size, + void* block ); + + + /************************************************************************* + * + * @struct: + * FT_MemoryRec + * + * @description: + * A structure used to describe a given memory manager to FreeType~2. + * + * @fields: + * user :: + * A generic typeless pointer for user data. + * + * alloc :: + * A pointer type to an allocation function. + * + * free :: + * A pointer type to an memory freeing function. + * + * realloc :: + * A pointer type to a reallocation function. + * + */ + struct FT_MemoryRec_ + { + void* user; + FT_Alloc_Func alloc; + FT_Free_Func free; + FT_Realloc_Func realloc; + }; + + + /*************************************************************************/ + /* */ + /* I / O M A N A G E M E N T */ + /* */ + /*************************************************************************/ + + + /************************************************************************* + * + * @type: + * FT_Stream + * + * @description: + * A handle to an input stream. + * + */ + typedef struct FT_StreamRec_* FT_Stream; + + + /************************************************************************* + * + * @struct: + * FT_StreamDesc + * + * @description: + * A union type used to store either a long or a pointer. This is used + * to store a file descriptor or a `FILE*' in an input stream. + * + */ + typedef union FT_StreamDesc_ + { + long value; + void* pointer; + + } FT_StreamDesc; + + + /************************************************************************* + * + * @functype: + * FT_Stream_IoFunc + * + * @description: + * A function used to seek and read data from a given input stream. + * + * @input: + * stream :: + * A handle to the source stream. + * + * offset :: + * The offset of read in stream (always from start). + * + * buffer :: + * The address of the read buffer. + * + * count :: + * The number of bytes to read from the stream. + * + * @return: + * The number of bytes effectively read by the stream. + * + * @note: + * This function might be called to perform a seek or skip operation + * with a `count' of~0. A non-zero return value then indicates an + * error. + * + */ + typedef unsigned long + (*FT_Stream_IoFunc)( FT_Stream stream, + unsigned long offset, + unsigned char* buffer, + unsigned long count ); + + + /************************************************************************* + * + * @functype: + * FT_Stream_CloseFunc + * + * @description: + * A function used to close a given input stream. + * + * @input: + * stream :: + * A handle to the target stream. + * + */ + typedef void + (*FT_Stream_CloseFunc)( FT_Stream stream ); + + + /************************************************************************* + * + * @struct: + * FT_StreamRec + * + * @description: + * A structure used to describe an input stream. + * + * @input: + * base :: + * For memory-based streams, this is the address of the first stream + * byte in memory. This field should always be set to NULL for + * disk-based streams. + * + * size :: + * The stream size in bytes. + * + * pos :: + * The current position within the stream. + * + * descriptor :: + * This field is a union that can hold an integer or a pointer. It is + * used by stream implementations to store file descriptors or `FILE*' + * pointers. + * + * pathname :: + * This field is completely ignored by FreeType. However, it is often + * useful during debugging to use it to store the stream's filename + * (where available). + * + * read :: + * The stream's input function. + * + * close :: + * The stream's close function. + * + * memory :: + * The memory manager to use to preload frames. This is set + * internally by FreeType and shouldn't be touched by stream + * implementations. + * + * cursor :: + * This field is set and used internally by FreeType when parsing + * frames. + * + * limit :: + * This field is set and used internally by FreeType when parsing + * frames. + * + */ + typedef struct FT_StreamRec_ + { + unsigned char* base; + unsigned long size; + unsigned long pos; + + FT_StreamDesc descriptor; + FT_StreamDesc pathname; + FT_Stream_IoFunc read; + FT_Stream_CloseFunc close; + + FT_Memory memory; + unsigned char* cursor; + unsigned char* limit; + + } FT_StreamRec; + + + /* */ + + +FT_END_HEADER + +#endif /* __FTSYSTEM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/fttrigon.h b/other/freetype/include/freetype/fttrigon.h new file mode 100644 index 0000000..6b77d2e --- /dev/null +++ b/other/freetype/include/freetype/fttrigon.h @@ -0,0 +1,350 @@ +/***************************************************************************/ +/* */ +/* fttrigon.h */ +/* */ +/* FreeType trigonometric functions (specification). */ +/* */ +/* Copyright 2001, 2003, 2005, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTTRIGON_H__ +#define __FTTRIGON_H__ + +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* computations */ + /* */ + /*************************************************************************/ + + + /************************************************************************* + * + * @type: + * FT_Angle + * + * @description: + * This type is used to model angle values in FreeType. Note that the + * angle is a 16.16 fixed float value expressed in degrees. + * + */ + typedef FT_Fixed FT_Angle; + + + /************************************************************************* + * + * @macro: + * FT_ANGLE_PI + * + * @description: + * The angle pi expressed in @FT_Angle units. + * + */ +#define FT_ANGLE_PI ( 180L << 16 ) + + + /************************************************************************* + * + * @macro: + * FT_ANGLE_2PI + * + * @description: + * The angle 2*pi expressed in @FT_Angle units. + * + */ +#define FT_ANGLE_2PI ( FT_ANGLE_PI * 2 ) + + + /************************************************************************* + * + * @macro: + * FT_ANGLE_PI2 + * + * @description: + * The angle pi/2 expressed in @FT_Angle units. + * + */ +#define FT_ANGLE_PI2 ( FT_ANGLE_PI / 2 ) + + + /************************************************************************* + * + * @macro: + * FT_ANGLE_PI4 + * + * @description: + * The angle pi/4 expressed in @FT_Angle units. + * + */ +#define FT_ANGLE_PI4 ( FT_ANGLE_PI / 4 ) + + + /************************************************************************* + * + * @function: + * FT_Sin + * + * @description: + * Return the sinus of a given angle in fixed point format. + * + * @input: + * angle :: + * The input angle. + * + * @return: + * The sinus value. + * + * @note: + * If you need both the sinus and cosinus for a given angle, use the + * function @FT_Vector_Unit. + * + */ + FT_EXPORT( FT_Fixed ) + FT_Sin( FT_Angle angle ); + + + /************************************************************************* + * + * @function: + * FT_Cos + * + * @description: + * Return the cosinus of a given angle in fixed point format. + * + * @input: + * angle :: + * The input angle. + * + * @return: + * The cosinus value. + * + * @note: + * If you need both the sinus and cosinus for a given angle, use the + * function @FT_Vector_Unit. + * + */ + FT_EXPORT( FT_Fixed ) + FT_Cos( FT_Angle angle ); + + + /************************************************************************* + * + * @function: + * FT_Tan + * + * @description: + * Return the tangent of a given angle in fixed point format. + * + * @input: + * angle :: + * The input angle. + * + * @return: + * The tangent value. + * + */ + FT_EXPORT( FT_Fixed ) + FT_Tan( FT_Angle angle ); + + + /************************************************************************* + * + * @function: + * FT_Atan2 + * + * @description: + * Return the arc-tangent corresponding to a given vector (x,y) in + * the 2d plane. + * + * @input: + * x :: + * The horizontal vector coordinate. + * + * y :: + * The vertical vector coordinate. + * + * @return: + * The arc-tangent value (i.e. angle). + * + */ + FT_EXPORT( FT_Angle ) + FT_Atan2( FT_Fixed x, + FT_Fixed y ); + + + /************************************************************************* + * + * @function: + * FT_Angle_Diff + * + * @description: + * Return the difference between two angles. The result is always + * constrained to the ]-PI..PI] interval. + * + * @input: + * angle1 :: + * First angle. + * + * angle2 :: + * Second angle. + * + * @return: + * Constrained value of `value2-value1'. + * + */ + FT_EXPORT( FT_Angle ) + FT_Angle_Diff( FT_Angle angle1, + FT_Angle angle2 ); + + + /************************************************************************* + * + * @function: + * FT_Vector_Unit + * + * @description: + * Return the unit vector corresponding to a given angle. After the + * call, the value of `vec.x' will be `sin(angle)', and the value of + * `vec.y' will be `cos(angle)'. + * + * This function is useful to retrieve both the sinus and cosinus of a + * given angle quickly. + * + * @output: + * vec :: + * The address of target vector. + * + * @input: + * angle :: + * The address of angle. + * + */ + FT_EXPORT( void ) + FT_Vector_Unit( FT_Vector* vec, + FT_Angle angle ); + + + /************************************************************************* + * + * @function: + * FT_Vector_Rotate + * + * @description: + * Rotate a vector by a given angle. + * + * @inout: + * vec :: + * The address of target vector. + * + * @input: + * angle :: + * The address of angle. + * + */ + FT_EXPORT( void ) + FT_Vector_Rotate( FT_Vector* vec, + FT_Angle angle ); + + + /************************************************************************* + * + * @function: + * FT_Vector_Length + * + * @description: + * Return the length of a given vector. + * + * @input: + * vec :: + * The address of target vector. + * + * @return: + * The vector length, expressed in the same units that the original + * vector coordinates. + * + */ + FT_EXPORT( FT_Fixed ) + FT_Vector_Length( FT_Vector* vec ); + + + /************************************************************************* + * + * @function: + * FT_Vector_Polarize + * + * @description: + * Compute both the length and angle of a given vector. + * + * @input: + * vec :: + * The address of source vector. + * + * @output: + * length :: + * The vector length. + * + * angle :: + * The vector angle. + * + */ + FT_EXPORT( void ) + FT_Vector_Polarize( FT_Vector* vec, + FT_Fixed *length, + FT_Angle *angle ); + + + /************************************************************************* + * + * @function: + * FT_Vector_From_Polar + * + * @description: + * Compute vector coordinates from a length and angle. + * + * @output: + * vec :: + * The address of source vector. + * + * @input: + * length :: + * The vector length. + * + * angle :: + * The vector angle. + * + */ + FT_EXPORT( void ) + FT_Vector_From_Polar( FT_Vector* vec, + FT_Fixed length, + FT_Angle angle ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTTRIGON_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/fttypes.h b/other/freetype/include/freetype/fttypes.h new file mode 100644 index 0000000..a57ffa6 --- /dev/null +++ b/other/freetype/include/freetype/fttypes.h @@ -0,0 +1,588 @@ +/***************************************************************************/ +/* */ +/* fttypes.h */ +/* */ +/* FreeType simple types definitions (specification only). */ +/* */ +/* Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTTYPES_H__ +#define __FTTYPES_H__ + + +#include <ft2build.h> +#include FT_CONFIG_CONFIG_H +#include FT_SYSTEM_H +#include FT_IMAGE_H + +#include <stddef.h> + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* basic_types */ + /* */ + /* <Title> */ + /* Basic Data Types */ + /* */ + /* <Abstract> */ + /* The basic data types defined by the library. */ + /* */ + /* <Description> */ + /* This section contains the basic data types defined by FreeType~2, */ + /* ranging from simple scalar types to bitmap descriptors. More */ + /* font-specific structures are defined in a different section. */ + /* */ + /* <Order> */ + /* FT_Byte */ + /* FT_Bytes */ + /* FT_Char */ + /* FT_Int */ + /* FT_UInt */ + /* FT_Int16 */ + /* FT_UInt16 */ + /* FT_Int32 */ + /* FT_UInt32 */ + /* FT_Short */ + /* FT_UShort */ + /* FT_Long */ + /* FT_ULong */ + /* FT_Bool */ + /* FT_Offset */ + /* FT_PtrDist */ + /* FT_String */ + /* FT_Tag */ + /* FT_Error */ + /* FT_Fixed */ + /* FT_Pointer */ + /* FT_Pos */ + /* FT_Vector */ + /* FT_BBox */ + /* FT_Matrix */ + /* FT_FWord */ + /* FT_UFWord */ + /* FT_F2Dot14 */ + /* FT_UnitVector */ + /* FT_F26Dot6 */ + /* */ + /* */ + /* FT_Generic */ + /* FT_Generic_Finalizer */ + /* */ + /* FT_Bitmap */ + /* FT_Pixel_Mode */ + /* FT_Palette_Mode */ + /* FT_Glyph_Format */ + /* FT_IMAGE_TAG */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Bool */ + /* */ + /* <Description> */ + /* A typedef of unsigned char, used for simple booleans. As usual, */ + /* values 1 and~0 represent true and false, respectively. */ + /* */ + typedef unsigned char FT_Bool; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_FWord */ + /* */ + /* <Description> */ + /* A signed 16-bit integer used to store a distance in original font */ + /* units. */ + /* */ + typedef signed short FT_FWord; /* distance in FUnits */ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_UFWord */ + /* */ + /* <Description> */ + /* An unsigned 16-bit integer used to store a distance in original */ + /* font units. */ + /* */ + typedef unsigned short FT_UFWord; /* unsigned distance */ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Char */ + /* */ + /* <Description> */ + /* A simple typedef for the _signed_ char type. */ + /* */ + typedef signed char FT_Char; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Byte */ + /* */ + /* <Description> */ + /* A simple typedef for the _unsigned_ char type. */ + /* */ + typedef unsigned char FT_Byte; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Bytes */ + /* */ + /* <Description> */ + /* A typedef for constant memory areas. */ + /* */ + typedef const FT_Byte* FT_Bytes; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Tag */ + /* */ + /* <Description> */ + /* A typedef for 32-bit tags (as used in the SFNT format). */ + /* */ + typedef FT_UInt32 FT_Tag; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_String */ + /* */ + /* <Description> */ + /* A simple typedef for the char type, usually used for strings. */ + /* */ + typedef char FT_String; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Short */ + /* */ + /* <Description> */ + /* A typedef for signed short. */ + /* */ + typedef signed short FT_Short; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_UShort */ + /* */ + /* <Description> */ + /* A typedef for unsigned short. */ + /* */ + typedef unsigned short FT_UShort; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Int */ + /* */ + /* <Description> */ + /* A typedef for the int type. */ + /* */ + typedef signed int FT_Int; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_UInt */ + /* */ + /* <Description> */ + /* A typedef for the unsigned int type. */ + /* */ + typedef unsigned int FT_UInt; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Long */ + /* */ + /* <Description> */ + /* A typedef for signed long. */ + /* */ + typedef signed long FT_Long; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_ULong */ + /* */ + /* <Description> */ + /* A typedef for unsigned long. */ + /* */ + typedef unsigned long FT_ULong; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_F2Dot14 */ + /* */ + /* <Description> */ + /* A signed 2.14 fixed float type used for unit vectors. */ + /* */ + typedef signed short FT_F2Dot14; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_F26Dot6 */ + /* */ + /* <Description> */ + /* A signed 26.6 fixed float type used for vectorial pixel */ + /* coordinates. */ + /* */ + typedef signed long FT_F26Dot6; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Fixed */ + /* */ + /* <Description> */ + /* This type is used to store 16.16 fixed float values, like scaling */ + /* values or matrix coefficients. */ + /* */ + typedef signed long FT_Fixed; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Error */ + /* */ + /* <Description> */ + /* The FreeType error code type. A value of~0 is always interpreted */ + /* as a successful operation. */ + /* */ + typedef int FT_Error; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Pointer */ + /* */ + /* <Description> */ + /* A simple typedef for a typeless pointer. */ + /* */ + typedef void* FT_Pointer; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_Offset */ + /* */ + /* <Description> */ + /* This is equivalent to the ANSI~C `size_t' type, i.e., the largest */ + /* _unsigned_ integer type used to express a file size or position, */ + /* or a memory block size. */ + /* */ + typedef size_t FT_Offset; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_PtrDist */ + /* */ + /* <Description> */ + /* This is equivalent to the ANSI~C `ptrdiff_t' type, i.e., the */ + /* largest _signed_ integer type used to express the distance */ + /* between two pointers. */ + /* */ + typedef ft_ptrdiff_t FT_PtrDist; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_UnitVector */ + /* */ + /* <Description> */ + /* A simple structure used to store a 2D vector unit vector. Uses */ + /* FT_F2Dot14 types. */ + /* */ + /* <Fields> */ + /* x :: Horizontal coordinate. */ + /* */ + /* y :: Vertical coordinate. */ + /* */ + typedef struct FT_UnitVector_ + { + FT_F2Dot14 x; + FT_F2Dot14 y; + + } FT_UnitVector; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Matrix */ + /* */ + /* <Description> */ + /* A simple structure used to store a 2x2 matrix. Coefficients are */ + /* in 16.16 fixed float format. The computation performed is: */ + /* */ + /* { */ + /* x' = x*xx + y*xy */ + /* y' = x*yx + y*yy */ + /* } */ + /* */ + /* <Fields> */ + /* xx :: Matrix coefficient. */ + /* */ + /* xy :: Matrix coefficient. */ + /* */ + /* yx :: Matrix coefficient. */ + /* */ + /* yy :: Matrix coefficient. */ + /* */ + typedef struct FT_Matrix_ + { + FT_Fixed xx, xy; + FT_Fixed yx, yy; + + } FT_Matrix; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Data */ + /* */ + /* <Description> */ + /* Read-only binary data represented as a pointer and a length. */ + /* */ + /* <Fields> */ + /* pointer :: The data. */ + /* */ + /* length :: The length of the data in bytes. */ + /* */ + typedef struct FT_Data_ + { + const FT_Byte* pointer; + FT_Int length; + + } FT_Data; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Generic_Finalizer */ + /* */ + /* <Description> */ + /* Describe a function used to destroy the `client' data of any */ + /* FreeType object. See the description of the @FT_Generic type for */ + /* details of usage. */ + /* */ + /* <Input> */ + /* The address of the FreeType object which is under finalization. */ + /* Its client data is accessed through its `generic' field. */ + /* */ + typedef void (*FT_Generic_Finalizer)(void* object); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Generic */ + /* */ + /* <Description> */ + /* Client applications often need to associate their own data to a */ + /* variety of FreeType core objects. For example, a text layout API */ + /* might want to associate a glyph cache to a given size object. */ + /* */ + /* Most FreeType object contains a `generic' field, of type */ + /* FT_Generic, which usage is left to client applications and font */ + /* servers. */ + /* */ + /* It can be used to store a pointer to client-specific data, as well */ + /* as the address of a `finalizer' function, which will be called by */ + /* FreeType when the object is destroyed (for example, the previous */ + /* client example would put the address of the glyph cache destructor */ + /* in the `finalizer' field). */ + /* */ + /* <Fields> */ + /* data :: A typeless pointer to any client-specified data. This */ + /* field is completely ignored by the FreeType library. */ + /* */ + /* finalizer :: A pointer to a `generic finalizer' function, which */ + /* will be called when the object is destroyed. If this */ + /* field is set to NULL, no code will be called. */ + /* */ + typedef struct FT_Generic_ + { + void* data; + FT_Generic_Finalizer finalizer; + + } FT_Generic; + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_MAKE_TAG */ + /* */ + /* <Description> */ + /* This macro converts four-letter tags which are used to label */ + /* TrueType tables into an unsigned long to be used within FreeType. */ + /* */ + /* <Note> */ + /* The produced values *must* be 32-bit integers. Don't redefine */ + /* this macro. */ + /* */ +#define FT_MAKE_TAG( _x1, _x2, _x3, _x4 ) \ + (FT_Tag) \ + ( ( (FT_ULong)_x1 << 24 ) | \ + ( (FT_ULong)_x2 << 16 ) | \ + ( (FT_ULong)_x3 << 8 ) | \ + (FT_ULong)_x4 ) + + + /*************************************************************************/ + /*************************************************************************/ + /* */ + /* L I S T M A N A G E M E N T */ + /* */ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* list_processing */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_ListNode */ + /* */ + /* <Description> */ + /* Many elements and objects in FreeType are listed through an */ + /* @FT_List record (see @FT_ListRec). As its name suggests, an */ + /* FT_ListNode is a handle to a single list element. */ + /* */ + typedef struct FT_ListNodeRec_* FT_ListNode; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* FT_List */ + /* */ + /* <Description> */ + /* A handle to a list record (see @FT_ListRec). */ + /* */ + typedef struct FT_ListRec_* FT_List; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_ListNodeRec */ + /* */ + /* <Description> */ + /* A structure used to hold a single list element. */ + /* */ + /* <Fields> */ + /* prev :: The previous element in the list. NULL if first. */ + /* */ + /* next :: The next element in the list. NULL if last. */ + /* */ + /* data :: A typeless pointer to the listed object. */ + /* */ + typedef struct FT_ListNodeRec_ + { + FT_ListNode prev; + FT_ListNode next; + void* data; + + } FT_ListNodeRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_ListRec */ + /* */ + /* <Description> */ + /* A structure used to hold a simple doubly-linked list. These are */ + /* used in many parts of FreeType. */ + /* */ + /* <Fields> */ + /* head :: The head (first element) of doubly-linked list. */ + /* */ + /* tail :: The tail (last element) of doubly-linked list. */ + /* */ + typedef struct FT_ListRec_ + { + FT_ListNode head; + FT_ListNode tail; + + } FT_ListRec; + + + /* */ + +#define FT_IS_EMPTY( list ) ( (list).head == 0 ) + + /* return base error code (without module-specific prefix) */ +#define FT_ERROR_BASE( x ) ( (x) & 0xFF ) + + /* return module error code */ +#define FT_ERROR_MODULE( x ) ( (x) & 0xFF00U ) + +#define FT_BOOL( x ) ( (FT_Bool)( x ) ) + +FT_END_HEADER + +#endif /* __FTTYPES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ftwinfnt.h b/other/freetype/include/freetype/ftwinfnt.h new file mode 100644 index 0000000..ea33353 --- /dev/null +++ b/other/freetype/include/freetype/ftwinfnt.h @@ -0,0 +1,274 @@ +/***************************************************************************/ +/* */ +/* ftwinfnt.h */ +/* */ +/* FreeType API for accessing Windows fnt-specific data. */ +/* */ +/* Copyright 2003, 2004, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTWINFNT_H__ +#define __FTWINFNT_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* winfnt_fonts */ + /* */ + /* <Title> */ + /* Window FNT Files */ + /* */ + /* <Abstract> */ + /* Windows FNT specific API. */ + /* */ + /* <Description> */ + /* This section contains the declaration of Windows FNT specific */ + /* functions. */ + /* */ + /*************************************************************************/ + + + /************************************************************************* + * + * @enum: + * FT_WinFNT_ID_XXX + * + * @description: + * A list of valid values for the `charset' byte in + * @FT_WinFNT_HeaderRec. Exact mapping tables for the various cpXXXX + * encodings (except for cp1361) can be found at ftp://ftp.unicode.org + * in the MAPPINGS/VENDORS/MICSFT/WINDOWS subdirectory. cp1361 is + * roughly a superset of MAPPINGS/OBSOLETE/EASTASIA/KSC/JOHAB.TXT. + * + * @values: + * FT_WinFNT_ID_DEFAULT :: + * This is used for font enumeration and font creation as a + * `don't care' value. Valid font files don't contain this value. + * When querying for information about the character set of the font + * that is currently selected into a specified device context, this + * return value (of the related Windows API) simply denotes failure. + * + * FT_WinFNT_ID_SYMBOL :: + * There is no known mapping table available. + * + * FT_WinFNT_ID_MAC :: + * Mac Roman encoding. + * + * FT_WinFNT_ID_OEM :: + * From Michael Pöttgen <michael@poettgen.de>: + * + * The `Windows Font Mapping' article says that FT_WinFNT_ID_OEM + * is used for the charset of vector fonts, like `modern.fon', + * `roman.fon', and `script.fon' on Windows. + * + * The `CreateFont' documentation says: The FT_WinFNT_ID_OEM value + * specifies a character set that is operating-system dependent. + * + * The `IFIMETRICS' documentation from the `Windows Driver + * Development Kit' says: This font supports an OEM-specific + * character set. The OEM character set is system dependent. + * + * In general OEM, as opposed to ANSI (i.e., cp1252), denotes the + * second default codepage that most international versions of + * Windows have. It is one of the OEM codepages from + * + * http://www.microsoft.com/globaldev/reference/cphome.mspx, + * + * and is used for the `DOS boxes', to support legacy applications. + * A German Windows version for example usually uses ANSI codepage + * 1252 and OEM codepage 850. + * + * FT_WinFNT_ID_CP874 :: + * A superset of Thai TIS 620 and ISO 8859-11. + * + * FT_WinFNT_ID_CP932 :: + * A superset of Japanese Shift-JIS (with minor deviations). + * + * FT_WinFNT_ID_CP936 :: + * A superset of simplified Chinese GB 2312-1980 (with different + * ordering and minor deviations). + * + * FT_WinFNT_ID_CP949 :: + * A superset of Korean Hangul KS~C 5601-1987 (with different + * ordering and minor deviations). + * + * FT_WinFNT_ID_CP950 :: + * A superset of traditional Chinese Big~5 ETen (with different + * ordering and minor deviations). + * + * FT_WinFNT_ID_CP1250 :: + * A superset of East European ISO 8859-2 (with slightly different + * ordering). + * + * FT_WinFNT_ID_CP1251 :: + * A superset of Russian ISO 8859-5 (with different ordering). + * + * FT_WinFNT_ID_CP1252 :: + * ANSI encoding. A superset of ISO 8859-1. + * + * FT_WinFNT_ID_CP1253 :: + * A superset of Greek ISO 8859-7 (with minor modifications). + * + * FT_WinFNT_ID_CP1254 :: + * A superset of Turkish ISO 8859-9. + * + * FT_WinFNT_ID_CP1255 :: + * A superset of Hebrew ISO 8859-8 (with some modifications). + * + * FT_WinFNT_ID_CP1256 :: + * A superset of Arabic ISO 8859-6 (with different ordering). + * + * FT_WinFNT_ID_CP1257 :: + * A superset of Baltic ISO 8859-13 (with some deviations). + * + * FT_WinFNT_ID_CP1258 :: + * For Vietnamese. This encoding doesn't cover all necessary + * characters. + * + * FT_WinFNT_ID_CP1361 :: + * Korean (Johab). + */ + +#define FT_WinFNT_ID_CP1252 0 +#define FT_WinFNT_ID_DEFAULT 1 +#define FT_WinFNT_ID_SYMBOL 2 +#define FT_WinFNT_ID_MAC 77 +#define FT_WinFNT_ID_CP932 128 +#define FT_WinFNT_ID_CP949 129 +#define FT_WinFNT_ID_CP1361 130 +#define FT_WinFNT_ID_CP936 134 +#define FT_WinFNT_ID_CP950 136 +#define FT_WinFNT_ID_CP1253 161 +#define FT_WinFNT_ID_CP1254 162 +#define FT_WinFNT_ID_CP1258 163 +#define FT_WinFNT_ID_CP1255 177 +#define FT_WinFNT_ID_CP1256 178 +#define FT_WinFNT_ID_CP1257 186 +#define FT_WinFNT_ID_CP1251 204 +#define FT_WinFNT_ID_CP874 222 +#define FT_WinFNT_ID_CP1250 238 +#define FT_WinFNT_ID_OEM 255 + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_WinFNT_HeaderRec */ + /* */ + /* <Description> */ + /* Windows FNT Header info. */ + /* */ + typedef struct FT_WinFNT_HeaderRec_ + { + FT_UShort version; + FT_ULong file_size; + FT_Byte copyright[60]; + FT_UShort file_type; + FT_UShort nominal_point_size; + FT_UShort vertical_resolution; + FT_UShort horizontal_resolution; + FT_UShort ascent; + FT_UShort internal_leading; + FT_UShort external_leading; + FT_Byte italic; + FT_Byte underline; + FT_Byte strike_out; + FT_UShort weight; + FT_Byte charset; + FT_UShort pixel_width; + FT_UShort pixel_height; + FT_Byte pitch_and_family; + FT_UShort avg_width; + FT_UShort max_width; + FT_Byte first_char; + FT_Byte last_char; + FT_Byte default_char; + FT_Byte break_char; + FT_UShort bytes_per_row; + FT_ULong device_offset; + FT_ULong face_name_offset; + FT_ULong bits_pointer; + FT_ULong bits_offset; + FT_Byte reserved; + FT_ULong flags; + FT_UShort A_space; + FT_UShort B_space; + FT_UShort C_space; + FT_UShort color_table_offset; + FT_ULong reserved1[4]; + + } FT_WinFNT_HeaderRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_WinFNT_Header */ + /* */ + /* <Description> */ + /* A handle to an @FT_WinFNT_HeaderRec structure. */ + /* */ + typedef struct FT_WinFNT_HeaderRec_* FT_WinFNT_Header; + + + /********************************************************************** + * + * @function: + * FT_Get_WinFNT_Header + * + * @description: + * Retrieve a Windows FNT font info header. + * + * @input: + * face :: A handle to the input face. + * + * @output: + * aheader :: The WinFNT header. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * This function only works with Windows FNT faces, returning an error + * otherwise. + */ + FT_EXPORT( FT_Error ) + FT_Get_WinFNT_Header( FT_Face face, + FT_WinFNT_HeaderRec *aheader ); + + + /* */ + +FT_END_HEADER + +#endif /* __FTWINFNT_H__ */ + + +/* END */ + + +/* Local Variables: */ +/* coding: utf-8 */ +/* End: */ diff --git a/other/freetype/include/freetype/ftxf86.h b/other/freetype/include/freetype/ftxf86.h new file mode 100644 index 0000000..8c68afd --- /dev/null +++ b/other/freetype/include/freetype/ftxf86.h @@ -0,0 +1,83 @@ +/***************************************************************************/ +/* */ +/* ftxf86.h */ +/* */ +/* Support functions for X11. */ +/* */ +/* Copyright 2002, 2003, 2004, 2006, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTXF86_H__ +#define __FTXF86_H__ + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* font_formats */ + /* */ + /* <Title> */ + /* Font Formats */ + /* */ + /* <Abstract> */ + /* Getting the font format. */ + /* */ + /* <Description> */ + /* The single function in this section can be used to get the font */ + /* format. Note that this information is not needed normally; */ + /* however, there are special cases (like in PDF devices) where it is */ + /* important to differentiate, in spite of FreeType's uniform API. */ + /* */ + /* This function is in the X11/xf86 namespace for historical reasons */ + /* and in no way depends on that windowing system. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_X11_Font_Format */ + /* */ + /* <Description> */ + /* Return a string describing the format of a given face, using values */ + /* which can be used as an X11 FONT_PROPERTY. Possible values are */ + /* `TrueType', `Type~1', `BDF', `PCF', `Type~42', `CID~Type~1', `CFF', */ + /* `PFR', and `Windows~FNT'. */ + /* */ + /* <Input> */ + /* face :: */ + /* Input face handle. */ + /* */ + /* <Return> */ + /* Font format string. NULL in case of error. */ + /* */ + FT_EXPORT( const char* ) + FT_Get_X11_Font_Format( FT_Face face ); + + /* */ + +FT_END_HEADER + +#endif /* __FTXF86_H__ */ diff --git a/other/freetype/include/freetype/internal/autohint.h b/other/freetype/include/freetype/internal/autohint.h new file mode 100644 index 0000000..7e3a08a --- /dev/null +++ b/other/freetype/include/freetype/internal/autohint.h @@ -0,0 +1,231 @@ +/***************************************************************************/ +/* */ +/* autohint.h */ +/* */ +/* High-level `autohint' module-specific interface (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* The auto-hinter is used to load and automatically hint glyphs if a */ + /* format-specific hinter isn't available. */ + /* */ + /*************************************************************************/ + + +#ifndef __AUTOHINT_H__ +#define __AUTOHINT_H__ + + + /*************************************************************************/ + /* */ + /* A small technical note regarding automatic hinting in order to */ + /* clarify this module interface. */ + /* */ + /* An automatic hinter might compute two kinds of data for a given face: */ + /* */ + /* - global hints: Usually some metrics that describe global properties */ + /* of the face. It is computed by scanning more or less */ + /* aggressively the glyphs in the face, and thus can be */ + /* very slow to compute (even if the size of global */ + /* hints is really small). */ + /* */ + /* - glyph hints: These describe some important features of the glyph */ + /* outline, as well as how to align them. They are */ + /* generally much faster to compute than global hints. */ + /* */ + /* The current FreeType auto-hinter does a pretty good job while */ + /* performing fast computations for both global and glyph hints. */ + /* However, we might be interested in introducing more complex and */ + /* powerful algorithms in the future, like the one described in the John */ + /* D. Hobby paper, which unfortunately requires a lot more horsepower. */ + /* */ + /* Because a sufficiently sophisticated font management system would */ + /* typically implement an LRU cache of opened face objects to reduce */ + /* memory usage, it is a good idea to be able to avoid recomputing */ + /* global hints every time the same face is re-opened. */ + /* */ + /* We thus provide the ability to cache global hints outside of the face */ + /* object, in order to speed up font re-opening time. Of course, this */ + /* feature is purely optional, so most client programs won't even notice */ + /* it. */ + /* */ + /* I initially thought that it would be a good idea to cache the glyph */ + /* hints too. However, my general idea now is that if you really need */ + /* to cache these too, you are simply in need of a new font format, */ + /* where all this information could be stored within the font file and */ + /* decoded on the fly. */ + /* */ + /*************************************************************************/ + + +#include <ft2build.h> +#include FT_FREETYPE_H + + +FT_BEGIN_HEADER + + + typedef struct FT_AutoHinterRec_ *FT_AutoHinter; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_AutoHinter_GlobalGetFunc */ + /* */ + /* <Description> */ + /* Retrieves the global hints computed for a given face object the */ + /* resulting data is dissociated from the face and will survive a */ + /* call to FT_Done_Face(). It must be discarded through the API */ + /* FT_AutoHinter_GlobalDoneFunc(). */ + /* */ + /* <Input> */ + /* hinter :: A handle to the source auto-hinter. */ + /* */ + /* face :: A handle to the source face object. */ + /* */ + /* <Output> */ + /* global_hints :: A typeless pointer to the global hints. */ + /* */ + /* global_len :: The size in bytes of the global hints. */ + /* */ + typedef void + (*FT_AutoHinter_GlobalGetFunc)( FT_AutoHinter hinter, + FT_Face face, + void** global_hints, + long* global_len ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_AutoHinter_GlobalDoneFunc */ + /* */ + /* <Description> */ + /* Discards the global hints retrieved through */ + /* FT_AutoHinter_GlobalGetFunc(). This is the only way these hints */ + /* are freed from memory. */ + /* */ + /* <Input> */ + /* hinter :: A handle to the auto-hinter module. */ + /* */ + /* global :: A pointer to retrieved global hints to discard. */ + /* */ + typedef void + (*FT_AutoHinter_GlobalDoneFunc)( FT_AutoHinter hinter, + void* global ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_AutoHinter_GlobalResetFunc */ + /* */ + /* <Description> */ + /* This function is used to recompute the global metrics in a given */ + /* font. This is useful when global font data changes (e.g. Multiple */ + /* Masters fonts where blend coordinates change). */ + /* */ + /* <Input> */ + /* hinter :: A handle to the source auto-hinter. */ + /* */ + /* face :: A handle to the face. */ + /* */ + typedef void + (*FT_AutoHinter_GlobalResetFunc)( FT_AutoHinter hinter, + FT_Face face ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_AutoHinter_GlyphLoadFunc */ + /* */ + /* <Description> */ + /* This function is used to load, scale, and automatically hint a */ + /* glyph from a given face. */ + /* */ + /* <Input> */ + /* face :: A handle to the face. */ + /* */ + /* glyph_index :: The glyph index. */ + /* */ + /* load_flags :: The load flags. */ + /* */ + /* <Note> */ + /* This function is capable of loading composite glyphs by hinting */ + /* each sub-glyph independently (which improves quality). */ + /* */ + /* It will call the font driver with FT_Load_Glyph(), with */ + /* FT_LOAD_NO_SCALE set. */ + /* */ + typedef FT_Error + (*FT_AutoHinter_GlyphLoadFunc)( FT_AutoHinter hinter, + FT_GlyphSlot slot, + FT_Size size, + FT_UInt glyph_index, + FT_Int32 load_flags ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_AutoHinter_ServiceRec */ + /* */ + /* <Description> */ + /* The auto-hinter module's interface. */ + /* */ + typedef struct FT_AutoHinter_ServiceRec_ + { + FT_AutoHinter_GlobalResetFunc reset_face; + FT_AutoHinter_GlobalGetFunc get_global_hints; + FT_AutoHinter_GlobalDoneFunc done_global_hints; + FT_AutoHinter_GlyphLoadFunc load_glyph; + + } FT_AutoHinter_ServiceRec, *FT_AutoHinter_Service; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \ + done_global_hints_, load_glyph_) \ + FT_CALLBACK_TABLE_DEF \ + const FT_AutoHinter_ServiceRec class_ = \ + { \ + reset_face_, get_global_hints_, done_global_hints_, load_glyph_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \ + done_global_hints_, load_glyph_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_AutoHinter_ServiceRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->reset_face = reset_face_; \ + clazz->get_global_hints = get_global_hints_; \ + clazz->done_global_hints = done_global_hints_; \ + clazz->load_glyph = load_glyph_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + +FT_END_HEADER + +#endif /* __AUTOHINT_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftcalc.h b/other/freetype/include/freetype/internal/ftcalc.h new file mode 100644 index 0000000..f8b4324 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftcalc.h @@ -0,0 +1,179 @@ +/***************************************************************************/ +/* */ +/* ftcalc.h */ +/* */ +/* Arithmetic computations (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTCALC_H__ +#define __FTCALC_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_FixedSqrt */ + /* */ + /* <Description> */ + /* Computes the square root of a 16.16 fixed point value. */ + /* */ + /* <Input> */ + /* x :: The value to compute the root for. */ + /* */ + /* <Return> */ + /* The result of `sqrt(x)'. */ + /* */ + /* <Note> */ + /* This function is not very fast. */ + /* */ + FT_BASE( FT_Int32 ) + FT_SqrtFixed( FT_Int32 x ); + + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Sqrt32 */ + /* */ + /* <Description> */ + /* Computes the square root of an Int32 integer (which will be */ + /* handled as an unsigned long value). */ + /* */ + /* <Input> */ + /* x :: The value to compute the root for. */ + /* */ + /* <Return> */ + /* The result of `sqrt(x)'. */ + /* */ + FT_EXPORT( FT_Int32 ) + FT_Sqrt32( FT_Int32 x ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /*************************************************************************/ + /* */ + /* FT_MulDiv() and FT_MulFix() are declared in freetype.h. */ + /* */ + /*************************************************************************/ + + +#ifdef TT_USE_BYTECODE_INTERPRETER + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_MulDiv_No_Round */ + /* */ + /* <Description> */ + /* A very simple function used to perform the computation `(a*b)/c' */ + /* (without rounding) with maximal accuracy (it uses a 64-bit */ + /* intermediate integer whenever necessary). */ + /* */ + /* This function isn't necessarily as fast as some processor specific */ + /* operations, but is at least completely portable. */ + /* */ + /* <Input> */ + /* a :: The first multiplier. */ + /* b :: The second multiplier. */ + /* c :: The divisor. */ + /* */ + /* <Return> */ + /* The result of `(a*b)/c'. This function never traps when trying to */ + /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ + /* on the signs of `a' and `b'. */ + /* */ + FT_BASE( FT_Long ) + FT_MulDiv_No_Round( FT_Long a, + FT_Long b, + FT_Long c ); + +#endif /* TT_USE_BYTECODE_INTERPRETER */ + + + /* + * A variant of FT_Matrix_Multiply which scales its result afterwards. + * The idea is that both `a' and `b' are scaled by factors of 10 so that + * the values are as precise as possible to get a correct result during + * the 64bit multiplication. Let `sa' and `sb' be the scaling factors of + * `a' and `b', respectively, then the scaling factor of the result is + * `sa*sb'. + */ + FT_BASE( void ) + FT_Matrix_Multiply_Scaled( const FT_Matrix* a, + FT_Matrix *b, + FT_Long scaling ); + + + /* + * A variant of FT_Vector_Transform. See comments for + * FT_Matrix_Multiply_Scaled. + */ + + FT_BASE( void ) + FT_Vector_Transform_Scaled( FT_Vector* vector, + const FT_Matrix* matrix, + FT_Long scaling ); + + + /* + * Return -1, 0, or +1, depending on the orientation of a given corner. + * We use the Cartesian coordinate system, with positive vertical values + * going upwards. The function returns +1 if the corner turns to the + * left, -1 to the right, and 0 for undecidable cases. + */ + FT_BASE( FT_Int ) + ft_corner_orientation( FT_Pos in_x, + FT_Pos in_y, + FT_Pos out_x, + FT_Pos out_y ); + + /* + * Return TRUE if a corner is flat or nearly flat. This is equivalent to + * saying that the angle difference between the `in' and `out' vectors is + * very small. + */ + FT_BASE( FT_Int ) + ft_corner_is_flat( FT_Pos in_x, + FT_Pos in_y, + FT_Pos out_x, + FT_Pos out_y ); + + +#define INT_TO_F26DOT6( x ) ( (FT_Long)(x) << 6 ) +#define INT_TO_F2DOT14( x ) ( (FT_Long)(x) << 14 ) +#define INT_TO_FIXED( x ) ( (FT_Long)(x) << 16 ) +#define F2DOT14_TO_FIXED( x ) ( (FT_Long)(x) << 2 ) +#define FLOAT_TO_FIXED( x ) ( (FT_Long)( x * 65536.0 ) ) +#define FIXED_TO_INT( x ) ( FT_RoundFix( x ) >> 16 ) + +#define ROUND_F26DOT6( x ) ( x >= 0 ? ( ( (x) + 32 ) & -64 ) \ + : ( -( ( 32 - (x) ) & -64 ) ) ) + + +FT_END_HEADER + +#endif /* __FTCALC_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftdebug.h b/other/freetype/include/freetype/internal/ftdebug.h new file mode 100644 index 0000000..7baae35 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftdebug.h @@ -0,0 +1,250 @@ +/***************************************************************************/ +/* */ +/* ftdebug.h */ +/* */ +/* Debugging and logging component (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/* */ +/* IMPORTANT: A description of FreeType's debugging support can be */ +/* found in `docs/DEBUG.TXT'. Read it if you need to use or */ +/* understand this code. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTDEBUG_H__ +#define __FTDEBUG_H__ + + +#include <ft2build.h> +#include FT_CONFIG_CONFIG_H +#include FT_FREETYPE_H + + +FT_BEGIN_HEADER + + + /* force the definition of FT_DEBUG_LEVEL_ERROR if FT_DEBUG_LEVEL_TRACE */ + /* is already defined; this simplifies the following #ifdefs */ + /* */ +#ifdef FT_DEBUG_LEVEL_TRACE +#undef FT_DEBUG_LEVEL_ERROR +#define FT_DEBUG_LEVEL_ERROR +#endif + + + /*************************************************************************/ + /* */ + /* Define the trace enums as well as the trace levels array when they */ + /* are needed. */ + /* */ + /*************************************************************************/ + +#ifdef FT_DEBUG_LEVEL_TRACE + +#define FT_TRACE_DEF( x ) trace_ ## x , + + /* defining the enumeration */ + typedef enum FT_Trace_ + { +#include FT_INTERNAL_TRACE_H + trace_count + + } FT_Trace; + + + /* defining the array of trace levels, provided by `src/base/ftdebug.c' */ + extern int ft_trace_levels[trace_count]; + +#undef FT_TRACE_DEF + +#endif /* FT_DEBUG_LEVEL_TRACE */ + + + /*************************************************************************/ + /* */ + /* Define the FT_TRACE macro */ + /* */ + /* IMPORTANT! */ + /* */ + /* Each component must define the macro FT_COMPONENT to a valid FT_Trace */ + /* value before using any TRACE macro. */ + /* */ + /*************************************************************************/ + +#ifdef FT_DEBUG_LEVEL_TRACE + +#define FT_TRACE( level, varformat ) \ + do \ + { \ + if ( ft_trace_levels[FT_COMPONENT] >= level ) \ + FT_Message varformat; \ + } while ( 0 ) + +#else /* !FT_DEBUG_LEVEL_TRACE */ + +#define FT_TRACE( level, varformat ) do { } while ( 0 ) /* nothing */ + +#endif /* !FT_DEBUG_LEVEL_TRACE */ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Trace_Get_Count */ + /* */ + /* <Description> */ + /* Return the number of available trace components. */ + /* */ + /* <Return> */ + /* The number of trace components. 0 if FreeType 2 is not built with */ + /* FT_DEBUG_LEVEL_TRACE definition. */ + /* */ + /* <Note> */ + /* This function may be useful if you want to access elements of */ + /* the internal `ft_trace_levels' array by an index. */ + /* */ + FT_BASE( FT_Int ) + FT_Trace_Get_Count( void ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Trace_Get_Name */ + /* */ + /* <Description> */ + /* Return the name of a trace component. */ + /* */ + /* <Input> */ + /* The index of the trace component. */ + /* */ + /* <Return> */ + /* The name of the trace component. This is a statically allocated */ + /* C string, so do not free it after use. NULL if FreeType 2 is not */ + /* built with FT_DEBUG_LEVEL_TRACE definition. */ + /* */ + /* <Note> */ + /* Use @FT_Trace_Get_Count to get the number of available trace */ + /* components. */ + /* */ + /* This function may be useful if you want to control FreeType 2's */ + /* debug level in your application. */ + /* */ + FT_BASE( const char * ) + FT_Trace_Get_Name( FT_Int idx ); + + + /*************************************************************************/ + /* */ + /* You need two opening and closing parentheses! */ + /* */ + /* Example: FT_TRACE0(( "Value is %i", foo )) */ + /* */ + /* Output of the FT_TRACEX macros is sent to stderr. */ + /* */ + /*************************************************************************/ + +#define FT_TRACE0( varformat ) FT_TRACE( 0, varformat ) +#define FT_TRACE1( varformat ) FT_TRACE( 1, varformat ) +#define FT_TRACE2( varformat ) FT_TRACE( 2, varformat ) +#define FT_TRACE3( varformat ) FT_TRACE( 3, varformat ) +#define FT_TRACE4( varformat ) FT_TRACE( 4, varformat ) +#define FT_TRACE5( varformat ) FT_TRACE( 5, varformat ) +#define FT_TRACE6( varformat ) FT_TRACE( 6, varformat ) +#define FT_TRACE7( varformat ) FT_TRACE( 7, varformat ) + + + /*************************************************************************/ + /* */ + /* Define the FT_ERROR macro. */ + /* */ + /* Output of this macro is sent to stderr. */ + /* */ + /*************************************************************************/ + +#ifdef FT_DEBUG_LEVEL_ERROR + +#define FT_ERROR( varformat ) FT_Message varformat + +#else /* !FT_DEBUG_LEVEL_ERROR */ + +#define FT_ERROR( varformat ) do { } while ( 0 ) /* nothing */ + +#endif /* !FT_DEBUG_LEVEL_ERROR */ + + + /*************************************************************************/ + /* */ + /* Define the FT_ASSERT macro. */ + /* */ + /*************************************************************************/ + +#ifdef FT_DEBUG_LEVEL_ERROR + +#define FT_ASSERT( condition ) \ + do \ + { \ + if ( !( condition ) ) \ + FT_Panic( "assertion failed on line %d of file %s\n", \ + __LINE__, __FILE__ ); \ + } while ( 0 ) + +#else /* !FT_DEBUG_LEVEL_ERROR */ + +#define FT_ASSERT( condition ) do { } while ( 0 ) + +#endif /* !FT_DEBUG_LEVEL_ERROR */ + + + /*************************************************************************/ + /* */ + /* Define `FT_Message' and `FT_Panic' when needed. */ + /* */ + /*************************************************************************/ + +#ifdef FT_DEBUG_LEVEL_ERROR + +#include "stdio.h" /* for vfprintf() */ + + /* print a message */ + FT_BASE( void ) + FT_Message( const char* fmt, + ... ); + + /* print a message and exit */ + FT_BASE( void ) + FT_Panic( const char* fmt, + ... ); + +#endif /* FT_DEBUG_LEVEL_ERROR */ + + + FT_BASE( void ) + ft_debug_init( void ); + + +#if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ + + /* We disable the warning `conditional expression is constant' here */ + /* in order to compile cleanly with the maximum level of warnings. */ +#pragma warning( disable : 4127 ) + +#endif /* _MSC_VER */ + + +FT_END_HEADER + +#endif /* __FTDEBUG_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftdriver.h b/other/freetype/include/freetype/internal/ftdriver.h new file mode 100644 index 0000000..1d06997 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftdriver.h @@ -0,0 +1,422 @@ +/***************************************************************************/ +/* */ +/* ftdriver.h */ +/* */ +/* FreeType font driver interface (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2006, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTDRIVER_H__ +#define __FTDRIVER_H__ + + +#include <ft2build.h> +#include FT_MODULE_H + + +FT_BEGIN_HEADER + + + typedef FT_Error + (*FT_Face_InitFunc)( FT_Stream stream, + FT_Face face, + FT_Int typeface_index, + FT_Int num_params, + FT_Parameter* parameters ); + + typedef void + (*FT_Face_DoneFunc)( FT_Face face ); + + + typedef FT_Error + (*FT_Size_InitFunc)( FT_Size size ); + + typedef void + (*FT_Size_DoneFunc)( FT_Size size ); + + + typedef FT_Error + (*FT_Slot_InitFunc)( FT_GlyphSlot slot ); + + typedef void + (*FT_Slot_DoneFunc)( FT_GlyphSlot slot ); + + + typedef FT_Error + (*FT_Size_RequestFunc)( FT_Size size, + FT_Size_Request req ); + + typedef FT_Error + (*FT_Size_SelectFunc)( FT_Size size, + FT_ULong size_index ); + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + typedef FT_Error + (*FT_Size_ResetPointsFunc)( FT_Size size, + FT_F26Dot6 char_width, + FT_F26Dot6 char_height, + FT_UInt horz_resolution, + FT_UInt vert_resolution ); + + typedef FT_Error + (*FT_Size_ResetPixelsFunc)( FT_Size size, + FT_UInt pixel_width, + FT_UInt pixel_height ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + typedef FT_Error + (*FT_Slot_LoadFunc)( FT_GlyphSlot slot, + FT_Size size, + FT_UInt glyph_index, + FT_Int32 load_flags ); + + + typedef FT_UInt + (*FT_CharMap_CharIndexFunc)( FT_CharMap charmap, + FT_Long charcode ); + + typedef FT_Long + (*FT_CharMap_CharNextFunc)( FT_CharMap charmap, + FT_Long charcode ); + + + typedef FT_Error + (*FT_Face_GetKerningFunc)( FT_Face face, + FT_UInt left_glyph, + FT_UInt right_glyph, + FT_Vector* kerning ); + + + typedef FT_Error + (*FT_Face_AttachFunc)( FT_Face face, + FT_Stream stream ); + + + typedef FT_Error + (*FT_Face_GetAdvancesFunc)( FT_Face face, + FT_UInt first, + FT_UInt count, + FT_Int32 flags, + FT_Fixed* advances ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Driver_ClassRec */ + /* */ + /* <Description> */ + /* The font driver class. This structure mostly contains pointers to */ + /* driver methods. */ + /* */ + /* <Fields> */ + /* root :: The parent module. */ + /* */ + /* face_object_size :: The size of a face object in bytes. */ + /* */ + /* size_object_size :: The size of a size object in bytes. */ + /* */ + /* slot_object_size :: The size of a glyph object in bytes. */ + /* */ + /* init_face :: The format-specific face constructor. */ + /* */ + /* done_face :: The format-specific face destructor. */ + /* */ + /* init_size :: The format-specific size constructor. */ + /* */ + /* done_size :: The format-specific size destructor. */ + /* */ + /* init_slot :: The format-specific slot constructor. */ + /* */ + /* done_slot :: The format-specific slot destructor. */ + /* */ + /* */ + /* load_glyph :: A function handle to load a glyph to a slot. */ + /* This field is mandatory! */ + /* */ + /* get_kerning :: A function handle to return the unscaled */ + /* kerning for a given pair of glyphs. Can be */ + /* set to 0 if the format doesn't support */ + /* kerning. */ + /* */ + /* attach_file :: This function handle is used to read */ + /* additional data for a face from another */ + /* file/stream. For example, this can be used to */ + /* add data from AFM or PFM files on a Type 1 */ + /* face, or a CIDMap on a CID-keyed face. */ + /* */ + /* get_advances :: A function handle used to return advance */ + /* widths of `count' glyphs (in font units), */ + /* starting at `first'. The `vertical' flag must */ + /* be set to get vertical advance heights. The */ + /* `advances' buffer is caller-allocated. */ + /* Currently not implemented. The idea of this */ + /* function is to be able to perform */ + /* device-independent text layout without loading */ + /* a single glyph image. */ + /* */ + /* request_size :: A handle to a function used to request the new */ + /* character size. Can be set to 0 if the */ + /* scaling done in the base layer suffices. */ + /* */ + /* select_size :: A handle to a function used to select a new */ + /* fixed size. It is used only if */ + /* @FT_FACE_FLAG_FIXED_SIZES is set. Can be set */ + /* to 0 if the scaling done in the base layer */ + /* suffices. */ + /* <Note> */ + /* Most function pointers, with the exception of `load_glyph', can be */ + /* set to 0 to indicate a default behaviour. */ + /* */ + typedef struct FT_Driver_ClassRec_ + { + FT_Module_Class root; + + FT_Long face_object_size; + FT_Long size_object_size; + FT_Long slot_object_size; + + FT_Face_InitFunc init_face; + FT_Face_DoneFunc done_face; + + FT_Size_InitFunc init_size; + FT_Size_DoneFunc done_size; + + FT_Slot_InitFunc init_slot; + FT_Slot_DoneFunc done_slot; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + FT_Size_ResetPointsFunc set_char_sizes; + FT_Size_ResetPixelsFunc set_pixel_sizes; + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + FT_Slot_LoadFunc load_glyph; + + FT_Face_GetKerningFunc get_kerning; + FT_Face_AttachFunc attach_file; + FT_Face_GetAdvancesFunc get_advances; + + /* since version 2.2 */ + FT_Size_RequestFunc request_size; + FT_Size_SelectFunc select_size; + + } FT_Driver_ClassRec, *FT_Driver_Class; + + + /* + * The following functions are used as stubs for `set_char_sizes' and + * `set_pixel_sizes'; the code uses `request_size' and `select_size' + * functions instead. + * + * Implementation is in `src/base/ftobjs.c'. + */ +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + FT_BASE( FT_Error ) + ft_stub_set_char_sizes( FT_Size size, + FT_F26Dot6 width, + FT_F26Dot6 height, + FT_UInt horz_res, + FT_UInt vert_res ); + + FT_BASE( FT_Error ) + ft_stub_set_pixel_sizes( FT_Size size, + FT_UInt width, + FT_UInt height ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DECLARE_DRIVER */ + /* */ + /* <Description> */ + /* Used to create a forward declaration of a */ + /* FT_Driver_ClassRec stract instance. */ + /* */ + /* <Macro> */ + /* FT_DEFINE_DRIVER */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Driver_ClassRec struct. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ + /* to called with a pointer where the allocated stracture is returned.*/ + /* And when it is no longer needed a Destroy function needs */ + /* to be called to release that allocation. */ + /* fcinit.c (ft_create_default_module_classes) already contains */ + /* a mechanism to call these functions for the default modules */ + /* described in ftmodule.h */ + /* */ + /* Notice that the created Create and Destroy functions call */ + /* pic_init and pic_free function to allow you to manually allocate */ + /* and initialize any additional global data, like module specific */ + /* interface, and put them in the global pic container defined in */ + /* ftpic.h. if you don't need them just implement the functions as */ + /* empty to resolve the link error. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS +#define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \ + a_, b_, +#else + #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) +#endif + +#define FT_DECLARE_DRIVER(class_) \ + FT_CALLBACK_TABLE \ + const FT_Driver_ClassRec class_; + +#define FT_DEFINE_DRIVER(class_, \ + flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_, \ + face_object_size_, size_object_size_, \ + slot_object_size_, init_face_, done_face_, \ + init_size_, done_size_, init_slot_, done_slot_, \ + old_set_char_sizes_, old_set_pixel_sizes_, \ + load_glyph_, get_kerning_, attach_file_, \ + get_advances_, request_size_, select_size_ ) \ + FT_CALLBACK_TABLE_DEF \ + const FT_Driver_ClassRec class_ = \ + { \ + FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_, \ + init_,done_,get_interface_) \ + \ + face_object_size_, \ + size_object_size_, \ + slot_object_size_, \ + \ + init_face_, \ + done_face_, \ + \ + init_size_, \ + done_size_, \ + \ + init_slot_, \ + done_slot_, \ + \ + FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \ + \ + load_glyph_, \ + \ + get_kerning_, \ + attach_file_, \ + get_advances_, \ + \ + request_size_, \ + select_size_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS +#define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \ + clazz->set_char_sizes = a_; \ + clazz->set_pixel_sizes = b_; +#else + #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) +#endif + +#define FT_DECLARE_DRIVER(class_) FT_DECLARE_MODULE(class_) + +#define FT_DEFINE_DRIVER(class_, \ + flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_, \ + face_object_size_, size_object_size_, \ + slot_object_size_, init_face_, done_face_, \ + init_size_, done_size_, init_slot_, done_slot_, \ + old_set_char_sizes_, old_set_pixel_sizes_, \ + load_glyph_, get_kerning_, attach_file_, \ + get_advances_, request_size_, select_size_ ) \ + void class_##_pic_free( FT_Library library ); \ + FT_Error class_##_pic_init( FT_Library library ); \ + \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_Module_Class* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + FT_Driver_Class dclazz = (FT_Driver_Class)clazz; \ + class_##_pic_free( library ); \ + if ( dclazz ) \ + FT_FREE( dclazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_Module_Class** output_class ) \ + { \ + FT_Driver_Class clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ + return error; \ + \ + error = class_##_pic_init( library ); \ + if(error) \ + { \ + FT_FREE( clazz ); \ + return error; \ + } \ + \ + FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_, \ + init_,done_,get_interface_) \ + \ + clazz->face_object_size = face_object_size_; \ + clazz->size_object_size = size_object_size_; \ + clazz->slot_object_size = slot_object_size_; \ + \ + clazz->init_face = init_face_; \ + clazz->done_face = done_face_; \ + \ + clazz->init_size = init_size_; \ + clazz->done_size = done_size_; \ + \ + clazz->init_slot = init_slot_; \ + clazz->done_slot = done_slot_; \ + \ + FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \ + \ + clazz->load_glyph = load_glyph_; \ + \ + clazz->get_kerning = get_kerning_; \ + clazz->attach_file = attach_file_; \ + clazz->get_advances = get_advances_; \ + \ + clazz->request_size = request_size_; \ + clazz->select_size = select_size_; \ + \ + *output_class = (FT_Module_Class*)clazz; \ + return FT_Err_Ok; \ + } + + +#endif /* FT_CONFIG_OPTION_PIC */ + +FT_END_HEADER + +#endif /* __FTDRIVER_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftgloadr.h b/other/freetype/include/freetype/internal/ftgloadr.h new file mode 100644 index 0000000..ce4dc6c --- /dev/null +++ b/other/freetype/include/freetype/internal/ftgloadr.h @@ -0,0 +1,168 @@ +/***************************************************************************/ +/* */ +/* ftgloadr.h */ +/* */ +/* The FreeType glyph loader (specification). */ +/* */ +/* Copyright 2002, 2003, 2005, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTGLOADR_H__ +#define __FTGLOADR_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_GlyphLoader */ + /* */ + /* <Description> */ + /* The glyph loader is an internal object used to load several glyphs */ + /* together (for example, in the case of composites). */ + /* */ + /* <Note> */ + /* The glyph loader implementation is not part of the high-level API, */ + /* hence the forward structure declaration. */ + /* */ + typedef struct FT_GlyphLoaderRec_* FT_GlyphLoader ; + + +#if 0 /* moved to freetype.h in version 2.2 */ +#define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS 1 +#define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES 2 +#define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID 4 +#define FT_SUBGLYPH_FLAG_SCALE 8 +#define FT_SUBGLYPH_FLAG_XY_SCALE 0x40 +#define FT_SUBGLYPH_FLAG_2X2 0x80 +#define FT_SUBGLYPH_FLAG_USE_MY_METRICS 0x200 +#endif + + + typedef struct FT_SubGlyphRec_ + { + FT_Int index; + FT_UShort flags; + FT_Int arg1; + FT_Int arg2; + FT_Matrix transform; + + } FT_SubGlyphRec; + + + typedef struct FT_GlyphLoadRec_ + { + FT_Outline outline; /* outline */ + FT_Vector* extra_points; /* extra points table */ + FT_Vector* extra_points2; /* second extra points table */ + FT_UInt num_subglyphs; /* number of subglyphs */ + FT_SubGlyph subglyphs; /* subglyphs */ + + } FT_GlyphLoadRec, *FT_GlyphLoad; + + + typedef struct FT_GlyphLoaderRec_ + { + FT_Memory memory; + FT_UInt max_points; + FT_UInt max_contours; + FT_UInt max_subglyphs; + FT_Bool use_extra; + + FT_GlyphLoadRec base; + FT_GlyphLoadRec current; + + void* other; /* for possible future extension? */ + + } FT_GlyphLoaderRec; + + + /* create new empty glyph loader */ + FT_BASE( FT_Error ) + FT_GlyphLoader_New( FT_Memory memory, + FT_GlyphLoader *aloader ); + + /* add an extra points table to a glyph loader */ + FT_BASE( FT_Error ) + FT_GlyphLoader_CreateExtra( FT_GlyphLoader loader ); + + /* destroy a glyph loader */ + FT_BASE( void ) + FT_GlyphLoader_Done( FT_GlyphLoader loader ); + + /* reset a glyph loader (frees everything int it) */ + FT_BASE( void ) + FT_GlyphLoader_Reset( FT_GlyphLoader loader ); + + /* rewind a glyph loader */ + FT_BASE( void ) + FT_GlyphLoader_Rewind( FT_GlyphLoader loader ); + + /* check that there is enough space to add `n_points' and `n_contours' */ + /* to the glyph loader */ + FT_BASE( FT_Error ) + FT_GlyphLoader_CheckPoints( FT_GlyphLoader loader, + FT_UInt n_points, + FT_UInt n_contours ); + + +#define FT_GLYPHLOADER_CHECK_P( _loader, _count ) \ + ( (_count) == 0 || ((_loader)->base.outline.n_points + \ + (_loader)->current.outline.n_points + \ + (unsigned long)(_count)) <= (_loader)->max_points ) + +#define FT_GLYPHLOADER_CHECK_C( _loader, _count ) \ + ( (_count) == 0 || ((_loader)->base.outline.n_contours + \ + (_loader)->current.outline.n_contours + \ + (unsigned long)(_count)) <= (_loader)->max_contours ) + +#define FT_GLYPHLOADER_CHECK_POINTS( _loader, _points,_contours ) \ + ( ( FT_GLYPHLOADER_CHECK_P( _loader, _points ) && \ + FT_GLYPHLOADER_CHECK_C( _loader, _contours ) ) \ + ? 0 \ + : FT_GlyphLoader_CheckPoints( (_loader), (_points), (_contours) ) ) + + + /* check that there is enough space to add `n_subs' sub-glyphs to */ + /* a glyph loader */ + FT_BASE( FT_Error ) + FT_GlyphLoader_CheckSubGlyphs( FT_GlyphLoader loader, + FT_UInt n_subs ); + + /* prepare a glyph loader, i.e. empty the current glyph */ + FT_BASE( void ) + FT_GlyphLoader_Prepare( FT_GlyphLoader loader ); + + /* add the current glyph to the base glyph */ + FT_BASE( void ) + FT_GlyphLoader_Add( FT_GlyphLoader loader ); + + /* copy points from one glyph loader to another */ + FT_BASE( FT_Error ) + FT_GlyphLoader_CopyPoints( FT_GlyphLoader target, + FT_GlyphLoader source ); + + /* */ + + +FT_END_HEADER + +#endif /* __FTGLOADR_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftmemory.h b/other/freetype/include/freetype/internal/ftmemory.h new file mode 100644 index 0000000..026aa63 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftmemory.h @@ -0,0 +1,380 @@ +/***************************************************************************/ +/* */ +/* ftmemory.h */ +/* */ +/* The FreeType memory management macros (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTMEMORY_H__ +#define __FTMEMORY_H__ + + +#include <ft2build.h> +#include FT_CONFIG_CONFIG_H +#include FT_TYPES_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_SET_ERROR */ + /* */ + /* <Description> */ + /* This macro is used to set an implicit `error' variable to a given */ + /* expression's value (usually a function call), and convert it to a */ + /* boolean which is set whenever the value is != 0. */ + /* */ +#undef FT_SET_ERROR +#define FT_SET_ERROR( expression ) \ + ( ( error = (expression) ) != 0 ) + + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** M E M O R Y ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /* + * C++ refuses to handle statements like p = (void*)anything, with `p' a + * typed pointer. Since we don't have a `typeof' operator in standard + * C++, we have to use a template to emulate it. + */ + +#ifdef __cplusplus + + extern "C++" + template <typename T> inline T* + cplusplus_typeof( T*, + void *v ) + { + return static_cast <T*> ( v ); + } + +#define FT_ASSIGNP( p, val ) (p) = cplusplus_typeof( (p), (val) ) + +#else + +#define FT_ASSIGNP( p, val ) (p) = (val) + +#endif + + + +#ifdef FT_DEBUG_MEMORY + + FT_BASE( const char* ) _ft_debug_file; + FT_BASE( long ) _ft_debug_lineno; + +#define FT_DEBUG_INNER( exp ) ( _ft_debug_file = __FILE__, \ + _ft_debug_lineno = __LINE__, \ + (exp) ) + +#define FT_ASSIGNP_INNER( p, exp ) ( _ft_debug_file = __FILE__, \ + _ft_debug_lineno = __LINE__, \ + FT_ASSIGNP( p, exp ) ) + +#else /* !FT_DEBUG_MEMORY */ + +#define FT_DEBUG_INNER( exp ) (exp) +#define FT_ASSIGNP_INNER( p, exp ) FT_ASSIGNP( p, exp ) + +#endif /* !FT_DEBUG_MEMORY */ + + + /* + * The allocation functions return a pointer, and the error code + * is written to through the `p_error' parameter. See below for + * for documentation. + */ + + FT_BASE( FT_Pointer ) + ft_mem_alloc( FT_Memory memory, + FT_Long size, + FT_Error *p_error ); + + FT_BASE( FT_Pointer ) + ft_mem_qalloc( FT_Memory memory, + FT_Long size, + FT_Error *p_error ); + + FT_BASE( FT_Pointer ) + ft_mem_realloc( FT_Memory memory, + FT_Long item_size, + FT_Long cur_count, + FT_Long new_count, + void* block, + FT_Error *p_error ); + + FT_BASE( FT_Pointer ) + ft_mem_qrealloc( FT_Memory memory, + FT_Long item_size, + FT_Long cur_count, + FT_Long new_count, + void* block, + FT_Error *p_error ); + + FT_BASE( void ) + ft_mem_free( FT_Memory memory, + const void* P ); + + +#define FT_MEM_ALLOC( ptr, size ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_alloc( memory, (size), &error ) ) + +#define FT_MEM_FREE( ptr ) \ + FT_BEGIN_STMNT \ + ft_mem_free( memory, (ptr) ); \ + (ptr) = NULL; \ + FT_END_STMNT + +#define FT_MEM_NEW( ptr ) \ + FT_MEM_ALLOC( ptr, sizeof ( *(ptr) ) ) + +#define FT_MEM_REALLOC( ptr, cursz, newsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, 1, \ + (cursz), (newsz), \ + (ptr), &error ) ) + +#define FT_MEM_QALLOC( ptr, size ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qalloc( memory, (size), &error ) ) + +#define FT_MEM_QNEW( ptr ) \ + FT_MEM_QALLOC( ptr, sizeof ( *(ptr) ) ) + +#define FT_MEM_QREALLOC( ptr, cursz, newsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, 1, \ + (cursz), (newsz), \ + (ptr), &error ) ) + +#define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ + (cursz), (newsz), \ + (ptr), &error ) ) + +#define FT_MEM_ALLOC_MULT( ptr, count, item_size ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (item_size), \ + 0, (count), \ + NULL, &error ) ) + +#define FT_MEM_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (itmsz), \ + (oldcnt), (newcnt), \ + (ptr), &error ) ) + +#define FT_MEM_QALLOC_MULT( ptr, count, item_size ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (item_size), \ + 0, (count), \ + NULL, &error ) ) + +#define FT_MEM_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (itmsz), \ + (oldcnt), (newcnt), \ + (ptr), &error ) ) + + +#define FT_MEM_SET_ERROR( cond ) ( (cond), error != 0 ) + + +#define FT_MEM_SET( dest, byte, count ) ft_memset( dest, byte, count ) + +#define FT_MEM_COPY( dest, source, count ) ft_memcpy( dest, source, count ) + +#define FT_MEM_MOVE( dest, source, count ) ft_memmove( dest, source, count ) + + +#define FT_MEM_ZERO( dest, count ) FT_MEM_SET( dest, 0, count ) + +#define FT_ZERO( p ) FT_MEM_ZERO( p, sizeof ( *(p) ) ) + + +#define FT_ARRAY_ZERO( dest, count ) \ + FT_MEM_ZERO( dest, (count) * sizeof ( *(dest) ) ) + +#define FT_ARRAY_COPY( dest, source, count ) \ + FT_MEM_COPY( dest, source, (count) * sizeof ( *(dest) ) ) + +#define FT_ARRAY_MOVE( dest, source, count ) \ + FT_MEM_MOVE( dest, source, (count) * sizeof ( *(dest) ) ) + + + /* + * Return the maximum number of addressable elements in an array. + * We limit ourselves to INT_MAX, rather than UINT_MAX, to avoid + * any problems. + */ +#define FT_ARRAY_MAX( ptr ) ( FT_INT_MAX / sizeof ( *(ptr) ) ) + +#define FT_ARRAY_CHECK( ptr, count ) ( (count) <= FT_ARRAY_MAX( ptr ) ) + + + /*************************************************************************/ + /* */ + /* The following functions macros expect that their pointer argument is */ + /* _typed_ in order to automatically compute array element sizes. */ + /* */ + +#define FT_MEM_NEW_ARRAY( ptr, count ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \ + 0, (count), \ + NULL, &error ) ) + +#define FT_MEM_RENEW_ARRAY( ptr, cursz, newsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \ + (cursz), (newsz), \ + (ptr), &error ) ) + +#define FT_MEM_QNEW_ARRAY( ptr, count ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ + 0, (count), \ + NULL, &error ) ) + +#define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz ) \ + FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ + (cursz), (newsz), \ + (ptr), &error ) ) + + +#define FT_ALLOC( ptr, size ) \ + FT_MEM_SET_ERROR( FT_MEM_ALLOC( ptr, size ) ) + +#define FT_REALLOC( ptr, cursz, newsz ) \ + FT_MEM_SET_ERROR( FT_MEM_REALLOC( ptr, cursz, newsz ) ) + +#define FT_ALLOC_MULT( ptr, count, item_size ) \ + FT_MEM_SET_ERROR( FT_MEM_ALLOC_MULT( ptr, count, item_size ) ) + +#define FT_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ + FT_MEM_SET_ERROR( FT_MEM_REALLOC_MULT( ptr, oldcnt, \ + newcnt, itmsz ) ) + +#define FT_QALLOC( ptr, size ) \ + FT_MEM_SET_ERROR( FT_MEM_QALLOC( ptr, size ) ) + +#define FT_QREALLOC( ptr, cursz, newsz ) \ + FT_MEM_SET_ERROR( FT_MEM_QREALLOC( ptr, cursz, newsz ) ) + +#define FT_QALLOC_MULT( ptr, count, item_size ) \ + FT_MEM_SET_ERROR( FT_MEM_QALLOC_MULT( ptr, count, item_size ) ) + +#define FT_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ + FT_MEM_SET_ERROR( FT_MEM_QREALLOC_MULT( ptr, oldcnt, \ + newcnt, itmsz ) ) + +#define FT_FREE( ptr ) FT_MEM_FREE( ptr ) + +#define FT_NEW( ptr ) FT_MEM_SET_ERROR( FT_MEM_NEW( ptr ) ) + +#define FT_NEW_ARRAY( ptr, count ) \ + FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) ) + +#define FT_RENEW_ARRAY( ptr, curcnt, newcnt ) \ + FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) ) + +#define FT_QNEW( ptr ) \ + FT_MEM_SET_ERROR( FT_MEM_QNEW( ptr ) ) + +#define FT_QNEW_ARRAY( ptr, count ) \ + FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) ) + +#define FT_QRENEW_ARRAY( ptr, curcnt, newcnt ) \ + FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) ) + + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + FT_BASE( FT_Error ) + FT_Alloc( FT_Memory memory, + FT_Long size, + void* *P ); + + FT_BASE( FT_Error ) + FT_QAlloc( FT_Memory memory, + FT_Long size, + void* *p ); + + FT_BASE( FT_Error ) + FT_Realloc( FT_Memory memory, + FT_Long current, + FT_Long size, + void* *P ); + + FT_BASE( FT_Error ) + FT_QRealloc( FT_Memory memory, + FT_Long current, + FT_Long size, + void* *p ); + + FT_BASE( void ) + FT_Free( FT_Memory memory, + void* *P ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + FT_BASE( FT_Pointer ) + ft_mem_strdup( FT_Memory memory, + const char* str, + FT_Error *p_error ); + + FT_BASE( FT_Pointer ) + ft_mem_dup( FT_Memory memory, + const void* address, + FT_ULong size, + FT_Error *p_error ); + +#define FT_MEM_STRDUP( dst, str ) \ + (dst) = (char*)ft_mem_strdup( memory, (const char*)(str), &error ) + +#define FT_STRDUP( dst, str ) \ + FT_MEM_SET_ERROR( FT_MEM_STRDUP( dst, str ) ) + +#define FT_MEM_DUP( dst, address, size ) \ + (dst) = ft_mem_dup( memory, (address), (FT_ULong)(size), &error ) + +#define FT_DUP( dst, address, size ) \ + FT_MEM_SET_ERROR( FT_MEM_DUP( dst, address, size ) ) + + + /* Return >= 1 if a truncation occurs. */ + /* Return 0 if the source string fits the buffer. */ + /* This is *not* the same as strlcpy(). */ + FT_BASE( FT_Int ) + ft_mem_strcpyn( char* dst, + const char* src, + FT_ULong size ); + +#define FT_STRCPYN( dst, src, size ) \ + ft_mem_strcpyn( (char*)dst, (const char*)(src), (FT_ULong)(size) ) + + /* */ + + +FT_END_HEADER + +#endif /* __FTMEMORY_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftobjs.h b/other/freetype/include/freetype/internal/ftobjs.h new file mode 100644 index 0000000..670eb78 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftobjs.h @@ -0,0 +1,1428 @@ +/***************************************************************************/ +/* */ +/* ftobjs.h */ +/* */ +/* The FreeType private base classes (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2010 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file contains the definition of all internal FreeType classes. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTOBJS_H__ +#define __FTOBJS_H__ + +#include <ft2build.h> +#include FT_RENDER_H +#include FT_SIZES_H +#include FT_LCD_FILTER_H +#include FT_INTERNAL_MEMORY_H +#include FT_INTERNAL_GLYPH_LOADER_H +#include FT_INTERNAL_DRIVER_H +#include FT_INTERNAL_AUTOHINT_H +#include FT_INTERNAL_SERVICE_H +#include FT_INTERNAL_PIC_H + +#ifdef FT_CONFIG_OPTION_INCREMENTAL +#include FT_INCREMENTAL_H +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* Some generic definitions. */ + /* */ +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef NULL +#define NULL (void*)0 +#endif + + + /*************************************************************************/ + /* */ + /* The min and max functions missing in C. As usual, be careful not to */ + /* write things like FT_MIN( a++, b++ ) to avoid side effects. */ + /* */ +#define FT_MIN( a, b ) ( (a) < (b) ? (a) : (b) ) +#define FT_MAX( a, b ) ( (a) > (b) ? (a) : (b) ) + +#define FT_ABS( a ) ( (a) < 0 ? -(a) : (a) ) + + +#define FT_PAD_FLOOR( x, n ) ( (x) & ~((n)-1) ) +#define FT_PAD_ROUND( x, n ) FT_PAD_FLOOR( (x) + ((n)/2), n ) +#define FT_PAD_CEIL( x, n ) FT_PAD_FLOOR( (x) + ((n)-1), n ) + +#define FT_PIX_FLOOR( x ) ( (x) & ~63 ) +#define FT_PIX_ROUND( x ) FT_PIX_FLOOR( (x) + 32 ) +#define FT_PIX_CEIL( x ) FT_PIX_FLOOR( (x) + 63 ) + + + /* + * Return the highest power of 2 that is <= value; this correspond to + * the highest bit in a given 32-bit value. + */ + FT_BASE( FT_UInt32 ) + ft_highpow2( FT_UInt32 value ); + + + /* + * character classification functions -- since these are used to parse + * font files, we must not use those in <ctypes.h> which are + * locale-dependent + */ +#define ft_isdigit( x ) ( ( (unsigned)(x) - '0' ) < 10U ) + +#define ft_isxdigit( x ) ( ( (unsigned)(x) - '0' ) < 10U || \ + ( (unsigned)(x) - 'a' ) < 6U || \ + ( (unsigned)(x) - 'A' ) < 6U ) + + /* the next two macros assume ASCII representation */ +#define ft_isupper( x ) ( ( (unsigned)(x) - 'A' ) < 26U ) +#define ft_islower( x ) ( ( (unsigned)(x) - 'a' ) < 26U ) + +#define ft_isalpha( x ) ( ft_isupper( x ) || ft_islower( x ) ) +#define ft_isalnum( x ) ( ft_isdigit( x ) || ft_isalpha( x ) ) + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** C H A R M A P S ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /* handle to internal charmap object */ + typedef struct FT_CMapRec_* FT_CMap; + + /* handle to charmap class structure */ + typedef const struct FT_CMap_ClassRec_* FT_CMap_Class; + + /* internal charmap object structure */ + typedef struct FT_CMapRec_ + { + FT_CharMapRec charmap; + FT_CMap_Class clazz; + + } FT_CMapRec; + + /* typecase any pointer to a charmap handle */ +#define FT_CMAP( x ) ((FT_CMap)( x )) + + /* obvious macros */ +#define FT_CMAP_PLATFORM_ID( x ) FT_CMAP( x )->charmap.platform_id +#define FT_CMAP_ENCODING_ID( x ) FT_CMAP( x )->charmap.encoding_id +#define FT_CMAP_ENCODING( x ) FT_CMAP( x )->charmap.encoding +#define FT_CMAP_FACE( x ) FT_CMAP( x )->charmap.face + + + /* class method definitions */ + typedef FT_Error + (*FT_CMap_InitFunc)( FT_CMap cmap, + FT_Pointer init_data ); + + typedef void + (*FT_CMap_DoneFunc)( FT_CMap cmap ); + + typedef FT_UInt + (*FT_CMap_CharIndexFunc)( FT_CMap cmap, + FT_UInt32 char_code ); + + typedef FT_UInt + (*FT_CMap_CharNextFunc)( FT_CMap cmap, + FT_UInt32 *achar_code ); + + typedef FT_UInt + (*FT_CMap_CharVarIndexFunc)( FT_CMap cmap, + FT_CMap unicode_cmap, + FT_UInt32 char_code, + FT_UInt32 variant_selector ); + + typedef FT_Bool + (*FT_CMap_CharVarIsDefaultFunc)( FT_CMap cmap, + FT_UInt32 char_code, + FT_UInt32 variant_selector ); + + typedef FT_UInt32 * + (*FT_CMap_VariantListFunc)( FT_CMap cmap, + FT_Memory mem ); + + typedef FT_UInt32 * + (*FT_CMap_CharVariantListFunc)( FT_CMap cmap, + FT_Memory mem, + FT_UInt32 char_code ); + + typedef FT_UInt32 * + (*FT_CMap_VariantCharListFunc)( FT_CMap cmap, + FT_Memory mem, + FT_UInt32 variant_selector ); + + + typedef struct FT_CMap_ClassRec_ + { + FT_ULong size; + FT_CMap_InitFunc init; + FT_CMap_DoneFunc done; + FT_CMap_CharIndexFunc char_index; + FT_CMap_CharNextFunc char_next; + + /* Subsequent entries are special ones for format 14 -- the variant */ + /* selector subtable which behaves like no other */ + + FT_CMap_CharVarIndexFunc char_var_index; + FT_CMap_CharVarIsDefaultFunc char_var_default; + FT_CMap_VariantListFunc variant_list; + FT_CMap_CharVariantListFunc charvariant_list; + FT_CMap_VariantCharListFunc variantchar_list; + + } FT_CMap_ClassRec; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DECLARE_CMAP_CLASS(class_) \ + FT_CALLBACK_TABLE const FT_CMap_ClassRec class_; + +#define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_, \ + char_next_, char_var_index_, char_var_default_, variant_list_, \ + charvariant_list_, variantchar_list_) \ + FT_CALLBACK_TABLE_DEF \ + const FT_CMap_ClassRec class_ = \ + { \ + size_, init_, done_, char_index_, char_next_, char_var_index_, \ + char_var_default_, variant_list_, charvariant_list_, variantchar_list_ \ + }; +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DECLARE_CMAP_CLASS(class_) \ + void FT_Init_Class_##class_( FT_Library library, FT_CMap_ClassRec* clazz); + +#define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_, \ + char_next_, char_var_index_, char_var_default_, variant_list_, \ + charvariant_list_, variantchar_list_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_CMap_ClassRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->size = size_; \ + clazz->init = init_; \ + clazz->done = done_; \ + clazz->char_index = char_index_; \ + clazz->char_next = char_next_; \ + clazz->char_var_index = char_var_index_; \ + clazz->char_var_default = char_var_default_; \ + clazz->variant_list = variant_list_; \ + clazz->charvariant_list = charvariant_list_; \ + clazz->variantchar_list = variantchar_list_; \ + } +#endif /* FT_CONFIG_OPTION_PIC */ + + /* create a new charmap and add it to charmap->face */ + FT_BASE( FT_Error ) + FT_CMap_New( FT_CMap_Class clazz, + FT_Pointer init_data, + FT_CharMap charmap, + FT_CMap *acmap ); + + /* destroy a charmap and remove it from face's list */ + FT_BASE( void ) + FT_CMap_Done( FT_CMap cmap ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Face_InternalRec */ + /* */ + /* <Description> */ + /* This structure contains the internal fields of each FT_Face */ + /* object. These fields may change between different releases of */ + /* FreeType. */ + /* */ + /* <Fields> */ + /* max_points :: */ + /* The maximal number of points used to store the vectorial outline */ + /* of any glyph in this face. If this value cannot be known in */ + /* advance, or if the face isn't scalable, this should be set to 0. */ + /* Only relevant for scalable formats. */ + /* */ + /* max_contours :: */ + /* The maximal number of contours used to store the vectorial */ + /* outline of any glyph in this face. If this value cannot be */ + /* known in advance, or if the face isn't scalable, this should be */ + /* set to 0. Only relevant for scalable formats. */ + /* */ + /* transform_matrix :: */ + /* A 2x2 matrix of 16.16 coefficients used to transform glyph */ + /* outlines after they are loaded from the font. Only used by the */ + /* convenience functions. */ + /* */ + /* transform_delta :: */ + /* A translation vector used to transform glyph outlines after they */ + /* are loaded from the font. Only used by the convenience */ + /* functions. */ + /* */ + /* transform_flags :: */ + /* Some flags used to classify the transform. Only used by the */ + /* convenience functions. */ + /* */ + /* services :: */ + /* A cache for frequently used services. It should be only */ + /* accessed with the macro `FT_FACE_LOOKUP_SERVICE'. */ + /* */ + /* incremental_interface :: */ + /* If non-null, the interface through which glyph data and metrics */ + /* are loaded incrementally for faces that do not provide all of */ + /* this data when first opened. This field exists only if */ + /* @FT_CONFIG_OPTION_INCREMENTAL is defined. */ + /* */ + /* ignore_unpatented_hinter :: */ + /* This boolean flag instructs the glyph loader to ignore the */ + /* native font hinter, if one is found. This is exclusively used */ + /* in the case when the unpatented hinter is compiled within the */ + /* library. */ + /* */ + /* refcount :: */ + /* A counter initialized to~1 at the time an @FT_Face structure is */ + /* created. @FT_Reference_Face increments this counter, and */ + /* @FT_Done_Face only destroys a face if the counter is~1, */ + /* otherwise it simply decrements it. */ + /* */ + typedef struct FT_Face_InternalRec_ + { +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + FT_UShort reserved1; + FT_Short reserved2; +#endif + FT_Matrix transform_matrix; + FT_Vector transform_delta; + FT_Int transform_flags; + + FT_ServiceCacheRec services; + +#ifdef FT_CONFIG_OPTION_INCREMENTAL + FT_Incremental_InterfaceRec* incremental_interface; +#endif + + FT_Bool ignore_unpatented_hinter; + FT_UInt refcount; + + } FT_Face_InternalRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Slot_InternalRec */ + /* */ + /* <Description> */ + /* This structure contains the internal fields of each FT_GlyphSlot */ + /* object. These fields may change between different releases of */ + /* FreeType. */ + /* */ + /* <Fields> */ + /* loader :: The glyph loader object used to load outlines */ + /* into the glyph slot. */ + /* */ + /* flags :: Possible values are zero or */ + /* FT_GLYPH_OWN_BITMAP. The latter indicates */ + /* that the FT_GlyphSlot structure owns the */ + /* bitmap buffer. */ + /* */ + /* glyph_transformed :: Boolean. Set to TRUE when the loaded glyph */ + /* must be transformed through a specific */ + /* font transformation. This is _not_ the same */ + /* as the face transform set through */ + /* FT_Set_Transform(). */ + /* */ + /* glyph_matrix :: The 2x2 matrix corresponding to the glyph */ + /* transformation, if necessary. */ + /* */ + /* glyph_delta :: The 2d translation vector corresponding to */ + /* the glyph transformation, if necessary. */ + /* */ + /* glyph_hints :: Format-specific glyph hints management. */ + /* */ + +#define FT_GLYPH_OWN_BITMAP 0x1 + + typedef struct FT_Slot_InternalRec_ + { + FT_GlyphLoader loader; + FT_UInt flags; + FT_Bool glyph_transformed; + FT_Matrix glyph_matrix; + FT_Vector glyph_delta; + void* glyph_hints; + + } FT_GlyphSlot_InternalRec; + + +#if 0 + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_Size_InternalRec */ + /* */ + /* <Description> */ + /* This structure contains the internal fields of each FT_Size */ + /* object. Currently, it's empty. */ + /* */ + /*************************************************************************/ + + typedef struct FT_Size_InternalRec_ + { + /* empty */ + + } FT_Size_InternalRec; + +#endif + + + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** M O D U L E S ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_ModuleRec */ + /* */ + /* <Description> */ + /* A module object instance. */ + /* */ + /* <Fields> */ + /* clazz :: A pointer to the module's class. */ + /* */ + /* library :: A handle to the parent library object. */ + /* */ + /* memory :: A handle to the memory manager. */ + /* */ + /* generic :: A generic structure for user-level extensibility (?). */ + /* */ + typedef struct FT_ModuleRec_ + { + FT_Module_Class* clazz; + FT_Library library; + FT_Memory memory; + FT_Generic generic; + + } FT_ModuleRec; + + + /* typecast an object to a FT_Module */ +#define FT_MODULE( x ) ((FT_Module)( x )) +#define FT_MODULE_CLASS( x ) FT_MODULE( x )->clazz +#define FT_MODULE_LIBRARY( x ) FT_MODULE( x )->library +#define FT_MODULE_MEMORY( x ) FT_MODULE( x )->memory + + +#define FT_MODULE_IS_DRIVER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_FONT_DRIVER ) + +#define FT_MODULE_IS_RENDERER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_RENDERER ) + +#define FT_MODULE_IS_HINTER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_HINTER ) + +#define FT_MODULE_IS_STYLER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_STYLER ) + +#define FT_DRIVER_IS_SCALABLE( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_DRIVER_SCALABLE ) + +#define FT_DRIVER_USES_OUTLINES( x ) !( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_DRIVER_NO_OUTLINES ) + +#define FT_DRIVER_HAS_HINTER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ + FT_MODULE_DRIVER_HAS_HINTER ) + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Module_Interface */ + /* */ + /* <Description> */ + /* Finds a module and returns its specific interface as a typeless */ + /* pointer. */ + /* */ + /* <Input> */ + /* library :: A handle to the library object. */ + /* */ + /* module_name :: The module's name (as an ASCII string). */ + /* */ + /* <Return> */ + /* A module-specific interface if available, 0 otherwise. */ + /* */ + /* <Note> */ + /* You should better be familiar with FreeType internals to know */ + /* which module to look for, and what its interface is :-) */ + /* */ + FT_BASE( const void* ) + FT_Get_Module_Interface( FT_Library library, + const char* mod_name ); + + FT_BASE( FT_Pointer ) + ft_module_get_service( FT_Module module, + const char* service_id ); + + /* */ + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** FACE, SIZE & GLYPH SLOT OBJECTS ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /* a few macros used to perform easy typecasts with minimal brain damage */ + +#define FT_FACE( x ) ((FT_Face)(x)) +#define FT_SIZE( x ) ((FT_Size)(x)) +#define FT_SLOT( x ) ((FT_GlyphSlot)(x)) + +#define FT_FACE_DRIVER( x ) FT_FACE( x )->driver +#define FT_FACE_LIBRARY( x ) FT_FACE_DRIVER( x )->root.library +#define FT_FACE_MEMORY( x ) FT_FACE( x )->memory +#define FT_FACE_STREAM( x ) FT_FACE( x )->stream + +#define FT_SIZE_FACE( x ) FT_SIZE( x )->face +#define FT_SLOT_FACE( x ) FT_SLOT( x )->face + +#define FT_FACE_SLOT( x ) FT_FACE( x )->glyph +#define FT_FACE_SIZE( x ) FT_FACE( x )->size + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_GlyphSlot */ + /* */ + /* <Description> */ + /* It is sometimes useful to have more than one glyph slot for a */ + /* given face object. This function is used to create additional */ + /* slots. All of them are automatically discarded when the face is */ + /* destroyed. */ + /* */ + /* <Input> */ + /* face :: A handle to a parent face object. */ + /* */ + /* <Output> */ + /* aslot :: A handle to a new glyph slot object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + FT_BASE( FT_Error ) + FT_New_GlyphSlot( FT_Face face, + FT_GlyphSlot *aslot ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_GlyphSlot */ + /* */ + /* <Description> */ + /* Destroys a given glyph slot. Remember however that all slots are */ + /* automatically destroyed with its parent. Using this function is */ + /* not always mandatory. */ + /* */ + /* <Input> */ + /* slot :: A handle to a target glyph slot. */ + /* */ + FT_BASE( void ) + FT_Done_GlyphSlot( FT_GlyphSlot slot ); + + /* */ + +#define FT_REQUEST_WIDTH( req ) \ + ( (req)->horiResolution \ + ? (FT_Pos)( (req)->width * (req)->horiResolution + 36 ) / 72 \ + : (req)->width ) + +#define FT_REQUEST_HEIGHT( req ) \ + ( (req)->vertResolution \ + ? (FT_Pos)( (req)->height * (req)->vertResolution + 36 ) / 72 \ + : (req)->height ) + + + /* Set the metrics according to a bitmap strike. */ + FT_BASE( void ) + FT_Select_Metrics( FT_Face face, + FT_ULong strike_index ); + + + /* Set the metrics according to a size request. */ + FT_BASE( void ) + FT_Request_Metrics( FT_Face face, + FT_Size_Request req ); + + + /* Match a size request against `available_sizes'. */ + FT_BASE( FT_Error ) + FT_Match_Size( FT_Face face, + FT_Size_Request req, + FT_Bool ignore_width, + FT_ULong* size_index ); + + + /* Use the horizontal metrics to synthesize the vertical metrics. */ + /* If `advance' is zero, it is also synthesized. */ + FT_BASE( void ) + ft_synthesize_vertical_metrics( FT_Glyph_Metrics* metrics, + FT_Pos advance ); + + + /* Free the bitmap of a given glyphslot when needed (i.e., only when it */ + /* was allocated with ft_glyphslot_alloc_bitmap). */ + FT_BASE( void ) + ft_glyphslot_free_bitmap( FT_GlyphSlot slot ); + + + /* Allocate a new bitmap buffer in a glyph slot. */ + FT_BASE( FT_Error ) + ft_glyphslot_alloc_bitmap( FT_GlyphSlot slot, + FT_ULong size ); + + + /* Set the bitmap buffer in a glyph slot to a given pointer. The buffer */ + /* will not be freed by a later call to ft_glyphslot_free_bitmap. */ + FT_BASE( void ) + ft_glyphslot_set_bitmap( FT_GlyphSlot slot, + FT_Byte* buffer ); + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** R E N D E R E R S ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + +#define FT_RENDERER( x ) ((FT_Renderer)( x )) +#define FT_GLYPH( x ) ((FT_Glyph)( x )) +#define FT_BITMAP_GLYPH( x ) ((FT_BitmapGlyph)( x )) +#define FT_OUTLINE_GLYPH( x ) ((FT_OutlineGlyph)( x )) + + + typedef struct FT_RendererRec_ + { + FT_ModuleRec root; + FT_Renderer_Class* clazz; + FT_Glyph_Format glyph_format; + FT_Glyph_Class glyph_class; + + FT_Raster raster; + FT_Raster_Render_Func raster_render; + FT_Renderer_RenderFunc render; + + } FT_RendererRec; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** F O N T D R I V E R S ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /* typecast a module into a driver easily */ +#define FT_DRIVER( x ) ((FT_Driver)(x)) + + /* typecast a module as a driver, and get its driver class */ +#define FT_DRIVER_CLASS( x ) FT_DRIVER( x )->clazz + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_DriverRec */ + /* */ + /* <Description> */ + /* The root font driver class. A font driver is responsible for */ + /* managing and loading font files of a given format. */ + /* */ + /* <Fields> */ + /* root :: Contains the fields of the root module class. */ + /* */ + /* clazz :: A pointer to the font driver's class. Note that */ + /* this is NOT root.clazz. `class' wasn't used */ + /* as it is a reserved word in C++. */ + /* */ + /* faces_list :: The list of faces currently opened by this */ + /* driver. */ + /* */ + /* extensions :: A typeless pointer to the driver's extensions */ + /* registry, if they are supported through the */ + /* configuration macro FT_CONFIG_OPTION_EXTENSIONS. */ + /* */ + /* glyph_loader :: The glyph loader for all faces managed by this */ + /* driver. This object isn't defined for unscalable */ + /* formats. */ + /* */ + typedef struct FT_DriverRec_ + { + FT_ModuleRec root; + FT_Driver_Class clazz; + + FT_ListRec faces_list; + void* extensions; + + FT_GlyphLoader glyph_loader; + + } FT_DriverRec; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** L I B R A R I E S ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /* This hook is used by the TrueType debugger. It must be set to an */ + /* alternate truetype bytecode interpreter function. */ +#define FT_DEBUG_HOOK_TRUETYPE 0 + + + /* Set this debug hook to a non-null pointer to force unpatented hinting */ + /* for all faces when both TT_USE_BYTECODE_INTERPRETER and */ + /* TT_CONFIG_OPTION_UNPATENTED_HINTING are defined. This is only used */ + /* during debugging. */ +#define FT_DEBUG_HOOK_UNPATENTED_HINTING 1 + + + typedef void (*FT_Bitmap_LcdFilterFunc)( FT_Bitmap* bitmap, + FT_Render_Mode render_mode, + FT_Library library ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* FT_LibraryRec */ + /* */ + /* <Description> */ + /* The FreeType library class. This is the root of all FreeType */ + /* data. Use FT_New_Library() to create a library object, and */ + /* FT_Done_Library() to discard it and all child objects. */ + /* */ + /* <Fields> */ + /* memory :: The library's memory object. Manages memory */ + /* allocation. */ + /* */ + /* generic :: Client data variable. Used to extend the */ + /* Library class by higher levels and clients. */ + /* */ + /* version_major :: The major version number of the library. */ + /* */ + /* version_minor :: The minor version number of the library. */ + /* */ + /* version_patch :: The current patch level of the library. */ + /* */ + /* num_modules :: The number of modules currently registered */ + /* within this library. This is set to 0 for new */ + /* libraries. New modules are added through the */ + /* FT_Add_Module() API function. */ + /* */ + /* modules :: A table used to store handles to the currently */ + /* registered modules. Note that each font driver */ + /* contains a list of its opened faces. */ + /* */ + /* renderers :: The list of renderers currently registered */ + /* within the library. */ + /* */ + /* cur_renderer :: The current outline renderer. This is a */ + /* shortcut used to avoid parsing the list on */ + /* each call to FT_Outline_Render(). It is a */ + /* handle to the current renderer for the */ + /* FT_GLYPH_FORMAT_OUTLINE format. */ + /* */ + /* auto_hinter :: XXX */ + /* */ + /* raster_pool :: The raster object's render pool. This can */ + /* ideally be changed dynamically at run-time. */ + /* */ + /* raster_pool_size :: The size of the render pool in bytes. */ + /* */ + /* debug_hooks :: XXX */ + /* */ + /* lcd_filter :: If subpixel rendering is activated, the */ + /* selected LCD filter mode. */ + /* */ + /* lcd_extra :: If subpixel rendering is activated, the number */ + /* of extra pixels needed for the LCD filter. */ + /* */ + /* lcd_weights :: If subpixel rendering is activated, the LCD */ + /* filter weights, if any. */ + /* */ + /* lcd_filter_func :: If subpixel rendering is activated, the LCD */ + /* filtering callback function. */ + /* */ + /* pic_container :: Contains global structs and tables, instead */ + /* of defining them globallly. */ + /* */ + /* refcount :: A counter initialized to~1 at the time an */ + /* @FT_Library structure is created. */ + /* @FT_Reference_Library increments this counter, */ + /* and @FT_Done_Library only destroys a library */ + /* if the counter is~1, otherwise it simply */ + /* decrements it. */ + /* */ + typedef struct FT_LibraryRec_ + { + FT_Memory memory; /* library's memory manager */ + + FT_Generic generic; + + FT_Int version_major; + FT_Int version_minor; + FT_Int version_patch; + + FT_UInt num_modules; + FT_Module modules[FT_MAX_MODULES]; /* module objects */ + + FT_ListRec renderers; /* list of renderers */ + FT_Renderer cur_renderer; /* current outline renderer */ + FT_Module auto_hinter; + + FT_Byte* raster_pool; /* scan-line conversion */ + /* render pool */ + FT_ULong raster_pool_size; /* size of render pool in bytes */ + + FT_DebugHook_Func debug_hooks[4]; + +#ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING + FT_LcdFilter lcd_filter; + FT_Int lcd_extra; /* number of extra pixels */ + FT_Byte lcd_weights[7]; /* filter weights, if any */ + FT_Bitmap_LcdFilterFunc lcd_filter_func; /* filtering callback */ +#endif + +#ifdef FT_CONFIG_OPTION_PIC + FT_PIC_Container pic_container; +#endif + + FT_UInt refcount; + + } FT_LibraryRec; + + + FT_BASE( FT_Renderer ) + FT_Lookup_Renderer( FT_Library library, + FT_Glyph_Format format, + FT_ListNode* node ); + + FT_BASE( FT_Error ) + FT_Render_Glyph_Internal( FT_Library library, + FT_GlyphSlot slot, + FT_Render_Mode render_mode ); + + typedef const char* + (*FT_Face_GetPostscriptNameFunc)( FT_Face face ); + + typedef FT_Error + (*FT_Face_GetGlyphNameFunc)( FT_Face face, + FT_UInt glyph_index, + FT_Pointer buffer, + FT_UInt buffer_max ); + + typedef FT_UInt + (*FT_Face_GetGlyphNameIndexFunc)( FT_Face face, + FT_String* glyph_name ); + + +#ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_New_Memory */ + /* */ + /* <Description> */ + /* Creates a new memory object. */ + /* */ + /* <Return> */ + /* A pointer to the new memory object. 0 in case of error. */ + /* */ + FT_BASE( FT_Memory ) + FT_New_Memory( void ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Done_Memory */ + /* */ + /* <Description> */ + /* Discards memory manager. */ + /* */ + /* <Input> */ + /* memory :: A handle to the memory manager. */ + /* */ + FT_BASE( void ) + FT_Done_Memory( FT_Memory memory ); + +#endif /* !FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */ + + + /* Define default raster's interface. The default raster is located in */ + /* `src/base/ftraster.c'. */ + /* */ + /* Client applications can register new rasters through the */ + /* FT_Set_Raster() API. */ + +#ifndef FT_NO_DEFAULT_RASTER + FT_EXPORT_VAR( FT_Raster_Funcs ) ft_default_raster; +#endif + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** PIC-Support Macros for ftimage.h ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DEFINE_OUTLINE_FUNCS */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Outline_Funcs struct. */ + /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ + /* called with a pre-allocated stracture to be filled. */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_, \ + cubic_to_, shift_, delta_) \ + static const FT_Outline_Funcs class_ = \ + { \ + move_to_, line_to_, conic_to_, cubic_to_, shift_, delta_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_, \ + cubic_to_, shift_, delta_) \ + static FT_Error \ + Init_Class_##class_( FT_Outline_Funcs* clazz ) \ + { \ + clazz->move_to = move_to_; \ + clazz->line_to = line_to_; \ + clazz->conic_to = conic_to_; \ + clazz->cubic_to = cubic_to_; \ + clazz->shift = shift_; \ + clazz->delta = delta_; \ + return FT_Err_Ok; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DEFINE_RASTER_FUNCS */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Raster_Funcs struct. */ + /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ + /* called with a pre-allocated stracture to be filled. */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_, \ + raster_reset_, raster_set_mode_, \ + raster_render_, raster_done_) \ + const FT_Raster_Funcs class_ = \ + { \ + glyph_format_, raster_new_, raster_reset_, \ + raster_set_mode_, raster_render_, raster_done_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_, \ + raster_reset_, raster_set_mode_, raster_render_, raster_done_) \ + void \ + FT_Init_Class_##class_( FT_Raster_Funcs* clazz ) \ + { \ + clazz->glyph_format = glyph_format_; \ + clazz->raster_new = raster_new_; \ + clazz->raster_reset = raster_reset_; \ + clazz->raster_set_mode = raster_set_mode_; \ + clazz->raster_render = raster_render_; \ + clazz->raster_done = raster_done_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** PIC-Support Macros for ftrender.h ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DEFINE_GLYPH */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Glyph_Class struct. */ + /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ + /* called with a pre-allocated stracture to be filled. */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_, \ + transform_, bbox_, prepare_) \ + FT_CALLBACK_TABLE_DEF \ + const FT_Glyph_Class class_ = \ + { \ + size_, format_, init_, done_, copy_, transform_, bbox_, prepare_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_, \ + transform_, bbox_, prepare_) \ + void \ + FT_Init_Class_##class_( FT_Glyph_Class* clazz ) \ + { \ + clazz->glyph_size = size_; \ + clazz->glyph_format = format_; \ + clazz->glyph_init = init_; \ + clazz->glyph_done = done_; \ + clazz->glyph_copy = copy_; \ + clazz->glyph_transform = transform_; \ + clazz->glyph_bbox = bbox_; \ + clazz->glyph_prepare = prepare_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DECLARE_RENDERER */ + /* */ + /* <Description> */ + /* Used to create a forward declaration of a */ + /* FT_Renderer_Class stract instance. */ + /* */ + /* <Macro> */ + /* FT_DEFINE_RENDERER */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Renderer_Class struct. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ + /* to called with a pointer where the allocated stracture is returned.*/ + /* And when it is no longer needed a Destroy function needs */ + /* to be called to release that allocation. */ + /* fcinit.c (ft_create_default_module_classes) already contains */ + /* a mechanism to call these functions for the default modules */ + /* described in ftmodule.h */ + /* */ + /* Notice that the created Create and Destroy functions call */ + /* pic_init and pic_free function to allow you to manually allocate */ + /* and initialize any additional global data, like module specific */ + /* interface, and put them in the global pic container defined in */ + /* ftpic.h. if you don't need them just implement the functions as */ + /* empty to resolve the link error. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DECLARE_RENDERER(class_) \ + FT_EXPORT_VAR( const FT_Renderer_Class ) class_; + +#define FT_DEFINE_RENDERER(class_, \ + flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_, \ + glyph_format_, render_glyph_, transform_glyph_, \ + get_glyph_cbox_, set_mode_, raster_class_ ) \ + FT_CALLBACK_TABLE_DEF \ + const FT_Renderer_Class class_ = \ + { \ + FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_, \ + interface_,init_,done_,get_interface_) \ + glyph_format_, \ + \ + render_glyph_, \ + transform_glyph_, \ + get_glyph_cbox_, \ + set_mode_, \ + \ + raster_class_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DECLARE_RENDERER(class_) FT_DECLARE_MODULE(class_) + +#define FT_DEFINE_RENDERER(class_, \ + flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_, \ + glyph_format_, render_glyph_, transform_glyph_, \ + get_glyph_cbox_, set_mode_, raster_class_ ) \ + void class_##_pic_free( FT_Library library ); \ + FT_Error class_##_pic_init( FT_Library library ); \ + \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_Module_Class* clazz ) \ + { \ + FT_Renderer_Class* rclazz = (FT_Renderer_Class*)clazz; \ + FT_Memory memory = library->memory; \ + class_##_pic_free( library ); \ + if ( rclazz ) \ + FT_FREE( rclazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_Module_Class** output_class ) \ + { \ + FT_Renderer_Class* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ + return error; \ + \ + error = class_##_pic_init( library ); \ + if(error) \ + { \ + FT_FREE( clazz ); \ + return error; \ + } \ + \ + FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_, \ + interface_,init_,done_,get_interface_) \ + \ + clazz->glyph_format = glyph_format_; \ + \ + clazz->render_glyph = render_glyph_; \ + clazz->transform_glyph = transform_glyph_; \ + clazz->get_glyph_cbox = get_glyph_cbox_; \ + clazz->set_mode = set_mode_; \ + \ + clazz->raster_class = raster_class_; \ + \ + *output_class = (FT_Module_Class*)clazz; \ + return FT_Err_Ok; \ + } + + + +#endif /* FT_CONFIG_OPTION_PIC */ + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** PIC-Support Macros for ftmodapi.h ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + +#ifdef FT_CONFIG_OPTION_PIC + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Module_Creator */ + /* */ + /* <Description> */ + /* A function used to create (allocate) a new module class object. */ + /* The object's members are initialized, but the module itself is */ + /* not. */ + /* */ + /* <Input> */ + /* memory :: A handle to the memory manager. */ + /* output_class :: Initialized with the newly allocated class. */ + /* */ + typedef FT_Error + (*FT_Module_Creator)( FT_Memory memory, + FT_Module_Class** output_class ); + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* FT_Module_Destroyer */ + /* */ + /* <Description> */ + /* A function used to destroy (deallocate) a module class object. */ + /* */ + /* <Input> */ + /* memory :: A handle to the memory manager. */ + /* clazz :: Module class to destroy. */ + /* */ + typedef void + (*FT_Module_Destroyer)( FT_Memory memory, + FT_Module_Class* clazz ); + +#endif + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DECLARE_MODULE */ + /* */ + /* <Description> */ + /* Used to create a forward declaration of a */ + /* FT_Module_Class stract instance. */ + /* */ + /* <Macro> */ + /* FT_DEFINE_MODULE */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Module_Class struct. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ + /* to called with a pointer where the allocated stracture is returned.*/ + /* And when it is no longer needed a Destroy function needs */ + /* to be called to release that allocation. */ + /* fcinit.c (ft_create_default_module_classes) already contains */ + /* a mechanism to call these functions for the default modules */ + /* described in ftmodule.h */ + /* */ + /* Notice that the created Create and Destroy functions call */ + /* pic_init and pic_free function to allow you to manually allocate */ + /* and initialize any additional global data, like module specific */ + /* interface, and put them in the global pic container defined in */ + /* ftpic.h. if you don't need them just implement the functions as */ + /* empty to resolve the link error. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ + /* <Macro> */ + /* FT_DEFINE_ROOT_MODULE */ + /* */ + /* <Description> */ + /* Used to initialize an instance of FT_Module_Class struct inside */ + /* another stract that contains it or in a function that initializes */ + /* that containing stract */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DECLARE_MODULE(class_) \ + FT_CALLBACK_TABLE \ + const FT_Module_Class class_; \ + +#define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_) \ + { \ + flags_, \ + size_, \ + \ + name_, \ + version_, \ + requires_, \ + \ + interface_, \ + \ + init_, \ + done_, \ + get_interface_, \ + }, + +#define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_) \ + FT_CALLBACK_TABLE_DEF \ + const FT_Module_Class class_ = \ + { \ + flags_, \ + size_, \ + \ + name_, \ + version_, \ + requires_, \ + \ + interface_, \ + \ + init_, \ + done_, \ + get_interface_, \ + }; + + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DECLARE_MODULE(class_) \ + FT_Error FT_Create_Class_##class_( FT_Library library, \ + FT_Module_Class** output_class ); \ + void FT_Destroy_Class_##class_( FT_Library library, \ + FT_Module_Class* clazz ); + +#define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_) \ + clazz->root.module_flags = flags_; \ + clazz->root.module_size = size_; \ + clazz->root.module_name = name_; \ + clazz->root.module_version = version_; \ + clazz->root.module_requires = requires_; \ + \ + clazz->root.module_interface = interface_; \ + \ + clazz->root.module_init = init_; \ + clazz->root.module_done = done_; \ + clazz->root.get_interface = get_interface_; + +#define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_, \ + interface_, init_, done_, get_interface_) \ + void class_##_pic_free( FT_Library library ); \ + FT_Error class_##_pic_init( FT_Library library ); \ + \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_Module_Class* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + class_##_pic_free( library ); \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_Module_Class** output_class ) \ + { \ + FT_Memory memory = library->memory; \ + FT_Module_Class* clazz; \ + FT_Error error; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ + return error; \ + error = class_##_pic_init( library ); \ + if(error) \ + { \ + FT_FREE( clazz ); \ + return error; \ + } \ + \ + clazz->module_flags = flags_; \ + clazz->module_size = size_; \ + clazz->module_name = name_; \ + clazz->module_version = version_; \ + clazz->module_requires = requires_; \ + \ + clazz->module_interface = interface_; \ + \ + clazz->module_init = init_; \ + clazz->module_done = done_; \ + clazz->get_interface = get_interface_; \ + \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + +FT_END_HEADER + +#endif /* __FTOBJS_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftpic.h b/other/freetype/include/freetype/internal/ftpic.h new file mode 100644 index 0000000..1b31957 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftpic.h @@ -0,0 +1,67 @@ +/***************************************************************************/ +/* */ +/* ftpic.h */ +/* */ +/* The FreeType position independent code services (declaration). */ +/* */ +/* Copyright 2009 by */ +/* Oran Agra and Mickey Gabel. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + /*************************************************************************/ + /* */ + /* Modules that ordinarily have const global data that need address */ + /* can instead define pointers here. */ + /* */ + /*************************************************************************/ + + +#ifndef __FTPIC_H__ +#define __FTPIC_H__ + + +FT_BEGIN_HEADER + +#ifdef FT_CONFIG_OPTION_PIC + + typedef struct FT_PIC_Container_ + { + /* pic containers for base */ + void* base; + /* pic containers for modules */ + void* autofit; + void* cff; + void* pshinter; + void* psnames; + void* raster; + void* sfnt; + void* smooth; + void* truetype; + } FT_PIC_Container; + + /* Initialize the various function tables, structs, etc. stored in the container. */ + FT_BASE( FT_Error ) + ft_pic_container_init( FT_Library library ); + + + /* Destroy the contents of the container. */ + FT_BASE( void ) + ft_pic_container_destroy( FT_Library library ); + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + +FT_END_HEADER + +#endif /* __FTPIC_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftrfork.h b/other/freetype/include/freetype/internal/ftrfork.h new file mode 100644 index 0000000..aa573c8 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftrfork.h @@ -0,0 +1,196 @@ +/***************************************************************************/ +/* */ +/* ftrfork.h */ +/* */ +/* Embedded resource forks accessor (specification). */ +/* */ +/* Copyright 2004, 2006, 2007 by */ +/* Masatake YAMATO and Redhat K.K. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +/***************************************************************************/ +/* Development of the code in this file is support of */ +/* Information-technology Promotion Agency, Japan. */ +/***************************************************************************/ + + +#ifndef __FTRFORK_H__ +#define __FTRFORK_H__ + + +#include <ft2build.h> +#include FT_INTERNAL_OBJECTS_H + + +FT_BEGIN_HEADER + + + /* Number of guessing rules supported in `FT_Raccess_Guess'. */ + /* Don't forget to increment the number if you add a new guessing rule. */ +#define FT_RACCESS_N_RULES 9 + + + /* A structure to describe a reference in a resource by its resource ID */ + /* and internal offset. The `POST' resource expects to be concatenated */ + /* by the order of resource IDs instead of its appearance in the file. */ + + typedef struct FT_RFork_Ref_ + { + FT_UShort res_id; + FT_ULong offset; + + } FT_RFork_Ref; + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Raccess_Guess */ + /* */ + /* <Description> */ + /* Guess a file name and offset where the actual resource fork is */ + /* stored. The macro FT_RACCESS_N_RULES holds the number of */ + /* guessing rules; the guessed result for the Nth rule is */ + /* represented as a triplet: a new file name (new_names[N]), a file */ + /* offset (offsets[N]), and an error code (errors[N]). */ + /* */ + /* <Input> */ + /* library :: */ + /* A FreeType library instance. */ + /* */ + /* stream :: */ + /* A file stream containing the resource fork. */ + /* */ + /* base_name :: */ + /* The (base) file name of the resource fork used for some */ + /* guessing rules. */ + /* */ + /* <Output> */ + /* new_names :: */ + /* An array of guessed file names in which the resource forks may */ + /* exist. If `new_names[N]' is NULL, the guessed file name is */ + /* equal to `base_name'. */ + /* */ + /* offsets :: */ + /* An array of guessed file offsets. `offsets[N]' holds the file */ + /* offset of the possible start of the resource fork in file */ + /* `new_names[N]'. */ + /* */ + /* errors :: */ + /* An array of FreeType error codes. `errors[N]' is the error */ + /* code of Nth guessing rule function. If `errors[N]' is not */ + /* FT_Err_Ok, `new_names[N]' and `offsets[N]' are meaningless. */ + /* */ + FT_BASE( void ) + FT_Raccess_Guess( FT_Library library, + FT_Stream stream, + char* base_name, + char** new_names, + FT_Long* offsets, + FT_Error* errors ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Raccess_Get_HeaderInfo */ + /* */ + /* <Description> */ + /* Get the information from the header of resource fork. The */ + /* information includes the file offset where the resource map */ + /* starts, and the file offset where the resource data starts. */ + /* `FT_Raccess_Get_DataOffsets' requires these two data. */ + /* */ + /* <Input> */ + /* library :: */ + /* A FreeType library instance. */ + /* */ + /* stream :: */ + /* A file stream containing the resource fork. */ + /* */ + /* rfork_offset :: */ + /* The file offset where the resource fork starts. */ + /* */ + /* <Output> */ + /* map_offset :: */ + /* The file offset where the resource map starts. */ + /* */ + /* rdata_pos :: */ + /* The file offset where the resource data starts. */ + /* */ + /* <Return> */ + /* FreeType error code. FT_Err_Ok means success. */ + /* */ + FT_BASE( FT_Error ) + FT_Raccess_Get_HeaderInfo( FT_Library library, + FT_Stream stream, + FT_Long rfork_offset, + FT_Long *map_offset, + FT_Long *rdata_pos ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Raccess_Get_DataOffsets */ + /* */ + /* <Description> */ + /* Get the data offsets for a tag in a resource fork. Offsets are */ + /* stored in an array because, in some cases, resources in a resource */ + /* fork have the same tag. */ + /* */ + /* <Input> */ + /* library :: */ + /* A FreeType library instance. */ + /* */ + /* stream :: */ + /* A file stream containing the resource fork. */ + /* */ + /* map_offset :: */ + /* The file offset where the resource map starts. */ + /* */ + /* rdata_pos :: */ + /* The file offset where the resource data starts. */ + /* */ + /* tag :: */ + /* The resource tag. */ + /* */ + /* <Output> */ + /* offsets :: */ + /* The stream offsets for the resource data specified by `tag'. */ + /* This array is allocated by the function, so you have to call */ + /* @ft_mem_free after use. */ + /* */ + /* count :: */ + /* The length of offsets array. */ + /* */ + /* <Return> */ + /* FreeType error code. FT_Err_Ok means success. */ + /* */ + /* <Note> */ + /* Normally you should use `FT_Raccess_Get_HeaderInfo' to get the */ + /* value for `map_offset' and `rdata_pos'. */ + /* */ + FT_BASE( FT_Error ) + FT_Raccess_Get_DataOffsets( FT_Library library, + FT_Stream stream, + FT_Long map_offset, + FT_Long rdata_pos, + FT_Long tag, + FT_Long **offsets, + FT_Long *count ); + + +FT_END_HEADER + +#endif /* __FTRFORK_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftserv.h b/other/freetype/include/freetype/internal/ftserv.h new file mode 100644 index 0000000..569b9f7 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftserv.h @@ -0,0 +1,620 @@ +/***************************************************************************/ +/* */ +/* ftserv.h */ +/* */ +/* The FreeType services (specification only). */ +/* */ +/* Copyright 2003, 2004, 2005, 2006, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + /*************************************************************************/ + /* */ + /* Each module can export one or more `services'. Each service is */ + /* identified by a constant string and modeled by a pointer; the latter */ + /* generally corresponds to a structure containing function pointers. */ + /* */ + /* Note that a service's data cannot be a mere function pointer because */ + /* in C it is possible that function pointers might be implemented */ + /* differently than data pointers (e.g. 48 bits instead of 32). */ + /* */ + /*************************************************************************/ + + +#ifndef __FTSERV_H__ +#define __FTSERV_H__ + + +FT_BEGIN_HEADER + +#if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ + + /* we disable the warning `conditional expression is constant' here */ + /* in order to compile cleanly with the maximum level of warnings */ +#pragma warning( disable : 4127 ) + +#endif /* _MSC_VER */ + + /* + * @macro: + * FT_FACE_FIND_SERVICE + * + * @description: + * This macro is used to look up a service from a face's driver module. + * + * @input: + * face :: + * The source face handle. + * + * id :: + * A string describing the service as defined in the service's + * header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to + * `multi-masters'). It is automatically prefixed with + * `FT_SERVICE_ID_'. + * + * @output: + * ptr :: + * A variable that receives the service pointer. Will be NULL + * if not found. + */ +#ifdef __cplusplus + +#define FT_FACE_FIND_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ + FT_Pointer _tmp_ = NULL; \ + FT_Pointer* _pptr_ = (FT_Pointer*)&(ptr); \ + \ + \ + if ( module->clazz->get_interface ) \ + _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \ + *_pptr_ = _tmp_; \ + FT_END_STMNT + +#else /* !C++ */ + +#define FT_FACE_FIND_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ + FT_Pointer _tmp_ = NULL; \ + \ + if ( module->clazz->get_interface ) \ + _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \ + ptr = _tmp_; \ + FT_END_STMNT + +#endif /* !C++ */ + + /* + * @macro: + * FT_FACE_FIND_GLOBAL_SERVICE + * + * @description: + * This macro is used to look up a service from all modules. + * + * @input: + * face :: + * The source face handle. + * + * id :: + * A string describing the service as defined in the service's + * header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to + * `multi-masters'). It is automatically prefixed with + * `FT_SERVICE_ID_'. + * + * @output: + * ptr :: + * A variable that receives the service pointer. Will be NULL + * if not found. + */ +#ifdef __cplusplus + +#define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ + FT_Pointer _tmp_; \ + FT_Pointer* _pptr_ = (FT_Pointer*)&(ptr); \ + \ + \ + _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \ + *_pptr_ = _tmp_; \ + FT_END_STMNT + +#else /* !C++ */ + +#define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ + FT_Pointer _tmp_; \ + \ + \ + _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \ + ptr = _tmp_; \ + FT_END_STMNT + +#endif /* !C++ */ + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** S E R V I C E D E S C R I P T O R S *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + /* + * The following structure is used to _describe_ a given service + * to the library. This is useful to build simple static service lists. + */ + typedef struct FT_ServiceDescRec_ + { + const char* serv_id; /* service name */ + const void* serv_data; /* service pointer/data */ + + } FT_ServiceDescRec; + + typedef const FT_ServiceDescRec* FT_ServiceDesc; + + /*************************************************************************/ + /* */ + /* <Macro> */ + /* FT_DEFINE_SERVICEDESCREC1 .. FT_DEFINE_SERVICEDESCREC6 */ + /* */ + /* <Description> */ + /* Used to initialize an array of FT_ServiceDescRec structs. */ + /* */ + /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ + /* to called with a pointer where the allocated array is returned. */ + /* And when it is no longer needed a Destroy function needs */ + /* to be called to release that allocation. */ + /* */ + /* These functions should be manyally called from the pic_init and */ + /* pic_free functions of your module (see FT_DEFINE_MODULE) */ + /* */ + /* When FT_CONFIG_OPTION_PIC is not defined the array will be */ + /* allocated in the global scope (or the scope where the macro */ + /* is used). */ + /* */ +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {NULL, NULL} \ + }; +#define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {serv_id_2, serv_data_2}, \ + {NULL, NULL} \ + }; +#define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {serv_id_2, serv_data_2}, \ + {serv_id_3, serv_data_3}, \ + {NULL, NULL} \ + }; +#define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ + serv_id_4, serv_data_4) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {serv_id_2, serv_data_2}, \ + {serv_id_3, serv_data_3}, \ + {serv_id_4, serv_data_4}, \ + {NULL, NULL} \ + }; +#define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ + serv_id_4, serv_data_4, serv_id_5, serv_data_5) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {serv_id_2, serv_data_2}, \ + {serv_id_3, serv_data_3}, \ + {serv_id_4, serv_data_4}, \ + {serv_id_5, serv_data_5}, \ + {NULL, NULL} \ + }; +#define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ + serv_id_4, serv_data_4, serv_id_5, serv_data_5, \ + serv_id_6, serv_data_6) \ + static const FT_ServiceDescRec class_[] = \ + { \ + {serv_id_1, serv_data_1}, \ + {serv_id_2, serv_data_2}, \ + {serv_id_3, serv_data_3}, \ + {serv_id_4, serv_data_4}, \ + {serv_id_5, serv_data_5}, \ + {serv_id_6, serv_data_6}, \ + {NULL, NULL} \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*2 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = NULL; \ + clazz[1].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*3 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = serv_id_2; \ + clazz[1].serv_data = serv_data_2; \ + clazz[2].serv_id = NULL; \ + clazz[2].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*4 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = serv_id_2; \ + clazz[1].serv_data = serv_data_2; \ + clazz[2].serv_id = serv_id_3; \ + clazz[2].serv_data = serv_data_3; \ + clazz[3].serv_id = NULL; \ + clazz[3].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ + serv_id_4, serv_data_4) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*5 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = serv_id_2; \ + clazz[1].serv_data = serv_data_2; \ + clazz[2].serv_id = serv_id_3; \ + clazz[2].serv_data = serv_data_3; \ + clazz[3].serv_id = serv_id_4; \ + clazz[3].serv_data = serv_data_4; \ + clazz[4].serv_id = NULL; \ + clazz[4].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, serv_id_4, \ + serv_data_4, serv_id_5, serv_data_5) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*6 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = serv_id_2; \ + clazz[1].serv_data = serv_data_2; \ + clazz[2].serv_id = serv_id_3; \ + clazz[2].serv_data = serv_data_3; \ + clazz[3].serv_id = serv_id_4; \ + clazz[3].serv_data = serv_data_4; \ + clazz[4].serv_id = serv_id_5; \ + clazz[4].serv_data = serv_data_5; \ + clazz[5].serv_id = NULL; \ + clazz[5].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } + +#define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1, \ + serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ + serv_id_4, serv_data_4, serv_id_5, serv_data_5, \ + serv_id_6, serv_data_6) \ + void \ + FT_Destroy_Class_##class_( FT_Library library, \ + FT_ServiceDescRec* clazz ) \ + { \ + FT_Memory memory = library->memory; \ + if ( clazz ) \ + FT_FREE( clazz ); \ + } \ + \ + FT_Error \ + FT_Create_Class_##class_( FT_Library library, \ + FT_ServiceDescRec** output_class) \ + { \ + FT_ServiceDescRec* clazz; \ + FT_Error error; \ + FT_Memory memory = library->memory; \ + \ + if ( FT_ALLOC( clazz, sizeof(*clazz)*7 ) ) \ + return error; \ + clazz[0].serv_id = serv_id_1; \ + clazz[0].serv_data = serv_data_1; \ + clazz[1].serv_id = serv_id_2; \ + clazz[1].serv_data = serv_data_2; \ + clazz[2].serv_id = serv_id_3; \ + clazz[2].serv_data = serv_data_3; \ + clazz[3].serv_id = serv_id_4; \ + clazz[3].serv_data = serv_data_4; \ + clazz[4].serv_id = serv_id_5; \ + clazz[4].serv_data = serv_data_5; \ + clazz[5].serv_id = serv_id_6; \ + clazz[5].serv_data = serv_data_6; \ + clazz[6].serv_id = NULL; \ + clazz[6].serv_data = NULL; \ + *output_class = clazz; \ + return FT_Err_Ok; \ + } +#endif /* FT_CONFIG_OPTION_PIC */ + + /* + * Parse a list of FT_ServiceDescRec descriptors and look for + * a specific service by ID. Note that the last element in the + * array must be { NULL, NULL }, and that the function should + * return NULL if the service isn't available. + * + * This function can be used by modules to implement their + * `get_service' method. + */ + FT_BASE( FT_Pointer ) + ft_service_list_lookup( FT_ServiceDesc service_descriptors, + const char* service_id ); + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** S E R V I C E S C A C H E *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + /* + * This structure is used to store a cache for several frequently used + * services. It is the type of `face->internal->services'. You + * should only use FT_FACE_LOOKUP_SERVICE to access it. + * + * All fields should have the type FT_Pointer to relax compilation + * dependencies. We assume the developer isn't completely stupid. + * + * Each field must be named `service_XXXX' where `XXX' corresponds to + * the correct FT_SERVICE_ID_XXXX macro. See the definition of + * FT_FACE_LOOKUP_SERVICE below how this is implemented. + * + */ + typedef struct FT_ServiceCacheRec_ + { + FT_Pointer service_POSTSCRIPT_FONT_NAME; + FT_Pointer service_MULTI_MASTERS; + FT_Pointer service_GLYPH_DICT; + FT_Pointer service_PFR_METRICS; + FT_Pointer service_WINFNT; + + } FT_ServiceCacheRec, *FT_ServiceCache; + + + /* + * A magic number used within the services cache. + */ +#define FT_SERVICE_UNAVAILABLE ((FT_Pointer)-2) /* magic number */ + + + /* + * @macro: + * FT_FACE_LOOKUP_SERVICE + * + * @description: + * This macro is used to lookup a service from a face's driver module + * using its cache. + * + * @input: + * face:: + * The source face handle containing the cache. + * + * field :: + * The field name in the cache. + * + * id :: + * The service ID. + * + * @output: + * ptr :: + * A variable receiving the service data. NULL if not available. + */ +#ifdef __cplusplus + +#define FT_FACE_LOOKUP_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Pointer svc; \ + FT_Pointer* Pptr = (FT_Pointer*)&(ptr); \ + \ + \ + svc = FT_FACE( face )->internal->services. service_ ## id; \ + if ( svc == FT_SERVICE_UNAVAILABLE ) \ + svc = NULL; \ + else if ( svc == NULL ) \ + { \ + FT_FACE_FIND_SERVICE( face, svc, id ); \ + \ + FT_FACE( face )->internal->services. service_ ## id = \ + (FT_Pointer)( svc != NULL ? svc \ + : FT_SERVICE_UNAVAILABLE ); \ + } \ + *Pptr = svc; \ + FT_END_STMNT + +#else /* !C++ */ + +#define FT_FACE_LOOKUP_SERVICE( face, ptr, id ) \ + FT_BEGIN_STMNT \ + FT_Pointer svc; \ + \ + \ + svc = FT_FACE( face )->internal->services. service_ ## id; \ + if ( svc == FT_SERVICE_UNAVAILABLE ) \ + svc = NULL; \ + else if ( svc == NULL ) \ + { \ + FT_FACE_FIND_SERVICE( face, svc, id ); \ + \ + FT_FACE( face )->internal->services. service_ ## id = \ + (FT_Pointer)( svc != NULL ? svc \ + : FT_SERVICE_UNAVAILABLE ); \ + } \ + ptr = svc; \ + FT_END_STMNT + +#endif /* !C++ */ + + /* + * A macro used to define new service structure types. + */ + +#define FT_DEFINE_SERVICE( name ) \ + typedef struct FT_Service_ ## name ## Rec_ \ + FT_Service_ ## name ## Rec ; \ + typedef struct FT_Service_ ## name ## Rec_ \ + const * FT_Service_ ## name ; \ + struct FT_Service_ ## name ## Rec_ + + /* */ + + /* + * The header files containing the services. + */ + +#define FT_SERVICE_BDF_H <freetype/internal/services/svbdf.h> +#define FT_SERVICE_CID_H <freetype/internal/services/svcid.h> +#define FT_SERVICE_GLYPH_DICT_H <freetype/internal/services/svgldict.h> +#define FT_SERVICE_GX_VALIDATE_H <freetype/internal/services/svgxval.h> +#define FT_SERVICE_KERNING_H <freetype/internal/services/svkern.h> +#define FT_SERVICE_MULTIPLE_MASTERS_H <freetype/internal/services/svmm.h> +#define FT_SERVICE_OPENTYPE_VALIDATE_H <freetype/internal/services/svotval.h> +#define FT_SERVICE_PFR_H <freetype/internal/services/svpfr.h> +#define FT_SERVICE_POSTSCRIPT_CMAPS_H <freetype/internal/services/svpscmap.h> +#define FT_SERVICE_POSTSCRIPT_INFO_H <freetype/internal/services/svpsinfo.h> +#define FT_SERVICE_POSTSCRIPT_NAME_H <freetype/internal/services/svpostnm.h> +#define FT_SERVICE_SFNT_H <freetype/internal/services/svsfnt.h> +#define FT_SERVICE_TRUETYPE_ENGINE_H <freetype/internal/services/svtteng.h> +#define FT_SERVICE_TT_CMAP_H <freetype/internal/services/svttcmap.h> +#define FT_SERVICE_WINFNT_H <freetype/internal/services/svwinfnt.h> +#define FT_SERVICE_XFREE86_NAME_H <freetype/internal/services/svxf86nm.h> +#define FT_SERVICE_TRUETYPE_GLYF_H <freetype/internal/services/svttglyf.h> + + /* */ + +FT_END_HEADER + +#endif /* __FTSERV_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftstream.h b/other/freetype/include/freetype/internal/ftstream.h new file mode 100644 index 0000000..8b18500 --- /dev/null +++ b/other/freetype/include/freetype/internal/ftstream.h @@ -0,0 +1,539 @@ +/***************************************************************************/ +/* */ +/* ftstream.h */ +/* */ +/* Stream handling (specification). */ +/* */ +/* Copyright 1996-2002, 2004-2006, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTSTREAM_H__ +#define __FTSTREAM_H__ + + +#include <ft2build.h> +#include FT_SYSTEM_H +#include FT_INTERNAL_OBJECTS_H + + +FT_BEGIN_HEADER + + + /* format of an 8-bit frame_op value: */ + /* */ + /* bit 76543210 */ + /* xxxxxxes */ + /* */ + /* s is set to 1 if the value is signed. */ + /* e is set to 1 if the value is little-endian. */ + /* xxx is a command. */ + +#define FT_FRAME_OP_SHIFT 2 +#define FT_FRAME_OP_SIGNED 1 +#define FT_FRAME_OP_LITTLE 2 +#define FT_FRAME_OP_COMMAND( x ) ( x >> FT_FRAME_OP_SHIFT ) + +#define FT_MAKE_FRAME_OP( command, little, sign ) \ + ( ( command << FT_FRAME_OP_SHIFT ) | ( little << 1 ) | sign ) + +#define FT_FRAME_OP_END 0 +#define FT_FRAME_OP_START 1 /* start a new frame */ +#define FT_FRAME_OP_BYTE 2 /* read 1-byte value */ +#define FT_FRAME_OP_SHORT 3 /* read 2-byte value */ +#define FT_FRAME_OP_LONG 4 /* read 4-byte value */ +#define FT_FRAME_OP_OFF3 5 /* read 3-byte value */ +#define FT_FRAME_OP_BYTES 6 /* read a bytes sequence */ + + + typedef enum FT_Frame_Op_ + { + ft_frame_end = 0, + ft_frame_start = FT_MAKE_FRAME_OP( FT_FRAME_OP_START, 0, 0 ), + + ft_frame_byte = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE, 0, 0 ), + ft_frame_schar = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE, 0, 1 ), + + ft_frame_ushort_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 0 ), + ft_frame_short_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 1 ), + ft_frame_ushort_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 0 ), + ft_frame_short_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 1 ), + + ft_frame_ulong_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 0 ), + ft_frame_long_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 1 ), + ft_frame_ulong_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 0 ), + ft_frame_long_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 1 ), + + ft_frame_uoff3_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 0 ), + ft_frame_off3_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 1 ), + ft_frame_uoff3_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 0 ), + ft_frame_off3_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 1 ), + + ft_frame_bytes = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 0 ), + ft_frame_skip = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 1 ) + + } FT_Frame_Op; + + + typedef struct FT_Frame_Field_ + { + FT_Byte value; + FT_Byte size; + FT_UShort offset; + + } FT_Frame_Field; + + + /* Construct an FT_Frame_Field out of a structure type and a field name. */ + /* The structure type must be set in the FT_STRUCTURE macro before */ + /* calling the FT_FRAME_START() macro. */ + /* */ +#define FT_FIELD_SIZE( f ) \ + (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f ) + +#define FT_FIELD_SIZE_DELTA( f ) \ + (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f[0] ) + +#define FT_FIELD_OFFSET( f ) \ + (FT_UShort)( offsetof( FT_STRUCTURE, f ) ) + +#define FT_FRAME_FIELD( frame_op, field ) \ + { \ + frame_op, \ + FT_FIELD_SIZE( field ), \ + FT_FIELD_OFFSET( field ) \ + } + +#define FT_MAKE_EMPTY_FIELD( frame_op ) { frame_op, 0, 0 } + +#define FT_FRAME_START( size ) { ft_frame_start, 0, size } +#define FT_FRAME_END { ft_frame_end, 0, 0 } + +#define FT_FRAME_LONG( f ) FT_FRAME_FIELD( ft_frame_long_be, f ) +#define FT_FRAME_ULONG( f ) FT_FRAME_FIELD( ft_frame_ulong_be, f ) +#define FT_FRAME_SHORT( f ) FT_FRAME_FIELD( ft_frame_short_be, f ) +#define FT_FRAME_USHORT( f ) FT_FRAME_FIELD( ft_frame_ushort_be, f ) +#define FT_FRAME_OFF3( f ) FT_FRAME_FIELD( ft_frame_off3_be, f ) +#define FT_FRAME_UOFF3( f ) FT_FRAME_FIELD( ft_frame_uoff3_be, f ) +#define FT_FRAME_BYTE( f ) FT_FRAME_FIELD( ft_frame_byte, f ) +#define FT_FRAME_CHAR( f ) FT_FRAME_FIELD( ft_frame_schar, f ) + +#define FT_FRAME_LONG_LE( f ) FT_FRAME_FIELD( ft_frame_long_le, f ) +#define FT_FRAME_ULONG_LE( f ) FT_FRAME_FIELD( ft_frame_ulong_le, f ) +#define FT_FRAME_SHORT_LE( f ) FT_FRAME_FIELD( ft_frame_short_le, f ) +#define FT_FRAME_USHORT_LE( f ) FT_FRAME_FIELD( ft_frame_ushort_le, f ) +#define FT_FRAME_OFF3_LE( f ) FT_FRAME_FIELD( ft_frame_off3_le, f ) +#define FT_FRAME_UOFF3_LE( f ) FT_FRAME_FIELD( ft_frame_uoff3_le, f ) + +#define FT_FRAME_SKIP_LONG { ft_frame_long_be, 0, 0 } +#define FT_FRAME_SKIP_SHORT { ft_frame_short_be, 0, 0 } +#define FT_FRAME_SKIP_BYTE { ft_frame_byte, 0, 0 } + +#define FT_FRAME_BYTES( field, count ) \ + { \ + ft_frame_bytes, \ + count, \ + FT_FIELD_OFFSET( field ) \ + } + +#define FT_FRAME_SKIP_BYTES( count ) { ft_frame_skip, count, 0 } + + + /*************************************************************************/ + /* */ + /* Integer extraction macros -- the `buffer' parameter must ALWAYS be of */ + /* type `char*' or equivalent (1-byte elements). */ + /* */ + +#define FT_BYTE_( p, i ) ( ((const FT_Byte*)(p))[(i)] ) +#define FT_INT8_( p, i ) ( ((const FT_Char*)(p))[(i)] ) + +#define FT_INT16( x ) ( (FT_Int16)(x) ) +#define FT_UINT16( x ) ( (FT_UInt16)(x) ) +#define FT_INT32( x ) ( (FT_Int32)(x) ) +#define FT_UINT32( x ) ( (FT_UInt32)(x) ) + +#define FT_BYTE_I16( p, i, s ) ( FT_INT16( FT_BYTE_( p, i ) ) << (s) ) +#define FT_BYTE_U16( p, i, s ) ( FT_UINT16( FT_BYTE_( p, i ) ) << (s) ) +#define FT_BYTE_I32( p, i, s ) ( FT_INT32( FT_BYTE_( p, i ) ) << (s) ) +#define FT_BYTE_U32( p, i, s ) ( FT_UINT32( FT_BYTE_( p, i ) ) << (s) ) + +#define FT_INT8_I16( p, i, s ) ( FT_INT16( FT_INT8_( p, i ) ) << (s) ) +#define FT_INT8_U16( p, i, s ) ( FT_UINT16( FT_INT8_( p, i ) ) << (s) ) +#define FT_INT8_I32( p, i, s ) ( FT_INT32( FT_INT8_( p, i ) ) << (s) ) +#define FT_INT8_U32( p, i, s ) ( FT_UINT32( FT_INT8_( p, i ) ) << (s) ) + + +#define FT_PEEK_SHORT( p ) FT_INT16( FT_INT8_I16( p, 0, 8) | \ + FT_BYTE_I16( p, 1, 0) ) + +#define FT_PEEK_USHORT( p ) FT_UINT16( FT_BYTE_U16( p, 0, 8 ) | \ + FT_BYTE_U16( p, 1, 0 ) ) + +#define FT_PEEK_LONG( p ) FT_INT32( FT_INT8_I32( p, 0, 24 ) | \ + FT_BYTE_I32( p, 1, 16 ) | \ + FT_BYTE_I32( p, 2, 8 ) | \ + FT_BYTE_I32( p, 3, 0 ) ) + +#define FT_PEEK_ULONG( p ) FT_UINT32( FT_BYTE_U32( p, 0, 24 ) | \ + FT_BYTE_U32( p, 1, 16 ) | \ + FT_BYTE_U32( p, 2, 8 ) | \ + FT_BYTE_U32( p, 3, 0 ) ) + +#define FT_PEEK_OFF3( p ) FT_INT32( FT_INT8_I32( p, 0, 16 ) | \ + FT_BYTE_I32( p, 1, 8 ) | \ + FT_BYTE_I32( p, 2, 0 ) ) + +#define FT_PEEK_UOFF3( p ) FT_UINT32( FT_BYTE_U32( p, 0, 16 ) | \ + FT_BYTE_U32( p, 1, 8 ) | \ + FT_BYTE_U32( p, 2, 0 ) ) + +#define FT_PEEK_SHORT_LE( p ) FT_INT16( FT_INT8_I16( p, 1, 8 ) | \ + FT_BYTE_I16( p, 0, 0 ) ) + +#define FT_PEEK_USHORT_LE( p ) FT_UINT16( FT_BYTE_U16( p, 1, 8 ) | \ + FT_BYTE_U16( p, 0, 0 ) ) + +#define FT_PEEK_LONG_LE( p ) FT_INT32( FT_INT8_I32( p, 3, 24 ) | \ + FT_BYTE_I32( p, 2, 16 ) | \ + FT_BYTE_I32( p, 1, 8 ) | \ + FT_BYTE_I32( p, 0, 0 ) ) + +#define FT_PEEK_ULONG_LE( p ) FT_UINT32( FT_BYTE_U32( p, 3, 24 ) | \ + FT_BYTE_U32( p, 2, 16 ) | \ + FT_BYTE_U32( p, 1, 8 ) | \ + FT_BYTE_U32( p, 0, 0 ) ) + +#define FT_PEEK_OFF3_LE( p ) FT_INT32( FT_INT8_I32( p, 2, 16 ) | \ + FT_BYTE_I32( p, 1, 8 ) | \ + FT_BYTE_I32( p, 0, 0 ) ) + +#define FT_PEEK_UOFF3_LE( p ) FT_UINT32( FT_BYTE_U32( p, 2, 16 ) | \ + FT_BYTE_U32( p, 1, 8 ) | \ + FT_BYTE_U32( p, 0, 0 ) ) + + +#define FT_NEXT_CHAR( buffer ) \ + ( (signed char)*buffer++ ) + +#define FT_NEXT_BYTE( buffer ) \ + ( (unsigned char)*buffer++ ) + +#define FT_NEXT_SHORT( buffer ) \ + ( (short)( buffer += 2, FT_PEEK_SHORT( buffer - 2 ) ) ) + +#define FT_NEXT_USHORT( buffer ) \ + ( (unsigned short)( buffer += 2, FT_PEEK_USHORT( buffer - 2 ) ) ) + +#define FT_NEXT_OFF3( buffer ) \ + ( (long)( buffer += 3, FT_PEEK_OFF3( buffer - 3 ) ) ) + +#define FT_NEXT_UOFF3( buffer ) \ + ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3( buffer - 3 ) ) ) + +#define FT_NEXT_LONG( buffer ) \ + ( (long)( buffer += 4, FT_PEEK_LONG( buffer - 4 ) ) ) + +#define FT_NEXT_ULONG( buffer ) \ + ( (unsigned long)( buffer += 4, FT_PEEK_ULONG( buffer - 4 ) ) ) + + +#define FT_NEXT_SHORT_LE( buffer ) \ + ( (short)( buffer += 2, FT_PEEK_SHORT_LE( buffer - 2 ) ) ) + +#define FT_NEXT_USHORT_LE( buffer ) \ + ( (unsigned short)( buffer += 2, FT_PEEK_USHORT_LE( buffer - 2 ) ) ) + +#define FT_NEXT_OFF3_LE( buffer ) \ + ( (long)( buffer += 3, FT_PEEK_OFF3_LE( buffer - 3 ) ) ) + +#define FT_NEXT_UOFF3_LE( buffer ) \ + ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3_LE( buffer - 3 ) ) ) + +#define FT_NEXT_LONG_LE( buffer ) \ + ( (long)( buffer += 4, FT_PEEK_LONG_LE( buffer - 4 ) ) ) + +#define FT_NEXT_ULONG_LE( buffer ) \ + ( (unsigned long)( buffer += 4, FT_PEEK_ULONG_LE( buffer - 4 ) ) ) + + + /*************************************************************************/ + /* */ + /* Each GET_xxxx() macro uses an implicit `stream' variable. */ + /* */ +#if 0 +#define FT_GET_MACRO( type ) FT_NEXT_ ## type ( stream->cursor ) + +#define FT_GET_CHAR() FT_GET_MACRO( CHAR ) +#define FT_GET_BYTE() FT_GET_MACRO( BYTE ) +#define FT_GET_SHORT() FT_GET_MACRO( SHORT ) +#define FT_GET_USHORT() FT_GET_MACRO( USHORT ) +#define FT_GET_OFF3() FT_GET_MACRO( OFF3 ) +#define FT_GET_UOFF3() FT_GET_MACRO( UOFF3 ) +#define FT_GET_LONG() FT_GET_MACRO( LONG ) +#define FT_GET_ULONG() FT_GET_MACRO( ULONG ) +#define FT_GET_TAG4() FT_GET_MACRO( ULONG ) + +#define FT_GET_SHORT_LE() FT_GET_MACRO( SHORT_LE ) +#define FT_GET_USHORT_LE() FT_GET_MACRO( USHORT_LE ) +#define FT_GET_LONG_LE() FT_GET_MACRO( LONG_LE ) +#define FT_GET_ULONG_LE() FT_GET_MACRO( ULONG_LE ) + +#else +#define FT_GET_MACRO( func, type ) ( (type)func( stream ) ) + +#define FT_GET_CHAR() FT_GET_MACRO( FT_Stream_GetChar, FT_Char ) +#define FT_GET_BYTE() FT_GET_MACRO( FT_Stream_GetChar, FT_Byte ) +#define FT_GET_SHORT() FT_GET_MACRO( FT_Stream_GetUShort, FT_Short ) +#define FT_GET_USHORT() FT_GET_MACRO( FT_Stream_GetUShort, FT_UShort ) +#define FT_GET_OFF3() FT_GET_MACRO( FT_Stream_GetUOffset, FT_Long ) +#define FT_GET_UOFF3() FT_GET_MACRO( FT_Stream_GetUOffset, FT_ULong ) +#define FT_GET_LONG() FT_GET_MACRO( FT_Stream_GetULong, FT_Long ) +#define FT_GET_ULONG() FT_GET_MACRO( FT_Stream_GetULong, FT_ULong ) +#define FT_GET_TAG4() FT_GET_MACRO( FT_Stream_GetULong, FT_ULong ) + +#define FT_GET_SHORT_LE() FT_GET_MACRO( FT_Stream_GetUShortLE, FT_Short ) +#define FT_GET_USHORT_LE() FT_GET_MACRO( FT_Stream_GetUShortLE, FT_UShort ) +#define FT_GET_LONG_LE() FT_GET_MACRO( FT_Stream_GetULongLE, FT_Long ) +#define FT_GET_ULONG_LE() FT_GET_MACRO( FT_Stream_GetULongLE, FT_ULong ) +#endif + +#define FT_READ_MACRO( func, type, var ) \ + ( var = (type)func( stream, &error ), \ + error != FT_Err_Ok ) + +#define FT_READ_BYTE( var ) FT_READ_MACRO( FT_Stream_ReadChar, FT_Byte, var ) +#define FT_READ_CHAR( var ) FT_READ_MACRO( FT_Stream_ReadChar, FT_Char, var ) +#define FT_READ_SHORT( var ) FT_READ_MACRO( FT_Stream_ReadUShort, FT_Short, var ) +#define FT_READ_USHORT( var ) FT_READ_MACRO( FT_Stream_ReadUShort, FT_UShort, var ) +#define FT_READ_OFF3( var ) FT_READ_MACRO( FT_Stream_ReadUOffset, FT_Long, var ) +#define FT_READ_UOFF3( var ) FT_READ_MACRO( FT_Stream_ReadUOffset, FT_ULong, var ) +#define FT_READ_LONG( var ) FT_READ_MACRO( FT_Stream_ReadULong, FT_Long, var ) +#define FT_READ_ULONG( var ) FT_READ_MACRO( FT_Stream_ReadULong, FT_ULong, var ) + +#define FT_READ_SHORT_LE( var ) FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_Short, var ) +#define FT_READ_USHORT_LE( var ) FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_UShort, var ) +#define FT_READ_LONG_LE( var ) FT_READ_MACRO( FT_Stream_ReadULongLE, FT_Long, var ) +#define FT_READ_ULONG_LE( var ) FT_READ_MACRO( FT_Stream_ReadULongLE, FT_ULong, var ) + + +#ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM + + /* initialize a stream for reading a regular system stream */ + FT_BASE( FT_Error ) + FT_Stream_Open( FT_Stream stream, + const char* filepathname ); + +#endif /* FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */ + + + /* create a new (input) stream from an FT_Open_Args structure */ + FT_BASE( FT_Error ) + FT_Stream_New( FT_Library library, + const FT_Open_Args* args, + FT_Stream *astream ); + + /* free a stream */ + FT_BASE( void ) + FT_Stream_Free( FT_Stream stream, + FT_Int external ); + + /* initialize a stream for reading in-memory data */ + FT_BASE( void ) + FT_Stream_OpenMemory( FT_Stream stream, + const FT_Byte* base, + FT_ULong size ); + + /* close a stream (does not destroy the stream structure) */ + FT_BASE( void ) + FT_Stream_Close( FT_Stream stream ); + + + /* seek within a stream. position is relative to start of stream */ + FT_BASE( FT_Error ) + FT_Stream_Seek( FT_Stream stream, + FT_ULong pos ); + + /* skip bytes in a stream */ + FT_BASE( FT_Error ) + FT_Stream_Skip( FT_Stream stream, + FT_Long distance ); + + /* return current stream position */ + FT_BASE( FT_Long ) + FT_Stream_Pos( FT_Stream stream ); + + /* read bytes from a stream into a user-allocated buffer, returns an */ + /* error if not all bytes could be read. */ + FT_BASE( FT_Error ) + FT_Stream_Read( FT_Stream stream, + FT_Byte* buffer, + FT_ULong count ); + + /* read bytes from a stream at a given position */ + FT_BASE( FT_Error ) + FT_Stream_ReadAt( FT_Stream stream, + FT_ULong pos, + FT_Byte* buffer, + FT_ULong count ); + + /* try to read bytes at the end of a stream; return number of bytes */ + /* really available */ + FT_BASE( FT_ULong ) + FT_Stream_TryRead( FT_Stream stream, + FT_Byte* buffer, + FT_ULong count ); + + /* Enter a frame of `count' consecutive bytes in a stream. Returns an */ + /* error if the frame could not be read/accessed. The caller can use */ + /* the FT_Stream_Get_XXX functions to retrieve frame data without */ + /* error checks. */ + /* */ + /* You must _always_ call FT_Stream_ExitFrame() once you have entered */ + /* a stream frame! */ + /* */ + FT_BASE( FT_Error ) + FT_Stream_EnterFrame( FT_Stream stream, + FT_ULong count ); + + /* exit a stream frame */ + FT_BASE( void ) + FT_Stream_ExitFrame( FT_Stream stream ); + + /* Extract a stream frame. If the stream is disk-based, a heap block */ + /* is allocated and the frame bytes are read into it. If the stream */ + /* is memory-based, this function simply set a pointer to the data. */ + /* */ + /* Useful to optimize access to memory-based streams transparently. */ + /* */ + /* All extracted frames must be `freed' with a call to the function */ + /* FT_Stream_ReleaseFrame(). */ + /* */ + FT_BASE( FT_Error ) + FT_Stream_ExtractFrame( FT_Stream stream, + FT_ULong count, + FT_Byte** pbytes ); + + /* release an extract frame (see FT_Stream_ExtractFrame) */ + FT_BASE( void ) + FT_Stream_ReleaseFrame( FT_Stream stream, + FT_Byte** pbytes ); + + /* read a byte from an entered frame */ + FT_BASE( FT_Char ) + FT_Stream_GetChar( FT_Stream stream ); + + /* read a 16-bit big-endian unsigned integer from an entered frame */ + FT_BASE( FT_UShort ) + FT_Stream_GetUShort( FT_Stream stream ); + + /* read a 24-bit big-endian unsigned integer from an entered frame */ + FT_BASE( FT_ULong ) + FT_Stream_GetUOffset( FT_Stream stream ); + + /* read a 32-bit big-endian unsigned integer from an entered frame */ + FT_BASE( FT_ULong ) + FT_Stream_GetULong( FT_Stream stream ); + + /* read a 16-bit little-endian unsigned integer from an entered frame */ + FT_BASE( FT_UShort ) + FT_Stream_GetUShortLE( FT_Stream stream ); + + /* read a 32-bit little-endian unsigned integer from an entered frame */ + FT_BASE( FT_ULong ) + FT_Stream_GetULongLE( FT_Stream stream ); + + + /* read a byte from a stream */ + FT_BASE( FT_Char ) + FT_Stream_ReadChar( FT_Stream stream, + FT_Error* error ); + + /* read a 16-bit big-endian unsigned integer from a stream */ + FT_BASE( FT_UShort ) + FT_Stream_ReadUShort( FT_Stream stream, + FT_Error* error ); + + /* read a 24-bit big-endian unsigned integer from a stream */ + FT_BASE( FT_ULong ) + FT_Stream_ReadUOffset( FT_Stream stream, + FT_Error* error ); + + /* read a 32-bit big-endian integer from a stream */ + FT_BASE( FT_ULong ) + FT_Stream_ReadULong( FT_Stream stream, + FT_Error* error ); + + /* read a 16-bit little-endian unsigned integer from a stream */ + FT_BASE( FT_UShort ) + FT_Stream_ReadUShortLE( FT_Stream stream, + FT_Error* error ); + + /* read a 32-bit little-endian unsigned integer from a stream */ + FT_BASE( FT_ULong ) + FT_Stream_ReadULongLE( FT_Stream stream, + FT_Error* error ); + + /* Read a structure from a stream. The structure must be described */ + /* by an array of FT_Frame_Field records. */ + FT_BASE( FT_Error ) + FT_Stream_ReadFields( FT_Stream stream, + const FT_Frame_Field* fields, + void* structure ); + + +#define FT_STREAM_POS() \ + FT_Stream_Pos( stream ) + +#define FT_STREAM_SEEK( position ) \ + FT_SET_ERROR( FT_Stream_Seek( stream, position ) ) + +#define FT_STREAM_SKIP( distance ) \ + FT_SET_ERROR( FT_Stream_Skip( stream, distance ) ) + +#define FT_STREAM_READ( buffer, count ) \ + FT_SET_ERROR( FT_Stream_Read( stream, \ + (FT_Byte*)buffer, \ + count ) ) + +#define FT_STREAM_READ_AT( position, buffer, count ) \ + FT_SET_ERROR( FT_Stream_ReadAt( stream, \ + position, \ + (FT_Byte*)buffer, \ + count ) ) + +#define FT_STREAM_READ_FIELDS( fields, object ) \ + FT_SET_ERROR( FT_Stream_ReadFields( stream, fields, object ) ) + + +#define FT_FRAME_ENTER( size ) \ + FT_SET_ERROR( \ + FT_DEBUG_INNER( FT_Stream_EnterFrame( stream, size ) ) ) + +#define FT_FRAME_EXIT() \ + FT_DEBUG_INNER( FT_Stream_ExitFrame( stream ) ) + +#define FT_FRAME_EXTRACT( size, bytes ) \ + FT_SET_ERROR( \ + FT_DEBUG_INNER( FT_Stream_ExtractFrame( stream, size, \ + (FT_Byte**)&(bytes) ) ) ) + +#define FT_FRAME_RELEASE( bytes ) \ + FT_DEBUG_INNER( FT_Stream_ReleaseFrame( stream, \ + (FT_Byte**)&(bytes) ) ) + + +FT_END_HEADER + +#endif /* __FTSTREAM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/fttrace.h b/other/freetype/include/freetype/internal/fttrace.h new file mode 100644 index 0000000..fbefdbd --- /dev/null +++ b/other/freetype/include/freetype/internal/fttrace.h @@ -0,0 +1,144 @@ +/***************************************************************************/ +/* */ +/* fttrace.h */ +/* */ +/* Tracing handling (specification only). */ +/* */ +/* Copyright 2002, 2004-2007, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /* definitions of trace levels for FreeType 2 */ + + /* the first level must always be `trace_any' */ +FT_TRACE_DEF( any ) + + /* base components */ +FT_TRACE_DEF( calc ) /* calculations (ftcalc.c) */ +FT_TRACE_DEF( memory ) /* memory manager (ftobjs.c) */ +FT_TRACE_DEF( stream ) /* stream manager (ftstream.c) */ +FT_TRACE_DEF( io ) /* i/o interface (ftsystem.c) */ +FT_TRACE_DEF( list ) /* list management (ftlist.c) */ +FT_TRACE_DEF( init ) /* initialization (ftinit.c) */ +FT_TRACE_DEF( objs ) /* base objects (ftobjs.c) */ +FT_TRACE_DEF( outline ) /* outline management (ftoutln.c) */ +FT_TRACE_DEF( glyph ) /* glyph management (ftglyph.c) */ +FT_TRACE_DEF( gloader ) /* glyph loader (ftgloadr.c) */ + +FT_TRACE_DEF( raster ) /* monochrome rasterizer (ftraster.c) */ +FT_TRACE_DEF( smooth ) /* anti-aliasing raster (ftgrays.c) */ +FT_TRACE_DEF( mm ) /* MM interface (ftmm.c) */ +FT_TRACE_DEF( raccess ) /* resource fork accessor (ftrfork.c) */ +FT_TRACE_DEF( synth ) /* bold/slant synthesizer (ftsynth.c) */ + + /* Cache sub-system */ +FT_TRACE_DEF( cache ) /* cache sub-system (ftcache.c, etc.) */ + + /* SFNT driver components */ +FT_TRACE_DEF( sfdriver ) /* SFNT font driver (sfdriver.c) */ +FT_TRACE_DEF( sfobjs ) /* SFNT object handler (sfobjs.c) */ +FT_TRACE_DEF( ttcmap ) /* charmap handler (ttcmap.c) */ +FT_TRACE_DEF( ttkern ) /* kerning handler (ttkern.c) */ +FT_TRACE_DEF( ttload ) /* basic TrueType tables (ttload.c) */ +FT_TRACE_DEF( ttmtx ) /* metrics-related tables (ttmtx.c) */ +FT_TRACE_DEF( ttpost ) /* PS table processing (ttpost.c) */ +FT_TRACE_DEF( ttsbit ) /* TrueType sbit handling (ttsbit.c) */ +FT_TRACE_DEF( ttbdf ) /* TrueType embedded BDF (ttbdf.c) */ + + /* TrueType driver components */ +FT_TRACE_DEF( ttdriver ) /* TT font driver (ttdriver.c) */ +FT_TRACE_DEF( ttgload ) /* TT glyph loader (ttgload.c) */ +FT_TRACE_DEF( ttinterp ) /* bytecode interpreter (ttinterp.c) */ +FT_TRACE_DEF( ttobjs ) /* TT objects manager (ttobjs.c) */ +FT_TRACE_DEF( ttpload ) /* TT data/program loader (ttpload.c) */ +FT_TRACE_DEF( ttgxvar ) /* TrueType GX var handler (ttgxvar.c) */ + + /* Type 1 driver components */ +FT_TRACE_DEF( t1afm ) +FT_TRACE_DEF( t1driver ) +FT_TRACE_DEF( t1gload ) +FT_TRACE_DEF( t1hint ) +FT_TRACE_DEF( t1load ) +FT_TRACE_DEF( t1objs ) +FT_TRACE_DEF( t1parse ) + + /* PostScript helper module `psaux' */ +FT_TRACE_DEF( t1decode ) +FT_TRACE_DEF( psobjs ) + + /* PostScript hinting module `pshinter' */ +FT_TRACE_DEF( pshrec ) +FT_TRACE_DEF( pshalgo1 ) +FT_TRACE_DEF( pshalgo2 ) + + /* Type 2 driver components */ +FT_TRACE_DEF( cffdriver ) +FT_TRACE_DEF( cffgload ) +FT_TRACE_DEF( cffload ) +FT_TRACE_DEF( cffobjs ) +FT_TRACE_DEF( cffparse ) + + /* Type 42 driver component */ +FT_TRACE_DEF( t42 ) + + /* CID driver components */ +FT_TRACE_DEF( cidafm ) +FT_TRACE_DEF( ciddriver ) +FT_TRACE_DEF( cidgload ) +FT_TRACE_DEF( cidload ) +FT_TRACE_DEF( cidobjs ) +FT_TRACE_DEF( cidparse ) + + /* Windows font component */ +FT_TRACE_DEF( winfnt ) + + /* PCF font components */ +FT_TRACE_DEF( pcfdriver ) +FT_TRACE_DEF( pcfread ) + + /* BDF font components */ +FT_TRACE_DEF( bdfdriver ) +FT_TRACE_DEF( bdflib ) + + /* PFR font component */ +FT_TRACE_DEF( pfr ) + + /* OpenType validation components */ +FT_TRACE_DEF( otvmodule ) +FT_TRACE_DEF( otvcommon ) +FT_TRACE_DEF( otvbase ) +FT_TRACE_DEF( otvgdef ) +FT_TRACE_DEF( otvgpos ) +FT_TRACE_DEF( otvgsub ) +FT_TRACE_DEF( otvjstf ) +FT_TRACE_DEF( otvmath ) + + /* TrueTypeGX/AAT validation components */ +FT_TRACE_DEF( gxvmodule ) +FT_TRACE_DEF( gxvcommon ) +FT_TRACE_DEF( gxvfeat ) +FT_TRACE_DEF( gxvmort ) +FT_TRACE_DEF( gxvmorx ) +FT_TRACE_DEF( gxvbsln ) +FT_TRACE_DEF( gxvjust ) +FT_TRACE_DEF( gxvkern ) +FT_TRACE_DEF( gxvopbd ) +FT_TRACE_DEF( gxvtrak ) +FT_TRACE_DEF( gxvprop ) +FT_TRACE_DEF( gxvlcar ) + + /* autofit components */ +FT_TRACE_DEF( afcjk ) +FT_TRACE_DEF( aflatin ) +FT_TRACE_DEF( aflatin2 ) +FT_TRACE_DEF( afwarp ) + +/* END */ diff --git a/other/freetype/include/freetype/internal/ftvalid.h b/other/freetype/include/freetype/internal/ftvalid.h new file mode 100644 index 0000000..00cd85e --- /dev/null +++ b/other/freetype/include/freetype/internal/ftvalid.h @@ -0,0 +1,150 @@ +/***************************************************************************/ +/* */ +/* ftvalid.h */ +/* */ +/* FreeType validation support (specification). */ +/* */ +/* Copyright 2004 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __FTVALID_H__ +#define __FTVALID_H__ + +#include <ft2build.h> +#include FT_CONFIG_STANDARD_LIBRARY_H /* for ft_setjmp and ft_longjmp */ + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /**** ****/ + /**** ****/ + /**** V A L I D A T I O N ****/ + /**** ****/ + /**** ****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /* handle to a validation object */ + typedef struct FT_ValidatorRec_ volatile* FT_Validator; + + + /*************************************************************************/ + /* */ + /* There are three distinct validation levels defined here: */ + /* */ + /* FT_VALIDATE_DEFAULT :: */ + /* A table that passes this validation level can be used reliably by */ + /* FreeType. It generally means that all offsets have been checked to */ + /* prevent out-of-bound reads, that array counts are correct, etc. */ + /* */ + /* FT_VALIDATE_TIGHT :: */ + /* A table that passes this validation level can be used reliably and */ + /* doesn't contain invalid data. For example, a charmap table that */ + /* returns invalid glyph indices will not pass, even though it can */ + /* be used with FreeType in default mode (the library will simply */ + /* return an error later when trying to load the glyph). */ + /* */ + /* It also checks that fields which must be a multiple of 2, 4, or 8, */ + /* don't have incorrect values, etc. */ + /* */ + /* FT_VALIDATE_PARANOID :: */ + /* Only for font debugging. Checks that a table follows the */ + /* specification by 100%. Very few fonts will be able to pass this */ + /* level anyway but it can be useful for certain tools like font */ + /* editors/converters. */ + /* */ + typedef enum FT_ValidationLevel_ + { + FT_VALIDATE_DEFAULT = 0, + FT_VALIDATE_TIGHT, + FT_VALIDATE_PARANOID + + } FT_ValidationLevel; + + + /* validator structure */ + typedef struct FT_ValidatorRec_ + { + const FT_Byte* base; /* address of table in memory */ + const FT_Byte* limit; /* `base' + sizeof(table) in memory */ + FT_ValidationLevel level; /* validation level */ + FT_Error error; /* error returned. 0 means success */ + + ft_jmp_buf jump_buffer; /* used for exception handling */ + + } FT_ValidatorRec; + + +#define FT_VALIDATOR( x ) ((FT_Validator)( x )) + + + FT_BASE( void ) + ft_validator_init( FT_Validator valid, + const FT_Byte* base, + const FT_Byte* limit, + FT_ValidationLevel level ); + + /* Do not use this. It's broken and will cause your validator to crash */ + /* if you run it on an invalid font. */ + FT_BASE( FT_Int ) + ft_validator_run( FT_Validator valid ); + + /* Sets the error field in a validator, then calls `longjmp' to return */ + /* to high-level caller. Using `setjmp/longjmp' avoids many stupid */ + /* error checks within the validation routines. */ + /* */ + FT_BASE( void ) + ft_validator_error( FT_Validator valid, + FT_Error error ); + + + /* Calls ft_validate_error. Assumes that the `valid' local variable */ + /* holds a pointer to the current validator object. */ + /* */ + /* Use preprocessor prescan to pass FT_ERR_PREFIX. */ + /* */ +#define FT_INVALID( _prefix, _error ) FT_INVALID_( _prefix, _error ) +#define FT_INVALID_( _prefix, _error ) \ + ft_validator_error( valid, _prefix ## _error ) + + /* called when a broken table is detected */ +#define FT_INVALID_TOO_SHORT \ + FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) + + /* called when an invalid offset is detected */ +#define FT_INVALID_OFFSET \ + FT_INVALID( FT_ERR_PREFIX, Invalid_Offset ) + + /* called when an invalid format/value is detected */ +#define FT_INVALID_FORMAT \ + FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) + + /* called when an invalid glyph index is detected */ +#define FT_INVALID_GLYPH_ID \ + FT_INVALID( FT_ERR_PREFIX, Invalid_Glyph_Index ) + + /* called when an invalid field value is detected */ +#define FT_INVALID_DATA \ + FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) + + +FT_END_HEADER + +#endif /* __FTVALID_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/internal.h b/other/freetype/include/freetype/internal/internal.h new file mode 100644 index 0000000..f500a65 --- /dev/null +++ b/other/freetype/include/freetype/internal/internal.h @@ -0,0 +1,51 @@ +/***************************************************************************/ +/* */ +/* internal.h */ +/* */ +/* Internal header files (specification only). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file is automatically included by `ft2build.h'. */ + /* Do not include it manually! */ + /* */ + /*************************************************************************/ + + +#define FT_INTERNAL_OBJECTS_H <freetype/internal/ftobjs.h> +#define FT_INTERNAL_PIC_H <freetype/internal/ftpic.h> +#define FT_INTERNAL_STREAM_H <freetype/internal/ftstream.h> +#define FT_INTERNAL_MEMORY_H <freetype/internal/ftmemory.h> +#define FT_INTERNAL_DEBUG_H <freetype/internal/ftdebug.h> +#define FT_INTERNAL_CALC_H <freetype/internal/ftcalc.h> +#define FT_INTERNAL_DRIVER_H <freetype/internal/ftdriver.h> +#define FT_INTERNAL_TRACE_H <freetype/internal/fttrace.h> +#define FT_INTERNAL_GLYPH_LOADER_H <freetype/internal/ftgloadr.h> +#define FT_INTERNAL_SFNT_H <freetype/internal/sfnt.h> +#define FT_INTERNAL_SERVICE_H <freetype/internal/ftserv.h> +#define FT_INTERNAL_RFORK_H <freetype/internal/ftrfork.h> +#define FT_INTERNAL_VALIDATE_H <freetype/internal/ftvalid.h> + +#define FT_INTERNAL_TRUETYPE_TYPES_H <freetype/internal/tttypes.h> +#define FT_INTERNAL_TYPE1_TYPES_H <freetype/internal/t1types.h> + +#define FT_INTERNAL_POSTSCRIPT_AUX_H <freetype/internal/psaux.h> +#define FT_INTERNAL_POSTSCRIPT_HINTS_H <freetype/internal/pshints.h> +#define FT_INTERNAL_POSTSCRIPT_GLOBALS_H <freetype/internal/psglobal.h> + +#define FT_INTERNAL_AUTOHINT_H <freetype/internal/autohint.h> + + +/* END */ diff --git a/other/freetype/include/freetype/internal/psaux.h b/other/freetype/include/freetype/internal/psaux.h new file mode 100644 index 0000000..a96e0df --- /dev/null +++ b/other/freetype/include/freetype/internal/psaux.h @@ -0,0 +1,873 @@ +/***************************************************************************/ +/* */ +/* psaux.h */ +/* */ +/* Auxiliary functions and data structures related to PostScript fonts */ +/* (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2006, 2008, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __PSAUX_H__ +#define __PSAUX_H__ + + +#include <ft2build.h> +#include FT_INTERNAL_OBJECTS_H +#include FT_INTERNAL_TYPE1_TYPES_H +#include FT_SERVICE_POSTSCRIPT_CMAPS_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** T1_TABLE *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + + typedef struct PS_TableRec_* PS_Table; + typedef const struct PS_Table_FuncsRec_* PS_Table_Funcs; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_Table_FuncsRec */ + /* */ + /* <Description> */ + /* A set of function pointers to manage PS_Table objects. */ + /* */ + /* <Fields> */ + /* table_init :: Used to initialize a table. */ + /* */ + /* table_done :: Finalizes resp. destroy a given table. */ + /* */ + /* table_add :: Adds a new object to a table. */ + /* */ + /* table_release :: Releases table data, then finalizes it. */ + /* */ + typedef struct PS_Table_FuncsRec_ + { + FT_Error + (*init)( PS_Table table, + FT_Int count, + FT_Memory memory ); + + void + (*done)( PS_Table table ); + + FT_Error + (*add)( PS_Table table, + FT_Int idx, + void* object, + FT_PtrDist length ); + + void + (*release)( PS_Table table ); + + } PS_Table_FuncsRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_TableRec */ + /* */ + /* <Description> */ + /* A PS_Table is a simple object used to store an array of objects in */ + /* a single memory block. */ + /* */ + /* <Fields> */ + /* block :: The address in memory of the growheap's block. This */ + /* can change between two object adds, due to */ + /* reallocation. */ + /* */ + /* cursor :: The current top of the grow heap within its block. */ + /* */ + /* capacity :: The current size of the heap block. Increments by */ + /* 1kByte chunks. */ + /* */ + /* max_elems :: The maximum number of elements in table. */ + /* */ + /* num_elems :: The current number of elements in table. */ + /* */ + /* elements :: A table of element addresses within the block. */ + /* */ + /* lengths :: A table of element sizes within the block. */ + /* */ + /* memory :: The object used for memory operations */ + /* (alloc/realloc). */ + /* */ + /* funcs :: A table of method pointers for this object. */ + /* */ + typedef struct PS_TableRec_ + { + FT_Byte* block; /* current memory block */ + FT_Offset cursor; /* current cursor in memory block */ + FT_Offset capacity; /* current size of memory block */ + FT_Long init; + + FT_Int max_elems; + FT_Int num_elems; + FT_Byte** elements; /* addresses of table elements */ + FT_PtrDist* lengths; /* lengths of table elements */ + + FT_Memory memory; + PS_Table_FuncsRec funcs; + + } PS_TableRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** T1 FIELDS & TOKENS *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef struct PS_ParserRec_* PS_Parser; + + typedef struct T1_TokenRec_* T1_Token; + + typedef struct T1_FieldRec_* T1_Field; + + + /* simple enumeration type used to identify token types */ + typedef enum T1_TokenType_ + { + T1_TOKEN_TYPE_NONE = 0, + T1_TOKEN_TYPE_ANY, + T1_TOKEN_TYPE_STRING, + T1_TOKEN_TYPE_ARRAY, + T1_TOKEN_TYPE_KEY, /* aka `name' */ + + /* do not remove */ + T1_TOKEN_TYPE_MAX + + } T1_TokenType; + + + /* a simple structure used to identify tokens */ + typedef struct T1_TokenRec_ + { + FT_Byte* start; /* first character of token in input stream */ + FT_Byte* limit; /* first character after the token */ + T1_TokenType type; /* type of token */ + + } T1_TokenRec; + + + /* enumeration type used to identify object fields */ + typedef enum T1_FieldType_ + { + T1_FIELD_TYPE_NONE = 0, + T1_FIELD_TYPE_BOOL, + T1_FIELD_TYPE_INTEGER, + T1_FIELD_TYPE_FIXED, + T1_FIELD_TYPE_FIXED_1000, + T1_FIELD_TYPE_STRING, + T1_FIELD_TYPE_KEY, + T1_FIELD_TYPE_BBOX, + T1_FIELD_TYPE_INTEGER_ARRAY, + T1_FIELD_TYPE_FIXED_ARRAY, + T1_FIELD_TYPE_CALLBACK, + + /* do not remove */ + T1_FIELD_TYPE_MAX + + } T1_FieldType; + + + typedef enum T1_FieldLocation_ + { + T1_FIELD_LOCATION_CID_INFO, + T1_FIELD_LOCATION_FONT_DICT, + T1_FIELD_LOCATION_FONT_EXTRA, + T1_FIELD_LOCATION_FONT_INFO, + T1_FIELD_LOCATION_PRIVATE, + T1_FIELD_LOCATION_BBOX, + T1_FIELD_LOCATION_LOADER, + T1_FIELD_LOCATION_FACE, + T1_FIELD_LOCATION_BLEND, + + /* do not remove */ + T1_FIELD_LOCATION_MAX + + } T1_FieldLocation; + + + typedef void + (*T1_Field_ParseFunc)( FT_Face face, + FT_Pointer parser ); + + + /* structure type used to model object fields */ + typedef struct T1_FieldRec_ + { + const char* ident; /* field identifier */ + T1_FieldLocation location; + T1_FieldType type; /* type of field */ + T1_Field_ParseFunc reader; + FT_UInt offset; /* offset of field in object */ + FT_Byte size; /* size of field in bytes */ + FT_UInt array_max; /* maximal number of elements for */ + /* array */ + FT_UInt count_offset; /* offset of element count for */ + /* arrays; must not be zero if in */ + /* use -- in other words, a */ + /* `num_FOO' element must not */ + /* start the used structure if we */ + /* parse a `FOO' array */ + FT_UInt dict; /* where we expect it */ + } T1_FieldRec; + +#define T1_FIELD_DICT_FONTDICT ( 1 << 0 ) /* also FontInfo and FDArray */ +#define T1_FIELD_DICT_PRIVATE ( 1 << 1 ) + + + +#define T1_NEW_SIMPLE_FIELD( _ident, _type, _fname, _dict ) \ + { \ + _ident, T1CODE, _type, \ + 0, \ + FT_FIELD_OFFSET( _fname ), \ + FT_FIELD_SIZE( _fname ), \ + 0, 0, \ + _dict \ + }, + +#define T1_NEW_CALLBACK_FIELD( _ident, _reader, _dict ) \ + { \ + _ident, T1CODE, T1_FIELD_TYPE_CALLBACK, \ + (T1_Field_ParseFunc)_reader, \ + 0, 0, \ + 0, 0, \ + _dict \ + }, + +#define T1_NEW_TABLE_FIELD( _ident, _type, _fname, _max, _dict ) \ + { \ + _ident, T1CODE, _type, \ + 0, \ + FT_FIELD_OFFSET( _fname ), \ + FT_FIELD_SIZE_DELTA( _fname ), \ + _max, \ + FT_FIELD_OFFSET( num_ ## _fname ), \ + _dict \ + }, + +#define T1_NEW_TABLE_FIELD2( _ident, _type, _fname, _max, _dict ) \ + { \ + _ident, T1CODE, _type, \ + 0, \ + FT_FIELD_OFFSET( _fname ), \ + FT_FIELD_SIZE_DELTA( _fname ), \ + _max, 0, \ + _dict \ + }, + + +#define T1_FIELD_BOOL( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BOOL, _fname, _dict ) + +#define T1_FIELD_NUM( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER, _fname, _dict ) + +#define T1_FIELD_FIXED( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED, _fname, _dict ) + +#define T1_FIELD_FIXED_1000( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_1000, _fname, \ + _dict ) + +#define T1_FIELD_STRING( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_STRING, _fname, _dict ) + +#define T1_FIELD_KEY( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_KEY, _fname, _dict ) + +#define T1_FIELD_BBOX( _ident, _fname, _dict ) \ + T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BBOX, _fname, _dict ) + + +#define T1_FIELD_NUM_TABLE( _ident, _fname, _fmax, _dict ) \ + T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \ + _fname, _fmax, _dict ) + +#define T1_FIELD_FIXED_TABLE( _ident, _fname, _fmax, _dict ) \ + T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \ + _fname, _fmax, _dict ) + +#define T1_FIELD_NUM_TABLE2( _ident, _fname, _fmax, _dict ) \ + T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \ + _fname, _fmax, _dict ) + +#define T1_FIELD_FIXED_TABLE2( _ident, _fname, _fmax, _dict ) \ + T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \ + _fname, _fmax, _dict ) + +#define T1_FIELD_CALLBACK( _ident, _name, _dict ) \ + T1_NEW_CALLBACK_FIELD( _ident, _name, _dict ) + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** T1 PARSER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef const struct PS_Parser_FuncsRec_* PS_Parser_Funcs; + + typedef struct PS_Parser_FuncsRec_ + { + void + (*init)( PS_Parser parser, + FT_Byte* base, + FT_Byte* limit, + FT_Memory memory ); + + void + (*done)( PS_Parser parser ); + + void + (*skip_spaces)( PS_Parser parser ); + void + (*skip_PS_token)( PS_Parser parser ); + + FT_Long + (*to_int)( PS_Parser parser ); + FT_Fixed + (*to_fixed)( PS_Parser parser, + FT_Int power_ten ); + + FT_Error + (*to_bytes)( PS_Parser parser, + FT_Byte* bytes, + FT_Offset max_bytes, + FT_Long* pnum_bytes, + FT_Bool delimiters ); + + FT_Int + (*to_coord_array)( PS_Parser parser, + FT_Int max_coords, + FT_Short* coords ); + FT_Int + (*to_fixed_array)( PS_Parser parser, + FT_Int max_values, + FT_Fixed* values, + FT_Int power_ten ); + + void + (*to_token)( PS_Parser parser, + T1_Token token ); + void + (*to_token_array)( PS_Parser parser, + T1_Token tokens, + FT_UInt max_tokens, + FT_Int* pnum_tokens ); + + FT_Error + (*load_field)( PS_Parser parser, + const T1_Field field, + void** objects, + FT_UInt max_objects, + FT_ULong* pflags ); + + FT_Error + (*load_field_table)( PS_Parser parser, + const T1_Field field, + void** objects, + FT_UInt max_objects, + FT_ULong* pflags ); + + } PS_Parser_FuncsRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_ParserRec */ + /* */ + /* <Description> */ + /* A PS_Parser is an object used to parse a Type 1 font very quickly. */ + /* */ + /* <Fields> */ + /* cursor :: The current position in the text. */ + /* */ + /* base :: Start of the processed text. */ + /* */ + /* limit :: End of the processed text. */ + /* */ + /* error :: The last error returned. */ + /* */ + /* memory :: The object used for memory operations (alloc/realloc). */ + /* */ + /* funcs :: A table of functions for the parser. */ + /* */ + typedef struct PS_ParserRec_ + { + FT_Byte* cursor; + FT_Byte* base; + FT_Byte* limit; + FT_Error error; + FT_Memory memory; + + PS_Parser_FuncsRec funcs; + + } PS_ParserRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** T1 BUILDER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + + typedef struct T1_BuilderRec_* T1_Builder; + + + typedef FT_Error + (*T1_Builder_Check_Points_Func)( T1_Builder builder, + FT_Int count ); + + typedef void + (*T1_Builder_Add_Point_Func)( T1_Builder builder, + FT_Pos x, + FT_Pos y, + FT_Byte flag ); + + typedef FT_Error + (*T1_Builder_Add_Point1_Func)( T1_Builder builder, + FT_Pos x, + FT_Pos y ); + + typedef FT_Error + (*T1_Builder_Add_Contour_Func)( T1_Builder builder ); + + typedef FT_Error + (*T1_Builder_Start_Point_Func)( T1_Builder builder, + FT_Pos x, + FT_Pos y ); + + typedef void + (*T1_Builder_Close_Contour_Func)( T1_Builder builder ); + + + typedef const struct T1_Builder_FuncsRec_* T1_Builder_Funcs; + + typedef struct T1_Builder_FuncsRec_ + { + void + (*init)( T1_Builder builder, + FT_Face face, + FT_Size size, + FT_GlyphSlot slot, + FT_Bool hinting ); + + void + (*done)( T1_Builder builder ); + + T1_Builder_Check_Points_Func check_points; + T1_Builder_Add_Point_Func add_point; + T1_Builder_Add_Point1_Func add_point1; + T1_Builder_Add_Contour_Func add_contour; + T1_Builder_Start_Point_Func start_point; + T1_Builder_Close_Contour_Func close_contour; + + } T1_Builder_FuncsRec; + + + /* an enumeration type to handle charstring parsing states */ + typedef enum T1_ParseState_ + { + T1_Parse_Start, + T1_Parse_Have_Width, + T1_Parse_Have_Moveto, + T1_Parse_Have_Path + + } T1_ParseState; + + + /*************************************************************************/ + /* */ + /* <Structure> */ + /* T1_BuilderRec */ + /* */ + /* <Description> */ + /* A structure used during glyph loading to store its outline. */ + /* */ + /* <Fields> */ + /* memory :: The current memory object. */ + /* */ + /* face :: The current face object. */ + /* */ + /* glyph :: The current glyph slot. */ + /* */ + /* loader :: XXX */ + /* */ + /* base :: The base glyph outline. */ + /* */ + /* current :: The current glyph outline. */ + /* */ + /* max_points :: maximum points in builder outline */ + /* */ + /* max_contours :: Maximal number of contours in builder outline. */ + /* */ + /* pos_x :: The horizontal translation (if composite glyph). */ + /* */ + /* pos_y :: The vertical translation (if composite glyph). */ + /* */ + /* left_bearing :: The left side bearing point. */ + /* */ + /* advance :: The horizontal advance vector. */ + /* */ + /* bbox :: Unused. */ + /* */ + /* parse_state :: An enumeration which controls the charstring */ + /* parsing state. */ + /* */ + /* load_points :: If this flag is not set, no points are loaded. */ + /* */ + /* no_recurse :: Set but not used. */ + /* */ + /* metrics_only :: A boolean indicating that we only want to compute */ + /* the metrics of a given glyph, not load all of its */ + /* points. */ + /* */ + /* funcs :: An array of function pointers for the builder. */ + /* */ + typedef struct T1_BuilderRec_ + { + FT_Memory memory; + FT_Face face; + FT_GlyphSlot glyph; + FT_GlyphLoader loader; + FT_Outline* base; + FT_Outline* current; + + FT_Pos pos_x; + FT_Pos pos_y; + + FT_Vector left_bearing; + FT_Vector advance; + + FT_BBox bbox; /* bounding box */ + T1_ParseState parse_state; + FT_Bool load_points; + FT_Bool no_recurse; + + FT_Bool metrics_only; + + void* hints_funcs; /* hinter-specific */ + void* hints_globals; /* hinter-specific */ + + T1_Builder_FuncsRec funcs; + + } T1_BuilderRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** T1 DECODER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + +#if 0 + + /*************************************************************************/ + /* */ + /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine */ + /* calls during glyph loading. */ + /* */ +#define T1_MAX_SUBRS_CALLS 8 + + + /*************************************************************************/ + /* */ + /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity. A */ + /* minimum of 16 is required. */ + /* */ +#define T1_MAX_CHARSTRINGS_OPERANDS 32 + +#endif /* 0 */ + + + typedef struct T1_Decoder_ZoneRec_ + { + FT_Byte* cursor; + FT_Byte* base; + FT_Byte* limit; + + } T1_Decoder_ZoneRec, *T1_Decoder_Zone; + + + typedef struct T1_DecoderRec_* T1_Decoder; + typedef const struct T1_Decoder_FuncsRec_* T1_Decoder_Funcs; + + + typedef FT_Error + (*T1_Decoder_Callback)( T1_Decoder decoder, + FT_UInt glyph_index ); + + + typedef struct T1_Decoder_FuncsRec_ + { + FT_Error + (*init)( T1_Decoder decoder, + FT_Face face, + FT_Size size, + FT_GlyphSlot slot, + FT_Byte** glyph_names, + PS_Blend blend, + FT_Bool hinting, + FT_Render_Mode hint_mode, + T1_Decoder_Callback callback ); + + void + (*done)( T1_Decoder decoder ); + + FT_Error + (*parse_charstrings)( T1_Decoder decoder, + FT_Byte* base, + FT_UInt len ); + + } T1_Decoder_FuncsRec; + + + typedef struct T1_DecoderRec_ + { + T1_BuilderRec builder; + + FT_Long stack[T1_MAX_CHARSTRINGS_OPERANDS]; + FT_Long* top; + + T1_Decoder_ZoneRec zones[T1_MAX_SUBRS_CALLS + 1]; + T1_Decoder_Zone zone; + + FT_Service_PsCMaps psnames; /* for seac */ + FT_UInt num_glyphs; + FT_Byte** glyph_names; + + FT_Int lenIV; /* internal for sub routine calls */ + FT_UInt num_subrs; + FT_Byte** subrs; + FT_PtrDist* subrs_len; /* array of subrs length (optional) */ + + FT_Matrix font_matrix; + FT_Vector font_offset; + + FT_Int flex_state; + FT_Int num_flex_vectors; + FT_Vector flex_vectors[7]; + + PS_Blend blend; /* for multiple master support */ + + FT_Render_Mode hint_mode; + + T1_Decoder_Callback parse_callback; + T1_Decoder_FuncsRec funcs; + + FT_Long* buildchar; + FT_UInt len_buildchar; + + FT_Bool seac; + + } T1_DecoderRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** AFM PARSER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef struct AFM_ParserRec_* AFM_Parser; + + typedef struct AFM_Parser_FuncsRec_ + { + FT_Error + (*init)( AFM_Parser parser, + FT_Memory memory, + FT_Byte* base, + FT_Byte* limit ); + + void + (*done)( AFM_Parser parser ); + + FT_Error + (*parse)( AFM_Parser parser ); + + } AFM_Parser_FuncsRec; + + + typedef struct AFM_StreamRec_* AFM_Stream; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* AFM_ParserRec */ + /* */ + /* <Description> */ + /* An AFM_Parser is a parser for the AFM files. */ + /* */ + /* <Fields> */ + /* memory :: The object used for memory operations (alloc and */ + /* realloc). */ + /* */ + /* stream :: This is an opaque object. */ + /* */ + /* FontInfo :: The result will be stored here. */ + /* */ + /* get_index :: A user provided function to get a glyph index by its */ + /* name. */ + /* */ + typedef struct AFM_ParserRec_ + { + FT_Memory memory; + AFM_Stream stream; + + AFM_FontInfo FontInfo; + + FT_Int + (*get_index)( const char* name, + FT_Offset len, + void* user_data ); + + void* user_data; + + } AFM_ParserRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** TYPE1 CHARMAPS *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef const struct T1_CMap_ClassesRec_* T1_CMap_Classes; + + typedef struct T1_CMap_ClassesRec_ + { + FT_CMap_Class standard; + FT_CMap_Class expert; + FT_CMap_Class custom; + FT_CMap_Class unicode; + + } T1_CMap_ClassesRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** PSAux Module Interface *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef struct PSAux_ServiceRec_ + { + /* don't use `PS_Table_Funcs' and friends to avoid compiler warnings */ + const PS_Table_FuncsRec* ps_table_funcs; + const PS_Parser_FuncsRec* ps_parser_funcs; + const T1_Builder_FuncsRec* t1_builder_funcs; + const T1_Decoder_FuncsRec* t1_decoder_funcs; + + void + (*t1_decrypt)( FT_Byte* buffer, + FT_Offset length, + FT_UShort seed ); + + T1_CMap_Classes t1_cmap_classes; + + /* fields after this comment line were added after version 2.1.10 */ + const AFM_Parser_FuncsRec* afm_parser_funcs; + + } PSAux_ServiceRec, *PSAux_Service; + + /* backwards-compatible type definition */ + typedef PSAux_ServiceRec PSAux_Interface; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** Some convenience functions *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + +#define IS_PS_NEWLINE( ch ) \ + ( (ch) == '\r' || \ + (ch) == '\n' ) + +#define IS_PS_SPACE( ch ) \ + ( (ch) == ' ' || \ + IS_PS_NEWLINE( ch ) || \ + (ch) == '\t' || \ + (ch) == '\f' || \ + (ch) == '\0' ) + +#define IS_PS_SPECIAL( ch ) \ + ( (ch) == '/' || \ + (ch) == '(' || (ch) == ')' || \ + (ch) == '<' || (ch) == '>' || \ + (ch) == '[' || (ch) == ']' || \ + (ch) == '{' || (ch) == '}' || \ + (ch) == '%' ) + +#define IS_PS_DELIM( ch ) \ + ( IS_PS_SPACE( ch ) || \ + IS_PS_SPECIAL( ch ) ) + +#define IS_PS_DIGIT( ch ) \ + ( (ch) >= '0' && (ch) <= '9' ) + +#define IS_PS_XDIGIT( ch ) \ + ( IS_PS_DIGIT( ch ) || \ + ( (ch) >= 'A' && (ch) <= 'F' ) || \ + ( (ch) >= 'a' && (ch) <= 'f' ) ) + +#define IS_PS_BASE85( ch ) \ + ( (ch) >= '!' && (ch) <= 'u' ) + +#define IS_PS_TOKEN( cur, limit, token ) \ + ( (char)(cur)[0] == (token)[0] && \ + ( (cur) + sizeof ( (token) ) == (limit) || \ + ( (cur) + sizeof( (token) ) < (limit) && \ + IS_PS_DELIM( (cur)[sizeof ( (token) ) - 1] ) ) ) && \ + ft_strncmp( (char*)(cur), (token), sizeof ( (token) ) - 1 ) == 0 ) + + +FT_END_HEADER + +#endif /* __PSAUX_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/pshints.h b/other/freetype/include/freetype/internal/pshints.h new file mode 100644 index 0000000..0c35765 --- /dev/null +++ b/other/freetype/include/freetype/internal/pshints.h @@ -0,0 +1,712 @@ +/***************************************************************************/ +/* */ +/* pshints.h */ +/* */ +/* Interface to Postscript-specific (Type 1 and Type 2) hints */ +/* recorders (specification only). These are used to support native */ +/* T1/T2 hints in the `type1', `cid', and `cff' font drivers. */ +/* */ +/* Copyright 2001, 2002, 2003, 2005, 2006, 2007, 2009 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __PSHINTS_H__ +#define __PSHINTS_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H +#include FT_TYPE1_TABLES_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** INTERNAL REPRESENTATION OF GLOBALS *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + typedef struct PSH_GlobalsRec_* PSH_Globals; + + typedef FT_Error + (*PSH_Globals_NewFunc)( FT_Memory memory, + T1_Private* private_dict, + PSH_Globals* aglobals ); + + typedef FT_Error + (*PSH_Globals_SetScaleFunc)( PSH_Globals globals, + FT_Fixed x_scale, + FT_Fixed y_scale, + FT_Fixed x_delta, + FT_Fixed y_delta ); + + typedef void + (*PSH_Globals_DestroyFunc)( PSH_Globals globals ); + + + typedef struct PSH_Globals_FuncsRec_ + { + PSH_Globals_NewFunc create; + PSH_Globals_SetScaleFunc set_scale; + PSH_Globals_DestroyFunc destroy; + + } PSH_Globals_FuncsRec, *PSH_Globals_Funcs; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** PUBLIC TYPE 1 HINTS RECORDER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + /************************************************************************* + * + * @type: + * T1_Hints + * + * @description: + * This is a handle to an opaque structure used to record glyph hints + * from a Type 1 character glyph character string. + * + * The methods used to operate on this object are defined by the + * @T1_Hints_FuncsRec structure. Recording glyph hints is normally + * achieved through the following scheme: + * + * - Open a new hint recording session by calling the `open' method. + * This rewinds the recorder and prepare it for new input. + * + * - For each hint found in the glyph charstring, call the corresponding + * method (`stem', `stem3', or `reset'). Note that these functions do + * not return an error code. + * + * - Close the recording session by calling the `close' method. It + * returns an error code if the hints were invalid or something + * strange happened (e.g., memory shortage). + * + * The hints accumulated in the object can later be used by the + * PostScript hinter. + * + */ + typedef struct T1_HintsRec_* T1_Hints; + + + /************************************************************************* + * + * @type: + * T1_Hints_Funcs + * + * @description: + * A pointer to the @T1_Hints_FuncsRec structure that defines the API of + * a given @T1_Hints object. + * + */ + typedef const struct T1_Hints_FuncsRec_* T1_Hints_Funcs; + + + /************************************************************************* + * + * @functype: + * T1_Hints_OpenFunc + * + * @description: + * A method of the @T1_Hints class used to prepare it for a new Type 1 + * hints recording session. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * @note: + * You should always call the @T1_Hints_CloseFunc method in order to + * close an opened recording session. + * + */ + typedef void + (*T1_Hints_OpenFunc)( T1_Hints hints ); + + + /************************************************************************* + * + * @functype: + * T1_Hints_SetStemFunc + * + * @description: + * A method of the @T1_Hints class used to record a new horizontal or + * vertical stem. This corresponds to the Type 1 `hstem' and `vstem' + * operators. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * dimension :: + * 0 for horizontal stems (hstem), 1 for vertical ones (vstem). + * + * coords :: + * Array of 2 coordinates in 16.16 format, used as (position,length) + * stem descriptor. + * + * @note: + * Use vertical coordinates (y) for horizontal stems (dim=0). Use + * horizontal coordinates (x) for vertical stems (dim=1). + * + * `coords[0]' is the absolute stem position (lowest coordinate); + * `coords[1]' is the length. + * + * The length can be negative, in which case it must be either -20 or + * -21. It is interpreted as a `ghost' stem, according to the Type 1 + * specification. + * + * If the length is -21 (corresponding to a bottom ghost stem), then + * the real stem position is `coords[0]+coords[1]'. + * + */ + typedef void + (*T1_Hints_SetStemFunc)( T1_Hints hints, + FT_UInt dimension, + FT_Fixed* coords ); + + + /************************************************************************* + * + * @functype: + * T1_Hints_SetStem3Func + * + * @description: + * A method of the @T1_Hints class used to record three + * counter-controlled horizontal or vertical stems at once. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * dimension :: + * 0 for horizontal stems, 1 for vertical ones. + * + * coords :: + * An array of 6 values in 16.16 format, holding 3 (position,length) + * pairs for the counter-controlled stems. + * + * @note: + * Use vertical coordinates (y) for horizontal stems (dim=0). Use + * horizontal coordinates (x) for vertical stems (dim=1). + * + * The lengths cannot be negative (ghost stems are never + * counter-controlled). + * + */ + typedef void + (*T1_Hints_SetStem3Func)( T1_Hints hints, + FT_UInt dimension, + FT_Fixed* coords ); + + + /************************************************************************* + * + * @functype: + * T1_Hints_ResetFunc + * + * @description: + * A method of the @T1_Hints class used to reset the stems hints in a + * recording session. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * end_point :: + * The index of the last point in the input glyph in which the + * previously defined hints apply. + * + */ + typedef void + (*T1_Hints_ResetFunc)( T1_Hints hints, + FT_UInt end_point ); + + + /************************************************************************* + * + * @functype: + * T1_Hints_CloseFunc + * + * @description: + * A method of the @T1_Hints class used to close a hint recording + * session. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * end_point :: + * The index of the last point in the input glyph. + * + * @return: + * FreeType error code. 0 means success. + * + * @note: + * The error code is set to indicate that an error occurred during the + * recording session. + * + */ + typedef FT_Error + (*T1_Hints_CloseFunc)( T1_Hints hints, + FT_UInt end_point ); + + + /************************************************************************* + * + * @functype: + * T1_Hints_ApplyFunc + * + * @description: + * A method of the @T1_Hints class used to apply hints to the + * corresponding glyph outline. Must be called once all hints have been + * recorded. + * + * @input: + * hints :: + * A handle to the Type 1 hints recorder. + * + * outline :: + * A pointer to the target outline descriptor. + * + * globals :: + * The hinter globals for this font. + * + * hint_mode :: + * Hinting information. + * + * @return: + * FreeType error code. 0 means success. + * + * @note: + * On input, all points within the outline are in font coordinates. On + * output, they are in 1/64th of pixels. + * + * The scaling transformation is taken from the `globals' object which + * must correspond to the same font as the glyph. + * + */ + typedef FT_Error + (*T1_Hints_ApplyFunc)( T1_Hints hints, + FT_Outline* outline, + PSH_Globals globals, + FT_Render_Mode hint_mode ); + + + /************************************************************************* + * + * @struct: + * T1_Hints_FuncsRec + * + * @description: + * The structure used to provide the API to @T1_Hints objects. + * + * @fields: + * hints :: + * A handle to the T1 Hints recorder. + * + * open :: + * The function to open a recording session. + * + * close :: + * The function to close a recording session. + * + * stem :: + * The function to set a simple stem. + * + * stem3 :: + * The function to set counter-controlled stems. + * + * reset :: + * The function to reset stem hints. + * + * apply :: + * The function to apply the hints to the corresponding glyph outline. + * + */ + typedef struct T1_Hints_FuncsRec_ + { + T1_Hints hints; + T1_Hints_OpenFunc open; + T1_Hints_CloseFunc close; + T1_Hints_SetStemFunc stem; + T1_Hints_SetStem3Func stem3; + T1_Hints_ResetFunc reset; + T1_Hints_ApplyFunc apply; + + } T1_Hints_FuncsRec; + + + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** PUBLIC TYPE 2 HINTS RECORDER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + + /************************************************************************* + * + * @type: + * T2_Hints + * + * @description: + * This is a handle to an opaque structure used to record glyph hints + * from a Type 2 character glyph character string. + * + * The methods used to operate on this object are defined by the + * @T2_Hints_FuncsRec structure. Recording glyph hints is normally + * achieved through the following scheme: + * + * - Open a new hint recording session by calling the `open' method. + * This rewinds the recorder and prepare it for new input. + * + * - For each hint found in the glyph charstring, call the corresponding + * method (`stems', `hintmask', `counters'). Note that these + * functions do not return an error code. + * + * - Close the recording session by calling the `close' method. It + * returns an error code if the hints were invalid or something + * strange happened (e.g., memory shortage). + * + * The hints accumulated in the object can later be used by the + * Postscript hinter. + * + */ + typedef struct T2_HintsRec_* T2_Hints; + + + /************************************************************************* + * + * @type: + * T2_Hints_Funcs + * + * @description: + * A pointer to the @T2_Hints_FuncsRec structure that defines the API of + * a given @T2_Hints object. + * + */ + typedef const struct T2_Hints_FuncsRec_* T2_Hints_Funcs; + + + /************************************************************************* + * + * @functype: + * T2_Hints_OpenFunc + * + * @description: + * A method of the @T2_Hints class used to prepare it for a new Type 2 + * hints recording session. + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * @note: + * You should always call the @T2_Hints_CloseFunc method in order to + * close an opened recording session. + * + */ + typedef void + (*T2_Hints_OpenFunc)( T2_Hints hints ); + + + /************************************************************************* + * + * @functype: + * T2_Hints_StemsFunc + * + * @description: + * A method of the @T2_Hints class used to set the table of stems in + * either the vertical or horizontal dimension. Equivalent to the + * `hstem', `vstem', `hstemhm', and `vstemhm' Type 2 operators. + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * dimension :: + * 0 for horizontal stems (hstem), 1 for vertical ones (vstem). + * + * count :: + * The number of stems. + * + * coords :: + * An array of `count' (position,length) pairs in 16.16 format. + * + * @note: + * Use vertical coordinates (y) for horizontal stems (dim=0). Use + * horizontal coordinates (x) for vertical stems (dim=1). + * + * There are `2*count' elements in the `coords' array. Each even + * element is an absolute position in font units, each odd element is a + * length in font units. + * + * A length can be negative, in which case it must be either -20 or + * -21. It is interpreted as a `ghost' stem, according to the Type 1 + * specification. + * + */ + typedef void + (*T2_Hints_StemsFunc)( T2_Hints hints, + FT_UInt dimension, + FT_UInt count, + FT_Fixed* coordinates ); + + + /************************************************************************* + * + * @functype: + * T2_Hints_MaskFunc + * + * @description: + * A method of the @T2_Hints class used to set a given hintmask (this + * corresponds to the `hintmask' Type 2 operator). + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * end_point :: + * The glyph index of the last point to which the previously defined + * or activated hints apply. + * + * bit_count :: + * The number of bits in the hint mask. + * + * bytes :: + * An array of bytes modelling the hint mask. + * + * @note: + * If the hintmask starts the charstring (before any glyph point + * definition), the value of `end_point' should be 0. + * + * `bit_count' is the number of meaningful bits in the `bytes' array; it + * must be equal to the total number of hints defined so far (i.e., + * horizontal+verticals). + * + * The `bytes' array can come directly from the Type 2 charstring and + * respects the same format. + * + */ + typedef void + (*T2_Hints_MaskFunc)( T2_Hints hints, + FT_UInt end_point, + FT_UInt bit_count, + const FT_Byte* bytes ); + + + /************************************************************************* + * + * @functype: + * T2_Hints_CounterFunc + * + * @description: + * A method of the @T2_Hints class used to set a given counter mask + * (this corresponds to the `hintmask' Type 2 operator). + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * end_point :: + * A glyph index of the last point to which the previously defined or + * active hints apply. + * + * bit_count :: + * The number of bits in the hint mask. + * + * bytes :: + * An array of bytes modelling the hint mask. + * + * @note: + * If the hintmask starts the charstring (before any glyph point + * definition), the value of `end_point' should be 0. + * + * `bit_count' is the number of meaningful bits in the `bytes' array; it + * must be equal to the total number of hints defined so far (i.e., + * horizontal+verticals). + * + * The `bytes' array can come directly from the Type 2 charstring and + * respects the same format. + * + */ + typedef void + (*T2_Hints_CounterFunc)( T2_Hints hints, + FT_UInt bit_count, + const FT_Byte* bytes ); + + + /************************************************************************* + * + * @functype: + * T2_Hints_CloseFunc + * + * @description: + * A method of the @T2_Hints class used to close a hint recording + * session. + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * end_point :: + * The index of the last point in the input glyph. + * + * @return: + * FreeType error code. 0 means success. + * + * @note: + * The error code is set to indicate that an error occurred during the + * recording session. + * + */ + typedef FT_Error + (*T2_Hints_CloseFunc)( T2_Hints hints, + FT_UInt end_point ); + + + /************************************************************************* + * + * @functype: + * T2_Hints_ApplyFunc + * + * @description: + * A method of the @T2_Hints class used to apply hints to the + * corresponding glyph outline. Must be called after the `close' + * method. + * + * @input: + * hints :: + * A handle to the Type 2 hints recorder. + * + * outline :: + * A pointer to the target outline descriptor. + * + * globals :: + * The hinter globals for this font. + * + * hint_mode :: + * Hinting information. + * + * @return: + * FreeType error code. 0 means success. + * + * @note: + * On input, all points within the outline are in font coordinates. On + * output, they are in 1/64th of pixels. + * + * The scaling transformation is taken from the `globals' object which + * must correspond to the same font than the glyph. + * + */ + typedef FT_Error + (*T2_Hints_ApplyFunc)( T2_Hints hints, + FT_Outline* outline, + PSH_Globals globals, + FT_Render_Mode hint_mode ); + + + /************************************************************************* + * + * @struct: + * T2_Hints_FuncsRec + * + * @description: + * The structure used to provide the API to @T2_Hints objects. + * + * @fields: + * hints :: + * A handle to the T2 hints recorder object. + * + * open :: + * The function to open a recording session. + * + * close :: + * The function to close a recording session. + * + * stems :: + * The function to set the dimension's stems table. + * + * hintmask :: + * The function to set hint masks. + * + * counter :: + * The function to set counter masks. + * + * apply :: + * The function to apply the hints on the corresponding glyph outline. + * + */ + typedef struct T2_Hints_FuncsRec_ + { + T2_Hints hints; + T2_Hints_OpenFunc open; + T2_Hints_CloseFunc close; + T2_Hints_StemsFunc stems; + T2_Hints_MaskFunc hintmask; + T2_Hints_CounterFunc counter; + T2_Hints_ApplyFunc apply; + + } T2_Hints_FuncsRec; + + + /* */ + + + typedef struct PSHinter_Interface_ + { + PSH_Globals_Funcs (*get_globals_funcs)( FT_Module module ); + T1_Hints_Funcs (*get_t1_funcs) ( FT_Module module ); + T2_Hints_Funcs (*get_t2_funcs) ( FT_Module module ); + + } PSHinter_Interface; + + typedef PSHinter_Interface* PSHinter_Service; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_, \ + get_t1_funcs_, get_t2_funcs_) \ + static const PSHinter_Interface class_ = \ + { \ + get_globals_funcs_, get_t1_funcs_, get_t2_funcs_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_, \ + get_t1_funcs_, get_t2_funcs_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + PSHinter_Interface* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->get_globals_funcs = get_globals_funcs_; \ + clazz->get_t1_funcs = get_t1_funcs_; \ + clazz->get_t2_funcs = get_t2_funcs_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + +FT_END_HEADER + +#endif /* __PSHINTS_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svbdf.h b/other/freetype/include/freetype/internal/services/svbdf.h new file mode 100644 index 0000000..9264239 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svbdf.h @@ -0,0 +1,77 @@ +/***************************************************************************/ +/* */ +/* svbdf.h */ +/* */ +/* The FreeType BDF services (specification). */ +/* */ +/* Copyright 2003 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVBDF_H__ +#define __SVBDF_H__ + +#include FT_BDF_H +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_BDF "bdf" + + typedef FT_Error + (*FT_BDF_GetCharsetIdFunc)( FT_Face face, + const char* *acharset_encoding, + const char* *acharset_registry ); + + typedef FT_Error + (*FT_BDF_GetPropertyFunc)( FT_Face face, + const char* prop_name, + BDF_PropertyRec *aproperty ); + + + FT_DEFINE_SERVICE( BDF ) + { + FT_BDF_GetCharsetIdFunc get_charset_id; + FT_BDF_GetPropertyFunc get_property; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \ + static const FT_Service_BDFRec class_ = \ + { \ + get_charset_id_, get_property_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \ + void \ + FT_Init_Class_##class_( FT_Service_BDFRec* clazz ) \ + { \ + clazz->get_charset_id = get_charset_id_; \ + clazz->get_property = get_property_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVBDF_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svcid.h b/other/freetype/include/freetype/internal/services/svcid.h new file mode 100644 index 0000000..9b874b5 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svcid.h @@ -0,0 +1,83 @@ +/***************************************************************************/ +/* */ +/* svcid.h */ +/* */ +/* The FreeType CID font services (specification). */ +/* */ +/* Copyright 2007, 2009 by Derek Clegg, Michael Toftdal. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVCID_H__ +#define __SVCID_H__ + +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_CID "CID" + + typedef FT_Error + (*FT_CID_GetRegistryOrderingSupplementFunc)( FT_Face face, + const char* *registry, + const char* *ordering, + FT_Int *supplement ); + typedef FT_Error + (*FT_CID_GetIsInternallyCIDKeyedFunc)( FT_Face face, + FT_Bool *is_cid ); + typedef FT_Error + (*FT_CID_GetCIDFromGlyphIndexFunc)( FT_Face face, + FT_UInt glyph_index, + FT_UInt *cid ); + + FT_DEFINE_SERVICE( CID ) + { + FT_CID_GetRegistryOrderingSupplementFunc get_ros; + FT_CID_GetIsInternallyCIDKeyedFunc get_is_cid; + FT_CID_GetCIDFromGlyphIndexFunc get_cid_from_glyph_index; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_, \ + get_is_cid_, get_cid_from_glyph_index_ ) \ + static const FT_Service_CIDRec class_ = \ + { \ + get_ros_, get_is_cid_, get_cid_from_glyph_index_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_, \ + get_is_cid_, get_cid_from_glyph_index_ ) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_CIDRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->get_ros = get_ros_; \ + clazz->get_is_cid = get_is_cid_; \ + clazz->get_cid_from_glyph_index = get_cid_from_glyph_index_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVCID_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svgldict.h b/other/freetype/include/freetype/internal/services/svgldict.h new file mode 100644 index 0000000..d66a41d --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svgldict.h @@ -0,0 +1,82 @@ +/***************************************************************************/ +/* */ +/* svgldict.h */ +/* */ +/* The FreeType glyph dictionary services (specification). */ +/* */ +/* Copyright 2003 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVGLDICT_H__ +#define __SVGLDICT_H__ + +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + + /* + * A service used to retrieve glyph names, as well as to find the + * index of a given glyph name in a font. + * + */ + +#define FT_SERVICE_ID_GLYPH_DICT "glyph-dict" + + + typedef FT_Error + (*FT_GlyphDict_GetNameFunc)( FT_Face face, + FT_UInt glyph_index, + FT_Pointer buffer, + FT_UInt buffer_max ); + + typedef FT_UInt + (*FT_GlyphDict_NameIndexFunc)( FT_Face face, + FT_String* glyph_name ); + + + FT_DEFINE_SERVICE( GlyphDict ) + { + FT_GlyphDict_GetNameFunc get_name; + FT_GlyphDict_NameIndexFunc name_index; /* optional */ + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \ + static const FT_Service_GlyphDictRec class_ = \ + { \ + get_name_, name_index_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_GlyphDictRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->get_name = get_name_; \ + clazz->name_index = name_index_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVGLDICT_H__ */ diff --git a/other/freetype/include/freetype/internal/services/svgxval.h b/other/freetype/include/freetype/internal/services/svgxval.h new file mode 100644 index 0000000..2cdab50 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svgxval.h @@ -0,0 +1,72 @@ +/***************************************************************************/ +/* */ +/* svgxval.h */ +/* */ +/* FreeType API for validating TrueTypeGX/AAT tables (specification). */ +/* */ +/* Copyright 2004, 2005 by */ +/* Masatake YAMATO, Red Hat K.K., */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +/***************************************************************************/ +/* */ +/* gxvalid is derived from both gxlayout module and otvalid module. */ +/* Development of gxlayout is supported by the Information-technology */ +/* Promotion Agency(IPA), Japan. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVGXVAL_H__ +#define __SVGXVAL_H__ + +#include FT_GX_VALIDATE_H +#include FT_INTERNAL_VALIDATE_H + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_GX_VALIDATE "truetypegx-validate" +#define FT_SERVICE_ID_CLASSICKERN_VALIDATE "classickern-validate" + + typedef FT_Error + (*gxv_validate_func)( FT_Face face, + FT_UInt gx_flags, + FT_Bytes tables[FT_VALIDATE_GX_LENGTH], + FT_UInt table_length ); + + + typedef FT_Error + (*ckern_validate_func)( FT_Face face, + FT_UInt ckern_flags, + FT_Bytes *ckern_table ); + + + FT_DEFINE_SERVICE( GXvalidate ) + { + gxv_validate_func validate; + }; + + FT_DEFINE_SERVICE( CKERNvalidate ) + { + ckern_validate_func validate; + }; + + /* */ + + +FT_END_HEADER + + +#endif /* __SVGXVAL_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svkern.h b/other/freetype/include/freetype/internal/services/svkern.h new file mode 100644 index 0000000..1488adf --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svkern.h @@ -0,0 +1,51 @@ +/***************************************************************************/ +/* */ +/* svkern.h */ +/* */ +/* The FreeType Kerning service (specification). */ +/* */ +/* Copyright 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVKERN_H__ +#define __SVKERN_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_TRUETYPE_TABLES_H + + +FT_BEGIN_HEADER + +#define FT_SERVICE_ID_KERNING "kerning" + + + typedef FT_Error + (*FT_Kerning_TrackGetFunc)( FT_Face face, + FT_Fixed point_size, + FT_Int degree, + FT_Fixed* akerning ); + + FT_DEFINE_SERVICE( Kerning ) + { + FT_Kerning_TrackGetFunc get_track; + }; + + /* */ + + +FT_END_HEADER + + +#endif /* __SVKERN_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svmm.h b/other/freetype/include/freetype/internal/services/svmm.h new file mode 100644 index 0000000..66e1da2 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svmm.h @@ -0,0 +1,104 @@ +/***************************************************************************/ +/* */ +/* svmm.h */ +/* */ +/* The FreeType Multiple Masters and GX var services (specification). */ +/* */ +/* Copyright 2003, 2004 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVMM_H__ +#define __SVMM_H__ + +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + + /* + * A service used to manage multiple-masters data in a given face. + * + * See the related APIs in `ftmm.h' (FT_MULTIPLE_MASTERS_H). + * + */ + +#define FT_SERVICE_ID_MULTI_MASTERS "multi-masters" + + + typedef FT_Error + (*FT_Get_MM_Func)( FT_Face face, + FT_Multi_Master* master ); + + typedef FT_Error + (*FT_Get_MM_Var_Func)( FT_Face face, + FT_MM_Var* *master ); + + typedef FT_Error + (*FT_Set_MM_Design_Func)( FT_Face face, + FT_UInt num_coords, + FT_Long* coords ); + + typedef FT_Error + (*FT_Set_Var_Design_Func)( FT_Face face, + FT_UInt num_coords, + FT_Fixed* coords ); + + typedef FT_Error + (*FT_Set_MM_Blend_Func)( FT_Face face, + FT_UInt num_coords, + FT_Long* coords ); + + + FT_DEFINE_SERVICE( MultiMasters ) + { + FT_Get_MM_Func get_mm; + FT_Set_MM_Design_Func set_mm_design; + FT_Set_MM_Blend_Func set_mm_blend; + FT_Get_MM_Var_Func get_mm_var; + FT_Set_Var_Design_Func set_var_design; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_, \ + set_mm_blend_, get_mm_var_, set_var_design_) \ + static const FT_Service_MultiMastersRec class_ = \ + { \ + get_mm_, set_mm_design_, set_mm_blend_, get_mm_var_, set_var_design_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_, \ + set_mm_blend_, get_mm_var_, set_var_design_) \ + void \ + FT_Init_Class_##class_( FT_Service_MultiMastersRec* clazz ) \ + { \ + clazz->get_mm = get_mm_; \ + clazz->set_mm_design = set_mm_design_; \ + clazz->set_mm_blend = set_mm_blend_; \ + clazz->get_mm_var = get_mm_var_; \ + clazz->set_var_design = set_var_design_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + +#endif /* __SVMM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svotval.h b/other/freetype/include/freetype/internal/services/svotval.h new file mode 100644 index 0000000..970bbd5 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svotval.h @@ -0,0 +1,55 @@ +/***************************************************************************/ +/* */ +/* svotval.h */ +/* */ +/* The FreeType OpenType validation service (specification). */ +/* */ +/* Copyright 2004, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVOTVAL_H__ +#define __SVOTVAL_H__ + +#include FT_OPENTYPE_VALIDATE_H +#include FT_INTERNAL_VALIDATE_H + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_OPENTYPE_VALIDATE "opentype-validate" + + + typedef FT_Error + (*otv_validate_func)( FT_Face volatile face, + FT_UInt ot_flags, + FT_Bytes *base, + FT_Bytes *gdef, + FT_Bytes *gpos, + FT_Bytes *gsub, + FT_Bytes *jstf ); + + + FT_DEFINE_SERVICE( OTvalidate ) + { + otv_validate_func validate; + }; + + /* */ + + +FT_END_HEADER + + +#endif /* __SVOTVAL_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svpfr.h b/other/freetype/include/freetype/internal/services/svpfr.h new file mode 100644 index 0000000..462786f --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svpfr.h @@ -0,0 +1,66 @@ +/***************************************************************************/ +/* */ +/* svpfr.h */ +/* */ +/* Internal PFR service functions (specification). */ +/* */ +/* Copyright 2003, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVPFR_H__ +#define __SVPFR_H__ + +#include FT_PFR_H +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_PFR_METRICS "pfr-metrics" + + + typedef FT_Error + (*FT_PFR_GetMetricsFunc)( FT_Face face, + FT_UInt *aoutline, + FT_UInt *ametrics, + FT_Fixed *ax_scale, + FT_Fixed *ay_scale ); + + typedef FT_Error + (*FT_PFR_GetKerningFunc)( FT_Face face, + FT_UInt left, + FT_UInt right, + FT_Vector *avector ); + + typedef FT_Error + (*FT_PFR_GetAdvanceFunc)( FT_Face face, + FT_UInt gindex, + FT_Pos *aadvance ); + + + FT_DEFINE_SERVICE( PfrMetrics ) + { + FT_PFR_GetMetricsFunc get_metrics; + FT_PFR_GetKerningFunc get_kerning; + FT_PFR_GetAdvanceFunc get_advance; + + }; + + /* */ + +FT_END_HEADER + +#endif /* __SVPFR_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svpostnm.h b/other/freetype/include/freetype/internal/services/svpostnm.h new file mode 100644 index 0000000..106c54f --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svpostnm.h @@ -0,0 +1,79 @@ +/***************************************************************************/ +/* */ +/* svpostnm.h */ +/* */ +/* The FreeType PostScript name services (specification). */ +/* */ +/* Copyright 2003, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVPOSTNM_H__ +#define __SVPOSTNM_H__ + +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + /* + * A trivial service used to retrieve the PostScript name of a given + * font when available. The `get_name' field should never be NULL. + * + * The corresponding function can return NULL to indicate that the + * PostScript name is not available. + * + * The name is owned by the face and will be destroyed with it. + */ + +#define FT_SERVICE_ID_POSTSCRIPT_FONT_NAME "postscript-font-name" + + + typedef const char* + (*FT_PsName_GetFunc)( FT_Face face ); + + + FT_DEFINE_SERVICE( PsFontName ) + { + FT_PsName_GetFunc get_ps_font_name; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \ + static const FT_Service_PsFontNameRec class_ = \ + { \ + get_ps_font_name_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_PsFontNameRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->get_ps_font_name = get_ps_font_name_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVPOSTNM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svpscmap.h b/other/freetype/include/freetype/internal/services/svpscmap.h new file mode 100644 index 0000000..961030c --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svpscmap.h @@ -0,0 +1,164 @@ +/***************************************************************************/ +/* */ +/* svpscmap.h */ +/* */ +/* The FreeType PostScript charmap service (specification). */ +/* */ +/* Copyright 2003, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVPSCMAP_H__ +#define __SVPSCMAP_H__ + +#include FT_INTERNAL_OBJECTS_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_POSTSCRIPT_CMAPS "postscript-cmaps" + + + /* + * Adobe glyph name to unicode value. + */ + typedef FT_UInt32 + (*PS_Unicode_ValueFunc)( const char* glyph_name ); + + /* + * Macintosh name id to glyph name. NULL if invalid index. + */ + typedef const char* + (*PS_Macintosh_NameFunc)( FT_UInt name_index ); + + /* + * Adobe standard string ID to glyph name. NULL if invalid index. + */ + typedef const char* + (*PS_Adobe_Std_StringsFunc)( FT_UInt string_index ); + + + /* + * Simple unicode -> glyph index charmap built from font glyph names + * table. + */ + typedef struct PS_UniMap_ + { + FT_UInt32 unicode; /* bit 31 set: is glyph variant */ + FT_UInt glyph_index; + + } PS_UniMap; + + + typedef struct PS_UnicodesRec_* PS_Unicodes; + + typedef struct PS_UnicodesRec_ + { + FT_CMapRec cmap; + FT_UInt num_maps; + PS_UniMap* maps; + + } PS_UnicodesRec; + + + /* + * A function which returns a glyph name for a given index. Returns + * NULL if invalid index. + */ + typedef const char* + (*PS_GetGlyphNameFunc)( FT_Pointer data, + FT_UInt string_index ); + + /* + * A function used to release the glyph name returned by + * PS_GetGlyphNameFunc, when needed + */ + typedef void + (*PS_FreeGlyphNameFunc)( FT_Pointer data, + const char* name ); + + typedef FT_Error + (*PS_Unicodes_InitFunc)( FT_Memory memory, + PS_Unicodes unicodes, + FT_UInt num_glyphs, + PS_GetGlyphNameFunc get_glyph_name, + PS_FreeGlyphNameFunc free_glyph_name, + FT_Pointer glyph_data ); + + typedef FT_UInt + (*PS_Unicodes_CharIndexFunc)( PS_Unicodes unicodes, + FT_UInt32 unicode ); + + typedef FT_UInt32 + (*PS_Unicodes_CharNextFunc)( PS_Unicodes unicodes, + FT_UInt32 *unicode ); + + + FT_DEFINE_SERVICE( PsCMaps ) + { + PS_Unicode_ValueFunc unicode_value; + + PS_Unicodes_InitFunc unicodes_init; + PS_Unicodes_CharIndexFunc unicodes_char_index; + PS_Unicodes_CharNextFunc unicodes_char_next; + + PS_Macintosh_NameFunc macintosh_name; + PS_Adobe_Std_StringsFunc adobe_std_strings; + const unsigned short* adobe_std_encoding; + const unsigned short* adobe_expert_encoding; + }; + + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \ + unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ + adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_) \ + static const FT_Service_PsCMapsRec class_ = \ + { \ + unicode_value_, unicodes_init_, \ + unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ + adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \ + unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ + adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_PsCMapsRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->unicode_value = unicode_value_; \ + clazz->unicodes_init = unicodes_init_; \ + clazz->unicodes_char_index = unicodes_char_index_; \ + clazz->unicodes_char_next = unicodes_char_next_; \ + clazz->macintosh_name = macintosh_name_; \ + clazz->adobe_std_strings = adobe_std_strings_; \ + clazz->adobe_std_encoding = adobe_std_encoding_; \ + clazz->adobe_expert_encoding = adobe_expert_encoding_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVPSCMAP_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svpsinfo.h b/other/freetype/include/freetype/internal/services/svpsinfo.h new file mode 100644 index 0000000..84d6a78 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svpsinfo.h @@ -0,0 +1,103 @@ +/***************************************************************************/ +/* */ +/* svpsinfo.h */ +/* */ +/* The FreeType PostScript info service (specification). */ +/* */ +/* Copyright 2003, 2004, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVPSINFO_H__ +#define __SVPSINFO_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_INTERNAL_TYPE1_TYPES_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_POSTSCRIPT_INFO "postscript-info" + + + typedef FT_Error + (*PS_GetFontInfoFunc)( FT_Face face, + PS_FontInfoRec* afont_info ); + + typedef FT_Error + (*PS_GetFontExtraFunc)( FT_Face face, + PS_FontExtraRec* afont_extra ); + + typedef FT_Int + (*PS_HasGlyphNamesFunc)( FT_Face face ); + + typedef FT_Error + (*PS_GetFontPrivateFunc)( FT_Face face, + PS_PrivateRec* afont_private ); + + typedef FT_Long + (*PS_GetFontValueFunc)( FT_Face face, + PS_Dict_Keys key, + FT_UInt idx, + void *value, + FT_Long value_len ); + + + FT_DEFINE_SERVICE( PsInfo ) + { + PS_GetFontInfoFunc ps_get_font_info; + PS_GetFontExtraFunc ps_get_font_extra; + PS_HasGlyphNamesFunc ps_has_glyph_names; + PS_GetFontPrivateFunc ps_get_font_private; + PS_GetFontValueFunc ps_get_font_value; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_, \ + ps_get_font_extra_, has_glyph_names_, get_font_private_, \ + get_font_value_) \ + static const FT_Service_PsInfoRec class_ = \ + { \ + get_font_info_, ps_get_font_extra_, has_glyph_names_, \ + get_font_private_, get_font_value_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_, \ + ps_get_font_extra_, has_glyph_names_, get_font_private_, \ + get_font_value_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_PsInfoRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->ps_get_font_info = get_font_info_; \ + clazz->ps_get_font_extra = ps_get_font_extra_; \ + clazz->ps_has_glyph_names = has_glyph_names_; \ + clazz->ps_get_font_private = get_font_private_; \ + clazz->ps_get_font_value = get_font_value_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVPSINFO_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svsfnt.h b/other/freetype/include/freetype/internal/services/svsfnt.h new file mode 100644 index 0000000..30bb162 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svsfnt.h @@ -0,0 +1,102 @@ +/***************************************************************************/ +/* */ +/* svsfnt.h */ +/* */ +/* The FreeType SFNT table loading service (specification). */ +/* */ +/* Copyright 2003, 2004 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVSFNT_H__ +#define __SVSFNT_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_TRUETYPE_TABLES_H + + +FT_BEGIN_HEADER + + + /* + * SFNT table loading service. + */ + +#define FT_SERVICE_ID_SFNT_TABLE "sfnt-table" + + + /* + * Used to implement FT_Load_Sfnt_Table(). + */ + typedef FT_Error + (*FT_SFNT_TableLoadFunc)( FT_Face face, + FT_ULong tag, + FT_Long offset, + FT_Byte* buffer, + FT_ULong* length ); + + /* + * Used to implement FT_Get_Sfnt_Table(). + */ + typedef void* + (*FT_SFNT_TableGetFunc)( FT_Face face, + FT_Sfnt_Tag tag ); + + + /* + * Used to implement FT_Sfnt_Table_Info(). + */ + typedef FT_Error + (*FT_SFNT_TableInfoFunc)( FT_Face face, + FT_UInt idx, + FT_ULong *tag, + FT_ULong *offset, + FT_ULong *length ); + + + FT_DEFINE_SERVICE( SFNT_Table ) + { + FT_SFNT_TableLoadFunc load_table; + FT_SFNT_TableGetFunc get_table; + FT_SFNT_TableInfoFunc table_info; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_) \ + static const FT_Service_SFNT_TableRec class_ = \ + { \ + load_, get_, info_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_) \ + void \ + FT_Init_Class_##class_( FT_Service_SFNT_TableRec* clazz ) \ + { \ + clazz->load_table = load_; \ + clazz->get_table = get_; \ + clazz->table_info = info_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + + +#endif /* __SVSFNT_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svttcmap.h b/other/freetype/include/freetype/internal/services/svttcmap.h new file mode 100644 index 0000000..8af0035 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svttcmap.h @@ -0,0 +1,106 @@ +/***************************************************************************/ +/* */ +/* svttcmap.h */ +/* */ +/* The FreeType TrueType/sfnt cmap extra information service. */ +/* */ +/* Copyright 2003 by */ +/* Masatake YAMATO, Redhat K.K. */ +/* */ +/* Copyright 2003, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +/* Development of this service is support of + Information-technology Promotion Agency, Japan. */ + +#ifndef __SVTTCMAP_H__ +#define __SVTTCMAP_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_TRUETYPE_TABLES_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_TT_CMAP "tt-cmaps" + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_CMapInfo */ + /* */ + /* <Description> */ + /* A structure used to store TrueType/sfnt specific cmap information */ + /* which is not covered by the generic @FT_CharMap structure. This */ + /* structure can be accessed with the @FT_Get_TT_CMap_Info function. */ + /* */ + /* <Fields> */ + /* language :: */ + /* The language ID used in Mac fonts. Definitions of values are in */ + /* freetype/ttnameid.h. */ + /* */ + /* format :: */ + /* The cmap format. OpenType 1.5 defines the formats 0 (byte */ + /* encoding table), 2~(high-byte mapping through table), 4~(segment */ + /* mapping to delta values), 6~(trimmed table mapping), 8~(mixed */ + /* 16-bit and 32-bit coverage), 10~(trimmed array), 12~(segmented */ + /* coverage), and 14 (Unicode Variation Sequences). */ + /* */ + typedef struct TT_CMapInfo_ + { + FT_ULong language; + FT_Long format; + + } TT_CMapInfo; + + + typedef FT_Error + (*TT_CMap_Info_GetFunc)( FT_CharMap charmap, + TT_CMapInfo *cmap_info ); + + + FT_DEFINE_SERVICE( TTCMaps ) + { + TT_CMap_Info_GetFunc get_cmap_info; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_) \ + static const FT_Service_TTCMapsRec class_ = \ + { \ + get_cmap_info_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_) \ + void \ + FT_Init_Class_##class_( FT_Library library, \ + FT_Service_TTCMapsRec* clazz) \ + { \ + FT_UNUSED(library); \ + clazz->get_cmap_info = get_cmap_info_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + +#endif /* __SVTTCMAP_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svtteng.h b/other/freetype/include/freetype/internal/services/svtteng.h new file mode 100644 index 0000000..58e02a6 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svtteng.h @@ -0,0 +1,53 @@ +/***************************************************************************/ +/* */ +/* svtteng.h */ +/* */ +/* The FreeType TrueType engine query service (specification). */ +/* */ +/* Copyright 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVTTENG_H__ +#define __SVTTENG_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_MODULE_H + + +FT_BEGIN_HEADER + + + /* + * SFNT table loading service. + */ + +#define FT_SERVICE_ID_TRUETYPE_ENGINE "truetype-engine" + + /* + * Used to implement FT_Get_TrueType_Engine_Type + */ + + FT_DEFINE_SERVICE( TrueTypeEngine ) + { + FT_TrueTypeEngineType engine_type; + }; + + /* */ + + +FT_END_HEADER + + +#endif /* __SVTTENG_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svttglyf.h b/other/freetype/include/freetype/internal/services/svttglyf.h new file mode 100644 index 0000000..ab2dc9a --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svttglyf.h @@ -0,0 +1,67 @@ +/***************************************************************************/ +/* */ +/* svttglyf.h */ +/* */ +/* The FreeType TrueType glyph service. */ +/* */ +/* Copyright 2007 by David Turner. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + +#ifndef __SVTTGLYF_H__ +#define __SVTTGLYF_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_TRUETYPE_TABLES_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_TT_GLYF "tt-glyf" + + + typedef FT_ULong + (*TT_Glyf_GetLocationFunc)( FT_Face face, + FT_UInt gindex, + FT_ULong *psize ); + + FT_DEFINE_SERVICE( TTGlyf ) + { + TT_Glyf_GetLocationFunc get_location; + }; + +#ifndef FT_CONFIG_OPTION_PIC + +#define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ ) \ + static const FT_Service_TTGlyfRec class_ = \ + { \ + get_location_ \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ ) \ + void \ + FT_Init_Class_##class_( FT_Service_TTGlyfRec* clazz ) \ + { \ + clazz->get_location = get_location_; \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + + /* */ + + +FT_END_HEADER + +#endif /* __SVTTGLYF_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svwinfnt.h b/other/freetype/include/freetype/internal/services/svwinfnt.h new file mode 100644 index 0000000..57f7765 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svwinfnt.h @@ -0,0 +1,50 @@ +/***************************************************************************/ +/* */ +/* svwinfnt.h */ +/* */ +/* The FreeType Windows FNT/FONT service (specification). */ +/* */ +/* Copyright 2003 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVWINFNT_H__ +#define __SVWINFNT_H__ + +#include FT_INTERNAL_SERVICE_H +#include FT_WINFONTS_H + + +FT_BEGIN_HEADER + + +#define FT_SERVICE_ID_WINFNT "winfonts" + + typedef FT_Error + (*FT_WinFnt_GetHeaderFunc)( FT_Face face, + FT_WinFNT_HeaderRec *aheader ); + + + FT_DEFINE_SERVICE( WinFnt ) + { + FT_WinFnt_GetHeaderFunc get_header; + }; + + /* */ + + +FT_END_HEADER + + +#endif /* __SVWINFNT_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/services/svxf86nm.h b/other/freetype/include/freetype/internal/services/svxf86nm.h new file mode 100644 index 0000000..ca5d884 --- /dev/null +++ b/other/freetype/include/freetype/internal/services/svxf86nm.h @@ -0,0 +1,55 @@ +/***************************************************************************/ +/* */ +/* svxf86nm.h */ +/* */ +/* The FreeType XFree86 services (specification only). */ +/* */ +/* Copyright 2003 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SVXF86NM_H__ +#define __SVXF86NM_H__ + +#include FT_INTERNAL_SERVICE_H + + +FT_BEGIN_HEADER + + + /* + * A trivial service used to return the name of a face's font driver, + * according to the XFree86 nomenclature. Note that the service data + * is a simple constant string pointer. + */ + +#define FT_SERVICE_ID_XF86_NAME "xf86-driver-name" + +#define FT_XF86_FORMAT_TRUETYPE "TrueType" +#define FT_XF86_FORMAT_TYPE_1 "Type 1" +#define FT_XF86_FORMAT_BDF "BDF" +#define FT_XF86_FORMAT_PCF "PCF" +#define FT_XF86_FORMAT_TYPE_42 "Type 42" +#define FT_XF86_FORMAT_CID "CID Type 1" +#define FT_XF86_FORMAT_CFF "CFF" +#define FT_XF86_FORMAT_PFR "PFR" +#define FT_XF86_FORMAT_WINFNT "Windows FNT" + + /* */ + + +FT_END_HEADER + + +#endif /* __SVXF86NM_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/sfnt.h b/other/freetype/include/freetype/internal/sfnt.h new file mode 100644 index 0000000..6326deb --- /dev/null +++ b/other/freetype/include/freetype/internal/sfnt.h @@ -0,0 +1,897 @@ +/***************************************************************************/ +/* */ +/* sfnt.h */ +/* */ +/* High-level `sfnt' driver interface (specification). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __SFNT_H__ +#define __SFNT_H__ + + +#include <ft2build.h> +#include FT_INTERNAL_DRIVER_H +#include FT_INTERNAL_TRUETYPE_TYPES_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Init_Face_Func */ + /* */ + /* <Description> */ + /* First part of the SFNT face object initialization. This finds */ + /* the face in a SFNT file or collection, and load its format tag in */ + /* face->format_tag. */ + /* */ + /* <Input> */ + /* stream :: The input stream. */ + /* */ + /* face :: A handle to the target face object. */ + /* */ + /* face_index :: The index of the TrueType font, if we are opening a */ + /* collection. */ + /* */ + /* num_params :: The number of additional parameters. */ + /* */ + /* params :: Optional additional parameters. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The stream cursor must be at the font file's origin. */ + /* */ + /* This function recognizes fonts embedded in a `TrueType */ + /* collection'. */ + /* */ + /* Once the format tag has been validated by the font driver, it */ + /* should then call the TT_Load_Face_Func() callback to read the rest */ + /* of the SFNT tables in the object. */ + /* */ + typedef FT_Error + (*TT_Init_Face_Func)( FT_Stream stream, + TT_Face face, + FT_Int face_index, + FT_Int num_params, + FT_Parameter* params ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Face_Func */ + /* */ + /* <Description> */ + /* Second part of the SFNT face object initialization. This loads */ + /* the common SFNT tables (head, OS/2, maxp, metrics, etc.) in the */ + /* face object. */ + /* */ + /* <Input> */ + /* stream :: The input stream. */ + /* */ + /* face :: A handle to the target face object. */ + /* */ + /* face_index :: The index of the TrueType font, if we are opening a */ + /* collection. */ + /* */ + /* num_params :: The number of additional parameters. */ + /* */ + /* params :: Optional additional parameters. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* This function must be called after TT_Init_Face_Func(). */ + /* */ + typedef FT_Error + (*TT_Load_Face_Func)( FT_Stream stream, + TT_Face face, + FT_Int face_index, + FT_Int num_params, + FT_Parameter* params ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Done_Face_Func */ + /* */ + /* <Description> */ + /* A callback used to delete the common SFNT data from a face. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* <Note> */ + /* This function does NOT destroy the face object. */ + /* */ + typedef void + (*TT_Done_Face_Func)( TT_Face face ); + + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_SFNT_HeaderRec_Func */ + /* */ + /* <Description> */ + /* Loads the header of a SFNT font file. Supports collections. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* face_index :: The index of the TrueType font, if we are opening a */ + /* collection. */ + /* */ + /* <Output> */ + /* sfnt :: The SFNT header. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The stream cursor must be at the font file's origin. */ + /* */ + /* This function recognizes fonts embedded in a `TrueType */ + /* collection'. */ + /* */ + /* This function checks that the header is valid by looking at the */ + /* values of `search_range', `entry_selector', and `range_shift'. */ + /* */ + typedef FT_Error + (*TT_Load_SFNT_HeaderRec_Func)( TT_Face face, + FT_Stream stream, + FT_Long face_index, + SFNT_Header sfnt ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Directory_Func */ + /* */ + /* <Description> */ + /* Loads the table directory into a face object. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* sfnt :: The SFNT header. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The stream cursor must be on the first byte after the 4-byte font */ + /* format tag. This is the case just after a call to */ + /* TT_Load_Format_Tag(). */ + /* */ + typedef FT_Error + (*TT_Load_Directory_Func)( TT_Face face, + FT_Stream stream, + SFNT_Header sfnt ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Any_Func */ + /* */ + /* <Description> */ + /* Load any font table into client memory. */ + /* */ + /* <Input> */ + /* face :: The face object to look for. */ + /* */ + /* tag :: The tag of table to load. Use the value 0 if you want */ + /* to access the whole font file, else set this parameter */ + /* to a valid TrueType table tag that you can forge with */ + /* the MAKE_TT_TAG macro. */ + /* */ + /* offset :: The starting offset in the table (or the file if */ + /* tag == 0). */ + /* */ + /* length :: The address of the decision variable: */ + /* */ + /* If length == NULL: */ + /* Loads the whole table. Returns an error if */ + /* `offset' == 0! */ + /* */ + /* If *length == 0: */ + /* Exits immediately; returning the length of the given */ + /* table or of the font file, depending on the value of */ + /* `tag'. */ + /* */ + /* If *length != 0: */ + /* Loads the next `length' bytes of table or font, */ + /* starting at offset `offset' (in table or font too). */ + /* */ + /* <Output> */ + /* buffer :: The address of target buffer. */ + /* */ + /* <Return> */ + /* TrueType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_Load_Any_Func)( TT_Face face, + FT_ULong tag, + FT_Long offset, + FT_Byte *buffer, + FT_ULong* length ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Find_SBit_Image_Func */ + /* */ + /* <Description> */ + /* Check whether an embedded bitmap (an `sbit') exists for a given */ + /* glyph, at a given strike. */ + /* */ + /* <Input> */ + /* face :: The target face object. */ + /* */ + /* glyph_index :: The glyph index. */ + /* */ + /* strike_index :: The current strike index. */ + /* */ + /* <Output> */ + /* arange :: The SBit range containing the glyph index. */ + /* */ + /* astrike :: The SBit strike containing the glyph index. */ + /* */ + /* aglyph_offset :: The offset of the glyph data in `EBDT' table. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. Returns */ + /* SFNT_Err_Invalid_Argument if no sbit exists for the requested */ + /* glyph. */ + /* */ + typedef FT_Error + (*TT_Find_SBit_Image_Func)( TT_Face face, + FT_UInt glyph_index, + FT_ULong strike_index, + TT_SBit_Range *arange, + TT_SBit_Strike *astrike, + FT_ULong *aglyph_offset ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_SBit_Metrics_Func */ + /* */ + /* <Description> */ + /* Get the big metrics for a given embedded bitmap. */ + /* */ + /* <Input> */ + /* stream :: The input stream. */ + /* */ + /* range :: The SBit range containing the glyph. */ + /* */ + /* <Output> */ + /* big_metrics :: A big SBit metrics structure for the glyph. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The stream cursor must be positioned at the glyph's offset within */ + /* the `EBDT' table before the call. */ + /* */ + /* If the image format uses variable metrics, the stream cursor is */ + /* positioned just after the metrics header in the `EBDT' table on */ + /* function exit. */ + /* */ + typedef FT_Error + (*TT_Load_SBit_Metrics_Func)( FT_Stream stream, + TT_SBit_Range range, + TT_SBit_Metrics metrics ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_SBit_Image_Func */ + /* */ + /* <Description> */ + /* Load a given glyph sbit image from the font resource. This also */ + /* returns its metrics. */ + /* */ + /* <Input> */ + /* face :: */ + /* The target face object. */ + /* */ + /* strike_index :: */ + /* The strike index. */ + /* */ + /* glyph_index :: */ + /* The current glyph index. */ + /* */ + /* load_flags :: */ + /* The current load flags. */ + /* */ + /* stream :: */ + /* The input stream. */ + /* */ + /* <Output> */ + /* amap :: */ + /* The target pixmap. */ + /* */ + /* ametrics :: */ + /* A big sbit metrics structure for the glyph image. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. Returns an error if no */ + /* glyph sbit exists for the index. */ + /* */ + /* <Note> */ + /* The `map.buffer' field is always freed before the glyph is loaded. */ + /* */ + typedef FT_Error + (*TT_Load_SBit_Image_Func)( TT_Face face, + FT_ULong strike_index, + FT_UInt glyph_index, + FT_UInt load_flags, + FT_Stream stream, + FT_Bitmap *amap, + TT_SBit_MetricsRec *ametrics ); + + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Set_SBit_Strike_OldFunc */ + /* */ + /* <Description> */ + /* Select an sbit strike for a given size request. */ + /* */ + /* <Input> */ + /* face :: The target face object. */ + /* */ + /* req :: The size request. */ + /* */ + /* <Output> */ + /* astrike_index :: The index of the sbit strike. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. Returns an error if no */ + /* sbit strike exists for the selected ppem values. */ + /* */ + typedef FT_Error + (*TT_Set_SBit_Strike_OldFunc)( TT_Face face, + FT_UInt x_ppem, + FT_UInt y_ppem, + FT_ULong* astrike_index ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_CharMap_Load_Func */ + /* */ + /* <Description> */ + /* Loads a given TrueType character map into memory. */ + /* */ + /* <Input> */ + /* face :: A handle to the parent face object. */ + /* */ + /* stream :: A handle to the current stream object. */ + /* */ + /* <InOut> */ + /* cmap :: A pointer to a cmap object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The function assumes that the stream is already in use (i.e., */ + /* opened). In case of error, all partially allocated tables are */ + /* released. */ + /* */ + typedef FT_Error + (*TT_CharMap_Load_Func)( TT_Face face, + void* cmap, + FT_Stream input ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_CharMap_Free_Func */ + /* */ + /* <Description> */ + /* Destroys a character mapping table. */ + /* */ + /* <Input> */ + /* face :: A handle to the parent face object. */ + /* */ + /* cmap :: A handle to a cmap object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_CharMap_Free_Func)( TT_Face face, + void* cmap ); + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Set_SBit_Strike_Func */ + /* */ + /* <Description> */ + /* Select an sbit strike for a given size request. */ + /* */ + /* <Input> */ + /* face :: The target face object. */ + /* */ + /* req :: The size request. */ + /* */ + /* <Output> */ + /* astrike_index :: The index of the sbit strike. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. Returns an error if no */ + /* sbit strike exists for the selected ppem values. */ + /* */ + typedef FT_Error + (*TT_Set_SBit_Strike_Func)( TT_Face face, + FT_Size_Request req, + FT_ULong* astrike_index ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Strike_Metrics_Func */ + /* */ + /* <Description> */ + /* Load the metrics of a given strike. */ + /* */ + /* <Input> */ + /* face :: The target face object. */ + /* */ + /* strike_index :: The strike index. */ + /* */ + /* <Output> */ + /* metrics :: the metrics of the strike. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. Returns an error if no */ + /* such sbit strike exists. */ + /* */ + typedef FT_Error + (*TT_Load_Strike_Metrics_Func)( TT_Face face, + FT_ULong strike_index, + FT_Size_Metrics* metrics ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Get_PS_Name_Func */ + /* */ + /* <Description> */ + /* Get the PostScript glyph name of a glyph. */ + /* */ + /* <Input> */ + /* idx :: The glyph index. */ + /* */ + /* PSname :: The address of a string pointer. Will be NULL in case */ + /* of error, otherwise it is a pointer to the glyph name. */ + /* */ + /* You must not modify the returned string! */ + /* */ + /* <Output> */ + /* FreeType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_Get_PS_Name_Func)( TT_Face face, + FT_UInt idx, + FT_String** PSname ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Metrics_Func */ + /* */ + /* <Description> */ + /* Load a metrics table, which is a table with a horizontal and a */ + /* vertical version. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* vertical :: A boolean flag. If set, load the vertical one. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_Load_Metrics_Func)( TT_Face face, + FT_Stream stream, + FT_Bool vertical ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Get_Metrics_Func */ + /* */ + /* <Description> */ + /* Load the horizontal or vertical header in a face object. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* vertical :: A boolean flag. If set, load vertical metrics. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_Get_Metrics_Func)( TT_Face face, + FT_Bool vertical, + FT_UInt gindex, + FT_Short* abearing, + FT_UShort* aadvance ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Load_Table_Func */ + /* */ + /* <Description> */ + /* Load a given TrueType table. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The function uses `face->goto_table' to seek the stream to the */ + /* start of the table, except while loading the font directory. */ + /* */ + typedef FT_Error + (*TT_Load_Table_Func)( TT_Face face, + FT_Stream stream ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Free_Table_Func */ + /* */ + /* <Description> */ + /* Free a given TrueType table. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + typedef void + (*TT_Free_Table_Func)( TT_Face face ); + + + /* + * @functype: + * TT_Face_GetKerningFunc + * + * @description: + * Return the horizontal kerning value between two glyphs. + * + * @input: + * face :: A handle to the source face object. + * left_glyph :: The left glyph index. + * right_glyph :: The right glyph index. + * + * @return: + * The kerning value in font units. + */ + typedef FT_Int + (*TT_Face_GetKerningFunc)( TT_Face face, + FT_UInt left_glyph, + FT_UInt right_glyph ); + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* SFNT_Interface */ + /* */ + /* <Description> */ + /* This structure holds pointers to the functions used to load and */ + /* free the basic tables that are required in a `sfnt' font file. */ + /* */ + /* <Fields> */ + /* Check the various xxx_Func() descriptions for details. */ + /* */ + typedef struct SFNT_Interface_ + { + TT_Loader_GotoTableFunc goto_table; + + TT_Init_Face_Func init_face; + TT_Load_Face_Func load_face; + TT_Done_Face_Func done_face; + FT_Module_Requester get_interface; + + TT_Load_Any_Func load_any; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + TT_Load_SFNT_HeaderRec_Func load_sfnt_header; + TT_Load_Directory_Func load_directory; +#endif + + /* these functions are called by `load_face' but they can also */ + /* be called from external modules, if there is a need to do so */ + TT_Load_Table_Func load_head; + TT_Load_Metrics_Func load_hhea; + TT_Load_Table_Func load_cmap; + TT_Load_Table_Func load_maxp; + TT_Load_Table_Func load_os2; + TT_Load_Table_Func load_post; + + TT_Load_Table_Func load_name; + TT_Free_Table_Func free_name; + + /* optional tables */ +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + TT_Load_Table_Func load_hdmx_stub; + TT_Free_Table_Func free_hdmx_stub; +#endif + + /* this field was called `load_kerning' up to version 2.1.10 */ + TT_Load_Table_Func load_kern; + + TT_Load_Table_Func load_gasp; + TT_Load_Table_Func load_pclt; + + /* see `ttload.h'; this field was called `load_bitmap_header' up to */ + /* version 2.1.10 */ + TT_Load_Table_Func load_bhed; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /* see `ttsbit.h' */ + TT_Set_SBit_Strike_OldFunc set_sbit_strike_stub; + TT_Load_Table_Func load_sbits_stub; + + /* + * The following two fields appeared in version 2.1.8, and were placed + * between `load_sbits' and `load_sbit_image'. We support them as a + * special exception since they are used by Xfont library within the + * X.Org xserver, and because the probability that other rogue clients + * use the other version 2.1.7 fields below is _extremely_ low. + * + * Note that this forces us to disable an interesting memory-saving + * optimization though... + */ + + TT_Find_SBit_Image_Func find_sbit_image; + TT_Load_SBit_Metrics_Func load_sbit_metrics; + +#endif + + TT_Load_SBit_Image_Func load_sbit_image; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + TT_Free_Table_Func free_sbits_stub; +#endif + + /* see `ttpost.h' */ + TT_Get_PS_Name_Func get_psname; + TT_Free_Table_Func free_psnames; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + TT_CharMap_Load_Func load_charmap_stub; + TT_CharMap_Free_Func free_charmap_stub; +#endif + + /* starting here, the structure differs from version 2.1.7 */ + + /* this field was introduced in version 2.1.8, named `get_psname' */ + TT_Face_GetKerningFunc get_kerning; + + /* new elements introduced after version 2.1.10 */ + + /* load the font directory, i.e., the offset table and */ + /* the table directory */ + TT_Load_Table_Func load_font_dir; + TT_Load_Metrics_Func load_hmtx; + + TT_Load_Table_Func load_eblc; + TT_Free_Table_Func free_eblc; + + TT_Set_SBit_Strike_Func set_sbit_strike; + TT_Load_Strike_Metrics_Func load_strike_metrics; + + TT_Get_Metrics_Func get_metrics; + + } SFNT_Interface; + + + /* transitional */ + typedef SFNT_Interface* SFNT_Service; + +#ifndef FT_CONFIG_OPTION_PIC + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS +#define FT_DEFINE_DRIVERS_OLD_INTERNAL(a) \ + a, +#else + #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a) +#endif +#define FT_INTERNAL(a) \ + a, + +#define FT_DEFINE_SFNT_INTERFACE(class_, \ + goto_table_, init_face_, load_face_, done_face_, get_interface_, \ + load_any_, load_sfnt_header_, load_directory_, load_head_, \ + load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_, \ + load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_, \ + load_kern_, load_gasp_, load_pclt_, load_bhed_, \ + set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_, \ + load_sbit_metrics_, load_sbit_image_, free_sbits_stub_, \ + get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_, \ + get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_, \ + set_sbit_strike_, load_strike_metrics_, get_metrics_ ) \ + static const SFNT_Interface class_ = \ + { \ + FT_INTERNAL(goto_table_) \ + FT_INTERNAL(init_face_) \ + FT_INTERNAL(load_face_) \ + FT_INTERNAL(done_face_) \ + FT_INTERNAL(get_interface_) \ + FT_INTERNAL(load_any_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory_) \ + FT_INTERNAL(load_head_) \ + FT_INTERNAL(load_hhea_) \ + FT_INTERNAL(load_cmap_) \ + FT_INTERNAL(load_maxp_) \ + FT_INTERNAL(load_os2_) \ + FT_INTERNAL(load_post_) \ + FT_INTERNAL(load_name_) \ + FT_INTERNAL(free_name_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub_) \ + FT_INTERNAL(load_kern_) \ + FT_INTERNAL(load_gasp_) \ + FT_INTERNAL(load_pclt_) \ + FT_INTERNAL(load_bhed_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics_) \ + FT_INTERNAL(load_sbit_image_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub_) \ + FT_INTERNAL(get_psname_) \ + FT_INTERNAL(free_psnames_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub_) \ + FT_INTERNAL(get_kerning_) \ + FT_INTERNAL(load_font_dir_) \ + FT_INTERNAL(load_hmtx_) \ + FT_INTERNAL(load_eblc_) \ + FT_INTERNAL(free_eblc_) \ + FT_INTERNAL(set_sbit_strike_) \ + FT_INTERNAL(load_strike_metrics_) \ + FT_INTERNAL(get_metrics_) \ + }; + +#else /* FT_CONFIG_OPTION_PIC */ + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS +#define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_) \ + clazz->a = a_; +#else + #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_) +#endif +#define FT_INTERNAL(a, a_) \ + clazz->a = a_; + +#define FT_DEFINE_SFNT_INTERFACE(class_, \ + goto_table_, init_face_, load_face_, done_face_, get_interface_, \ + load_any_, load_sfnt_header_, load_directory_, load_head_, \ + load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_, \ + load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_, \ + load_kern_, load_gasp_, load_pclt_, load_bhed_, \ + set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_, \ + load_sbit_metrics_, load_sbit_image_, free_sbits_stub_, \ + get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_, \ + get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_, \ + set_sbit_strike_, load_strike_metrics_, get_metrics_ ) \ + void \ + FT_Init_Class_##class_( FT_Library library, SFNT_Interface* clazz ) \ + { \ + FT_UNUSED(library); \ + FT_INTERNAL(goto_table,goto_table_) \ + FT_INTERNAL(init_face,init_face_) \ + FT_INTERNAL(load_face,load_face_) \ + FT_INTERNAL(done_face,done_face_) \ + FT_INTERNAL(get_interface,get_interface_) \ + FT_INTERNAL(load_any,load_any_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header,load_sfnt_header_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory,load_directory_) \ + FT_INTERNAL(load_head,load_head_) \ + FT_INTERNAL(load_hhea,load_hhea_) \ + FT_INTERNAL(load_cmap,load_cmap_) \ + FT_INTERNAL(load_maxp,load_maxp_) \ + FT_INTERNAL(load_os2,load_os2_) \ + FT_INTERNAL(load_post,load_post_) \ + FT_INTERNAL(load_name,load_name_) \ + FT_INTERNAL(free_name,free_name_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub,load_hdmx_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub,free_hdmx_stub_) \ + FT_INTERNAL(load_kern,load_kern_) \ + FT_INTERNAL(load_gasp,load_gasp_) \ + FT_INTERNAL(load_pclt,load_pclt_) \ + FT_INTERNAL(load_bhed,load_bhed_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub,set_sbit_strike_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub,load_sbits_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image,find_sbit_image_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics,load_sbit_metrics_) \ + FT_INTERNAL(load_sbit_image,load_sbit_image_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub,free_sbits_stub_) \ + FT_INTERNAL(get_psname,get_psname_) \ + FT_INTERNAL(free_psnames,free_psnames_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub,load_charmap_stub_) \ + FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub,free_charmap_stub_) \ + FT_INTERNAL(get_kerning,get_kerning_) \ + FT_INTERNAL(load_font_dir,load_font_dir_) \ + FT_INTERNAL(load_hmtx,load_hmtx_) \ + FT_INTERNAL(load_eblc,load_eblc_) \ + FT_INTERNAL(free_eblc,free_eblc_) \ + FT_INTERNAL(set_sbit_strike,set_sbit_strike_) \ + FT_INTERNAL(load_strike_metrics,load_strike_metrics_) \ + FT_INTERNAL(get_metrics,get_metrics_) \ + } + +#endif /* FT_CONFIG_OPTION_PIC */ + +FT_END_HEADER + +#endif /* __SFNT_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/t1types.h b/other/freetype/include/freetype/internal/t1types.h new file mode 100644 index 0000000..f859de2 --- /dev/null +++ b/other/freetype/include/freetype/internal/t1types.h @@ -0,0 +1,259 @@ +/***************************************************************************/ +/* */ +/* t1types.h */ +/* */ +/* Basic Type1/Type2 type definitions and interface (specification */ +/* only). */ +/* */ +/* Copyright 1996-2004, 2006, 2008, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __T1TYPES_H__ +#define __T1TYPES_H__ + + +#include <ft2build.h> +#include FT_TYPE1_TABLES_H +#include FT_INTERNAL_POSTSCRIPT_HINTS_H +#include FT_INTERNAL_SERVICE_H +#include FT_SERVICE_POSTSCRIPT_CMAPS_H + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** REQUIRED TYPE1/TYPE2 TABLES DEFINITIONS ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* T1_EncodingRec */ + /* */ + /* <Description> */ + /* A structure modeling a custom encoding. */ + /* */ + /* <Fields> */ + /* num_chars :: The number of character codes in the encoding. */ + /* Usually 256. */ + /* */ + /* code_first :: The lowest valid character code in the encoding. */ + /* */ + /* code_last :: The highest valid character code in the encoding */ + /* + 1. When equal to code_first there are no valid */ + /* character codes. */ + /* */ + /* char_index :: An array of corresponding glyph indices. */ + /* */ + /* char_name :: An array of corresponding glyph names. */ + /* */ + typedef struct T1_EncodingRecRec_ + { + FT_Int num_chars; + FT_Int code_first; + FT_Int code_last; + + FT_UShort* char_index; + FT_String** char_name; + + } T1_EncodingRec, *T1_Encoding; + + + /* used to hold extra data of PS_FontInfoRec that + * cannot be stored in the publicly defined structure. + * + * Note these can't be blended with multiple-masters. + */ + typedef struct PS_FontExtraRec_ + { + FT_UShort fs_type; + + } PS_FontExtraRec; + + + typedef struct T1_FontRec_ + { + PS_FontInfoRec font_info; /* font info dictionary */ + PS_FontExtraRec font_extra; /* font info extra fields */ + PS_PrivateRec private_dict; /* private dictionary */ + FT_String* font_name; /* top-level dictionary */ + + T1_EncodingType encoding_type; + T1_EncodingRec encoding; + + FT_Byte* subrs_block; + FT_Byte* charstrings_block; + FT_Byte* glyph_names_block; + + FT_Int num_subrs; + FT_Byte** subrs; + FT_PtrDist* subrs_len; + + FT_Int num_glyphs; + FT_String** glyph_names; /* array of glyph names */ + FT_Byte** charstrings; /* array of glyph charstrings */ + FT_PtrDist* charstrings_len; + + FT_Byte paint_type; + FT_Byte font_type; + FT_Matrix font_matrix; + FT_Vector font_offset; + FT_BBox font_bbox; + FT_Long font_id; + + FT_Fixed stroke_width; + + } T1_FontRec, *T1_Font; + + + typedef struct CID_SubrsRec_ + { + FT_UInt num_subrs; + FT_Byte** code; + + } CID_SubrsRec, *CID_Subrs; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** AFM FONT INFORMATION STRUCTURES ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + typedef struct AFM_TrackKernRec_ + { + FT_Int degree; + FT_Fixed min_ptsize; + FT_Fixed min_kern; + FT_Fixed max_ptsize; + FT_Fixed max_kern; + + } AFM_TrackKernRec, *AFM_TrackKern; + + typedef struct AFM_KernPairRec_ + { + FT_Int index1; + FT_Int index2; + FT_Int x; + FT_Int y; + + } AFM_KernPairRec, *AFM_KernPair; + + typedef struct AFM_FontInfoRec_ + { + FT_Bool IsCIDFont; + FT_BBox FontBBox; + FT_Fixed Ascender; + FT_Fixed Descender; + AFM_TrackKern TrackKerns; /* free if non-NULL */ + FT_Int NumTrackKern; + AFM_KernPair KernPairs; /* free if non-NULL */ + FT_Int NumKernPair; + + } AFM_FontInfoRec, *AFM_FontInfo; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** ORIGINAL T1_FACE CLASS DEFINITION ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + typedef struct T1_FaceRec_* T1_Face; + typedef struct CID_FaceRec_* CID_Face; + + + typedef struct T1_FaceRec_ + { + FT_FaceRec root; + T1_FontRec type1; + const void* psnames; + const void* psaux; + const void* afm_data; + FT_CharMapRec charmaprecs[2]; + FT_CharMap charmaps[2]; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + PS_Unicodes unicode_map; +#endif + + /* support for Multiple Masters fonts */ + PS_Blend blend; + + /* undocumented, optional: indices of subroutines that express */ + /* the NormalizeDesignVector and the ConvertDesignVector procedure, */ + /* respectively, as Type 2 charstrings; -1 if keywords not present */ + FT_Int ndv_idx; + FT_Int cdv_idx; + + /* undocumented, optional: has the same meaning as len_buildchar */ + /* for Type 2 fonts; manipulated by othersubrs 19, 24, and 25 */ + FT_UInt len_buildchar; + FT_Long* buildchar; + + /* since version 2.1 - interface to PostScript hinter */ + const void* pshinter; + + } T1_FaceRec; + + + typedef struct CID_FaceRec_ + { + FT_FaceRec root; + void* psnames; + void* psaux; + CID_FaceInfoRec cid; + PS_FontExtraRec font_extra; +#if 0 + void* afm_data; +#endif + CID_Subrs subrs; + + /* since version 2.1 - interface to PostScript hinter */ + void* pshinter; + + /* since version 2.1.8, but was originally positioned after `afm_data' */ + FT_Byte* binary_data; /* used if hex data has been converted */ + FT_Stream cid_stream; + + } CID_FaceRec; + + +FT_END_HEADER + +#endif /* __T1TYPES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/internal/tttypes.h b/other/freetype/include/freetype/internal/tttypes.h new file mode 100644 index 0000000..acbb863 --- /dev/null +++ b/other/freetype/include/freetype/internal/tttypes.h @@ -0,0 +1,1543 @@ +/***************************************************************************/ +/* */ +/* tttypes.h */ +/* */ +/* Basic SFNT/TrueType type definitions and interface (specification */ +/* only). */ +/* */ +/* Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __TTTYPES_H__ +#define __TTTYPES_H__ + + +#include <ft2build.h> +#include FT_TRUETYPE_TABLES_H +#include FT_INTERNAL_OBJECTS_H + +#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT +#include FT_MULTIPLE_MASTERS_H +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** REQUIRED TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TTC_HeaderRec */ + /* */ + /* <Description> */ + /* TrueType collection header. This table contains the offsets of */ + /* the font headers of each distinct TrueType face in the file. */ + /* */ + /* <Fields> */ + /* tag :: Must be `ttc ' to indicate a TrueType collection. */ + /* */ + /* version :: The version number. */ + /* */ + /* count :: The number of faces in the collection. The */ + /* specification says this should be an unsigned long, but */ + /* we use a signed long since we need the value -1 for */ + /* specific purposes. */ + /* */ + /* offsets :: The offsets of the font headers, one per face. */ + /* */ + typedef struct TTC_HeaderRec_ + { + FT_ULong tag; + FT_Fixed version; + FT_Long count; + FT_ULong* offsets; + + } TTC_HeaderRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* SFNT_HeaderRec */ + /* */ + /* <Description> */ + /* SFNT file format header. */ + /* */ + /* <Fields> */ + /* format_tag :: The font format tag. */ + /* */ + /* num_tables :: The number of tables in file. */ + /* */ + /* search_range :: Must be `16 * (max power of 2 <= num_tables)'. */ + /* */ + /* entry_selector :: Must be log2 of `search_range / 16'. */ + /* */ + /* range_shift :: Must be `num_tables * 16 - search_range'. */ + /* */ + typedef struct SFNT_HeaderRec_ + { + FT_ULong format_tag; + FT_UShort num_tables; + FT_UShort search_range; + FT_UShort entry_selector; + FT_UShort range_shift; + + FT_ULong offset; /* not in file */ + + } SFNT_HeaderRec, *SFNT_Header; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_TableRec */ + /* */ + /* <Description> */ + /* This structure describes a given table of a TrueType font. */ + /* */ + /* <Fields> */ + /* Tag :: A four-bytes tag describing the table. */ + /* */ + /* CheckSum :: The table checksum. This value can be ignored. */ + /* */ + /* Offset :: The offset of the table from the start of the TrueType */ + /* font in its resource. */ + /* */ + /* Length :: The table length (in bytes). */ + /* */ + typedef struct TT_TableRec_ + { + FT_ULong Tag; /* table type */ + FT_ULong CheckSum; /* table checksum */ + FT_ULong Offset; /* table file offset */ + FT_ULong Length; /* table length */ + + } TT_TableRec, *TT_Table; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_LongMetricsRec */ + /* */ + /* <Description> */ + /* A structure modeling the long metrics of the `hmtx' and `vmtx' */ + /* TrueType tables. The values are expressed in font units. */ + /* */ + /* <Fields> */ + /* advance :: The advance width or height for the glyph. */ + /* */ + /* bearing :: The left-side or top-side bearing for the glyph. */ + /* */ + typedef struct TT_LongMetricsRec_ + { + FT_UShort advance; + FT_Short bearing; + + } TT_LongMetricsRec, *TT_LongMetrics; + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* TT_ShortMetrics */ + /* */ + /* <Description> */ + /* A simple type to model the short metrics of the `hmtx' and `vmtx' */ + /* tables. */ + /* */ + typedef FT_Short TT_ShortMetrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_NameEntryRec */ + /* */ + /* <Description> */ + /* A structure modeling TrueType name records. Name records are used */ + /* to store important strings like family name, style name, */ + /* copyright, etc. in _localized_ versions (i.e., language, encoding, */ + /* etc). */ + /* */ + /* <Fields> */ + /* platformID :: The ID of the name's encoding platform. */ + /* */ + /* encodingID :: The platform-specific ID for the name's encoding. */ + /* */ + /* languageID :: The platform-specific ID for the name's language. */ + /* */ + /* nameID :: The ID specifying what kind of name this is. */ + /* */ + /* stringLength :: The length of the string in bytes. */ + /* */ + /* stringOffset :: The offset to the string in the `name' table. */ + /* */ + /* string :: A pointer to the string's bytes. Note that these */ + /* are usually UTF-16 encoded characters. */ + /* */ + typedef struct TT_NameEntryRec_ + { + FT_UShort platformID; + FT_UShort encodingID; + FT_UShort languageID; + FT_UShort nameID; + FT_UShort stringLength; + FT_ULong stringOffset; + + /* this last field is not defined in the spec */ + /* but used by the FreeType engine */ + + FT_Byte* string; + + } TT_NameEntryRec, *TT_NameEntry; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_NameTableRec */ + /* */ + /* <Description> */ + /* A structure modeling the TrueType name table. */ + /* */ + /* <Fields> */ + /* format :: The format of the name table. */ + /* */ + /* numNameRecords :: The number of names in table. */ + /* */ + /* storageOffset :: The offset of the name table in the `name' */ + /* TrueType table. */ + /* */ + /* names :: An array of name records. */ + /* */ + /* stream :: the file's input stream. */ + /* */ + typedef struct TT_NameTableRec_ + { + FT_UShort format; + FT_UInt numNameRecords; + FT_UInt storageOffset; + TT_NameEntryRec* names; + FT_Stream stream; + + } TT_NameTableRec, *TT_NameTable; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** OPTIONAL TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_GaspRangeRec */ + /* */ + /* <Description> */ + /* A tiny structure used to model a gasp range according to the */ + /* TrueType specification. */ + /* */ + /* <Fields> */ + /* maxPPEM :: The maximum ppem value to which `gaspFlag' applies. */ + /* */ + /* gaspFlag :: A flag describing the grid-fitting and anti-aliasing */ + /* modes to be used. */ + /* */ + typedef struct TT_GaspRangeRec_ + { + FT_UShort maxPPEM; + FT_UShort gaspFlag; + + } TT_GaspRangeRec, *TT_GaspRange; + + +#define TT_GASP_GRIDFIT 0x01 +#define TT_GASP_DOGRAY 0x02 + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_GaspRec */ + /* */ + /* <Description> */ + /* A structure modeling the TrueType `gasp' table used to specify */ + /* grid-fitting and anti-aliasing behaviour. */ + /* */ + /* <Fields> */ + /* version :: The version number. */ + /* */ + /* numRanges :: The number of gasp ranges in table. */ + /* */ + /* gaspRanges :: An array of gasp ranges. */ + /* */ + typedef struct TT_Gasp_ + { + FT_UShort version; + FT_UShort numRanges; + TT_GaspRange gaspRanges; + + } TT_GaspRec; + + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_HdmxEntryRec */ + /* */ + /* <Description> */ + /* A small structure used to model the pre-computed widths of a given */ + /* size. They are found in the `hdmx' table. */ + /* */ + /* <Fields> */ + /* ppem :: The pixels per EM value at which these metrics apply. */ + /* */ + /* max_width :: The maximum advance width for this metric. */ + /* */ + /* widths :: An array of widths. Note: These are 8-bit bytes. */ + /* */ + typedef struct TT_HdmxEntryRec_ + { + FT_Byte ppem; + FT_Byte max_width; + FT_Byte* widths; + + } TT_HdmxEntryRec, *TT_HdmxEntry; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_HdmxRec */ + /* */ + /* <Description> */ + /* A structure used to model the `hdmx' table, which contains */ + /* pre-computed widths for a set of given sizes/dimensions. */ + /* */ + /* <Fields> */ + /* version :: The version number. */ + /* */ + /* num_records :: The number of hdmx records. */ + /* */ + /* records :: An array of hdmx records. */ + /* */ + typedef struct TT_HdmxRec_ + { + FT_UShort version; + FT_Short num_records; + TT_HdmxEntry records; + + } TT_HdmxRec, *TT_Hdmx; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Kern0_PairRec */ + /* */ + /* <Description> */ + /* A structure used to model a kerning pair for the kerning table */ + /* format 0. The engine now loads this table if it finds one in the */ + /* font file. */ + /* */ + /* <Fields> */ + /* left :: The index of the left glyph in pair. */ + /* */ + /* right :: The index of the right glyph in pair. */ + /* */ + /* value :: The kerning distance. A positive value spaces the */ + /* glyphs, a negative one makes them closer. */ + /* */ + typedef struct TT_Kern0_PairRec_ + { + FT_UShort left; /* index of left glyph in pair */ + FT_UShort right; /* index of right glyph in pair */ + FT_FWord value; /* kerning value */ + + } TT_Kern0_PairRec, *TT_Kern0_Pair; + +#endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** EMBEDDED BITMAPS SUPPORT ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_MetricsRec */ + /* */ + /* <Description> */ + /* A structure used to hold the big metrics of a given glyph bitmap */ + /* in a TrueType or OpenType font. These are usually found in the */ + /* `EBDT' (Microsoft) or `bloc' (Apple) table. */ + /* */ + /* <Fields> */ + /* height :: The glyph height in pixels. */ + /* */ + /* width :: The glyph width in pixels. */ + /* */ + /* horiBearingX :: The horizontal left bearing. */ + /* */ + /* horiBearingY :: The horizontal top bearing. */ + /* */ + /* horiAdvance :: The horizontal advance. */ + /* */ + /* vertBearingX :: The vertical left bearing. */ + /* */ + /* vertBearingY :: The vertical top bearing. */ + /* */ + /* vertAdvance :: The vertical advance. */ + /* */ + typedef struct TT_SBit_MetricsRec_ + { + FT_Byte height; + FT_Byte width; + + FT_Char horiBearingX; + FT_Char horiBearingY; + FT_Byte horiAdvance; + + FT_Char vertBearingX; + FT_Char vertBearingY; + FT_Byte vertAdvance; + + } TT_SBit_MetricsRec, *TT_SBit_Metrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_SmallMetricsRec */ + /* */ + /* <Description> */ + /* A structure used to hold the small metrics of a given glyph bitmap */ + /* in a TrueType or OpenType font. These are usually found in the */ + /* `EBDT' (Microsoft) or the `bdat' (Apple) table. */ + /* */ + /* <Fields> */ + /* height :: The glyph height in pixels. */ + /* */ + /* width :: The glyph width in pixels. */ + /* */ + /* bearingX :: The left-side bearing. */ + /* */ + /* bearingY :: The top-side bearing. */ + /* */ + /* advance :: The advance width or height. */ + /* */ + typedef struct TT_SBit_Small_Metrics_ + { + FT_Byte height; + FT_Byte width; + + FT_Char bearingX; + FT_Char bearingY; + FT_Byte advance; + + } TT_SBit_SmallMetricsRec, *TT_SBit_SmallMetrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_LineMetricsRec */ + /* */ + /* <Description> */ + /* A structure used to describe the text line metrics of a given */ + /* bitmap strike, for either a horizontal or vertical layout. */ + /* */ + /* <Fields> */ + /* ascender :: The ascender in pixels. */ + /* */ + /* descender :: The descender in pixels. */ + /* */ + /* max_width :: The maximum glyph width in pixels. */ + /* */ + /* caret_slope_enumerator :: Rise of the caret slope, typically set */ + /* to 1 for non-italic fonts. */ + /* */ + /* caret_slope_denominator :: Rise of the caret slope, typically set */ + /* to 0 for non-italic fonts. */ + /* */ + /* caret_offset :: Offset in pixels to move the caret for */ + /* proper positioning. */ + /* */ + /* min_origin_SB :: Minimum of horiBearingX (resp. */ + /* vertBearingY). */ + /* min_advance_SB :: Minimum of */ + /* */ + /* horizontal advance - */ + /* ( horiBearingX + width ) */ + /* */ + /* resp. */ + /* */ + /* vertical advance - */ + /* ( vertBearingY + height ) */ + /* */ + /* max_before_BL :: Maximum of horiBearingY (resp. */ + /* vertBearingY). */ + /* */ + /* min_after_BL :: Minimum of */ + /* */ + /* horiBearingY - height */ + /* */ + /* resp. */ + /* */ + /* vertBearingX - width */ + /* */ + /* pads :: Unused (to make the size of the record */ + /* a multiple of 32 bits. */ + /* */ + typedef struct TT_SBit_LineMetricsRec_ + { + FT_Char ascender; + FT_Char descender; + FT_Byte max_width; + FT_Char caret_slope_numerator; + FT_Char caret_slope_denominator; + FT_Char caret_offset; + FT_Char min_origin_SB; + FT_Char min_advance_SB; + FT_Char max_before_BL; + FT_Char min_after_BL; + FT_Char pads[2]; + + } TT_SBit_LineMetricsRec, *TT_SBit_LineMetrics; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_RangeRec */ + /* */ + /* <Description> */ + /* A TrueType/OpenType subIndexTable as defined in the `EBLC' */ + /* (Microsoft) or `bloc' (Apple) tables. */ + /* */ + /* <Fields> */ + /* first_glyph :: The first glyph index in the range. */ + /* */ + /* last_glyph :: The last glyph index in the range. */ + /* */ + /* index_format :: The format of index table. Valid values are 1 */ + /* to 5. */ + /* */ + /* image_format :: The format of `EBDT' image data. */ + /* */ + /* image_offset :: The offset to image data in `EBDT'. */ + /* */ + /* image_size :: For index formats 2 and 5. This is the size in */ + /* bytes of each glyph bitmap. */ + /* */ + /* big_metrics :: For index formats 2 and 5. This is the big */ + /* metrics for each glyph bitmap. */ + /* */ + /* num_glyphs :: For index formats 4 and 5. This is the number of */ + /* glyphs in the code array. */ + /* */ + /* glyph_offsets :: For index formats 1 and 3. */ + /* */ + /* glyph_codes :: For index formats 4 and 5. */ + /* */ + /* table_offset :: The offset of the index table in the `EBLC' */ + /* table. Only used during strike loading. */ + /* */ + typedef struct TT_SBit_RangeRec_ + { + FT_UShort first_glyph; + FT_UShort last_glyph; + + FT_UShort index_format; + FT_UShort image_format; + FT_ULong image_offset; + + FT_ULong image_size; + TT_SBit_MetricsRec metrics; + FT_ULong num_glyphs; + + FT_ULong* glyph_offsets; + FT_UShort* glyph_codes; + + FT_ULong table_offset; + + } TT_SBit_RangeRec, *TT_SBit_Range; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_StrikeRec */ + /* */ + /* <Description> */ + /* A structure used describe a given bitmap strike in the `EBLC' */ + /* (Microsoft) or `bloc' (Apple) tables. */ + /* */ + /* <Fields> */ + /* num_index_ranges :: The number of index ranges. */ + /* */ + /* index_ranges :: An array of glyph index ranges. */ + /* */ + /* color_ref :: Unused. `color_ref' is put in for future */ + /* enhancements, but these fields are already */ + /* in use by other platforms (e.g. Newton). */ + /* For details, please see */ + /* */ + /* http://fonts.apple.com/ */ + /* TTRefMan/RM06/Chap6bloc.html */ + /* */ + /* hori :: The line metrics for horizontal layouts. */ + /* */ + /* vert :: The line metrics for vertical layouts. */ + /* */ + /* start_glyph :: The lowest glyph index for this strike. */ + /* */ + /* end_glyph :: The highest glyph index for this strike. */ + /* */ + /* x_ppem :: The number of horizontal pixels per EM. */ + /* */ + /* y_ppem :: The number of vertical pixels per EM. */ + /* */ + /* bit_depth :: The bit depth. Valid values are 1, 2, 4, */ + /* and 8. */ + /* */ + /* flags :: Is this a vertical or horizontal strike? For */ + /* details, please see */ + /* */ + /* http://fonts.apple.com/ */ + /* TTRefMan/RM06/Chap6bloc.html */ + /* */ + typedef struct TT_SBit_StrikeRec_ + { + FT_Int num_ranges; + TT_SBit_Range sbit_ranges; + FT_ULong ranges_offset; + + FT_ULong color_ref; + + TT_SBit_LineMetricsRec hori; + TT_SBit_LineMetricsRec vert; + + FT_UShort start_glyph; + FT_UShort end_glyph; + + FT_Byte x_ppem; + FT_Byte y_ppem; + + FT_Byte bit_depth; + FT_Char flags; + + } TT_SBit_StrikeRec, *TT_SBit_Strike; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_ComponentRec */ + /* */ + /* <Description> */ + /* A simple structure to describe a compound sbit element. */ + /* */ + /* <Fields> */ + /* glyph_code :: The element's glyph index. */ + /* */ + /* x_offset :: The element's left bearing. */ + /* */ + /* y_offset :: The element's top bearing. */ + /* */ + typedef struct TT_SBit_ComponentRec_ + { + FT_UShort glyph_code; + FT_Char x_offset; + FT_Char y_offset; + + } TT_SBit_ComponentRec, *TT_SBit_Component; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_SBit_ScaleRec */ + /* */ + /* <Description> */ + /* A structure used describe a given bitmap scaling table, as defined */ + /* in the `EBSC' table. */ + /* */ + /* <Fields> */ + /* hori :: The horizontal line metrics. */ + /* */ + /* vert :: The vertical line metrics. */ + /* */ + /* x_ppem :: The number of horizontal pixels per EM. */ + /* */ + /* y_ppem :: The number of vertical pixels per EM. */ + /* */ + /* x_ppem_substitute :: Substitution x_ppem value. */ + /* */ + /* y_ppem_substitute :: Substitution y_ppem value. */ + /* */ + typedef struct TT_SBit_ScaleRec_ + { + TT_SBit_LineMetricsRec hori; + TT_SBit_LineMetricsRec vert; + + FT_Byte x_ppem; + FT_Byte y_ppem; + + FT_Byte x_ppem_substitute; + FT_Byte y_ppem_substitute; + + } TT_SBit_ScaleRec, *TT_SBit_Scale; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** POSTSCRIPT GLYPH NAMES SUPPORT ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Post_20Rec */ + /* */ + /* <Description> */ + /* Postscript names sub-table, format 2.0. Stores the PS name of */ + /* each glyph in the font face. */ + /* */ + /* <Fields> */ + /* num_glyphs :: The number of named glyphs in the table. */ + /* */ + /* num_names :: The number of PS names stored in the table. */ + /* */ + /* glyph_indices :: The indices of the glyphs in the names arrays. */ + /* */ + /* glyph_names :: The PS names not in Mac Encoding. */ + /* */ + typedef struct TT_Post_20Rec_ + { + FT_UShort num_glyphs; + FT_UShort num_names; + FT_UShort* glyph_indices; + FT_Char** glyph_names; + + } TT_Post_20Rec, *TT_Post_20; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Post_25Rec */ + /* */ + /* <Description> */ + /* Postscript names sub-table, format 2.5. Stores the PS name of */ + /* each glyph in the font face. */ + /* */ + /* <Fields> */ + /* num_glyphs :: The number of glyphs in the table. */ + /* */ + /* offsets :: An array of signed offsets in a normal Mac */ + /* Postscript name encoding. */ + /* */ + typedef struct TT_Post_25_ + { + FT_UShort num_glyphs; + FT_Char* offsets; + + } TT_Post_25Rec, *TT_Post_25; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Post_NamesRec */ + /* */ + /* <Description> */ + /* Postscript names table, either format 2.0 or 2.5. */ + /* */ + /* <Fields> */ + /* loaded :: A flag to indicate whether the PS names are loaded. */ + /* */ + /* format_20 :: The sub-table used for format 2.0. */ + /* */ + /* format_25 :: The sub-table used for format 2.5. */ + /* */ + typedef struct TT_Post_NamesRec_ + { + FT_Bool loaded; + + union + { + TT_Post_20Rec format_20; + TT_Post_25Rec format_25; + + } names; + + } TT_Post_NamesRec, *TT_Post_Names; + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** GX VARIATION TABLE SUPPORT ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + +#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT + typedef struct GX_BlendRec_ *GX_Blend; +#endif + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** EMBEDDED BDF PROPERTIES TABLE SUPPORT ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + /* + * These types are used to support a `BDF ' table that isn't part of the + * official TrueType specification. It is mainly used in SFNT-based + * bitmap fonts that were generated from a set of BDF fonts. + * + * The format of the table is as follows. + * + * USHORT version `BDF ' table version number, should be 0x0001. + * USHORT strikeCount Number of strikes (bitmap sizes) in this table. + * ULONG stringTable Offset (from start of BDF table) to string + * table. + * + * This is followed by an array of `strikeCount' descriptors, having the + * following format. + * + * USHORT ppem Vertical pixels per EM for this strike. + * USHORT numItems Number of items for this strike (properties and + * atoms). Maximum is 255. + * + * This array in turn is followed by `strikeCount' value sets. Each + * `value set' is an array of `numItems' items with the following format. + * + * ULONG item_name Offset in string table to item name. + * USHORT item_type The item type. Possible values are + * 0 => string (e.g., COMMENT) + * 1 => atom (e.g., FONT or even SIZE) + * 2 => int32 + * 3 => uint32 + * 0x10 => A flag to indicate a properties. This + * is ORed with the above values. + * ULONG item_value For strings => Offset into string table without + * the corresponding double quotes. + * For atoms => Offset into string table. + * For integers => Direct value. + * + * All strings in the string table consist of bytes and are + * zero-terminated. + * + */ + +#ifdef TT_CONFIG_OPTION_BDF + + typedef struct TT_BDFRec_ + { + FT_Byte* table; + FT_Byte* table_end; + FT_Byte* strings; + FT_ULong strings_size; + FT_UInt num_strikes; + FT_Bool loaded; + + } TT_BDFRec, *TT_BDF; + +#endif /* TT_CONFIG_OPTION_BDF */ + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /*** ***/ + /*** ***/ + /*** ORIGINAL TT_FACE CLASS DEFINITION ***/ + /*** ***/ + /*** ***/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This structure/class is defined here because it is common to the */ + /* following formats: TTF, OpenType-TT, and OpenType-CFF. */ + /* */ + /* Note, however, that the classes TT_Size and TT_GlyphSlot are not */ + /* shared between font drivers, and are thus defined in `ttobjs.h'. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Type> */ + /* TT_Face */ + /* */ + /* <Description> */ + /* A handle to a TrueType face/font object. A TT_Face encapsulates */ + /* the resolution and scaling independent parts of a TrueType font */ + /* resource. */ + /* */ + /* <Note> */ + /* The TT_Face structure is also used as a `parent class' for the */ + /* OpenType-CFF class (T2_Face). */ + /* */ + typedef struct TT_FaceRec_* TT_Face; + + + /* a function type used for the truetype bytecode interpreter hooks */ + typedef FT_Error + (*TT_Interpreter)( void* exec_context ); + + /* forward declaration */ + typedef struct TT_LoaderRec_* TT_Loader; + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Loader_GotoTableFunc */ + /* */ + /* <Description> */ + /* Seeks a stream to the start of a given TrueType table. */ + /* */ + /* <Input> */ + /* face :: A handle to the target face object. */ + /* */ + /* tag :: A 4-byte tag used to name the table. */ + /* */ + /* stream :: The input stream. */ + /* */ + /* <Output> */ + /* length :: The length of the table in bytes. Set to 0 if not */ + /* needed. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* The stream cursor must be at the font file's origin. */ + /* */ + typedef FT_Error + (*TT_Loader_GotoTableFunc)( TT_Face face, + FT_ULong tag, + FT_Stream stream, + FT_ULong* length ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Loader_StartGlyphFunc */ + /* */ + /* <Description> */ + /* Seeks a stream to the start of a given glyph element, and opens a */ + /* frame for it. */ + /* */ + /* <Input> */ + /* loader :: The current TrueType glyph loader object. */ + /* */ + /* glyph index :: The index of the glyph to access. */ + /* */ + /* offset :: The offset of the glyph according to the */ + /* `locations' table. */ + /* */ + /* byte_count :: The size of the frame in bytes. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + /* <Note> */ + /* This function is normally equivalent to FT_STREAM_SEEK(offset) */ + /* followed by FT_FRAME_ENTER(byte_count) with the loader's stream, */ + /* but alternative formats (e.g. compressed ones) might use something */ + /* different. */ + /* */ + typedef FT_Error + (*TT_Loader_StartGlyphFunc)( TT_Loader loader, + FT_UInt glyph_index, + FT_ULong offset, + FT_UInt byte_count ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Loader_ReadGlyphFunc */ + /* */ + /* <Description> */ + /* Reads one glyph element (its header, a simple glyph, or a */ + /* composite) from the loader's current stream frame. */ + /* */ + /* <Input> */ + /* loader :: The current TrueType glyph loader object. */ + /* */ + /* <Return> */ + /* FreeType error code. 0 means success. */ + /* */ + typedef FT_Error + (*TT_Loader_ReadGlyphFunc)( TT_Loader loader ); + + + /*************************************************************************/ + /* */ + /* <FuncType> */ + /* TT_Loader_EndGlyphFunc */ + /* */ + /* <Description> */ + /* Closes the current loader stream frame for the glyph. */ + /* */ + /* <Input> */ + /* loader :: The current TrueType glyph loader object. */ + /* */ + typedef void + (*TT_Loader_EndGlyphFunc)( TT_Loader loader ); + + + /*************************************************************************/ + /* */ + /* TrueType Face Type */ + /* */ + /* <Struct> */ + /* TT_Face */ + /* */ + /* <Description> */ + /* The TrueType face class. These objects model the resolution and */ + /* point-size independent data found in a TrueType font file. */ + /* */ + /* <Fields> */ + /* root :: The base FT_Face structure, managed by the */ + /* base layer. */ + /* */ + /* ttc_header :: The TrueType collection header, used when */ + /* the file is a `ttc' rather than a `ttf'. */ + /* For ordinary font files, the field */ + /* `ttc_header.count' is set to 0. */ + /* */ + /* format_tag :: The font format tag. */ + /* */ + /* num_tables :: The number of TrueType tables in this font */ + /* file. */ + /* */ + /* dir_tables :: The directory of TrueType tables for this */ + /* font file. */ + /* */ + /* header :: The font's font header (`head' table). */ + /* Read on font opening. */ + /* */ + /* horizontal :: The font's horizontal header (`hhea' */ + /* table). This field also contains the */ + /* associated horizontal metrics table */ + /* (`hmtx'). */ + /* */ + /* max_profile :: The font's maximum profile table. Read on */ + /* font opening. Note that some maximum */ + /* values cannot be taken directly from this */ + /* table. We thus define additional fields */ + /* below to hold the computed maxima. */ + /* */ + /* vertical_info :: A boolean which is set when the font file */ + /* contains vertical metrics. If not, the */ + /* value of the `vertical' field is */ + /* undefined. */ + /* */ + /* vertical :: The font's vertical header (`vhea' table). */ + /* This field also contains the associated */ + /* vertical metrics table (`vmtx'), if found. */ + /* IMPORTANT: The contents of this field is */ + /* undefined if the `verticalInfo' field is */ + /* unset. */ + /* */ + /* num_names :: The number of name records within this */ + /* TrueType font. */ + /* */ + /* name_table :: The table of name records (`name'). */ + /* */ + /* os2 :: The font's OS/2 table (`OS/2'). */ + /* */ + /* postscript :: The font's PostScript table (`post' */ + /* table). The PostScript glyph names are */ + /* not loaded by the driver on face opening. */ + /* See the `ttpost' module for more details. */ + /* */ + /* cmap_table :: Address of the face's `cmap' SFNT table */ + /* in memory (it's an extracted frame). */ + /* */ + /* cmap_size :: The size in bytes of the `cmap_table' */ + /* described above. */ + /* */ + /* goto_table :: A function called by each TrueType table */ + /* loader to position a stream's cursor to */ + /* the start of a given table according to */ + /* its tag. It defaults to TT_Goto_Face but */ + /* can be different for strange formats (e.g. */ + /* Type 42). */ + /* */ + /* access_glyph_frame :: A function used to access the frame of a */ + /* given glyph within the face's font file. */ + /* */ + /* forget_glyph_frame :: A function used to forget the frame of a */ + /* given glyph when all data has been loaded. */ + /* */ + /* read_glyph_header :: A function used to read a glyph header. */ + /* It must be called between an `access' and */ + /* `forget'. */ + /* */ + /* read_simple_glyph :: A function used to read a simple glyph. */ + /* It must be called after the header was */ + /* read, and before the `forget'. */ + /* */ + /* read_composite_glyph :: A function used to read a composite glyph. */ + /* It must be called after the header was */ + /* read, and before the `forget'. */ + /* */ + /* sfnt :: A pointer to the SFNT service. */ + /* */ + /* psnames :: A pointer to the PostScript names service. */ + /* */ + /* hdmx :: The face's horizontal device metrics */ + /* (`hdmx' table). This table is optional in */ + /* TrueType/OpenType fonts. */ + /* */ + /* gasp :: The grid-fitting and scaling properties */ + /* table (`gasp'). This table is optional in */ + /* TrueType/OpenType fonts. */ + /* */ + /* pclt :: The `pclt' SFNT table. */ + /* */ + /* num_sbit_strikes :: The number of sbit strikes, i.e., bitmap */ + /* sizes, embedded in this font. */ + /* */ + /* sbit_strikes :: An array of sbit strikes embedded in this */ + /* font. This table is optional in a */ + /* TrueType/OpenType font. */ + /* */ + /* num_sbit_scales :: The number of sbit scales for this font. */ + /* */ + /* sbit_scales :: Array of sbit scales embedded in this */ + /* font. This table is optional in a */ + /* TrueType/OpenType font. */ + /* */ + /* postscript_names :: A table used to store the Postscript names */ + /* of the glyphs for this font. See the */ + /* file `ttconfig.h' for comments on the */ + /* TT_CONFIG_OPTION_POSTSCRIPT_NAMES option. */ + /* */ + /* num_locations :: The number of glyph locations in this */ + /* TrueType file. This should be */ + /* identical to the number of glyphs. */ + /* Ignored for Type 2 fonts. */ + /* */ + /* glyph_locations :: An array of longs. These are offsets to */ + /* glyph data within the `glyf' table. */ + /* Ignored for Type 2 font faces. */ + /* */ + /* glyf_len :: The length of the `glyf' table. Needed */ + /* for malformed `loca' tables. */ + /* */ + /* font_program_size :: Size in bytecodes of the face's font */ + /* program. 0 if none defined. Ignored for */ + /* Type 2 fonts. */ + /* */ + /* font_program :: The face's font program (bytecode stream) */ + /* executed at load time, also used during */ + /* glyph rendering. Comes from the `fpgm' */ + /* table. Ignored for Type 2 font fonts. */ + /* */ + /* cvt_program_size :: The size in bytecodes of the face's cvt */ + /* program. Ignored for Type 2 fonts. */ + /* */ + /* cvt_program :: The face's cvt program (bytecode stream) */ + /* executed each time an instance/size is */ + /* changed/reset. Comes from the `prep' */ + /* table. Ignored for Type 2 fonts. */ + /* */ + /* cvt_size :: Size of the control value table (in */ + /* entries). Ignored for Type 2 fonts. */ + /* */ + /* cvt :: The face's original control value table. */ + /* Coordinates are expressed in unscaled font */ + /* units. Comes from the `cvt ' table. */ + /* Ignored for Type 2 fonts. */ + /* */ + /* num_kern_pairs :: The number of kerning pairs present in the */ + /* font file. The engine only loads the */ + /* first horizontal format 0 kern table it */ + /* finds in the font file. Ignored for */ + /* Type 2 fonts. */ + /* */ + /* kern_table_index :: The index of the kerning table in the font */ + /* kerning directory. Ignored for Type 2 */ + /* fonts. */ + /* */ + /* interpreter :: A pointer to the TrueType bytecode */ + /* interpreters field is also used to hook */ + /* the debugger in `ttdebug'. */ + /* */ + /* unpatented_hinting :: If true, use only unpatented methods in */ + /* the bytecode interpreter. */ + /* */ + /* doblend :: A boolean which is set if the font should */ + /* be blended (this is for GX var). */ + /* */ + /* blend :: Contains the data needed to control GX */ + /* variation tables (rather like Multiple */ + /* Master data). */ + /* */ + /* extra :: Reserved for third-party font drivers. */ + /* */ + /* postscript_name :: The PS name of the font. Used by the */ + /* postscript name service. */ + /* */ + typedef struct TT_FaceRec_ + { + FT_FaceRec root; + + TTC_HeaderRec ttc_header; + + FT_ULong format_tag; + FT_UShort num_tables; + TT_Table dir_tables; + + TT_Header header; /* TrueType header table */ + TT_HoriHeader horizontal; /* TrueType horizontal header */ + + TT_MaxProfile max_profile; +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + FT_ULong max_components; /* stubbed to 0 */ +#endif + + FT_Bool vertical_info; + TT_VertHeader vertical; /* TT Vertical header, if present */ + + FT_UShort num_names; /* number of name records */ + TT_NameTableRec name_table; /* name table */ + + TT_OS2 os2; /* TrueType OS/2 table */ + TT_Postscript postscript; /* TrueType Postscript table */ + + FT_Byte* cmap_table; /* extracted `cmap' table */ + FT_ULong cmap_size; + + TT_Loader_GotoTableFunc goto_table; + + TT_Loader_StartGlyphFunc access_glyph_frame; + TT_Loader_EndGlyphFunc forget_glyph_frame; + TT_Loader_ReadGlyphFunc read_glyph_header; + TT_Loader_ReadGlyphFunc read_simple_glyph; + TT_Loader_ReadGlyphFunc read_composite_glyph; + + /* a typeless pointer to the SFNT_Interface table used to load */ + /* the basic TrueType tables in the face object */ + void* sfnt; + + /* a typeless pointer to the FT_Service_PsCMapsRec table used to */ + /* handle glyph names <-> unicode & Mac values */ + void* psnames; + + + /***********************************************************************/ + /* */ + /* Optional TrueType/OpenType tables */ + /* */ + /***********************************************************************/ + + /* horizontal device metrics */ +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + TT_HdmxRec hdmx; +#endif + + /* grid-fitting and scaling table */ + TT_GaspRec gasp; /* the `gasp' table */ + + /* PCL 5 table */ + TT_PCLT pclt; + + /* embedded bitmaps support */ +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + FT_ULong num_sbit_strikes; + TT_SBit_Strike sbit_strikes; +#endif + + FT_ULong num_sbit_scales; + TT_SBit_Scale sbit_scales; + + /* postscript names table */ + TT_Post_NamesRec postscript_names; + + + /***********************************************************************/ + /* */ + /* TrueType-specific fields (ignored by the OTF-Type2 driver) */ + /* */ + /***********************************************************************/ + + /* the glyph locations */ +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + FT_UShort num_locations_stub; + FT_Long* glyph_locations_stub; +#endif + + /* the font program, if any */ + FT_ULong font_program_size; + FT_Byte* font_program; + + /* the cvt program, if any */ + FT_ULong cvt_program_size; + FT_Byte* cvt_program; + + /* the original, unscaled, control value table */ + FT_ULong cvt_size; + FT_Short* cvt; + +#ifdef FT_CONFIG_OPTION_OLD_INTERNALS + /* the format 0 kerning table, if any */ + FT_Int num_kern_pairs; + FT_Int kern_table_index; + TT_Kern0_Pair kern_pairs; +#endif + + /* A pointer to the bytecode interpreter to use. This is also */ + /* used to hook the debugger for the `ttdebug' utility. */ + TT_Interpreter interpreter; + +#ifdef TT_CONFIG_OPTION_UNPATENTED_HINTING + /* Use unpatented hinting only. */ + FT_Bool unpatented_hinting; +#endif + + /***********************************************************************/ + /* */ + /* Other tables or fields. This is used by derivative formats like */ + /* OpenType. */ + /* */ + /***********************************************************************/ + + FT_Generic extra; + + const char* postscript_name; + + /* since version 2.1.8, but was originally placed after */ + /* `glyph_locations_stub' */ + FT_ULong glyf_len; + + /* since version 2.1.8, but was originally placed before `extra' */ +#ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT + FT_Bool doblend; + GX_Blend blend; +#endif + + /* since version 2.2 */ + + FT_Byte* horz_metrics; + FT_ULong horz_metrics_size; + + FT_Byte* vert_metrics; + FT_ULong vert_metrics_size; + + FT_ULong num_locations; /* in broken TTF, gid > 0xFFFF */ + FT_Byte* glyph_locations; + + FT_Byte* hdmx_table; + FT_ULong hdmx_table_size; + FT_UInt hdmx_record_count; + FT_ULong hdmx_record_size; + FT_Byte* hdmx_record_sizes; + + FT_Byte* sbit_table; + FT_ULong sbit_table_size; + FT_UInt sbit_num_strikes; + + FT_Byte* kern_table; + FT_ULong kern_table_size; + FT_UInt num_kern_tables; + FT_UInt32 kern_avail_bits; + FT_UInt32 kern_order_bits; + +#ifdef TT_CONFIG_OPTION_BDF + TT_BDFRec bdf; +#endif /* TT_CONFIG_OPTION_BDF */ + + /* since 2.3.0 */ + FT_ULong horz_metrics_offset; + FT_ULong vert_metrics_offset; + + } TT_FaceRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_GlyphZoneRec */ + /* */ + /* <Description> */ + /* A glyph zone is used to load, scale and hint glyph outline */ + /* coordinates. */ + /* */ + /* <Fields> */ + /* memory :: A handle to the memory manager. */ + /* */ + /* max_points :: The maximal size in points of the zone. */ + /* */ + /* max_contours :: Max size in links contours of the zone. */ + /* */ + /* n_points :: The current number of points in the zone. */ + /* */ + /* n_contours :: The current number of contours in the zone. */ + /* */ + /* org :: The original glyph coordinates (font */ + /* units/scaled). */ + /* */ + /* cur :: The current glyph coordinates (scaled/hinted). */ + /* */ + /* tags :: The point control tags. */ + /* */ + /* contours :: The contours end points. */ + /* */ + /* first_point :: Offset of the current subglyph's first point. */ + /* */ + typedef struct TT_GlyphZoneRec_ + { + FT_Memory memory; + FT_UShort max_points; + FT_UShort max_contours; + FT_UShort n_points; /* number of points in zone */ + FT_Short n_contours; /* number of contours */ + + FT_Vector* org; /* original point coordinates */ + FT_Vector* cur; /* current point coordinates */ + FT_Vector* orus; /* original (unscaled) point coordinates */ + + FT_Byte* tags; /* current touch flags */ + FT_UShort* contours; /* contour end points */ + + FT_UShort first_point; /* offset of first (#0) point */ + + } TT_GlyphZoneRec, *TT_GlyphZone; + + + /* handle to execution context */ + typedef struct TT_ExecContextRec_* TT_ExecContext; + + /* glyph loader structure */ + typedef struct TT_LoaderRec_ + { + FT_Face face; + FT_Size size; + FT_GlyphSlot glyph; + FT_GlyphLoader gloader; + + FT_ULong load_flags; + FT_UInt glyph_index; + + FT_Stream stream; + FT_Int byte_len; + + FT_Short n_contours; + FT_BBox bbox; + FT_Int left_bearing; + FT_Int advance; + FT_Int linear; + FT_Bool linear_def; + FT_Bool preserve_pps; + FT_Vector pp1; + FT_Vector pp2; + + FT_ULong glyf_offset; + + /* the zone where we load our glyphs */ + TT_GlyphZoneRec base; + TT_GlyphZoneRec zone; + + TT_ExecContext exec; + FT_Byte* instructions; + FT_ULong ins_pos; + + /* for possible extensibility in other formats */ + void* other; + + /* since version 2.1.8 */ + FT_Int top_bearing; + FT_Int vadvance; + FT_Vector pp3; + FT_Vector pp4; + + /* since version 2.2.1 */ + FT_Byte* cursor; + FT_Byte* limit; + + } TT_LoaderRec; + + +FT_END_HEADER + +#endif /* __TTTYPES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/t1tables.h b/other/freetype/include/freetype/t1tables.h new file mode 100644 index 0000000..db1a91e --- /dev/null +++ b/other/freetype/include/freetype/t1tables.h @@ -0,0 +1,662 @@ +/***************************************************************************/ +/* */ +/* t1tables.h */ +/* */ +/* Basic Type 1/Type 2 tables definitions and interface (specification */ +/* only). */ +/* */ +/* Copyright 1996-2004, 2006, 2008, 2009, 2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __T1TABLES_H__ +#define __T1TABLES_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* type1_tables */ + /* */ + /* <Title> */ + /* Type 1 Tables */ + /* */ + /* <Abstract> */ + /* Type~1 (PostScript) specific font tables. */ + /* */ + /* <Description> */ + /* This section contains the definition of Type 1-specific tables, */ + /* including structures related to other PostScript font formats. */ + /* */ + /*************************************************************************/ + + + /* Note that we separate font data in PS_FontInfoRec and PS_PrivateRec */ + /* structures in order to support Multiple Master fonts. */ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_FontInfoRec */ + /* */ + /* <Description> */ + /* A structure used to model a Type~1 or Type~2 FontInfo dictionary. */ + /* Note that for Multiple Master fonts, each instance has its own */ + /* FontInfo dictionary. */ + /* */ + typedef struct PS_FontInfoRec_ + { + FT_String* version; + FT_String* notice; + FT_String* full_name; + FT_String* family_name; + FT_String* weight; + FT_Long italic_angle; + FT_Bool is_fixed_pitch; + FT_Short underline_position; + FT_UShort underline_thickness; + + } PS_FontInfoRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_FontInfo */ + /* */ + /* <Description> */ + /* A handle to a @PS_FontInfoRec structure. */ + /* */ + typedef struct PS_FontInfoRec_* PS_FontInfo; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* T1_FontInfo */ + /* */ + /* <Description> */ + /* This type is equivalent to @PS_FontInfoRec. It is deprecated but */ + /* kept to maintain source compatibility between various versions of */ + /* FreeType. */ + /* */ + typedef PS_FontInfoRec T1_FontInfo; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_PrivateRec */ + /* */ + /* <Description> */ + /* A structure used to model a Type~1 or Type~2 private dictionary. */ + /* Note that for Multiple Master fonts, each instance has its own */ + /* Private dictionary. */ + /* */ + typedef struct PS_PrivateRec_ + { + FT_Int unique_id; + FT_Int lenIV; + + FT_Byte num_blue_values; + FT_Byte num_other_blues; + FT_Byte num_family_blues; + FT_Byte num_family_other_blues; + + FT_Short blue_values[14]; + FT_Short other_blues[10]; + + FT_Short family_blues [14]; + FT_Short family_other_blues[10]; + + FT_Fixed blue_scale; + FT_Int blue_shift; + FT_Int blue_fuzz; + + FT_UShort standard_width[1]; + FT_UShort standard_height[1]; + + FT_Byte num_snap_widths; + FT_Byte num_snap_heights; + FT_Bool force_bold; + FT_Bool round_stem_up; + + FT_Short snap_widths [13]; /* including std width */ + FT_Short snap_heights[13]; /* including std height */ + + FT_Fixed expansion_factor; + + FT_Long language_group; + FT_Long password; + + FT_Short min_feature[2]; + + } PS_PrivateRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* PS_Private */ + /* */ + /* <Description> */ + /* A handle to a @PS_PrivateRec structure. */ + /* */ + typedef struct PS_PrivateRec_* PS_Private; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* T1_Private */ + /* */ + /* <Description> */ + /* This type is equivalent to @PS_PrivateRec. It is deprecated but */ + /* kept to maintain source compatibility between various versions of */ + /* FreeType. */ + /* */ + typedef PS_PrivateRec T1_Private; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* T1_Blend_Flags */ + /* */ + /* <Description> */ + /* A set of flags used to indicate which fields are present in a */ + /* given blend dictionary (font info or private). Used to support */ + /* Multiple Masters fonts. */ + /* */ + typedef enum T1_Blend_Flags_ + { + /*# required fields in a FontInfo blend dictionary */ + T1_BLEND_UNDERLINE_POSITION = 0, + T1_BLEND_UNDERLINE_THICKNESS, + T1_BLEND_ITALIC_ANGLE, + + /*# required fields in a Private blend dictionary */ + T1_BLEND_BLUE_VALUES, + T1_BLEND_OTHER_BLUES, + T1_BLEND_STANDARD_WIDTH, + T1_BLEND_STANDARD_HEIGHT, + T1_BLEND_STEM_SNAP_WIDTHS, + T1_BLEND_STEM_SNAP_HEIGHTS, + T1_BLEND_BLUE_SCALE, + T1_BLEND_BLUE_SHIFT, + T1_BLEND_FAMILY_BLUES, + T1_BLEND_FAMILY_OTHER_BLUES, + T1_BLEND_FORCE_BOLD, + + /*# never remove */ + T1_BLEND_MAX + + } T1_Blend_Flags; + + /* */ + + + /*# backwards compatible definitions */ +#define t1_blend_underline_position T1_BLEND_UNDERLINE_POSITION +#define t1_blend_underline_thickness T1_BLEND_UNDERLINE_THICKNESS +#define t1_blend_italic_angle T1_BLEND_ITALIC_ANGLE +#define t1_blend_blue_values T1_BLEND_BLUE_VALUES +#define t1_blend_other_blues T1_BLEND_OTHER_BLUES +#define t1_blend_standard_widths T1_BLEND_STANDARD_WIDTH +#define t1_blend_standard_height T1_BLEND_STANDARD_HEIGHT +#define t1_blend_stem_snap_widths T1_BLEND_STEM_SNAP_WIDTHS +#define t1_blend_stem_snap_heights T1_BLEND_STEM_SNAP_HEIGHTS +#define t1_blend_blue_scale T1_BLEND_BLUE_SCALE +#define t1_blend_blue_shift T1_BLEND_BLUE_SHIFT +#define t1_blend_family_blues T1_BLEND_FAMILY_BLUES +#define t1_blend_family_other_blues T1_BLEND_FAMILY_OTHER_BLUES +#define t1_blend_force_bold T1_BLEND_FORCE_BOLD +#define t1_blend_max T1_BLEND_MAX + + + /* maximum number of Multiple Masters designs, as defined in the spec */ +#define T1_MAX_MM_DESIGNS 16 + + /* maximum number of Multiple Masters axes, as defined in the spec */ +#define T1_MAX_MM_AXIS 4 + + /* maximum number of elements in a design map */ +#define T1_MAX_MM_MAP_POINTS 20 + + + /* this structure is used to store the BlendDesignMap entry for an axis */ + typedef struct PS_DesignMap_ + { + FT_Byte num_points; + FT_Long* design_points; + FT_Fixed* blend_points; + + } PS_DesignMapRec, *PS_DesignMap; + + /* backwards-compatible definition */ + typedef PS_DesignMapRec T1_DesignMap; + + + typedef struct PS_BlendRec_ + { + FT_UInt num_designs; + FT_UInt num_axis; + + FT_String* axis_names[T1_MAX_MM_AXIS]; + FT_Fixed* design_pos[T1_MAX_MM_DESIGNS]; + PS_DesignMapRec design_map[T1_MAX_MM_AXIS]; + + FT_Fixed* weight_vector; + FT_Fixed* default_weight_vector; + + PS_FontInfo font_infos[T1_MAX_MM_DESIGNS + 1]; + PS_Private privates [T1_MAX_MM_DESIGNS + 1]; + + FT_ULong blend_bitflags; + + FT_BBox* bboxes [T1_MAX_MM_DESIGNS + 1]; + + /* since 2.3.0 */ + + /* undocumented, optional: the default design instance; */ + /* corresponds to default_weight_vector -- */ + /* num_default_design_vector == 0 means it is not present */ + /* in the font and associated metrics files */ + FT_UInt default_design_vector[T1_MAX_MM_DESIGNS]; + FT_UInt num_default_design_vector; + + } PS_BlendRec, *PS_Blend; + + + /* backwards-compatible definition */ + typedef PS_BlendRec T1_Blend; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* CID_FaceDictRec */ + /* */ + /* <Description> */ + /* A structure used to represent data in a CID top-level dictionary. */ + /* */ + typedef struct CID_FaceDictRec_ + { + PS_PrivateRec private_dict; + + FT_UInt len_buildchar; + FT_Fixed forcebold_threshold; + FT_Pos stroke_width; + FT_Fixed expansion_factor; + + FT_Byte paint_type; + FT_Byte font_type; + FT_Matrix font_matrix; + FT_Vector font_offset; + + FT_UInt num_subrs; + FT_ULong subrmap_offset; + FT_Int sd_bytes; + + } CID_FaceDictRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* CID_FaceDict */ + /* */ + /* <Description> */ + /* A handle to a @CID_FaceDictRec structure. */ + /* */ + typedef struct CID_FaceDictRec_* CID_FaceDict; + + /* */ + + + /* backwards-compatible definition */ + typedef CID_FaceDictRec CID_FontDict; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* CID_FaceInfoRec */ + /* */ + /* <Description> */ + /* A structure used to represent CID Face information. */ + /* */ + typedef struct CID_FaceInfoRec_ + { + FT_String* cid_font_name; + FT_Fixed cid_version; + FT_Int cid_font_type; + + FT_String* registry; + FT_String* ordering; + FT_Int supplement; + + PS_FontInfoRec font_info; + FT_BBox font_bbox; + FT_ULong uid_base; + + FT_Int num_xuid; + FT_ULong xuid[16]; + + FT_ULong cidmap_offset; + FT_Int fd_bytes; + FT_Int gd_bytes; + FT_ULong cid_count; + + FT_Int num_dicts; + CID_FaceDict font_dicts; + + FT_ULong data_offset; + + } CID_FaceInfoRec; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* CID_FaceInfo */ + /* */ + /* <Description> */ + /* A handle to a @CID_FaceInfoRec structure. */ + /* */ + typedef struct CID_FaceInfoRec_* CID_FaceInfo; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* CID_Info */ + /* */ + /* <Description> */ + /* This type is equivalent to @CID_FaceInfoRec. It is deprecated but */ + /* kept to maintain source compatibility between various versions of */ + /* FreeType. */ + /* */ + typedef CID_FaceInfoRec CID_Info; + + + /************************************************************************ + * + * @function: + * FT_Has_PS_Glyph_Names + * + * @description: + * Return true if a given face provides reliable PostScript glyph + * names. This is similar to using the @FT_HAS_GLYPH_NAMES macro, + * except that certain fonts (mostly TrueType) contain incorrect + * glyph name tables. + * + * When this function returns true, the caller is sure that the glyph + * names returned by @FT_Get_Glyph_Name are reliable. + * + * @input: + * face :: + * face handle + * + * @return: + * Boolean. True if glyph names are reliable. + * + */ + FT_EXPORT( FT_Int ) + FT_Has_PS_Glyph_Names( FT_Face face ); + + + /************************************************************************ + * + * @function: + * FT_Get_PS_Font_Info + * + * @description: + * Retrieve the @PS_FontInfoRec structure corresponding to a given + * PostScript font. + * + * @input: + * face :: + * PostScript face handle. + * + * @output: + * afont_info :: + * Output font info structure pointer. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The string pointers within the font info structure are owned by + * the face and don't need to be freed by the caller. + * + * If the font's format is not PostScript-based, this function will + * return the `FT_Err_Invalid_Argument' error code. + * + */ + FT_EXPORT( FT_Error ) + FT_Get_PS_Font_Info( FT_Face face, + PS_FontInfo afont_info ); + + + /************************************************************************ + * + * @function: + * FT_Get_PS_Font_Private + * + * @description: + * Retrieve the @PS_PrivateRec structure corresponding to a given + * PostScript font. + * + * @input: + * face :: + * PostScript face handle. + * + * @output: + * afont_private :: + * Output private dictionary structure pointer. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * The string pointers within the @PS_PrivateRec structure are owned by + * the face and don't need to be freed by the caller. + * + * If the font's format is not PostScript-based, this function returns + * the `FT_Err_Invalid_Argument' error code. + * + */ + FT_EXPORT( FT_Error ) + FT_Get_PS_Font_Private( FT_Face face, + PS_Private afont_private ); + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* T1_EncodingType */ + /* */ + /* <Description> */ + /* An enumeration describing the `Encoding' entry in a Type 1 */ + /* dictionary. */ + /* */ + typedef enum T1_EncodingType_ + { + T1_ENCODING_TYPE_NONE = 0, + T1_ENCODING_TYPE_ARRAY, + T1_ENCODING_TYPE_STANDARD, + T1_ENCODING_TYPE_ISOLATIN1, + T1_ENCODING_TYPE_EXPERT + + } T1_EncodingType; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* PS_Dict_Keys */ + /* */ + /* <Description> */ + /* An enumeration used in calls to @FT_Get_PS_Font_Value to identify */ + /* the Type~1 dictionary entry to retrieve. */ + /* */ + typedef enum PS_Dict_Keys_ + { + /* conventionally in the font dictionary */ + PS_DICT_FONT_TYPE, /* FT_Byte */ + PS_DICT_FONT_MATRIX, /* FT_Fixed */ + PS_DICT_FONT_BBOX, /* FT_Fixed */ + PS_DICT_PAINT_TYPE, /* FT_Byte */ + PS_DICT_FONT_NAME, /* FT_String* */ + PS_DICT_UNIQUE_ID, /* FT_Int */ + PS_DICT_NUM_CHAR_STRINGS, /* FT_Int */ + PS_DICT_CHAR_STRING_KEY, /* FT_String* */ + PS_DICT_CHAR_STRING, /* FT_String* */ + PS_DICT_ENCODING_TYPE, /* T1_EncodingType */ + PS_DICT_ENCODING_ENTRY, /* FT_String* */ + + /* conventionally in the font Private dictionary */ + PS_DICT_NUM_SUBRS, /* FT_Int */ + PS_DICT_SUBR, /* FT_String* */ + PS_DICT_STD_HW, /* FT_UShort */ + PS_DICT_STD_VW, /* FT_UShort */ + PS_DICT_NUM_BLUE_VALUES, /* FT_Byte */ + PS_DICT_BLUE_VALUE, /* FT_Short */ + PS_DICT_BLUE_FUZZ, /* FT_Int */ + PS_DICT_NUM_OTHER_BLUES, /* FT_Byte */ + PS_DICT_OTHER_BLUE, /* FT_Short */ + PS_DICT_NUM_FAMILY_BLUES, /* FT_Byte */ + PS_DICT_FAMILY_BLUE, /* FT_Short */ + PS_DICT_NUM_FAMILY_OTHER_BLUES, /* FT_Byte */ + PS_DICT_FAMILY_OTHER_BLUE, /* FT_Short */ + PS_DICT_BLUE_SCALE, /* FT_Fixed */ + PS_DICT_BLUE_SHIFT, /* FT_Int */ + PS_DICT_NUM_STEM_SNAP_H, /* FT_Byte */ + PS_DICT_STEM_SNAP_H, /* FT_Short */ + PS_DICT_NUM_STEM_SNAP_V, /* FT_Byte */ + PS_DICT_STEM_SNAP_V, /* FT_Short */ + PS_DICT_FORCE_BOLD, /* FT_Bool */ + PS_DICT_RND_STEM_UP, /* FT_Bool */ + PS_DICT_MIN_FEATURE, /* FT_Short */ + PS_DICT_LEN_IV, /* FT_Int */ + PS_DICT_PASSWORD, /* FT_Long */ + PS_DICT_LANGUAGE_GROUP, /* FT_Long */ + + /* conventionally in the font FontInfo dictionary */ + PS_DICT_VERSION, /* FT_String* */ + PS_DICT_NOTICE, /* FT_String* */ + PS_DICT_FULL_NAME, /* FT_String* */ + PS_DICT_FAMILY_NAME, /* FT_String* */ + PS_DICT_WEIGHT, /* FT_String */ + PS_DICT_IS_FIXED_PITCH, /* FT_Bool */ + PS_DICT_UNDERLINE_POSITION, /* FT_Short */ + PS_DICT_UNDERLINE_THICKNESS, /* FT_UShort */ + PS_DICT_FS_TYPE, /* FT_UShort */ + PS_DICT_ITALIC_ANGLE, /* FT_Long */ + + PS_DICT_MAX = PS_DICT_ITALIC_ANGLE + + } PS_Dict_Keys; + + + /************************************************************************ + * + * @function: + * FT_Get_PS_Font_Value + * + * @description: + * Retrieve the value for the supplied key from a PostScript font. + * + * @input: + * face :: + * PostScript face handle. + * + * key :: + * An enumeration value representing the dictionary key to retrieve. + * + * idx :: + * For array values, this specifies the index to be returned. + * + * value :: + * A pointer to memory into which to write the value. + * + * valen_len :: + * The size, in bytes, of the memory supplied for the value. + * + * @output: + * value :: + * The value matching the above key, if it exists. + * + * @return: + * The amount of memory (in bytes) required to hold the requested + * value (if it exists, -1 otherwise). + * + * @note: + * The values returned are not pointers into the internal structures of + * the face, but are `fresh' copies, so that the memory containing them + * belongs to the calling application. This also enforces the + * `read-only' nature of these values, i.e., this function cannot be + * used to manipulate the face. + * + * `value' is a void pointer because the values returned can be of + * various types. + * + * If either `value' is NULL or `value_len' is too small, just the + * required memory size for the requested entry is returned. + * + * The `idx' parameter is used, not only to retrieve elements of, for + * example, the FontMatrix or FontBBox, but also to retrieve name keys + * from the CharStrings dictionary, and the charstrings themselves. It + * is ignored for atomic values. + * + * PS_DICT_BLUE_SCALE returns a value that is scaled up by 1000. To + * get the value as in the font stream, you need to divide by + * 65536000.0 (to remove the FT_Fixed scale, and the x1000 scale). + * + * IMPORTANT: Only key/value pairs read by the FreeType interpreter can + * be retrieved. So, for example, PostScript procedures such as NP, + * ND, and RD are not available. Arbitrary keys are, obviously, not be + * available either. + * + * If the font's format is not PostScript-based, this function returns + * the `FT_Err_Invalid_Argument' error code. + * + */ + FT_EXPORT( FT_Long ) + FT_Get_PS_Font_Value( FT_Face face, + PS_Dict_Keys key, + FT_UInt idx, + void *value, + FT_Long value_len ); + + /* */ + +FT_END_HEADER + +#endif /* __T1TABLES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ttnameid.h b/other/freetype/include/freetype/ttnameid.h new file mode 100644 index 0000000..66aef04 --- /dev/null +++ b/other/freetype/include/freetype/ttnameid.h @@ -0,0 +1,1247 @@ +/***************************************************************************/ +/* */ +/* ttnameid.h */ +/* */ +/* TrueType name ID definitions (specification only). */ +/* */ +/* Copyright 1996-2002, 2003, 2004, 2006, 2007, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __TTNAMEID_H__ +#define __TTNAMEID_H__ + + +#include <ft2build.h> + + +FT_BEGIN_HEADER + + + /*************************************************************************/ + /* */ + /* <Section> */ + /* truetype_tables */ + /* */ + + + /*************************************************************************/ + /* */ + /* Possible values for the `platform' identifier code in the name */ + /* records of the TTF `name' table. */ + /* */ + /*************************************************************************/ + + + /*********************************************************************** + * + * @enum: + * TT_PLATFORM_XXX + * + * @description: + * A list of valid values for the `platform_id' identifier code in + * @FT_CharMapRec and @FT_SfntName structures. + * + * @values: + * TT_PLATFORM_APPLE_UNICODE :: + * Used by Apple to indicate a Unicode character map and/or name entry. + * See @TT_APPLE_ID_XXX for corresponding `encoding_id' values. Note + * that name entries in this format are coded as big-endian UCS-2 + * character codes _only_. + * + * TT_PLATFORM_MACINTOSH :: + * Used by Apple to indicate a MacOS-specific charmap and/or name entry. + * See @TT_MAC_ID_XXX for corresponding `encoding_id' values. Note that + * most TrueType fonts contain an Apple roman charmap to be usable on + * MacOS systems (even if they contain a Microsoft charmap as well). + * + * TT_PLATFORM_ISO :: + * This value was used to specify ISO/IEC 10646 charmaps. It is however + * now deprecated. See @TT_ISO_ID_XXX for a list of corresponding + * `encoding_id' values. + * + * TT_PLATFORM_MICROSOFT :: + * Used by Microsoft to indicate Windows-specific charmaps. See + * @TT_MS_ID_XXX for a list of corresponding `encoding_id' values. + * Note that most fonts contain a Unicode charmap using + * (TT_PLATFORM_MICROSOFT, @TT_MS_ID_UNICODE_CS). + * + * TT_PLATFORM_CUSTOM :: + * Used to indicate application-specific charmaps. + * + * TT_PLATFORM_ADOBE :: + * This value isn't part of any font format specification, but is used + * by FreeType to report Adobe-specific charmaps in an @FT_CharMapRec + * structure. See @TT_ADOBE_ID_XXX. + */ + +#define TT_PLATFORM_APPLE_UNICODE 0 +#define TT_PLATFORM_MACINTOSH 1 +#define TT_PLATFORM_ISO 2 /* deprecated */ +#define TT_PLATFORM_MICROSOFT 3 +#define TT_PLATFORM_CUSTOM 4 +#define TT_PLATFORM_ADOBE 7 /* artificial */ + + + /*********************************************************************** + * + * @enum: + * TT_APPLE_ID_XXX + * + * @description: + * A list of valid values for the `encoding_id' for + * @TT_PLATFORM_APPLE_UNICODE charmaps and name entries. + * + * @values: + * TT_APPLE_ID_DEFAULT :: + * Unicode version 1.0. + * + * TT_APPLE_ID_UNICODE_1_1 :: + * Unicode 1.1; specifies Hangul characters starting at U+34xx. + * + * TT_APPLE_ID_ISO_10646 :: + * Deprecated (identical to preceding). + * + * TT_APPLE_ID_UNICODE_2_0 :: + * Unicode 2.0 and beyond (UTF-16 BMP only). + * + * TT_APPLE_ID_UNICODE_32 :: + * Unicode 3.1 and beyond, using UTF-32. + * + * TT_APPLE_ID_VARIANT_SELECTOR :: + * From Adobe, not Apple. Not a normal cmap. Specifies variations + * on a real cmap. + */ + +#define TT_APPLE_ID_DEFAULT 0 /* Unicode 1.0 */ +#define TT_APPLE_ID_UNICODE_1_1 1 /* specify Hangul at U+34xx */ +#define TT_APPLE_ID_ISO_10646 2 /* deprecated */ +#define TT_APPLE_ID_UNICODE_2_0 3 /* or later */ +#define TT_APPLE_ID_UNICODE_32 4 /* 2.0 or later, full repertoire */ +#define TT_APPLE_ID_VARIANT_SELECTOR 5 /* variation selector data */ + + + /*********************************************************************** + * + * @enum: + * TT_MAC_ID_XXX + * + * @description: + * A list of valid values for the `encoding_id' for + * @TT_PLATFORM_MACINTOSH charmaps and name entries. + * + * @values: + * TT_MAC_ID_ROMAN :: + * TT_MAC_ID_JAPANESE :: + * TT_MAC_ID_TRADITIONAL_CHINESE :: + * TT_MAC_ID_KOREAN :: + * TT_MAC_ID_ARABIC :: + * TT_MAC_ID_HEBREW :: + * TT_MAC_ID_GREEK :: + * TT_MAC_ID_RUSSIAN :: + * TT_MAC_ID_RSYMBOL :: + * TT_MAC_ID_DEVANAGARI :: + * TT_MAC_ID_GURMUKHI :: + * TT_MAC_ID_GUJARATI :: + * TT_MAC_ID_ORIYA :: + * TT_MAC_ID_BENGALI :: + * TT_MAC_ID_TAMIL :: + * TT_MAC_ID_TELUGU :: + * TT_MAC_ID_KANNADA :: + * TT_MAC_ID_MALAYALAM :: + * TT_MAC_ID_SINHALESE :: + * TT_MAC_ID_BURMESE :: + * TT_MAC_ID_KHMER :: + * TT_MAC_ID_THAI :: + * TT_MAC_ID_LAOTIAN :: + * TT_MAC_ID_GEORGIAN :: + * TT_MAC_ID_ARMENIAN :: + * TT_MAC_ID_MALDIVIAN :: + * TT_MAC_ID_SIMPLIFIED_CHINESE :: + * TT_MAC_ID_TIBETAN :: + * TT_MAC_ID_MONGOLIAN :: + * TT_MAC_ID_GEEZ :: + * TT_MAC_ID_SLAVIC :: + * TT_MAC_ID_VIETNAMESE :: + * TT_MAC_ID_SINDHI :: + * TT_MAC_ID_UNINTERP :: + */ + +#define TT_MAC_ID_ROMAN 0 +#define TT_MAC_ID_JAPANESE 1 +#define TT_MAC_ID_TRADITIONAL_CHINESE 2 +#define TT_MAC_ID_KOREAN 3 +#define TT_MAC_ID_ARABIC 4 +#define TT_MAC_ID_HEBREW 5 +#define TT_MAC_ID_GREEK 6 +#define TT_MAC_ID_RUSSIAN 7 +#define TT_MAC_ID_RSYMBOL 8 +#define TT_MAC_ID_DEVANAGARI 9 +#define TT_MAC_ID_GURMUKHI 10 +#define TT_MAC_ID_GUJARATI 11 +#define TT_MAC_ID_ORIYA 12 +#define TT_MAC_ID_BENGALI 13 +#define TT_MAC_ID_TAMIL 14 +#define TT_MAC_ID_TELUGU 15 +#define TT_MAC_ID_KANNADA 16 +#define TT_MAC_ID_MALAYALAM 17 +#define TT_MAC_ID_SINHALESE 18 +#define TT_MAC_ID_BURMESE 19 +#define TT_MAC_ID_KHMER 20 +#define TT_MAC_ID_THAI 21 +#define TT_MAC_ID_LAOTIAN 22 +#define TT_MAC_ID_GEORGIAN 23 +#define TT_MAC_ID_ARMENIAN 24 +#define TT_MAC_ID_MALDIVIAN 25 +#define TT_MAC_ID_SIMPLIFIED_CHINESE 25 +#define TT_MAC_ID_TIBETAN 26 +#define TT_MAC_ID_MONGOLIAN 27 +#define TT_MAC_ID_GEEZ 28 +#define TT_MAC_ID_SLAVIC 29 +#define TT_MAC_ID_VIETNAMESE 30 +#define TT_MAC_ID_SINDHI 31 +#define TT_MAC_ID_UNINTERP 32 + + + /*********************************************************************** + * + * @enum: + * TT_ISO_ID_XXX + * + * @description: + * A list of valid values for the `encoding_id' for + * @TT_PLATFORM_ISO charmaps and name entries. + * + * Their use is now deprecated. + * + * @values: + * TT_ISO_ID_7BIT_ASCII :: + * ASCII. + * TT_ISO_ID_10646 :: + * ISO/10646. + * TT_ISO_ID_8859_1 :: + * Also known as Latin-1. + */ + +#define TT_ISO_ID_7BIT_ASCII 0 +#define TT_ISO_ID_10646 1 +#define TT_ISO_ID_8859_1 2 + + + /*********************************************************************** + * + * @enum: + * TT_MS_ID_XXX + * + * @description: + * A list of valid values for the `encoding_id' for + * @TT_PLATFORM_MICROSOFT charmaps and name entries. + * + * @values: + * TT_MS_ID_SYMBOL_CS :: + * Corresponds to Microsoft symbol encoding. See + * @FT_ENCODING_MS_SYMBOL. + * + * TT_MS_ID_UNICODE_CS :: + * Corresponds to a Microsoft WGL4 charmap, matching Unicode. See + * @FT_ENCODING_UNICODE. + * + * TT_MS_ID_SJIS :: + * Corresponds to SJIS Japanese encoding. See @FT_ENCODING_SJIS. + * + * TT_MS_ID_GB2312 :: + * Corresponds to Simplified Chinese as used in Mainland China. See + * @FT_ENCODING_GB2312. + * + * TT_MS_ID_BIG_5 :: + * Corresponds to Traditional Chinese as used in Taiwan and Hong Kong. + * See @FT_ENCODING_BIG5. + * + * TT_MS_ID_WANSUNG :: + * Corresponds to Korean Wansung encoding. See @FT_ENCODING_WANSUNG. + * + * TT_MS_ID_JOHAB :: + * Corresponds to Johab encoding. See @FT_ENCODING_JOHAB. + * + * TT_MS_ID_UCS_4 :: + * Corresponds to UCS-4 or UTF-32 charmaps. This has been added to + * the OpenType specification version 1.4 (mid-2001.) + */ + +#define TT_MS_ID_SYMBOL_CS 0 +#define TT_MS_ID_UNICODE_CS 1 +#define TT_MS_ID_SJIS 2 +#define TT_MS_ID_GB2312 3 +#define TT_MS_ID_BIG_5 4 +#define TT_MS_ID_WANSUNG 5 +#define TT_MS_ID_JOHAB 6 +#define TT_MS_ID_UCS_4 10 + + + /*********************************************************************** + * + * @enum: + * TT_ADOBE_ID_XXX + * + * @description: + * A list of valid values for the `encoding_id' for + * @TT_PLATFORM_ADOBE charmaps. This is a FreeType-specific extension! + * + * @values: + * TT_ADOBE_ID_STANDARD :: + * Adobe standard encoding. + * TT_ADOBE_ID_EXPERT :: + * Adobe expert encoding. + * TT_ADOBE_ID_CUSTOM :: + * Adobe custom encoding. + * TT_ADOBE_ID_LATIN_1 :: + * Adobe Latin~1 encoding. + */ + +#define TT_ADOBE_ID_STANDARD 0 +#define TT_ADOBE_ID_EXPERT 1 +#define TT_ADOBE_ID_CUSTOM 2 +#define TT_ADOBE_ID_LATIN_1 3 + + + /*************************************************************************/ + /* */ + /* Possible values of the language identifier field in the name records */ + /* of the TTF `name' table if the `platform' identifier code is */ + /* TT_PLATFORM_MACINTOSH. */ + /* */ + /* The canonical source for the Apple assigned Language ID's is at */ + /* */ + /* http://fonts.apple.com/TTRefMan/RM06/Chap6name.html */ + /* */ +#define TT_MAC_LANGID_ENGLISH 0 +#define TT_MAC_LANGID_FRENCH 1 +#define TT_MAC_LANGID_GERMAN 2 +#define TT_MAC_LANGID_ITALIAN 3 +#define TT_MAC_LANGID_DUTCH 4 +#define TT_MAC_LANGID_SWEDISH 5 +#define TT_MAC_LANGID_SPANISH 6 +#define TT_MAC_LANGID_DANISH 7 +#define TT_MAC_LANGID_PORTUGUESE 8 +#define TT_MAC_LANGID_NORWEGIAN 9 +#define TT_MAC_LANGID_HEBREW 10 +#define TT_MAC_LANGID_JAPANESE 11 +#define TT_MAC_LANGID_ARABIC 12 +#define TT_MAC_LANGID_FINNISH 13 +#define TT_MAC_LANGID_GREEK 14 +#define TT_MAC_LANGID_ICELANDIC 15 +#define TT_MAC_LANGID_MALTESE 16 +#define TT_MAC_LANGID_TURKISH 17 +#define TT_MAC_LANGID_CROATIAN 18 +#define TT_MAC_LANGID_CHINESE_TRADITIONAL 19 +#define TT_MAC_LANGID_URDU 20 +#define TT_MAC_LANGID_HINDI 21 +#define TT_MAC_LANGID_THAI 22 +#define TT_MAC_LANGID_KOREAN 23 +#define TT_MAC_LANGID_LITHUANIAN 24 +#define TT_MAC_LANGID_POLISH 25 +#define TT_MAC_LANGID_HUNGARIAN 26 +#define TT_MAC_LANGID_ESTONIAN 27 +#define TT_MAC_LANGID_LETTISH 28 +#define TT_MAC_LANGID_SAAMISK 29 +#define TT_MAC_LANGID_FAEROESE 30 +#define TT_MAC_LANGID_FARSI 31 +#define TT_MAC_LANGID_RUSSIAN 32 +#define TT_MAC_LANGID_CHINESE_SIMPLIFIED 33 +#define TT_MAC_LANGID_FLEMISH 34 +#define TT_MAC_LANGID_IRISH 35 +#define TT_MAC_LANGID_ALBANIAN 36 +#define TT_MAC_LANGID_ROMANIAN 37 +#define TT_MAC_LANGID_CZECH 38 +#define TT_MAC_LANGID_SLOVAK 39 +#define TT_MAC_LANGID_SLOVENIAN 40 +#define TT_MAC_LANGID_YIDDISH 41 +#define TT_MAC_LANGID_SERBIAN 42 +#define TT_MAC_LANGID_MACEDONIAN 43 +#define TT_MAC_LANGID_BULGARIAN 44 +#define TT_MAC_LANGID_UKRAINIAN 45 +#define TT_MAC_LANGID_BYELORUSSIAN 46 +#define TT_MAC_LANGID_UZBEK 47 +#define TT_MAC_LANGID_KAZAKH 48 +#define TT_MAC_LANGID_AZERBAIJANI 49 +#define TT_MAC_LANGID_AZERBAIJANI_CYRILLIC_SCRIPT 49 +#define TT_MAC_LANGID_AZERBAIJANI_ARABIC_SCRIPT 50 +#define TT_MAC_LANGID_ARMENIAN 51 +#define TT_MAC_LANGID_GEORGIAN 52 +#define TT_MAC_LANGID_MOLDAVIAN 53 +#define TT_MAC_LANGID_KIRGHIZ 54 +#define TT_MAC_LANGID_TAJIKI 55 +#define TT_MAC_LANGID_TURKMEN 56 +#define TT_MAC_LANGID_MONGOLIAN 57 +#define TT_MAC_LANGID_MONGOLIAN_MONGOLIAN_SCRIPT 57 +#define TT_MAC_LANGID_MONGOLIAN_CYRILLIC_SCRIPT 58 +#define TT_MAC_LANGID_PASHTO 59 +#define TT_MAC_LANGID_KURDISH 60 +#define TT_MAC_LANGID_KASHMIRI 61 +#define TT_MAC_LANGID_SINDHI 62 +#define TT_MAC_LANGID_TIBETAN 63 +#define TT_MAC_LANGID_NEPALI 64 +#define TT_MAC_LANGID_SANSKRIT 65 +#define TT_MAC_LANGID_MARATHI 66 +#define TT_MAC_LANGID_BENGALI 67 +#define TT_MAC_LANGID_ASSAMESE 68 +#define TT_MAC_LANGID_GUJARATI 69 +#define TT_MAC_LANGID_PUNJABI 70 +#define TT_MAC_LANGID_ORIYA 71 +#define TT_MAC_LANGID_MALAYALAM 72 +#define TT_MAC_LANGID_KANNADA 73 +#define TT_MAC_LANGID_TAMIL 74 +#define TT_MAC_LANGID_TELUGU 75 +#define TT_MAC_LANGID_SINHALESE 76 +#define TT_MAC_LANGID_BURMESE 77 +#define TT_MAC_LANGID_KHMER 78 +#define TT_MAC_LANGID_LAO 79 +#define TT_MAC_LANGID_VIETNAMESE 80 +#define TT_MAC_LANGID_INDONESIAN 81 +#define TT_MAC_LANGID_TAGALOG 82 +#define TT_MAC_LANGID_MALAY_ROMAN_SCRIPT 83 +#define TT_MAC_LANGID_MALAY_ARABIC_SCRIPT 84 +#define TT_MAC_LANGID_AMHARIC 85 +#define TT_MAC_LANGID_TIGRINYA 86 +#define TT_MAC_LANGID_GALLA 87 +#define TT_MAC_LANGID_SOMALI 88 +#define TT_MAC_LANGID_SWAHILI 89 +#define TT_MAC_LANGID_RUANDA 90 +#define TT_MAC_LANGID_RUNDI 91 +#define TT_MAC_LANGID_CHEWA 92 +#define TT_MAC_LANGID_MALAGASY 93 +#define TT_MAC_LANGID_ESPERANTO 94 +#define TT_MAC_LANGID_WELSH 128 +#define TT_MAC_LANGID_BASQUE 129 +#define TT_MAC_LANGID_CATALAN 130 +#define TT_MAC_LANGID_LATIN 131 +#define TT_MAC_LANGID_QUECHUA 132 +#define TT_MAC_LANGID_GUARANI 133 +#define TT_MAC_LANGID_AYMARA 134 +#define TT_MAC_LANGID_TATAR 135 +#define TT_MAC_LANGID_UIGHUR 136 +#define TT_MAC_LANGID_DZONGKHA 137 +#define TT_MAC_LANGID_JAVANESE 138 +#define TT_MAC_LANGID_SUNDANESE 139 + + +#if 0 /* these seem to be errors that have been dropped */ + +#define TT_MAC_LANGID_SCOTTISH_GAELIC 140 +#define TT_MAC_LANGID_IRISH_GAELIC 141 + +#endif + + + /* The following codes are new as of 2000-03-10 */ +#define TT_MAC_LANGID_GALICIAN 140 +#define TT_MAC_LANGID_AFRIKAANS 141 +#define TT_MAC_LANGID_BRETON 142 +#define TT_MAC_LANGID_INUKTITUT 143 +#define TT_MAC_LANGID_SCOTTISH_GAELIC 144 +#define TT_MAC_LANGID_MANX_GAELIC 145 +#define TT_MAC_LANGID_IRISH_GAELIC 146 +#define TT_MAC_LANGID_TONGAN 147 +#define TT_MAC_LANGID_GREEK_POLYTONIC 148 +#define TT_MAC_LANGID_GREELANDIC 149 +#define TT_MAC_LANGID_AZERBAIJANI_ROMAN_SCRIPT 150 + + + /*************************************************************************/ + /* */ + /* Possible values of the language identifier field in the name records */ + /* of the TTF `name' table if the `platform' identifier code is */ + /* TT_PLATFORM_MICROSOFT. */ + /* */ + /* The canonical source for the MS assigned LCID's (seems to) be at */ + /* */ + /* http://www.microsoft.com/globaldev/reference/lcid-all.mspx */ + /* */ + /* It used to be at various places, among them */ + /* */ + /* http://www.microsoft.com/typography/OTSPEC/lcid-cp.txt */ + /* http://www.microsoft.com/globaldev/reference/loclanghome.asp */ + /* http://support.microsoft.com/support/kb/articles/Q224/8/04.ASP */ + /* http://msdn.microsoft.com/library/en-us/passport25/ */ + /* NET_Passport_VBScript_Documentation/Single_Sign_In/ */ + /* Advanced_Single_Sign_In/Localization_and_LCIDs.asp */ + /* */ + /* Hopefully, it seems now that the Globaldev site prevails... */ + /* (updated by Antoine, 2004-02-17) */ + +#define TT_MS_LANGID_ARABIC_GENERAL 0x0001 +#define TT_MS_LANGID_ARABIC_SAUDI_ARABIA 0x0401 +#define TT_MS_LANGID_ARABIC_IRAQ 0x0801 +#define TT_MS_LANGID_ARABIC_EGYPT 0x0c01 +#define TT_MS_LANGID_ARABIC_LIBYA 0x1001 +#define TT_MS_LANGID_ARABIC_ALGERIA 0x1401 +#define TT_MS_LANGID_ARABIC_MOROCCO 0x1801 +#define TT_MS_LANGID_ARABIC_TUNISIA 0x1c01 +#define TT_MS_LANGID_ARABIC_OMAN 0x2001 +#define TT_MS_LANGID_ARABIC_YEMEN 0x2401 +#define TT_MS_LANGID_ARABIC_SYRIA 0x2801 +#define TT_MS_LANGID_ARABIC_JORDAN 0x2c01 +#define TT_MS_LANGID_ARABIC_LEBANON 0x3001 +#define TT_MS_LANGID_ARABIC_KUWAIT 0x3401 +#define TT_MS_LANGID_ARABIC_UAE 0x3801 +#define TT_MS_LANGID_ARABIC_BAHRAIN 0x3c01 +#define TT_MS_LANGID_ARABIC_QATAR 0x4001 +#define TT_MS_LANGID_BULGARIAN_BULGARIA 0x0402 +#define TT_MS_LANGID_CATALAN_SPAIN 0x0403 +#define TT_MS_LANGID_CHINESE_GENERAL 0x0004 +#define TT_MS_LANGID_CHINESE_TAIWAN 0x0404 +#define TT_MS_LANGID_CHINESE_PRC 0x0804 +#define TT_MS_LANGID_CHINESE_HONG_KONG 0x0c04 +#define TT_MS_LANGID_CHINESE_SINGAPORE 0x1004 + +#if 1 /* this looks like the correct value */ +#define TT_MS_LANGID_CHINESE_MACAU 0x1404 +#else /* but beware, Microsoft may change its mind... + the most recent Word reference has the following: */ +#define TT_MS_LANGID_CHINESE_MACAU TT_MS_LANGID_CHINESE_HONG_KONG +#endif + +#if 0 /* used only with .NET `cultures'; commented out */ +#define TT_MS_LANGID_CHINESE_TRADITIONAL 0x7C04 +#endif + +#define TT_MS_LANGID_CZECH_CZECH_REPUBLIC 0x0405 +#define TT_MS_LANGID_DANISH_DENMARK 0x0406 +#define TT_MS_LANGID_GERMAN_GERMANY 0x0407 +#define TT_MS_LANGID_GERMAN_SWITZERLAND 0x0807 +#define TT_MS_LANGID_GERMAN_AUSTRIA 0x0c07 +#define TT_MS_LANGID_GERMAN_LUXEMBOURG 0x1007 +#define TT_MS_LANGID_GERMAN_LIECHTENSTEI 0x1407 +#define TT_MS_LANGID_GREEK_GREECE 0x0408 + + /* don't ask what this one means... It is commented out currently. */ +#if 0 +#define TT_MS_LANGID_GREEK_GREECE2 0x2008 +#endif + +#define TT_MS_LANGID_ENGLISH_GENERAL 0x0009 +#define TT_MS_LANGID_ENGLISH_UNITED_STATES 0x0409 +#define TT_MS_LANGID_ENGLISH_UNITED_KINGDOM 0x0809 +#define TT_MS_LANGID_ENGLISH_AUSTRALIA 0x0c09 +#define TT_MS_LANGID_ENGLISH_CANADA 0x1009 +#define TT_MS_LANGID_ENGLISH_NEW_ZEALAND 0x1409 +#define TT_MS_LANGID_ENGLISH_IRELAND 0x1809 +#define TT_MS_LANGID_ENGLISH_SOUTH_AFRICA 0x1c09 +#define TT_MS_LANGID_ENGLISH_JAMAICA 0x2009 +#define TT_MS_LANGID_ENGLISH_CARIBBEAN 0x2409 +#define TT_MS_LANGID_ENGLISH_BELIZE 0x2809 +#define TT_MS_LANGID_ENGLISH_TRINIDAD 0x2c09 +#define TT_MS_LANGID_ENGLISH_ZIMBABWE 0x3009 +#define TT_MS_LANGID_ENGLISH_PHILIPPINES 0x3409 +#define TT_MS_LANGID_ENGLISH_INDONESIA 0x3809 +#define TT_MS_LANGID_ENGLISH_HONG_KONG 0x3c09 +#define TT_MS_LANGID_ENGLISH_INDIA 0x4009 +#define TT_MS_LANGID_ENGLISH_MALAYSIA 0x4409 +#define TT_MS_LANGID_ENGLISH_SINGAPORE 0x4809 +#define TT_MS_LANGID_SPANISH_SPAIN_TRADITIONAL_SORT 0x040a +#define TT_MS_LANGID_SPANISH_MEXICO 0x080a +#define TT_MS_LANGID_SPANISH_SPAIN_INTERNATIONAL_SORT 0x0c0a +#define TT_MS_LANGID_SPANISH_GUATEMALA 0x100a +#define TT_MS_LANGID_SPANISH_COSTA_RICA 0x140a +#define TT_MS_LANGID_SPANISH_PANAMA 0x180a +#define TT_MS_LANGID_SPANISH_DOMINICAN_REPUBLIC 0x1c0a +#define TT_MS_LANGID_SPANISH_VENEZUELA 0x200a +#define TT_MS_LANGID_SPANISH_COLOMBIA 0x240a +#define TT_MS_LANGID_SPANISH_PERU 0x280a +#define TT_MS_LANGID_SPANISH_ARGENTINA 0x2c0a +#define TT_MS_LANGID_SPANISH_ECUADOR 0x300a +#define TT_MS_LANGID_SPANISH_CHILE 0x340a +#define TT_MS_LANGID_SPANISH_URUGUAY 0x380a +#define TT_MS_LANGID_SPANISH_PARAGUAY 0x3c0a +#define TT_MS_LANGID_SPANISH_BOLIVIA 0x400a +#define TT_MS_LANGID_SPANISH_EL_SALVADOR 0x440a +#define TT_MS_LANGID_SPANISH_HONDURAS 0x480a +#define TT_MS_LANGID_SPANISH_NICARAGUA 0x4c0a +#define TT_MS_LANGID_SPANISH_PUERTO_RICO 0x500a +#define TT_MS_LANGID_SPANISH_UNITED_STATES 0x540a + /* The following ID blatantly violate MS specs by using a */ + /* sublanguage > 0x1F. */ +#define TT_MS_LANGID_SPANISH_LATIN_AMERICA 0xE40aU +#define TT_MS_LANGID_FINNISH_FINLAND 0x040b +#define TT_MS_LANGID_FRENCH_FRANCE 0x040c +#define TT_MS_LANGID_FRENCH_BELGIUM 0x080c +#define TT_MS_LANGID_FRENCH_CANADA 0x0c0c +#define TT_MS_LANGID_FRENCH_SWITZERLAND 0x100c +#define TT_MS_LANGID_FRENCH_LUXEMBOURG 0x140c +#define TT_MS_LANGID_FRENCH_MONACO 0x180c +#define TT_MS_LANGID_FRENCH_WEST_INDIES 0x1c0c +#define TT_MS_LANGID_FRENCH_REUNION 0x200c +#define TT_MS_LANGID_FRENCH_CONGO 0x240c + /* which was formerly: */ +#define TT_MS_LANGID_FRENCH_ZAIRE TT_MS_LANGID_FRENCH_CONGO +#define TT_MS_LANGID_FRENCH_SENEGAL 0x280c +#define TT_MS_LANGID_FRENCH_CAMEROON 0x2c0c +#define TT_MS_LANGID_FRENCH_COTE_D_IVOIRE 0x300c +#define TT_MS_LANGID_FRENCH_MALI 0x340c +#define TT_MS_LANGID_FRENCH_MOROCCO 0x380c +#define TT_MS_LANGID_FRENCH_HAITI 0x3c0c + /* and another violation of the spec (see 0xE40aU) */ +#define TT_MS_LANGID_FRENCH_NORTH_AFRICA 0xE40cU +#define TT_MS_LANGID_HEBREW_ISRAEL 0x040d +#define TT_MS_LANGID_HUNGARIAN_HUNGARY 0x040e +#define TT_MS_LANGID_ICELANDIC_ICELAND 0x040f +#define TT_MS_LANGID_ITALIAN_ITALY 0x0410 +#define TT_MS_LANGID_ITALIAN_SWITZERLAND 0x0810 +#define TT_MS_LANGID_JAPANESE_JAPAN 0x0411 +#define TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA 0x0412 +#define TT_MS_LANGID_KOREAN_JOHAB_KOREA 0x0812 +#define TT_MS_LANGID_DUTCH_NETHERLANDS 0x0413 +#define TT_MS_LANGID_DUTCH_BELGIUM 0x0813 +#define TT_MS_LANGID_NORWEGIAN_NORWAY_BOKMAL 0x0414 +#define TT_MS_LANGID_NORWEGIAN_NORWAY_NYNORSK 0x0814 +#define TT_MS_LANGID_POLISH_POLAND 0x0415 +#define TT_MS_LANGID_PORTUGUESE_BRAZIL 0x0416 +#define TT_MS_LANGID_PORTUGUESE_PORTUGAL 0x0816 +#define TT_MS_LANGID_RHAETO_ROMANIC_SWITZERLAND 0x0417 +#define TT_MS_LANGID_ROMANIAN_ROMANIA 0x0418 +#define TT_MS_LANGID_MOLDAVIAN_MOLDAVIA 0x0818 +#define TT_MS_LANGID_RUSSIAN_RUSSIA 0x0419 +#define TT_MS_LANGID_RUSSIAN_MOLDAVIA 0x0819 +#define TT_MS_LANGID_CROATIAN_CROATIA 0x041a +#define TT_MS_LANGID_SERBIAN_SERBIA_LATIN 0x081a +#define TT_MS_LANGID_SERBIAN_SERBIA_CYRILLIC 0x0c1a + +#if 0 /* this used to be this value, but it looks like we were wrong */ +#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA 0x101a +#else /* current sources say */ +#define TT_MS_LANGID_CROATIAN_BOSNIA_HERZEGOVINA 0x101a +#define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA 0x141a + /* and XPsp2 Platform SDK added (2004-07-26) */ + /* Names are shortened to be significant within 40 chars. */ +#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_LATIN 0x181a +#define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_CYRILLIC 0x181a +#endif + +#define TT_MS_LANGID_SLOVAK_SLOVAKIA 0x041b +#define TT_MS_LANGID_ALBANIAN_ALBANIA 0x041c +#define TT_MS_LANGID_SWEDISH_SWEDEN 0x041d +#define TT_MS_LANGID_SWEDISH_FINLAND 0x081d +#define TT_MS_LANGID_THAI_THAILAND 0x041e +#define TT_MS_LANGID_TURKISH_TURKEY 0x041f +#define TT_MS_LANGID_URDU_PAKISTAN 0x0420 +#define TT_MS_LANGID_URDU_INDIA 0x0820 +#define TT_MS_LANGID_INDONESIAN_INDONESIA 0x0421 +#define TT_MS_LANGID_UKRAINIAN_UKRAINE 0x0422 +#define TT_MS_LANGID_BELARUSIAN_BELARUS 0x0423 +#define TT_MS_LANGID_SLOVENE_SLOVENIA 0x0424 +#define TT_MS_LANGID_ESTONIAN_ESTONIA 0x0425 +#define TT_MS_LANGID_LATVIAN_LATVIA 0x0426 +#define TT_MS_LANGID_LITHUANIAN_LITHUANIA 0x0427 +#define TT_MS_LANGID_CLASSIC_LITHUANIAN_LITHUANIA 0x0827 +#define TT_MS_LANGID_TAJIK_TAJIKISTAN 0x0428 +#define TT_MS_LANGID_FARSI_IRAN 0x0429 +#define TT_MS_LANGID_VIETNAMESE_VIET_NAM 0x042a +#define TT_MS_LANGID_ARMENIAN_ARMENIA 0x042b +#define TT_MS_LANGID_AZERI_AZERBAIJAN_LATIN 0x042c +#define TT_MS_LANGID_AZERI_AZERBAIJAN_CYRILLIC 0x082c +#define TT_MS_LANGID_BASQUE_SPAIN 0x042d +#define TT_MS_LANGID_SORBIAN_GERMANY 0x042e +#define TT_MS_LANGID_MACEDONIAN_MACEDONIA 0x042f +#define TT_MS_LANGID_SUTU_SOUTH_AFRICA 0x0430 +#define TT_MS_LANGID_TSONGA_SOUTH_AFRICA 0x0431 +#define TT_MS_LANGID_TSWANA_SOUTH_AFRICA 0x0432 +#define TT_MS_LANGID_VENDA_SOUTH_AFRICA 0x0433 +#define TT_MS_LANGID_XHOSA_SOUTH_AFRICA 0x0434 +#define TT_MS_LANGID_ZULU_SOUTH_AFRICA 0x0435 +#define TT_MS_LANGID_AFRIKAANS_SOUTH_AFRICA 0x0436 +#define TT_MS_LANGID_GEORGIAN_GEORGIA 0x0437 +#define TT_MS_LANGID_FAEROESE_FAEROE_ISLANDS 0x0438 +#define TT_MS_LANGID_HINDI_INDIA 0x0439 +#define TT_MS_LANGID_MALTESE_MALTA 0x043a + /* Added by XPsp2 Platform SDK (2004-07-26) */ +#define TT_MS_LANGID_SAMI_NORTHERN_NORWAY 0x043b +#define TT_MS_LANGID_SAMI_NORTHERN_SWEDEN 0x083b +#define TT_MS_LANGID_SAMI_NORTHERN_FINLAND 0x0C3b +#define TT_MS_LANGID_SAMI_LULE_NORWAY 0x103b +#define TT_MS_LANGID_SAMI_LULE_SWEDEN 0x143b +#define TT_MS_LANGID_SAMI_SOUTHERN_NORWAY 0x183b +#define TT_MS_LANGID_SAMI_SOUTHERN_SWEDEN 0x1C3b +#define TT_MS_LANGID_SAMI_SKOLT_FINLAND 0x203b +#define TT_MS_LANGID_SAMI_INARI_FINLAND 0x243b + /* ... and we also keep our old identifier... */ +#define TT_MS_LANGID_SAAMI_LAPONIA 0x043b + +#if 0 /* this seems to be a previous inversion */ +#define TT_MS_LANGID_IRISH_GAELIC_IRELAND 0x043c +#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM 0x083c +#else +#define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM 0x083c +#define TT_MS_LANGID_IRISH_GAELIC_IRELAND 0x043c +#endif + +#define TT_MS_LANGID_YIDDISH_GERMANY 0x043d +#define TT_MS_LANGID_MALAY_MALAYSIA 0x043e +#define TT_MS_LANGID_MALAY_BRUNEI_DARUSSALAM 0x083e +#define TT_MS_LANGID_KAZAK_KAZAKSTAN 0x043f +#define TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN /* Cyrillic*/ 0x0440 + /* alias declared in Windows 2000 */ +#define TT_MS_LANGID_KIRGHIZ_KIRGHIZ_REPUBLIC \ + TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN + +#define TT_MS_LANGID_SWAHILI_KENYA 0x0441 +#define TT_MS_LANGID_TURKMEN_TURKMENISTAN 0x0442 +#define TT_MS_LANGID_UZBEK_UZBEKISTAN_LATIN 0x0443 +#define TT_MS_LANGID_UZBEK_UZBEKISTAN_CYRILLIC 0x0843 +#define TT_MS_LANGID_TATAR_TATARSTAN 0x0444 +#define TT_MS_LANGID_BENGALI_INDIA 0x0445 +#define TT_MS_LANGID_BENGALI_BANGLADESH 0x0845 +#define TT_MS_LANGID_PUNJABI_INDIA 0x0446 +#define TT_MS_LANGID_PUNJABI_ARABIC_PAKISTAN 0x0846 +#define TT_MS_LANGID_GUJARATI_INDIA 0x0447 +#define TT_MS_LANGID_ORIYA_INDIA 0x0448 +#define TT_MS_LANGID_TAMIL_INDIA 0x0449 +#define TT_MS_LANGID_TELUGU_INDIA 0x044a +#define TT_MS_LANGID_KANNADA_INDIA 0x044b +#define TT_MS_LANGID_MALAYALAM_INDIA 0x044c +#define TT_MS_LANGID_ASSAMESE_INDIA 0x044d +#define TT_MS_LANGID_MARATHI_INDIA 0x044e +#define TT_MS_LANGID_SANSKRIT_INDIA 0x044f +#define TT_MS_LANGID_MONGOLIAN_MONGOLIA /* Cyrillic */ 0x0450 +#define TT_MS_LANGID_MONGOLIAN_MONGOLIA_MONGOLIAN 0x0850 +#define TT_MS_LANGID_TIBETAN_CHINA 0x0451 + /* Don't use the next constant! It has */ + /* (1) the wrong spelling (Dzonghka) */ + /* (2) Microsoft doesn't officially define it -- */ + /* at least it is not in the List of Local */ + /* ID Values. */ + /* (3) Dzongkha is not the same language as */ + /* Tibetan, so merging it is wrong anyway. */ + /* */ + /* TT_MS_LANGID_TIBETAN_BHUTAN is correct, BTW. */ +#define TT_MS_LANGID_DZONGHKA_BHUTAN 0x0851 + +#if 0 + /* the following used to be defined */ +#define TT_MS_LANGID_TIBETAN_BHUTAN 0x0451 + /* ... but it was changed; */ +#else + /* So we will continue to #define it, but with the correct value */ +#define TT_MS_LANGID_TIBETAN_BHUTAN TT_MS_LANGID_DZONGHKA_BHUTAN +#endif + +#define TT_MS_LANGID_WELSH_WALES 0x0452 +#define TT_MS_LANGID_KHMER_CAMBODIA 0x0453 +#define TT_MS_LANGID_LAO_LAOS 0x0454 +#define TT_MS_LANGID_BURMESE_MYANMAR 0x0455 +#define TT_MS_LANGID_GALICIAN_SPAIN 0x0456 +#define TT_MS_LANGID_KONKANI_INDIA 0x0457 +#define TT_MS_LANGID_MANIPURI_INDIA /* Bengali */ 0x0458 +#define TT_MS_LANGID_SINDHI_INDIA /* Arabic */ 0x0459 +#define TT_MS_LANGID_SINDHI_PAKISTAN 0x0859 + /* Missing a LCID for Sindhi in Devanagari script */ +#define TT_MS_LANGID_SYRIAC_SYRIA 0x045a +#define TT_MS_LANGID_SINHALESE_SRI_LANKA 0x045b +#define TT_MS_LANGID_CHEROKEE_UNITED_STATES 0x045c +#define TT_MS_LANGID_INUKTITUT_CANADA 0x045d +#define TT_MS_LANGID_AMHARIC_ETHIOPIA 0x045e +#define TT_MS_LANGID_TAMAZIGHT_MOROCCO /* Arabic */ 0x045f +#define TT_MS_LANGID_TAMAZIGHT_MOROCCO_LATIN 0x085f + /* Missing a LCID for Tifinagh script */ +#define TT_MS_LANGID_KASHMIRI_PAKISTAN /* Arabic */ 0x0460 + /* Spelled this way by XPsp2 Platform SDK (2004-07-26) */ + /* script is yet unclear... might be Arabic, Nagari or Sharada */ +#define TT_MS_LANGID_KASHMIRI_SASIA 0x0860 + /* ... and aliased (by MS) for compatibility reasons. */ +#define TT_MS_LANGID_KASHMIRI_INDIA TT_MS_LANGID_KASHMIRI_SASIA +#define TT_MS_LANGID_NEPALI_NEPAL 0x0461 +#define TT_MS_LANGID_NEPALI_INDIA 0x0861 +#define TT_MS_LANGID_FRISIAN_NETHERLANDS 0x0462 +#define TT_MS_LANGID_PASHTO_AFGHANISTAN 0x0463 +#define TT_MS_LANGID_FILIPINO_PHILIPPINES 0x0464 +#define TT_MS_LANGID_DHIVEHI_MALDIVES 0x0465 + /* alias declared in Windows 2000 */ +#define TT_MS_LANGID_DIVEHI_MALDIVES TT_MS_LANGID_DHIVEHI_MALDIVES +#define TT_MS_LANGID_EDO_NIGERIA 0x0466 +#define TT_MS_LANGID_FULFULDE_NIGERIA 0x0467 +#define TT_MS_LANGID_HAUSA_NIGERIA 0x0468 +#define TT_MS_LANGID_IBIBIO_NIGERIA 0x0469 +#define TT_MS_LANGID_YORUBA_NIGERIA 0x046a +#define TT_MS_LANGID_QUECHUA_BOLIVIA 0x046b +#define TT_MS_LANGID_QUECHUA_ECUADOR 0x086b +#define TT_MS_LANGID_QUECHUA_PERU 0x0c6b +#define TT_MS_LANGID_SEPEDI_SOUTH_AFRICA 0x046c + /* Also spelled by XPsp2 Platform SDK (2004-07-26) */ +#define TT_MS_LANGID_SOTHO_SOUTHERN_SOUTH_AFRICA \ + TT_MS_LANGID_SEPEDI_SOUTH_AFRICA + /* language codes 0x046d, 0x046e and 0x046f are (still) unknown. */ +#define TT_MS_LANGID_IGBO_NIGERIA 0x0470 +#define TT_MS_LANGID_KANURI_NIGERIA 0x0471 +#define TT_MS_LANGID_OROMO_ETHIOPIA 0x0472 +#define TT_MS_LANGID_TIGRIGNA_ETHIOPIA 0x0473 +#define TT_MS_LANGID_TIGRIGNA_ERYTHREA 0x0873 + /* also spelled in the `Passport SDK' list as: */ +#define TT_MS_LANGID_TIGRIGNA_ERYTREA TT_MS_LANGID_TIGRIGNA_ERYTHREA +#define TT_MS_LANGID_GUARANI_PARAGUAY 0x0474 +#define TT_MS_LANGID_HAWAIIAN_UNITED_STATES 0x0475 +#define TT_MS_LANGID_LATIN 0x0476 +#define TT_MS_LANGID_SOMALI_SOMALIA 0x0477 + /* Note: Yi does not have a (proper) ISO 639-2 code, since it is mostly */ + /* not written (but OTOH the peculiar writing system is worth */ + /* studying). */ +#define TT_MS_LANGID_YI_CHINA 0x0478 +#define TT_MS_LANGID_PAPIAMENTU_NETHERLANDS_ANTILLES 0x0479 + /* language codes from 0x047a to 0x047f are (still) unknown. */ +#define TT_MS_LANGID_UIGHUR_CHINA 0x0480 +#define TT_MS_LANGID_MAORI_NEW_ZEALAND 0x0481 + +#if 0 /* not deemed useful for fonts */ +#define TT_MS_LANGID_HUMAN_INTERFACE_DEVICE 0x04ff +#endif + + + /*************************************************************************/ + /* */ + /* Possible values of the `name' identifier field in the name records of */ + /* the TTF `name' table. These values are platform independent. */ + /* */ +#define TT_NAME_ID_COPYRIGHT 0 +#define TT_NAME_ID_FONT_FAMILY 1 +#define TT_NAME_ID_FONT_SUBFAMILY 2 +#define TT_NAME_ID_UNIQUE_ID 3 +#define TT_NAME_ID_FULL_NAME 4 +#define TT_NAME_ID_VERSION_STRING 5 +#define TT_NAME_ID_PS_NAME 6 +#define TT_NAME_ID_TRADEMARK 7 + + /* the following values are from the OpenType spec */ +#define TT_NAME_ID_MANUFACTURER 8 +#define TT_NAME_ID_DESIGNER 9 +#define TT_NAME_ID_DESCRIPTION 10 +#define TT_NAME_ID_VENDOR_URL 11 +#define TT_NAME_ID_DESIGNER_URL 12 +#define TT_NAME_ID_LICENSE 13 +#define TT_NAME_ID_LICENSE_URL 14 + /* number 15 is reserved */ +#define TT_NAME_ID_PREFERRED_FAMILY 16 +#define TT_NAME_ID_PREFERRED_SUBFAMILY 17 +#define TT_NAME_ID_MAC_FULL_NAME 18 + + /* The following code is new as of 2000-01-21 */ +#define TT_NAME_ID_SAMPLE_TEXT 19 + + /* This is new in OpenType 1.3 */ +#define TT_NAME_ID_CID_FINDFONT_NAME 20 + + /* This is new in OpenType 1.5 */ +#define TT_NAME_ID_WWS_FAMILY 21 +#define TT_NAME_ID_WWS_SUBFAMILY 22 + + + /*************************************************************************/ + /* */ + /* Bit mask values for the Unicode Ranges from the TTF `OS2 ' table. */ + /* */ + /* Updated 08-Nov-2008. */ + /* */ + + /* Bit 0 Basic Latin */ +#define TT_UCR_BASIC_LATIN (1L << 0) /* U+0020-U+007E */ + /* Bit 1 C1 Controls and Latin-1 Supplement */ +#define TT_UCR_LATIN1_SUPPLEMENT (1L << 1) /* U+0080-U+00FF */ + /* Bit 2 Latin Extended-A */ +#define TT_UCR_LATIN_EXTENDED_A (1L << 2) /* U+0100-U+017F */ + /* Bit 3 Latin Extended-B */ +#define TT_UCR_LATIN_EXTENDED_B (1L << 3) /* U+0180-U+024F */ + /* Bit 4 IPA Extensions */ + /* Phonetic Extensions */ + /* Phonetic Extensions Supplement */ +#define TT_UCR_IPA_EXTENSIONS (1L << 4) /* U+0250-U+02AF */ + /* U+1D00-U+1D7F */ + /* U+1D80-U+1DBF */ + /* Bit 5 Spacing Modifier Letters */ + /* Modifier Tone Letters */ +#define TT_UCR_SPACING_MODIFIER (1L << 5) /* U+02B0-U+02FF */ + /* U+A700-U+A71F */ + /* Bit 6 Combining Diacritical Marks */ + /* Combining Diacritical Marks Supplement */ +#define TT_UCR_COMBINING_DIACRITICS (1L << 6) /* U+0300-U+036F */ + /* U+1DC0-U+1DFF */ + /* Bit 7 Greek and Coptic */ +#define TT_UCR_GREEK (1L << 7) /* U+0370-U+03FF */ + /* Bit 8 Coptic */ +#define TT_UCR_COPTIC (1L << 8) /* U+2C80-U+2CFF */ + /* Bit 9 Cyrillic */ + /* Cyrillic Supplement */ + /* Cyrillic Extended-A */ + /* Cyrillic Extended-B */ +#define TT_UCR_CYRILLIC (1L << 9) /* U+0400-U+04FF */ + /* U+0500-U+052F */ + /* U+2DE0-U+2DFF */ + /* U+A640-U+A69F */ + /* Bit 10 Armenian */ +#define TT_UCR_ARMENIAN (1L << 10) /* U+0530-U+058F */ + /* Bit 11 Hebrew */ +#define TT_UCR_HEBREW (1L << 11) /* U+0590-U+05FF */ + /* Bit 12 Vai */ +#define TT_UCR_VAI (1L << 12) /* U+A500-U+A63F */ + /* Bit 13 Arabic */ + /* Arabic Supplement */ +#define TT_UCR_ARABIC (1L << 13) /* U+0600-U+06FF */ + /* U+0750-U+077F */ + /* Bit 14 NKo */ +#define TT_UCR_NKO (1L << 14) /* U+07C0-U+07FF */ + /* Bit 15 Devanagari */ +#define TT_UCR_DEVANAGARI (1L << 15) /* U+0900-U+097F */ + /* Bit 16 Bengali */ +#define TT_UCR_BENGALI (1L << 16) /* U+0980-U+09FF */ + /* Bit 17 Gurmukhi */ +#define TT_UCR_GURMUKHI (1L << 17) /* U+0A00-U+0A7F */ + /* Bit 18 Gujarati */ +#define TT_UCR_GUJARATI (1L << 18) /* U+0A80-U+0AFF */ + /* Bit 19 Oriya */ +#define TT_UCR_ORIYA (1L << 19) /* U+0B00-U+0B7F */ + /* Bit 20 Tamil */ +#define TT_UCR_TAMIL (1L << 20) /* U+0B80-U+0BFF */ + /* Bit 21 Telugu */ +#define TT_UCR_TELUGU (1L << 21) /* U+0C00-U+0C7F */ + /* Bit 22 Kannada */ +#define TT_UCR_KANNADA (1L << 22) /* U+0C80-U+0CFF */ + /* Bit 23 Malayalam */ +#define TT_UCR_MALAYALAM (1L << 23) /* U+0D00-U+0D7F */ + /* Bit 24 Thai */ +#define TT_UCR_THAI (1L << 24) /* U+0E00-U+0E7F */ + /* Bit 25 Lao */ +#define TT_UCR_LAO (1L << 25) /* U+0E80-U+0EFF */ + /* Bit 26 Georgian */ + /* Georgian Supplement */ +#define TT_UCR_GEORGIAN (1L << 26) /* U+10A0-U+10FF */ + /* U+2D00-U+2D2F */ + /* Bit 27 Balinese */ +#define TT_UCR_BALINESE (1L << 27) /* U+1B00-U+1B7F */ + /* Bit 28 Hangul Jamo */ +#define TT_UCR_HANGUL_JAMO (1L << 28) /* U+1100-U+11FF */ + /* Bit 29 Latin Extended Additional */ + /* Latin Extended-C */ + /* Latin Extended-D */ +#define TT_UCR_LATIN_EXTENDED_ADDITIONAL (1L << 29) /* U+1E00-U+1EFF */ + /* U+2C60-U+2C7F */ + /* U+A720-U+A7FF */ + /* Bit 30 Greek Extended */ +#define TT_UCR_GREEK_EXTENDED (1L << 30) /* U+1F00-U+1FFF */ + /* Bit 31 General Punctuation */ + /* Supplemental Punctuation */ +#define TT_UCR_GENERAL_PUNCTUATION (1L << 31) /* U+2000-U+206F */ + /* U+2E00-U+2E7F */ + /* Bit 32 Superscripts And Subscripts */ +#define TT_UCR_SUPERSCRIPTS_SUBSCRIPTS (1L << 0) /* U+2070-U+209F */ + /* Bit 33 Currency Symbols */ +#define TT_UCR_CURRENCY_SYMBOLS (1L << 1) /* U+20A0-U+20CF */ + /* Bit 34 Combining Diacritical Marks For Symbols */ +#define TT_UCR_COMBINING_DIACRITICS_SYMB (1L << 2) /* U+20D0-U+20FF */ + /* Bit 35 Letterlike Symbols */ +#define TT_UCR_LETTERLIKE_SYMBOLS (1L << 3) /* U+2100-U+214F */ + /* Bit 36 Number Forms */ +#define TT_UCR_NUMBER_FORMS (1L << 4) /* U+2150-U+218F */ + /* Bit 37 Arrows */ + /* Supplemental Arrows-A */ + /* Supplemental Arrows-B */ + /* Miscellaneous Symbols and Arrows */ +#define TT_UCR_ARROWS (1L << 5) /* U+2190-U+21FF */ + /* U+27F0-U+27FF */ + /* U+2900-U+297F */ + /* U+2B00-U+2BFF */ + /* Bit 38 Mathematical Operators */ + /* Supplemental Mathematical Operators */ + /* Miscellaneous Mathematical Symbols-A */ + /* Miscellaneous Mathematical Symbols-B */ +#define TT_UCR_MATHEMATICAL_OPERATORS (1L << 6) /* U+2200-U+22FF */ + /* U+2A00-U+2AFF */ + /* U+27C0-U+27EF */ + /* U+2980-U+29FF */ + /* Bit 39 Miscellaneous Technical */ +#define TT_UCR_MISCELLANEOUS_TECHNICAL (1L << 7) /* U+2300-U+23FF */ + /* Bit 40 Control Pictures */ +#define TT_UCR_CONTROL_PICTURES (1L << 8) /* U+2400-U+243F */ + /* Bit 41 Optical Character Recognition */ +#define TT_UCR_OCR (1L << 9) /* U+2440-U+245F */ + /* Bit 42 Enclosed Alphanumerics */ +#define TT_UCR_ENCLOSED_ALPHANUMERICS (1L << 10) /* U+2460-U+24FF */ + /* Bit 43 Box Drawing */ +#define TT_UCR_BOX_DRAWING (1L << 11) /* U+2500-U+257F */ + /* Bit 44 Block Elements */ +#define TT_UCR_BLOCK_ELEMENTS (1L << 12) /* U+2580-U+259F */ + /* Bit 45 Geometric Shapes */ +#define TT_UCR_GEOMETRIC_SHAPES (1L << 13) /* U+25A0-U+25FF */ + /* Bit 46 Miscellaneous Symbols */ +#define TT_UCR_MISCELLANEOUS_SYMBOLS (1L << 14) /* U+2600-U+26FF */ + /* Bit 47 Dingbats */ +#define TT_UCR_DINGBATS (1L << 15) /* U+2700-U+27BF */ + /* Bit 48 CJK Symbols and Punctuation */ +#define TT_UCR_CJK_SYMBOLS (1L << 16) /* U+3000-U+303F */ + /* Bit 49 Hiragana */ +#define TT_UCR_HIRAGANA (1L << 17) /* U+3040-U+309F */ + /* Bit 50 Katakana */ + /* Katakana Phonetic Extensions */ +#define TT_UCR_KATAKANA (1L << 18) /* U+30A0-U+30FF */ + /* U+31F0-U+31FF */ + /* Bit 51 Bopomofo */ + /* Bopomofo Extended */ +#define TT_UCR_BOPOMOFO (1L << 19) /* U+3100-U+312F */ + /* U+31A0-U+31BF */ + /* Bit 52 Hangul Compatibility Jamo */ +#define TT_UCR_HANGUL_COMPATIBILITY_JAMO (1L << 20) /* U+3130-U+318F */ + /* Bit 53 Phags-Pa */ +#define TT_UCR_CJK_MISC (1L << 21) /* U+A840-U+A87F */ +#define TT_UCR_KANBUN TT_UCR_CJK_MISC /* deprecated */ +#define TT_UCR_PHAGSPA + /* Bit 54 Enclosed CJK Letters and Months */ +#define TT_UCR_ENCLOSED_CJK_LETTERS_MONTHS (1L << 22) /* U+3200-U+32FF */ + /* Bit 55 CJK Compatibility */ +#define TT_UCR_CJK_COMPATIBILITY (1L << 23) /* U+3300-U+33FF */ + /* Bit 56 Hangul Syllables */ +#define TT_UCR_HANGUL (1L << 24) /* U+AC00-U+D7A3 */ + /* Bit 57 High Surrogates */ + /* High Private Use Surrogates */ + /* Low Surrogates */ + /* */ + /* According to OpenType specs v.1.3+, */ + /* setting bit 57 implies that there is */ + /* at least one codepoint beyond the */ + /* Basic Multilingual Plane that is */ + /* supported by this font. So it really */ + /* means >= U+10000 */ +#define TT_UCR_SURROGATES (1L << 25) /* U+D800-U+DB7F */ + /* U+DB80-U+DBFF */ + /* U+DC00-U+DFFF */ +#define TT_UCR_NON_PLANE_0 TT_UCR_SURROGATES + /* Bit 58 Phoenician */ +#define TT_UCR_PHOENICIAN (1L << 26) /*U+10900-U+1091F*/ + /* Bit 59 CJK Unified Ideographs */ + /* CJK Radicals Supplement */ + /* Kangxi Radicals */ + /* Ideographic Description Characters */ + /* CJK Unified Ideographs Extension A */ + /* CJK Unified Ideographs Extension B */ + /* Kanbun */ +#define TT_UCR_CJK_UNIFIED_IDEOGRAPHS (1L << 27) /* U+4E00-U+9FFF */ + /* U+2E80-U+2EFF */ + /* U+2F00-U+2FDF */ + /* U+2FF0-U+2FFF */ + /* U+3400-U+4DB5 */ + /*U+20000-U+2A6DF*/ + /* U+3190-U+319F */ + /* Bit 60 Private Use */ +#define TT_UCR_PRIVATE_USE (1L << 28) /* U+E000-U+F8FF */ + /* Bit 61 CJK Strokes */ + /* CJK Compatibility Ideographs */ + /* CJK Compatibility Ideographs Supplement */ +#define TT_UCR_CJK_COMPATIBILITY_IDEOGRAPHS (1L << 29) /* U+31C0-U+31EF */ + /* U+F900-U+FAFF */ + /*U+2F800-U+2FA1F*/ + /* Bit 62 Alphabetic Presentation Forms */ +#define TT_UCR_ALPHABETIC_PRESENTATION_FORMS (1L << 30) /* U+FB00-U+FB4F */ + /* Bit 63 Arabic Presentation Forms-A */ +#define TT_UCR_ARABIC_PRESENTATIONS_A (1L << 31) /* U+FB50-U+FDFF */ + /* Bit 64 Combining Half Marks */ +#define TT_UCR_COMBINING_HALF_MARKS (1L << 0) /* U+FE20-U+FE2F */ + /* Bit 65 Vertical forms */ + /* CJK Compatibility Forms */ +#define TT_UCR_CJK_COMPATIBILITY_FORMS (1L << 1) /* U+FE10-U+FE1F */ + /* U+FE30-U+FE4F */ + /* Bit 66 Small Form Variants */ +#define TT_UCR_SMALL_FORM_VARIANTS (1L << 2) /* U+FE50-U+FE6F */ + /* Bit 67 Arabic Presentation Forms-B */ +#define TT_UCR_ARABIC_PRESENTATIONS_B (1L << 3) /* U+FE70-U+FEFE */ + /* Bit 68 Halfwidth and Fullwidth Forms */ +#define TT_UCR_HALFWIDTH_FULLWIDTH_FORMS (1L << 4) /* U+FF00-U+FFEF */ + /* Bit 69 Specials */ +#define TT_UCR_SPECIALS (1L << 5) /* U+FFF0-U+FFFD */ + /* Bit 70 Tibetan */ +#define TT_UCR_TIBETAN (1L << 6) /* U+0F00-U+0FFF */ + /* Bit 71 Syriac */ +#define TT_UCR_SYRIAC (1L << 7) /* U+0700-U+074F */ + /* Bit 72 Thaana */ +#define TT_UCR_THAANA (1L << 8) /* U+0780-U+07BF */ + /* Bit 73 Sinhala */ +#define TT_UCR_SINHALA (1L << 9) /* U+0D80-U+0DFF */ + /* Bit 74 Myanmar */ +#define TT_UCR_MYANMAR (1L << 10) /* U+1000-U+109F */ + /* Bit 75 Ethiopic */ + /* Ethiopic Supplement */ + /* Ethiopic Extended */ +#define TT_UCR_ETHIOPIC (1L << 11) /* U+1200-U+137F */ + /* U+1380-U+139F */ + /* U+2D80-U+2DDF */ + /* Bit 76 Cherokee */ +#define TT_UCR_CHEROKEE (1L << 12) /* U+13A0-U+13FF */ + /* Bit 77 Unified Canadian Aboriginal Syllabics */ +#define TT_UCR_CANADIAN_ABORIGINAL_SYLLABICS (1L << 13) /* U+1400-U+167F */ + /* Bit 78 Ogham */ +#define TT_UCR_OGHAM (1L << 14) /* U+1680-U+169F */ + /* Bit 79 Runic */ +#define TT_UCR_RUNIC (1L << 15) /* U+16A0-U+16FF */ + /* Bit 80 Khmer */ + /* Khmer Symbols */ +#define TT_UCR_KHMER (1L << 16) /* U+1780-U+17FF */ + /* U+19E0-U+19FF */ + /* Bit 81 Mongolian */ +#define TT_UCR_MONGOLIAN (1L << 17) /* U+1800-U+18AF */ + /* Bit 82 Braille Patterns */ +#define TT_UCR_BRAILLE (1L << 18) /* U+2800-U+28FF */ + /* Bit 83 Yi Syllables */ + /* Yi Radicals */ +#define TT_UCR_YI (1L << 19) /* U+A000-U+A48F */ + /* U+A490-U+A4CF */ + /* Bit 84 Tagalog */ + /* Hanunoo */ + /* Buhid */ + /* Tagbanwa */ +#define TT_UCR_PHILIPPINE (1L << 20) /* U+1700-U+171F */ + /* U+1720-U+173F */ + /* U+1740-U+175F */ + /* U+1760-U+177F */ + /* Bit 85 Old Italic */ +#define TT_UCR_OLD_ITALIC (1L << 21) /*U+10300-U+1032F*/ + /* Bit 86 Gothic */ +#define TT_UCR_GOTHIC (1L << 22) /*U+10330-U+1034F*/ + /* Bit 87 Deseret */ +#define TT_UCR_DESERET (1L << 23) /*U+10400-U+1044F*/ + /* Bit 88 Byzantine Musical Symbols */ + /* Musical Symbols */ + /* Ancient Greek Musical Notation */ +#define TT_UCR_MUSICAL_SYMBOLS (1L << 24) /*U+1D000-U+1D0FF*/ + /*U+1D100-U+1D1FF*/ + /*U+1D200-U+1D24F*/ + /* Bit 89 Mathematical Alphanumeric Symbols */ +#define TT_UCR_MATH_ALPHANUMERIC_SYMBOLS (1L << 25) /*U+1D400-U+1D7FF*/ + /* Bit 90 Private Use (plane 15) */ + /* Private Use (plane 16) */ +#define TT_UCR_PRIVATE_USE_SUPPLEMENTARY (1L << 26) /*U+F0000-U+FFFFD*/ + /*U+100000-U+10FFFD*/ + /* Bit 91 Variation Selectors */ + /* Variation Selectors Supplement */ +#define TT_UCR_VARIATION_SELECTORS (1L << 27) /* U+FE00-U+FE0F */ + /*U+E0100-U+E01EF*/ + /* Bit 92 Tags */ +#define TT_UCR_TAGS (1L << 28) /*U+E0000-U+E007F*/ + /* Bit 93 Limbu */ +#define TT_UCR_LIMBU (1L << 29) /* U+1900-U+194F */ + /* Bit 94 Tai Le */ +#define TT_UCR_TAI_LE (1L << 30) /* U+1950-U+197F */ + /* Bit 95 New Tai Lue */ +#define TT_UCR_NEW_TAI_LUE (1L << 31) /* U+1980-U+19DF */ + /* Bit 96 Buginese */ +#define TT_UCR_BUGINESE (1L << 0) /* U+1A00-U+1A1F */ + /* Bit 97 Glagolitic */ +#define TT_UCR_GLAGOLITIC (1L << 1) /* U+2C00-U+2C5F */ + /* Bit 98 Tifinagh */ +#define TT_UCR_TIFINAGH (1L << 2) /* U+2D30-U+2D7F */ + /* Bit 99 Yijing Hexagram Symbols */ +#define TT_UCR_YIJING (1L << 3) /* U+4DC0-U+4DFF */ + /* Bit 100 Syloti Nagri */ +#define TT_UCR_SYLOTI_NAGRI (1L << 4) /* U+A800-U+A82F */ + /* Bit 101 Linear B Syllabary */ + /* Linear B Ideograms */ + /* Aegean Numbers */ +#define TT_UCR_LINEAR_B (1L << 5) /*U+10000-U+1007F*/ + /*U+10080-U+100FF*/ + /*U+10100-U+1013F*/ + /* Bit 102 Ancient Greek Numbers */ +#define TT_UCR_ANCIENT_GREEK_NUMBERS (1L << 6) /*U+10140-U+1018F*/ + /* Bit 103 Ugaritic */ +#define TT_UCR_UGARITIC (1L << 7) /*U+10380-U+1039F*/ + /* Bit 104 Old Persian */ +#define TT_UCR_OLD_PERSIAN (1L << 8) /*U+103A0-U+103DF*/ + /* Bit 105 Shavian */ +#define TT_UCR_SHAVIAN (1L << 9) /*U+10450-U+1047F*/ + /* Bit 106 Osmanya */ +#define TT_UCR_OSMANYA (1L << 10) /*U+10480-U+104AF*/ + /* Bit 107 Cypriot Syllabary */ +#define TT_UCR_CYPRIOT_SYLLABARY (1L << 11) /*U+10800-U+1083F*/ + /* Bit 108 Kharoshthi */ +#define TT_UCR_KHAROSHTHI (1L << 12) /*U+10A00-U+10A5F*/ + /* Bit 109 Tai Xuan Jing Symbols */ +#define TT_UCR_TAI_XUAN_JING (1L << 13) /*U+1D300-U+1D35F*/ + /* Bit 110 Cuneiform */ + /* Cuneiform Numbers and Punctuation */ +#define TT_UCR_CUNEIFORM (1L << 14) /*U+12000-U+123FF*/ + /*U+12400-U+1247F*/ + /* Bit 111 Counting Rod Numerals */ +#define TT_UCR_COUNTING_ROD_NUMERALS (1L << 15) /*U+1D360-U+1D37F*/ + /* Bit 112 Sundanese */ +#define TT_UCR_SUNDANESE (1L << 16) /* U+1B80-U+1BBF */ + /* Bit 113 Lepcha */ +#define TT_UCR_LEPCHA (1L << 17) /* U+1C00-U+1C4F */ + /* Bit 114 Ol Chiki */ +#define TT_UCR_OL_CHIKI (1L << 18) /* U+1C50-U+1C7F */ + /* Bit 115 Saurashtra */ +#define TT_UCR_SAURASHTRA (1L << 19) /* U+A880-U+A8DF */ + /* Bit 116 Kayah Li */ +#define TT_UCR_KAYAH_LI (1L << 20) /* U+A900-U+A92F */ + /* Bit 117 Rejang */ +#define TT_UCR_REJANG (1L << 21) /* U+A930-U+A95F */ + /* Bit 118 Cham */ +#define TT_UCR_CHAM (1L << 22) /* U+AA00-U+AA5F */ + /* Bit 119 Ancient Symbols */ +#define TT_UCR_ANCIENT_SYMBOLS (1L << 23) /*U+10190-U+101CF*/ + /* Bit 120 Phaistos Disc */ +#define TT_UCR_PHAISTOS_DISC (1L << 24) /*U+101D0-U+101FF*/ + /* Bit 121 Carian */ + /* Lycian */ + /* Lydian */ +#define TT_UCR_OLD_ANATOLIAN (1L << 25) /*U+102A0-U+102DF*/ + /*U+10280-U+1029F*/ + /*U+10920-U+1093F*/ + /* Bit 122 Domino Tiles */ + /* Mahjong Tiles */ +#define TT_UCR_GAME_TILES (1L << 26) /*U+1F030-U+1F09F*/ + /*U+1F000-U+1F02F*/ + /* Bit 123-127 Reserved for process-internal usage */ + + + /*************************************************************************/ + /* */ + /* Some compilers have a very limited length of identifiers. */ + /* */ +#if defined( __TURBOC__ ) && __TURBOC__ < 0x0410 || defined( __PACIFIC__ ) +#define HAVE_LIMIT_ON_IDENTS +#endif + + +#ifndef HAVE_LIMIT_ON_IDENTS + + + /*************************************************************************/ + /* */ + /* Here some alias #defines in order to be clearer. */ + /* */ + /* These are not always #defined to stay within the 31~character limit */ + /* which some compilers have. */ + /* */ + /* Credits go to Dave Hoo <dhoo@flash.net> for pointing out that modern */ + /* Borland compilers (read: from BC++ 3.1 on) can increase this limit. */ + /* If you get a warning with such a compiler, use the -i40 switch. */ + /* */ +#define TT_UCR_ARABIC_PRESENTATION_FORMS_A \ + TT_UCR_ARABIC_PRESENTATIONS_A +#define TT_UCR_ARABIC_PRESENTATION_FORMS_B \ + TT_UCR_ARABIC_PRESENTATIONS_B + +#define TT_UCR_COMBINING_DIACRITICAL_MARKS \ + TT_UCR_COMBINING_DIACRITICS +#define TT_UCR_COMBINING_DIACRITICAL_MARKS_SYMB \ + TT_UCR_COMBINING_DIACRITICS_SYMB + + +#endif /* !HAVE_LIMIT_ON_IDENTS */ + + +FT_END_HEADER + +#endif /* __TTNAMEID_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/tttables.h b/other/freetype/include/freetype/tttables.h new file mode 100644 index 0000000..02236c2 --- /dev/null +++ b/other/freetype/include/freetype/tttables.h @@ -0,0 +1,763 @@ +/***************************************************************************/ +/* */ +/* tttables.h */ +/* */ +/* Basic SFNT/TrueType tables definitions and interface */ +/* (specification only). */ +/* */ +/* Copyright 1996-2005, 2008-2011 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __TTTABLES_H__ +#define __TTTABLES_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + /*************************************************************************/ + /* */ + /* <Section> */ + /* truetype_tables */ + /* */ + /* <Title> */ + /* TrueType Tables */ + /* */ + /* <Abstract> */ + /* TrueType specific table types and functions. */ + /* */ + /* <Description> */ + /* This section contains the definition of TrueType-specific tables */ + /* as well as some routines used to access and process them. */ + /* */ + /*************************************************************************/ + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Header */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType font header table. All */ + /* fields follow the TrueType specification. */ + /* */ + typedef struct TT_Header_ + { + FT_Fixed Table_Version; + FT_Fixed Font_Revision; + + FT_Long CheckSum_Adjust; + FT_Long Magic_Number; + + FT_UShort Flags; + FT_UShort Units_Per_EM; + + FT_Long Created [2]; + FT_Long Modified[2]; + + FT_Short xMin; + FT_Short yMin; + FT_Short xMax; + FT_Short yMax; + + FT_UShort Mac_Style; + FT_UShort Lowest_Rec_PPEM; + + FT_Short Font_Direction; + FT_Short Index_To_Loc_Format; + FT_Short Glyph_Data_Format; + + } TT_Header; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_HoriHeader */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType horizontal header, the `hhea' */ + /* table, as well as the corresponding horizontal metrics table, */ + /* i.e., the `hmtx' table. */ + /* */ + /* <Fields> */ + /* Version :: The table version. */ + /* */ + /* Ascender :: The font's ascender, i.e., the distance */ + /* from the baseline to the top-most of all */ + /* glyph points found in the font. */ + /* */ + /* This value is invalid in many fonts, as */ + /* it is usually set by the font designer, */ + /* and often reflects only a portion of the */ + /* glyphs found in the font (maybe ASCII). */ + /* */ + /* You should use the `sTypoAscender' field */ + /* of the OS/2 table instead if you want */ + /* the correct one. */ + /* */ + /* Descender :: The font's descender, i.e., the distance */ + /* from the baseline to the bottom-most of */ + /* all glyph points found in the font. It */ + /* is negative. */ + /* */ + /* This value is invalid in many fonts, as */ + /* it is usually set by the font designer, */ + /* and often reflects only a portion of the */ + /* glyphs found in the font (maybe ASCII). */ + /* */ + /* You should use the `sTypoDescender' */ + /* field of the OS/2 table instead if you */ + /* want the correct one. */ + /* */ + /* Line_Gap :: The font's line gap, i.e., the distance */ + /* to add to the ascender and descender to */ + /* get the BTB, i.e., the */ + /* baseline-to-baseline distance for the */ + /* font. */ + /* */ + /* advance_Width_Max :: This field is the maximum of all advance */ + /* widths found in the font. It can be */ + /* used to compute the maximum width of an */ + /* arbitrary string of text. */ + /* */ + /* min_Left_Side_Bearing :: The minimum left side bearing of all */ + /* glyphs within the font. */ + /* */ + /* min_Right_Side_Bearing :: The minimum right side bearing of all */ + /* glyphs within the font. */ + /* */ + /* xMax_Extent :: The maximum horizontal extent (i.e., the */ + /* `width' of a glyph's bounding box) for */ + /* all glyphs in the font. */ + /* */ + /* caret_Slope_Rise :: The rise coefficient of the cursor's */ + /* slope of the cursor (slope=rise/run). */ + /* */ + /* caret_Slope_Run :: The run coefficient of the cursor's */ + /* slope. */ + /* */ + /* Reserved :: 8~reserved bytes. */ + /* */ + /* metric_Data_Format :: Always~0. */ + /* */ + /* number_Of_HMetrics :: Number of HMetrics entries in the `hmtx' */ + /* table -- this value can be smaller than */ + /* the total number of glyphs in the font. */ + /* */ + /* long_metrics :: A pointer into the `hmtx' table. */ + /* */ + /* short_metrics :: A pointer into the `hmtx' table. */ + /* */ + /* <Note> */ + /* IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should */ + /* be identical except for the names of their fields which */ + /* are different. */ + /* */ + /* This ensures that a single function in the `ttload' */ + /* module is able to read both the horizontal and vertical */ + /* headers. */ + /* */ + typedef struct TT_HoriHeader_ + { + FT_Fixed Version; + FT_Short Ascender; + FT_Short Descender; + FT_Short Line_Gap; + + FT_UShort advance_Width_Max; /* advance width maximum */ + + FT_Short min_Left_Side_Bearing; /* minimum left-sb */ + FT_Short min_Right_Side_Bearing; /* minimum right-sb */ + FT_Short xMax_Extent; /* xmax extents */ + FT_Short caret_Slope_Rise; + FT_Short caret_Slope_Run; + FT_Short caret_Offset; + + FT_Short Reserved[4]; + + FT_Short metric_Data_Format; + FT_UShort number_Of_HMetrics; + + /* The following fields are not defined by the TrueType specification */ + /* but they are used to connect the metrics header to the relevant */ + /* `HMTX' table. */ + + void* long_metrics; + void* short_metrics; + + } TT_HoriHeader; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_VertHeader */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType vertical header, the `vhea' */ + /* table, as well as the corresponding vertical metrics table, i.e., */ + /* the `vmtx' table. */ + /* */ + /* <Fields> */ + /* Version :: The table version. */ + /* */ + /* Ascender :: The font's ascender, i.e., the distance */ + /* from the baseline to the top-most of */ + /* all glyph points found in the font. */ + /* */ + /* This value is invalid in many fonts, as */ + /* it is usually set by the font designer, */ + /* and often reflects only a portion of */ + /* the glyphs found in the font (maybe */ + /* ASCII). */ + /* */ + /* You should use the `sTypoAscender' */ + /* field of the OS/2 table instead if you */ + /* want the correct one. */ + /* */ + /* Descender :: The font's descender, i.e., the */ + /* distance from the baseline to the */ + /* bottom-most of all glyph points found */ + /* in the font. It is negative. */ + /* */ + /* This value is invalid in many fonts, as */ + /* it is usually set by the font designer, */ + /* and often reflects only a portion of */ + /* the glyphs found in the font (maybe */ + /* ASCII). */ + /* */ + /* You should use the `sTypoDescender' */ + /* field of the OS/2 table instead if you */ + /* want the correct one. */ + /* */ + /* Line_Gap :: The font's line gap, i.e., the distance */ + /* to add to the ascender and descender to */ + /* get the BTB, i.e., the */ + /* baseline-to-baseline distance for the */ + /* font. */ + /* */ + /* advance_Height_Max :: This field is the maximum of all */ + /* advance heights found in the font. It */ + /* can be used to compute the maximum */ + /* height of an arbitrary string of text. */ + /* */ + /* min_Top_Side_Bearing :: The minimum top side bearing of all */ + /* glyphs within the font. */ + /* */ + /* min_Bottom_Side_Bearing :: The minimum bottom side bearing of all */ + /* glyphs within the font. */ + /* */ + /* yMax_Extent :: The maximum vertical extent (i.e., the */ + /* `height' of a glyph's bounding box) for */ + /* all glyphs in the font. */ + /* */ + /* caret_Slope_Rise :: The rise coefficient of the cursor's */ + /* slope of the cursor (slope=rise/run). */ + /* */ + /* caret_Slope_Run :: The run coefficient of the cursor's */ + /* slope. */ + /* */ + /* caret_Offset :: The cursor's offset for slanted fonts. */ + /* This value is `reserved' in vmtx */ + /* version 1.0. */ + /* */ + /* Reserved :: 8~reserved bytes. */ + /* */ + /* metric_Data_Format :: Always~0. */ + /* */ + /* number_Of_HMetrics :: Number of VMetrics entries in the */ + /* `vmtx' table -- this value can be */ + /* smaller than the total number of glyphs */ + /* in the font. */ + /* */ + /* long_metrics :: A pointer into the `vmtx' table. */ + /* */ + /* short_metrics :: A pointer into the `vmtx' table. */ + /* */ + /* <Note> */ + /* IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should */ + /* be identical except for the names of their fields which */ + /* are different. */ + /* */ + /* This ensures that a single function in the `ttload' */ + /* module is able to read both the horizontal and vertical */ + /* headers. */ + /* */ + typedef struct TT_VertHeader_ + { + FT_Fixed Version; + FT_Short Ascender; + FT_Short Descender; + FT_Short Line_Gap; + + FT_UShort advance_Height_Max; /* advance height maximum */ + + FT_Short min_Top_Side_Bearing; /* minimum left-sb or top-sb */ + FT_Short min_Bottom_Side_Bearing; /* minimum right-sb or bottom-sb */ + FT_Short yMax_Extent; /* xmax or ymax extents */ + FT_Short caret_Slope_Rise; + FT_Short caret_Slope_Run; + FT_Short caret_Offset; + + FT_Short Reserved[4]; + + FT_Short metric_Data_Format; + FT_UShort number_Of_VMetrics; + + /* The following fields are not defined by the TrueType specification */ + /* but they're used to connect the metrics header to the relevant */ + /* `HMTX' or `VMTX' table. */ + + void* long_metrics; + void* short_metrics; + + } TT_VertHeader; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_OS2 */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType OS/2 table. This is the long */ + /* table version. All fields comply to the TrueType specification. */ + /* */ + /* Note that we now support old Mac fonts which do not include an */ + /* OS/2 table. In this case, the `version' field is always set to */ + /* 0xFFFF. */ + /* */ + typedef struct TT_OS2_ + { + FT_UShort version; /* 0x0001 - more or 0xFFFF */ + FT_Short xAvgCharWidth; + FT_UShort usWeightClass; + FT_UShort usWidthClass; + FT_Short fsType; + FT_Short ySubscriptXSize; + FT_Short ySubscriptYSize; + FT_Short ySubscriptXOffset; + FT_Short ySubscriptYOffset; + FT_Short ySuperscriptXSize; + FT_Short ySuperscriptYSize; + FT_Short ySuperscriptXOffset; + FT_Short ySuperscriptYOffset; + FT_Short yStrikeoutSize; + FT_Short yStrikeoutPosition; + FT_Short sFamilyClass; + + FT_Byte panose[10]; + + FT_ULong ulUnicodeRange1; /* Bits 0-31 */ + FT_ULong ulUnicodeRange2; /* Bits 32-63 */ + FT_ULong ulUnicodeRange3; /* Bits 64-95 */ + FT_ULong ulUnicodeRange4; /* Bits 96-127 */ + + FT_Char achVendID[4]; + + FT_UShort fsSelection; + FT_UShort usFirstCharIndex; + FT_UShort usLastCharIndex; + FT_Short sTypoAscender; + FT_Short sTypoDescender; + FT_Short sTypoLineGap; + FT_UShort usWinAscent; + FT_UShort usWinDescent; + + /* only version 1 tables: */ + + FT_ULong ulCodePageRange1; /* Bits 0-31 */ + FT_ULong ulCodePageRange2; /* Bits 32-63 */ + + /* only version 2 tables: */ + + FT_Short sxHeight; + FT_Short sCapHeight; + FT_UShort usDefaultChar; + FT_UShort usBreakChar; + FT_UShort usMaxContext; + + } TT_OS2; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_Postscript */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType PostScript table. All fields */ + /* comply to the TrueType specification. This structure does not */ + /* reference the PostScript glyph names, which can be nevertheless */ + /* accessed with the `ttpost' module. */ + /* */ + typedef struct TT_Postscript_ + { + FT_Fixed FormatType; + FT_Fixed italicAngle; + FT_Short underlinePosition; + FT_Short underlineThickness; + FT_ULong isFixedPitch; + FT_ULong minMemType42; + FT_ULong maxMemType42; + FT_ULong minMemType1; + FT_ULong maxMemType1; + + /* Glyph names follow in the file, but we don't */ + /* load them by default. See the ttpost.c file. */ + + } TT_Postscript; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_PCLT */ + /* */ + /* <Description> */ + /* A structure used to model a TrueType PCLT table. All fields */ + /* comply to the TrueType specification. */ + /* */ + typedef struct TT_PCLT_ + { + FT_Fixed Version; + FT_ULong FontNumber; + FT_UShort Pitch; + FT_UShort xHeight; + FT_UShort Style; + FT_UShort TypeFamily; + FT_UShort CapHeight; + FT_UShort SymbolSet; + FT_Char TypeFace[16]; + FT_Char CharacterComplement[8]; + FT_Char FileName[6]; + FT_Char StrokeWeight; + FT_Char WidthType; + FT_Byte SerifStyle; + FT_Byte Reserved; + + } TT_PCLT; + + + /*************************************************************************/ + /* */ + /* <Struct> */ + /* TT_MaxProfile */ + /* */ + /* <Description> */ + /* The maximum profile is a table containing many max values which */ + /* can be used to pre-allocate arrays. This ensures that no memory */ + /* allocation occurs during a glyph load. */ + /* */ + /* <Fields> */ + /* version :: The version number. */ + /* */ + /* numGlyphs :: The number of glyphs in this TrueType */ + /* font. */ + /* */ + /* maxPoints :: The maximum number of points in a */ + /* non-composite TrueType glyph. See also */ + /* the structure element */ + /* `maxCompositePoints'. */ + /* */ + /* maxContours :: The maximum number of contours in a */ + /* non-composite TrueType glyph. See also */ + /* the structure element */ + /* `maxCompositeContours'. */ + /* */ + /* maxCompositePoints :: The maximum number of points in a */ + /* composite TrueType glyph. See also the */ + /* structure element `maxPoints'. */ + /* */ + /* maxCompositeContours :: The maximum number of contours in a */ + /* composite TrueType glyph. See also the */ + /* structure element `maxContours'. */ + /* */ + /* maxZones :: The maximum number of zones used for */ + /* glyph hinting. */ + /* */ + /* maxTwilightPoints :: The maximum number of points in the */ + /* twilight zone used for glyph hinting. */ + /* */ + /* maxStorage :: The maximum number of elements in the */ + /* storage area used for glyph hinting. */ + /* */ + /* maxFunctionDefs :: The maximum number of function */ + /* definitions in the TrueType bytecode for */ + /* this font. */ + /* */ + /* maxInstructionDefs :: The maximum number of instruction */ + /* definitions in the TrueType bytecode for */ + /* this font. */ + /* */ + /* maxStackElements :: The maximum number of stack elements used */ + /* during bytecode interpretation. */ + /* */ + /* maxSizeOfInstructions :: The maximum number of TrueType opcodes */ + /* used for glyph hinting. */ + /* */ + /* maxComponentElements :: The maximum number of simple (i.e., non- */ + /* composite) glyphs in a composite glyph. */ + /* */ + /* maxComponentDepth :: The maximum nesting depth of composite */ + /* glyphs. */ + /* */ + /* <Note> */ + /* This structure is only used during font loading. */ + /* */ + typedef struct TT_MaxProfile_ + { + FT_Fixed version; + FT_UShort numGlyphs; + FT_UShort maxPoints; + FT_UShort maxContours; + FT_UShort maxCompositePoints; + FT_UShort maxCompositeContours; + FT_UShort maxZones; + FT_UShort maxTwilightPoints; + FT_UShort maxStorage; + FT_UShort maxFunctionDefs; + FT_UShort maxInstructionDefs; + FT_UShort maxStackElements; + FT_UShort maxSizeOfInstructions; + FT_UShort maxComponentElements; + FT_UShort maxComponentDepth; + + } TT_MaxProfile; + + + /*************************************************************************/ + /* */ + /* <Enum> */ + /* FT_Sfnt_Tag */ + /* */ + /* <Description> */ + /* An enumeration used to specify the index of an SFNT table. */ + /* Used in the @FT_Get_Sfnt_Table API function. */ + /* */ + typedef enum FT_Sfnt_Tag_ + { + ft_sfnt_head = 0, /* TT_Header */ + ft_sfnt_maxp = 1, /* TT_MaxProfile */ + ft_sfnt_os2 = 2, /* TT_OS2 */ + ft_sfnt_hhea = 3, /* TT_HoriHeader */ + ft_sfnt_vhea = 4, /* TT_VertHeader */ + ft_sfnt_post = 5, /* TT_Postscript */ + ft_sfnt_pclt = 6, /* TT_PCLT */ + + sfnt_max /* internal end mark */ + + } FT_Sfnt_Tag; + + /* */ + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_Sfnt_Table */ + /* */ + /* <Description> */ + /* Return a pointer to a given SFNT table within a face. */ + /* */ + /* <Input> */ + /* face :: A handle to the source. */ + /* */ + /* tag :: The index of the SFNT table. */ + /* */ + /* <Return> */ + /* A type-less pointer to the table. This will be~0 in case of */ + /* error, or if the corresponding table was not found *OR* loaded */ + /* from the file. */ + /* */ + /* Use a typecast according to `tag' to access the structure */ + /* elements. */ + /* */ + /* <Note> */ + /* The table is owned by the face object and disappears with it. */ + /* */ + /* This function is only useful to access SFNT tables that are loaded */ + /* by the sfnt, truetype, and opentype drivers. See @FT_Sfnt_Tag for */ + /* a list. */ + /* */ + FT_EXPORT( void* ) + FT_Get_Sfnt_Table( FT_Face face, + FT_Sfnt_Tag tag ); + + + /************************************************************************** + * + * @function: + * FT_Load_Sfnt_Table + * + * @description: + * Load any font table into client memory. + * + * @input: + * face :: + * A handle to the source face. + * + * tag :: + * The four-byte tag of the table to load. Use the value~0 if you want + * to access the whole font file. Otherwise, you can use one of the + * definitions found in the @FT_TRUETYPE_TAGS_H file, or forge a new + * one with @FT_MAKE_TAG. + * + * offset :: + * The starting offset in the table (or file if tag == 0). + * + * @output: + * buffer :: + * The target buffer address. The client must ensure that the memory + * array is big enough to hold the data. + * + * @inout: + * length :: + * If the `length' parameter is NULL, then try to load the whole table. + * Return an error code if it fails. + * + * Else, if `*length' is~0, exit immediately while returning the + * table's (or file) full size in it. + * + * Else the number of bytes to read from the table or file, from the + * starting offset. + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * If you need to determine the table's length you should first call this + * function with `*length' set to~0, as in the following example: + * + * { + * FT_ULong length = 0; + * + * + * error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &length ); + * if ( error ) { ... table does not exist ... } + * + * buffer = malloc( length ); + * if ( buffer == NULL ) { ... not enough memory ... } + * + * error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &length ); + * if ( error ) { ... could not load table ... } + * } + */ + FT_EXPORT( FT_Error ) + FT_Load_Sfnt_Table( FT_Face face, + FT_ULong tag, + FT_Long offset, + FT_Byte* buffer, + FT_ULong* length ); + + + /************************************************************************** + * + * @function: + * FT_Sfnt_Table_Info + * + * @description: + * Return information on an SFNT table. + * + * @input: + * face :: + * A handle to the source face. + * + * table_index :: + * The index of an SFNT table. The function returns + * FT_Err_Table_Missing for an invalid value. + * + * @inout: + * tag :: + * The name tag of the SFNT table. If the value is NULL, `table_index' + * is ignored, and `length' returns the number of SFNT tables in the + * font. + * + * @output: + * length :: + * The length of the SFNT table (or the number of SFNT tables, depending + * on `tag'). + * + * @return: + * FreeType error code. 0~means success. + * + * @note: + * SFNT tables with length zero are treated as missing. + * + */ + FT_EXPORT( FT_Error ) + FT_Sfnt_Table_Info( FT_Face face, + FT_UInt table_index, + FT_ULong *tag, + FT_ULong *length ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_CMap_Language_ID */ + /* */ + /* <Description> */ + /* Return TrueType/sfnt specific cmap language ID. Definitions of */ + /* language ID values are in `freetype/ttnameid.h'. */ + /* */ + /* <Input> */ + /* charmap :: */ + /* The target charmap. */ + /* */ + /* <Return> */ + /* The language ID of `charmap'. If `charmap' doesn't belong to a */ + /* TrueType/sfnt face, just return~0 as the default value. */ + /* */ + FT_EXPORT( FT_ULong ) + FT_Get_CMap_Language_ID( FT_CharMap charmap ); + + + /*************************************************************************/ + /* */ + /* <Function> */ + /* FT_Get_CMap_Format */ + /* */ + /* <Description> */ + /* Return TrueType/sfnt specific cmap format. */ + /* */ + /* <Input> */ + /* charmap :: */ + /* The target charmap. */ + /* */ + /* <Return> */ + /* The format of `charmap'. If `charmap' doesn't belong to a */ + /* TrueType/sfnt face, return -1. */ + /* */ + FT_EXPORT( FT_Long ) + FT_Get_CMap_Format( FT_CharMap charmap ); + + /* */ + + +FT_END_HEADER + +#endif /* __TTTABLES_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/tttags.h b/other/freetype/include/freetype/tttags.h new file mode 100644 index 0000000..307ce4b --- /dev/null +++ b/other/freetype/include/freetype/tttags.h @@ -0,0 +1,107 @@ +/***************************************************************************/ +/* */ +/* tttags.h */ +/* */ +/* Tags for TrueType and OpenType tables (specification only). */ +/* */ +/* Copyright 1996-2001, 2004, 2005, 2007, 2008 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __TTAGS_H__ +#define __TTAGS_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + +#define TTAG_avar FT_MAKE_TAG( 'a', 'v', 'a', 'r' ) +#define TTAG_BASE FT_MAKE_TAG( 'B', 'A', 'S', 'E' ) +#define TTAG_bdat FT_MAKE_TAG( 'b', 'd', 'a', 't' ) +#define TTAG_BDF FT_MAKE_TAG( 'B', 'D', 'F', ' ' ) +#define TTAG_bhed FT_MAKE_TAG( 'b', 'h', 'e', 'd' ) +#define TTAG_bloc FT_MAKE_TAG( 'b', 'l', 'o', 'c' ) +#define TTAG_bsln FT_MAKE_TAG( 'b', 's', 'l', 'n' ) +#define TTAG_CFF FT_MAKE_TAG( 'C', 'F', 'F', ' ' ) +#define TTAG_CID FT_MAKE_TAG( 'C', 'I', 'D', ' ' ) +#define TTAG_cmap FT_MAKE_TAG( 'c', 'm', 'a', 'p' ) +#define TTAG_cvar FT_MAKE_TAG( 'c', 'v', 'a', 'r' ) +#define TTAG_cvt FT_MAKE_TAG( 'c', 'v', 't', ' ' ) +#define TTAG_DSIG FT_MAKE_TAG( 'D', 'S', 'I', 'G' ) +#define TTAG_EBDT FT_MAKE_TAG( 'E', 'B', 'D', 'T' ) +#define TTAG_EBLC FT_MAKE_TAG( 'E', 'B', 'L', 'C' ) +#define TTAG_EBSC FT_MAKE_TAG( 'E', 'B', 'S', 'C' ) +#define TTAG_feat FT_MAKE_TAG( 'f', 'e', 'a', 't' ) +#define TTAG_FOND FT_MAKE_TAG( 'F', 'O', 'N', 'D' ) +#define TTAG_fpgm FT_MAKE_TAG( 'f', 'p', 'g', 'm' ) +#define TTAG_fvar FT_MAKE_TAG( 'f', 'v', 'a', 'r' ) +#define TTAG_gasp FT_MAKE_TAG( 'g', 'a', 's', 'p' ) +#define TTAG_GDEF FT_MAKE_TAG( 'G', 'D', 'E', 'F' ) +#define TTAG_glyf FT_MAKE_TAG( 'g', 'l', 'y', 'f' ) +#define TTAG_GPOS FT_MAKE_TAG( 'G', 'P', 'O', 'S' ) +#define TTAG_GSUB FT_MAKE_TAG( 'G', 'S', 'U', 'B' ) +#define TTAG_gvar FT_MAKE_TAG( 'g', 'v', 'a', 'r' ) +#define TTAG_hdmx FT_MAKE_TAG( 'h', 'd', 'm', 'x' ) +#define TTAG_head FT_MAKE_TAG( 'h', 'e', 'a', 'd' ) +#define TTAG_hhea FT_MAKE_TAG( 'h', 'h', 'e', 'a' ) +#define TTAG_hmtx FT_MAKE_TAG( 'h', 'm', 't', 'x' ) +#define TTAG_JSTF FT_MAKE_TAG( 'J', 'S', 'T', 'F' ) +#define TTAG_just FT_MAKE_TAG( 'j', 'u', 's', 't' ) +#define TTAG_kern FT_MAKE_TAG( 'k', 'e', 'r', 'n' ) +#define TTAG_lcar FT_MAKE_TAG( 'l', 'c', 'a', 'r' ) +#define TTAG_loca FT_MAKE_TAG( 'l', 'o', 'c', 'a' ) +#define TTAG_LTSH FT_MAKE_TAG( 'L', 'T', 'S', 'H' ) +#define TTAG_LWFN FT_MAKE_TAG( 'L', 'W', 'F', 'N' ) +#define TTAG_MATH FT_MAKE_TAG( 'M', 'A', 'T', 'H' ) +#define TTAG_maxp FT_MAKE_TAG( 'm', 'a', 'x', 'p' ) +#define TTAG_META FT_MAKE_TAG( 'M', 'E', 'T', 'A' ) +#define TTAG_MMFX FT_MAKE_TAG( 'M', 'M', 'F', 'X' ) +#define TTAG_MMSD FT_MAKE_TAG( 'M', 'M', 'S', 'D' ) +#define TTAG_mort FT_MAKE_TAG( 'm', 'o', 'r', 't' ) +#define TTAG_morx FT_MAKE_TAG( 'm', 'o', 'r', 'x' ) +#define TTAG_name FT_MAKE_TAG( 'n', 'a', 'm', 'e' ) +#define TTAG_opbd FT_MAKE_TAG( 'o', 'p', 'b', 'd' ) +#define TTAG_OS2 FT_MAKE_TAG( 'O', 'S', '/', '2' ) +#define TTAG_OTTO FT_MAKE_TAG( 'O', 'T', 'T', 'O' ) +#define TTAG_PCLT FT_MAKE_TAG( 'P', 'C', 'L', 'T' ) +#define TTAG_POST FT_MAKE_TAG( 'P', 'O', 'S', 'T' ) +#define TTAG_post FT_MAKE_TAG( 'p', 'o', 's', 't' ) +#define TTAG_prep FT_MAKE_TAG( 'p', 'r', 'e', 'p' ) +#define TTAG_prop FT_MAKE_TAG( 'p', 'r', 'o', 'p' ) +#define TTAG_sfnt FT_MAKE_TAG( 's', 'f', 'n', 't' ) +#define TTAG_SING FT_MAKE_TAG( 'S', 'I', 'N', 'G' ) +#define TTAG_trak FT_MAKE_TAG( 't', 'r', 'a', 'k' ) +#define TTAG_true FT_MAKE_TAG( 't', 'r', 'u', 'e' ) +#define TTAG_ttc FT_MAKE_TAG( 't', 't', 'c', ' ' ) +#define TTAG_ttcf FT_MAKE_TAG( 't', 't', 'c', 'f' ) +#define TTAG_TYP1 FT_MAKE_TAG( 'T', 'Y', 'P', '1' ) +#define TTAG_typ1 FT_MAKE_TAG( 't', 'y', 'p', '1' ) +#define TTAG_VDMX FT_MAKE_TAG( 'V', 'D', 'M', 'X' ) +#define TTAG_vhea FT_MAKE_TAG( 'v', 'h', 'e', 'a' ) +#define TTAG_vmtx FT_MAKE_TAG( 'v', 'm', 't', 'x' ) + + +FT_END_HEADER + +#endif /* __TTAGS_H__ */ + + +/* END */ diff --git a/other/freetype/include/freetype/ttunpat.h b/other/freetype/include/freetype/ttunpat.h new file mode 100644 index 0000000..a016275 --- /dev/null +++ b/other/freetype/include/freetype/ttunpat.h @@ -0,0 +1,59 @@ +/***************************************************************************/ +/* */ +/* ttunpat.h */ +/* */ +/* Definitions for the unpatented TrueType hinting system */ +/* */ +/* Copyright 2003, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* Written by Graham Asher <graham.asher@btinternet.com> */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#ifndef __TTUNPAT_H__ +#define __TTUNPAT_H__ + + +#include <ft2build.h> +#include FT_FREETYPE_H + +#ifdef FREETYPE_H +#error "freetype.h of FreeType 1 has been loaded!" +#error "Please fix the directory search order for header files" +#error "so that freetype.h of FreeType 2 is found first." +#endif + + +FT_BEGIN_HEADER + + + /*************************************************************************** + * + * @constant: + * FT_PARAM_TAG_UNPATENTED_HINTING + * + * @description: + * A constant used as the tag of an @FT_Parameter structure to indicate + * that unpatented methods only should be used by the TrueType bytecode + * interpreter for a typeface opened by @FT_Open_Face. + * + */ +#define FT_PARAM_TAG_UNPATENTED_HINTING FT_MAKE_TAG( 'u', 'n', 'p', 'a' ) + + /* */ + +FT_END_HEADER + + +#endif /* __TTUNPAT_H__ */ + + +/* END */ diff --git a/other/freetype/include/ft2build.h b/other/freetype/include/ft2build.h new file mode 100644 index 0000000..923d887 --- /dev/null +++ b/other/freetype/include/ft2build.h @@ -0,0 +1,39 @@ +/***************************************************************************/ +/* */ +/* ft2build.h */ +/* */ +/* FreeType 2 build and setup macros. */ +/* (Generic version) */ +/* */ +/* Copyright 1996-2001, 2006 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + + /*************************************************************************/ + /* */ + /* This file corresponds to the default `ft2build.h' file for */ + /* FreeType 2. It uses the `freetype' include root. */ + /* */ + /* Note that specific platforms might use a different configuration. */ + /* See builds/unix/ft2unix.h for an example. */ + /* */ + /*************************************************************************/ + + +#ifndef __FT2_BUILD_GENERIC_H__ +#define __FT2_BUILD_GENERIC_H__ + +#include <freetype/config/ftheader.h> + +#endif /* __FT2_BUILD_GENERIC_H__ */ + + +/* END */ diff --git a/other/freetype/lib64/freetype.lib b/other/freetype/lib64/freetype.lib new file mode 100644 index 0000000..9893e93 Binary files /dev/null and b/other/freetype/lib64/freetype.lib differ diff --git a/other/mysql/include/cppconn/build_config.h b/other/mysql/include/cppconn/build_config.h new file mode 100644 index 0000000..c2807ef --- /dev/null +++ b/other/mysql/include/cppconn/build_config.h @@ -0,0 +1,51 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_BUILD_CONFIG_H_ +#define _SQL_BUILD_CONFIG_H_ + +#ifndef CPPCONN_PUBLIC_FUNC + +#if defined(_WIN32) + // mysqlcppconn_EXPORTS is added by cmake and defined for dynamic lib build only + #ifdef mysqlcppconn_EXPORTS + #define CPPCONN_PUBLIC_FUNC __declspec(dllexport) + #else + // this is for static build + #ifdef CPPCONN_LIB_BUILD + #define CPPCONN_PUBLIC_FUNC + #else + // this is for clients using dynamic lib + #define CPPCONN_PUBLIC_FUNC __declspec(dllimport) + #endif + #endif +#else + #define CPPCONN_PUBLIC_FUNC +#endif + +#endif //#ifndef CPPCONN_PUBLIC_FUNC + +#endif //#ifndef _SQL_BUILD_CONFIG_H_ diff --git a/other/mysql/include/cppconn/config.h b/other/mysql/include/cppconn/config.h new file mode 100644 index 0000000..0bf9727 --- /dev/null +++ b/other/mysql/include/cppconn/config.h @@ -0,0 +1,110 @@ +/* + Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. + + The MySQL Connector/C++ is licensed under the terms of the GPLv2 + <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most + MySQL Connectors. There are special exceptions to the terms and + conditions of the GPL as it is applied to this software, see the + FLOSS License Exception + <http://www.mysql.com/about/legal/licensing/foss-exception.html>. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published + by the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +// libmysql defines HAVE_STRTOUL (on win), so we have to follow different pattern in definitions names +// to avoid annoying warnings. + +#define HAVE_FUNCTION_STRTOLD 1 +#define HAVE_FUNCTION_STRTOLL 1 +#define HAVE_FUNCTION_STRTOL 1 +#define HAVE_FUNCTION_STRTOULL 1 + +#define HAVE_FUNCTION_STRTOUL 1 + +#define HAVE_FUNCTION_STRTOIMAX 1 +#define HAVE_FUNCTION_STRTOUMAX 1 + +#define HAVE_STDINT_H 1 +#define HAVE_INTTYPES_H 1 + +#define HAVE_INT8_T 1 +#define HAVE_UINT8_T 1 +#define HAVE_INT16_T 1 +#define HAVE_UINT16_T 1 +#define HAVE_INT32_T 1 +#define HAVE_UINT32_T 1 +#define HAVE_INT32_T 1 +#define HAVE_UINT32_T 1 +#define HAVE_INT64_T 1 +#define HAVE_UINT64_T 1 +/* #undef HAVE_MS_INT8 */ +/* #undef HAVE_MS_UINT8 */ +/* #undef HAVE_MS_INT16 */ +/* #undef HAVE_MS_UINT16 */ +/* #undef HAVE_MS_INT32 */ +/* #undef HAVE_MS_UINT32 */ +/* #undef HAVE_MS_INT64 */ +/* #undef HAVE_MS_UINT64 */ + + +#ifdef HAVE_STDINT_H +#include <stdint.h> +#endif + +#ifdef HAVE_INTTYPES_H +#include <inttypes.h> +#endif + +#if defined(_WIN32) +#ifndef CPPCONN_DONT_TYPEDEF_MS_TYPES_TO_C99_TYPES + +#if _MSC_VER >= 1600 + +#include <stdint.h> + +#else + +#if !defined(HAVE_INT8_T) && defined(HAVE_MS_INT8) +typedef __int8 int8_t; +#endif + +#ifdef HAVE_MS_UINT8 +typedef unsigned __int8 uint8_t; +#endif +#ifdef HAVE_MS_INT16 +typedef __int16 int16_t; +#endif + +#ifdef HAVE_MS_UINT16 +typedef unsigned __int16 uint16_t; +#endif + +#ifdef HAVE_MS_INT32 +typedef __int32 int32_t; +#endif + +#ifdef HAVE_MS_UINT32 +typedef unsigned __int32 uint32_t; +#endif + +#ifdef HAVE_MS_INT64 +typedef __int64 int64_t; +#endif +#ifdef HAVE_MS_UINT64 +typedef unsigned __int64 uint64_t; +#endif + +#endif // _MSC_VER >= 1600 +#endif // CPPCONN_DONT_TYPEDEF_MS_TYPES_TO_C99_TYPES +#endif // _WIN32 diff --git a/other/mysql/include/cppconn/connection.h b/other/mysql/include/cppconn/connection.h new file mode 100644 index 0000000..426ebe3 --- /dev/null +++ b/other/mysql/include/cppconn/connection.h @@ -0,0 +1,157 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_CONNECTION_H_ +#define _SQL_CONNECTION_H_ + +#include <map> +#include <boost/variant.hpp> + +#include "build_config.h" +#include "warning.h" +#include "sqlstring.h" + +namespace sql +{ + + +typedef boost::variant<int, double, bool, sql::SQLString > ConnectPropertyVal; + +typedef std::map< sql::SQLString, ConnectPropertyVal > ConnectOptionsMap; + +class DatabaseMetaData; +class PreparedStatement; +class Statement; +class Driver; + +typedef enum transaction_isolation +{ + TRANSACTION_NONE= 0, + TRANSACTION_READ_COMMITTED, + TRANSACTION_READ_UNCOMMITTED, + TRANSACTION_REPEATABLE_READ, + TRANSACTION_SERIALIZABLE +} enum_transaction_isolation; + +class Savepoint +{ + /* Prevent use of these */ + Savepoint(const Savepoint &); + void operator=(Savepoint &); +public: + Savepoint() {}; + virtual ~Savepoint() {}; + virtual int getSavepointId() = 0; + + virtual sql::SQLString getSavepointName() = 0; +}; + + +class CPPCONN_PUBLIC_FUNC Connection +{ + /* Prevent use of these */ + Connection(const Connection &); + void operator=(Connection &); +public: + + Connection() {}; + + virtual ~Connection() {}; + + virtual void clearWarnings() = 0; + + virtual Statement *createStatement() = 0; + + virtual void close() = 0; + + virtual void commit() = 0; + + virtual bool getAutoCommit() = 0; + + virtual sql::SQLString getCatalog() = 0; + + virtual Driver *getDriver() = 0; + + virtual sql::SQLString getSchema() = 0; + + virtual sql::SQLString getClientInfo() = 0; + + virtual void getClientOption(const sql::SQLString & optionName, void * optionValue) = 0; + + virtual DatabaseMetaData * getMetaData() = 0; + + virtual enum_transaction_isolation getTransactionIsolation() = 0; + + virtual const SQLWarning * getWarnings() = 0; + + virtual bool isClosed() = 0; + + virtual bool isReadOnly() = 0; + + virtual sql::SQLString nativeSQL(const sql::SQLString& sql) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql, int autoGeneratedKeys) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql, int* columnIndexes) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) = 0; + + virtual PreparedStatement * prepareStatement(const sql::SQLString& sql, sql::SQLString columnNames[]) = 0; + + virtual void releaseSavepoint(Savepoint * savepoint) = 0; + + virtual void rollback() = 0; + + virtual void rollback(Savepoint * savepoint) = 0; + + virtual void setAutoCommit(bool autoCommit) = 0; + + virtual void setCatalog(const sql::SQLString& catalog) = 0; + + virtual void setSchema(const sql::SQLString& catalog) = 0; + + virtual sql::Connection * setClientOption(const sql::SQLString & optionName, const void * optionValue) = 0; + + virtual void setHoldability(int holdability) = 0; + + virtual void setReadOnly(bool readOnly) = 0; + + virtual Savepoint * setSavepoint() = 0; + + virtual Savepoint * setSavepoint(const sql::SQLString& name) = 0; + + virtual void setTransactionIsolation(enum_transaction_isolation level) = 0; + + /* virtual void setTypeMap(Map map) = 0; */ +}; + +} /* namespace sql */ + +#endif // _SQL_CONNECTION_H_ diff --git a/other/mysql/include/cppconn/datatype.h b/other/mysql/include/cppconn/datatype.h new file mode 100644 index 0000000..7ada3bc --- /dev/null +++ b/other/mysql/include/cppconn/datatype.h @@ -0,0 +1,68 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_DATATYPE_H_ +#define _SQL_DATATYPE_H_ + +namespace sql +{ + +class DataType +{ + DataType(); +public: + enum { + UNKNOWN = 0, + BIT, + TINYINT, + SMALLINT, + MEDIUMINT, + INTEGER, + BIGINT, + REAL, + DOUBLE, + DECIMAL, + NUMERIC, + CHAR, + BINARY, + VARCHAR, + VARBINARY, + LONGVARCHAR, + LONGVARBINARY, + TIMESTAMP, + DATE, + TIME, + YEAR, + GEOMETRY, + ENUM, + SET, + SQLNULL + }; +}; + +} /* namespace */ + +#endif /* _SQL_DATATYPE_H_ */ diff --git a/other/mysql/include/cppconn/driver.h b/other/mysql/include/cppconn/driver.h new file mode 100644 index 0000000..9ce8469 --- /dev/null +++ b/other/mysql/include/cppconn/driver.h @@ -0,0 +1,70 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_DRIVER_H_ +#define _SQL_DRIVER_H_ + +#include "connection.h" +#include "build_config.h" + +namespace sql +{ + +class CPPCONN_PUBLIC_FUNC Driver +{ +protected: + virtual ~Driver() {} +public: + // Attempts to make a database connection to the given URL. + + virtual Connection * connect(const sql::SQLString& hostName, const sql::SQLString& userName, const sql::SQLString& password) = 0; + + virtual Connection * connect(ConnectOptionsMap & options) = 0; + + virtual int getMajorVersion() = 0; + + virtual int getMinorVersion() = 0; + + virtual int getPatchVersion() = 0; + + virtual const sql::SQLString & getName() = 0; + + virtual void threadInit() = 0; + + virtual void threadEnd() = 0; +}; + +} /* namespace sql */ + +extern "C" +{ + CPPCONN_PUBLIC_FUNC sql::Driver * get_driver_instance(); + + /* If dynamic loading is disabled in a driver then this function works just like get_driver_instance() */ + CPPCONN_PUBLIC_FUNC sql::Driver * get_driver_instance_by_name(const char * const clientlib); +} + +#endif /* _SQL_DRIVER_H_ */ diff --git a/other/mysql/include/cppconn/exception.h b/other/mysql/include/cppconn/exception.h new file mode 100644 index 0000000..67cce8a --- /dev/null +++ b/other/mysql/include/cppconn/exception.h @@ -0,0 +1,128 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_EXCEPTION_H_ +#define _SQL_EXCEPTION_H_ + +#include "build_config.h" +#include <stdexcept> +#include <string> +#include <memory> + +namespace sql +{ + +#define MEMORY_ALLOC_OPERATORS(Class) \ + void* operator new(size_t size) throw (std::bad_alloc) { return ::operator new(size); } \ + void* operator new(size_t, void*) throw(); \ + void* operator new(size_t, const std::nothrow_t&) throw(); \ + void* operator new[](size_t) throw (std::bad_alloc); \ + void* operator new[](size_t, void*) throw(); \ + void* operator new[](size_t, const std::nothrow_t&) throw(); \ + void* operator new(size_t N, std::allocator<Class>&); + +#ifdef _WIN32 +#pragma warning (disable : 4290) +//warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow) + + +#pragma warning(push) +#pragma warning(disable: 4275) +#endif +class CPPCONN_PUBLIC_FUNC SQLException : public std::runtime_error +{ +#ifdef _WIN32 +#pragma warning(pop) +#endif +protected: + const std::string sql_state; + const int errNo; + +public: + SQLException(const SQLException& e) : std::runtime_error(e.what()), sql_state(e.sql_state), errNo(e.errNo) {} + + SQLException(const std::string& reason, const std::string& SQLState, int vendorCode) : + std::runtime_error (reason ), + sql_state (SQLState ), + errNo (vendorCode) + {} + + SQLException(const std::string& reason, const std::string& SQLState) : std::runtime_error(reason), sql_state(SQLState), errNo(0) {} + + SQLException(const std::string& reason) : std::runtime_error(reason), sql_state("HY000"), errNo(0) {} + + SQLException() : std::runtime_error(""), sql_state("HY000"), errNo(0) {} + + const std::string & getSQLState() const + { + return sql_state; + } + + const char * getSQLStateCStr() const + { + return sql_state.c_str(); + } + + + int getErrorCode() const + { + return errNo; + } + + virtual ~SQLException() throw () {}; + +protected: + MEMORY_ALLOC_OPERATORS(SQLException) +}; + +struct CPPCONN_PUBLIC_FUNC MethodNotImplementedException : public SQLException +{ + MethodNotImplementedException(const MethodNotImplementedException& e) : SQLException(e.what(), e.sql_state, e.errNo) { } + MethodNotImplementedException(const std::string& reason) : SQLException(reason, "", 0) {} +}; + +struct CPPCONN_PUBLIC_FUNC InvalidArgumentException : public SQLException +{ + InvalidArgumentException(const InvalidArgumentException& e) : SQLException(e.what(), e.sql_state, e.errNo) { } + InvalidArgumentException(const std::string& reason) : SQLException(reason, "", 0) {} +}; + +struct CPPCONN_PUBLIC_FUNC InvalidInstanceException : public SQLException +{ + InvalidInstanceException(const InvalidInstanceException& e) : SQLException(e.what(), e.sql_state, e.errNo) { } + InvalidInstanceException(const std::string& reason) : SQLException(reason, "", 0) {} +}; + + +struct CPPCONN_PUBLIC_FUNC NonScrollableException : public SQLException +{ + NonScrollableException(const NonScrollableException& e) : SQLException(e.what(), e.sql_state, e.errNo) { } + NonScrollableException(const std::string& reason) : SQLException(reason, "", 0) {} +}; + +} /* namespace sql */ + +#endif /* _SQL_EXCEPTION_H_ */ diff --git a/other/mysql/include/cppconn/metadata.h b/other/mysql/include/cppconn/metadata.h new file mode 100644 index 0000000..7f65768 --- /dev/null +++ b/other/mysql/include/cppconn/metadata.h @@ -0,0 +1,479 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_METADATA_H_ +#define _SQL_METADATA_H_ + +#include <string> +#include <list> +#include "datatype.h" +#include "sqlstring.h" + +namespace sql +{ +class ResultSet; + +class DatabaseMetaData +{ +protected: + virtual ~DatabaseMetaData() {} + +public: + enum + { + attributeNoNulls = 0, + attributeNullable, + attributeNullableUnknown + }; + enum + { + bestRowTemporary = 0, + bestRowTransaction, + bestRowSession + }; + enum + { + bestRowUnknown = 0, + bestRowNotPseudo, + bestRowPseudo + }; + enum + { + columnNoNulls = 0, + columnNullable, + columnNullableUnknown + }; + enum + { + importedKeyCascade = 0, + importedKeyInitiallyDeferred, + importedKeyInitiallyImmediate, + importedKeyNoAction, + importedKeyNotDeferrable, + importedKeyRestrict, + importedKeySetDefault, + importedKeySetNull + }; + enum + { + procedureColumnIn = 0, + procedureColumnInOut, + procedureColumnOut, + procedureColumnResult, + procedureColumnReturn, + procedureColumnUnknown, + procedureNoNulls, + procedureNoResult, + procedureNullable, + procedureNullableUnknown, + procedureResultUnknown, + procedureReturnsResult + }; + enum + { + sqlStateSQL99 = 0, + sqlStateXOpen + }; + enum + { + tableIndexClustered = 0, + tableIndexHashed, + tableIndexOther, + tableIndexStatistic + }; + enum + { + versionColumnUnknown = 0, + versionColumnNotPseudo = 1, + versionColumnPseudo = 2 + }; + enum + { + typeNoNulls = 0, + typeNullable = 1, + typeNullableUnknown = 2 + }; + enum + { + typePredNone = 0, + typePredChar = 1, + typePredBasic= 2, + typeSearchable = 3 + }; + + + virtual bool allProceduresAreCallable() = 0; + + virtual bool allTablesAreSelectable() = 0; + + virtual bool dataDefinitionCausesTransactionCommit() = 0; + + virtual bool dataDefinitionIgnoredInTransactions() = 0; + + virtual bool deletesAreDetected(int type) = 0; + + virtual bool doesMaxRowSizeIncludeBlobs() = 0; + + virtual ResultSet * getAttributes(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& typeNamePattern, const sql::SQLString& attributeNamePattern) = 0; + + virtual ResultSet * getBestRowIdentifier(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table, int scope, bool nullable) = 0; + + virtual ResultSet * getCatalogs() = 0; + + virtual const sql::SQLString& getCatalogSeparator() = 0; + + virtual const sql::SQLString& getCatalogTerm() = 0; + + virtual ResultSet * getColumnPrivileges(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table, const sql::SQLString& columnNamePattern) = 0; + + virtual ResultSet * getColumns(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& tableNamePattern, const sql::SQLString& columnNamePattern) = 0; + + virtual Connection * getConnection() = 0; + + virtual ResultSet * getCrossReference(const sql::SQLString& primaryCatalog, const sql::SQLString& primarySchema, const sql::SQLString& primaryTable, const sql::SQLString& foreignCatalog, const sql::SQLString& foreignSchema, const sql::SQLString& foreignTable) = 0; + + virtual unsigned int getDatabaseMajorVersion() = 0; + + virtual unsigned int getDatabaseMinorVersion() = 0; + + virtual unsigned int getDatabasePatchVersion() = 0; + + virtual const sql::SQLString& getDatabaseProductName() = 0; + + virtual SQLString getDatabaseProductVersion() = 0; + + virtual int getDefaultTransactionIsolation() = 0; + + virtual unsigned int getDriverMajorVersion() = 0; + + virtual unsigned int getDriverMinorVersion() = 0; + + virtual unsigned int getDriverPatchVersion() = 0; + + virtual const sql::SQLString& getDriverName() = 0; + + virtual const sql::SQLString& getDriverVersion() = 0; + + virtual ResultSet * getExportedKeys(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table) = 0; + + virtual const sql::SQLString& getExtraNameCharacters() = 0; + + virtual const sql::SQLString& getIdentifierQuoteString() = 0; + + virtual ResultSet * getImportedKeys(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table) = 0; + + virtual ResultSet * getIndexInfo(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table, bool unique, bool approximate) = 0; + + virtual unsigned int getCDBCMajorVersion() = 0; + + virtual unsigned int getCDBCMinorVersion() = 0; + + virtual unsigned int getMaxBinaryLiteralLength() = 0; + + virtual unsigned int getMaxCatalogNameLength() = 0; + + virtual unsigned int getMaxCharLiteralLength() = 0; + + virtual unsigned int getMaxColumnNameLength() = 0; + + virtual unsigned int getMaxColumnsInGroupBy() = 0; + + virtual unsigned int getMaxColumnsInIndex() = 0; + + virtual unsigned int getMaxColumnsInOrderBy() = 0; + + virtual unsigned int getMaxColumnsInSelect() = 0; + + virtual unsigned int getMaxColumnsInTable() = 0; + + virtual unsigned int getMaxConnections() = 0; + + virtual unsigned int getMaxCursorNameLength() = 0; + + virtual unsigned int getMaxIndexLength() = 0; + + virtual unsigned int getMaxProcedureNameLength() = 0; + + virtual unsigned int getMaxRowSize() = 0; + + virtual unsigned int getMaxSchemaNameLength() = 0; + + virtual unsigned int getMaxStatementLength() = 0; + + virtual unsigned int getMaxStatements() = 0; + + virtual unsigned int getMaxTableNameLength() = 0; + + virtual unsigned int getMaxTablesInSelect() = 0; + + virtual unsigned int getMaxUserNameLength() = 0; + + virtual const sql::SQLString& getNumericFunctions() = 0; + + virtual ResultSet * getPrimaryKeys(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table) = 0; + + virtual ResultSet * getProcedureColumns(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& procedureNamePattern, const sql::SQLString& columnNamePattern) = 0; + + virtual ResultSet * getProcedures(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& procedureNamePattern) = 0; + + virtual const sql::SQLString& getProcedureTerm() = 0; + + virtual int getResultSetHoldability() = 0; + + virtual ResultSet * getSchemas() = 0; + + virtual const sql::SQLString& getSchemaTerm() = 0; + + virtual const sql::SQLString& getSearchStringEscape() = 0; + + virtual const sql::SQLString& getSQLKeywords() = 0; + + virtual int getSQLStateType() = 0; + + virtual const sql::SQLString& getStringFunctions() = 0; + + virtual ResultSet * getSuperTables(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& tableNamePattern) = 0; + + virtual ResultSet * getSuperTypes(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& typeNamePattern) = 0; + + virtual const sql::SQLString& getSystemFunctions() = 0; + + virtual ResultSet * getTablePrivileges(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& tableNamePattern) = 0; + + virtual ResultSet * getTables(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& tableNamePattern, std::list<sql::SQLString> &types) = 0; + + virtual ResultSet * getTableTypes() = 0; + + virtual const sql::SQLString& getTimeDateFunctions() = 0; + + virtual ResultSet * getTypeInfo() = 0; + + virtual ResultSet * getUDTs(const sql::SQLString& catalog, const sql::SQLString& schemaPattern, const sql::SQLString& typeNamePattern, std::list<int> &types) = 0; + + virtual SQLString getURL() = 0; + + virtual SQLString getUserName() = 0; + + virtual ResultSet * getVersionColumns(const sql::SQLString& catalog, const sql::SQLString& schema, const sql::SQLString& table) = 0; + + virtual bool insertsAreDetected(int type) = 0; + + virtual bool isCatalogAtStart() = 0; + + virtual bool isReadOnly() = 0; + + virtual bool locatorsUpdateCopy() = 0; + + virtual bool nullPlusNonNullIsNull() = 0; + + virtual bool nullsAreSortedAtEnd() = 0; + + virtual bool nullsAreSortedAtStart() = 0; + + virtual bool nullsAreSortedHigh() = 0; + + virtual bool nullsAreSortedLow() = 0; + + virtual bool othersDeletesAreVisible(int type) = 0; + + virtual bool othersInsertsAreVisible(int type) = 0; + + virtual bool othersUpdatesAreVisible(int type) = 0; + + virtual bool ownDeletesAreVisible(int type) = 0; + + virtual bool ownInsertsAreVisible(int type) = 0; + + virtual bool ownUpdatesAreVisible(int type) = 0; + + virtual bool storesLowerCaseIdentifiers() = 0; + + virtual bool storesLowerCaseQuotedIdentifiers() = 0; + + virtual bool storesMixedCaseIdentifiers() = 0; + + virtual bool storesMixedCaseQuotedIdentifiers() = 0; + + virtual bool storesUpperCaseIdentifiers() = 0; + + virtual bool storesUpperCaseQuotedIdentifiers() = 0; + + virtual bool supportsAlterTableWithAddColumn() = 0; + + virtual bool supportsAlterTableWithDropColumn() = 0; + + virtual bool supportsANSI92EntryLevelSQL() = 0; + + virtual bool supportsANSI92FullSQL() = 0; + + virtual bool supportsANSI92IntermediateSQL() = 0; + + virtual bool supportsBatchUpdates() = 0; + + virtual bool supportsCatalogsInDataManipulation() = 0; + + virtual bool supportsCatalogsInIndexDefinitions() = 0; + + virtual bool supportsCatalogsInPrivilegeDefinitions() = 0; + + virtual bool supportsCatalogsInProcedureCalls() = 0; + + virtual bool supportsCatalogsInTableDefinitions() = 0; + + virtual bool supportsColumnAliasing() = 0; + + virtual bool supportsConvert() = 0; + + virtual bool supportsConvert(int fromType, int toType) = 0; + + virtual bool supportsCoreSQLGrammar() = 0; + + virtual bool supportsCorrelatedSubqueries() = 0; + + virtual bool supportsDataDefinitionAndDataManipulationTransactions() = 0; + + virtual bool supportsDataManipulationTransactionsOnly() = 0; + + virtual bool supportsDifferentTableCorrelationNames() = 0; + + virtual bool supportsExpressionsInOrderBy() = 0; + + virtual bool supportsExtendedSQLGrammar() = 0; + + virtual bool supportsFullOuterJoins() = 0; + + virtual bool supportsGetGeneratedKeys() = 0; + + virtual bool supportsGroupBy() = 0; + + virtual bool supportsGroupByBeyondSelect() = 0; + + virtual bool supportsGroupByUnrelated() = 0; + + virtual bool supportsIntegrityEnhancementFacility() = 0; + + virtual bool supportsLikeEscapeClause() = 0; + + virtual bool supportsLimitedOuterJoins() = 0; + + virtual bool supportsMinimumSQLGrammar() = 0; + + virtual bool supportsMixedCaseIdentifiers() = 0; + + virtual bool supportsMixedCaseQuotedIdentifiers() = 0; + + virtual bool supportsMultipleOpenResults() = 0; + + virtual bool supportsMultipleResultSets() = 0; + + virtual bool supportsMultipleTransactions() = 0; + + virtual bool supportsNamedParameters() = 0; + + virtual bool supportsNonNullableColumns() = 0; + + virtual bool supportsOpenCursorsAcrossCommit() = 0; + + virtual bool supportsOpenCursorsAcrossRollback() = 0; + + virtual bool supportsOpenStatementsAcrossCommit() = 0; + + virtual bool supportsOpenStatementsAcrossRollback() = 0; + + virtual bool supportsOrderByUnrelated() = 0; + + virtual bool supportsOuterJoins() = 0; + + virtual bool supportsPositionedDelete() = 0; + + virtual bool supportsPositionedUpdate() = 0; + + virtual bool supportsResultSetConcurrency(int type, int concurrency) = 0; + + virtual bool supportsResultSetHoldability(int holdability) = 0; + + virtual bool supportsResultSetType(int type) = 0; + + virtual bool supportsSavepoints() = 0; + + virtual bool supportsSchemasInDataManipulation() = 0; + + virtual bool supportsSchemasInIndexDefinitions() = 0; + + virtual bool supportsSchemasInPrivilegeDefinitions() = 0; + + virtual bool supportsSchemasInProcedureCalls() = 0; + + virtual bool supportsSchemasInTableDefinitions() = 0; + + virtual bool supportsSelectForUpdate() = 0; + + virtual bool supportsStatementPooling() = 0; + + virtual bool supportsStoredProcedures() = 0; + + virtual bool supportsSubqueriesInComparisons() = 0; + + virtual bool supportsSubqueriesInExists() = 0; + + virtual bool supportsSubqueriesInIns() = 0; + + virtual bool supportsSubqueriesInQuantifieds() = 0; + + virtual bool supportsTableCorrelationNames() = 0; + + virtual bool supportsTransactionIsolationLevel(int level) = 0; + + virtual bool supportsTransactions() = 0; + + virtual bool supportsTypeConversion() = 0; /* SDBC */ + + virtual bool supportsUnion() = 0; + + virtual bool supportsUnionAll() = 0; + + virtual bool updatesAreDetected(int type) = 0; + + virtual bool usesLocalFilePerTable() = 0; + + virtual bool usesLocalFiles() = 0; + + virtual ResultSet *getSchemata(const sql::SQLString& catalogName = "") = 0; + + virtual ResultSet *getSchemaObjects(const sql::SQLString& catalogName = "", + const sql::SQLString& schemaName = "", + const sql::SQLString& objectType = "", + bool includingDdl = true, + const sql::SQLString& objectName = "", + const sql::SQLString& contextTableName = "") = 0; + + virtual ResultSet *getSchemaObjectTypes() = 0; +}; + + +} /* namespace sql */ + +#endif /* _SQL_METADATA_H_ */ diff --git a/other/mysql/include/cppconn/parameter_metadata.h b/other/mysql/include/cppconn/parameter_metadata.h new file mode 100644 index 0000000..06639ed --- /dev/null +++ b/other/mysql/include/cppconn/parameter_metadata.h @@ -0,0 +1,78 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_PARAMETER_METADATA_H_ +#define _SQL_PARAMETER_METADATA_H_ + +#include <cppconn/sqlstring.h> + + +namespace sql +{ + +class ParameterMetaData +{ +public: + enum + { + parameterModeIn, + parameterModeInOut, + parameterModeOut, + parameterModeUnknown + }; + enum + { + parameterNoNulls, + parameterNullable, + parameterNullableUnknown + }; + + virtual sql::SQLString getParameterClassName(unsigned int param) = 0; + + virtual int getParameterCount() = 0; + + virtual int getParameterMode(unsigned int param) = 0; + + virtual int getParameterType(unsigned int param) = 0; + + virtual sql::SQLString getParameterTypeName(unsigned int param) = 0; + + virtual int getPrecision(unsigned int param) = 0; + + virtual int getScale(unsigned int param) = 0; + + virtual int isNullable(unsigned int param) = 0; + + virtual bool isSigned(unsigned int param) = 0; + +protected: + virtual ~ParameterMetaData() {} +}; + + +} /* namespace sql */ + +#endif /* _SQL_PARAMETER_METADATA_H_ */ diff --git a/other/mysql/include/cppconn/prepared_statement.h b/other/mysql/include/cppconn/prepared_statement.h new file mode 100644 index 0000000..a2945e4 --- /dev/null +++ b/other/mysql/include/cppconn/prepared_statement.h @@ -0,0 +1,91 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + + +#ifndef _SQL_PREPARED_STATEMENT_H_ +#define _SQL_PREPARED_STATEMENT_H_ + +#include <iostream> +#include "statement.h" + + +namespace sql +{ + +class Connection; +class ResultSet; +class ResultSetMetaData; +class ParameterMetaData; + +class PreparedStatement : public Statement +{ +public: + virtual ~PreparedStatement() {} + + virtual void clearParameters() = 0; + + virtual bool execute(const sql::SQLString& sql) = 0; + virtual bool execute() = 0; + + virtual ResultSet *executeQuery(const sql::SQLString& sql) = 0; + virtual ResultSet *executeQuery() = 0; + + virtual int executeUpdate(const sql::SQLString& sql) = 0; + virtual int executeUpdate() = 0; + + virtual ResultSetMetaData * getMetaData() = 0; + + virtual ParameterMetaData * getParameterMetaData() = 0; + + virtual void setBigInt(unsigned int parameterIndex, const sql::SQLString& value) = 0; + + virtual void setBlob(unsigned int parameterIndex, std::istream * blob) = 0; + + virtual void setBoolean(unsigned int parameterIndex, bool value) = 0; + + virtual void setDateTime(unsigned int parameterIndex, const sql::SQLString& value) = 0; + + virtual void setDouble(unsigned int parameterIndex, double value) = 0; + + virtual void setInt(unsigned int parameterIndex, int32_t value) = 0; + + virtual void setUInt(unsigned int parameterIndex, uint32_t value) = 0; + + virtual void setInt64(unsigned int parameterIndex, int64_t value) = 0; + + virtual void setUInt64(unsigned int parameterIndex, uint64_t value) = 0; + + virtual void setNull(unsigned int parameterIndex, int sqlType) = 0; + + virtual void setString(unsigned int parameterIndex, const sql::SQLString& value) = 0; + + virtual PreparedStatement * setResultSetType(sql::ResultSet::enum_type type) = 0; +}; + + +} /* namespace sql */ + +#endif /* _SQL_PREPARED_STATEMENT_H_ */ diff --git a/other/mysql/include/cppconn/resultset.h b/other/mysql/include/cppconn/resultset.h new file mode 100644 index 0000000..bd45dfb --- /dev/null +++ b/other/mysql/include/cppconn/resultset.h @@ -0,0 +1,182 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_RESULTSET_H_ +#define _SQL_RESULTSET_H_ + +#include "config.h" + +#include <list> +#include <map> +#include <iostream> +#include "sqlstring.h" +#include "resultset_metadata.h" + + +namespace sql +{ + +class Statement; + +class RowID +{ +public: + virtual ~RowID() {} +}; + +class ResultSet +{ +public: + enum + { + CLOSE_CURSORS_AT_COMMIT, + HOLD_CURSORS_OVER_COMMIT + }; + enum + { + CONCUR_READ_ONLY, + CONCUR_UPDATABLE + }; + enum + { + FETCH_FORWARD, + FETCH_REVERSE, + FETCH_UNKNOWN + }; + typedef enum + { + TYPE_FORWARD_ONLY, + TYPE_SCROLL_INSENSITIVE, + TYPE_SCROLL_SENSITIVE + } enum_type; + + virtual ~ResultSet() {} + + virtual bool absolute(int row) = 0; + + virtual void afterLast() = 0; + + virtual void beforeFirst() = 0; + + virtual void cancelRowUpdates() = 0; + + virtual void clearWarnings() = 0; + + virtual void close() = 0; + + virtual uint32_t findColumn(const sql::SQLString& columnLabel) const = 0; + + virtual bool first() = 0; + + virtual std::istream * getBlob(uint32_t columnIndex) const = 0; + virtual std::istream * getBlob(const sql::SQLString& columnLabel) const = 0; + + virtual bool getBoolean(uint32_t columnIndex) const = 0; + virtual bool getBoolean(const sql::SQLString& columnLabel) const = 0; + + virtual int getConcurrency() = 0; + virtual SQLString getCursorName() = 0; + + virtual long double getDouble(uint32_t columnIndex) const = 0; + virtual long double getDouble(const sql::SQLString& columnLabel) const = 0; + + virtual int getFetchDirection() = 0; + virtual size_t getFetchSize() = 0; + virtual int getHoldability() = 0; + + virtual int32_t getInt(uint32_t columnIndex) const = 0; + virtual int32_t getInt(const sql::SQLString& columnLabel) const = 0; + + virtual uint32_t getUInt(uint32_t columnIndex) const = 0; + virtual uint32_t getUInt(const sql::SQLString& columnLabel) const = 0; + + virtual int64_t getInt64(uint32_t columnIndex) const = 0; + virtual int64_t getInt64(const sql::SQLString& columnLabel) const = 0; + + virtual uint64_t getUInt64(uint32_t columnIndex) const = 0; + virtual uint64_t getUInt64(const sql::SQLString& columnLabel) const = 0; + + virtual ResultSetMetaData * getMetaData() const = 0; + + virtual size_t getRow() const = 0; + + virtual RowID * getRowId(uint32_t columnIndex) = 0; + virtual RowID * getRowId(const sql::SQLString & columnLabel) = 0; + + virtual const Statement * getStatement() const = 0; + + virtual SQLString getString(uint32_t columnIndex) const = 0; + virtual SQLString getString(const sql::SQLString& columnLabel) const = 0; + + virtual enum_type getType() const = 0; + + virtual void getWarnings() = 0; + + virtual void insertRow() = 0; + + virtual bool isAfterLast() const = 0; + + virtual bool isBeforeFirst() const = 0; + + virtual bool isClosed() const = 0; + + virtual bool isFirst() const = 0; + + virtual bool isLast() const = 0; + + virtual bool isNull(uint32_t columnIndex) const = 0; + virtual bool isNull(const sql::SQLString& columnLabel) const = 0; + + virtual bool last() = 0; + + virtual bool next() = 0; + + virtual void moveToCurrentRow() = 0; + + virtual void moveToInsertRow() = 0; + + virtual bool previous() = 0; + + virtual void refreshRow() = 0; + + virtual bool relative(int rows) = 0; + + virtual bool rowDeleted() = 0; + + virtual bool rowInserted() = 0; + + virtual bool rowUpdated() = 0; + + virtual void setFetchSize(size_t rows) = 0; + + virtual size_t rowsCount() const = 0; + + virtual bool wasNull() const = 0; +}; + +} /* namespace sql */ + +#endif /* _SQL_RESULTSET_H_ */ diff --git a/other/mysql/include/cppconn/resultset_metadata.h b/other/mysql/include/cppconn/resultset_metadata.h new file mode 100644 index 0000000..fb0efce --- /dev/null +++ b/other/mysql/include/cppconn/resultset_metadata.h @@ -0,0 +1,97 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_RESULTSET_METADATA_H_ +#define _SQL_RESULTSET_METADATA_H_ + +#include "sqlstring.h" +#include "datatype.h" + +namespace sql +{ + +class ResultSetMetaData +{ +public: + enum + { + columnNoNulls, + columnNullable, + columnNullableUnknown + }; + + virtual SQLString getCatalogName(unsigned int column) = 0; + + virtual unsigned int getColumnCount() = 0; + + virtual unsigned int getColumnDisplaySize(unsigned int column) = 0; + + virtual SQLString getColumnLabel(unsigned int column) = 0; + + virtual SQLString getColumnName(unsigned int column) = 0; + + virtual int getColumnType(unsigned int column) = 0; + + virtual SQLString getColumnTypeName(unsigned int column) = 0; + + virtual unsigned int getPrecision(unsigned int column) = 0; + + virtual unsigned int getScale(unsigned int column) = 0; + + virtual SQLString getSchemaName(unsigned int column) = 0; + + virtual SQLString getTableName(unsigned int column) = 0; + + virtual bool isAutoIncrement(unsigned int column) = 0; + + virtual bool isCaseSensitive(unsigned int column) = 0; + + virtual bool isCurrency(unsigned int column) = 0; + + virtual bool isDefinitelyWritable(unsigned int column) = 0; + + virtual int isNullable(unsigned int column) = 0; + + virtual bool isNumeric(unsigned int column) = 0; + + virtual bool isReadOnly(unsigned int column) = 0; + + virtual bool isSearchable(unsigned int column) = 0; + + virtual bool isSigned(unsigned int column) = 0; + + virtual bool isWritable(unsigned int column) = 0; + + virtual bool isZerofill(unsigned int column) = 0; + +protected: + virtual ~ResultSetMetaData() {} +}; + + +} /* namespace sql */ + +#endif /* _SQL_RESULTSET_METADATA_H_ */ diff --git a/other/mysql/include/cppconn/sqlstring.h b/other/mysql/include/cppconn/sqlstring.h new file mode 100644 index 0000000..d20080d --- /dev/null +++ b/other/mysql/include/cppconn/sqlstring.h @@ -0,0 +1,213 @@ +/* +Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_STRING_H_ +#define _SQL_STRING_H_ + +#include <string> +#include "build_config.h" +#include <iostream> + +namespace sql +{ + class CPPCONN_PUBLIC_FUNC SQLString + { + std::string realStr; + + public: +#ifdef _WIN32 + //TODO something less dirty-hackish. + static const size_t npos = static_cast<std::string::size_type>(-1); +#else + static const size_t npos = std::string::npos; +#endif + + ~SQLString() {} + + SQLString() {} + + SQLString(const SQLString & other) : realStr(other.realStr) {} + + SQLString(const std::string & other) : realStr(other) {} + + SQLString(const char other[]) : realStr(other) {} + + SQLString(const char * s, size_t n) : realStr(s, n) {} + + // Needed for stuff like SQLString str= "char * string constant" + const SQLString & operator=(const char * s) + { + realStr = s; + return *this; + } + + const SQLString & operator=(const std::string & rhs) + { + realStr = rhs; + return *this; + } + + const SQLString & operator=(const SQLString & rhs) + { + realStr = rhs.realStr; + return *this; + } + + // Conversion to st::string. Comes in play for stuff like std::string str= SQLString_var; + operator const std::string &() const + { + return realStr; + } + + /** For access std::string methods. Not sure we need it. Makes it look like some smart ptr. + possibly operator* - will look even more like smart ptr */ + std::string * operator ->() + { + return & realStr; + } + + int compare(const SQLString& str) const + { + return realStr.compare(str.realStr); + } + + int compare(const char * s) const + { + return realStr.compare(s); + } + + int compare(size_t pos1, size_t n1, const char * s) const + { + return realStr.compare(pos1, n1, s); + } + + const std::string & asStdString() const + { + return realStr; + } + + const char * c_str() const + { + return realStr.c_str(); + } + + size_t length() const + { + return realStr.length(); + } + + SQLString & append(const std::string & str) + { + realStr.append(str); + return *this; + } + + SQLString & append(const char * s) + { + realStr.append(s); + return *this; + } + + const char& operator[](size_t pos) const + { + return realStr[pos]; + } + + size_t find(char c, size_t pos = 0) const + { + return realStr.find(c, pos); + } + + size_t find(const SQLString & s, size_t pos = 0) const + { + return realStr.find(s.realStr, pos); + } + + SQLString substr(size_t pos = 0, size_t n = npos) const + { + return realStr.substr(pos, n); + } + + const SQLString& replace(size_t pos1, size_t n1, const SQLString & s) + { + realStr.replace(pos1, n1, s.realStr); + return *this; + } + + size_t find_first_of(char c, size_t pos = 0) const + { + return realStr.find_first_of(c, pos); + } + + size_t find_last_of(char c, size_t pos = npos) const + { + return realStr.find_last_of(c, pos); + } + + const SQLString & operator+=(const SQLString & op2) + { + realStr += op2.realStr; + return *this; + } +}; + + +/* + Operators that can and have to be not a member. +*/ +inline const SQLString operator+(const SQLString & op1, const SQLString & op2) +{ + return sql::SQLString(op1.asStdString() + op2.asStdString()); +} + +inline bool operator ==(const SQLString & op1, const SQLString & op2) +{ + return (op1.asStdString() == op2.asStdString()); +} + +inline bool operator !=(const SQLString & op1, const SQLString & op2) +{ + return (op1.asStdString() != op2.asStdString()); +} + +inline bool operator <(const SQLString & op1, const SQLString & op2) +{ + return op1.asStdString() < op2.asStdString(); +} + + +}// namespace sql + + +namespace std +{ + // operator << for SQLString output + inline ostream & operator << (ostream & os, const sql::SQLString & str ) + { + return os << str.asStdString(); + } +} +#endif diff --git a/other/mysql/include/cppconn/statement.h b/other/mysql/include/cppconn/statement.h new file mode 100644 index 0000000..ecb4db7 --- /dev/null +++ b/other/mysql/include/cppconn/statement.h @@ -0,0 +1,97 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_STATEMENT_H_ +#define _SQL_STATEMENT_H_ + +#include "config.h" +#include "resultset.h" + +#include <string> + +namespace sql +{ + +class ResultSet; +class Connection; +class SQLWarning; + + +class Statement +{ +public: + virtual ~Statement() {}; + + virtual Connection * getConnection() = 0; + + virtual void cancel() = 0; + + virtual void clearWarnings() = 0; + + virtual void close() = 0; + + virtual bool execute(const sql::SQLString& sql) = 0; + + virtual ResultSet * executeQuery(const sql::SQLString& sql) = 0; + + virtual int executeUpdate(const sql::SQLString& sql) = 0; + + virtual size_t getFetchSize() = 0; + + virtual unsigned int getMaxFieldSize() = 0; + + virtual uint64_t getMaxRows() = 0; + + virtual bool getMoreResults() = 0; + + virtual unsigned int getQueryTimeout() = 0; + + virtual ResultSet * getResultSet() = 0; + + virtual sql::ResultSet::enum_type getResultSetType() = 0; + + virtual uint64_t getUpdateCount() = 0; + + virtual const SQLWarning * getWarnings() = 0; + + virtual void setCursorName(const sql::SQLString & name) = 0; + + virtual void setEscapeProcessing(bool enable) = 0; + + virtual void setFetchSize(size_t rows) = 0; + + virtual void setMaxFieldSize(unsigned int max) = 0; + + virtual void setMaxRows(unsigned int max) = 0; + + virtual void setQueryTimeout(unsigned int seconds) = 0; + + virtual Statement * setResultSetType(sql::ResultSet::enum_type type) = 0; +}; + +} /* namespace sql */ + +#endif /* _SQL_STATEMENT_H_ */ diff --git a/other/mysql/include/cppconn/warning.h b/other/mysql/include/cppconn/warning.h new file mode 100644 index 0000000..3c4653a --- /dev/null +++ b/other/mysql/include/cppconn/warning.h @@ -0,0 +1,74 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _SQL_WARNING_H_ +#define _SQL_WARNING_H_ + + +#include <stdexcept> +#include <string> +#include <memory> +#include "sqlstring.h" + +namespace sql +{ + +#ifdef _WIN32 +#pragma warning (disable : 4290) +//warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +class SQLWarning +{ +public: + + SQLWarning(){} + + virtual const sql::SQLString & getMessage() const = 0; + + virtual const sql::SQLString & getSQLState() const = 0; + + virtual int getErrorCode() const = 0; + + virtual const SQLWarning * getNextWarning() const = 0; + + virtual void setNextWarning(const SQLWarning * _next) = 0; + +protected: + + virtual ~SQLWarning(){}; + + SQLWarning(const SQLWarning& e){}; + +private: + const SQLWarning & operator = (const SQLWarning & rhs); + +}; + + +} /* namespace sql */ + +#endif /* _SQL_WARNING_H_ */ diff --git a/other/mysql/include/mysql_connection.h b/other/mysql/include/mysql_connection.h new file mode 100644 index 0000000..8c81e81 --- /dev/null +++ b/other/mysql/include/mysql_connection.h @@ -0,0 +1,190 @@ +/* +Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _MYSQL_CONNECTION_H_ +#define _MYSQL_CONNECTION_H_ + +#include <cppconn/connection.h> +#include <boost/shared_ptr.hpp> +#include <boost/scoped_ptr.hpp> + +namespace sql +{ +namespace mysql +{ + +class MySQL_Savepoint : public sql::Savepoint +{ + sql::SQLString name; + +public: + MySQL_Savepoint(const sql::SQLString &savepoint); + virtual ~MySQL_Savepoint() {} + + int getSavepointId(); + + sql::SQLString getSavepointName(); + +private: + /* Prevent use of these */ + MySQL_Savepoint(const MySQL_Savepoint &); + void operator=(MySQL_Savepoint &); +}; + + +class MySQL_DebugLogger; +struct MySQL_ConnectionData; /* PIMPL */ +class MySQL_Statement; + +namespace NativeAPI +{ +class NativeConnectionWrapper; +} + +class CPPCONN_PUBLIC_FUNC MySQL_Connection : public sql::Connection +{ + MySQL_Statement * createServiceStmt(); + +public: + MySQL_Connection(Driver * _driver, + ::sql::mysql::NativeAPI::NativeConnectionWrapper & _proxy, + const sql::SQLString& hostName, + const sql::SQLString& userName, + const sql::SQLString& password); + + MySQL_Connection(Driver * _driver, ::sql::mysql::NativeAPI::NativeConnectionWrapper & _proxy, + std::map< sql::SQLString, sql::ConnectPropertyVal > & options); + + virtual ~MySQL_Connection(); + + void clearWarnings(); + + void close(); + + void commit(); + + sql::Statement * createStatement(); + + sql::SQLString escapeString(const sql::SQLString &); + + bool getAutoCommit(); + + sql::SQLString getCatalog(); + + Driver *getDriver(); + + sql::SQLString getSchema(); + + sql::SQLString getClientInfo(); + + void getClientOption(const sql::SQLString & optionName, void * optionValue); + + sql::DatabaseMetaData * getMetaData(); + + enum_transaction_isolation getTransactionIsolation(); + + const SQLWarning * getWarnings(); + + bool isClosed(); + + bool isReadOnly(); + + sql::SQLString nativeSQL(const sql::SQLString& sql); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql, int autoGeneratedKeys); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql, int columnIndexes[]); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability); + + sql::PreparedStatement * prepareStatement(const sql::SQLString& sql, sql::SQLString columnNames[]); + + void releaseSavepoint(Savepoint * savepoint) ; + + void rollback(); + + void rollback(Savepoint * savepoint); + + void setAutoCommit(bool autoCommit); + + void setCatalog(const sql::SQLString& catalog); + + void setSchema(const sql::SQLString& catalog); + + sql::Connection * setClientOption(const sql::SQLString & optionName, const void * optionValue); + + void setHoldability(int holdability); + + void setReadOnly(bool readOnly); + + sql::Savepoint * setSavepoint(); + + sql::Savepoint * setSavepoint(const sql::SQLString& name); + + void setTransactionIsolation(enum_transaction_isolation level); + + virtual sql::SQLString getSessionVariable(const sql::SQLString & varname); + + virtual void setSessionVariable(const sql::SQLString & varname, const sql::SQLString & value); + + virtual sql::SQLString getLastStatementInfo(); + +private: + /* We do not really think this class has to be subclassed*/ + void checkClosed(); + void init(std::map< sql::SQLString, sql::ConnectPropertyVal > & properties); + + Driver * driver; + boost::shared_ptr< NativeAPI::NativeConnectionWrapper > proxy; + + /* statement handle to execute queries initiated by driver. Perhaps it is + a good idea to move it to a separate helper class */ + boost::scoped_ptr< ::sql::mysql::MySQL_Statement > service; + + MySQL_ConnectionData * intern; /* pimpl */ + + /* Prevent use of these */ + MySQL_Connection(const MySQL_Connection &); + void operator=(MySQL_Connection &); +}; + +} /* namespace mysql */ +} /* namespace sql */ + +#endif // _MYSQL_CONNECTION_H_ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ diff --git a/other/mysql/include/mysql_driver.h b/other/mysql/include/mysql_driver.h new file mode 100644 index 0000000..ccd8cbc --- /dev/null +++ b/other/mysql/include/mysql_driver.h @@ -0,0 +1,104 @@ +/* +Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. + +The MySQL Connector/C++ is licensed under the terms of the GPLv2 +<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most +MySQL Connectors. There are special exceptions to the terms and +conditions of the GPLv2 as it is applied to this software, see the +FLOSS License Exception +<http://www.mysql.com/about/legal/licensing/foss-exception.html>. + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + + + +#ifndef _MYSQL_DRIVER_H_ +#define _MYSQL_DRIVER_H_ + +#include <boost/scoped_ptr.hpp> + +#include <cppconn/driver.h> + +extern "C" +{ +CPPCONN_PUBLIC_FUNC void * sql_mysql_get_driver_instance(); +} + +namespace sql +{ +namespace mysql +{ +namespace NativeAPI +{ + class NativeDriverWrapper; +} + +//class sql::mysql::NativeAPI::NativeDriverWrapper; + +class CPPCONN_PUBLIC_FUNC MySQL_Driver : public sql::Driver +{ + boost::scoped_ptr< ::sql::mysql::NativeAPI::NativeDriverWrapper > proxy; + +public: + MySQL_Driver(); + MySQL_Driver(const ::sql::SQLString & clientLib); + + virtual ~MySQL_Driver(); + + sql::Connection * connect(const sql::SQLString& hostName, const sql::SQLString& userName, const sql::SQLString& password); + + sql::Connection * connect(sql::ConnectOptionsMap & options); + + int getMajorVersion(); + + int getMinorVersion(); + + int getPatchVersion(); + + const sql::SQLString & getName(); + + void threadInit(); + + void threadEnd(); + +private: + /* Prevent use of these */ + MySQL_Driver(const MySQL_Driver &); + void operator=(MySQL_Driver &); +}; + +/** We do not hide the function if MYSQLCLIENT_STATIC_BINDING(or anything else) not defined + because the counterpart C function is declared in the cppconn and is always visible. + If dynamic loading is not enabled then its result is just like of get_driver_instance() +*/ +CPPCONN_PUBLIC_FUNC MySQL_Driver * get_driver_instance_by_name(const char * const clientlib); + +CPPCONN_PUBLIC_FUNC MySQL_Driver * get_driver_instance(); +static inline MySQL_Driver * get_mysql_driver_instance() { return get_driver_instance(); } + + +} /* namespace mysql */ +} /* namespace sql */ + +#endif // _MYSQL_DRIVER_H_ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ diff --git a/other/mysql/mysql.lua b/other/mysql/mysql.lua new file mode 100644 index 0000000..20dcb6d --- /dev/null +++ b/other/mysql/mysql.lua @@ -0,0 +1,94 @@ +Mysql = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.lib_path = nil + + if IsNegativeTerm(ScriptArgs[name .. ".use_mysqlconfig"]) then + option.use_mysqlconfig = false + elseif IsPositiveTerm(ScriptArgs[name .. ".use_mysqlconfig"]) then + option.use_mysqlconfig = true + end + + if ExecuteSilent("mysql_config --version") == 0 then + option.value = true + if option.use_mysqlconfig == nil then + option.use_mysqlconfig = true + end + end + + if option.use_mysqlconfig == nil then + option.use_mysqlconfig = false + end + + if platform == "win32" then + option.value = true + elseif platform == "win64" then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "32") then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "64") then + option.value = true + elseif platform == "linux" and arch == "ia32" then + option.value = true + elseif platform == "linux" and arch == "amd64" then + option.value = true + end + end + + local apply = function(option, settings) + if option.use_mysqlconfig == true then + settings.cc.flags:Add("`mysql_config --cflags`") + settings.link.flags:Add("`mysql_config --libs`") + settings.link.libs:Add("mysqlcppconn") + else + settings.cc.includes:Add(Mysql.basepath .. "/include") + + if family ~= "windows" then + settings.link.libs:Add("mysqlcppconn-static") + settings.link.libs:Add("mysqlclient") + settings.link.libs:Add("dl") + if platform ~= "macosx" then + settings.link.libs:Add("rt") + end + end + + if platform == "macosx" and string.find(settings.config_name, "32") then + settings.link.libpath:Add("other/mysql/mac/lib32") + elseif platform == "macosx" and string.find(settings.config_name, "64") then + settings.link.libpath:Add("other/mysql/mac/lib64") + elseif platform == "linux" then + settings.link.libpath:Add("other/mysql/linux/lib64") + settings.link.libpath:Add("other/mysql/linux/lib32") + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_mysqlconfig") + end + + local display = function(option) + if option.value == true then + if option.use_mysqlconfig == true then return "using mysql_config" end + return "using bundled libs" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/mysql/vc2005libs/mysqlcppconn.lib b/other/mysql/vc2005libs/mysqlcppconn.lib new file mode 100644 index 0000000..866944d Binary files /dev/null and b/other/mysql/vc2005libs/mysqlcppconn.lib differ diff --git a/other/opus/AUTHORS b/other/opus/AUTHORS new file mode 100644 index 0000000..d0ac09d --- /dev/null +++ b/other/opus/AUTHORS @@ -0,0 +1,5 @@ +Timothy B. Terriberry <tterribe@xiph.org> +Ralph Giles <giles@xiph.org> +Christopher "Monty" Montgomery <xiphmont@xiph.org> (original libvorbisfile) +Gregory Maxwell <greg@xiph.org> (noise shaping dithering) +nu774 <honeycomb77@gmail.com> (original winsock support) diff --git a/other/opus/COPYING b/other/opus/COPYING new file mode 100644 index 0000000..7b53d66 --- /dev/null +++ b/other/opus/COPYING @@ -0,0 +1,28 @@ +Copyright (c) 1994-2013 Xiph.Org Foundation and contributors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/other/opus/VERSIONS b/other/opus/VERSIONS new file mode 100644 index 0000000..6452aaf --- /dev/null +++ b/other/opus/VERSIONS @@ -0,0 +1,3 @@ +ogg 1.3.2 +opus 1.1 +opusfile 0.6 diff --git a/other/opus/include/ogg/ogg.h b/other/opus/include/ogg/ogg.h new file mode 100644 index 0000000..cea4ebe --- /dev/null +++ b/other/opus/include/ogg/ogg.h @@ -0,0 +1,210 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007 * + * by the Xiph.Org Foundation http://www.xiph.org/ * + * * + ******************************************************************** + + function: toplevel libogg include + last mod: $Id: ogg.h 18044 2011-08-01 17:55:20Z gmaxwell $ + + ********************************************************************/ +#ifndef _OGG_H +#define _OGG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include <stddef.h> +#include <ogg/os_types.h> + +typedef struct { + void *iov_base; + size_t iov_len; +} ogg_iovec_t; + +typedef struct { + long endbyte; + int endbit; + + unsigned char *buffer; + unsigned char *ptr; + long storage; +} oggpack_buffer; + +/* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/ + +typedef struct { + unsigned char *header; + long header_len; + unsigned char *body; + long body_len; +} ogg_page; + +/* ogg_stream_state contains the current encode/decode state of a logical + Ogg bitstream **********************************************************/ + +typedef struct { + unsigned char *body_data; /* bytes from packet bodies */ + long body_storage; /* storage elements allocated */ + long body_fill; /* elements stored; fill mark */ + long body_returned; /* elements of fill returned */ + + + int *lacing_vals; /* The values that will go to the segment table */ + ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact + this way, but it is simple coupled to the + lacing fifo */ + long lacing_storage; + long lacing_fill; + long lacing_packet; + long lacing_returned; + + unsigned char header[282]; /* working space for header encode */ + int header_fill; + + int e_o_s; /* set when we have buffered the last packet in the + logical bitstream */ + int b_o_s; /* set after we've written the initial page + of a logical bitstream */ + long serialno; + long pageno; + ogg_int64_t packetno; /* sequence number for decode; the framing + knows where there's a hole in the data, + but we need coupling so that the codec + (which is in a separate abstraction + layer) also knows about the gap */ + ogg_int64_t granulepos; + +} ogg_stream_state; + +/* ogg_packet is used to encapsulate the data and metadata belonging + to a single raw Ogg/Vorbis packet *************************************/ + +typedef struct { + unsigned char *packet; + long bytes; + long b_o_s; + long e_o_s; + + ogg_int64_t granulepos; + + ogg_int64_t packetno; /* sequence number for decode; the framing + knows where there's a hole in the data, + but we need coupling so that the codec + (which is in a separate abstraction + layer) also knows about the gap */ +} ogg_packet; + +typedef struct { + unsigned char *data; + int storage; + int fill; + int returned; + + int unsynced; + int headerbytes; + int bodybytes; +} ogg_sync_state; + +/* Ogg BITSTREAM PRIMITIVES: bitstream ************************/ + +extern void oggpack_writeinit(oggpack_buffer *b); +extern int oggpack_writecheck(oggpack_buffer *b); +extern void oggpack_writetrunc(oggpack_buffer *b,long bits); +extern void oggpack_writealign(oggpack_buffer *b); +extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits); +extern void oggpack_reset(oggpack_buffer *b); +extern void oggpack_writeclear(oggpack_buffer *b); +extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes); +extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits); +extern long oggpack_look(oggpack_buffer *b,int bits); +extern long oggpack_look1(oggpack_buffer *b); +extern void oggpack_adv(oggpack_buffer *b,int bits); +extern void oggpack_adv1(oggpack_buffer *b); +extern long oggpack_read(oggpack_buffer *b,int bits); +extern long oggpack_read1(oggpack_buffer *b); +extern long oggpack_bytes(oggpack_buffer *b); +extern long oggpack_bits(oggpack_buffer *b); +extern unsigned char *oggpack_get_buffer(oggpack_buffer *b); + +extern void oggpackB_writeinit(oggpack_buffer *b); +extern int oggpackB_writecheck(oggpack_buffer *b); +extern void oggpackB_writetrunc(oggpack_buffer *b,long bits); +extern void oggpackB_writealign(oggpack_buffer *b); +extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits); +extern void oggpackB_reset(oggpack_buffer *b); +extern void oggpackB_writeclear(oggpack_buffer *b); +extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes); +extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits); +extern long oggpackB_look(oggpack_buffer *b,int bits); +extern long oggpackB_look1(oggpack_buffer *b); +extern void oggpackB_adv(oggpack_buffer *b,int bits); +extern void oggpackB_adv1(oggpack_buffer *b); +extern long oggpackB_read(oggpack_buffer *b,int bits); +extern long oggpackB_read1(oggpack_buffer *b); +extern long oggpackB_bytes(oggpack_buffer *b); +extern long oggpackB_bits(oggpack_buffer *b); +extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b); + +/* Ogg BITSTREAM PRIMITIVES: encoding **************************/ + +extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op); +extern int ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov, + int count, long e_o_s, ogg_int64_t granulepos); +extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og); +extern int ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill); +extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og); +extern int ogg_stream_flush_fill(ogg_stream_state *os, ogg_page *og, int nfill); + +/* Ogg BITSTREAM PRIMITIVES: decoding **************************/ + +extern int ogg_sync_init(ogg_sync_state *oy); +extern int ogg_sync_clear(ogg_sync_state *oy); +extern int ogg_sync_reset(ogg_sync_state *oy); +extern int ogg_sync_destroy(ogg_sync_state *oy); +extern int ogg_sync_check(ogg_sync_state *oy); + +extern char *ogg_sync_buffer(ogg_sync_state *oy, long size); +extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes); +extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og); +extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og); +extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og); +extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op); +extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op); + +/* Ogg BITSTREAM PRIMITIVES: general ***************************/ + +extern int ogg_stream_init(ogg_stream_state *os,int serialno); +extern int ogg_stream_clear(ogg_stream_state *os); +extern int ogg_stream_reset(ogg_stream_state *os); +extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno); +extern int ogg_stream_destroy(ogg_stream_state *os); +extern int ogg_stream_check(ogg_stream_state *os); +extern int ogg_stream_eos(ogg_stream_state *os); + +extern void ogg_page_checksum_set(ogg_page *og); + +extern int ogg_page_version(const ogg_page *og); +extern int ogg_page_continued(const ogg_page *og); +extern int ogg_page_bos(const ogg_page *og); +extern int ogg_page_eos(const ogg_page *og); +extern ogg_int64_t ogg_page_granulepos(const ogg_page *og); +extern int ogg_page_serialno(const ogg_page *og); +extern long ogg_page_pageno(const ogg_page *og); +extern int ogg_page_packets(const ogg_page *og); + +extern void ogg_packet_clear(ogg_packet *op); + + +#ifdef __cplusplus +} +#endif + +#endif /* _OGG_H */ diff --git a/other/opus/include/ogg/os_types.h b/other/opus/include/ogg/os_types.h new file mode 100644 index 0000000..f5ea869 --- /dev/null +++ b/other/opus/include/ogg/os_types.h @@ -0,0 +1,35 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 * + * by the Xiph.Org Foundation http://www.xiph.org/ * + * * + ******************************************************************** + + function: #ifdef jail to whip a few platforms into the UNIX ideal. + last mod: $Id: os_types.h 19098 2014-02-26 19:06:45Z giles $ + + ********************************************************************/ +#ifndef _OS_TYPES_H +#define _OS_TYPES_H + +/* make it easy on the folks that want to compile the libs with a + different malloc than stdlib */ +#define _ogg_malloc malloc +#define _ogg_calloc calloc +#define _ogg_realloc realloc +#define _ogg_free free + +#include <stdint.h> +typedef int16_t ogg_int16_t; +typedef uint16_t ogg_uint16_t; +typedef int32_t ogg_int32_t; +typedef uint32_t ogg_uint32_t; +typedef int64_t ogg_int64_t; +typedef uint64_t ogg_uint64_t; + +#endif /* _OS_TYPES_H */ diff --git a/other/opus/include/opus/opus.h b/other/opus/include/opus/opus.h new file mode 100644 index 0000000..93a53a2 --- /dev/null +++ b/other/opus/include/opus/opus.h @@ -0,0 +1,978 @@ +/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited + Written by Jean-Marc Valin and Koen Vos */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file opus.h + * @brief Opus reference implementation API + */ + +#ifndef OPUS_H +#define OPUS_H + +#include "opus_types.h" +#include "opus_defines.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @mainpage Opus + * + * The Opus codec is designed for interactive speech and audio transmission over the Internet. + * It is designed by the IETF Codec Working Group and incorporates technology from + * Skype's SILK codec and Xiph.Org's CELT codec. + * + * The Opus codec is designed to handle a wide range of interactive audio applications, + * including Voice over IP, videoconferencing, in-game chat, and even remote live music + * performances. It can scale from low bit-rate narrowband speech to very high quality + * stereo music. Its main features are: + + * @li Sampling rates from 8 to 48 kHz + * @li Bit-rates from 6 kb/s to 510 kb/s + * @li Support for both constant bit-rate (CBR) and variable bit-rate (VBR) + * @li Audio bandwidth from narrowband to full-band + * @li Support for speech and music + * @li Support for mono and stereo + * @li Support for multichannel (up to 255 channels) + * @li Frame sizes from 2.5 ms to 60 ms + * @li Good loss robustness and packet loss concealment (PLC) + * @li Floating point and fixed-point implementation + * + * Documentation sections: + * @li @ref opus_encoder + * @li @ref opus_decoder + * @li @ref opus_repacketizer + * @li @ref opus_multistream + * @li @ref opus_libinfo + * @li @ref opus_custom + */ + +/** @defgroup opus_encoder Opus Encoder + * @{ + * + * @brief This page describes the process and functions used to encode Opus. + * + * Since Opus is a stateful codec, the encoding process starts with creating an encoder + * state. This can be done with: + * + * @code + * int error; + * OpusEncoder *enc; + * enc = opus_encoder_create(Fs, channels, application, &error); + * @endcode + * + * From this point, @c enc can be used for encoding an audio stream. An encoder state + * @b must @b not be used for more than one stream at the same time. Similarly, the encoder + * state @b must @b not be re-initialized for each frame. + * + * While opus_encoder_create() allocates memory for the state, it's also possible + * to initialize pre-allocated memory: + * + * @code + * int size; + * int error; + * OpusEncoder *enc; + * size = opus_encoder_get_size(channels); + * enc = malloc(size); + * error = opus_encoder_init(enc, Fs, channels, application); + * @endcode + * + * where opus_encoder_get_size() returns the required size for the encoder state. Note that + * future versions of this code may change the size, so no assuptions should be made about it. + * + * The encoder state is always continuous in memory and only a shallow copy is sufficient + * to copy it (e.g. memcpy()) + * + * It is possible to change some of the encoder's settings using the opus_encoder_ctl() + * interface. All these settings already default to the recommended value, so they should + * only be changed when necessary. The most common settings one may want to change are: + * + * @code + * opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate)); + * opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity)); + * opus_encoder_ctl(enc, OPUS_SET_SIGNAL(signal_type)); + * @endcode + * + * where + * + * @arg bitrate is in bits per second (b/s) + * @arg complexity is a value from 1 to 10, where 1 is the lowest complexity and 10 is the highest + * @arg signal_type is either OPUS_AUTO (default), OPUS_SIGNAL_VOICE, or OPUS_SIGNAL_MUSIC + * + * See @ref opus_encoderctls and @ref opus_genericctls for a complete list of parameters that can be set or queried. Most parameters can be set or changed at any time during a stream. + * + * To encode a frame, opus_encode() or opus_encode_float() must be called with exactly one frame (2.5, 5, 10, 20, 40 or 60 ms) of audio data: + * @code + * len = opus_encode(enc, audio_frame, frame_size, packet, max_packet); + * @endcode + * + * where + * <ul> + * <li>audio_frame is the audio data in opus_int16 (or float for opus_encode_float())</li> + * <li>frame_size is the duration of the frame in samples (per channel)</li> + * <li>packet is the byte array to which the compressed data is written</li> + * <li>max_packet is the maximum number of bytes that can be written in the packet (4000 bytes is recommended). + * Do not use max_packet to control VBR target bitrate, instead use the #OPUS_SET_BITRATE CTL.</li> + * </ul> + * + * opus_encode() and opus_encode_float() return the number of bytes actually written to the packet. + * The return value <b>can be negative</b>, which indicates that an error has occurred. If the return value + * is 1 byte, then the packet does not need to be transmitted (DTX). + * + * Once the encoder state if no longer needed, it can be destroyed with + * + * @code + * opus_encoder_destroy(enc); + * @endcode + * + * If the encoder was created with opus_encoder_init() rather than opus_encoder_create(), + * then no action is required aside from potentially freeing the memory that was manually + * allocated for it (calling free(enc) for the example above) + * + */ + +/** Opus encoder state. + * This contains the complete state of an Opus encoder. + * It is position independent and can be freely copied. + * @see opus_encoder_create,opus_encoder_init + */ +typedef struct OpusEncoder OpusEncoder; + +/** Gets the size of an <code>OpusEncoder</code> structure. + * @param[in] channels <tt>int</tt>: Number of channels. + * This must be 1 or 2. + * @returns The size in bytes. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_encoder_get_size(int channels); + +/** + */ + +/** Allocates and initializes an encoder state. + * There are three coding modes: + * + * @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice + * signals. It enhances the input signal by high-pass filtering and + * emphasizing formants and harmonics. Optionally it includes in-band + * forward error correction to protect against packet loss. Use this + * mode for typical VoIP applications. Because of the enhancement, + * even at high bitrates the output may sound different from the input. + * + * @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most + * non-voice signals like music. Use this mode for music and mixed + * (music/voice) content, broadcast, and applications requiring less + * than 15 ms of coding delay. + * + * @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that + * disables the speech-optimized mode in exchange for slightly reduced delay. + * This mode can only be set on an newly initialized or freshly reset encoder + * because it changes the codec delay. + * + * This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution). + * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz) + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal + * @param [in] application <tt>int</tt>: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY) + * @param [out] error <tt>int*</tt>: @ref opus_errorcodes + * @note Regardless of the sampling rate and number channels selected, the Opus encoder + * can switch to a lower audio bandwidth or number of channels if the bitrate + * selected is too low. This also means that it is safe to always use 48 kHz stereo input + * and let the encoder optimize the encoding. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusEncoder *opus_encoder_create( + opus_int32 Fs, + int channels, + int application, + int *error +); + +/** Initializes a previously allocated encoder state + * The memory pointed to by st must be at least the size returned by opus_encoder_get_size(). + * This is intended for applications which use their own allocator instead of malloc. + * @see opus_encoder_create(),opus_encoder_get_size() + * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. + * @param [in] st <tt>OpusEncoder*</tt>: Encoder state + * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz) + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal + * @param [in] application <tt>int</tt>: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY) + * @retval #OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_EXPORT int opus_encoder_init( + OpusEncoder *st, + opus_int32 Fs, + int channels, + int application +) OPUS_ARG_NONNULL(1); + +/** Encodes an Opus frame. + * @param [in] st <tt>OpusEncoder*</tt>: Encoder state + * @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16) + * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the + * input signal. + * This must be an Opus frame size for + * the encoder's sampling rate. + * For example, at 48 kHz the permitted + * values are 120, 240, 480, 960, 1920, + * and 2880. + * Passing in a duration of less than + * 10 ms (480 samples at 48 kHz) will + * prevent the encoder from using the LPC + * or hybrid modes. + * @param [out] data <tt>unsigned char*</tt>: Output payload. + * This must contain storage for at + * least \a max_data_bytes. + * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated + * memory for the output + * payload. This may be + * used to impose an upper limit on + * the instant bitrate, but should + * not be used as the only bitrate + * control. Use #OPUS_SET_BITRATE to + * control the bitrate. + * @returns The length of the encoded packet (in bytes) on success or a + * negative error code (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode( + OpusEncoder *st, + const opus_int16 *pcm, + int frame_size, + unsigned char *data, + opus_int32 max_data_bytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Encodes an Opus frame from floating point input. + * @param [in] st <tt>OpusEncoder*</tt>: Encoder state + * @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0. + * Samples with a range beyond +/-1.0 are supported but will + * be clipped by decoders using the integer API and should + * only be used if it is known that the far end supports + * extended dynamic range. + * length is frame_size*channels*sizeof(float) + * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the + * input signal. + * This must be an Opus frame size for + * the encoder's sampling rate. + * For example, at 48 kHz the permitted + * values are 120, 240, 480, 960, 1920, + * and 2880. + * Passing in a duration of less than + * 10 ms (480 samples at 48 kHz) will + * prevent the encoder from using the LPC + * or hybrid modes. + * @param [out] data <tt>unsigned char*</tt>: Output payload. + * This must contain storage for at + * least \a max_data_bytes. + * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated + * memory for the output + * payload. This may be + * used to impose an upper limit on + * the instant bitrate, but should + * not be used as the only bitrate + * control. Use #OPUS_SET_BITRATE to + * control the bitrate. + * @returns The length of the encoded packet (in bytes) on success or a + * negative error code (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode_float( + OpusEncoder *st, + const float *pcm, + int frame_size, + unsigned char *data, + opus_int32 max_data_bytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Frees an <code>OpusEncoder</code> allocated by opus_encoder_create(). + * @param[in] st <tt>OpusEncoder*</tt>: State to be freed. + */ +OPUS_EXPORT void opus_encoder_destroy(OpusEncoder *st); + +/** Perform a CTL function on an Opus encoder. + * + * Generally the request and subsequent arguments are generated + * by a convenience macro. + * @param st <tt>OpusEncoder*</tt>: Encoder state. + * @param request This and all remaining parameters should be replaced by one + * of the convenience macros in @ref opus_genericctls or + * @ref opus_encoderctls. + * @see opus_genericctls + * @see opus_encoderctls + */ +OPUS_EXPORT int opus_encoder_ctl(OpusEncoder *st, int request, ...) OPUS_ARG_NONNULL(1); +/**@}*/ + +/** @defgroup opus_decoder Opus Decoder + * @{ + * + * @brief This page describes the process and functions used to decode Opus. + * + * The decoding process also starts with creating a decoder + * state. This can be done with: + * @code + * int error; + * OpusDecoder *dec; + * dec = opus_decoder_create(Fs, channels, &error); + * @endcode + * where + * @li Fs is the sampling rate and must be 8000, 12000, 16000, 24000, or 48000 + * @li channels is the number of channels (1 or 2) + * @li error will hold the error code in case of failure (or #OPUS_OK on success) + * @li the return value is a newly created decoder state to be used for decoding + * + * While opus_decoder_create() allocates memory for the state, it's also possible + * to initialize pre-allocated memory: + * @code + * int size; + * int error; + * OpusDecoder *dec; + * size = opus_decoder_get_size(channels); + * dec = malloc(size); + * error = opus_decoder_init(dec, Fs, channels); + * @endcode + * where opus_decoder_get_size() returns the required size for the decoder state. Note that + * future versions of this code may change the size, so no assuptions should be made about it. + * + * The decoder state is always continuous in memory and only a shallow copy is sufficient + * to copy it (e.g. memcpy()) + * + * To decode a frame, opus_decode() or opus_decode_float() must be called with a packet of compressed audio data: + * @code + * frame_size = opus_decode(dec, packet, len, decoded, max_size, 0); + * @endcode + * where + * + * @li packet is the byte array containing the compressed data + * @li len is the exact number of bytes contained in the packet + * @li decoded is the decoded audio data in opus_int16 (or float for opus_decode_float()) + * @li max_size is the max duration of the frame in samples (per channel) that can fit into the decoded_frame array + * + * opus_decode() and opus_decode_float() return the number of samples (per channel) decoded from the packet. + * If that value is negative, then an error has occurred. This can occur if the packet is corrupted or if the audio + * buffer is too small to hold the decoded audio. + * + * Opus is a stateful codec with overlapping blocks and as a result Opus + * packets are not coded independently of each other. Packets must be + * passed into the decoder serially and in the correct order for a correct + * decode. Lost packets can be replaced with loss concealment by calling + * the decoder with a null pointer and zero length for the missing packet. + * + * A single codec state may only be accessed from a single thread at + * a time and any required locking must be performed by the caller. Separate + * streams must be decoded with separate decoder states and can be decoded + * in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK + * defined. + * + */ + +/** Opus decoder state. + * This contains the complete state of an Opus decoder. + * It is position independent and can be freely copied. + * @see opus_decoder_create,opus_decoder_init + */ +typedef struct OpusDecoder OpusDecoder; + +/** Gets the size of an <code>OpusDecoder</code> structure. + * @param [in] channels <tt>int</tt>: Number of channels. + * This must be 1 or 2. + * @returns The size in bytes. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_size(int channels); + +/** Allocates and initializes a decoder state. + * @param [in] Fs <tt>opus_int32</tt>: Sample rate to decode at (Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode + * @param [out] error <tt>int*</tt>: #OPUS_OK Success or @ref opus_errorcodes + * + * Internally Opus stores data at 48000 Hz, so that should be the default + * value for Fs. However, the decoder can efficiently decode to buffers + * at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use + * data at the full sample rate, or knows the compressed data doesn't + * use the full frequency range, it can request decoding at a reduced + * rate. Likewise, the decoder is capable of filling in either mono or + * interleaved stereo pcm buffers, at the caller's request. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusDecoder *opus_decoder_create( + opus_int32 Fs, + int channels, + int *error +); + +/** Initializes a previously allocated decoder state. + * The state must be at least the size returned by opus_decoder_get_size(). + * This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size + * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. + * @param [in] st <tt>OpusDecoder*</tt>: Decoder state. + * @param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode + * @retval #OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_EXPORT int opus_decoder_init( + OpusDecoder *st, + opus_int32 Fs, + int channels +) OPUS_ARG_NONNULL(1); + +/** Decode an Opus packet. + * @param [in] st <tt>OpusDecoder*</tt>: Decoder state + * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss + * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload* + * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(opus_int16) + * @param [in] frame_size Number of samples per channel of available space in \a pcm. + * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will + * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1), + * then frame_size needs to be exactly the duration of audio that is missing, otherwise the + * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and + * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms. + * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be + * decoded. If no such data is available, the frame is decoded as if it were lost. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode( + OpusDecoder *st, + const unsigned char *data, + opus_int32 len, + opus_int16 *pcm, + int frame_size, + int decode_fec +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Decode an Opus packet with floating point output. + * @param [in] st <tt>OpusDecoder*</tt>: Decoder state + * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss + * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload + * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(float) + * @param [in] frame_size Number of samples per channel of available space in \a pcm. + * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will + * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1), + * then frame_size needs to be exactly the duration of audio that is missing, otherwise the + * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and + * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms. + * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be + * decoded. If no such data is available the frame is decoded as if it were lost. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode_float( + OpusDecoder *st, + const unsigned char *data, + opus_int32 len, + float *pcm, + int frame_size, + int decode_fec +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Perform a CTL function on an Opus decoder. + * + * Generally the request and subsequent arguments are generated + * by a convenience macro. + * @param st <tt>OpusDecoder*</tt>: Decoder state. + * @param request This and all remaining parameters should be replaced by one + * of the convenience macros in @ref opus_genericctls or + * @ref opus_decoderctls. + * @see opus_genericctls + * @see opus_decoderctls + */ +OPUS_EXPORT int opus_decoder_ctl(OpusDecoder *st, int request, ...) OPUS_ARG_NONNULL(1); + +/** Frees an <code>OpusDecoder</code> allocated by opus_decoder_create(). + * @param[in] st <tt>OpusDecoder*</tt>: State to be freed. + */ +OPUS_EXPORT void opus_decoder_destroy(OpusDecoder *st); + +/** Parse an opus packet into one or more frames. + * Opus_decode will perform this operation internally so most applications do + * not need to use this function. + * This function does not copy the frames, the returned pointers are pointers into + * the input packet. + * @param [in] data <tt>char*</tt>: Opus packet to be parsed + * @param [in] len <tt>opus_int32</tt>: size of data + * @param [out] out_toc <tt>char*</tt>: TOC pointer + * @param [out] frames <tt>char*[48]</tt> encapsulated frames + * @param [out] size <tt>opus_int16[48]</tt> sizes of the encapsulated frames + * @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes) + * @returns number of frames + */ +OPUS_EXPORT int opus_packet_parse( + const unsigned char *data, + opus_int32 len, + unsigned char *out_toc, + const unsigned char *frames[48], + opus_int16 size[48], + int *payload_offset +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Gets the bandwidth of an Opus packet. + * @param [in] data <tt>char*</tt>: Opus packet + * @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass) + * @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass) + * @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass) + * @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass) + * @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass) + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_bandwidth(const unsigned char *data) OPUS_ARG_NONNULL(1); + +/** Gets the number of samples per frame from an Opus packet. + * @param [in] data <tt>char*</tt>: Opus packet. + * This must contain at least one byte of + * data. + * @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz. + * This must be a multiple of 400, or + * inaccurate results will be returned. + * @returns Number of samples per frame. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_samples_per_frame(const unsigned char *data, opus_int32 Fs) OPUS_ARG_NONNULL(1); + +/** Gets the number of channels from an Opus packet. + * @param [in] data <tt>char*</tt>: Opus packet + * @returns Number of channels + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_channels(const unsigned char *data) OPUS_ARG_NONNULL(1); + +/** Gets the number of frames in an Opus packet. + * @param [in] packet <tt>char*</tt>: Opus packet + * @param [in] len <tt>opus_int32</tt>: Length of packet + * @returns Number of frames + * @retval OPUS_BAD_ARG Insufficient data was passed to the function + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1); + +/** Gets the number of samples of an Opus packet. + * @param [in] packet <tt>char*</tt>: Opus packet + * @param [in] len <tt>opus_int32</tt>: Length of packet + * @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz. + * This must be a multiple of 400, or + * inaccurate results will be returned. + * @returns Number of samples + * @retval OPUS_BAD_ARG Insufficient data was passed to the function + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_samples(const unsigned char packet[], opus_int32 len, opus_int32 Fs) OPUS_ARG_NONNULL(1); + +/** Gets the number of samples of an Opus packet. + * @param [in] dec <tt>OpusDecoder*</tt>: Decoder state + * @param [in] packet <tt>char*</tt>: Opus packet + * @param [in] len <tt>opus_int32</tt>: Length of packet + * @returns Number of samples + * @retval OPUS_BAD_ARG Insufficient data was passed to the function + * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_nb_samples(const OpusDecoder *dec, const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); + +/** Applies soft-clipping to bring a float signal within the [-1,1] range. If + * the signal is already in that range, nothing is done. If there are values + * outside of [-1,1], then the signal is clipped as smoothly as possible to + * both fit in the range and avoid creating excessive distortion in the + * process. + * @param [in,out] pcm <tt>float*</tt>: Input PCM and modified PCM + * @param [in] frame_size <tt>int</tt> Number of samples per channel to process + * @param [in] channels <tt>int</tt>: Number of channels + * @param [in,out] softclip_mem <tt>float*</tt>: State memory for the soft clipping process (one float per channel, initialized to zero) + */ +OPUS_EXPORT void opus_pcm_soft_clip(float *pcm, int frame_size, int channels, float *softclip_mem); + + +/**@}*/ + +/** @defgroup opus_repacketizer Repacketizer + * @{ + * + * The repacketizer can be used to merge multiple Opus packets into a single + * packet or alternatively to split Opus packets that have previously been + * merged. Splitting valid Opus packets is always guaranteed to succeed, + * whereas merging valid packets only succeeds if all frames have the same + * mode, bandwidth, and frame size, and when the total duration of the merged + * packet is no more than 120 ms. + * The repacketizer currently only operates on elementary Opus + * streams. It will not manipualte multistream packets successfully, except in + * the degenerate case where they consist of data from a single stream. + * + * The repacketizing process starts with creating a repacketizer state, either + * by calling opus_repacketizer_create() or by allocating the memory yourself, + * e.g., + * @code + * OpusRepacketizer *rp; + * rp = (OpusRepacketizer*)malloc(opus_repacketizer_get_size()); + * if (rp != NULL) + * opus_repacketizer_init(rp); + * @endcode + * + * Then the application should submit packets with opus_repacketizer_cat(), + * extract new packets with opus_repacketizer_out() or + * opus_repacketizer_out_range(), and then reset the state for the next set of + * input packets via opus_repacketizer_init(). + * + * For example, to split a sequence of packets into individual frames: + * @code + * unsigned char *data; + * int len; + * while (get_next_packet(&data, &len)) + * { + * unsigned char out[1276]; + * opus_int32 out_len; + * int nb_frames; + * int err; + * int i; + * err = opus_repacketizer_cat(rp, data, len); + * if (err != OPUS_OK) + * { + * release_packet(data); + * return err; + * } + * nb_frames = opus_repacketizer_get_nb_frames(rp); + * for (i = 0; i < nb_frames; i++) + * { + * out_len = opus_repacketizer_out_range(rp, i, i+1, out, sizeof(out)); + * if (out_len < 0) + * { + * release_packet(data); + * return (int)out_len; + * } + * output_next_packet(out, out_len); + * } + * opus_repacketizer_init(rp); + * release_packet(data); + * } + * @endcode + * + * Alternatively, to combine a sequence of frames into packets that each + * contain up to <code>TARGET_DURATION_MS</code> milliseconds of data: + * @code + * // The maximum number of packets with duration TARGET_DURATION_MS occurs + * // when the frame size is 2.5 ms, for a total of (TARGET_DURATION_MS*2/5) + * // packets. + * unsigned char *data[(TARGET_DURATION_MS*2/5)+1]; + * opus_int32 len[(TARGET_DURATION_MS*2/5)+1]; + * int nb_packets; + * unsigned char out[1277*(TARGET_DURATION_MS*2/2)]; + * opus_int32 out_len; + * int prev_toc; + * nb_packets = 0; + * while (get_next_packet(data+nb_packets, len+nb_packets)) + * { + * int nb_frames; + * int err; + * nb_frames = opus_packet_get_nb_frames(data[nb_packets], len[nb_packets]); + * if (nb_frames < 1) + * { + * release_packets(data, nb_packets+1); + * return nb_frames; + * } + * nb_frames += opus_repacketizer_get_nb_frames(rp); + * // If adding the next packet would exceed our target, or it has an + * // incompatible TOC sequence, output the packets we already have before + * // submitting it. + * // N.B., The nb_packets > 0 check ensures we've submitted at least one + * // packet since the last call to opus_repacketizer_init(). Otherwise a + * // single packet longer than TARGET_DURATION_MS would cause us to try to + * // output an (invalid) empty packet. It also ensures that prev_toc has + * // been set to a valid value. Additionally, len[nb_packets] > 0 is + * // guaranteed by the call to opus_packet_get_nb_frames() above, so the + * // reference to data[nb_packets][0] should be valid. + * if (nb_packets > 0 && ( + * ((prev_toc & 0xFC) != (data[nb_packets][0] & 0xFC)) || + * opus_packet_get_samples_per_frame(data[nb_packets], 48000)*nb_frames > + * TARGET_DURATION_MS*48)) + * { + * out_len = opus_repacketizer_out(rp, out, sizeof(out)); + * if (out_len < 0) + * { + * release_packets(data, nb_packets+1); + * return (int)out_len; + * } + * output_next_packet(out, out_len); + * opus_repacketizer_init(rp); + * release_packets(data, nb_packets); + * data[0] = data[nb_packets]; + * len[0] = len[nb_packets]; + * nb_packets = 0; + * } + * err = opus_repacketizer_cat(rp, data[nb_packets], len[nb_packets]); + * if (err != OPUS_OK) + * { + * release_packets(data, nb_packets+1); + * return err; + * } + * prev_toc = data[nb_packets][0]; + * nb_packets++; + * } + * // Output the final, partial packet. + * if (nb_packets > 0) + * { + * out_len = opus_repacketizer_out(rp, out, sizeof(out)); + * release_packets(data, nb_packets); + * if (out_len < 0) + * return (int)out_len; + * output_next_packet(out, out_len); + * } + * @endcode + * + * An alternate way of merging packets is to simply call opus_repacketizer_cat() + * unconditionally until it fails. At that point, the merged packet can be + * obtained with opus_repacketizer_out() and the input packet for which + * opus_repacketizer_cat() needs to be re-added to a newly reinitialized + * repacketizer state. + */ + +typedef struct OpusRepacketizer OpusRepacketizer; + +/** Gets the size of an <code>OpusRepacketizer</code> structure. + * @returns The size in bytes. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_size(void); + +/** (Re)initializes a previously allocated repacketizer state. + * The state must be at least the size returned by opus_repacketizer_get_size(). + * This can be used for applications which use their own allocator instead of + * malloc(). + * It must also be called to reset the queue of packets waiting to be + * repacketized, which is necessary if the maximum packet duration of 120 ms + * is reached or if you wish to submit packets with a different Opus + * configuration (coding mode, audio bandwidth, frame size, or channel count). + * Failure to do so will prevent a new packet from being added with + * opus_repacketizer_cat(). + * @see opus_repacketizer_create + * @see opus_repacketizer_get_size + * @see opus_repacketizer_cat + * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to + * (re)initialize. + * @returns A pointer to the same repacketizer state that was passed in. + */ +OPUS_EXPORT OpusRepacketizer *opus_repacketizer_init(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1); + +/** Allocates memory and initializes the new repacketizer with + * opus_repacketizer_init(). + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusRepacketizer *opus_repacketizer_create(void); + +/** Frees an <code>OpusRepacketizer</code> allocated by + * opus_repacketizer_create(). + * @param[in] rp <tt>OpusRepacketizer*</tt>: State to be freed. + */ +OPUS_EXPORT void opus_repacketizer_destroy(OpusRepacketizer *rp); + +/** Add a packet to the current repacketizer state. + * This packet must match the configuration of any packets already submitted + * for repacketization since the last call to opus_repacketizer_init(). + * This means that it must have the same coding mode, audio bandwidth, frame + * size, and channel count. + * This can be checked in advance by examining the top 6 bits of the first + * byte of the packet, and ensuring they match the top 6 bits of the first + * byte of any previously submitted packet. + * The total duration of audio in the repacketizer state also must not exceed + * 120 ms, the maximum duration of a single packet, after adding this packet. + * + * The contents of the current repacketizer state can be extracted into new + * packets using opus_repacketizer_out() or opus_repacketizer_out_range(). + * + * In order to add a packet with a different configuration or to add more + * audio beyond 120 ms, you must clear the repacketizer state by calling + * opus_repacketizer_init(). + * If a packet is too large to add to the current repacketizer state, no part + * of it is added, even if it contains multiple frames, some of which might + * fit. + * If you wish to be able to add parts of such packets, you should first use + * another repacketizer to split the packet into pieces and add them + * individually. + * @see opus_repacketizer_out_range + * @see opus_repacketizer_out + * @see opus_repacketizer_init + * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to + * add the packet. + * @param[in] data <tt>const unsigned char*</tt>: The packet data. + * The application must ensure + * this pointer remains valid + * until the next call to + * opus_repacketizer_init() or + * opus_repacketizer_destroy(). + * @param len <tt>opus_int32</tt>: The number of bytes in the packet data. + * @returns An error code indicating whether or not the operation succeeded. + * @retval #OPUS_OK The packet's contents have been added to the repacketizer + * state. + * @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence, + * the packet's TOC sequence was not compatible + * with previously submitted packets (because + * the coding mode, audio bandwidth, frame size, + * or channel count did not match), or adding + * this packet would increase the total amount of + * audio stored in the repacketizer state to more + * than 120 ms. + */ +OPUS_EXPORT int opus_repacketizer_cat(OpusRepacketizer *rp, const unsigned char *data, opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); + + +/** Construct a new packet from data previously submitted to the repacketizer + * state via opus_repacketizer_cat(). + * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to + * construct the new packet. + * @param begin <tt>int</tt>: The index of the first frame in the current + * repacketizer state to include in the output. + * @param end <tt>int</tt>: One past the index of the last frame in the + * current repacketizer state to include in the + * output. + * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to + * store the output packet. + * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in + * the output buffer. In order to guarantee + * success, this should be at least + * <code>1276</code> for a single frame, + * or for multiple frames, + * <code>1277*(end-begin)</code>. + * However, <code>1*(end-begin)</code> plus + * the size of all packet data submitted to + * the repacketizer since the last call to + * opus_repacketizer_init() or + * opus_repacketizer_create() is also + * sufficient, and possibly much smaller. + * @returns The total size of the output packet on success, or an error code + * on failure. + * @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of + * frames (begin < 0, begin >= end, or end > + * opus_repacketizer_get_nb_frames()). + * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the + * complete output packet. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out_range(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Return the total number of frames contained in packet data submitted to + * the repacketizer state so far via opus_repacketizer_cat() since the last + * call to opus_repacketizer_init() or opus_repacketizer_create(). + * This defines the valid range of packets that can be extracted with + * opus_repacketizer_out_range() or opus_repacketizer_out(). + * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state containing the + * frames. + * @returns The total number of frames contained in the packet data submitted + * to the repacketizer state. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_nb_frames(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1); + +/** Construct a new packet from data previously submitted to the repacketizer + * state via opus_repacketizer_cat(). + * This is a convenience routine that returns all the data submitted so far + * in a single packet. + * It is equivalent to calling + * @code + * opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp), + * data, maxlen) + * @endcode + * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to + * construct the new packet. + * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to + * store the output packet. + * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in + * the output buffer. In order to guarantee + * success, this should be at least + * <code>1277*opus_repacketizer_get_nb_frames(rp)</code>. + * However, + * <code>1*opus_repacketizer_get_nb_frames(rp)</code> + * plus the size of all packet data + * submitted to the repacketizer since the + * last call to opus_repacketizer_init() or + * opus_repacketizer_create() is also + * sufficient, and possibly much smaller. + * @returns The total size of the output packet on success, or an error code + * on failure. + * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the + * complete output packet. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out(OpusRepacketizer *rp, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1); + +/** Pads a given Opus packet to a larger size (possibly changing the TOC sequence). + * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the + * packet to pad. + * @param len <tt>opus_int32</tt>: The size of the packet. + * This must be at least 1. + * @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding. + * This must be at least as large as len. + * @returns an error code + * @retval #OPUS_OK \a on success. + * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len. + * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. + */ +OPUS_EXPORT int opus_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len); + +/** Remove all padding from a given Opus packet and rewrite the TOC sequence to + * minimize space usage. + * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the + * packet to strip. + * @param len <tt>opus_int32</tt>: The size of the packet. + * This must be at least 1. + * @returns The new size of the output packet on success, or an error code + * on failure. + * @retval #OPUS_BAD_ARG \a len was less than 1. + * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_packet_unpad(unsigned char *data, opus_int32 len); + +/** Pads a given Opus multi-stream packet to a larger size (possibly changing the TOC sequence). + * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the + * packet to pad. + * @param len <tt>opus_int32</tt>: The size of the packet. + * This must be at least 1. + * @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding. + * This must be at least 1. + * @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet. + * This must be at least as large as len. + * @returns an error code + * @retval #OPUS_OK \a on success. + * @retval #OPUS_BAD_ARG \a len was less than 1. + * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. + */ +OPUS_EXPORT int opus_multistream_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len, int nb_streams); + +/** Remove all padding from a given Opus multi-stream packet and rewrite the TOC sequence to + * minimize space usage. + * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the + * packet to strip. + * @param len <tt>opus_int32</tt>: The size of the packet. + * This must be at least 1. + * @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet. + * This must be at least 1. + * @returns The new size of the output packet on success, or an error code + * on failure. + * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len. + * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_packet_unpad(unsigned char *data, opus_int32 len, int nb_streams); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* OPUS_H */ diff --git a/other/opus/include/opus/opus_custom.h b/other/opus/include/opus/opus_custom.h new file mode 100644 index 0000000..41f36bf --- /dev/null +++ b/other/opus/include/opus/opus_custom.h @@ -0,0 +1,342 @@ +/* Copyright (c) 2007-2008 CSIRO + Copyright (c) 2007-2009 Xiph.Org Foundation + Copyright (c) 2008-2012 Gregory Maxwell + Written by Jean-Marc Valin and Gregory Maxwell */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + @file opus_custom.h + @brief Opus-Custom reference implementation API + */ + +#ifndef OPUS_CUSTOM_H +#define OPUS_CUSTOM_H + +#include "opus_defines.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef CUSTOM_MODES +# define OPUS_CUSTOM_EXPORT OPUS_EXPORT +# define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT +#else +# define OPUS_CUSTOM_EXPORT +# ifdef OPUS_BUILD +# define OPUS_CUSTOM_EXPORT_STATIC static OPUS_INLINE +# else +# define OPUS_CUSTOM_EXPORT_STATIC +# endif +#endif + +/** @defgroup opus_custom Opus Custom + * @{ + * Opus Custom is an optional part of the Opus specification and + * reference implementation which uses a distinct API from the regular + * API and supports frame sizes that are not normally supported.\ Use + * of Opus Custom is discouraged for all but very special applications + * for which a frame size different from 2.5, 5, 10, or 20 ms is needed + * (for either complexity or latency reasons) and where interoperability + * is less important. + * + * In addition to the interoperability limitations the use of Opus custom + * disables a substantial chunk of the codec and generally lowers the + * quality available at a given bitrate. Normally when an application needs + * a different frame size from the codec it should buffer to match the + * sizes but this adds a small amount of delay which may be important + * in some very low latency applications. Some transports (especially + * constant rate RF transports) may also work best with frames of + * particular durations. + * + * Libopus only supports custom modes if they are enabled at compile time. + * + * The Opus Custom API is similar to the regular API but the + * @ref opus_encoder_create and @ref opus_decoder_create calls take + * an additional mode parameter which is a structure produced by + * a call to @ref opus_custom_mode_create. Both the encoder and decoder + * must create a mode using the same sample rate (fs) and frame size + * (frame size) so these parameters must either be signaled out of band + * or fixed in a particular implementation. + * + * Similar to regular Opus the custom modes support on the fly frame size + * switching, but the sizes available depend on the particular frame size in + * use. For some initial frame sizes on a single on the fly size is available. + */ + +/** Contains the state of an encoder. One encoder state is needed + for each stream. It is initialized once at the beginning of the + stream. Do *not* re-initialize the state for every frame. + @brief Encoder state + */ +typedef struct OpusCustomEncoder OpusCustomEncoder; + +/** State of the decoder. One decoder state is needed for each stream. + It is initialized once at the beginning of the stream. Do *not* + re-initialize the state for every frame. + @brief Decoder state + */ +typedef struct OpusCustomDecoder OpusCustomDecoder; + +/** The mode contains all the information necessary to create an + encoder. Both the encoder and decoder need to be initialized + with exactly the same mode, otherwise the output will be + corrupted. + @brief Mode configuration + */ +typedef struct OpusCustomMode OpusCustomMode; + +/** Creates a new mode struct. This will be passed to an encoder or + * decoder. The mode MUST NOT BE DESTROYED until the encoders and + * decoders that use it are destroyed as well. + * @param [in] Fs <tt>int</tt>: Sampling rate (8000 to 96000 Hz) + * @param [in] frame_size <tt>int</tt>: Number of samples (per channel) to encode in each + * packet (64 - 1024, prime factorization must contain zero or more 2s, 3s, or 5s and no other primes) + * @param [out] error <tt>int*</tt>: Returned error code (if NULL, no error will be returned) + * @return A newly created mode + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomMode *opus_custom_mode_create(opus_int32 Fs, int frame_size, int *error); + +/** Destroys a mode struct. Only call this after all encoders and + * decoders using this mode are destroyed as well. + * @param [in] mode <tt>OpusCustomMode*</tt>: Mode to be freed. + */ +OPUS_CUSTOM_EXPORT void opus_custom_mode_destroy(OpusCustomMode *mode); + + +#if !defined(OPUS_BUILD) || defined(CELT_ENCODER_C) + +/* Encoder */ +/** Gets the size of an OpusCustomEncoder structure. + * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration + * @param [in] channels <tt>int</tt>: Number of channels + * @returns size + */ +OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_encoder_get_size( + const OpusCustomMode *mode, + int channels +) OPUS_ARG_NONNULL(1); + +# ifdef CUSTOM_MODES +/** Initializes a previously allocated encoder state + * The memory pointed to by st must be the size returned by opus_custom_encoder_get_size. + * This is intended for applications which use their own allocator instead of malloc. + * @see opus_custom_encoder_create(),opus_custom_encoder_get_size() + * To reset a previously initialized state use the OPUS_RESET_STATE CTL. + * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state + * @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of + * the stream (must be the same characteristics as used for the + * decoder) + * @param [in] channels <tt>int</tt>: Number of channels + * @return OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_CUSTOM_EXPORT int opus_custom_encoder_init( + OpusCustomEncoder *st, + const OpusCustomMode *mode, + int channels +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); +# endif +#endif + + +/** Creates a new encoder state. Each stream needs its own encoder + * state (can't be shared across simultaneous streams). + * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of + * the stream (must be the same characteristics as used for the + * decoder) + * @param [in] channels <tt>int</tt>: Number of channels + * @param [out] error <tt>int*</tt>: Returns an error code + * @return Newly created encoder state. +*/ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomEncoder *opus_custom_encoder_create( + const OpusCustomMode *mode, + int channels, + int *error +) OPUS_ARG_NONNULL(1); + + +/** Destroys a an encoder state. + * @param[in] st <tt>OpusCustomEncoder*</tt>: State to be freed. + */ +OPUS_CUSTOM_EXPORT void opus_custom_encoder_destroy(OpusCustomEncoder *st); + +/** Encodes a frame of audio. + * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state + * @param [in] pcm <tt>float*</tt>: PCM audio in float format, with a normal range of +/-1.0. + * Samples with a range beyond +/-1.0 are supported but will + * be clipped by decoders using the integer API and should + * only be used if it is known that the far end supports + * extended dynamic range. There must be exactly + * frame_size samples per channel. + * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal + * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long. + * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame + * (can change from one frame to another) + * @return Number of bytes written to "compressed". + * If negative, an error has occurred (see error codes). It is IMPORTANT that + * the length returned be somehow transmitted to the decoder. Otherwise, no + * decoding is possible. + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode_float( + OpusCustomEncoder *st, + const float *pcm, + int frame_size, + unsigned char *compressed, + int maxCompressedBytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Encodes a frame of audio. + * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state + * @param [in] pcm <tt>opus_int16*</tt>: PCM audio in signed 16-bit format (native endian). + * There must be exactly frame_size samples per channel. + * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal + * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long. + * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame + * (can change from one frame to another) + * @return Number of bytes written to "compressed". + * If negative, an error has occurred (see error codes). It is IMPORTANT that + * the length returned be somehow transmitted to the decoder. Otherwise, no + * decoding is possible. + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode( + OpusCustomEncoder *st, + const opus_int16 *pcm, + int frame_size, + unsigned char *compressed, + int maxCompressedBytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Perform a CTL function on an Opus custom encoder. + * + * Generally the request and subsequent arguments are generated + * by a convenience macro. + * @see opus_encoderctls + */ +OPUS_CUSTOM_EXPORT int opus_custom_encoder_ctl(OpusCustomEncoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1); + + +#if !defined(OPUS_BUILD) || defined(CELT_DECODER_C) +/* Decoder */ + +/** Gets the size of an OpusCustomDecoder structure. + * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration + * @param [in] channels <tt>int</tt>: Number of channels + * @returns size + */ +OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_decoder_get_size( + const OpusCustomMode *mode, + int channels +) OPUS_ARG_NONNULL(1); + +/** Initializes a previously allocated decoder state + * The memory pointed to by st must be the size returned by opus_custom_decoder_get_size. + * This is intended for applications which use their own allocator instead of malloc. + * @see opus_custom_decoder_create(),opus_custom_decoder_get_size() + * To reset a previously initialized state use the OPUS_RESET_STATE CTL. + * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state + * @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of + * the stream (must be the same characteristics as used for the + * encoder) + * @param [in] channels <tt>int</tt>: Number of channels + * @return OPUS_OK Success or @ref opus_errorcodes + */ +OPUS_CUSTOM_EXPORT_STATIC int opus_custom_decoder_init( + OpusCustomDecoder *st, + const OpusCustomMode *mode, + int channels +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); + +#endif + + +/** Creates a new decoder state. Each stream needs its own decoder state (can't + * be shared across simultaneous streams). + * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the + * stream (must be the same characteristics as used for the encoder) + * @param [in] channels <tt>int</tt>: Number of channels + * @param [out] error <tt>int*</tt>: Returns an error code + * @return Newly created decoder state. + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomDecoder *opus_custom_decoder_create( + const OpusCustomMode *mode, + int channels, + int *error +) OPUS_ARG_NONNULL(1); + +/** Destroys a an decoder state. + * @param[in] st <tt>OpusCustomDecoder*</tt>: State to be freed. + */ +OPUS_CUSTOM_EXPORT void opus_custom_decoder_destroy(OpusCustomDecoder *st); + +/** Decode an opus custom frame with floating point output + * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state + * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss + * @param [in] len <tt>int</tt>: Number of bytes in payload + * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(float) + * @param [in] frame_size Number of samples per channel of available space in *pcm. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode_float( + OpusCustomDecoder *st, + const unsigned char *data, + int len, + float *pcm, + int frame_size +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Decode an opus custom frame + * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state + * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss + * @param [in] len <tt>int</tt>: Number of bytes in payload + * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length + * is frame_size*channels*sizeof(opus_int16) + * @param [in] frame_size Number of samples per channel of available space in *pcm. + * @returns Number of decoded samples or @ref opus_errorcodes + */ +OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode( + OpusCustomDecoder *st, + const unsigned char *data, + int len, + opus_int16 *pcm, + int frame_size +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Perform a CTL function on an Opus custom decoder. + * + * Generally the request and subsequent arguments are generated + * by a convenience macro. + * @see opus_genericctls + */ +OPUS_CUSTOM_EXPORT int opus_custom_decoder_ctl(OpusCustomDecoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1); + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* OPUS_CUSTOM_H */ diff --git a/other/opus/include/opus/opus_defines.h b/other/opus/include/opus/opus_defines.h new file mode 100644 index 0000000..265089f --- /dev/null +++ b/other/opus/include/opus/opus_defines.h @@ -0,0 +1,726 @@ +/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited + Written by Jean-Marc Valin and Koen Vos */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file opus_defines.h + * @brief Opus reference implementation constants + */ + +#ifndef OPUS_DEFINES_H +#define OPUS_DEFINES_H + +#include "opus_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @defgroup opus_errorcodes Error codes + * @{ + */ +/** No error @hideinitializer*/ +#define OPUS_OK 0 +/** One or more invalid/out of range arguments @hideinitializer*/ +#define OPUS_BAD_ARG -1 +/** The mode struct passed is invalid @hideinitializer*/ +#define OPUS_BUFFER_TOO_SMALL -2 +/** An internal error was detected @hideinitializer*/ +#define OPUS_INTERNAL_ERROR -3 +/** The compressed data passed is corrupted @hideinitializer*/ +#define OPUS_INVALID_PACKET -4 +/** Invalid/unsupported request number @hideinitializer*/ +#define OPUS_UNIMPLEMENTED -5 +/** An encoder or decoder structure is invalid or already freed @hideinitializer*/ +#define OPUS_INVALID_STATE -6 +/** Memory allocation has failed @hideinitializer*/ +#define OPUS_ALLOC_FAIL -7 +/**@}*/ + +/** @cond OPUS_INTERNAL_DOC */ +/**Export control for opus functions */ + +#ifndef OPUS_EXPORT +# if defined(WIN32) +# ifdef OPUS_BUILD +# define OPUS_EXPORT __declspec(dllexport) +# else +# define OPUS_EXPORT +# endif +# elif defined(__GNUC__) && defined(OPUS_BUILD) +# define OPUS_EXPORT __attribute__ ((visibility ("default"))) +# else +# define OPUS_EXPORT +# endif +#endif + +# if !defined(OPUS_GNUC_PREREQ) +# if defined(__GNUC__)&&defined(__GNUC_MINOR__) +# define OPUS_GNUC_PREREQ(_maj,_min) \ + ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) +# else +# define OPUS_GNUC_PREREQ(_maj,_min) 0 +# endif +# endif + +#if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if OPUS_GNUC_PREREQ(3,0) +# define OPUS_RESTRICT __restrict__ +# elif (defined(_MSC_VER) && _MSC_VER >= 1400) +# define OPUS_RESTRICT __restrict +# else +# define OPUS_RESTRICT +# endif +#else +# define OPUS_RESTRICT restrict +#endif + +#if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if OPUS_GNUC_PREREQ(2,7) +# define OPUS_INLINE __inline__ +# elif (defined(_MSC_VER)) +# define OPUS_INLINE __inline +# else +# define OPUS_INLINE +# endif +#else +# define OPUS_INLINE inline +#endif + +/**Warning attributes for opus functions + * NONNULL is not used in OPUS_BUILD to avoid the compiler optimizing out + * some paranoid null checks. */ +#if defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4) +# define OPUS_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__)) +#else +# define OPUS_WARN_UNUSED_RESULT +#endif +#if !defined(OPUS_BUILD) && defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4) +# define OPUS_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x))) +#else +# define OPUS_ARG_NONNULL(_x) +#endif + +/** These are the actual Encoder CTL ID numbers. + * They should not be used directly by applications. + * In general, SETs should be even and GETs should be odd.*/ +#define OPUS_SET_APPLICATION_REQUEST 4000 +#define OPUS_GET_APPLICATION_REQUEST 4001 +#define OPUS_SET_BITRATE_REQUEST 4002 +#define OPUS_GET_BITRATE_REQUEST 4003 +#define OPUS_SET_MAX_BANDWIDTH_REQUEST 4004 +#define OPUS_GET_MAX_BANDWIDTH_REQUEST 4005 +#define OPUS_SET_VBR_REQUEST 4006 +#define OPUS_GET_VBR_REQUEST 4007 +#define OPUS_SET_BANDWIDTH_REQUEST 4008 +#define OPUS_GET_BANDWIDTH_REQUEST 4009 +#define OPUS_SET_COMPLEXITY_REQUEST 4010 +#define OPUS_GET_COMPLEXITY_REQUEST 4011 +#define OPUS_SET_INBAND_FEC_REQUEST 4012 +#define OPUS_GET_INBAND_FEC_REQUEST 4013 +#define OPUS_SET_PACKET_LOSS_PERC_REQUEST 4014 +#define OPUS_GET_PACKET_LOSS_PERC_REQUEST 4015 +#define OPUS_SET_DTX_REQUEST 4016 +#define OPUS_GET_DTX_REQUEST 4017 +#define OPUS_SET_VBR_CONSTRAINT_REQUEST 4020 +#define OPUS_GET_VBR_CONSTRAINT_REQUEST 4021 +#define OPUS_SET_FORCE_CHANNELS_REQUEST 4022 +#define OPUS_GET_FORCE_CHANNELS_REQUEST 4023 +#define OPUS_SET_SIGNAL_REQUEST 4024 +#define OPUS_GET_SIGNAL_REQUEST 4025 +#define OPUS_GET_LOOKAHEAD_REQUEST 4027 +/* #define OPUS_RESET_STATE 4028 */ +#define OPUS_GET_SAMPLE_RATE_REQUEST 4029 +#define OPUS_GET_FINAL_RANGE_REQUEST 4031 +#define OPUS_GET_PITCH_REQUEST 4033 +#define OPUS_SET_GAIN_REQUEST 4034 +#define OPUS_GET_GAIN_REQUEST 4045 /* Should have been 4035 */ +#define OPUS_SET_LSB_DEPTH_REQUEST 4036 +#define OPUS_GET_LSB_DEPTH_REQUEST 4037 +#define OPUS_GET_LAST_PACKET_DURATION_REQUEST 4039 +#define OPUS_SET_EXPERT_FRAME_DURATION_REQUEST 4040 +#define OPUS_GET_EXPERT_FRAME_DURATION_REQUEST 4041 +#define OPUS_SET_PREDICTION_DISABLED_REQUEST 4042 +#define OPUS_GET_PREDICTION_DISABLED_REQUEST 4043 + +/* Don't use 4045, it's already taken by OPUS_GET_GAIN_REQUEST */ + +/* Macros to trigger compilation errors when the wrong types are provided to a CTL */ +#define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x)) +#define __opus_check_int_ptr(ptr) ((ptr) + ((ptr) - (opus_int32*)(ptr))) +#define __opus_check_uint_ptr(ptr) ((ptr) + ((ptr) - (opus_uint32*)(ptr))) +#define __opus_check_val16_ptr(ptr) ((ptr) + ((ptr) - (opus_val16*)(ptr))) +/** @endcond */ + +/** @defgroup opus_ctlvalues Pre-defined values for CTL interface + * @see opus_genericctls, opus_encoderctls + * @{ + */ +/* Values for the various encoder CTLs */ +#define OPUS_AUTO -1000 /**<Auto/default setting @hideinitializer*/ +#define OPUS_BITRATE_MAX -1 /**<Maximum bitrate @hideinitializer*/ + +/** Best for most VoIP/videoconference applications where listening quality and intelligibility matter most + * @hideinitializer */ +#define OPUS_APPLICATION_VOIP 2048 +/** Best for broadcast/high-fidelity application where the decoded audio should be as close as possible to the input + * @hideinitializer */ +#define OPUS_APPLICATION_AUDIO 2049 +/** Only use when lowest-achievable latency is what matters most. Voice-optimized modes cannot be used. + * @hideinitializer */ +#define OPUS_APPLICATION_RESTRICTED_LOWDELAY 2051 + +#define OPUS_SIGNAL_VOICE 3001 /**< Signal being encoded is voice */ +#define OPUS_SIGNAL_MUSIC 3002 /**< Signal being encoded is music */ +#define OPUS_BANDWIDTH_NARROWBAND 1101 /**< 4 kHz bandpass @hideinitializer*/ +#define OPUS_BANDWIDTH_MEDIUMBAND 1102 /**< 6 kHz bandpass @hideinitializer*/ +#define OPUS_BANDWIDTH_WIDEBAND 1103 /**< 8 kHz bandpass @hideinitializer*/ +#define OPUS_BANDWIDTH_SUPERWIDEBAND 1104 /**<12 kHz bandpass @hideinitializer*/ +#define OPUS_BANDWIDTH_FULLBAND 1105 /**<20 kHz bandpass @hideinitializer*/ + +#define OPUS_FRAMESIZE_ARG 5000 /**< Select frame size from the argument (default) */ +#define OPUS_FRAMESIZE_2_5_MS 5001 /**< Use 2.5 ms frames */ +#define OPUS_FRAMESIZE_5_MS 5002 /**< Use 5 ms frames */ +#define OPUS_FRAMESIZE_10_MS 5003 /**< Use 10 ms frames */ +#define OPUS_FRAMESIZE_20_MS 5004 /**< Use 20 ms frames */ +#define OPUS_FRAMESIZE_40_MS 5005 /**< Use 40 ms frames */ +#define OPUS_FRAMESIZE_60_MS 5006 /**< Use 60 ms frames */ + +/**@}*/ + + +/** @defgroup opus_encoderctls Encoder related CTLs + * + * These are convenience macros for use with the \c opus_encode_ctl + * interface. They are used to generate the appropriate series of + * arguments for that call, passing the correct type, size and so + * on as expected for each particular request. + * + * Some usage examples: + * + * @code + * int ret; + * ret = opus_encoder_ctl(enc_ctx, OPUS_SET_BANDWIDTH(OPUS_AUTO)); + * if (ret != OPUS_OK) return ret; + * + * opus_int32 rate; + * opus_encoder_ctl(enc_ctx, OPUS_GET_BANDWIDTH(&rate)); + * + * opus_encoder_ctl(enc_ctx, OPUS_RESET_STATE); + * @endcode + * + * @see opus_genericctls, opus_encoder + * @{ + */ + +/** Configures the encoder's computational complexity. + * The supported range is 0-10 inclusive with 10 representing the highest complexity. + * @see OPUS_GET_COMPLEXITY + * @param[in] x <tt>opus_int32</tt>: Allowed values: 0-10, inclusive. + * + * @hideinitializer */ +#define OPUS_SET_COMPLEXITY(x) OPUS_SET_COMPLEXITY_REQUEST, __opus_check_int(x) +/** Gets the encoder's complexity configuration. + * @see OPUS_SET_COMPLEXITY + * @param[out] x <tt>opus_int32 *</tt>: Returns a value in the range 0-10, + * inclusive. + * @hideinitializer */ +#define OPUS_GET_COMPLEXITY(x) OPUS_GET_COMPLEXITY_REQUEST, __opus_check_int_ptr(x) + +/** Configures the bitrate in the encoder. + * Rates from 500 to 512000 bits per second are meaningful, as well as the + * special values #OPUS_AUTO and #OPUS_BITRATE_MAX. + * The value #OPUS_BITRATE_MAX can be used to cause the codec to use as much + * rate as it can, which is useful for controlling the rate by adjusting the + * output buffer size. + * @see OPUS_GET_BITRATE + * @param[in] x <tt>opus_int32</tt>: Bitrate in bits per second. The default + * is determined based on the number of + * channels and the input sampling rate. + * @hideinitializer */ +#define OPUS_SET_BITRATE(x) OPUS_SET_BITRATE_REQUEST, __opus_check_int(x) +/** Gets the encoder's bitrate configuration. + * @see OPUS_SET_BITRATE + * @param[out] x <tt>opus_int32 *</tt>: Returns the bitrate in bits per second. + * The default is determined based on the + * number of channels and the input + * sampling rate. + * @hideinitializer */ +#define OPUS_GET_BITRATE(x) OPUS_GET_BITRATE_REQUEST, __opus_check_int_ptr(x) + +/** Enables or disables variable bitrate (VBR) in the encoder. + * The configured bitrate may not be met exactly because frames must + * be an integer number of bytes in length. + * @warning Only the MDCT mode of Opus can provide hard CBR behavior. + * @see OPUS_GET_VBR + * @see OPUS_SET_VBR_CONSTRAINT + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>0</dt><dd>Hard CBR. For LPC/hybrid modes at very low bit-rate, this can + * cause noticeable quality degradation.</dd> + * <dt>1</dt><dd>VBR (default). The exact type of VBR is controlled by + * #OPUS_SET_VBR_CONSTRAINT.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_VBR(x) OPUS_SET_VBR_REQUEST, __opus_check_int(x) +/** Determine if variable bitrate (VBR) is enabled in the encoder. + * @see OPUS_SET_VBR + * @see OPUS_GET_VBR_CONSTRAINT + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>0</dt><dd>Hard CBR.</dd> + * <dt>1</dt><dd>VBR (default). The exact type of VBR may be retrieved via + * #OPUS_GET_VBR_CONSTRAINT.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_VBR(x) OPUS_GET_VBR_REQUEST, __opus_check_int_ptr(x) + +/** Enables or disables constrained VBR in the encoder. + * This setting is ignored when the encoder is in CBR mode. + * @warning Only the MDCT mode of Opus currently heeds the constraint. + * Speech mode ignores it completely, hybrid mode may fail to obey it + * if the LPC layer uses more bitrate than the constraint would have + * permitted. + * @see OPUS_GET_VBR_CONSTRAINT + * @see OPUS_SET_VBR + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>0</dt><dd>Unconstrained VBR.</dd> + * <dt>1</dt><dd>Constrained VBR (default). This creates a maximum of one + * frame of buffering delay assuming a transport with a + * serialization speed of the nominal bitrate.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_VBR_CONSTRAINT(x) OPUS_SET_VBR_CONSTRAINT_REQUEST, __opus_check_int(x) +/** Determine if constrained VBR is enabled in the encoder. + * @see OPUS_SET_VBR_CONSTRAINT + * @see OPUS_GET_VBR + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>0</dt><dd>Unconstrained VBR.</dd> + * <dt>1</dt><dd>Constrained VBR (default).</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_VBR_CONSTRAINT(x) OPUS_GET_VBR_CONSTRAINT_REQUEST, __opus_check_int_ptr(x) + +/** Configures mono/stereo forcing in the encoder. + * This can force the encoder to produce packets encoded as either mono or + * stereo, regardless of the format of the input audio. This is useful when + * the caller knows that the input signal is currently a mono source embedded + * in a stereo stream. + * @see OPUS_GET_FORCE_CHANNELS + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>#OPUS_AUTO</dt><dd>Not forced (default)</dd> + * <dt>1</dt> <dd>Forced mono</dd> + * <dt>2</dt> <dd>Forced stereo</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_FORCE_CHANNELS(x) OPUS_SET_FORCE_CHANNELS_REQUEST, __opus_check_int(x) +/** Gets the encoder's forced channel configuration. + * @see OPUS_SET_FORCE_CHANNELS + * @param[out] x <tt>opus_int32 *</tt>: + * <dl> + * <dt>#OPUS_AUTO</dt><dd>Not forced (default)</dd> + * <dt>1</dt> <dd>Forced mono</dd> + * <dt>2</dt> <dd>Forced stereo</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_FORCE_CHANNELS(x) OPUS_GET_FORCE_CHANNELS_REQUEST, __opus_check_int_ptr(x) + +/** Configures the maximum bandpass that the encoder will select automatically. + * Applications should normally use this instead of #OPUS_SET_BANDWIDTH + * (leaving that set to the default, #OPUS_AUTO). This allows the + * application to set an upper bound based on the type of input it is + * providing, but still gives the encoder the freedom to reduce the bandpass + * when the bitrate becomes too low, for better overall quality. + * @see OPUS_GET_MAX_BANDWIDTH + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd> + * <dt>OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd> + * <dt>OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd> + * <dt>OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd> + * <dt>OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband (default)</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_MAX_BANDWIDTH(x) OPUS_SET_MAX_BANDWIDTH_REQUEST, __opus_check_int(x) + +/** Gets the encoder's configured maximum allowed bandpass. + * @see OPUS_SET_MAX_BANDWIDTH + * @param[out] x <tt>opus_int32 *</tt>: Allowed values: + * <dl> + * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband (default)</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_MAX_BANDWIDTH(x) OPUS_GET_MAX_BANDWIDTH_REQUEST, __opus_check_int_ptr(x) + +/** Sets the encoder's bandpass to a specific value. + * This prevents the encoder from automatically selecting the bandpass based + * on the available bitrate. If an application knows the bandpass of the input + * audio it is providing, it should normally use #OPUS_SET_MAX_BANDWIDTH + * instead, which still gives the encoder the freedom to reduce the bandpass + * when the bitrate becomes too low, for better overall quality. + * @see OPUS_GET_BANDWIDTH + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>#OPUS_AUTO</dt> <dd>(default)</dd> + * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_BANDWIDTH(x) OPUS_SET_BANDWIDTH_REQUEST, __opus_check_int(x) + +/** Configures the type of signal being encoded. + * This is a hint which helps the encoder's mode selection. + * @see OPUS_GET_SIGNAL + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>#OPUS_AUTO</dt> <dd>(default)</dd> + * <dt>#OPUS_SIGNAL_VOICE</dt><dd>Bias thresholds towards choosing LPC or Hybrid modes.</dd> + * <dt>#OPUS_SIGNAL_MUSIC</dt><dd>Bias thresholds towards choosing MDCT modes.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_SIGNAL(x) OPUS_SET_SIGNAL_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured signal type. + * @see OPUS_SET_SIGNAL + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>#OPUS_AUTO</dt> <dd>(default)</dd> + * <dt>#OPUS_SIGNAL_VOICE</dt><dd>Bias thresholds towards choosing LPC or Hybrid modes.</dd> + * <dt>#OPUS_SIGNAL_MUSIC</dt><dd>Bias thresholds towards choosing MDCT modes.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_SIGNAL(x) OPUS_GET_SIGNAL_REQUEST, __opus_check_int_ptr(x) + + +/** Configures the encoder's intended application. + * The initial value is a mandatory argument to the encoder_create function. + * @see OPUS_GET_APPLICATION + * @param[in] x <tt>opus_int32</tt>: Returns one of the following values: + * <dl> + * <dt>#OPUS_APPLICATION_VOIP</dt> + * <dd>Process signal for improved speech intelligibility.</dd> + * <dt>#OPUS_APPLICATION_AUDIO</dt> + * <dd>Favor faithfulness to the original input.</dd> + * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> + * <dd>Configure the minimum possible coding delay by disabling certain modes + * of operation.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_APPLICATION(x) OPUS_SET_APPLICATION_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured application. + * @see OPUS_SET_APPLICATION + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>#OPUS_APPLICATION_VOIP</dt> + * <dd>Process signal for improved speech intelligibility.</dd> + * <dt>#OPUS_APPLICATION_AUDIO</dt> + * <dd>Favor faithfulness to the original input.</dd> + * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> + * <dd>Configure the minimum possible coding delay by disabling certain modes + * of operation.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_APPLICATION(x) OPUS_GET_APPLICATION_REQUEST, __opus_check_int_ptr(x) + +/** Gets the sampling rate the encoder or decoder was initialized with. + * This simply returns the <code>Fs</code> value passed to opus_encoder_init() + * or opus_decoder_init(). + * @param[out] x <tt>opus_int32 *</tt>: Sampling rate of encoder or decoder. + * @hideinitializer + */ +#define OPUS_GET_SAMPLE_RATE(x) OPUS_GET_SAMPLE_RATE_REQUEST, __opus_check_int_ptr(x) + +/** Gets the total samples of delay added by the entire codec. + * This can be queried by the encoder and then the provided number of samples can be + * skipped on from the start of the decoder's output to provide time aligned input + * and output. From the perspective of a decoding application the real data begins this many + * samples late. + * + * The decoder contribution to this delay is identical for all decoders, but the + * encoder portion of the delay may vary from implementation to implementation, + * version to version, or even depend on the encoder's initial configuration. + * Applications needing delay compensation should call this CTL rather than + * hard-coding a value. + * @param[out] x <tt>opus_int32 *</tt>: Number of lookahead samples + * @hideinitializer */ +#define OPUS_GET_LOOKAHEAD(x) OPUS_GET_LOOKAHEAD_REQUEST, __opus_check_int_ptr(x) + +/** Configures the encoder's use of inband forward error correction (FEC). + * @note This is only applicable to the LPC layer + * @see OPUS_GET_INBAND_FEC + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>0</dt><dd>Disable inband FEC (default).</dd> + * <dt>1</dt><dd>Enable inband FEC.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_INBAND_FEC(x) OPUS_SET_INBAND_FEC_REQUEST, __opus_check_int(x) +/** Gets encoder's configured use of inband forward error correction. + * @see OPUS_SET_INBAND_FEC + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>0</dt><dd>Inband FEC disabled (default).</dd> + * <dt>1</dt><dd>Inband FEC enabled.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_INBAND_FEC(x) OPUS_GET_INBAND_FEC_REQUEST, __opus_check_int_ptr(x) + +/** Configures the encoder's expected packet loss percentage. + * Higher values with trigger progressively more loss resistant behavior in the encoder + * at the expense of quality at a given bitrate in the lossless case, but greater quality + * under loss. + * @see OPUS_GET_PACKET_LOSS_PERC + * @param[in] x <tt>opus_int32</tt>: Loss percentage in the range 0-100, inclusive (default: 0). + * @hideinitializer */ +#define OPUS_SET_PACKET_LOSS_PERC(x) OPUS_SET_PACKET_LOSS_PERC_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured packet loss percentage. + * @see OPUS_SET_PACKET_LOSS_PERC + * @param[out] x <tt>opus_int32 *</tt>: Returns the configured loss percentage + * in the range 0-100, inclusive (default: 0). + * @hideinitializer */ +#define OPUS_GET_PACKET_LOSS_PERC(x) OPUS_GET_PACKET_LOSS_PERC_REQUEST, __opus_check_int_ptr(x) + +/** Configures the encoder's use of discontinuous transmission (DTX). + * @note This is only applicable to the LPC layer + * @see OPUS_GET_DTX + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>0</dt><dd>Disable DTX (default).</dd> + * <dt>1</dt><dd>Enabled DTX.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_DTX(x) OPUS_SET_DTX_REQUEST, __opus_check_int(x) +/** Gets encoder's configured use of discontinuous transmission. + * @see OPUS_SET_DTX + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>0</dt><dd>DTX disabled (default).</dd> + * <dt>1</dt><dd>DTX enabled.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_DTX(x) OPUS_GET_DTX_REQUEST, __opus_check_int_ptr(x) +/** Configures the depth of signal being encoded. + * This is a hint which helps the encoder identify silence and near-silence. + * @see OPUS_GET_LSB_DEPTH + * @param[in] x <tt>opus_int32</tt>: Input precision in bits, between 8 and 24 + * (default: 24). + * @hideinitializer */ +#define OPUS_SET_LSB_DEPTH(x) OPUS_SET_LSB_DEPTH_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured signal depth. + * @see OPUS_SET_LSB_DEPTH + * @param[out] x <tt>opus_int32 *</tt>: Input precision in bits, between 8 and + * 24 (default: 24). + * @hideinitializer */ +#define OPUS_GET_LSB_DEPTH(x) OPUS_GET_LSB_DEPTH_REQUEST, __opus_check_int_ptr(x) + +/** Gets the duration (in samples) of the last packet successfully decoded or concealed. + * @param[out] x <tt>opus_int32 *</tt>: Number of samples (at current sampling rate). + * @hideinitializer */ +#define OPUS_GET_LAST_PACKET_DURATION(x) OPUS_GET_LAST_PACKET_DURATION_REQUEST, __opus_check_int_ptr(x) + +/** Configures the encoder's use of variable duration frames. + * When variable duration is enabled, the encoder is free to use a shorter frame + * size than the one requested in the opus_encode*() call. + * It is then the user's responsibility + * to verify how much audio was encoded by checking the ToC byte of the encoded + * packet. The part of the audio that was not encoded needs to be resent to the + * encoder for the next call. Do not use this option unless you <b>really</b> + * know what you are doing. + * @see OPUS_GET_EXPERT_VARIABLE_DURATION + * @param[in] x <tt>opus_int32</tt>: Allowed values: + * <dl> + * <dt>OPUS_FRAMESIZE_ARG</dt><dd>Select frame size from the argument (default).</dd> + * <dt>OPUS_FRAMESIZE_2_5_MS</dt><dd>Use 2.5 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 2.5 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_10_MS</dt><dd>Use 10 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_20_MS</dt><dd>Use 20 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_40_MS</dt><dd>Use 40 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_60_MS</dt><dd>Use 60 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_VARIABLE</dt><dd>Optimize the frame size dynamically.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_SET_EXPERT_FRAME_DURATION(x) OPUS_SET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured use of variable duration frames. + * @see OPUS_SET_EXPERT_VARIABLE_DURATION + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>OPUS_FRAMESIZE_ARG</dt><dd>Select frame size from the argument (default).</dd> + * <dt>OPUS_FRAMESIZE_2_5_MS</dt><dd>Use 2.5 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_5_MS</dt><dd>Use 2.5 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_10_MS</dt><dd>Use 10 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_20_MS</dt><dd>Use 20 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_40_MS</dt><dd>Use 40 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_60_MS</dt><dd>Use 60 ms frames.</dd> + * <dt>OPUS_FRAMESIZE_VARIABLE</dt><dd>Optimize the frame size dynamically.</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_EXPERT_FRAME_DURATION(x) OPUS_GET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int_ptr(x) + +/** If set to 1, disables almost all use of prediction, making frames almost + completely independent. This reduces quality. (default : 0) + * @hideinitializer */ +#define OPUS_SET_PREDICTION_DISABLED(x) OPUS_SET_PREDICTION_DISABLED_REQUEST, __opus_check_int(x) +/** Gets the encoder's configured prediction status. + * @hideinitializer */ +#define OPUS_GET_PREDICTION_DISABLED(x) OPUS_GET_PREDICTION_DISABLED_REQUEST, __opus_check_int_ptr(x) + +/**@}*/ + +/** @defgroup opus_genericctls Generic CTLs + * + * These macros are used with the \c opus_decoder_ctl and + * \c opus_encoder_ctl calls to generate a particular + * request. + * + * When called on an \c OpusDecoder they apply to that + * particular decoder instance. When called on an + * \c OpusEncoder they apply to the corresponding setting + * on that encoder instance, if present. + * + * Some usage examples: + * + * @code + * int ret; + * opus_int32 pitch; + * ret = opus_decoder_ctl(dec_ctx, OPUS_GET_PITCH(&pitch)); + * if (ret == OPUS_OK) return ret; + * + * opus_encoder_ctl(enc_ctx, OPUS_RESET_STATE); + * opus_decoder_ctl(dec_ctx, OPUS_RESET_STATE); + * + * opus_int32 enc_bw, dec_bw; + * opus_encoder_ctl(enc_ctx, OPUS_GET_BANDWIDTH(&enc_bw)); + * opus_decoder_ctl(dec_ctx, OPUS_GET_BANDWIDTH(&dec_bw)); + * if (enc_bw != dec_bw) { + * printf("packet bandwidth mismatch!\n"); + * } + * @endcode + * + * @see opus_encoder, opus_decoder_ctl, opus_encoder_ctl, opus_decoderctls, opus_encoderctls + * @{ + */ + +/** Resets the codec state to be equivalent to a freshly initialized state. + * This should be called when switching streams in order to prevent + * the back to back decoding from giving different results from + * one at a time decoding. + * @hideinitializer */ +#define OPUS_RESET_STATE 4028 + +/** Gets the final state of the codec's entropy coder. + * This is used for testing purposes, + * The encoder and decoder state should be identical after coding a payload + * (assuming no data corruption or software bugs) + * + * @param[out] x <tt>opus_uint32 *</tt>: Entropy coder state + * + * @hideinitializer */ +#define OPUS_GET_FINAL_RANGE(x) OPUS_GET_FINAL_RANGE_REQUEST, __opus_check_uint_ptr(x) + +/** Gets the pitch of the last decoded frame, if available. + * This can be used for any post-processing algorithm requiring the use of pitch, + * e.g. time stretching/shortening. If the last frame was not voiced, or if the + * pitch was not coded in the frame, then zero is returned. + * + * This CTL is only implemented for decoder instances. + * + * @param[out] x <tt>opus_int32 *</tt>: pitch period at 48 kHz (or 0 if not available) + * + * @hideinitializer */ +#define OPUS_GET_PITCH(x) OPUS_GET_PITCH_REQUEST, __opus_check_int_ptr(x) + +/** Gets the encoder's configured bandpass or the decoder's last bandpass. + * @see OPUS_SET_BANDWIDTH + * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values: + * <dl> + * <dt>#OPUS_AUTO</dt> <dd>(default)</dd> + * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd> + * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband</dd> + * </dl> + * @hideinitializer */ +#define OPUS_GET_BANDWIDTH(x) OPUS_GET_BANDWIDTH_REQUEST, __opus_check_int_ptr(x) + +/**@}*/ + +/** @defgroup opus_decoderctls Decoder related CTLs + * @see opus_genericctls, opus_encoderctls, opus_decoder + * @{ + */ + +/** Configures decoder gain adjustment. + * Scales the decoded output by a factor specified in Q8 dB units. + * This has a maximum range of -32768 to 32767 inclusive, and returns + * OPUS_BAD_ARG otherwise. The default is zero indicating no adjustment. + * This setting survives decoder reset. + * + * gain = pow(10, x/(20.0*256)) + * + * @param[in] x <tt>opus_int32</tt>: Amount to scale PCM signal by in Q8 dB units. + * @hideinitializer */ +#define OPUS_SET_GAIN(x) OPUS_SET_GAIN_REQUEST, __opus_check_int(x) +/** Gets the decoder's configured gain adjustment. @see OPUS_SET_GAIN + * + * @param[out] x <tt>opus_int32 *</tt>: Amount to scale PCM signal by in Q8 dB units. + * @hideinitializer */ +#define OPUS_GET_GAIN(x) OPUS_GET_GAIN_REQUEST, __opus_check_int_ptr(x) + +/**@}*/ + +/** @defgroup opus_libinfo Opus library information functions + * @{ + */ + +/** Converts an opus error code into a human readable string. + * + * @param[in] error <tt>int</tt>: Error number + * @returns Error string + */ +OPUS_EXPORT const char *opus_strerror(int error); + +/** Gets the libopus version string. + * + * @returns Version string + */ +OPUS_EXPORT const char *opus_get_version_string(void); +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* OPUS_DEFINES_H */ diff --git a/other/opus/include/opus/opus_multistream.h b/other/opus/include/opus/opus_multistream.h new file mode 100644 index 0000000..ae59979 --- /dev/null +++ b/other/opus/include/opus/opus_multistream.h @@ -0,0 +1,660 @@ +/* Copyright (c) 2011 Xiph.Org Foundation + Written by Jean-Marc Valin */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/** + * @file opus_multistream.h + * @brief Opus reference implementation multistream API + */ + +#ifndef OPUS_MULTISTREAM_H +#define OPUS_MULTISTREAM_H + +#include "opus.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @cond OPUS_INTERNAL_DOC */ + +/** Macros to trigger compilation errors when the wrong types are provided to a + * CTL. */ +/**@{*/ +#define __opus_check_encstate_ptr(ptr) ((ptr) + ((ptr) - (OpusEncoder**)(ptr))) +#define __opus_check_decstate_ptr(ptr) ((ptr) + ((ptr) - (OpusDecoder**)(ptr))) +/**@}*/ + +/** These are the actual encoder and decoder CTL ID numbers. + * They should not be used directly by applications. + * In general, SETs should be even and GETs should be odd.*/ +/**@{*/ +#define OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST 5120 +#define OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST 5122 +/**@}*/ + +/** @endcond */ + +/** @defgroup opus_multistream_ctls Multistream specific encoder and decoder CTLs + * + * These are convenience macros that are specific to the + * opus_multistream_encoder_ctl() and opus_multistream_decoder_ctl() + * interface. + * The CTLs from @ref opus_genericctls, @ref opus_encoderctls, and + * @ref opus_decoderctls may be applied to a multistream encoder or decoder as + * well. + * In addition, you may retrieve the encoder or decoder state for an specific + * stream via #OPUS_MULTISTREAM_GET_ENCODER_STATE or + * #OPUS_MULTISTREAM_GET_DECODER_STATE and apply CTLs to it individually. + */ +/**@{*/ + +/** Gets the encoder state for an individual stream of a multistream encoder. + * @param[in] x <tt>opus_int32</tt>: The index of the stream whose encoder you + * wish to retrieve. + * This must be non-negative and less than + * the <code>streams</code> parameter used + * to initialize the encoder. + * @param[out] y <tt>OpusEncoder**</tt>: Returns a pointer to the given + * encoder state. + * @retval OPUS_BAD_ARG The index of the requested stream was out of range. + * @hideinitializer + */ +#define OPUS_MULTISTREAM_GET_ENCODER_STATE(x,y) OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST, __opus_check_int(x), __opus_check_encstate_ptr(y) + +/** Gets the decoder state for an individual stream of a multistream decoder. + * @param[in] x <tt>opus_int32</tt>: The index of the stream whose decoder you + * wish to retrieve. + * This must be non-negative and less than + * the <code>streams</code> parameter used + * to initialize the decoder. + * @param[out] y <tt>OpusDecoder**</tt>: Returns a pointer to the given + * decoder state. + * @retval OPUS_BAD_ARG The index of the requested stream was out of range. + * @hideinitializer + */ +#define OPUS_MULTISTREAM_GET_DECODER_STATE(x,y) OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST, __opus_check_int(x), __opus_check_decstate_ptr(y) + +/**@}*/ + +/** @defgroup opus_multistream Opus Multistream API + * @{ + * + * The multistream API allows individual Opus streams to be combined into a + * single packet, enabling support for up to 255 channels. Unlike an + * elementary Opus stream, the encoder and decoder must negotiate the channel + * configuration before the decoder can successfully interpret the data in the + * packets produced by the encoder. Some basic information, such as packet + * duration, can be computed without any special negotiation. + * + * The format for multistream Opus packets is defined in the + * <a href="http://tools.ietf.org/html/draft-terriberry-oggopus">Ogg + * encapsulation specification</a> and is based on the self-delimited Opus + * framing described in Appendix B of <a href="http://tools.ietf.org/html/rfc6716">RFC 6716</a>. + * Normal Opus packets are just a degenerate case of multistream Opus packets, + * and can be encoded or decoded with the multistream API by setting + * <code>streams</code> to <code>1</code> when initializing the encoder or + * decoder. + * + * Multistream Opus streams can contain up to 255 elementary Opus streams. + * These may be either "uncoupled" or "coupled", indicating that the decoder + * is configured to decode them to either 1 or 2 channels, respectively. + * The streams are ordered so that all coupled streams appear at the + * beginning. + * + * A <code>mapping</code> table defines which decoded channel <code>i</code> + * should be used for each input/output (I/O) channel <code>j</code>. This table is + * typically provided as an unsigned char array. + * Let <code>i = mapping[j]</code> be the index for I/O channel <code>j</code>. + * If <code>i < 2*coupled_streams</code>, then I/O channel <code>j</code> is + * encoded as the left channel of stream <code>(i/2)</code> if <code>i</code> + * is even, or as the right channel of stream <code>(i/2)</code> if + * <code>i</code> is odd. Otherwise, I/O channel <code>j</code> is encoded as + * mono in stream <code>(i - coupled_streams)</code>, unless it has the special + * value 255, in which case it is omitted from the encoding entirely (the + * decoder will reproduce it as silence). Each value <code>i</code> must either + * be the special value 255 or be less than <code>streams + coupled_streams</code>. + * + * The output channels specified by the encoder + * should use the + * <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis + * channel ordering</a>. A decoder may wish to apply an additional permutation + * to the mapping the encoder used to achieve a different output channel + * order (e.g. for outputing in WAV order). + * + * Each multistream packet contains an Opus packet for each stream, and all of + * the Opus packets in a single multistream packet must have the same + * duration. Therefore the duration of a multistream packet can be extracted + * from the TOC sequence of the first stream, which is located at the + * beginning of the packet, just like an elementary Opus stream: + * + * @code + * int nb_samples; + * int nb_frames; + * nb_frames = opus_packet_get_nb_frames(data, len); + * if (nb_frames < 1) + * return nb_frames; + * nb_samples = opus_packet_get_samples_per_frame(data, 48000) * nb_frames; + * @endcode + * + * The general encoding and decoding process proceeds exactly the same as in + * the normal @ref opus_encoder and @ref opus_decoder APIs. + * See their documentation for an overview of how to use the corresponding + * multistream functions. + */ + +/** Opus multistream encoder state. + * This contains the complete state of a multistream Opus encoder. + * It is position independent and can be freely copied. + * @see opus_multistream_encoder_create + * @see opus_multistream_encoder_init + */ +typedef struct OpusMSEncoder OpusMSEncoder; + +/** Opus multistream decoder state. + * This contains the complete state of a multistream Opus decoder. + * It is position independent and can be freely copied. + * @see opus_multistream_decoder_create + * @see opus_multistream_decoder_init + */ +typedef struct OpusMSDecoder OpusMSDecoder; + +/**\name Multistream encoder functions */ +/**@{*/ + +/** Gets the size of an OpusMSEncoder structure. + * @param streams <tt>int</tt>: The total number of streams to encode from the + * input. + * This must be no more than 255. + * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams + * to encode. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * encoded channels (<code>streams + + * coupled_streams</code>) must be no + * more than 255. + * @returns The size in bytes on success, or a negative error code + * (see @ref opus_errorcodes) on error. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_encoder_get_size( + int streams, + int coupled_streams +); + +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_surround_encoder_get_size( + int channels, + int mapping_family +); + + +/** Allocates and initializes a multistream encoder state. + * Call opus_multistream_encoder_destroy() to release + * this object when finished. + * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param channels <tt>int</tt>: Number of channels in the input signal. + * This must be at most 255. + * It may be greater than the number of + * coded channels (<code>streams + + * coupled_streams</code>). + * @param streams <tt>int</tt>: The total number of streams to encode from the + * input. + * This must be no more than the number of channels. + * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams + * to encode. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * encoded channels (<code>streams + + * coupled_streams</code>) must be no + * more than the number of input channels. + * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from + * encoded channels to input channels, as described in + * @ref opus_multistream. As an extra constraint, the + * multistream encoder does not allow encoding coupled + * streams for which one channel is unused since this + * is never a good idea. + * @param application <tt>int</tt>: The target encoder application. + * This must be one of the following: + * <dl> + * <dt>#OPUS_APPLICATION_VOIP</dt> + * <dd>Process signal for improved speech intelligibility.</dd> + * <dt>#OPUS_APPLICATION_AUDIO</dt> + * <dd>Favor faithfulness to the original input.</dd> + * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> + * <dd>Configure the minimum possible coding delay by disabling certain modes + * of operation.</dd> + * </dl> + * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error + * code (see @ref opus_errorcodes) on + * failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSEncoder *opus_multistream_encoder_create( + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int application, + int *error +) OPUS_ARG_NONNULL(5); + +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSEncoder *opus_multistream_surround_encoder_create( + opus_int32 Fs, + int channels, + int mapping_family, + int *streams, + int *coupled_streams, + unsigned char *mapping, + int application, + int *error +) OPUS_ARG_NONNULL(5); + +/** Initialize a previously allocated multistream encoder state. + * The memory pointed to by \a st must be at least the size returned by + * opus_multistream_encoder_get_size(). + * This is intended for applications which use their own allocator instead of + * malloc. + * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. + * @see opus_multistream_encoder_create + * @see opus_multistream_encoder_get_size + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize. + * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param channels <tt>int</tt>: Number of channels in the input signal. + * This must be at most 255. + * It may be greater than the number of + * coded channels (<code>streams + + * coupled_streams</code>). + * @param streams <tt>int</tt>: The total number of streams to encode from the + * input. + * This must be no more than the number of channels. + * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams + * to encode. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * encoded channels (<code>streams + + * coupled_streams</code>) must be no + * more than the number of input channels. + * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from + * encoded channels to input channels, as described in + * @ref opus_multistream. As an extra constraint, the + * multistream encoder does not allow encoding coupled + * streams for which one channel is unused since this + * is never a good idea. + * @param application <tt>int</tt>: The target encoder application. + * This must be one of the following: + * <dl> + * <dt>#OPUS_APPLICATION_VOIP</dt> + * <dd>Process signal for improved speech intelligibility.</dd> + * <dt>#OPUS_APPLICATION_AUDIO</dt> + * <dd>Favor faithfulness to the original input.</dd> + * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt> + * <dd>Configure the minimum possible coding delay by disabling certain modes + * of operation.</dd> + * </dl> + * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) + * on failure. + */ +OPUS_EXPORT int opus_multistream_encoder_init( + OpusMSEncoder *st, + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int application +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); + +OPUS_EXPORT int opus_multistream_surround_encoder_init( + OpusMSEncoder *st, + opus_int32 Fs, + int channels, + int mapping_family, + int *streams, + int *coupled_streams, + unsigned char *mapping, + int application +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); + +/** Encodes a multistream Opus frame. + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. + * @param[in] pcm <tt>const opus_int16*</tt>: The input signal as interleaved + * samples. + * This must contain + * <code>frame_size*channels</code> + * samples. + * @param frame_size <tt>int</tt>: Number of samples per channel in the input + * signal. + * This must be an Opus frame size for the + * encoder's sampling rate. + * For example, at 48 kHz the permitted values + * are 120, 240, 480, 960, 1920, and 2880. + * Passing in a duration of less than 10 ms + * (480 samples at 48 kHz) will prevent the + * encoder from using the LPC or hybrid modes. + * @param[out] data <tt>unsigned char*</tt>: Output payload. + * This must contain storage for at + * least \a max_data_bytes. + * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated + * memory for the output + * payload. This may be + * used to impose an upper limit on + * the instant bitrate, but should + * not be used as the only bitrate + * control. Use #OPUS_SET_BITRATE to + * control the bitrate. + * @returns The length of the encoded packet (in bytes) on success or a + * negative error code (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_encode( + OpusMSEncoder *st, + const opus_int16 *pcm, + int frame_size, + unsigned char *data, + opus_int32 max_data_bytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Encodes a multistream Opus frame from floating point input. + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. + * @param[in] pcm <tt>const float*</tt>: The input signal as interleaved + * samples with a normal range of + * +/-1.0. + * Samples with a range beyond +/-1.0 + * are supported but will be clipped by + * decoders using the integer API and + * should only be used if it is known + * that the far end supports extended + * dynamic range. + * This must contain + * <code>frame_size*channels</code> + * samples. + * @param frame_size <tt>int</tt>: Number of samples per channel in the input + * signal. + * This must be an Opus frame size for the + * encoder's sampling rate. + * For example, at 48 kHz the permitted values + * are 120, 240, 480, 960, 1920, and 2880. + * Passing in a duration of less than 10 ms + * (480 samples at 48 kHz) will prevent the + * encoder from using the LPC or hybrid modes. + * @param[out] data <tt>unsigned char*</tt>: Output payload. + * This must contain storage for at + * least \a max_data_bytes. + * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated + * memory for the output + * payload. This may be + * used to impose an upper limit on + * the instant bitrate, but should + * not be used as the only bitrate + * control. Use #OPUS_SET_BITRATE to + * control the bitrate. + * @returns The length of the encoded packet (in bytes) on success or a + * negative error code (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_encode_float( + OpusMSEncoder *st, + const float *pcm, + int frame_size, + unsigned char *data, + opus_int32 max_data_bytes +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); + +/** Frees an <code>OpusMSEncoder</code> allocated by + * opus_multistream_encoder_create(). + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to be freed. + */ +OPUS_EXPORT void opus_multistream_encoder_destroy(OpusMSEncoder *st); + +/** Perform a CTL function on a multistream Opus encoder. + * + * Generally the request and subsequent arguments are generated by a + * convenience macro. + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state. + * @param request This and all remaining parameters should be replaced by one + * of the convenience macros in @ref opus_genericctls, + * @ref opus_encoderctls, or @ref opus_multistream_ctls. + * @see opus_genericctls + * @see opus_encoderctls + * @see opus_multistream_ctls + */ +OPUS_EXPORT int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...) OPUS_ARG_NONNULL(1); + +/**@}*/ + +/**\name Multistream decoder functions */ +/**@{*/ + +/** Gets the size of an <code>OpusMSDecoder</code> structure. + * @param streams <tt>int</tt>: The total number of streams coded in the + * input. + * This must be no more than 255. + * @param coupled_streams <tt>int</tt>: Number streams to decode as coupled + * (2 channel) streams. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * coded channels (<code>streams + + * coupled_streams</code>) must be no + * more than 255. + * @returns The size in bytes on success, or a negative error code + * (see @ref opus_errorcodes) on error. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_decoder_get_size( + int streams, + int coupled_streams +); + +/** Allocates and initializes a multistream decoder state. + * Call opus_multistream_decoder_destroy() to release + * this object when finished. + * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param channels <tt>int</tt>: Number of channels to output. + * This must be at most 255. + * It may be different from the number of coded + * channels (<code>streams + + * coupled_streams</code>). + * @param streams <tt>int</tt>: The total number of streams coded in the + * input. + * This must be no more than 255. + * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled + * (2 channel) streams. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * coded channels (<code>streams + + * coupled_streams</code>) must be no + * more than 255. + * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from + * coded channels to output channels, as described in + * @ref opus_multistream. + * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error + * code (see @ref opus_errorcodes) on + * failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSDecoder *opus_multistream_decoder_create( + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int *error +) OPUS_ARG_NONNULL(5); + +/** Intialize a previously allocated decoder state object. + * The memory pointed to by \a st must be at least the size returned by + * opus_multistream_encoder_get_size(). + * This is intended for applications which use their own allocator instead of + * malloc. + * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. + * @see opus_multistream_decoder_create + * @see opus_multistream_deocder_get_size + * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize. + * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz). + * This must be one of 8000, 12000, 16000, + * 24000, or 48000. + * @param channels <tt>int</tt>: Number of channels to output. + * This must be at most 255. + * It may be different from the number of coded + * channels (<code>streams + + * coupled_streams</code>). + * @param streams <tt>int</tt>: The total number of streams coded in the + * input. + * This must be no more than 255. + * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled + * (2 channel) streams. + * This must be no larger than the total + * number of streams. + * Additionally, The total number of + * coded channels (<code>streams + + * coupled_streams</code>) must be no + * more than 255. + * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from + * coded channels to output channels, as described in + * @ref opus_multistream. + * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) + * on failure. + */ +OPUS_EXPORT int opus_multistream_decoder_init( + OpusMSDecoder *st, + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); + +/** Decode a multistream Opus packet. + * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. + * @param[in] data <tt>const unsigned char*</tt>: Input payload. + * Use a <code>NULL</code> + * pointer to indicate packet + * loss. + * @param len <tt>opus_int32</tt>: Number of bytes in payload. + * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved + * samples. + * This must contain room for + * <code>frame_size*channels</code> + * samples. + * @param frame_size <tt>int</tt>: The number of samples per channel of + * available space in \a pcm. + * If this is less than the maximum packet duration + * (120 ms; 5760 for 48kHz), this function will not be capable + * of decoding some packets. In the case of PLC (data==NULL) + * or FEC (decode_fec=1), then frame_size needs to be exactly + * the duration of audio that is missing, otherwise the + * decoder will not be in the optimal state to decode the + * next incoming packet. For the PLC and FEC cases, frame_size + * <b>must</b> be a multiple of 2.5 ms. + * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band + * forward error correction data be decoded. + * If no such data is available, the frame is + * decoded as if it were lost. + * @returns Number of samples decoded on success or a negative error code + * (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_decode( + OpusMSDecoder *st, + const unsigned char *data, + opus_int32 len, + opus_int16 *pcm, + int frame_size, + int decode_fec +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Decode a multistream Opus packet with floating point output. + * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. + * @param[in] data <tt>const unsigned char*</tt>: Input payload. + * Use a <code>NULL</code> + * pointer to indicate packet + * loss. + * @param len <tt>opus_int32</tt>: Number of bytes in payload. + * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved + * samples. + * This must contain room for + * <code>frame_size*channels</code> + * samples. + * @param frame_size <tt>int</tt>: The number of samples per channel of + * available space in \a pcm. + * If this is less than the maximum packet duration + * (120 ms; 5760 for 48kHz), this function will not be capable + * of decoding some packets. In the case of PLC (data==NULL) + * or FEC (decode_fec=1), then frame_size needs to be exactly + * the duration of audio that is missing, otherwise the + * decoder will not be in the optimal state to decode the + * next incoming packet. For the PLC and FEC cases, frame_size + * <b>must</b> be a multiple of 2.5 ms. + * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band + * forward error correction data be decoded. + * If no such data is available, the frame is + * decoded as if it were lost. + * @returns Number of samples decoded on success or a negative error code + * (see @ref opus_errorcodes) on failure. + */ +OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_decode_float( + OpusMSDecoder *st, + const unsigned char *data, + opus_int32 len, + float *pcm, + int frame_size, + int decode_fec +) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); + +/** Perform a CTL function on a multistream Opus decoder. + * + * Generally the request and subsequent arguments are generated by a + * convenience macro. + * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state. + * @param request This and all remaining parameters should be replaced by one + * of the convenience macros in @ref opus_genericctls, + * @ref opus_decoderctls, or @ref opus_multistream_ctls. + * @see opus_genericctls + * @see opus_decoderctls + * @see opus_multistream_ctls + */ +OPUS_EXPORT int opus_multistream_decoder_ctl(OpusMSDecoder *st, int request, ...) OPUS_ARG_NONNULL(1); + +/** Frees an <code>OpusMSDecoder</code> allocated by + * opus_multistream_decoder_create(). + * @param st <tt>OpusMSDecoder</tt>: Multistream decoder state to be freed. + */ +OPUS_EXPORT void opus_multistream_decoder_destroy(OpusMSDecoder *st); + +/**@}*/ + +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* OPUS_MULTISTREAM_H */ diff --git a/other/opus/include/opus/opus_types.h b/other/opus/include/opus/opus_types.h new file mode 100644 index 0000000..b28e03a --- /dev/null +++ b/other/opus/include/opus/opus_types.h @@ -0,0 +1,159 @@ +/* (C) COPYRIGHT 1994-2002 Xiph.Org Foundation */ +/* Modified by Jean-Marc Valin */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* opus_types.h based on ogg_types.h from libogg */ + +/** + @file opus_types.h + @brief Opus reference implementation types +*/ +#ifndef OPUS_TYPES_H +#define OPUS_TYPES_H + +/* Use the real stdint.h if it's there (taken from Paul Hsieh's pstdint.h) */ +#if (defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) || defined (HAVE_STDINT_H)) +#include <stdint.h> + + typedef int16_t opus_int16; + typedef uint16_t opus_uint16; + typedef int32_t opus_int32; + typedef uint32_t opus_uint32; +#elif defined(_WIN32) + +# if defined(__CYGWIN__) +# include <_G_config.h> + typedef _G_int32_t opus_int32; + typedef _G_uint32_t opus_uint32; + typedef _G_int16 opus_int16; + typedef _G_uint16 opus_uint16; +# elif defined(__MINGW32__) + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef int opus_int32; + typedef unsigned int opus_uint32; +# elif defined(__MWERKS__) + typedef int opus_int32; + typedef unsigned int opus_uint32; + typedef short opus_int16; + typedef unsigned short opus_uint16; +# else + /* MSVC/Borland */ + typedef __int32 opus_int32; + typedef unsigned __int32 opus_uint32; + typedef __int16 opus_int16; + typedef unsigned __int16 opus_uint16; +# endif + +#elif defined(__MACOS__) + +# include <sys/types.h> + typedef SInt16 opus_int16; + typedef UInt16 opus_uint16; + typedef SInt32 opus_int32; + typedef UInt32 opus_uint32; + +#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */ + +# include <sys/types.h> + typedef int16_t opus_int16; + typedef u_int16_t opus_uint16; + typedef int32_t opus_int32; + typedef u_int32_t opus_uint32; + +#elif defined(__BEOS__) + + /* Be */ +# include <inttypes.h> + typedef int16 opus_int16; + typedef u_int16 opus_uint16; + typedef int32_t opus_int32; + typedef u_int32_t opus_uint32; + +#elif defined (__EMX__) + + /* OS/2 GCC */ + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef int opus_int32; + typedef unsigned int opus_uint32; + +#elif defined (DJGPP) + + /* DJGPP */ + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef int opus_int32; + typedef unsigned int opus_uint32; + +#elif defined(R5900) + + /* PS2 EE */ + typedef int opus_int32; + typedef unsigned opus_uint32; + typedef short opus_int16; + typedef unsigned short opus_uint16; + +#elif defined(__SYMBIAN32__) + + /* Symbian GCC */ + typedef signed short opus_int16; + typedef unsigned short opus_uint16; + typedef signed int opus_int32; + typedef unsigned int opus_uint32; + +#elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X) + + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef long opus_int32; + typedef unsigned long opus_uint32; + +#elif defined(CONFIG_TI_C6X) + + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef int opus_int32; + typedef unsigned int opus_uint32; + +#else + + /* Give up, take a reasonable guess */ + typedef short opus_int16; + typedef unsigned short opus_uint16; + typedef int opus_int32; + typedef unsigned int opus_uint32; + +#endif + +#define opus_int int /* used for counters etc; at least 16 bits */ +#define opus_int64 long long +#define opus_int8 signed char + +#define opus_uint unsigned int /* used for counters etc; at least 16 bits */ +#define opus_uint64 unsigned long long +#define opus_uint8 unsigned char + +#endif /* OPUS_TYPES_H */ diff --git a/other/opus/include/opusfile.h b/other/opus/include/opusfile.h new file mode 100644 index 0000000..a31b6c4 --- /dev/null +++ b/other/opus/include/opusfile.h @@ -0,0 +1,2102 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012 * + * by the Xiph.Org Foundation and contributors http://www.xiph.org/ * + * * + ******************************************************************** + + function: stdio-based convenience library for opening/seeking/decoding + last mod: $Id: vorbisfile.h 17182 2010-04-29 03:48:32Z xiphmont $ + + ********************************************************************/ +#if !defined(_opusfile_h) +# define _opusfile_h (1) + +/**\mainpage + \section Introduction + + This is the documentation for the <tt>libopusfile</tt> C API. + + The <tt>libopusfile</tt> package provides a convenient high-level API for + decoding and basic manipulation of all Ogg Opus audio streams. + <tt>libopusfile</tt> is implemented as a layer on top of Xiph.Org's + reference + <tt><a href="https://www.xiph.org/ogg/doc/libogg/reference.html">libogg</a></tt> + and + <tt><a href="https://mf4.xiph.org/jenkins/view/opus/job/opus/ws/doc/html/index.html">libopus</a></tt> + libraries. + + <tt>libopusfile</tt> provides several sets of built-in routines for + file/stream access, and may also use custom stream I/O routines provided by + the embedded environment. + There are built-in I/O routines provided for ANSI-compliant + <code>stdio</code> (<code>FILE *</code>), memory buffers, and URLs + (including <file:> URLs, plus optionally <http:> and <https:> URLs). + + \section Organization + + The main API is divided into several sections: + - \ref stream_open_close + - \ref stream_info + - \ref stream_decoding + - \ref stream_seeking + + Several additional sections are not tied to the main API. + - \ref stream_callbacks + - \ref header_info + - \ref error_codes + + \section Overview + + The <tt>libopusfile</tt> API always decodes files to 48 kHz. + The original sample rate is not preserved by the lossy compression, though + it is stored in the header to allow you to resample to it after decoding + (the <tt>libopusfile</tt> API does not currently provide a resampler, + but the + <a href="http://www.speex.org/docs/manual/speex-manual/node7.html#SECTION00760000000000000000">the + Speex resampler</a> is a good choice if you need one). + In general, if you are playing back the audio, you should leave it at + 48 kHz, provided your audio hardware supports it. + When decoding to a file, it may be worth resampling back to the original + sample rate, so as not to surprise users who might not expect the sample + rate to change after encoding to Opus and decoding. + + Opus files can contain anywhere from 1 to 255 channels of audio. + The channel mappings for up to 8 channels are the same as the + <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis + mappings</a>. + A special stereo API can convert everything to 2 channels, making it simple + to support multichannel files in an application which only has stereo + output. + Although the <tt>libopusfile</tt> ABI provides support for the theoretical + maximum number of channels, the current implementation does not support + files with more than 8 channels, as they do not have well-defined channel + mappings. + + Like all Ogg files, Opus files may be "chained". + That is, multiple Opus files may be combined into a single, longer file just + by concatenating the original files. + This is commonly done in internet radio streaming, as it allows the title + and artist to be updated each time the song changes, since each link in the + chain includes its own set of metadata. + + <tt>libopusfile</tt> fully supports chained files. + It will decode the first Opus stream found in each link of a chained file + (ignoring any other streams that might be concurrently multiplexed with it, + such as a video stream). + + The channel count can also change between links. + If your application is not prepared to deal with this, it can use the stereo + API to ensure the audio from all links will always get decoded into a + common format. + Since <tt>libopusfile</tt> always decodes to 48 kHz, you do not have to + worry about the sample rate changing between links (as was possible with + Vorbis). + This makes application support for chained files with <tt>libopusfile</tt> + very easy.*/ + +# if defined(__cplusplus) +extern "C" { +# endif + +# include <stdarg.h> +# include <stdio.h> +# include <ogg/ogg.h> +# include <opus_multistream.h> + +/**@cond PRIVATE*/ + +/*Enable special features for gcc and gcc-compatible compilers.*/ +# if !defined(OP_GNUC_PREREQ) +# if defined(__GNUC__)&&defined(__GNUC_MINOR__) +# define OP_GNUC_PREREQ(_maj,_min) \ + ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) +# else +# define OP_GNUC_PREREQ(_maj,_min) 0 +# endif +# endif + +# if OP_GNUC_PREREQ(4,0) +# pragma GCC visibility push(default) +# endif + +typedef struct OpusHead OpusHead; +typedef struct OpusTags OpusTags; +typedef struct OpusPictureTag OpusPictureTag; +typedef struct OpusServerInfo OpusServerInfo; +typedef struct OpusFileCallbacks OpusFileCallbacks; +typedef struct OggOpusFile OggOpusFile; + +/*Warning attributes for libopusfile functions.*/ +# if OP_GNUC_PREREQ(3,4) +# define OP_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) +# else +# define OP_WARN_UNUSED_RESULT +# endif +# if OP_GNUC_PREREQ(3,4) +# define OP_ARG_NONNULL(_x) __attribute__((__nonnull__(_x))) +# else +# define OP_ARG_NONNULL(_x) +# endif + +/**@endcond*/ + +/**\defgroup error_codes Error Codes*/ +/*@{*/ +/**\name List of possible error codes + Many of the functions in this library return a negative error code when a + function fails. + This list provides a brief explanation of the common errors. + See each individual function for more details on what a specific error code + means in that context.*/ +/*@{*/ + +/**A request did not succeed.*/ +#define OP_FALSE (-1) +/*Currently not used externally.*/ +#define OP_EOF (-2) +/**There was a hole in the page sequence numbers (e.g., a page was corrupt or + missing).*/ +#define OP_HOLE (-3) +/**An underlying read, seek, or tell operation failed when it should have + succeeded.*/ +#define OP_EREAD (-128) +/**A <code>NULL</code> pointer was passed where one was unexpected, or an + internal memory allocation failed, or an internal library error was + encountered.*/ +#define OP_EFAULT (-129) +/**The stream used a feature that is not implemented, such as an unsupported + channel family.*/ +#define OP_EIMPL (-130) +/**One or more parameters to a function were invalid.*/ +#define OP_EINVAL (-131) +/**A purported Ogg Opus stream did not begin with an Ogg page, a purported + header packet did not start with one of the required strings, "OpusHead" or + "OpusTags", or a link in a chained file was encountered that did not + contain any logical Opus streams.*/ +#define OP_ENOTFORMAT (-132) +/**A required header packet was not properly formatted, contained illegal + values, or was missing altogether.*/ +#define OP_EBADHEADER (-133) +/**The ID header contained an unrecognized version number.*/ +#define OP_EVERSION (-134) +/*Currently not used at all.*/ +#define OP_ENOTAUDIO (-135) +/**An audio packet failed to decode properly. + This is usually caused by a multistream Ogg packet where the durations of + the individual Opus packets contained in it are not all the same.*/ +#define OP_EBADPACKET (-136) +/**We failed to find data we had seen before, or the bitstream structure was + sufficiently malformed that seeking to the target destination was + impossible.*/ +#define OP_EBADLINK (-137) +/**An operation that requires seeking was requested on an unseekable stream.*/ +#define OP_ENOSEEK (-138) +/**The first or last granule position of a link failed basic validity checks.*/ +#define OP_EBADTIMESTAMP (-139) + +/*@}*/ +/*@}*/ + +/**\defgroup header_info Header Information*/ +/*@{*/ + +/**The maximum number of channels in an Ogg Opus stream.*/ +#define OPUS_CHANNEL_COUNT_MAX (255) + +/**Ogg Opus bitstream information. + This contains the basic playback parameters for a stream, and corresponds to + the initial ID header packet of an Ogg Opus stream.*/ +struct OpusHead{ + /**The Ogg Opus format version, in the range 0...255. + The top 4 bits represent a "major" version, and the bottom four bits + represent backwards-compatible "minor" revisions. + The current specification describes version 1. + This library will recognize versions up through 15 as backwards compatible + with the current specification. + An earlier draft of the specification described a version 0, but the only + difference between version 1 and version 0 is that version 0 did + not specify the semantics for handling the version field.*/ + int version; + /**The number of channels, in the range 1...255.*/ + int channel_count; + /**The number of samples that should be discarded from the beginning of the + stream.*/ + unsigned pre_skip; + /**The sampling rate of the original input. + All Opus audio is coded at 48 kHz, and should also be decoded at 48 kHz + for playback (unless the target hardware does not support this sampling + rate). + However, this field may be used to resample the audio back to the original + sampling rate, for example, when saving the output to a file.*/ + opus_uint32 input_sample_rate; + /**The gain to apply to the decoded output, in dB, as a Q8 value in the range + -32768...32767. + The <tt>libopusfile</tt> API will automatically apply this gain to the + decoded output before returning it, scaling it by + <code>pow(10,output_gain/(20.0*256))</code>.*/ + int output_gain; + /**The channel mapping family, in the range 0...255. + Channel mapping family 0 covers mono or stereo in a single stream. + Channel mapping family 1 covers 1 to 8 channels in one or more streams, + using the Vorbis speaker assignments. + Channel mapping family 255 covers 1 to 255 channels in one or more + streams, but without any defined speaker assignment.*/ + int mapping_family; + /**The number of Opus streams in each Ogg packet, in the range 1...255.*/ + int stream_count; + /**The number of coupled Opus streams in each Ogg packet, in the range + 0...127. + This must satisfy <code>0 <= coupled_count <= stream_count</code> and + <code>coupled_count + stream_count <= 255</code>. + The coupled streams appear first, before all uncoupled streams, in an Ogg + Opus packet.*/ + int coupled_count; + /**The mapping from coded stream channels to output channels. + Let <code>index=mapping[k]</code> be the value for channel <code>k</code>. + If <code>index<2*coupled_count</code>, then it refers to the left channel + from stream <code>(index/2)</code> if even, and the right channel from + stream <code>(index/2)</code> if odd. + Otherwise, it refers to the output of the uncoupled stream + <code>(index-coupled_count)</code>.*/ + unsigned char mapping[OPUS_CHANNEL_COUNT_MAX]; +}; + +/**The metadata from an Ogg Opus stream. + + This structure holds the in-stream metadata corresponding to the 'comment' + header packet of an Ogg Opus stream. + The comment header is meant to be used much like someone jotting a quick + note on the label of a CD. + It should be a short, to the point text note that can be more than a couple + words, but not more than a short paragraph. + + The metadata is stored as a series of (tag, value) pairs, in length-encoded + string vectors, using the same format as Vorbis (without the final "framing + bit"), Theora, and Speex, except for the packet header. + The first occurrence of the '=' character delimits the tag and value. + A particular tag may occur more than once, and order is significant. + The character set encoding for the strings is always UTF-8, but the tag + names are limited to ASCII, and treated as case-insensitive. + See <a href="http://www.xiph.org/vorbis/doc/v-comment.html">the Vorbis + comment header specification</a> for details. + + In filling in this structure, <tt>libopusfile</tt> will null-terminate the + #user_comments strings for safety. + However, the bitstream format itself treats them as 8-bit clean vectors, + possibly containing NUL characters, so the #comment_lengths array should be + treated as their authoritative length. + + This structure is binary and source-compatible with a + <code>vorbis_comment</code>, and pointers to it may be freely cast to + <code>vorbis_comment</code> pointers, and vice versa. + It is provided as a separate type to avoid introducing a compile-time + dependency on the libvorbis headers.*/ +struct OpusTags{ + /**The array of comment string vectors.*/ + char **user_comments; + /**An array of the corresponding length of each vector, in bytes.*/ + int *comment_lengths; + /**The total number of comment streams.*/ + int comments; + /**The null-terminated vendor string. + This identifies the software used to encode the stream.*/ + char *vendor; +}; + +/**\name Picture tag image formats*/ +/*@{*/ + +/**The MIME type was not recognized, or the image data did not match the + declared MIME type.*/ +#define OP_PIC_FORMAT_UNKNOWN (-1) +/**The MIME type indicates the image data is really a URL.*/ +#define OP_PIC_FORMAT_URL (0) +/**The image is a JPEG.*/ +#define OP_PIC_FORMAT_JPEG (1) +/**The image is a PNG.*/ +#define OP_PIC_FORMAT_PNG (2) +/**The image is a GIF.*/ +#define OP_PIC_FORMAT_GIF (3) + +/*@}*/ + +/**The contents of a METADATA_BLOCK_PICTURE tag.*/ +struct OpusPictureTag{ + /**The picture type according to the ID3v2 APIC frame: + <ol start="0"> + <li>Other</li> + <li>32x32 pixels 'file icon' (PNG only)</li> + <li>Other file icon</li> + <li>Cover (front)</li> + <li>Cover (back)</li> + <li>Leaflet page</li> + <li>Media (e.g. label side of CD)</li> + <li>Lead artist/lead performer/soloist</li> + <li>Artist/performer</li> + <li>Conductor</li> + <li>Band/Orchestra</li> + <li>Composer</li> + <li>Lyricist/text writer</li> + <li>Recording Location</li> + <li>During recording</li> + <li>During performance</li> + <li>Movie/video screen capture</li> + <li>A bright colored fish</li> + <li>Illustration</li> + <li>Band/artist logotype</li> + <li>Publisher/Studio logotype</li> + </ol> + Others are reserved and should not be used. + There may only be one each of picture type 1 and 2 in a file.*/ + opus_int32 type; + /**The MIME type of the picture, in printable ASCII characters 0x20-0x7E. + The MIME type may also be <code>"-->"</code> to signify that the data part + is a URL pointing to the picture instead of the picture data itself. + In this case, a terminating NUL is appended to the URL string in #data, + but #data_length is set to the length of the string excluding that + terminating NUL.*/ + char *mime_type; + /**The description of the picture, in UTF-8.*/ + char *description; + /**The width of the picture in pixels.*/ + opus_uint32 width; + /**The height of the picture in pixels.*/ + opus_uint32 height; + /**The color depth of the picture in bits-per-pixel (<em>not</em> + bits-per-channel).*/ + opus_uint32 depth; + /**For indexed-color pictures (e.g., GIF), the number of colors used, or 0 + for non-indexed pictures.*/ + opus_uint32 colors; + /**The length of the picture data in bytes.*/ + opus_uint32 data_length; + /**The binary picture data.*/ + unsigned char *data; + /**The format of the picture data, if known. + One of + <ul> + <li>#OP_PIC_FORMAT_UNKNOWN,</li> + <li>#OP_PIC_FORMAT_URL,</li> + <li>#OP_PIC_FORMAT_JPEG,</li> + <li>#OP_PIC_FORMAT_PNG, or</li> + <li>#OP_PIC_FORMAT_GIF.</li> + </ul>*/ + int format; +}; + +/**\name Functions for manipulating header data + + These functions manipulate the #OpusHead and #OpusTags structures, + which describe the audio parameters and tag-value metadata, respectively. + These can be used to query the headers returned by <tt>libopusfile</tt>, or + to parse Opus headers from sources other than an Ogg Opus stream, provided + they use the same format.*/ +/*@{*/ + +/**Parses the contents of the ID header packet of an Ogg Opus stream. + \param[out] _head Returns the contents of the parsed packet. + The contents of this structure are untouched on error. + This may be <code>NULL</code> to merely test the header + for validity. + \param[in] _data The contents of the ID header packet. + \param _len The number of bytes of data in the ID header packet. + \return 0 on success or a negative value on error. + \retval #OP_ENOTFORMAT If the data does not start with the "OpusHead" + string. + \retval #OP_EVERSION If the version field signaled a version this library + does not know how to parse. + \retval #OP_EIMPL If the channel mapping family was 255, which general + purpose players should not attempt to play. + \retval #OP_EBADHEADER If the contents of the packet otherwise violate the + Ogg Opus specification: + <ul> + <li>Insufficient data,</li> + <li>Too much data for the known minor versions,</li> + <li>An unrecognized channel mapping family,</li> + <li>Zero channels or too many channels,</li> + <li>Zero coded streams,</li> + <li>Too many coupled streams, or</li> + <li>An invalid channel mapping index.</li> + </ul>*/ +OP_WARN_UNUSED_RESULT int opus_head_parse(OpusHead *_head, + const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2); + +/**Converts a granule position to a sample offset for a given Ogg Opus stream. + The sample offset is simply <code>_gp-_head->pre_skip</code>. + Granule position values smaller than OpusHead#pre_skip correspond to audio + that should never be played, and thus have no associated sample offset. + This function returns -1 for such values. + This function also correctly handles extremely large granule positions, + which may have wrapped around to a negative number when stored in a signed + ogg_int64_t value. + \param _head The #OpusHead information from the ID header of the stream. + \param _gp The granule position to convert. + \return The sample offset associated with the given granule position + (counting at a 48 kHz sampling rate), or the special value -1 on + error (i.e., the granule position was smaller than the pre-skip + amount).*/ +ogg_int64_t opus_granule_sample(const OpusHead *_head,ogg_int64_t _gp) + OP_ARG_NONNULL(1); + +/**Parses the contents of the 'comment' header packet of an Ogg Opus stream. + \param[out] _tags An uninitialized #OpusTags structure. + This returns the contents of the parsed packet. + The contents of this structure are untouched on error. + This may be <code>NULL</code> to merely test the header + for validity. + \param[in] _data The contents of the 'comment' header packet. + \param _len The number of bytes of data in the 'info' header packet. + \retval 0 Success. + \retval #OP_ENOTFORMAT If the data does not start with the "OpusTags" + string. + \retval #OP_EBADHEADER If the contents of the packet otherwise violate the + Ogg Opus specification. + \retval #OP_EFAULT If there wasn't enough memory to store the tags.*/ +OP_WARN_UNUSED_RESULT int opus_tags_parse(OpusTags *_tags, + const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2); + +/**Performs a deep copy of an #OpusTags structure. + \param _dst The #OpusTags structure to copy into. + If this function fails, the contents of this structure remain + untouched. + \param _src The #OpusTags structure to copy from. + \retval 0 Success. + \retval #OP_EFAULT If there wasn't enough memory to copy the tags.*/ +int opus_tags_copy(OpusTags *_dst,const OpusTags *_src) OP_ARG_NONNULL(1); + +/**Initializes an #OpusTags structure. + This should be called on a freshly allocated #OpusTags structure before + attempting to use it. + \param _tags The #OpusTags structure to initialize.*/ +void opus_tags_init(OpusTags *_tags) OP_ARG_NONNULL(1); + +/**Add a (tag, value) pair to an initialized #OpusTags structure. + \note Neither opus_tags_add() nor opus_tags_add_comment() support values + containing embedded NULs, although the bitstream format does support them. + To add such tags, you will need to manipulate the #OpusTags structure + directly. + \param _tags The #OpusTags structure to add the (tag, value) pair to. + \param _tag A NUL-terminated, case-insensitive, ASCII string containing + the tag to add (without an '=' character). + \param _value A NUL-terminated UTF-8 containing the corresponding value. + \return 0 on success, or a negative value on failure. + \retval #OP_EFAULT An internal memory allocation failed.*/ +int opus_tags_add(OpusTags *_tags,const char *_tag,const char *_value) + OP_ARG_NONNULL(1) OP_ARG_NONNULL(2) OP_ARG_NONNULL(3); + +/**Add a comment to an initialized #OpusTags structure. + \note Neither opus_tags_add_comment() nor opus_tags_add() support comments + containing embedded NULs, although the bitstream format does support them. + To add such tags, you will need to manipulate the #OpusTags structure + directly. + \param _tags The #OpusTags structure to add the comment to. + \param _comment A NUL-terminated UTF-8 string containing the comment in + "TAG=value" form. + \return 0 on success, or a negative value on failure. + \retval #OP_EFAULT An internal memory allocation failed.*/ +int opus_tags_add_comment(OpusTags *_tags,const char *_comment) + OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Look up a comment value by its tag. + \param _tags An initialized #OpusTags structure. + \param _tag The tag to look up. + \param _count The instance of the tag. + The same tag can appear multiple times, each with a distinct + value, so an index is required to retrieve them all. + The order in which these values appear is significant and + should be preserved. + Use opus_tags_query_count() to get the legal range for the + \a _count parameter. + \return A pointer to the queried tag's value. + This points directly to data in the #OpusTags structure. + It should not be modified or freed by the application, and + modifications to the structure may invalidate the pointer. + \retval NULL If no matching tag is found.*/ +const char *opus_tags_query(const OpusTags *_tags,const char *_tag,int _count) + OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Look up the number of instances of a tag. + Call this first when querying for a specific tag and then iterate over the + number of instances with separate calls to opus_tags_query() to retrieve + all the values for that tag in order. + \param _tags An initialized #OpusTags structure. + \param _tag The tag to look up. + \return The number of instances of this particular tag.*/ +int opus_tags_query_count(const OpusTags *_tags,const char *_tag) + OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Get the track gain from an R128_TRACK_GAIN tag, if one was specified. + This searches for the first R128_TRACK_GAIN tag with a valid signed, + 16-bit decimal integer value and returns the value. + This routine is exposed merely for convenience for applications which wish + to do something special with the track gain (i.e., display it). + If you simply wish to apply the track gain instead of the header gain, you + can use op_set_gain_offset() with an #OP_TRACK_GAIN type and no offset. + \param _tags An initialized #OpusTags structure. + \param[out] _gain_q8 The track gain, in 1/256ths of a dB. + This will lie in the range [-32768,32767], and should + be applied in <em>addition</em> to the header gain. + On error, no value is returned, and the previous + contents remain unchanged. + \return 0 on success, or a negative value on error. + \retval #OP_FALSE There was no track gain available in the given tags.*/ +int opus_tags_get_track_gain(const OpusTags *_tags,int *_gain_q8) + OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Clears the #OpusTags structure. + This should be called on an #OpusTags structure after it is no longer + needed. + It will free all memory used by the structure members. + \param _tags The #OpusTags structure to clear.*/ +void opus_tags_clear(OpusTags *_tags) OP_ARG_NONNULL(1); + +/**Check if \a _comment is an instance of a \a _tag_name tag. + \see opus_tagncompare + \param _tag_name A NUL-terminated, case-insensitive, ASCII string containing + the name of the tag to check for (without the terminating + '=' character). + \param _comment The comment string to check. + \return An integer less than, equal to, or greater than zero if \a _comment + is found respectively, to be less than, to match, or be greater + than a "tag=value" string whose tag matches \a _tag_name.*/ +int opus_tagcompare(const char *_tag_name,const char *_comment); + +/**Check if \a _comment is an instance of a \a _tag_name tag. + This version is slightly more efficient than opus_tagcompare() if the length + of the tag name is already known (e.g., because it is a constant). + \see opus_tagcompare + \param _tag_name A case-insensitive ASCII string containing the name of the + tag to check for (without the terminating '=' character). + \param _tag_len The number of characters in the tag name. + This must be non-negative. + \param _comment The comment string to check. + \return An integer less than, equal to, or greater than zero if \a _comment + is found respectively, to be less than, to match, or be greater + than a "tag=value" string whose tag matches the first \a _tag_len + characters of \a _tag_name.*/ +int opus_tagncompare(const char *_tag_name,int _tag_len,const char *_comment); + +/**Parse a single METADATA_BLOCK_PICTURE tag. + This decodes the BASE64-encoded content of the tag and returns a structure + with the MIME type, description, image parameters (if known), and the + compressed image data. + If the MIME type indicates the presence of an image format we recognize + (JPEG, PNG, or GIF) and the actual image data contains the magic signature + associated with that format, then the OpusPictureTag::format field will be + set to the corresponding format. + This is provided as a convenience to avoid requiring applications to parse + the MIME type and/or do their own format detection for the commonly used + formats. + In this case, we also attempt to extract the image parameters directly from + the image data (overriding any that were present in the tag, which the + specification says applications are not meant to rely on). + The application must still provide its own support for actually decoding the + image data and, if applicable, retrieving that data from URLs. + \param[out] _pic Returns the parsed picture data. + No sanitation is done on the type, MIME type, or + description fields, so these might return invalid values. + The contents of this structure are left unmodified on + failure. + \param _tag The METADATA_BLOCK_PICTURE tag contents. + The leading "METADATA_BLOCK_PICTURE=" portion is optional, + to allow the function to be used on either directly on the + values in OpusTags::user_comments or on the return value + of opus_tags_query(). + \return 0 on success or a negative value on error. + \retval #OP_ENOTFORMAT The METADATA_BLOCK_PICTURE contents were not valid. + \retval #OP_EFAULT There was not enough memory to store the picture tag + contents.*/ +OP_WARN_UNUSED_RESULT int opus_picture_tag_parse(OpusPictureTag *_pic, + const char *_tag) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Initializes an #OpusPictureTag structure. + This should be called on a freshly allocated #OpusPictureTag structure + before attempting to use it. + \param _pic The #OpusPictureTag structure to initialize.*/ +void opus_picture_tag_init(OpusPictureTag *_pic) OP_ARG_NONNULL(1); + +/**Clears the #OpusPictureTag structure. + This should be called on an #OpusPictureTag structure after it is no longer + needed. + It will free all memory used by the structure members. + \param _pic The #OpusPictureTag structure to clear.*/ +void opus_picture_tag_clear(OpusPictureTag *_pic) OP_ARG_NONNULL(1); + +/*@}*/ + +/*@}*/ + +/**\defgroup url_options URL Reading Options*/ +/*@{*/ +/**\name URL reading options + Options for op_url_stream_create() and associated functions. + These allow you to provide proxy configuration parameters, skip SSL + certificate checks, etc. + Options are processed in order, and if the same option is passed multiple + times, only the value specified by the last occurrence has an effect + (unless otherwise specified). + They may be expanded in the future.*/ +/*@{*/ + +/**@cond PRIVATE*/ + +/*These are the raw numbers used to define the request codes. + They should not be used directly.*/ +#define OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST (6464) +#define OP_HTTP_PROXY_HOST_REQUEST (6528) +#define OP_HTTP_PROXY_PORT_REQUEST (6592) +#define OP_HTTP_PROXY_USER_REQUEST (6656) +#define OP_HTTP_PROXY_PASS_REQUEST (6720) +#define OP_GET_SERVER_INFO_REQUEST (6784) + +#define OP_URL_OPT(_request) ((_request)+(char *)0) + +/*These macros trigger compilation errors or warnings if the wrong types are + provided to one of the URL options.*/ +#define OP_CHECK_INT(_x) ((void)((_x)==(opus_int32)0),(opus_int32)(_x)) +#define OP_CHECK_CONST_CHAR_PTR(_x) ((_x)+((_x)-(const char *)(_x))) +#define OP_CHECK_SERVER_INFO_PTR(_x) ((_x)+((_x)-(OpusServerInfo *)(_x))) + +/**@endcond*/ + +/**HTTP/Shoutcast/Icecast server information associated with a URL.*/ +struct OpusServerInfo{ + /**The name of the server (icy-name/ice-name). + This is <code>NULL</code> if there was no <code>icy-name</code> or + <code>ice-name</code> header.*/ + char *name; + /**A short description of the server (icy-description/ice-description). + This is <code>NULL</code> if there was no <code>icy-description</code> or + <code>ice-description</code> header.*/ + char *description; + /**The genre the server falls under (icy-genre/ice-genre). + This is <code>NULL</code> if there was no <code>icy-genre</code> or + <code>ice-genre</code> header.*/ + char *genre; + /**The homepage for the server (icy-url/ice-url). + This is <code>NULL</code> if there was no <code>icy-url</code> or + <code>ice-url</code> header.*/ + char *url; + /**The software used by the origin server (Server). + This is <code>NULL</code> if there was no <code>Server</code> header.*/ + char *server; + /**The media type of the entity sent to the recepient (Content-Type). + This is <code>NULL</code> if there was no <code>Content-Type</code> + header.*/ + char *content_type; + /**The nominal stream bitrate in kbps (icy-br/ice-bitrate). + This is <code>-1</code> if there was no <code>icy-br</code> or + <code>ice-bitrate</code> header.*/ + opus_int32 bitrate_kbps; + /**Flag indicating whether the server is public (<code>1</code>) or not + (<code>0</code>) (icy-pub/ice-public). + This is <code>-1</code> if there was no <code>icy-pub</code> or + <code>ice-public</code> header.*/ + int is_public; + /**Flag indicating whether the server is using HTTPS instead of HTTP. + This is <code>0</code> unless HTTPS is being used. + This may not match the protocol used in the original URL if there were + redirections.*/ + int is_ssl; +}; + +/**Initializes an #OpusServerInfo structure. + All fields are set as if the corresponding header was not available. + \param _info The #OpusServerInfo structure to initialize. + \note If you use this function, you must link against <tt>libopusurl</tt>.*/ +void opus_server_info_init(OpusServerInfo *_info) OP_ARG_NONNULL(1); + +/**Clears the #OpusServerInfo structure. + This should be called on an #OpusServerInfo structure after it is no longer + needed. + It will free all memory used by the structure members. + \param _info The #OpusServerInfo structure to clear. + \note If you use this function, you must link against <tt>libopusurl</tt>.*/ +void opus_server_info_clear(OpusServerInfo *_info) OP_ARG_NONNULL(1); + +/**Skip the certificate check when connecting via TLS/SSL (https). + \param _b <code>opus_int32</code>: Whether or not to skip the certificate + check. + The check will be skipped if \a _b is non-zero, and will not be + skipped if \a _b is zero. + \hideinitializer*/ +#define OP_SSL_SKIP_CERTIFICATE_CHECK(_b) \ + OP_URL_OPT(OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST),OP_CHECK_INT(_b) + +/**Proxy connections through the given host. + If no port is specified via #OP_HTTP_PROXY_PORT, the port number defaults + to 8080 (http-alt). + All proxy parameters are ignored for non-http and non-https URLs. + \param _host <code>const char *</code>: The proxy server hostname. + This may be <code>NULL</code> to disable the use of a proxy + server. + \hideinitializer*/ +#define OP_HTTP_PROXY_HOST(_host) \ + OP_URL_OPT(OP_HTTP_PROXY_HOST_REQUEST),OP_CHECK_CONST_CHAR_PTR(_host) + +/**Use the given port when proxying connections. + This option only has an effect if #OP_HTTP_PROXY_HOST is specified with a + non-<code>NULL</code> \a _host. + If this option is not provided, the proxy port number defaults to 8080 + (http-alt). + All proxy parameters are ignored for non-http and non-https URLs. + \param _port <code>opus_int32</code>: The proxy server port. + This must be in the range 0...65535 (inclusive), or the + URL function this is passed to will fail. + \hideinitializer*/ +#define OP_HTTP_PROXY_PORT(_port) \ + OP_URL_OPT(OP_HTTP_PROXY_PORT_REQUEST),OP_CHECK_INT(_port) + +/**Use the given user name for authentication when proxying connections. + All proxy parameters are ignored for non-http and non-https URLs. + \param _user const char *: The proxy server user name. + This may be <code>NULL</code> to disable proxy + authentication. + A non-<code>NULL</code> value only has an effect + if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_PASS + are also specified with non-<code>NULL</code> + arguments. + \hideinitializer*/ +#define OP_HTTP_PROXY_USER(_user) \ + OP_URL_OPT(OP_HTTP_PROXY_USER_REQUEST),OP_CHECK_CONST_CHAR_PTR(_user) + +/**Use the given password for authentication when proxying connections. + All proxy parameters are ignored for non-http and non-https URLs. + \param _pass const char *: The proxy server password. + This may be <code>NULL</code> to disable proxy + authentication. + A non-<code>NULL</code> value only has an effect + if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_USER + are also specified with non-<code>NULL</code> + arguments. + \hideinitializer*/ +#define OP_HTTP_PROXY_PASS(_pass) \ + OP_URL_OPT(OP_HTTP_PROXY_PASS_REQUEST),OP_CHECK_CONST_CHAR_PTR(_pass) + +/**Parse information about the streaming server (if any) and return it. + Very little validation is done. + In particular, OpusServerInfo::url may not be a valid URL, + OpusServerInfo::bitrate_kbps may not really be in kbps, and + OpusServerInfo::content_type may not be a valid MIME type. + The character set of the string fields is not specified anywhere, and should + not be assumed to be valid UTF-8. + \param _info OpusServerInfo *: Returns information about the server. + If there is any error opening the stream, the + contents of this structure remain + unmodified. + On success, fills in the structure with the + server information that was available, if + any. + After a successful return, the contents of + this structure should be freed by calling + opus_server_info_clear(). + \hideinitializer*/ +#define OP_GET_SERVER_INFO(_info) \ + OP_URL_OPT(OP_GET_SERVER_INFO_REQUEST),OP_CHECK_SERVER_INFO_PTR(_info) + +/*@}*/ +/*@}*/ + +/**\defgroup stream_callbacks Abstract Stream Reading Interface*/ +/*@{*/ +/**\name Functions for reading from streams + These functions define the interface used to read from and seek in a stream + of data. + A stream does not need to implement seeking, but the decoder will not be + able to seek if it does not do so. + These functions also include some convenience routines for working with + standard <code>FILE</code> pointers, complete streams stored in a single + block of memory, or URLs.*/ +/*@{*/ + +/**Reads up to \a _nbytes bytes of data from \a _stream. + \param _stream The stream to read from. + \param[out] _ptr The buffer to store the data in. + \param _nbytes The maximum number of bytes to read. + This function may return fewer, though it will not + return zero unless it reaches end-of-file. + \return The number of bytes successfully read, or a negative value on + error.*/ +typedef int (*op_read_func)(void *_stream,unsigned char *_ptr,int _nbytes); + +/**Sets the position indicator for \a _stream. + The new position, measured in bytes, is obtained by adding \a _offset + bytes to the position specified by \a _whence. + If \a _whence is set to <code>SEEK_SET</code>, <code>SEEK_CUR</code>, or + <code>SEEK_END</code>, the offset is relative to the start of the stream, + the current position indicator, or end-of-file, respectively. + \retval 0 Success. + \retval -1 Seeking is not supported or an error occurred. + <code>errno</code> need not be set.*/ +typedef int (*op_seek_func)(void *_stream,opus_int64 _offset,int _whence); + +/**Obtains the current value of the position indicator for \a _stream. + \return The current position indicator.*/ +typedef opus_int64 (*op_tell_func)(void *_stream); + +/**Closes the underlying stream. + \retval 0 Success. + \retval EOF An error occurred. + <code>errno</code> need not be set.*/ +typedef int (*op_close_func)(void *_stream); + +/**The callbacks used to access non-<code>FILE</code> stream resources. + The function prototypes are basically the same as for the stdio functions + <code>fread()</code>, <code>fseek()</code>, <code>ftell()</code>, and + <code>fclose()</code>. + The differences are that the <code>FILE *</code> arguments have been + replaced with a <code>void *</code>, which is to be used as a pointer to + whatever internal data these functions might need, that #seek and #tell + take and return 64-bit offsets, and that #seek <em>must</em> return -1 if + the stream is unseekable.*/ +struct OpusFileCallbacks{ + /**Used to read data from the stream. + This must not be <code>NULL</code>.*/ + op_read_func read; + /**Used to seek in the stream. + This may be <code>NULL</code> if seeking is not implemented.*/ + op_seek_func seek; + /**Used to return the current read position in the stream. + This may be <code>NULL</code> if seeking is not implemented.*/ + op_tell_func tell; + /**Used to close the stream when the decoder is freed. + This may be <code>NULL</code> to leave the stream open.*/ + op_close_func close; +}; + +/**Opens a stream with <code>fopen()</code> and fills in a set of callbacks + that can be used to access it. + This is useful to avoid writing your own portable 64-bit seeking wrappers, + and also avoids cross-module linking issues on Windows, where a + <code>FILE *</code> must be accessed by routines defined in the same module + that opened it. + \param[out] _cb The callbacks to use for this file. + If there is an error opening the file, nothing will be + filled in here. + \param _path The path to the file to open. + On Windows, this string must be UTF-8 (to allow access to + files whose names cannot be represented in the current + MBCS code page). + All other systems use the native character encoding. + \param _mode The mode to open the file in. + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_fopen(OpusFileCallbacks *_cb, + const char *_path,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2) + OP_ARG_NONNULL(3); + +/**Opens a stream with <code>fdopen()</code> and fills in a set of callbacks + that can be used to access it. + This is useful to avoid writing your own portable 64-bit seeking wrappers, + and also avoids cross-module linking issues on Windows, where a + <code>FILE *</code> must be accessed by routines defined in the same module + that opened it. + \param[out] _cb The callbacks to use for this file. + If there is an error opening the file, nothing will be + filled in here. + \param _fd The file descriptor to open. + \param _mode The mode to open the file in. + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_fdopen(OpusFileCallbacks *_cb, + int _fd,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(3); + +/**Opens a stream with <code>freopen()</code> and fills in a set of callbacks + that can be used to access it. + This is useful to avoid writing your own portable 64-bit seeking wrappers, + and also avoids cross-module linking issues on Windows, where a + <code>FILE *</code> must be accessed by routines defined in the same module + that opened it. + \param[out] _cb The callbacks to use for this file. + If there is an error opening the file, nothing will be + filled in here. + \param _path The path to the file to open. + On Windows, this string must be UTF-8 (to allow access + to files whose names cannot be represented in the + current MBCS code page). + All other systems use the native character encoding. + \param _mode The mode to open the file in. + \param _stream A stream previously returned by op_fopen(), op_fdopen(), + or op_freopen(). + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_freopen(OpusFileCallbacks *_cb, + const char *_path,const char *_mode,void *_stream) OP_ARG_NONNULL(1) + OP_ARG_NONNULL(2) OP_ARG_NONNULL(3) OP_ARG_NONNULL(4); + +/**Creates a stream that reads from the given block of memory. + This block of memory must contain the complete stream to decode. + This is useful for caching small streams (e.g., sound effects) in RAM. + \param[out] _cb The callbacks to use for this stream. + If there is an error creating the stream, nothing will be + filled in here. + \param _data The block of memory to read from. + \param _size The size of the block of memory. + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_mem_stream_create(OpusFileCallbacks *_cb, + const unsigned char *_data,size_t _size) OP_ARG_NONNULL(1); + +/**Creates a stream that reads from the given URL. + This function behaves identically to op_url_stream_create(), except that it + takes a va_list instead of a variable number of arguments. + It does not call the <code>va_end</code> macro, and because it invokes the + <code>va_arg</code> macro, the value of \a _ap is undefined after the call. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \param[out] _cb The callbacks to use for this stream. + If there is an error creating the stream, nothing will + be filled in here. + \param _url The URL to read from. + Currently only the <file:>, <http:>, and <https:> + schemes are supported. + Both <http:> and <https:> may be disabled at compile + time, in which case opening such URLs will always fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, with + internationalized domain names encoded in punycode, + before passing them to this function. + \param[in,out] _ap A list of the \ref url_options "optional flags" to use. + This is a variable-length list of options terminated + with <code>NULL</code>. + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_url_stream_vcreate(OpusFileCallbacks *_cb, + const char *_url,va_list _ap) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/**Creates a stream that reads from the given URL. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \param[out] _cb The callbacks to use for this stream. + If there is an error creating the stream, nothing will be + filled in here. + \param _url The URL to read from. + Currently only the <file:>, <http:>, and <https:> schemes + are supported. + Both <http:> and <https:> may be disabled at compile time, + in which case opening such URLs will always fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, with + internationalized domain names encoded in punycode, before + passing them to this function. + \param ... The \ref url_options "optional flags" to use. + This is a variable-length list of options terminated with + <code>NULL</code>. + \return A stream handle to use with the callbacks, or <code>NULL</code> on + error.*/ +OP_WARN_UNUSED_RESULT void *op_url_stream_create(OpusFileCallbacks *_cb, + const char *_url,...) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); + +/*@}*/ +/*@}*/ + +/**\defgroup stream_open_close Opening and Closing*/ +/*@{*/ +/**\name Functions for opening and closing streams + + These functions allow you to test a stream to see if it is Opus, open it, + and close it. + Several flavors are provided for each of the built-in stream types, plus a + more general version which takes a set of application-provided callbacks.*/ +/*@{*/ + +/**Test to see if this is an Opus stream. + For good results, you will need at least 57 bytes (for a pure Opus-only + stream). + Something like 512 bytes will give more reliable results for multiplexed + streams. + This function is meant to be a quick-rejection filter. + Its purpose is not to guarantee that a stream is a valid Opus stream, but to + ensure that it looks enough like Opus that it isn't going to be recognized + as some other format (except possibly an Opus stream that is also + multiplexed with other codecs, such as video). + \param[out] _head The parsed ID header contents. + You may pass <code>NULL</code> if you do not need + this information. + If the function fails, the contents of this structure + remain untouched. + \param _initial_data An initial buffer of data from the start of the + stream. + \param _initial_bytes The number of bytes in \a _initial_data. + \return 0 if the data appears to be Opus, or a negative value on error. + \retval #OP_FALSE There was not enough data to tell if this was an Opus + stream or not. + \retval #OP_EFAULT An internal memory allocation failed. + \retval #OP_EIMPL The stream used a feature that is not implemented, + such as an unsupported channel family. + \retval #OP_ENOTFORMAT If the data did not contain a recognizable ID + header for an Opus stream. + \retval #OP_EVERSION If the version field signaled a version this library + does not know how to parse. + \retval #OP_EBADHEADER The ID header was not properly formatted or contained + illegal values.*/ +int op_test(OpusHead *_head, + const unsigned char *_initial_data,size_t _initial_bytes); + +/**Open a stream from the given file path. + \param _path The path to the file to open. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + The failure code will be #OP_EFAULT if the file could not + be opened, or one of the other failure codes from + op_open_callbacks() otherwise. + \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_open_file(const char *_path,int *_error) + OP_ARG_NONNULL(1); + +/**Open a stream from a memory buffer. + \param _data The memory buffer to open. + \param _size The number of bytes in the buffer. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + See op_open_callbacks() for a full list of failure codes. + \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_open_memory(const unsigned char *_data, + size_t _size,int *_error); + +/**Open a stream from a URL. + This function behaves identically to op_open_url(), except that it + takes a va_list instead of a variable number of arguments. + It does not call the <code>va_end</code> macro, and because it invokes the + <code>va_arg</code> macro, the value of \a _ap is undefined after the call. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \param _url The URL to open. + Currently only the <file:>, <http:>, and <https:> + schemes are supported. + Both <http:> and <https:> may be disabled at compile + time, in which case opening such URLs will always + fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, + with internationalized domain names encoded in + punycode, before passing them to this function. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want + the failure code. + See op_open_callbacks() for a full list of failure + codes. + \param[in,out] _ap A list of the \ref url_options "optional flags" to + use. + This is a variable-length list of options terminated + with <code>NULL</code>. + \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_vopen_url(const char *_url, + int *_error,va_list _ap) OP_ARG_NONNULL(1); + +/**Open a stream from a URL. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \param _url The URL to open. + Currently only the <file:>, <http:>, and <https:> schemes + are supported. + Both <http:> and <https:> may be disabled at compile + time, in which case opening such URLs will always fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, with + internationalized domain names encoded in punycode, + before passing them to this function. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + See op_open_callbacks() for a full list of failure codes. + \param ... The \ref url_options "optional flags" to use. + This is a variable-length list of options terminated with + <code>NULL</code>. + \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_open_url(const char *_url, + int *_error,...) OP_ARG_NONNULL(1); + +/**Open a stream using the given set of callbacks to access it. + \param _source The stream to read from (e.g., a <code>FILE *</code>). + \param _cb The callbacks with which to access the stream. + <code><a href="#op_read_func">read()</a></code> must + be implemented. + <code><a href="#op_seek_func">seek()</a></code> and + <code><a href="#op_tell_func">tell()</a></code> may + be <code>NULL</code>, or may always return -1 to + indicate a source is unseekable, but if + <code><a href="#op_seek_func">seek()</a></code> is + implemented and succeeds on a particular source, then + <code><a href="#op_tell_func">tell()</a></code> must + also. + <code><a href="#op_close_func">close()</a></code> may + be <code>NULL</code>, but if it is not, it will be + called when the \c OggOpusFile is destroyed by + op_free(). + It will not be called if op_open_callbacks() fails + with an error. + \param _initial_data An initial buffer of data from the start of the + stream. + Applications can read some number of bytes from the + start of the stream to help identify this as an Opus + stream, and then provide them here to allow the + stream to be opened, even if it is unseekable. + \param _initial_bytes The number of bytes in \a _initial_data. + If the stream is seekable, its current position (as + reported by + <code><a href="#opus_tell_func">tell()</a></code> + at the start of this function) must be equal to + \a _initial_bytes. + Otherwise, seeking to absolute positions will + generate inconsistent results. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want + the failure code. + The failure code will be one of + <dl> + <dt>#OP_EREAD</dt> + <dd>An underlying read, seek, or tell operation + failed when it should have succeeded, or we failed + to find data in the stream we had seen before.</dd> + <dt>#OP_EFAULT</dt> + <dd>There was a memory allocation failure, or an + internal library error.</dd> + <dt>#OP_EIMPL</dt> + <dd>The stream used a feature that is not + implemented, such as an unsupported channel + family.</dd> + <dt>#OP_EINVAL</dt> + <dd><code><a href="#op_seek_func">seek()</a></code> + was implemented and succeeded on this source, but + <code><a href="#op_tell_func">tell()</a></code> + did not, or the starting position indicator was + not equal to \a _initial_bytes.</dd> + <dt>#OP_ENOTFORMAT</dt> + <dd>The stream contained a link that did not have + any logical Opus streams in it.</dd> + <dt>#OP_EBADHEADER</dt> + <dd>A required header packet was not properly + formatted, contained illegal values, or was missing + altogether.</dd> + <dt>#OP_EVERSION</dt> + <dd>An ID header contained an unrecognized version + number.</dd> + <dt>#OP_EBADLINK</dt> + <dd>We failed to find data we had seen before after + seeking.</dd> + <dt>#OP_EBADTIMESTAMP</dt> + <dd>The first or last timestamp in a link failed + basic validity checks.</dd> + </dl> + \return A freshly opened \c OggOpusFile, or <code>NULL</code> on error. + <tt>libopusfile</tt> does <em>not</em> take ownership of the source + if the call fails. + The calling application is responsible for closing the source if + this call returns an error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_open_callbacks(void *_source, + const OpusFileCallbacks *_cb,const unsigned char *_initial_data, + size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2); + +/**Partially open a stream from the given file path. + \see op_test_callbacks + \param _path The path to the file to open. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + The failure code will be #OP_EFAULT if the file could not + be opened, or one of the other failure codes from + op_open_callbacks() otherwise. + \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_test_file(const char *_path,int *_error) + OP_ARG_NONNULL(1); + +/**Partially open a stream from a memory buffer. + \see op_test_callbacks + \param _data The memory buffer to open. + \param _size The number of bytes in the buffer. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + See op_open_callbacks() for a full list of failure codes. + \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_test_memory(const unsigned char *_data, + size_t _size,int *_error); + +/**Partially open a stream from a URL. + This function behaves identically to op_test_url(), except that it + takes a va_list instead of a variable number of arguments. + It does not call the <code>va_end</code> macro, and because it invokes the + <code>va_arg</code> macro, the value of \a _ap is undefined after the call. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \see op_test_url + \see op_test_callbacks + \param _url The URL to open. + Currently only the <file:>, <http:>, and <https:> + schemes are supported. + Both <http:> and <https:> may be disabled at compile + time, in which case opening such URLs will always + fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, + with internationalized domain names encoded in + punycode, before passing them to this function. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want + the failure code. + See op_open_callbacks() for a full list of failure + codes. + \param[in,out] _ap A list of the \ref url_options "optional flags" to + use. + This is a variable-length list of options terminated + with <code>NULL</code>. + \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_vtest_url(const char *_url, + int *_error,va_list _ap) OP_ARG_NONNULL(1); + +/**Partially open a stream from a URL. + \note If you use this function, you must link against <tt>libopusurl</tt>. + \see op_test_callbacks + \param _url The URL to open. + Currently only the <file:>, <http:>, and <https:> + schemes are supported. + Both <http:> and <https:> may be disabled at compile + time, in which case opening such URLs will always fail. + Currently this only supports URIs. + IRIs should be converted to UTF-8 and URL-escaped, with + internationalized domain names encoded in punycode, + before passing them to this function. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want the + failure code. + See op_open_callbacks() for a full list of failure + codes. + \param ... The \ref url_options "optional flags" to use. + This is a variable-length list of options terminated + with <code>NULL</code>. + \return A partially opened \c OggOpusFile, or <code>NULL</code> on error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_test_url(const char *_url, + int *_error,...) OP_ARG_NONNULL(1); + +/**Partially open a stream using the given set of callbacks to access it. + This tests for Opusness and loads the headers for the first link. + It does not seek (although it tests for seekability). + You can query a partially open stream for the few pieces of basic + information returned by op_serialno(), op_channel_count(), op_head(), and + op_tags() (but only for the first link). + You may also determine if it is seekable via a call to op_seekable(). + You cannot read audio from the stream, seek, get the size or duration, + get information from links other than the first one, or even get the total + number of links until you finish opening the stream with op_test_open(). + If you do not need to do any of these things, you can dispose of it with + op_free() instead. + + This function is provided mostly to simplify porting existing code that used + <tt>libvorbisfile</tt>. + For new code, you are likely better off using op_test() instead, which + is less resource-intensive, requires less data to succeed, and imposes a + hard limit on the amount of data it examines (important for unseekable + sources, where all such data must be buffered until you are sure of the + stream type). + \param _source The stream to read from (e.g., a <code>FILE *</code>). + \param _cb The callbacks with which to access the stream. + <code><a href="#op_read_func">read()</a></code> must + be implemented. + <code><a href="#op_seek_func">seek()</a></code> and + <code><a href="#op_tell_func">tell()</a></code> may + be <code>NULL</code>, or may always return -1 to + indicate a source is unseekable, but if + <code><a href="#op_seek_func">seek()</a></code> is + implemented and succeeds on a particular source, then + <code><a href="#op_tell_func">tell()</a></code> must + also. + <code><a href="#op_close_func">close()</a></code> may + be <code>NULL</code>, but if it is not, it will be + called when the \c OggOpusFile is destroyed by + op_free(). + It will not be called if op_open_callbacks() fails + with an error. + \param _initial_data An initial buffer of data from the start of the + stream. + Applications can read some number of bytes from the + start of the stream to help identify this as an Opus + stream, and then provide them here to allow the + stream to be tested more thoroughly, even if it is + unseekable. + \param _initial_bytes The number of bytes in \a _initial_data. + If the stream is seekable, its current position (as + reported by + <code><a href="#opus_tell_func">tell()</a></code> + at the start of this function) must be equal to + \a _initial_bytes. + Otherwise, seeking to absolute positions will + generate inconsistent results. + \param[out] _error Returns 0 on success, or a failure code on error. + You may pass in <code>NULL</code> if you don't want + the failure code. + See op_open_callbacks() for a full list of failure + codes. + \return A partially opened \c OggOpusFile, or <code>NULL</code> on error. + <tt>libopusfile</tt> does <em>not</em> take ownership of the source + if the call fails. + The calling application is responsible for closing the source if + this call returns an error.*/ +OP_WARN_UNUSED_RESULT OggOpusFile *op_test_callbacks(void *_source, + const OpusFileCallbacks *_cb,const unsigned char *_initial_data, + size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2); + +/**Finish opening a stream partially opened with op_test_callbacks() or one of + the associated convenience functions. + If this function fails, you are still responsible for freeing the + \c OggOpusFile with op_free(). + \param _of The \c OggOpusFile to finish opening. + \return 0 on success, or a negative value on error. + \retval #OP_EREAD An underlying read, seek, or tell operation failed + when it should have succeeded. + \retval #OP_EFAULT There was a memory allocation failure, or an + internal library error. + \retval #OP_EIMPL The stream used a feature that is not implemented, + such as an unsupported channel family. + \retval #OP_EINVAL The stream was not partially opened with + op_test_callbacks() or one of the associated + convenience functions. + \retval #OP_ENOTFORMAT The stream contained a link that did not have any + logical Opus streams in it. + \retval #OP_EBADHEADER A required header packet was not properly + formatted, contained illegal values, or was + missing altogether. + \retval #OP_EVERSION An ID header contained an unrecognized version + number. + \retval #OP_EBADLINK We failed to find data we had seen before after + seeking. + \retval #OP_EBADTIMESTAMP The first or last timestamp in a link failed basic + validity checks.*/ +int op_test_open(OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Release all memory used by an \c OggOpusFile. + \param _of The \c OggOpusFile to free.*/ +void op_free(OggOpusFile *_of); + +/*@}*/ +/*@}*/ + +/**\defgroup stream_info Stream Information*/ +/*@{*/ +/**\name Functions for obtaining information about streams + + These functions allow you to get basic information about a stream, including + seekability, the number of links (for chained streams), plus the size, + duration, bitrate, header parameters, and meta information for each link + (or, where available, the stream as a whole). + Some of these (size, duration) are only available for seekable streams. + You can also query the current stream position, link, and playback time, + and instantaneous bitrate during playback. + + Some of these functions may be used successfully on the partially open + streams returned by op_test_callbacks() or one of the associated + convenience functions. + Their documention will indicate so explicitly.*/ +/*@{*/ + +/**Returns whether or not the data source being read is seekable. + This is true if + <ol> + <li>The <code><a href="#op_seek_func">seek()</a></code> and + <code><a href="#op_tell_func">tell()</a></code> callbacks are both + non-<code>NULL</code>,</li> + <li>The <code><a href="#op_seek_func">seek()</a></code> callback was + successfully executed at least once, and</li> + <li>The <code><a href="#op_tell_func">tell()</a></code> callback was + successfully able to report the position indicator afterwards.</li> + </ol> + This function may be called on partially-opened streams. + \param _of The \c OggOpusFile whose seekable status is to be returned. + \return A non-zero value if seekable, and 0 if unseekable.*/ +int op_seekable(const OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Returns the number of links in this chained stream. + This function may be called on partially-opened streams, but it will always + return 1. + The actual number of links is not known until the stream is fully opened. + \param _of The \c OggOpusFile from which to retrieve the link count. + \return For fully-open seekable sources, this returns the total number of + links in the whole stream, which will be at least 1. + For partially-open or unseekable sources, this always returns 1.*/ +int op_link_count(const OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Get the serial number of the given link in a (possibly-chained) Ogg Opus + stream. + This function may be called on partially-opened streams, but it will always + return the serial number of the Opus stream in the first link. + \param _of The \c OggOpusFile from which to retrieve the serial number. + \param _li The index of the link whose serial number should be retrieved. + Use a negative number to get the serial number of the current + link. + \return The serial number of the given link. + If \a _li is greater than the total number of links, this returns + the serial number of the last link. + If the source is not seekable, this always returns the serial number + of the current link.*/ +opus_uint32 op_serialno(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Get the channel count of the given link in a (possibly-chained) Ogg Opus + stream. + This is equivalent to <code>op_head(_of,_li)->channel_count</code>, but + is provided for convenience. + This function may be called on partially-opened streams, but it will always + return the channel count of the Opus stream in the first link. + \param _of The \c OggOpusFile from which to retrieve the channel count. + \param _li The index of the link whose channel count should be retrieved. + Use a negative number to get the channel count of the current + link. + \return The channel count of the given link. + If \a _li is greater than the total number of links, this returns + the channel count of the last link. + If the source is not seekable, this always returns the channel count + of the current link.*/ +int op_channel_count(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Get the total (compressed) size of the stream, or of an individual link in + a (possibly-chained) Ogg Opus stream, including all headers and Ogg muxing + overhead. + \warning If the Opus stream (or link) is concurrently multiplexed with other + logical streams (e.g., video), this returns the size of the entire stream + (or link), not just the number of bytes in the first logical Opus stream. + Returning the latter would require scanning the entire file. + \param _of The \c OggOpusFile from which to retrieve the compressed size. + \param _li The index of the link whose compressed size should be computed. + Use a negative number to get the compressed size of the entire + stream. + \return The compressed size of the entire stream if \a _li is negative, the + compressed size of link \a _li if it is non-negative, or a negative + value on error. + The compressed size of the entire stream may be smaller than that + of the underlying source if trailing garbage was detected in the + file. + \retval #OP_EINVAL The source is not seekable (so we can't know the length), + \a _li wasn't less than the total number of links in + the stream, or the stream was only partially open.*/ +opus_int64 op_raw_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Get the total PCM length (number of samples at 48 kHz) of the stream, or of + an individual link in a (possibly-chained) Ogg Opus stream. + Users looking for <code>op_time_total()</code> should use op_pcm_total() + instead. + Because timestamps in Opus are fixed at 48 kHz, there is no need for a + separate function to convert this to seconds (and leaving it out avoids + introducing floating point to the API, for those that wish to avoid it). + \param _of The \c OggOpusFile from which to retrieve the PCM offset. + \param _li The index of the link whose PCM length should be computed. + Use a negative number to get the PCM length of the entire stream. + \return The PCM length of the entire stream if \a _li is negative, the PCM + length of link \a _li if it is non-negative, or a negative value on + error. + \retval #OP_EINVAL The source is not seekable (so we can't know the length), + \a _li wasn't less than the total number of links in + the stream, or the stream was only partially open.*/ +ogg_int64_t op_pcm_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Get the ID header information for the given link in a (possibly chained) Ogg + Opus stream. + This function may be called on partially-opened streams, but it will always + return the ID header information of the Opus stream in the first link. + \param _of The \c OggOpusFile from which to retrieve the ID header + information. + \param _li The index of the link whose ID header information should be + retrieved. + Use a negative number to get the ID header information of the + current link. + For an unseekable stream, \a _li is ignored, and the ID header + information for the current link is always returned, if + available. + \return The contents of the ID header for the given link.*/ +const OpusHead *op_head(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Get the comment header information for the given link in a (possibly + chained) Ogg Opus stream. + This function may be called on partially-opened streams, but it will always + return the tags from the Opus stream in the first link. + \param _of The \c OggOpusFile from which to retrieve the comment header + information. + \param _li The index of the link whose comment header information should be + retrieved. + Use a negative number to get the comment header information of + the current link. + For an unseekable stream, \a _li is ignored, and the comment + header information for the current link is always returned, if + available. + \return The contents of the comment header for the given link, or + <code>NULL</code> if this is an unseekable stream that encountered + an invalid link.*/ +const OpusTags *op_tags(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Retrieve the index of the current link. + This is the link that produced the data most recently read by + op_read_float() or its associated functions, or, after a seek, the link + that the seek target landed in. + Reading more data may advance the link index (even on the first read after a + seek). + \param _of The \c OggOpusFile from which to retrieve the current link index. + \return The index of the current link on success, or a negative value on + failure. + For seekable streams, this is a number between 0 and the value + returned by op_link_count(). + For unseekable streams, this value starts at 0 and increments by one + each time a new link is encountered (even though op_link_count() + always returns 1). + \retval #OP_EINVAL The stream was only partially open.*/ +int op_current_link(const OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Computes the bitrate of the stream, or of an individual link in a + (possibly-chained) Ogg Opus stream. + The stream must be seekable to compute the bitrate. + For unseekable streams, use op_bitrate_instant() to get periodic estimates. + \warning If the Opus stream (or link) is concurrently multiplexed with other + logical streams (e.g., video), this uses the size of the entire stream (or + link) to compute the bitrate, not just the number of bytes in the first + logical Opus stream. + Returning the latter requires scanning the entire file, but this may be done + by decoding the whole file and calling op_bitrate_instant() once at the + end. + Install a trivial decoding callback with op_set_decode_callback() if you + wish to skip actual decoding during this process. + \param _of The \c OggOpusFile from which to retrieve the bitrate. + \param _li The index of the link whose bitrate should be computed. + Use a negative number to get the bitrate of the whole stream. + \return The bitrate on success, or a negative value on error. + \retval #OP_EINVAL The stream was only partially open, the stream was not + seekable, or \a _li was larger than the number of + links.*/ +opus_int32 op_bitrate(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); + +/**Compute the instantaneous bitrate, measured as the ratio of bits to playable + samples decoded since a) the last call to op_bitrate_instant(), b) the last + seek, or c) the start of playback, whichever was most recent. + This will spike somewhat after a seek or at the start/end of a chain + boundary, as pre-skip, pre-roll, and end-trimming causes samples to be + decoded but not played. + \param _of The \c OggOpusFile from which to retrieve the bitrate. + \return The bitrate, in bits per second, or a negative value on error. + \retval #OP_FALSE No data has been decoded since any of the events + described above. + \retval #OP_EINVAL The stream was only partially open.*/ +opus_int32 op_bitrate_instant(OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Obtain the current value of the position indicator for \a _of. + \param _of The \c OggOpusFile from which to retrieve the position indicator. + \return The byte position that is currently being read from. + \retval #OP_EINVAL The stream was only partially open.*/ +opus_int64 op_raw_tell(const OggOpusFile *_of) OP_ARG_NONNULL(1); + +/**Obtain the PCM offset of the next sample to be read. + If the stream is not properly timestamped, this might not increment by the + proper amount between reads, or even return monotonically increasing + values. + \param _of The \c OggOpusFile from which to retrieve the PCM offset. + \return The PCM offset of the next sample to be read. + \retval #OP_EINVAL The stream was only partially open.*/ +ogg_int64_t op_pcm_tell(const OggOpusFile *_of) OP_ARG_NONNULL(1); + +/*@}*/ +/*@}*/ + +/**\defgroup stream_seeking Seeking*/ +/*@{*/ +/**\name Functions for seeking in Opus streams + + These functions let you seek in Opus streams, if the underlying source + support it. + Seeking is implemented for all built-in stream I/O routines, though some + individual sources may not be seekable (pipes, live HTTP streams, or HTTP + streams from a server that does not support <code>Range</code> requests). + + op_raw_seek() is the fastest: it is guaranteed to perform at most one + physical seek, but, since the target is a byte position, makes no guarantee + how close to a given time it will come. + op_pcm_seek() provides sample-accurate seeking. + The number of physical seeks it requires is still quite small (often 1 or + 2, even in highly variable bitrate streams). + + Seeking in Opus requires decoding some pre-roll amount before playback to + allow the internal state to converge (as if recovering from packet loss). + This is handled internally by <tt>libopusfile</tt>, but means there is + little extra overhead for decoding up to the exact position requested + (since it must decode some amount of audio anyway). + It also means that decoding after seeking may not return exactly the same + values as would be obtained by decoding the stream straight through. + However, such differences are expected to be smaller than the loss + introduced by Opus's lossy compression.*/ +/*@{*/ + +/**Seek to a byte offset relative to the <b>compressed</b> data. + This also scans packets to update the PCM cursor. + It will cross a logical bitstream boundary, but only if it can't get any + packets out of the tail of the link to which it seeks. + \param _of The \c OggOpusFile in which to seek. + \param _byte_offset The byte position to seek to. + \return 0 on success, or a negative error code on failure. + \retval #OP_EREAD The underlying seek operation failed. + \retval #OP_EINVAL The stream was only partially open, or the target was + outside the valid range for the stream. + \retval #OP_ENOSEEK This stream is not seekable. + \retval #OP_EBADLINK Failed to initialize a decoder for a stream for an + unknown reason.*/ +int op_raw_seek(OggOpusFile *_of,opus_int64 _byte_offset) OP_ARG_NONNULL(1); + +/**Seek to the specified PCM offset, such that decoding will begin at exactly + the requested position. + \param _of The \c OggOpusFile in which to seek. + \param _pcm_offset The PCM offset to seek to. + This is in samples at 48 kHz relative to the start of the + stream. + \return 0 on success, or a negative value on error. + \retval #OP_EREAD An underlying read or seek operation failed. + \retval #OP_EINVAL The stream was only partially open, or the target was + outside the valid range for the stream. + \retval #OP_ENOSEEK This stream is not seekable. + \retval #OP_EBADLINK We failed to find data we had seen before, or the + bitstream structure was sufficiently malformed that + seeking to the target destination was impossible.*/ +int op_pcm_seek(OggOpusFile *_of,ogg_int64_t _pcm_offset) OP_ARG_NONNULL(1); + +/*@}*/ +/*@}*/ + +/**\defgroup stream_decoding Decoding*/ +/*@{*/ +/**\name Functions for decoding audio data + + These functions retrieve actual decoded audio data from the stream. + The general functions, op_read() and op_read_float() return 16-bit or + floating-point output, both using native endian ordering. + The number of channels returned can change from link to link in a chained + stream. + There are special functions, op_read_stereo() and op_read_float_stereo(), + which always output two channels, to simplify applications which do not + wish to handle multichannel audio. + These downmix multichannel files to two channels, so they can always return + samples in the same format for every link in a chained file. + + If the rest of your audio processing chain can handle floating point, those + routines should be preferred, as floating point output avoids introducing + clipping and other issues which might be avoided entirely if, e.g., you + scale down the volume at some other stage. + However, if you intend to direct consume 16-bit samples, the conversion in + <tt>libopusfile</tt> provides noise-shaping dithering and, if compiled + against <tt>libopus</tt> 1.1 or later, soft-clipping prevention. + + <tt>libopusfile</tt> can also be configured at compile time to use the + fixed-point <tt>libopus</tt> API. + If so, <tt>libopusfile</tt>'s floating-point API may also be disabled. + In that configuration, nothing in <tt>libopusfile</tt> will use any + floating-point operations, to simplify support on devices without an + adequate FPU. + + \warning HTTPS streams may be be vulnerable to truncation attacks if you do + not check the error return code from op_read_float() or its associated + functions. + If the remote peer does not close the connection gracefully (with a TLS + "close notify" message), these functions will return #OP_EREAD instead of 0 + when they reach the end of the file. + If you are reading from an <https:> URL (particularly if seeking is not + supported), you should make sure to check for this error and warn the user + appropriately.*/ +/*@{*/ + +/**Indicates that the decoding callback should produce signed 16-bit + native-endian output samples.*/ +#define OP_DEC_FORMAT_SHORT (7008) +/**Indicates that the decoding callback should produce 32-bit native-endian + float samples.*/ +#define OP_DEC_FORMAT_FLOAT (7040) + +/**Indicates that the decoding callback did not decode anything, and that + <tt>libopusfile</tt> should decode normally instead.*/ +#define OP_DEC_USE_DEFAULT (6720) + +/**Called to decode an Opus packet. + This should invoke the functional equivalent of opus_multistream_decode() or + opus_multistream_decode_float(), except that it returns 0 on success + instead of the number of decoded samples (which is known a priori). + \param _ctx The application-provided callback context. + \param _decoder The decoder to use to decode the packet. + \param[out] _pcm The buffer to decode into. + This will always have enough room for \a _nchannels of + \a _nsamples samples, which should be placed into this + buffer interleaved. + \param _op The packet to decode. + This will always have its granule position set to a valid + value. + \param _nsamples The number of samples expected from the packet. + \param _nchannels The number of channels expected from the packet. + \param _format The desired sample output format. + This is either #OP_DEC_FORMAT_SHORT or + #OP_DEC_FORMAT_FLOAT. + \param _li The index of the link from which this packet was decoded. + \return A non-negative value on success, or a negative value on error. + The error codes should be the same as those returned by + opus_multistream_decode() or opus_multistream_decode_float(). + \retval 0 Decoding was successful. + The application has filled the buffer with + exactly <code>\a _nsamples*\a + _nchannels</code> samples in the requested + format. + \retval #OP_DEC_USE_DEFAULT No decoding was done. + <tt>libopusfile</tt> should decode normally + instead.*/ +typedef int (*op_decode_cb_func)(void *_ctx,OpusMSDecoder *_decoder,void *_pcm, + const ogg_packet *_op,int _nsamples,int _nchannels,int _format,int _li); + +/**Sets the packet decode callback function. + This is called once for each packet that needs to be decoded. + A call to this function is no guarantee that the audio will eventually be + delivered to the application. + Some or all of the data from the packet may be discarded (i.e., at the + beginning or end of a link, or after a seek), however the callback is + required to provide all of it. + \param _of The \c OggOpusFile on which to set the decode callback. + \param _decode_cb The callback function to call. + This may be <code>NULL</code> to disable calling the + callback. + \param _ctx The application-provided context pointer to pass to the + callback on each call.*/ +void op_set_decode_callback(OggOpusFile *_of, + op_decode_cb_func _decode_cb,void *_ctx) OP_ARG_NONNULL(1); + +/**Gain offset type that indicates that the provided offset is relative to the + header gain. + This is the default.*/ +#define OP_HEADER_GAIN (0) + +/**Gain offset type that indicates that the provided offset is relative to the + R128_TRACK_GAIN value (if any), in addition to the header gain.*/ +#define OP_TRACK_GAIN (3008) + +/**Gain offset type that indicates that the provided offset should be used as + the gain directly, without applying any the header or track gains.*/ +#define OP_ABSOLUTE_GAIN (3009) + +/**Sets the gain to be used for decoded output. + By default, the gain in the header is applied with no additional offset. + The total gain (including header gain and/or track gain, if applicable, and + this offset), will be clamped to [-32768,32767]/256 dB. + This is more than enough to saturate or underflow 16-bit PCM. + \note The new gain will not be applied to any already buffered, decoded + output. + This means you cannot change it sample-by-sample, as at best it will be + updated packet-by-packet. + It is meant for setting a target volume level, rather than applying smooth + fades, etc. + \param _of The \c OggOpusFile on which to set the gain offset. + \param _gain_type One of #OP_HEADER_GAIN, #OP_TRACK_GAIN, or + #OP_ABSOLUTE_GAIN. + \param _gain_offset_q8 The gain offset to apply, in 1/256ths of a dB. + \return 0 on success or a negative value on error. + \retval #OP_EINVAL The \a _gain_type was unrecognized.*/ +int op_set_gain_offset(OggOpusFile *_of, + int _gain_type,opus_int32 _gain_offset_q8) OP_ARG_NONNULL(1); + +/**Sets whether or not dithering is enabled for 16-bit decoding. + By default, when <tt>libopusfile</tt> is compiled to use floating-point + internally, calling op_read() or op_read_stereo() will first decode to + float, and then convert to fixed-point using noise-shaping dithering. + This flag can be used to disable that dithering. + When the application uses op_read_float() or op_read_float_stereo(), or when + the library has been compiled to decode directly to fixed point, this flag + has no effect. + \param _of The \c OggOpusFile on which to enable or disable dithering. + \param _enabled A non-zero value to enable dithering, or 0 to disable it.*/ +void op_set_dither_enabled(OggOpusFile *_of,int _enabled) OP_ARG_NONNULL(1); + +/**Reads more samples from the stream. + \note Although \a _buf_size must indicate the total number of values that + can be stored in \a _pcm, the return value is the number of samples + <em>per channel</em>. + This is done because + <ol> + <li>The channel count cannot be known a priori (reading more samples might + advance us into the next link, with a different channel count), so + \a _buf_size cannot also be in units of samples per channel,</li> + <li>Returning the samples per channel matches the <code>libopus</code> API + as closely as we're able,</li> + <li>Returning the total number of values instead of samples per channel + would mean the caller would need a division to compute the samples per + channel, and might worry about the possibility of getting back samples + for some channels and not others, and</li> + <li>This approach is relatively fool-proof: if an application passes too + small a value to \a _buf_size, they will simply get fewer samples back, + and if they assume the return value is the total number of values, then + they will simply read too few (rather than reading too many and going + off the end of the buffer).</li> + </ol> + \param _of The \c OggOpusFile from which to read. + \param[out] _pcm A buffer in which to store the output PCM samples, as + signed native-endian 16-bit values at 48 kHz + with a nominal range of <code>[-32768,32767)</code>. + Multiple channels are interleaved using the + <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis + channel ordering</a>. + This must have room for at least \a _buf_size values. + \param _buf_size The number of values that can be stored in \a _pcm. + It is recommended that this be large enough for at + least 120 ms of data at 48 kHz per channel (5760 + values per channel). + Smaller buffers will simply return less data, possibly + consuming more memory to buffer the data internally. + <tt>libopusfile</tt> may return less data than + requested. + If so, there is no guarantee that the remaining data + in \a _pcm will be unmodified. + \param[out] _li The index of the link this data was decoded from. + You may pass <code>NULL</code> if you do not need this + information. + If this function fails (returning a negative value), + this parameter is left unset. + \return The number of samples read per channel on success, or a negative + value on failure. + The channel count can be retrieved on success by calling + <code>op_head(_of,*_li)</code>. + The number of samples returned may be 0 if the buffer was too small + to store even a single sample for all channels, or if end-of-file + was reached. + The list of possible failure codes follows. + Most of them can only be returned by unseekable, chained streams + that encounter a new link. + \retval #OP_HOLE There was a hole in the data, and some samples + may have been skipped. + Call this function again to continue decoding + past the hole. + \retval #OP_EREAD An underlying read operation failed. + This may signal a truncation attack from an + <https:> source. + \retval #OP_EFAULT An internal memory allocation failed. + \retval #OP_EIMPL An unseekable stream encountered a new link that + used a feature that is not implemented, such as + an unsupported channel family. + \retval #OP_EINVAL The stream was only partially open. + \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that + did not have any logical Opus streams in it. + \retval #OP_EBADHEADER An unseekable stream encountered a new link with a + required header packet that was not properly + formatted, contained illegal values, or was + missing altogether. + \retval #OP_EVERSION An unseekable stream encountered a new link with + an ID header that contained an unrecognized + version number. + \retval #OP_EBADPACKET Failed to properly decode the next packet. + \retval #OP_EBADLINK We failed to find data we had seen before. + \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with + a starting timestamp that failed basic validity + checks.*/ +OP_WARN_UNUSED_RESULT int op_read(OggOpusFile *_of, + opus_int16 *_pcm,int _buf_size,int *_li) OP_ARG_NONNULL(1); + +/**Reads more samples from the stream. + \note Although \a _buf_size must indicate the total number of values that + can be stored in \a _pcm, the return value is the number of samples + <em>per channel</em>. + <ol> + <li>The channel count cannot be known a priori (reading more samples might + advance us into the next link, with a different channel count), so + \a _buf_size cannot also be in units of samples per channel,</li> + <li>Returning the samples per channel matches the <code>libopus</code> API + as closely as we're able,</li> + <li>Returning the total number of values instead of samples per channel + would mean the caller would need a division to compute the samples per + channel, and might worry about the possibility of getting back samples + for some channels and not others, and</li> + <li>This approach is relatively fool-proof: if an application passes too + small a value to \a _buf_size, they will simply get fewer samples back, + and if they assume the return value is the total number of values, then + they will simply read too few (rather than reading too many and going + off the end of the buffer).</li> + </ol> + \param _of The \c OggOpusFile from which to read. + \param[out] _pcm A buffer in which to store the output PCM samples as + signed floats at 48 kHz with a nominal range of + <code>[-1.0,1.0]</code>. + Multiple channels are interleaved using the + <a href="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">Vorbis + channel ordering</a>. + This must have room for at least \a _buf_size floats. + \param _buf_size The number of floats that can be stored in \a _pcm. + It is recommended that this be large enough for at + least 120 ms of data at 48 kHz per channel (5760 + samples per channel). + Smaller buffers will simply return less data, possibly + consuming more memory to buffer the data internally. + If less than \a _buf_size values are returned, + <tt>libopusfile</tt> makes no guarantee that the + remaining data in \a _pcm will be unmodified. + \param[out] _li The index of the link this data was decoded from. + You may pass <code>NULL</code> if you do not need this + information. + If this function fails (returning a negative value), + this parameter is left unset. + \return The number of samples read per channel on success, or a negative + value on failure. + The channel count can be retrieved on success by calling + <code>op_head(_of,*_li)</code>. + The number of samples returned may be 0 if the buffer was too small + to store even a single sample for all channels, or if end-of-file + was reached. + The list of possible failure codes follows. + Most of them can only be returned by unseekable, chained streams + that encounter a new link. + \retval #OP_HOLE There was a hole in the data, and some samples + may have been skipped. + Call this function again to continue decoding + past the hole. + \retval #OP_EREAD An underlying read operation failed. + This may signal a truncation attack from an + <https:> source. + \retval #OP_EFAULT An internal memory allocation failed. + \retval #OP_EIMPL An unseekable stream encountered a new link that + used a feature that is not implemented, such as + an unsupported channel family. + \retval #OP_EINVAL The stream was only partially open. + \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that + did not have any logical Opus streams in it. + \retval #OP_EBADHEADER An unseekable stream encountered a new link with a + required header packet that was not properly + formatted, contained illegal values, or was + missing altogether. + \retval #OP_EVERSION An unseekable stream encountered a new link with + an ID header that contained an unrecognized + version number. + \retval #OP_EBADPACKET Failed to properly decode the next packet. + \retval #OP_EBADLINK We failed to find data we had seen before. + \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with + a starting timestamp that failed basic validity + checks.*/ +OP_WARN_UNUSED_RESULT int op_read_float(OggOpusFile *_of, + float *_pcm,int _buf_size,int *_li) OP_ARG_NONNULL(1); + +/**Reads more samples from the stream and downmixes to stereo, if necessary. + This function is intended for simple players that want a uniform output + format, even if the channel count changes between links in a chained + stream. + \note \a _buf_size indicates the total number of values that can be stored + in \a _pcm, while the return value is the number of samples <em>per + channel</em>, even though the channel count is known, for consistency with + op_read(). + \param _of The \c OggOpusFile from which to read. + \param[out] _pcm A buffer in which to store the output PCM samples, as + signed native-endian 16-bit values at 48 kHz + with a nominal range of <code>[-32768,32767)</code>. + The left and right channels are interleaved in the + buffer. + This must have room for at least \a _buf_size values. + \param _buf_size The number of values that can be stored in \a _pcm. + It is recommended that this be large enough for at + least 120 ms of data at 48 kHz per channel (11520 + values total). + Smaller buffers will simply return less data, possibly + consuming more memory to buffer the data internally. + If less than \a _buf_size values are returned, + <tt>libopusfile</tt> makes no guarantee that the + remaining data in \a _pcm will be unmodified. + \return The number of samples read per channel on success, or a negative + value on failure. + The number of samples returned may be 0 if the buffer was too small + to store even a single sample for both channels, or if end-of-file + was reached. + The list of possible failure codes follows. + Most of them can only be returned by unseekable, chained streams + that encounter a new link. + \retval #OP_HOLE There was a hole in the data, and some samples + may have been skipped. + Call this function again to continue decoding + past the hole. + \retval #OP_EREAD An underlying read operation failed. + This may signal a truncation attack from an + <https:> source. + \retval #OP_EFAULT An internal memory allocation failed. + \retval #OP_EIMPL An unseekable stream encountered a new link that + used a feature that is not implemented, such as + an unsupported channel family. + \retval #OP_EINVAL The stream was only partially open. + \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that + did not have any logical Opus streams in it. + \retval #OP_EBADHEADER An unseekable stream encountered a new link with a + required header packet that was not properly + formatted, contained illegal values, or was + missing altogether. + \retval #OP_EVERSION An unseekable stream encountered a new link with + an ID header that contained an unrecognized + version number. + \retval #OP_EBADPACKET Failed to properly decode the next packet. + \retval #OP_EBADLINK We failed to find data we had seen before. + \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with + a starting timestamp that failed basic validity + checks.*/ +OP_WARN_UNUSED_RESULT int op_read_stereo(OggOpusFile *_of, + opus_int16 *_pcm,int _buf_size) OP_ARG_NONNULL(1); + +/**Reads more samples from the stream and downmixes to stereo, if necessary. + This function is intended for simple players that want a uniform output + format, even if the channel count changes between links in a chained + stream. + \note \a _buf_size indicates the total number of values that can be stored + in \a _pcm, while the return value is the number of samples <em>per + channel</em>, even though the channel count is known, for consistency with + op_read_float(). + \param _of The \c OggOpusFile from which to read. + \param[out] _pcm A buffer in which to store the output PCM samples, as + signed floats at 48 kHz with a nominal range of + <code>[-1.0,1.0]</code>. + The left and right channels are interleaved in the + buffer. + This must have room for at least \a _buf_size values. + \param _buf_size The number of values that can be stored in \a _pcm. + It is recommended that this be large enough for at + least 120 ms of data at 48 kHz per channel (11520 + values total). + Smaller buffers will simply return less data, possibly + consuming more memory to buffer the data internally. + If less than \a _buf_size values are returned, + <tt>libopusfile</tt> makes no guarantee that the + remaining data in \a _pcm will be unmodified. + \return The number of samples read per channel on success, or a negative + value on failure. + The number of samples returned may be 0 if the buffer was too small + to store even a single sample for both channels, or if end-of-file + was reached. + The list of possible failure codes follows. + Most of them can only be returned by unseekable, chained streams + that encounter a new link. + \retval #OP_HOLE There was a hole in the data, and some samples + may have been skipped. + Call this function again to continue decoding + past the hole. + \retval #OP_EREAD An underlying read operation failed. + This may signal a truncation attack from an + <https:> source. + \retval #OP_EFAULT An internal memory allocation failed. + \retval #OP_EIMPL An unseekable stream encountered a new link that + used a feature that is not implemented, such as + an unsupported channel family. + \retval #OP_EINVAL The stream was only partially open. + \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that + that did not have any logical Opus streams in it. + \retval #OP_EBADHEADER An unseekable stream encountered a new link with a + required header packet that was not properly + formatted, contained illegal values, or was + missing altogether. + \retval #OP_EVERSION An unseekable stream encountered a new link with + an ID header that contained an unrecognized + version number. + \retval #OP_EBADPACKET Failed to properly decode the next packet. + \retval #OP_EBADLINK We failed to find data we had seen before. + \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with + a starting timestamp that failed basic validity + checks.*/ +OP_WARN_UNUSED_RESULT int op_read_float_stereo(OggOpusFile *_of, + float *_pcm,int _buf_size) OP_ARG_NONNULL(1); + +/*@}*/ +/*@}*/ + +# if OP_GNUC_PREREQ(4,0) +# pragma GCC visibility pop +# endif + +# if defined(__cplusplus) +} +# endif + +#endif diff --git a/other/opus/linux/lib32/libogg.a b/other/opus/linux/lib32/libogg.a new file mode 100644 index 0000000..357b714 Binary files /dev/null and b/other/opus/linux/lib32/libogg.a differ diff --git a/other/opus/linux/lib32/libopus.a b/other/opus/linux/lib32/libopus.a new file mode 100644 index 0000000..36646bd Binary files /dev/null and b/other/opus/linux/lib32/libopus.a differ diff --git a/other/opus/linux/lib32/libopusfile.a b/other/opus/linux/lib32/libopusfile.a new file mode 100644 index 0000000..7db80f6 Binary files /dev/null and b/other/opus/linux/lib32/libopusfile.a differ diff --git a/other/opus/linux/lib64/libogg.a b/other/opus/linux/lib64/libogg.a new file mode 100644 index 0000000..8e85a95 Binary files /dev/null and b/other/opus/linux/lib64/libogg.a differ diff --git a/other/opus/linux/lib64/libopus.a b/other/opus/linux/lib64/libopus.a new file mode 100644 index 0000000..9745837 Binary files /dev/null and b/other/opus/linux/lib64/libopus.a differ diff --git a/other/opus/linux/lib64/libopusfile.a b/other/opus/linux/lib64/libopusfile.a new file mode 100644 index 0000000..6ad787f Binary files /dev/null and b/other/opus/linux/lib64/libopusfile.a differ diff --git a/other/opus/ogg.lua b/other/opus/ogg.lua new file mode 100644 index 0000000..d4e01a3 --- /dev/null +++ b/other/opus/ogg.lua @@ -0,0 +1,93 @@ +Ogg = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.lib_path = nil + + if IsNegativeTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = false + elseif IsPositiveTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = true + end + + if family ~= "windows" and ExecuteSilent("pkg-config ogg") == 0 then + option.value = true + if option.use_pkgconfig == nil then + option.use_pkgconfig = true + end + end + + if option.use_pkgconfig == nil then + option.use_pkgconfig = false + end + + if platform == "win32" then + option.value = true + elseif platform == "win64" then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "32") then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "64") then + option.value = true + elseif platform == "linux" and arch == "ia32" then + option.value = true + elseif platform == "linux" and arch == "amd64" then + option.value = true + end + end + + local apply = function(option, settings) + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config --cflags ogg`") + settings.link.flags:Add("`pkg-config --libs ogg`") + else + settings.cc.includes:Add(Ogg.basepath .. "/include") + settings.cc.includes:Add(Ogg.basepath .. "/include/ogg") + + if family ~= "windows" then + settings.link.libs:Add("ogg") + end + + if platform == "win32" then + client_settings.link.libpath:Add("other/opus/windows/lib32") + elseif platform == "win64" then + client_settings.link.libpath:Add("other/opus/windows/lib64") + elseif platform == "macosx" and string.find(settings.config_name, "32") then + client_settings.link.libpath:Add("other/opus/mac/lib32") + elseif platform == "macosx" and string.find(settings.config_name, "64") then + client_settings.link.libpath:Add("other/opus/mac/lib64") + elseif platform == "linux" then + client_settings.link.libpath:Add("other/opus/linux/lib64") + client_settings.link.libpath:Add("other/opus/linux/lib32") + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + return "using bundled libs" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/opus/opus.lua b/other/opus/opus.lua new file mode 100644 index 0000000..f8a7e8d --- /dev/null +++ b/other/opus/opus.lua @@ -0,0 +1,93 @@ +Opus = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.lib_path = nil + + if IsNegativeTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = false + elseif IsPositiveTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = true + end + + if family ~= "windows" and ExecuteSilent("pkg-config opus") == 0 then + option.value = true + if option.use_pkgconfig == nil then + option.use_pkgconfig = true + end + end + + if option.use_pkgconfig == nil then + option.use_pkgconfig = false + end + + if platform == "win32" then + option.value = true + elseif platform == "win64" then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "32") then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "64") then + option.value = true + elseif platform == "linux" and arch == "ia32" then + option.value = true + elseif platform == "linux" and arch == "amd64" then + option.value = true + end + end + + local apply = function(option, settings) + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config --cflags opus`") + settings.link.flags:Add("`pkg-config --libs opus`") + else + settings.cc.includes:Add(Opus.basepath .. "/include") + settings.cc.includes:Add(Opus.basepath .. "/include/opus") + + if family ~= "windows" then + settings.link.libs:Add("opus") + end + + if platform == "win32" then + client_settings.link.libpath:Add("other/opus/windows/lib32") + elseif platform == "win64" then + client_settings.link.libpath:Add("other/opus/windows/lib64") + elseif platform == "macosx" and string.find(settings.config_name, "32") then + client_settings.link.libpath:Add("other/opus/mac/lib32") + elseif platform == "macosx" and string.find(settings.config_name, "64") then + client_settings.link.libpath:Add("other/opus/mac/lib64") + elseif platform == "linux" then + client_settings.link.libpath:Add("other/opus/linux/lib64") + client_settings.link.libpath:Add("other/opus/linux/lib32") + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + return "using bundled libs" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/opus/opusfile.lua b/other/opus/opusfile.lua new file mode 100644 index 0000000..e294d51 --- /dev/null +++ b/other/opus/opusfile.lua @@ -0,0 +1,93 @@ +Opusfile = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.lib_path = nil + + if IsNegativeTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = false + elseif IsPositiveTerm(ScriptArgs[name .. ".use_pkgconfig"]) then + option.use_pkgconfig = true + end + + if family ~= "windows" and ExecuteSilent("pkg-config opusfile") == 0 then + option.value = true + if option.use_pkgconfig == nil then + option.use_pkgconfig = true + end + end + + if option.use_pkgconfig == nil then + option.use_pkgconfig = false + end + + if platform == "win32" then + option.value = true + elseif platform == "win64" then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "32") then + option.value = true + elseif platform == "macosx" and string.find(settings.config_name, "64") then + option.value = true + elseif platform == "linux" and arch == "ia32" then + option.value = true + elseif platform == "linux" and arch == "amd64" then + option.value = true + end + end + + local apply = function(option, settings) + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config --cflags opusfile`") + settings.link.flags:Add("`pkg-config --libs opusfile`") + else + settings.cc.includes:Add(Opusfile.basepath .. "/include") + settings.cc.includes:Add(Opusfile.basepath .. "/include/opus") + + if family ~= "windows" then + settings.link.libs:Add("opusfile") + end + + if platform == "win32" then + client_settings.link.libpath:Add("other/opus/windows/lib32") + elseif platform == "win64" then + client_settings.link.libpath:Add("other/opus/windows/lib64") + elseif platform == "macosx" and string.find(settings.config_name, "32") then + client_settings.link.libpath:Add("other/opus/mac/lib32") + elseif platform == "macosx" and string.find(settings.config_name, "64") then + client_settings.link.libpath:Add("other/opus/mac/lib64") + elseif platform == "linux" then + client_settings.link.libpath:Add("other/opus/linux/lib64") + client_settings.link.libpath:Add("other/opus/linux/lib32") + end + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + return "using bundled libs" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/opus/windows/lib32/libopusfile-0.lib b/other/opus/windows/lib32/libopusfile-0.lib new file mode 100644 index 0000000..bb5638f Binary files /dev/null and b/other/opus/windows/lib32/libopusfile-0.lib differ diff --git a/other/sdl/include/SDL.h b/other/sdl/include/SDL.h new file mode 100644 index 0000000..119ed7f --- /dev/null +++ b/other/sdl/include/SDL.h @@ -0,0 +1,101 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL.h + * Main include header for the SDL library + */ + +#ifndef _SDL_H +#define _SDL_H + +#include "SDL_main.h" +#include "SDL_stdinc.h" +#include "SDL_audio.h" +#include "SDL_cdrom.h" +#include "SDL_cpuinfo.h" +#include "SDL_endian.h" +#include "SDL_error.h" +#include "SDL_events.h" +#include "SDL_loadso.h" +#include "SDL_mutex.h" +#include "SDL_rwops.h" +#include "SDL_thread.h" +#include "SDL_timer.h" +#include "SDL_video.h" +#include "SDL_version.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @file SDL.h + * @note As of version 0.5, SDL is loaded dynamically into the application + */ + +/** @name SDL_INIT Flags + * These are the flags which may be passed to SDL_Init() -- you should + * specify the subsystems which you will be using in your application. + */ +/*@{*/ +#define SDL_INIT_TIMER 0x00000001 +#define SDL_INIT_AUDIO 0x00000010 +#define SDL_INIT_VIDEO 0x00000020 +#define SDL_INIT_CDROM 0x00000100 +#define SDL_INIT_JOYSTICK 0x00000200 +#define SDL_INIT_NOPARACHUTE 0x00100000 /**< Don't catch fatal signals */ +#define SDL_INIT_EVENTTHREAD 0x01000000 /**< Not supported on all OS's */ +#define SDL_INIT_EVERYTHING 0x0000FFFF +/*@}*/ + +/** This function loads the SDL dynamically linked library and initializes + * the subsystems specified by 'flags' (and those satisfying dependencies) + * Unless the SDL_INIT_NOPARACHUTE flag is set, it will install cleanup + * signal handlers for some commonly ignored fatal signals (like SIGSEGV) + */ +extern DECLSPEC int SDLCALL SDL_Init(Uint32 flags); + +/** This function initializes specific SDL subsystems */ +extern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags); + +/** This function cleans up specific SDL subsystems */ +extern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags); + +/** This function returns mask of the specified subsystems which have + * been initialized. + * If 'flags' is 0, it returns a mask of all initialized subsystems. + */ +extern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags); + +/** This function cleans up all initialized subsystems and unloads the + * dynamically linked library. You should call it upon all exit conditions. + */ +extern DECLSPEC void SDLCALL SDL_Quit(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_H */ diff --git a/other/sdl/include/SDL_active.h b/other/sdl/include/SDL_active.h new file mode 100644 index 0000000..0ae92f2 --- /dev/null +++ b/other/sdl/include/SDL_active.h @@ -0,0 +1,63 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_active.h + * Include file for SDL application focus event handling + */ + +#ifndef _SDL_active_h +#define _SDL_active_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @name The available application states */ +/*@{*/ +#define SDL_APPMOUSEFOCUS 0x01 /**< The app has mouse coverage */ +#define SDL_APPINPUTFOCUS 0x02 /**< The app has input focus */ +#define SDL_APPACTIVE 0x04 /**< The application is active */ +/*@}*/ + +/* Function prototypes */ +/** + * This function returns the current state of the application, which is a + * bitwise combination of SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, and + * SDL_APPACTIVE. If SDL_APPACTIVE is set, then the user is able to + * see your application, otherwise it has been iconified or disabled. + */ +extern DECLSPEC Uint8 SDLCALL SDL_GetAppState(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_active_h */ diff --git a/other/sdl/include/SDL_audio.h b/other/sdl/include/SDL_audio.h new file mode 100644 index 0000000..3a8e7fa --- /dev/null +++ b/other/sdl/include/SDL_audio.h @@ -0,0 +1,284 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_audio.h + * Access to the raw audio mixing buffer for the SDL library + */ + +#ifndef _SDL_audio_h +#define _SDL_audio_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_endian.h" +#include "SDL_mutex.h" +#include "SDL_thread.h" +#include "SDL_rwops.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * When filling in the desired audio spec structure, + * - 'desired->freq' should be the desired audio frequency in samples-per-second. + * - 'desired->format' should be the desired audio format. + * - 'desired->samples' is the desired size of the audio buffer, in samples. + * This number should be a power of two, and may be adjusted by the audio + * driver to a value more suitable for the hardware. Good values seem to + * range between 512 and 8096 inclusive, depending on the application and + * CPU speed. Smaller values yield faster response time, but can lead + * to underflow if the application is doing heavy processing and cannot + * fill the audio buffer in time. A stereo sample consists of both right + * and left channels in LR ordering. + * Note that the number of samples is directly related to time by the + * following formula: ms = (samples*1000)/freq + * - 'desired->size' is the size in bytes of the audio buffer, and is + * calculated by SDL_OpenAudio(). + * - 'desired->silence' is the value used to set the buffer to silence, + * and is calculated by SDL_OpenAudio(). + * - 'desired->callback' should be set to a function that will be called + * when the audio device is ready for more data. It is passed a pointer + * to the audio buffer, and the length in bytes of the audio buffer. + * This function usually runs in a separate thread, and so you should + * protect data structures that it accesses by calling SDL_LockAudio() + * and SDL_UnlockAudio() in your code. + * - 'desired->userdata' is passed as the first parameter to your callback + * function. + * + * @note The calculated values in this structure are calculated by SDL_OpenAudio() + * + */ +typedef struct SDL_AudioSpec { + int freq; /**< DSP frequency -- samples per second */ + Uint16 format; /**< Audio data format */ + Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */ + Uint8 silence; /**< Audio buffer silence value (calculated) */ + Uint16 samples; /**< Audio buffer size in samples (power of 2) */ + Uint16 padding; /**< Necessary for some compile environments */ + Uint32 size; /**< Audio buffer size in bytes (calculated) */ + /** + * This function is called when the audio device needs more data. + * + * @param[out] stream A pointer to the audio data buffer + * @param[in] len The length of the audio buffer in bytes. + * + * Once the callback returns, the buffer will no longer be valid. + * Stereo samples are stored in a LRLRLR ordering. + */ + void (SDLCALL *callback)(void *userdata, Uint8 *stream, int len); + void *userdata; +} SDL_AudioSpec; + +/** + * @name Audio format flags + * defaults to LSB byte order + */ +/*@{*/ +#define AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */ +#define AUDIO_S8 0x8008 /**< Signed 8-bit samples */ +#define AUDIO_U16LSB 0x0010 /**< Unsigned 16-bit samples */ +#define AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */ +#define AUDIO_U16MSB 0x1010 /**< As above, but big-endian byte order */ +#define AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */ +#define AUDIO_U16 AUDIO_U16LSB +#define AUDIO_S16 AUDIO_S16LSB + +/** + * @name Native audio byte ordering + */ +/*@{*/ +#if SDL_BYTEORDER == SDL_LIL_ENDIAN +#define AUDIO_U16SYS AUDIO_U16LSB +#define AUDIO_S16SYS AUDIO_S16LSB +#else +#define AUDIO_U16SYS AUDIO_U16MSB +#define AUDIO_S16SYS AUDIO_S16MSB +#endif +/*@}*/ + +/*@}*/ + + +/** A structure to hold a set of audio conversion filters and buffers */ +typedef struct SDL_AudioCVT { + int needed; /**< Set to 1 if conversion possible */ + Uint16 src_format; /**< Source audio format */ + Uint16 dst_format; /**< Target audio format */ + double rate_incr; /**< Rate conversion increment */ + Uint8 *buf; /**< Buffer to hold entire audio data */ + int len; /**< Length of original audio buffer */ + int len_cvt; /**< Length of converted audio buffer */ + int len_mult; /**< buffer must be len*len_mult big */ + double len_ratio; /**< Given len, final size is len*len_ratio */ + void (SDLCALL *filters[10])(struct SDL_AudioCVT *cvt, Uint16 format); + int filter_index; /**< Current audio conversion function */ +} SDL_AudioCVT; + + +/* Function prototypes */ + +/** + * @name Audio Init and Quit + * These functions are used internally, and should not be used unless you + * have a specific need to specify the audio driver you want to use. + * You should normally use SDL_Init() or SDL_InitSubSystem(). + */ +/*@{*/ +extern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name); +extern DECLSPEC void SDLCALL SDL_AudioQuit(void); +/*@}*/ + +/** + * This function fills the given character buffer with the name of the + * current audio driver, and returns a pointer to it if the audio driver has + * been initialized. It returns NULL if no driver has been initialized. + */ +extern DECLSPEC char * SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen); + +/** + * This function opens the audio device with the desired parameters, and + * returns 0 if successful, placing the actual hardware parameters in the + * structure pointed to by 'obtained'. If 'obtained' is NULL, the audio + * data passed to the callback function will be guaranteed to be in the + * requested format, and will be automatically converted to the hardware + * audio format if necessary. This function returns -1 if it failed + * to open the audio device, or couldn't set up the audio thread. + * + * The audio device starts out playing silence when it's opened, and should + * be enabled for playing by calling SDL_PauseAudio(0) when you are ready + * for your audio callback function to be called. Since the audio driver + * may modify the requested size of the audio buffer, you should allocate + * any local mixing buffers after you open the audio device. + * + * @sa SDL_AudioSpec + */ +extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained); + +typedef enum { + SDL_AUDIO_STOPPED = 0, + SDL_AUDIO_PLAYING, + SDL_AUDIO_PAUSED +} SDL_audiostatus; + +/** Get the current audio state */ +extern DECLSPEC SDL_audiostatus SDLCALL SDL_GetAudioStatus(void); + +/** + * This function pauses and unpauses the audio callback processing. + * It should be called with a parameter of 0 after opening the audio + * device to start playing sound. This is so you can safely initialize + * data for your callback function after opening the audio device. + * Silence will be written to the audio device during the pause. + */ +extern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on); + +/** + * This function loads a WAVE from the data source, automatically freeing + * that source if 'freesrc' is non-zero. For example, to load a WAVE file, + * you could do: + * @code SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...); @endcode + * + * If this function succeeds, it returns the given SDL_AudioSpec, + * filled with the audio data format of the wave data, and sets + * 'audio_buf' to a malloc()'d buffer containing the audio data, + * and sets 'audio_len' to the length of that audio buffer, in bytes. + * You need to free the audio buffer with SDL_FreeWAV() when you are + * done with it. + * + * This function returns NULL and sets the SDL error message if the + * wave file cannot be opened, uses an unknown data format, or is + * corrupt. Currently raw and MS-ADPCM WAVE files are supported. + */ +extern DECLSPEC SDL_AudioSpec * SDLCALL SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len); + +/** Compatibility convenience function -- loads a WAV from a file */ +#define SDL_LoadWAV(file, spec, audio_buf, audio_len) \ + SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"),1, spec,audio_buf,audio_len) + +/** + * This function frees data previously allocated with SDL_LoadWAV_RW() + */ +extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 *audio_buf); + +/** + * This function takes a source format and rate and a destination format + * and rate, and initializes the 'cvt' structure with information needed + * by SDL_ConvertAudio() to convert a buffer of audio data from one format + * to the other. + * + * @return This function returns 0, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT *cvt, + Uint16 src_format, Uint8 src_channels, int src_rate, + Uint16 dst_format, Uint8 dst_channels, int dst_rate); + +/** + * Once you have initialized the 'cvt' structure using SDL_BuildAudioCVT(), + * created an audio buffer cvt->buf, and filled it with cvt->len bytes of + * audio data in the source format, this function will convert it in-place + * to the desired format. + * The data conversion may expand the size of the audio data, so the buffer + * cvt->buf should be allocated after the cvt structure is initialized by + * SDL_BuildAudioCVT(), and should be cvt->len*cvt->len_mult bytes long. + */ +extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT *cvt); + + +#define SDL_MIX_MAXVOLUME 128 +/** + * This takes two audio buffers of the playing audio format and mixes + * them, performing addition, volume adjustment, and overflow clipping. + * The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME + * for full audio volume. Note this does not change hardware volume. + * This is provided for convenience -- you can mix your own audio data. + */ +extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume); + +/** + * @name Audio Locks + * The lock manipulated by these functions protects the callback function. + * During a LockAudio/UnlockAudio pair, you can be guaranteed that the + * callback function is not running. Do not call these from the callback + * function or you will cause deadlock. + */ +/*@{*/ +extern DECLSPEC void SDLCALL SDL_LockAudio(void); +extern DECLSPEC void SDLCALL SDL_UnlockAudio(void); +/*@}*/ + +/** + * This function shuts down audio processing and closes the audio device. + */ +extern DECLSPEC void SDLCALL SDL_CloseAudio(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_audio_h */ diff --git a/other/sdl/include/SDL_byteorder.h b/other/sdl/include/SDL_byteorder.h new file mode 100644 index 0000000..9b93cd6 --- /dev/null +++ b/other/sdl/include/SDL_byteorder.h @@ -0,0 +1,29 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_byteorder.h + * @deprecated Use SDL_endian.h instead + */ + +/* DEPRECATED */ +#include "SDL_endian.h" diff --git a/other/sdl/include/SDL_cdrom.h b/other/sdl/include/SDL_cdrom.h new file mode 100644 index 0000000..fff5cfa --- /dev/null +++ b/other/sdl/include/SDL_cdrom.h @@ -0,0 +1,202 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_cdrom.h + * This is the CD-audio control API for Simple DirectMedia Layer + */ + +#ifndef _SDL_cdrom_h +#define _SDL_cdrom_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file SDL_cdrom.h + * In order to use these functions, SDL_Init() must have been called + * with the SDL_INIT_CDROM flag. This causes SDL to scan the system + * for CD-ROM drives, and load appropriate drivers. + */ + +/** The maximum number of CD-ROM tracks on a disk */ +#define SDL_MAX_TRACKS 99 + +/** @name Track Types + * The types of CD-ROM track possible + */ +/*@{*/ +#define SDL_AUDIO_TRACK 0x00 +#define SDL_DATA_TRACK 0x04 +/*@}*/ + +/** The possible states which a CD-ROM drive can be in. */ +typedef enum { + CD_TRAYEMPTY, + CD_STOPPED, + CD_PLAYING, + CD_PAUSED, + CD_ERROR = -1 +} CDstatus; + +/** Given a status, returns true if there's a disk in the drive */ +#define CD_INDRIVE(status) ((int)(status) > 0) + +typedef struct SDL_CDtrack { + Uint8 id; /**< Track number */ + Uint8 type; /**< Data or audio track */ + Uint16 unused; + Uint32 length; /**< Length, in frames, of this track */ + Uint32 offset; /**< Offset, in frames, from start of disk */ +} SDL_CDtrack; + +/** This structure is only current as of the last call to SDL_CDStatus() */ +typedef struct SDL_CD { + int id; /**< Private drive identifier */ + CDstatus status; /**< Current drive status */ + + /** The rest of this structure is only valid if there's a CD in drive */ + /*@{*/ + int numtracks; /**< Number of tracks on disk */ + int cur_track; /**< Current track position */ + int cur_frame; /**< Current frame offset within current track */ + SDL_CDtrack track[SDL_MAX_TRACKS+1]; + /*@}*/ +} SDL_CD; + +/** @name Frames / MSF Conversion Functions + * Conversion functions from frames to Minute/Second/Frames and vice versa + */ +/*@{*/ +#define CD_FPS 75 +#define FRAMES_TO_MSF(f, M,S,F) { \ + int value = f; \ + *(F) = value%CD_FPS; \ + value /= CD_FPS; \ + *(S) = value%60; \ + value /= 60; \ + *(M) = value; \ +} +#define MSF_TO_FRAMES(M, S, F) ((M)*60*CD_FPS+(S)*CD_FPS+(F)) +/*@}*/ + +/* CD-audio API functions: */ + +/** + * Returns the number of CD-ROM drives on the system, or -1 if + * SDL_Init() has not been called with the SDL_INIT_CDROM flag. + */ +extern DECLSPEC int SDLCALL SDL_CDNumDrives(void); + +/** + * Returns a human-readable, system-dependent identifier for the CD-ROM. + * Example: + * - "/dev/cdrom" + * - "E:" + * - "/dev/disk/ide/1/master" + */ +extern DECLSPEC const char * SDLCALL SDL_CDName(int drive); + +/** + * Opens a CD-ROM drive for access. It returns a drive handle on success, + * or NULL if the drive was invalid or busy. This newly opened CD-ROM + * becomes the default CD used when other CD functions are passed a NULL + * CD-ROM handle. + * Drives are numbered starting with 0. Drive 0 is the system default CD-ROM. + */ +extern DECLSPEC SDL_CD * SDLCALL SDL_CDOpen(int drive); + +/** + * This function returns the current status of the given drive. + * If the drive has a CD in it, the table of contents of the CD and current + * play position of the CD will be stored in the SDL_CD structure. + */ +extern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD *cdrom); + +/** + * Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks' + * tracks and 'nframes' frames. If both 'ntrack' and 'nframe' are 0, play + * until the end of the CD. This function will skip data tracks. + * This function should only be called after calling SDL_CDStatus() to + * get track information about the CD. + * For example: + * @code + * // Play entire CD: + * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) + * SDL_CDPlayTracks(cdrom, 0, 0, 0, 0); + * // Play last track: + * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) { + * SDL_CDPlayTracks(cdrom, cdrom->numtracks-1, 0, 0, 0); + * } + * // Play first and second track and 10 seconds of third track: + * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) + * SDL_CDPlayTracks(cdrom, 0, 0, 2, 10); + * @endcode + * + * @return This function returns 0, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_CDPlayTracks(SDL_CD *cdrom, + int start_track, int start_frame, int ntracks, int nframes); + +/** + * Play the given CD starting at 'start' frame for 'length' frames. + * @return It returns 0, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_CDPlay(SDL_CD *cdrom, int start, int length); + +/** Pause play + * @return returns 0, or -1 on error + */ +extern DECLSPEC int SDLCALL SDL_CDPause(SDL_CD *cdrom); + +/** Resume play + * @return returns 0, or -1 on error + */ +extern DECLSPEC int SDLCALL SDL_CDResume(SDL_CD *cdrom); + +/** Stop play + * @return returns 0, or -1 on error + */ +extern DECLSPEC int SDLCALL SDL_CDStop(SDL_CD *cdrom); + +/** Eject CD-ROM + * @return returns 0, or -1 on error + */ +extern DECLSPEC int SDLCALL SDL_CDEject(SDL_CD *cdrom); + +/** Closes the handle for the CD-ROM drive */ +extern DECLSPEC void SDLCALL SDL_CDClose(SDL_CD *cdrom); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_video_h */ diff --git a/other/sdl/include/SDL_config.h b/other/sdl/include/SDL_config.h new file mode 100644 index 0000000..a508101 --- /dev/null +++ b/other/sdl/include/SDL_config.h @@ -0,0 +1,45 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_h +#define _SDL_config_h + +#include "SDL_platform.h" + +/* Add any platform that doesn't build using the configure system */ +#if defined(__DREAMCAST__) +#include "SDL_config_dreamcast.h" +#elif defined(__MACOS__) +#include "SDL_config_macos.h" +#elif defined(__MACOSX__) +#include "SDL_config_macosx.h" +#elif defined(__SYMBIAN32__) +#include "SDL_config_symbian.h" /* must be before win32! */ +#elif defined(__WIN32__) +#include "SDL_config_win32.h" +#elif defined(__OS2__) +#include "SDL_config_os2.h" +#else +#include "SDL_config_minimal.h" +#endif /* platform config */ + +#endif /* _SDL_config_h */ diff --git a/other/sdl/include/SDL_config.h.default b/other/sdl/include/SDL_config.h.default new file mode 100644 index 0000000..c82f42a --- /dev/null +++ b/other/sdl/include/SDL_config.h.default @@ -0,0 +1,45 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_h +#define _SDL_config_h + +#include "SDL_platform.h" + +/* Add any platform that doesn't build using the configure system */ +#if defined(__DREAMCAST__) +#include "SDL_config_dreamcast.h" +#elif defined(__MACOS__) +#include "SDL_config_macos.h" +#elif defined(__MACOSX__) +#include "SDL_config_macosx.h" +#elif defined(__SYMBIAN32__) +#include "SDL_config_symbian.h" /* must be before win32! */ +#elif defined(__WIN32__) +#include "SDL_config_win32.h" +#elif defined(__OS2__) +#include "SDL_config_os2.h" +#else +#include "SDL_config_minimal.h" +#endif /* platform config */ + +#endif /* _SDL_config_h */ diff --git a/other/sdl/include/SDL_config.h.in b/other/sdl/include/SDL_config.h.in new file mode 100644 index 0000000..13a3f9a --- /dev/null +++ b/other/sdl/include/SDL_config.h.in @@ -0,0 +1,305 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_h +#define _SDL_config_h + +/* This is a set of defines to configure the SDL features */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +/* Make sure that this isn't included by Visual C++ */ +#ifdef _MSC_VER +#error You should copy include/SDL_config.h.default to include/SDL_config.h +#endif + +/* C language features */ +#undef const +#undef inline +#undef volatile + +/* C datatypes */ +#undef size_t +#undef int8_t +#undef uint8_t +#undef int16_t +#undef uint16_t +#undef int32_t +#undef uint32_t +#undef int64_t +#undef uint64_t +#undef uintptr_t +#undef SDL_HAS_64BIT_TYPE + +/* Endianness */ +#undef SDL_BYTEORDER + +/* Comment this if you want to build without any C library requirements */ +#undef HAVE_LIBC +#if HAVE_LIBC + +/* Useful headers */ +#undef HAVE_ALLOCA_H +#undef HAVE_SYS_TYPES_H +#undef HAVE_STDIO_H +#undef STDC_HEADERS +#undef HAVE_STDLIB_H +#undef HAVE_STDARG_H +#undef HAVE_MALLOC_H +#undef HAVE_MEMORY_H +#undef HAVE_STRING_H +#undef HAVE_STRINGS_H +#undef HAVE_INTTYPES_H +#undef HAVE_STDINT_H +#undef HAVE_CTYPE_H +#undef HAVE_MATH_H +#undef HAVE_ICONV_H +#undef HAVE_SIGNAL_H +#undef HAVE_ALTIVEC_H + +/* C library functions */ +#undef HAVE_MALLOC +#undef HAVE_CALLOC +#undef HAVE_REALLOC +#undef HAVE_FREE +#undef HAVE_ALLOCA +#ifndef _WIN32 /* Don't use C runtime versions of these on Windows */ +#undef HAVE_GETENV +#undef HAVE_PUTENV +#undef HAVE_UNSETENV +#endif +#undef HAVE_QSORT +#undef HAVE_ABS +#undef HAVE_BCOPY +#undef HAVE_MEMSET +#undef HAVE_MEMCPY +#undef HAVE_MEMMOVE +#undef HAVE_MEMCMP +#undef HAVE_STRLEN +#undef HAVE_STRLCPY +#undef HAVE_STRLCAT +#undef HAVE_STRDUP +#undef HAVE__STRREV +#undef HAVE__STRUPR +#undef HAVE__STRLWR +#undef HAVE_INDEX +#undef HAVE_RINDEX +#undef HAVE_STRCHR +#undef HAVE_STRRCHR +#undef HAVE_STRSTR +#undef HAVE_ITOA +#undef HAVE__LTOA +#undef HAVE__UITOA +#undef HAVE__ULTOA +#undef HAVE_STRTOL +#undef HAVE_STRTOUL +#undef HAVE__I64TOA +#undef HAVE__UI64TOA +#undef HAVE_STRTOLL +#undef HAVE_STRTOULL +#undef HAVE_STRTOD +#undef HAVE_ATOI +#undef HAVE_ATOF +#undef HAVE_STRCMP +#undef HAVE_STRNCMP +#undef HAVE__STRICMP +#undef HAVE_STRCASECMP +#undef HAVE__STRNICMP +#undef HAVE_STRNCASECMP +#undef HAVE_SSCANF +#undef HAVE_SNPRINTF +#undef HAVE_VSNPRINTF +#undef HAVE_ICONV +#undef HAVE_SIGACTION +#undef HAVE_SETJMP +#undef HAVE_NANOSLEEP +#undef HAVE_CLOCK_GETTIME +#undef HAVE_DLVSYM +#undef HAVE_GETPAGESIZE + +#else +/* We may need some replacement for stdarg.h here */ +#include <stdarg.h> +#endif /* HAVE_LIBC */ + +/* Allow disabling of core subsystems */ +#undef SDL_AUDIO_DISABLED +#undef SDL_CDROM_DISABLED +#undef SDL_CPUINFO_DISABLED +#undef SDL_EVENTS_DISABLED +#undef SDL_FILE_DISABLED +#undef SDL_JOYSTICK_DISABLED +#undef SDL_LOADSO_DISABLED +#undef SDL_THREADS_DISABLED +#undef SDL_TIMERS_DISABLED +#undef SDL_VIDEO_DISABLED + +/* Enable various audio drivers */ +#undef SDL_AUDIO_DRIVER_ALSA +#undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC +#undef SDL_AUDIO_DRIVER_ARTS +#undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC +#undef SDL_AUDIO_DRIVER_BAUDIO +#undef SDL_AUDIO_DRIVER_BSD +#undef SDL_AUDIO_DRIVER_COREAUDIO +#undef SDL_AUDIO_DRIVER_DART +#undef SDL_AUDIO_DRIVER_DC +#undef SDL_AUDIO_DRIVER_DISK +#undef SDL_AUDIO_DRIVER_DUMMY +#undef SDL_AUDIO_DRIVER_DMEDIA +#undef SDL_AUDIO_DRIVER_DSOUND +#undef SDL_AUDIO_DRIVER_PULSE +#undef SDL_AUDIO_DRIVER_PULSE_DYNAMIC +#undef SDL_AUDIO_DRIVER_ESD +#undef SDL_AUDIO_DRIVER_ESD_DYNAMIC +#undef SDL_AUDIO_DRIVER_MINT +#undef SDL_AUDIO_DRIVER_MMEAUDIO +#undef SDL_AUDIO_DRIVER_NAS +#undef SDL_AUDIO_DRIVER_OSS +#undef SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H +#undef SDL_AUDIO_DRIVER_PAUD +#undef SDL_AUDIO_DRIVER_QNXNTO +#undef SDL_AUDIO_DRIVER_SNDMGR +#undef SDL_AUDIO_DRIVER_SUNAUDIO +#undef SDL_AUDIO_DRIVER_WAVEOUT + +/* Enable various cdrom drivers */ +#undef SDL_CDROM_AIX +#undef SDL_CDROM_BEOS +#undef SDL_CDROM_BSDI +#undef SDL_CDROM_DC +#undef SDL_CDROM_DUMMY +#undef SDL_CDROM_FREEBSD +#undef SDL_CDROM_LINUX +#undef SDL_CDROM_MACOS +#undef SDL_CDROM_MACOSX +#undef SDL_CDROM_MINT +#undef SDL_CDROM_OPENBSD +#undef SDL_CDROM_OS2 +#undef SDL_CDROM_OSF +#undef SDL_CDROM_QNX +#undef SDL_CDROM_WIN32 + +/* Enable various input drivers */ +#undef SDL_INPUT_TSLIB +#undef SDL_JOYSTICK_BEOS +#undef SDL_JOYSTICK_DC +#undef SDL_JOYSTICK_DUMMY +#undef SDL_JOYSTICK_IOKIT +#undef SDL_JOYSTICK_LINUX +#undef SDL_JOYSTICK_LINUXEV +#undef SDL_JOYSTICK_MACOS +#undef SDL_JOYSTICK_MINT +#undef SDL_JOYSTICK_OS2 +#undef SDL_JOYSTICK_RISCOS +#undef SDL_JOYSTICK_WINMM +#undef SDL_JOYSTICK_USBHID +#undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H + +/* Enable various shared object loading systems */ +#undef SDL_LOADSO_BEOS +#undef SDL_LOADSO_DLCOMPAT +#undef SDL_LOADSO_DLOPEN +#undef SDL_LOADSO_DUMMY +#undef SDL_LOADSO_LDG +#undef SDL_LOADSO_MACOS +#undef SDL_LOADSO_OS2 +#undef SDL_LOADSO_WIN32 + +/* Enable various threading systems */ +#undef SDL_THREAD_BEOS +#undef SDL_THREAD_DC +#undef SDL_THREAD_OS2 +#undef SDL_THREAD_PTH +#undef SDL_THREAD_PTHREAD +#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX +#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP +#undef SDL_THREAD_SPROC +#undef SDL_THREAD_WIN32 + +/* Enable various timer systems */ +#undef SDL_TIMER_BEOS +#undef SDL_TIMER_DC +#undef SDL_TIMER_DUMMY +#undef SDL_TIMER_MACOS +#undef SDL_TIMER_MINT +#undef SDL_TIMER_OS2 +#undef SDL_TIMER_RISCOS +#undef SDL_TIMER_UNIX +#undef SDL_TIMER_WIN32 +#undef SDL_TIMER_WINCE + +/* Enable various video drivers */ +#undef SDL_VIDEO_DRIVER_AALIB +#undef SDL_VIDEO_DRIVER_BWINDOW +#undef SDL_VIDEO_DRIVER_DC +#undef SDL_VIDEO_DRIVER_DDRAW +#undef SDL_VIDEO_DRIVER_DGA +#undef SDL_VIDEO_DRIVER_DIRECTFB +#undef SDL_VIDEO_DRIVER_DRAWSPROCKET +#undef SDL_VIDEO_DRIVER_DUMMY +#undef SDL_VIDEO_DRIVER_FBCON +#undef SDL_VIDEO_DRIVER_GAPI +#undef SDL_VIDEO_DRIVER_GEM +#undef SDL_VIDEO_DRIVER_GGI +#undef SDL_VIDEO_DRIVER_IPOD +#undef SDL_VIDEO_DRIVER_NANOX +#undef SDL_VIDEO_DRIVER_OS2FS +#undef SDL_VIDEO_DRIVER_PHOTON +#undef SDL_VIDEO_DRIVER_PICOGUI +#undef SDL_VIDEO_DRIVER_PS2GS +#undef SDL_VIDEO_DRIVER_QTOPIA +#undef SDL_VIDEO_DRIVER_QUARTZ +#undef SDL_VIDEO_DRIVER_RISCOS +#undef SDL_VIDEO_DRIVER_SVGALIB +#undef SDL_VIDEO_DRIVER_TOOLBOX +#undef SDL_VIDEO_DRIVER_VGL +#undef SDL_VIDEO_DRIVER_WINDIB +#undef SDL_VIDEO_DRIVER_WSCONS +#undef SDL_VIDEO_DRIVER_X11 +#undef SDL_VIDEO_DRIVER_X11_DGAMOUSE +#undef SDL_VIDEO_DRIVER_X11_DPMS +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER +#undef SDL_VIDEO_DRIVER_X11_VIDMODE +#undef SDL_VIDEO_DRIVER_X11_XINERAMA +#undef SDL_VIDEO_DRIVER_X11_XME +#undef SDL_VIDEO_DRIVER_X11_XRANDR +#undef SDL_VIDEO_DRIVER_X11_XV +#undef SDL_VIDEO_DRIVER_XBIOS + +/* Enable OpenGL support */ +#undef SDL_VIDEO_OPENGL +#undef SDL_VIDEO_OPENGL_GLX +#undef SDL_VIDEO_OPENGL_WGL +#undef SDL_VIDEO_OPENGL_OSMESA +#undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC + +/* Enable assembly routines */ +#undef SDL_ASSEMBLY_ROUTINES +#undef SDL_HERMES_BLITTERS +#undef SDL_ALTIVEC_BLITTERS + +#endif /* _SDL_config_h */ diff --git a/other/sdl/include/SDL_config_amiga.h b/other/sdl/include/SDL_config_amiga.h new file mode 100644 index 0000000..23e0861 --- /dev/null +++ b/other/sdl/include/SDL_config_amiga.h @@ -0,0 +1,80 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_amiga_h +#define _SDL_config_amiga_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +#define SDL_HAS_64BIT_TYPE 1 + +/* Useful headers */ +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_SIGNAL_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_AHI 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#define SDL_CDROM_DUMMY 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_AMIGA 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DUMMY 1 + +/* Enable various threading systems */ +#define SDL_THREAD_AMIGA 1 + +/* Enable various timer systems */ +#define SDL_TIMER_AMIGA 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_CYBERGRAPHICS 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +/* Enable OpenGL support */ +#define SDL_VIDEO_OPENGL 1 + +#endif /* _SDL_config_amiga_h */ diff --git a/other/sdl/include/SDL_config_dreamcast.h b/other/sdl/include/SDL_config_dreamcast.h new file mode 100644 index 0000000..07c2f08 --- /dev/null +++ b/other/sdl/include/SDL_config_dreamcast.h @@ -0,0 +1,106 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_dreamcast_h +#define _SDL_config_dreamcast_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; +typedef unsigned long uintptr_t; +#define SDL_HAS_64BIT_TYPE 1 + +/* Useful headers */ +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_CTYPE_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRDUP 1 +#define HAVE_INDEX 1 +#define HAVE_RINDEX 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_DC 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#define SDL_CDROM_DC 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_DC 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DUMMY 1 + +/* Enable various threading systems */ +#define SDL_THREAD_DC 1 + +/* Enable various timer systems */ +#define SDL_TIMER_DC 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DC 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +#endif /* _SDL_config_dreamcast_h */ diff --git a/other/sdl/include/SDL_config_macos.h b/other/sdl/include/SDL_config_macos.h new file mode 100644 index 0000000..4ba5c22 --- /dev/null +++ b/other/sdl/include/SDL_config_macos.h @@ -0,0 +1,112 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_macos_h +#define _SDL_config_macos_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +#include <MacTypes.h> + +typedef SInt8 int8_t; +typedef UInt8 uint8_t; +typedef SInt16 int16_t; +typedef UInt16 uint16_t; +typedef SInt32 int32_t; +typedef UInt32 uint32_t; +typedef SInt64 int64_t; +typedef UInt64 uint64_t; +typedef unsigned long uintptr_t; + +#define SDL_HAS_64BIT_TYPE 1 + +/* Useful headers */ +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_ITOA 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_SSCANF 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_SNDMGR 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#if TARGET_API_MAC_CARBON +#define SDL_CDROM_DUMMY 1 +#else +#define SDL_CDROM_MACOS 1 +#endif + +/* Enable various input drivers */ +#if TARGET_API_MAC_CARBON +#define SDL_JOYSTICK_DUMMY 1 +#else +#define SDL_JOYSTICK_MACOS 1 +#endif + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_MACOS 1 + +/* Enable various threading systems */ +#define SDL_THREADS_DISABLED 1 + +/* Enable various timer systems */ +#define SDL_TIMER_MACOS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_DRAWSPROCKET 1 +#define SDL_VIDEO_DRIVER_TOOLBOX 1 + +/* Enable OpenGL support */ +#define SDL_VIDEO_OPENGL 1 + +#endif /* _SDL_config_macos_h */ diff --git a/other/sdl/include/SDL_config_macosx.h b/other/sdl/include/SDL_config_macosx.h new file mode 100644 index 0000000..295b872 --- /dev/null +++ b/other/sdl/include/SDL_config_macosx.h @@ -0,0 +1,150 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_macosx_h +#define _SDL_config_macosx_h + +#include "SDL_platform.h" + +/* This gets us MAC_OS_X_VERSION_MIN_REQUIRED... */ +#include <AvailabilityMacros.h> + +/* This is a set of defines to configure the SDL features */ + +#define SDL_HAS_64BIT_TYPE 1 + +/* Useful headers */ +/* If we specified an SDK or have a post-PowerPC chip, then alloca.h exists. */ +#if ( (MAC_OS_X_VERSION_MIN_REQUIRED >= 1030) || (!defined(__POWERPC__)) ) +#define HAVE_ALLOCA_H 1 +#endif +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRDUP 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_COREAUDIO 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#define SDL_CDROM_MACOSX 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_IOKIT 1 + +/* Enable various shared object loading systems */ +#ifdef __ppc__ +/* For Mac OS X 10.2 compatibility */ +#define SDL_LOADSO_DLCOMPAT 1 +#else +#define SDL_LOADSO_DLOPEN 1 +#endif + +/* Enable various threading systems */ +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 + +/* Enable various timer systems */ +#define SDL_TIMER_UNIX 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#if ((defined TARGET_API_MAC_CARBON) && (TARGET_API_MAC_CARBON)) +#define SDL_VIDEO_DRIVER_TOOLBOX 1 +#else +#define SDL_VIDEO_DRIVER_QUARTZ 1 +#endif +#define SDL_VIDEO_DRIVER_DGA 1 +#define SDL_VIDEO_DRIVER_X11 1 +#define SDL_VIDEO_DRIVER_X11_DGAMOUSE 1 +#define SDL_VIDEO_DRIVER_X11_DYNAMIC "/usr/X11R6/lib/libX11.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT "/usr/X11R6/lib/libXext.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR "/usr/X11R6/lib/libXrandr.2.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER "/usr/X11R6/lib/libXrender.1.dylib" +#define SDL_VIDEO_DRIVER_X11_VIDMODE 1 +#define SDL_VIDEO_DRIVER_X11_XINERAMA 1 +#define SDL_VIDEO_DRIVER_X11_XME 1 +#define SDL_VIDEO_DRIVER_X11_XRANDR 1 +#define SDL_VIDEO_DRIVER_X11_XV 1 + +/* Enable OpenGL support */ +#define SDL_VIDEO_OPENGL 1 +#define SDL_VIDEO_OPENGL_GLX 1 + +/* Disable screensaver */ +#define SDL_VIDEO_DISABLE_SCREENSAVER 1 + +/* Enable assembly routines */ +#define SDL_ASSEMBLY_ROUTINES 1 +#ifdef __ppc__ +#define SDL_ALTIVEC_BLITTERS 1 +#endif + +#endif /* _SDL_config_macosx_h */ diff --git a/other/sdl/include/SDL_config_minimal.h b/other/sdl/include/SDL_config_minimal.h new file mode 100644 index 0000000..002c56e --- /dev/null +++ b/other/sdl/include/SDL_config_minimal.h @@ -0,0 +1,62 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_minimal_h +#define _SDL_config_minimal_h + +#include "SDL_platform.h" + +/* This is the minimal configuration that can be used to build SDL */ + +#include <stdarg.h> + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef unsigned int size_t; +typedef unsigned long uintptr_t; + +/* Enable the dummy audio driver (src/audio/dummy/\*.c) */ +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ +#define SDL_CDROM_DISABLED 1 + +/* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ +#define SDL_JOYSTICK_DISABLED 1 + +/* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ +#define SDL_LOADSO_DISABLED 1 + +/* Enable the stub thread support (src/thread/generic/\*.c) */ +#define SDL_THREADS_DISABLED 1 + +/* Enable the stub timer support (src/timer/dummy/\*.c) */ +#define SDL_TIMERS_DISABLED 1 + +/* Enable the dummy video driver (src/video/dummy/\*.c) */ +#define SDL_VIDEO_DRIVER_DUMMY 1 + +#endif /* _SDL_config_minimal_h */ diff --git a/other/sdl/include/SDL_config_nds.h b/other/sdl/include/SDL_config_nds.h new file mode 100644 index 0000000..4ac60a5 --- /dev/null +++ b/other/sdl/include/SDL_config_nds.h @@ -0,0 +1,115 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_nds_h +#define _SDL_config_nds_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +/* C datatypes */ +#define SDL_HAS_64BIT_TYPE 1 + +/* Endianness */ +#define SDL_BYTEORDER 1234 + +/* Useful headers */ +#define HAVE_ALLOCA_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_STRING_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_SIGNAL_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRDUP 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_SETJMP 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_NDS 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ +#define SDL_CDROM_DISABLED 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_NDS 1 + +/* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ +#define SDL_LOADSO_DISABLED 1 + +/* Enable the stub thread support (src/thread/generic/\*.c) */ +#define SDL_THREADS_DISABLED 1 + +/* Enable various timer systems */ +#define SDL_TIMER_NDS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_NDS 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +#endif /* _SDL_config_nds_h */ diff --git a/other/sdl/include/SDL_config_os2.h b/other/sdl/include/SDL_config_os2.h new file mode 100644 index 0000000..bb40df0 --- /dev/null +++ b/other/sdl/include/SDL_config_os2.h @@ -0,0 +1,141 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_os2_h +#define _SDL_config_os2_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef unsigned int size_t; +typedef unsigned long uintptr_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; + +#define SDL_HAS_64BIT_TYPE 1 + +/* Use Watcom's LIBC */ +#define HAVE_LIBC 1 + +/* Useful headers */ +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRDUP 1 +#define HAVE__STRREV 1 +#define HAVE__STRUPR 1 +#define HAVE__STRLWR 1 +#define HAVE_INDEX 1 +#define HAVE_RINDEX 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_ITOA 1 +#define HAVE__LTOA 1 +#define HAVE__UITOA 1 +#define HAVE__ULTOA 1 +#define HAVE_STRTOL 1 +#define HAVE__I64TOA 1 +#define HAVE__UI64TOA 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_SETJMP 1 +#define HAVE_CLOCK_GETTIME 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_DART 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#define SDL_CDROM_OS2 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_OS2 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_OS2 1 + +/* Enable various threading systems */ +#define SDL_THREAD_OS2 1 + +/* Enable various timer systems */ +#define SDL_TIMER_OS2 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_OS2FS 1 + +/* Enable OpenGL support */ +/* Nothing here yet for OS/2... :( */ + +/* Enable assembly routines where available */ +#define SDL_ASSEMBLY_ROUTINES 1 + +#endif /* _SDL_config_os2_h */ diff --git a/other/sdl/include/SDL_config_symbian.h b/other/sdl/include/SDL_config_symbian.h new file mode 100644 index 0000000..53527b2 --- /dev/null +++ b/other/sdl/include/SDL_config_symbian.h @@ -0,0 +1,146 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/* + +Symbian version Markus Mertama + +*/ + + +#ifndef _SDL_CONFIG_SYMBIAN_H +#define _SDL_CONFIG_SYMBIAN_H + +#include "SDL_platform.h" + +/* This is the minimal configuration that can be used to build SDL */ + + +#include <stdarg.h> +#include <stddef.h> + + +#ifdef __GCCE__ +#define SYMBIAN32_GCCE +#endif + +#ifndef _SIZE_T_DEFINED +typedef unsigned int size_t; +#endif + +#ifndef _INTPTR_T_DECLARED +typedef unsigned int uintptr_t; +#endif + +#ifndef _INT8_T_DECLARED +typedef signed char int8_t; +#endif + +#ifndef _UINT8_T_DECLARED +typedef unsigned char uint8_t; +#endif + +#ifndef _INT16_T_DECLARED +typedef signed short int16_t; +#endif + +#ifndef _UINT16_T_DECLARED +typedef unsigned short uint16_t; +#endif + +#ifndef _INT32_T_DECLARED +typedef signed int int32_t; +#endif + +#ifndef _UINT32_T_DECLARED +typedef unsigned int uint32_t; +#endif + +#ifndef _INT64_T_DECLARED +typedef signed long long int64_t; +#endif + +#ifndef _UINT64_T_DECLARED +typedef unsigned long long uint64_t; +#endif + +#define SDL_AUDIO_DRIVER_EPOCAUDIO 1 + + +/* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ +#define SDL_CDROM_DISABLED 1 + +/* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ +#define SDL_JOYSTICK_DISABLED 1 + +/* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ +#define SDL_LOADSO_DISABLED 1 + +#define SDL_THREAD_SYMBIAN 1 + +#define SDL_VIDEO_DRIVER_EPOC 1 + +#define SDL_VIDEO_OPENGL 0 + +#define SDL_HAS_64BIT_TYPE 1 + +#define HAVE_LIBC 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 + +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +/*#define HAVE_ALLOCA 1*/ +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRUPR 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_ITOA 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +/*#define HAVE__STRICMP 1*/ +#define HAVE__STRNICMP 1 +#define HAVE_SSCANF 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 + + + +#endif /* _SDL_CONFIG_SYMBIAN_H */ diff --git a/other/sdl/include/SDL_config_win32.h b/other/sdl/include/SDL_config_win32.h new file mode 100644 index 0000000..6d019a8 --- /dev/null +++ b/other/sdl/include/SDL_config_win32.h @@ -0,0 +1,183 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_config_win32_h +#define _SDL_config_win32_h + +#include "SDL_platform.h" + +/* This is a set of defines to configure the SDL features */ + +#if defined(__GNUC__) || defined(__DMC__) +#define HAVE_STDINT_H 1 +#elif defined(_MSC_VER) +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; +#ifndef _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __int64 uintptr_t; +#else +typedef unsigned int uintptr_t; +#endif +#define _UINTPTR_T_DEFINED +#endif +/* Older Visual C++ headers don't have the Win64-compatible typedefs... */ +#if ((_MSC_VER <= 1200) && (!defined(DWORD_PTR))) +#define DWORD_PTR DWORD +#endif +#if ((_MSC_VER <= 1200) && (!defined(LONG_PTR))) +#define LONG_PTR LONG +#endif +#else /* !__GNUC__ && !_MSC_VER */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; +#ifndef _SIZE_T_DEFINED_ +#define _SIZE_T_DEFINED_ +typedef unsigned int size_t; +#endif +typedef unsigned int uintptr_t; +#endif /* __GNUC__ || _MSC_VER */ +#define SDL_HAS_64BIT_TYPE 1 + +/* Enabled for SDL 1.2 (binary compatibility) */ +#define HAVE_LIBC 1 +#ifdef HAVE_LIBC +/* Useful headers */ +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STRING_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#ifndef _WIN32_WCE +#define HAVE_SIGNAL_H 1 +#endif + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRREV 1 +#define HAVE__STRUPR 1 +#define HAVE__STRLWR 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_ITOA 1 +#define HAVE__LTOA 1 +#define HAVE__ULTOA 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE__STRICMP 1 +#define HAVE__STRNICMP 1 +#define HAVE_SSCANF 1 +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#endif + +/* Enable various audio drivers */ +#ifndef _WIN32_WCE +#define SDL_AUDIO_DRIVER_DSOUND 1 +#endif +#define SDL_AUDIO_DRIVER_WAVEOUT 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various cdrom drivers */ +#ifdef _WIN32_WCE +#define SDL_CDROM_DISABLED 1 +#else +#define SDL_CDROM_WIN32 1 +#endif + +/* Enable various input drivers */ +#ifdef _WIN32_WCE +#define SDL_JOYSTICK_DISABLED 1 +#else +#define SDL_JOYSTICK_WINMM 1 +#endif + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_WIN32 1 + +/* Enable various threading systems */ +#define SDL_THREAD_WIN32 1 + +/* Enable various timer systems */ +#ifdef _WIN32_WCE +#define SDL_TIMER_WINCE 1 +#else +#define SDL_TIMER_WIN32 1 +#endif + +/* Enable various video drivers */ +#ifdef _WIN32_WCE +#define SDL_VIDEO_DRIVER_GAPI 1 +#endif +#ifndef _WIN32_WCE +#define SDL_VIDEO_DRIVER_DDRAW 1 +#endif +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_WINDIB 1 + +/* Enable OpenGL support */ +#ifndef _WIN32_WCE +#define SDL_VIDEO_OPENGL 1 +#define SDL_VIDEO_OPENGL_WGL 1 +#endif + +/* Disable screensaver */ +#define SDL_VIDEO_DISABLE_SCREENSAVER 1 + +/* Enable assembly routines (Win64 doesn't have inline asm) */ +#ifndef _WIN64 +#define SDL_ASSEMBLY_ROUTINES 1 +#endif + +#endif /* _SDL_config_win32_h */ diff --git a/other/sdl/include/SDL_copying.h b/other/sdl/include/SDL_copying.h new file mode 100644 index 0000000..1bd6b84 --- /dev/null +++ b/other/sdl/include/SDL_copying.h @@ -0,0 +1,22 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + diff --git a/other/sdl/include/SDL_cpuinfo.h b/other/sdl/include/SDL_cpuinfo.h new file mode 100644 index 0000000..f4be8e0 --- /dev/null +++ b/other/sdl/include/SDL_cpuinfo.h @@ -0,0 +1,69 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_cpuinfo.h + * CPU feature detection for SDL + */ + +#ifndef _SDL_cpuinfo_h +#define _SDL_cpuinfo_h + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** This function returns true if the CPU has the RDTSC instruction */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void); + +/** This function returns true if the CPU has MMX features */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void); + +/** This function returns true if the CPU has MMX Ext. features */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasMMXExt(void); + +/** This function returns true if the CPU has 3DNow features */ +extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void); + +/** This function returns true if the CPU has 3DNow! Ext. features */ +extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNowExt(void); + +/** This function returns true if the CPU has SSE features */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void); + +/** This function returns true if the CPU has SSE2 features */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void); + +/** This function returns true if the CPU has AltiVec features */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_cpuinfo_h */ diff --git a/other/sdl/include/SDL_endian.h b/other/sdl/include/SDL_endian.h new file mode 100644 index 0000000..f7a2e2f --- /dev/null +++ b/other/sdl/include/SDL_endian.h @@ -0,0 +1,209 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_endian.h + * Functions for reading and writing endian-specific values + */ + +#ifndef _SDL_endian_h +#define _SDL_endian_h + +#include "SDL_stdinc.h" + +/** @name SDL_ENDIANs + * The two types of endianness + */ +/*@{*/ +#define SDL_LIL_ENDIAN 1234 +#define SDL_BIG_ENDIAN 4321 +/*@}*/ + +#ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */ +#if defined(__hppa__) || \ + defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ + (defined(__MIPS__) && defined(__MISPEB__)) || \ + defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ + defined(__sparc__) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#endif +#endif /* !SDL_BYTEORDER */ + + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @name SDL_Swap Functions + * Use inline functions for compilers that support them, and static + * functions for those that do not. Because these functions become + * static for compilers that do not support inline functions, this + * header should only be included in files that actually use them. + */ +/*@{*/ +#if defined(__GNUC__) && defined(__i386__) && \ + !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) +static __inline__ Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0" : "=q" (x) : "0" (x)); + return x; +} +#elif defined(__GNUC__) && defined(__x86_64__) +static __inline__ Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0" : "=Q" (x) : "0" (x)); + return x; +} +#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) +static __inline__ Uint16 SDL_Swap16(Uint16 x) +{ + Uint16 result; + + __asm__("rlwimi %0,%2,8,16,23" : "=&r" (result) : "0" (x >> 8), "r" (x)); + return result; +} +#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) +static __inline__ Uint16 SDL_Swap16(Uint16 x) +{ + __asm__("rorw #8,%0" : "=d" (x) : "0" (x) : "cc"); + return x; +} +#else +static __inline__ Uint16 SDL_Swap16(Uint16 x) { + return((x<<8)|(x>>8)); +} +#endif + +#if defined(__GNUC__) && defined(__i386__) && \ + !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) +static __inline__ Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("bswap %0" : "=r" (x) : "0" (x)); + return x; +} +#elif defined(__GNUC__) && defined(__x86_64__) +static __inline__ Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("bswapl %0" : "=r" (x) : "0" (x)); + return x; +} +#elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) +static __inline__ Uint32 SDL_Swap32(Uint32 x) +{ + Uint32 result; + + __asm__("rlwimi %0,%2,24,16,23" : "=&r" (result) : "0" (x>>24), "r" (x)); + __asm__("rlwimi %0,%2,8,8,15" : "=&r" (result) : "0" (result), "r" (x)); + __asm__("rlwimi %0,%2,24,0,7" : "=&r" (result) : "0" (result), "r" (x)); + return result; +} +#elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) +static __inline__ Uint32 SDL_Swap32(Uint32 x) +{ + __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0" : "=d" (x) : "0" (x) : "cc"); + return x; +} +#else +static __inline__ Uint32 SDL_Swap32(Uint32 x) { + return((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24)); +} +#endif + +#ifdef SDL_HAS_64BIT_TYPE +#if defined(__GNUC__) && defined(__i386__) && \ + !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) +static __inline__ Uint64 SDL_Swap64(Uint64 x) +{ + union { + struct { Uint32 a,b; } s; + Uint64 u; + } v; + v.u = x; + __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1" + : "=r" (v.s.a), "=r" (v.s.b) + : "0" (v.s.a), "1" (v.s.b)); + return v.u; +} +#elif defined(__GNUC__) && defined(__x86_64__) +static __inline__ Uint64 SDL_Swap64(Uint64 x) +{ + __asm__("bswapq %0" : "=r" (x) : "0" (x)); + return x; +} +#else +static __inline__ Uint64 SDL_Swap64(Uint64 x) +{ + Uint32 hi, lo; + + /* Separate into high and low 32-bit values and swap them */ + lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x >>= 32; + hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x = SDL_Swap32(lo); + x <<= 32; + x |= SDL_Swap32(hi); + return(x); +} +#endif +#else +/* This is mainly to keep compilers from complaining in SDL code. + * If there is no real 64-bit datatype, then compilers will complain about + * the fake 64-bit datatype that SDL provides when it compiles user code. + */ +#define SDL_Swap64(X) (X) +#endif /* SDL_HAS_64BIT_TYPE */ +/*@}*/ + +/** + * @name SDL_SwapLE and SDL_SwapBE Functions + * Byteswap item from the specified endianness to the native endianness + */ +/*@{*/ +#if SDL_BYTEORDER == SDL_LIL_ENDIAN +#define SDL_SwapLE16(X) (X) +#define SDL_SwapLE32(X) (X) +#define SDL_SwapLE64(X) (X) +#define SDL_SwapBE16(X) SDL_Swap16(X) +#define SDL_SwapBE32(X) SDL_Swap32(X) +#define SDL_SwapBE64(X) SDL_Swap64(X) +#else +#define SDL_SwapLE16(X) SDL_Swap16(X) +#define SDL_SwapLE32(X) SDL_Swap32(X) +#define SDL_SwapLE64(X) SDL_Swap64(X) +#define SDL_SwapBE16(X) (X) +#define SDL_SwapBE32(X) (X) +#define SDL_SwapBE64(X) (X) +#endif +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_endian_h */ diff --git a/other/sdl/include/SDL_error.h b/other/sdl/include/SDL_error.h new file mode 100644 index 0000000..b103703 --- /dev/null +++ b/other/sdl/include/SDL_error.h @@ -0,0 +1,72 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_error.h + * Simple error message routines for SDL + */ + +#ifndef _SDL_error_h +#define _SDL_error_h + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @name Public functions + */ +/*@{*/ +extern DECLSPEC void SDLCALL SDL_SetError(const char *fmt, ...); +extern DECLSPEC char * SDLCALL SDL_GetError(void); +extern DECLSPEC void SDLCALL SDL_ClearError(void); +/*@}*/ + +/** + * @name Private functions + * @internal Private error message function - used internally + */ +/*@{*/ +#define SDL_OutOfMemory() SDL_Error(SDL_ENOMEM) +#define SDL_Unsupported() SDL_Error(SDL_UNSUPPORTED) +typedef enum { + SDL_ENOMEM, + SDL_EFREAD, + SDL_EFWRITE, + SDL_EFSEEK, + SDL_UNSUPPORTED, + SDL_LASTERROR +} SDL_errorcode; +extern DECLSPEC void SDLCALL SDL_Error(SDL_errorcode code); +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_error_h */ diff --git a/other/sdl/include/SDL_events.h b/other/sdl/include/SDL_events.h new file mode 100644 index 0000000..c94a30c --- /dev/null +++ b/other/sdl/include/SDL_events.h @@ -0,0 +1,356 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file SDL_events.h + * Include file for SDL event handling + */ + +#ifndef _SDL_events_h +#define _SDL_events_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_active.h" +#include "SDL_keyboard.h" +#include "SDL_mouse.h" +#include "SDL_joystick.h" +#include "SDL_quit.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @name General keyboard/mouse state definitions */ +/*@{*/ +#define SDL_RELEASED 0 +#define SDL_PRESSED 1 +/*@}*/ + +/** Event enumerations */ +typedef enum { + SDL_NOEVENT = 0, /**< Unused (do not remove) */ + SDL_ACTIVEEVENT, /**< Application loses/gains visibility */ + SDL_KEYDOWN, /**< Keys pressed */ + SDL_KEYUP, /**< Keys released */ + SDL_MOUSEMOTION, /**< Mouse moved */ + SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */ + SDL_MOUSEBUTTONUP, /**< Mouse button released */ + SDL_JOYAXISMOTION, /**< Joystick axis motion */ + SDL_JOYBALLMOTION, /**< Joystick trackball motion */ + SDL_JOYHATMOTION, /**< Joystick hat position change */ + SDL_JOYBUTTONDOWN, /**< Joystick button pressed */ + SDL_JOYBUTTONUP, /**< Joystick button released */ + SDL_QUIT, /**< User-requested quit */ + SDL_SYSWMEVENT, /**< System specific event */ + SDL_EVENT_RESERVEDA, /**< Reserved for future use.. */ + SDL_EVENT_RESERVEDB, /**< Reserved for future use.. */ + SDL_VIDEORESIZE, /**< User resized video mode */ + SDL_VIDEOEXPOSE, /**< Screen needs to be redrawn */ + SDL_EVENT_RESERVED2, /**< Reserved for future use.. */ + SDL_EVENT_RESERVED3, /**< Reserved for future use.. */ + SDL_EVENT_RESERVED4, /**< Reserved for future use.. */ + SDL_EVENT_RESERVED5, /**< Reserved for future use.. */ + SDL_EVENT_RESERVED6, /**< Reserved for future use.. */ + SDL_EVENT_RESERVED7, /**< Reserved for future use.. */ + /** Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ + SDL_USEREVENT = 24, + /** This last event is only for bounding internal arrays + * It is the number of bits in the event mask datatype -- Uint32 + */ + SDL_NUMEVENTS = 32 +} SDL_EventType; + +/** @name Predefined event masks */ +/*@{*/ +#define SDL_EVENTMASK(X) (1<<(X)) +typedef enum { + SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT), + SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN), + SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP), + SDL_KEYEVENTMASK = SDL_EVENTMASK(SDL_KEYDOWN)| + SDL_EVENTMASK(SDL_KEYUP), + SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION), + SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN), + SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP), + SDL_MOUSEEVENTMASK = SDL_EVENTMASK(SDL_MOUSEMOTION)| + SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)| + SDL_EVENTMASK(SDL_MOUSEBUTTONUP), + SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION), + SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION), + SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION), + SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN), + SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP), + SDL_JOYEVENTMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION)| + SDL_EVENTMASK(SDL_JOYBALLMOTION)| + SDL_EVENTMASK(SDL_JOYHATMOTION)| + SDL_EVENTMASK(SDL_JOYBUTTONDOWN)| + SDL_EVENTMASK(SDL_JOYBUTTONUP), + SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE), + SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE), + SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT), + SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT) +} SDL_EventMask ; +#define SDL_ALLEVENTS 0xFFFFFFFF +/*@}*/ + +/** Application visibility event structure */ +typedef struct SDL_ActiveEvent { + Uint8 type; /**< SDL_ACTIVEEVENT */ + Uint8 gain; /**< Whether given states were gained or lost (1/0) */ + Uint8 state; /**< A mask of the focus states */ +} SDL_ActiveEvent; + +/** Keyboard event structure */ +typedef struct SDL_KeyboardEvent { + Uint8 type; /**< SDL_KEYDOWN or SDL_KEYUP */ + Uint8 which; /**< The keyboard device index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + SDL_keysym keysym; +} SDL_KeyboardEvent; + +/** Mouse motion event structure */ +typedef struct SDL_MouseMotionEvent { + Uint8 type; /**< SDL_MOUSEMOTION */ + Uint8 which; /**< The mouse device index */ + Uint8 state; /**< The current button state */ + Uint16 x, y; /**< The X/Y coordinates of the mouse */ + Sint16 xrel; /**< The relative motion in the X direction */ + Sint16 yrel; /**< The relative motion in the Y direction */ +} SDL_MouseMotionEvent; + +/** Mouse button event structure */ +typedef struct SDL_MouseButtonEvent { + Uint8 type; /**< SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */ + Uint8 which; /**< The mouse device index */ + Uint8 button; /**< The mouse button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + Uint16 x, y; /**< The X/Y coordinates of the mouse at press time */ +} SDL_MouseButtonEvent; + +/** Joystick axis motion event structure */ +typedef struct SDL_JoyAxisEvent { + Uint8 type; /**< SDL_JOYAXISMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 axis; /**< The joystick axis index */ + Sint16 value; /**< The axis value (range: -32768 to 32767) */ +} SDL_JoyAxisEvent; + +/** Joystick trackball motion event structure */ +typedef struct SDL_JoyBallEvent { + Uint8 type; /**< SDL_JOYBALLMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 ball; /**< The joystick trackball index */ + Sint16 xrel; /**< The relative motion in the X direction */ + Sint16 yrel; /**< The relative motion in the Y direction */ +} SDL_JoyBallEvent; + +/** Joystick hat position change event structure */ +typedef struct SDL_JoyHatEvent { + Uint8 type; /**< SDL_JOYHATMOTION */ + Uint8 which; /**< The joystick device index */ + Uint8 hat; /**< The joystick hat index */ + Uint8 value; /**< The hat position value: + * SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP + * SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT + * SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN + * Note that zero means the POV is centered. + */ +} SDL_JoyHatEvent; + +/** Joystick button event structure */ +typedef struct SDL_JoyButtonEvent { + Uint8 type; /**< SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */ + Uint8 which; /**< The joystick device index */ + Uint8 button; /**< The joystick button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ +} SDL_JoyButtonEvent; + +/** The "window resized" event + * When you get this event, you are responsible for setting a new video + * mode with the new width and height. + */ +typedef struct SDL_ResizeEvent { + Uint8 type; /**< SDL_VIDEORESIZE */ + int w; /**< New width */ + int h; /**< New height */ +} SDL_ResizeEvent; + +/** The "screen redraw" event */ +typedef struct SDL_ExposeEvent { + Uint8 type; /**< SDL_VIDEOEXPOSE */ +} SDL_ExposeEvent; + +/** The "quit requested" event */ +typedef struct SDL_QuitEvent { + Uint8 type; /**< SDL_QUIT */ +} SDL_QuitEvent; + +/** A user-defined event type */ +typedef struct SDL_UserEvent { + Uint8 type; /**< SDL_USEREVENT through SDL_NUMEVENTS-1 */ + int code; /**< User defined event code */ + void *data1; /**< User defined data pointer */ + void *data2; /**< User defined data pointer */ +} SDL_UserEvent; + +/** If you want to use this event, you should include SDL_syswm.h */ +struct SDL_SysWMmsg; +typedef struct SDL_SysWMmsg SDL_SysWMmsg; +typedef struct SDL_SysWMEvent { + Uint8 type; + SDL_SysWMmsg *msg; +} SDL_SysWMEvent; + +/** General event structure */ +typedef union SDL_Event { + Uint8 type; + SDL_ActiveEvent active; + SDL_KeyboardEvent key; + SDL_MouseMotionEvent motion; + SDL_MouseButtonEvent button; + SDL_JoyAxisEvent jaxis; + SDL_JoyBallEvent jball; + SDL_JoyHatEvent jhat; + SDL_JoyButtonEvent jbutton; + SDL_ResizeEvent resize; + SDL_ExposeEvent expose; + SDL_QuitEvent quit; + SDL_UserEvent user; + SDL_SysWMEvent syswm; +} SDL_Event; + + +/* Function prototypes */ + +/** Pumps the event loop, gathering events from the input devices. + * This function updates the event queue and internal input device state. + * This should only be run in the thread that sets the video mode. + */ +extern DECLSPEC void SDLCALL SDL_PumpEvents(void); + +typedef enum { + SDL_ADDEVENT, + SDL_PEEKEVENT, + SDL_GETEVENT +} SDL_eventaction; + +/** + * Checks the event queue for messages and optionally returns them. + * + * If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to + * the back of the event queue. + * If 'action' is SDL_PEEKEVENT, up to 'numevents' events at the front + * of the event queue, matching 'mask', will be returned and will not + * be removed from the queue. + * If 'action' is SDL_GETEVENT, up to 'numevents' events at the front + * of the event queue, matching 'mask', will be returned and will be + * removed from the queue. + * + * @return + * This function returns the number of events actually stored, or -1 + * if there was an error. + * + * This function is thread-safe. + */ +extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event *events, int numevents, + SDL_eventaction action, Uint32 mask); + +/** Polls for currently pending events, and returns 1 if there are any pending + * events, or 0 if there are none available. If 'event' is not NULL, the next + * event is removed from the queue and stored in that area. + */ +extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event *event); + +/** Waits indefinitely for the next available event, returning 1, or 0 if there + * was an error while waiting for events. If 'event' is not NULL, the next + * event is removed from the queue and stored in that area. + */ +extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event *event); + +/** Add an event to the event queue. + * This function returns 0 on success, or -1 if the event queue was full + * or there was some other error. + */ +extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event *event); + +/** @name Event Filtering */ +/*@{*/ +typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); +/** + * This function sets up a filter to process all events before they + * change internal state and are posted to the internal event queue. + * + * The filter is protypted as: + * @code typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); @endcode + * + * If the filter returns 1, then the event will be added to the internal queue. + * If it returns 0, then the event will be dropped from the queue, but the + * internal state will still be updated. This allows selective filtering of + * dynamically arriving events. + * + * @warning Be very careful of what you do in the event filter function, as + * it may run in a different thread! + * + * There is one caveat when dealing with the SDL_QUITEVENT event type. The + * event filter is only called when the window manager desires to close the + * application window. If the event filter returns 1, then the window will + * be closed, otherwise the window will remain open if possible. + * If the quit event is generated by an interrupt signal, it will bypass the + * internal queue and be delivered to the application at the next event poll. + */ +extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter); + +/** + * Return the current event filter - can be used to "chain" filters. + * If there is no event filter set, this function returns NULL. + */ +extern DECLSPEC SDL_EventFilter SDLCALL SDL_GetEventFilter(void); +/*@}*/ + +/** @name Event State */ +/*@{*/ +#define SDL_QUERY -1 +#define SDL_IGNORE 0 +#define SDL_DISABLE 0 +#define SDL_ENABLE 1 +/*@}*/ + +/** +* This function allows you to set the state of processing certain events. +* If 'state' is set to SDL_IGNORE, that event will be automatically dropped +* from the event queue and will not event be filtered. +* If 'state' is set to SDL_ENABLE, that event will be processed normally. +* If 'state' is set to SDL_QUERY, SDL_EventState() will return the +* current processing state of the specified event. +*/ +extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint8 type, int state); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_events_h */ diff --git a/other/sdl/include/SDL_getenv.h b/other/sdl/include/SDL_getenv.h new file mode 100644 index 0000000..253ad88 --- /dev/null +++ b/other/sdl/include/SDL_getenv.h @@ -0,0 +1,28 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_getenv.h + * @deprecated Use SDL_stdinc.h instead + */ + +/* DEPRECATED */ +#include "SDL_stdinc.h" diff --git a/other/sdl/include/SDL_joystick.h b/other/sdl/include/SDL_joystick.h new file mode 100644 index 0000000..d5135c3 --- /dev/null +++ b/other/sdl/include/SDL_joystick.h @@ -0,0 +1,187 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_joystick.h + * Include file for SDL joystick event handling + */ + +#ifndef _SDL_joystick_h +#define _SDL_joystick_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @file SDL_joystick.h + * @note In order to use these functions, SDL_Init() must have been called + * with the SDL_INIT_JOYSTICK flag. This causes SDL to scan the system + * for joysticks, and load appropriate drivers. + */ + +/** The joystick structure used to identify an SDL joystick */ +struct _SDL_Joystick; +typedef struct _SDL_Joystick SDL_Joystick; + +/* Function prototypes */ +/** + * Count the number of joysticks attached to the system + */ +extern DECLSPEC int SDLCALL SDL_NumJoysticks(void); + +/** + * Get the implementation dependent name of a joystick. + * + * This can be called before any joysticks are opened. + * If no name can be found, this function returns NULL. + */ +extern DECLSPEC const char * SDLCALL SDL_JoystickName(int device_index); + +/** + * Open a joystick for use. + * + * @param[in] device_index + * The index passed as an argument refers to + * the N'th joystick on the system. This index is the value which will + * identify this joystick in future joystick events. + * + * @return This function returns a joystick identifier, or NULL if an error occurred. + */ +extern DECLSPEC SDL_Joystick * SDLCALL SDL_JoystickOpen(int device_index); + +/** + * Returns 1 if the joystick has been opened, or 0 if it has not. + */ +extern DECLSPEC int SDLCALL SDL_JoystickOpened(int device_index); + +/** + * Get the device index of an opened joystick. + */ +extern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick *joystick); + +/** + * Get the number of general axis controls on a joystick + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick); + +/** + * Get the number of trackballs on a joystick + * + * Joystick trackballs have only relative motion events associated + * with them and their state cannot be polled. + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick); + +/** + * Get the number of POV hats on a joystick + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick); + +/** + * Get the number of buttons on a joystick + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick); + +/** + * Update the current state of the open joysticks. + * + * This is called automatically by the event loop if any joystick + * events are enabled. + */ +extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void); + +/** + * Enable/disable joystick event polling. + * + * If joystick events are disabled, you must call SDL_JoystickUpdate() + * yourself and check the state of the joystick when you want joystick + * information. + * + * @param[in] state The state can be one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE. + */ +extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state); + +/** + * Get the current state of an axis control on a joystick + * + * @param[in] axis The axis indices start at index 0. + * + * @return The state is a value ranging from -32768 to 32767. + */ +extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, int axis); + +/** + * @name Hat Positions + * The return value of SDL_JoystickGetHat() is one of the following positions: + */ +/*@{*/ +#define SDL_HAT_CENTERED 0x00 +#define SDL_HAT_UP 0x01 +#define SDL_HAT_RIGHT 0x02 +#define SDL_HAT_DOWN 0x04 +#define SDL_HAT_LEFT 0x08 +#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP) +#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN) +#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP) +#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN) +/*@}*/ + +/** + * Get the current state of a POV hat on a joystick + * + * @param[in] hat The hat indices start at index 0. + */ +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick, int hat); + +/** + * Get the ball axis change since the last poll + * + * @param[in] ball The ball indices start at index 0. + * + * @return This returns 0, or -1 if you passed it invalid parameters. + */ +extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick, int ball, int *dx, int *dy); + +/** + * Get the current state of a button on a joystick + * + * @param[in] button The button indices start at index 0. + */ +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick, int button); + +/** + * Close a joystick previously opened with SDL_JoystickOpen() + */ +extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_joystick_h */ diff --git a/other/sdl/include/SDL_keyboard.h b/other/sdl/include/SDL_keyboard.h new file mode 100644 index 0000000..7b59d24 --- /dev/null +++ b/other/sdl/include/SDL_keyboard.h @@ -0,0 +1,135 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_keyboard.h + * Include file for SDL keyboard event handling + */ + +#ifndef _SDL_keyboard_h +#define _SDL_keyboard_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_keysym.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** Keysym structure + * + * - The scancode is hardware dependent, and should not be used by general + * applications. If no hardware scancode is available, it will be 0. + * + * - The 'unicode' translated character is only available when character + * translation is enabled by the SDL_EnableUNICODE() API. If non-zero, + * this is a UNICODE character corresponding to the keypress. If the + * high 9 bits of the character are 0, then this maps to the equivalent + * ASCII character: + * @code + * char ch; + * if ( (keysym.unicode & 0xFF80) == 0 ) { + * ch = keysym.unicode & 0x7F; + * } else { + * An international character.. + * } + * @endcode + */ +typedef struct SDL_keysym { + Uint8 scancode; /**< hardware specific scancode */ + SDLKey sym; /**< SDL virtual keysym */ + SDLMod mod; /**< current key modifiers */ + Uint16 unicode; /**< translated character */ +} SDL_keysym; + +/** This is the mask which refers to all hotkey bindings */ +#define SDL_ALL_HOTKEYS 0xFFFFFFFF + +/* Function prototypes */ +/** + * Enable/Disable UNICODE translation of keyboard input. + * + * This translation has some overhead, so translation defaults off. + * + * @param[in] enable + * If 'enable' is 1, translation is enabled. + * If 'enable' is 0, translation is disabled. + * If 'enable' is -1, the translation state is not changed. + * + * @return It returns the previous state of keyboard translation. + */ +extern DECLSPEC int SDLCALL SDL_EnableUNICODE(int enable); + +#define SDL_DEFAULT_REPEAT_DELAY 500 +#define SDL_DEFAULT_REPEAT_INTERVAL 30 +/** + * Enable/Disable keyboard repeat. Keyboard repeat defaults to off. + * + * @param[in] delay + * 'delay' is the initial delay in ms between the time when a key is + * pressed, and keyboard repeat begins. + * + * @param[in] interval + * 'interval' is the time in ms between keyboard repeat events. + * + * If 'delay' is set to 0, keyboard repeat is disabled. + */ +extern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval); +extern DECLSPEC void SDLCALL SDL_GetKeyRepeat(int *delay, int *interval); + +/** + * Get a snapshot of the current state of the keyboard. + * Returns an array of keystates, indexed by the SDLK_* syms. + * Usage: + * @code + * Uint8 *keystate = SDL_GetKeyState(NULL); + * if ( keystate[SDLK_RETURN] ) //... \<RETURN> is pressed. + * @endcode + */ +extern DECLSPEC Uint8 * SDLCALL SDL_GetKeyState(int *numkeys); + +/** + * Get the current key modifier state + */ +extern DECLSPEC SDLMod SDLCALL SDL_GetModState(void); + +/** + * Set the current key modifier state. + * This does not change the keyboard state, only the key modifier flags. + */ +extern DECLSPEC void SDLCALL SDL_SetModState(SDLMod modstate); + +/** + * Get the name of an SDL virtual keysym + */ +extern DECLSPEC char * SDLCALL SDL_GetKeyName(SDLKey key); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_keyboard_h */ diff --git a/other/sdl/include/SDL_keysym.h b/other/sdl/include/SDL_keysym.h new file mode 100644 index 0000000..9010128 --- /dev/null +++ b/other/sdl/include/SDL_keysym.h @@ -0,0 +1,326 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_keysym_h +#define _SDL_keysym_h + +/** What we really want is a mapping of every raw key on the keyboard. + * To support international keyboards, we use the range 0xA1 - 0xFF + * as international virtual keycodes. We'll follow in the footsteps of X11... + * @brief The names of the keys + */ +typedef enum { + /** @name ASCII mapped keysyms + * The keyboard syms have been cleverly chosen to map to ASCII + */ + /*@{*/ + SDLK_UNKNOWN = 0, + SDLK_FIRST = 0, + SDLK_BACKSPACE = 8, + SDLK_TAB = 9, + SDLK_CLEAR = 12, + SDLK_RETURN = 13, + SDLK_PAUSE = 19, + SDLK_ESCAPE = 27, + SDLK_SPACE = 32, + SDLK_EXCLAIM = 33, + SDLK_QUOTEDBL = 34, + SDLK_HASH = 35, + SDLK_DOLLAR = 36, + SDLK_AMPERSAND = 38, + SDLK_QUOTE = 39, + SDLK_LEFTPAREN = 40, + SDLK_RIGHTPAREN = 41, + SDLK_ASTERISK = 42, + SDLK_PLUS = 43, + SDLK_COMMA = 44, + SDLK_MINUS = 45, + SDLK_PERIOD = 46, + SDLK_SLASH = 47, + SDLK_0 = 48, + SDLK_1 = 49, + SDLK_2 = 50, + SDLK_3 = 51, + SDLK_4 = 52, + SDLK_5 = 53, + SDLK_6 = 54, + SDLK_7 = 55, + SDLK_8 = 56, + SDLK_9 = 57, + SDLK_COLON = 58, + SDLK_SEMICOLON = 59, + SDLK_LESS = 60, + SDLK_EQUALS = 61, + SDLK_GREATER = 62, + SDLK_QUESTION = 63, + SDLK_AT = 64, + /* + Skip uppercase letters + */ + SDLK_LEFTBRACKET = 91, + SDLK_BACKSLASH = 92, + SDLK_RIGHTBRACKET = 93, + SDLK_CARET = 94, + SDLK_UNDERSCORE = 95, + SDLK_BACKQUOTE = 96, + SDLK_a = 97, + SDLK_b = 98, + SDLK_c = 99, + SDLK_d = 100, + SDLK_e = 101, + SDLK_f = 102, + SDLK_g = 103, + SDLK_h = 104, + SDLK_i = 105, + SDLK_j = 106, + SDLK_k = 107, + SDLK_l = 108, + SDLK_m = 109, + SDLK_n = 110, + SDLK_o = 111, + SDLK_p = 112, + SDLK_q = 113, + SDLK_r = 114, + SDLK_s = 115, + SDLK_t = 116, + SDLK_u = 117, + SDLK_v = 118, + SDLK_w = 119, + SDLK_x = 120, + SDLK_y = 121, + SDLK_z = 122, + SDLK_DELETE = 127, + /* End of ASCII mapped keysyms */ + /*@}*/ + + /** @name International keyboard syms */ + /*@{*/ + SDLK_WORLD_0 = 160, /* 0xA0 */ + SDLK_WORLD_1 = 161, + SDLK_WORLD_2 = 162, + SDLK_WORLD_3 = 163, + SDLK_WORLD_4 = 164, + SDLK_WORLD_5 = 165, + SDLK_WORLD_6 = 166, + SDLK_WORLD_7 = 167, + SDLK_WORLD_8 = 168, + SDLK_WORLD_9 = 169, + SDLK_WORLD_10 = 170, + SDLK_WORLD_11 = 171, + SDLK_WORLD_12 = 172, + SDLK_WORLD_13 = 173, + SDLK_WORLD_14 = 174, + SDLK_WORLD_15 = 175, + SDLK_WORLD_16 = 176, + SDLK_WORLD_17 = 177, + SDLK_WORLD_18 = 178, + SDLK_WORLD_19 = 179, + SDLK_WORLD_20 = 180, + SDLK_WORLD_21 = 181, + SDLK_WORLD_22 = 182, + SDLK_WORLD_23 = 183, + SDLK_WORLD_24 = 184, + SDLK_WORLD_25 = 185, + SDLK_WORLD_26 = 186, + SDLK_WORLD_27 = 187, + SDLK_WORLD_28 = 188, + SDLK_WORLD_29 = 189, + SDLK_WORLD_30 = 190, + SDLK_WORLD_31 = 191, + SDLK_WORLD_32 = 192, + SDLK_WORLD_33 = 193, + SDLK_WORLD_34 = 194, + SDLK_WORLD_35 = 195, + SDLK_WORLD_36 = 196, + SDLK_WORLD_37 = 197, + SDLK_WORLD_38 = 198, + SDLK_WORLD_39 = 199, + SDLK_WORLD_40 = 200, + SDLK_WORLD_41 = 201, + SDLK_WORLD_42 = 202, + SDLK_WORLD_43 = 203, + SDLK_WORLD_44 = 204, + SDLK_WORLD_45 = 205, + SDLK_WORLD_46 = 206, + SDLK_WORLD_47 = 207, + SDLK_WORLD_48 = 208, + SDLK_WORLD_49 = 209, + SDLK_WORLD_50 = 210, + SDLK_WORLD_51 = 211, + SDLK_WORLD_52 = 212, + SDLK_WORLD_53 = 213, + SDLK_WORLD_54 = 214, + SDLK_WORLD_55 = 215, + SDLK_WORLD_56 = 216, + SDLK_WORLD_57 = 217, + SDLK_WORLD_58 = 218, + SDLK_WORLD_59 = 219, + SDLK_WORLD_60 = 220, + SDLK_WORLD_61 = 221, + SDLK_WORLD_62 = 222, + SDLK_WORLD_63 = 223, + SDLK_WORLD_64 = 224, + SDLK_WORLD_65 = 225, + SDLK_WORLD_66 = 226, + SDLK_WORLD_67 = 227, + SDLK_WORLD_68 = 228, + SDLK_WORLD_69 = 229, + SDLK_WORLD_70 = 230, + SDLK_WORLD_71 = 231, + SDLK_WORLD_72 = 232, + SDLK_WORLD_73 = 233, + SDLK_WORLD_74 = 234, + SDLK_WORLD_75 = 235, + SDLK_WORLD_76 = 236, + SDLK_WORLD_77 = 237, + SDLK_WORLD_78 = 238, + SDLK_WORLD_79 = 239, + SDLK_WORLD_80 = 240, + SDLK_WORLD_81 = 241, + SDLK_WORLD_82 = 242, + SDLK_WORLD_83 = 243, + SDLK_WORLD_84 = 244, + SDLK_WORLD_85 = 245, + SDLK_WORLD_86 = 246, + SDLK_WORLD_87 = 247, + SDLK_WORLD_88 = 248, + SDLK_WORLD_89 = 249, + SDLK_WORLD_90 = 250, + SDLK_WORLD_91 = 251, + SDLK_WORLD_92 = 252, + SDLK_WORLD_93 = 253, + SDLK_WORLD_94 = 254, + SDLK_WORLD_95 = 255, /* 0xFF */ + /*@}*/ + + /** @name Numeric keypad */ + /*@{*/ + SDLK_KP0 = 256, + SDLK_KP1 = 257, + SDLK_KP2 = 258, + SDLK_KP3 = 259, + SDLK_KP4 = 260, + SDLK_KP5 = 261, + SDLK_KP6 = 262, + SDLK_KP7 = 263, + SDLK_KP8 = 264, + SDLK_KP9 = 265, + SDLK_KP_PERIOD = 266, + SDLK_KP_DIVIDE = 267, + SDLK_KP_MULTIPLY = 268, + SDLK_KP_MINUS = 269, + SDLK_KP_PLUS = 270, + SDLK_KP_ENTER = 271, + SDLK_KP_EQUALS = 272, + /*@}*/ + + /** @name Arrows + Home/End pad */ + /*@{*/ + SDLK_UP = 273, + SDLK_DOWN = 274, + SDLK_RIGHT = 275, + SDLK_LEFT = 276, + SDLK_INSERT = 277, + SDLK_HOME = 278, + SDLK_END = 279, + SDLK_PAGEUP = 280, + SDLK_PAGEDOWN = 281, + /*@}*/ + + /** @name Function keys */ + /*@{*/ + SDLK_F1 = 282, + SDLK_F2 = 283, + SDLK_F3 = 284, + SDLK_F4 = 285, + SDLK_F5 = 286, + SDLK_F6 = 287, + SDLK_F7 = 288, + SDLK_F8 = 289, + SDLK_F9 = 290, + SDLK_F10 = 291, + SDLK_F11 = 292, + SDLK_F12 = 293, + SDLK_F13 = 294, + SDLK_F14 = 295, + SDLK_F15 = 296, + /*@}*/ + + /** @name Key state modifier keys */ + /*@{*/ + SDLK_NUMLOCK = 300, + SDLK_CAPSLOCK = 301, + SDLK_SCROLLOCK = 302, + SDLK_RSHIFT = 303, + SDLK_LSHIFT = 304, + SDLK_RCTRL = 305, + SDLK_LCTRL = 306, + SDLK_RALT = 307, + SDLK_LALT = 308, + SDLK_RMETA = 309, + SDLK_LMETA = 310, + SDLK_LSUPER = 311, /**< Left "Windows" key */ + SDLK_RSUPER = 312, /**< Right "Windows" key */ + SDLK_MODE = 313, /**< "Alt Gr" key */ + SDLK_COMPOSE = 314, /**< Multi-key compose key */ + /*@}*/ + + /** @name Miscellaneous function keys */ + /*@{*/ + SDLK_HELP = 315, + SDLK_PRINT = 316, + SDLK_SYSREQ = 317, + SDLK_BREAK = 318, + SDLK_MENU = 319, + SDLK_POWER = 320, /**< Power Macintosh power key */ + SDLK_EURO = 321, /**< Some european keyboards */ + SDLK_UNDO = 322, /**< Atari keyboard has Undo */ + /*@}*/ + + /* Add any other keys here */ + + SDLK_LAST +} SDLKey; + +/** Enumeration of valid key mods (possibly OR'd together) */ +typedef enum { + KMOD_NONE = 0x0000, + KMOD_LSHIFT= 0x0001, + KMOD_RSHIFT= 0x0002, + KMOD_LCTRL = 0x0040, + KMOD_RCTRL = 0x0080, + KMOD_LALT = 0x0100, + KMOD_RALT = 0x0200, + KMOD_LMETA = 0x0400, + KMOD_RMETA = 0x0800, + KMOD_NUM = 0x1000, + KMOD_CAPS = 0x2000, + KMOD_MODE = 0x4000, + KMOD_RESERVED = 0x8000 +} SDLMod; + +#define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) +#define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) +#define KMOD_ALT (KMOD_LALT|KMOD_RALT) +#define KMOD_META (KMOD_LMETA|KMOD_RMETA) + +#endif /* _SDL_keysym_h */ diff --git a/other/sdl/include/SDL_loadso.h b/other/sdl/include/SDL_loadso.h new file mode 100644 index 0000000..45a17f9 --- /dev/null +++ b/other/sdl/include/SDL_loadso.h @@ -0,0 +1,78 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_loadso.h + * System dependent library loading routines + */ + +/** @file SDL_loadso.h + * Some things to keep in mind: + * - These functions only work on C function names. Other languages may + * have name mangling and intrinsic language support that varies from + * compiler to compiler. + * - Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * - Avoid namespace collisions. If you load a symbol from the library, + * it is not defined whether or not it goes into the global symbol + * namespace for the application. If it does and it conflicts with + * symbols in your code or other shared libraries, you will not get + * the results you expect. :) + */ + + +#ifndef _SDL_loadso_h +#define _SDL_loadso_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This function dynamically loads a shared object and returns a pointer + * to the object handle (or NULL if there was an error). + * The 'sofile' parameter is a system dependent name of the object file. + */ +extern DECLSPEC void * SDLCALL SDL_LoadObject(const char *sofile); + +/** + * Given an object handle, this function looks up the address of the + * named function in the shared object and returns it. This address + * is no longer valid after calling SDL_UnloadObject(). + */ +extern DECLSPEC void * SDLCALL SDL_LoadFunction(void *handle, const char *name); + +/** Unload a shared object from memory */ +extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_loadso_h */ diff --git a/other/sdl/include/SDL_main.h b/other/sdl/include/SDL_main.h new file mode 100644 index 0000000..b7f6b2c --- /dev/null +++ b/other/sdl/include/SDL_main.h @@ -0,0 +1,106 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_main_h +#define _SDL_main_h + +#include "SDL_stdinc.h" + +/** @file SDL_main.h + * Redefine main() on Win32 and MacOS so that it is called by winmain.c + */ + +#if defined(__WIN32__) || \ + (defined(__MWERKS__) && !defined(__BEOS__)) || \ + defined(__MACOS__) || defined(__MACOSX__) || \ + defined(__SYMBIAN32__) || defined(QWS) + +#ifdef __cplusplus +#define C_LINKAGE "C" +#else +#define C_LINKAGE +#endif /* __cplusplus */ + +/** The application's main() function must be called with C linkage, + * and should be declared like this: + * @code + * #ifdef __cplusplus + * extern "C" + * #endif + * int main(int argc, char *argv[]) + * { + * } + * @endcode + */ +#define main SDL_main + +/** The prototype for the application's main() function */ +extern C_LINKAGE int SDL_main(int argc, char *argv[]); + + +/** @name From the SDL library code -- needed for registering the app on Win32 */ +/*@{*/ +#ifdef __WIN32__ + +#include "begin_code.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** This should be called from your WinMain() function, if any */ +extern DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst); +/** This can also be called, but is no longer necessary */ +extern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style, void *hInst); +/** This can also be called, but is no longer necessary (SDL_Quit calls it) */ +extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); +#ifdef __cplusplus +} +#endif +#include "close_code.h" +#endif +/*@}*/ + +/** @name From the SDL library code -- needed for registering QuickDraw on MacOS */ +/*@{*/ +#if defined(__MACOS__) + +#include "begin_code.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** Forward declaration so we don't need to include QuickDraw.h */ +struct QDGlobals; + +/** This should be called from your main() function, if any */ +extern DECLSPEC void SDLCALL SDL_InitQuickDraw(struct QDGlobals *the_qd); + +#ifdef __cplusplus +} +#endif +#include "close_code.h" +#endif +/*@}*/ + +#endif /* Need to redefine main()? */ + +#endif /* _SDL_main_h */ diff --git a/other/sdl/include/SDL_mouse.h b/other/sdl/include/SDL_mouse.h new file mode 100644 index 0000000..a573f04 --- /dev/null +++ b/other/sdl/include/SDL_mouse.h @@ -0,0 +1,143 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_mouse.h + * Include file for SDL mouse event handling + */ + +#ifndef _SDL_mouse_h +#define _SDL_mouse_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct WMcursor WMcursor; /**< Implementation dependent */ +typedef struct SDL_Cursor { + SDL_Rect area; /**< The area of the mouse cursor */ + Sint16 hot_x, hot_y; /**< The "tip" of the cursor */ + Uint8 *data; /**< B/W cursor data */ + Uint8 *mask; /**< B/W cursor mask */ + Uint8 *save[2]; /**< Place to save cursor area */ + WMcursor *wm_cursor; /**< Window-manager cursor */ +} SDL_Cursor; + +/* Function prototypes */ +/** + * Retrieve the current state of the mouse. + * The current button state is returned as a button bitmask, which can + * be tested using the SDL_BUTTON(X) macros, and x and y are set to the + * current mouse cursor position. You can pass NULL for either x or y. + */ +extern DECLSPEC Uint8 SDLCALL SDL_GetMouseState(int *x, int *y); + +/** + * Retrieve the current state of the mouse. + * The current button state is returned as a button bitmask, which can + * be tested using the SDL_BUTTON(X) macros, and x and y are set to the + * mouse deltas since the last call to SDL_GetRelativeMouseState(). + */ +extern DECLSPEC Uint8 SDLCALL SDL_GetRelativeMouseState(int *x, int *y); + +/** + * Set the position of the mouse cursor (generates a mouse motion event) + */ +extern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y); + +/** + * Create a cursor using the specified data and mask (in MSB format). + * The cursor width must be a multiple of 8 bits. + * + * The cursor is created in black and white according to the following: + * data mask resulting pixel on screen + * 0 1 White + * 1 1 Black + * 0 0 Transparent + * 1 0 Inverted color if possible, black if not. + * + * Cursors created with this function must be freed with SDL_FreeCursor(). + */ +extern DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor + (Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); + +/** + * Set the currently active cursor to the specified one. + * If the cursor is currently visible, the change will be immediately + * represented on the display. + */ +extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor *cursor); + +/** + * Returns the currently active cursor. + */ +extern DECLSPEC SDL_Cursor * SDLCALL SDL_GetCursor(void); + +/** + * Deallocates a cursor created with SDL_CreateCursor(). + */ +extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor *cursor); + +/** + * Toggle whether or not the cursor is shown on the screen. + * The cursor start off displayed, but can be turned off. + * SDL_ShowCursor() returns 1 if the cursor was being displayed + * before the call, or 0 if it was not. You can query the current + * state by passing a 'toggle' value of -1. + */ +extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); + +/*@{*/ +/** Used as a mask when testing buttons in buttonstate + * Button 1: Left mouse button + * Button 2: Middle mouse button + * Button 3: Right mouse button + * Button 4: Mouse wheel up (may also be a real button) + * Button 5: Mouse wheel down (may also be a real button) + */ +#define SDL_BUTTON(X) (1 << ((X)-1)) +#define SDL_BUTTON_LEFT 1 +#define SDL_BUTTON_MIDDLE 2 +#define SDL_BUTTON_RIGHT 3 +#define SDL_BUTTON_WHEELUP 4 +#define SDL_BUTTON_WHEELDOWN 5 +#define SDL_BUTTON_X1 6 +#define SDL_BUTTON_X2 7 +#define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT) +#define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE) +#define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT) +#define SDL_BUTTON_X1MASK SDL_BUTTON(SDL_BUTTON_X1) +#define SDL_BUTTON_X2MASK SDL_BUTTON(SDL_BUTTON_X2) +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_mouse_h */ diff --git a/other/sdl/include/SDL_mutex.h b/other/sdl/include/SDL_mutex.h new file mode 100644 index 0000000..920971d --- /dev/null +++ b/other/sdl/include/SDL_mutex.h @@ -0,0 +1,177 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_mutex_h +#define _SDL_mutex_h + +/** @file SDL_mutex.h + * Functions to provide thread synchronization primitives + * + * @note These are independent of the other SDL routines. + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** Synchronization functions which can time out return this value + * if they time out. + */ +#define SDL_MUTEX_TIMEDOUT 1 + +/** This is the timeout value which corresponds to never time out */ +#define SDL_MUTEX_MAXWAIT (~(Uint32)0) + + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name Mutex functions */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/** The SDL mutex structure, defined in SDL_mutex.c */ +struct SDL_mutex; +typedef struct SDL_mutex SDL_mutex; + +/** Create a mutex, initialized unlocked */ +extern DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void); + +#define SDL_LockMutex(m) SDL_mutexP(m) +/** Lock the mutex + * @return 0, or -1 on error + */ +extern DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex); + +#define SDL_UnlockMutex(m) SDL_mutexV(m) +/** Unlock the mutex + * @return 0, or -1 on error + * + * It is an error to unlock a mutex that has not been locked by + * the current thread, and doing so results in undefined behavior. + */ +extern DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex); + +/** Destroy a mutex */ +extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex); + +/*@}*/ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name Semaphore functions */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/** The SDL semaphore structure, defined in SDL_sem.c */ +struct SDL_semaphore; +typedef struct SDL_semaphore SDL_sem; + +/** Create a semaphore, initialized with value, returns NULL on failure. */ +extern DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value); + +/** Destroy a semaphore */ +extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem); + +/** + * This function suspends the calling thread until the semaphore pointed + * to by sem has a positive count. It then atomically decreases the semaphore + * count. + */ +extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem); + +/** Non-blocking variant of SDL_SemWait(). + * @return 0 if the wait succeeds, + * SDL_MUTEX_TIMEDOUT if the wait would block, and -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem); + +/** Variant of SDL_SemWait() with a timeout in milliseconds, returns 0 if + * the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait does not succeed in + * the allotted time, and -1 on error. + * + * On some platforms this function is implemented by looping with a delay + * of 1 ms, and so should be avoided if possible. + */ +extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 ms); + +/** Atomically increases the semaphore's count (not blocking). + * @return 0, or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem); + +/** Returns the current count of the semaphore */ +extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem); + +/*@}*/ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name Condition_variable_functions */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/*@{*/ +/** The SDL condition variable structure, defined in SDL_cond.c */ +struct SDL_cond; +typedef struct SDL_cond SDL_cond; +/*@}*/ + +/** Create a condition variable */ +extern DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void); + +/** Destroy a condition variable */ +extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond); + +/** Restart one of the threads that are waiting on the condition variable, + * @return 0 or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond); + +/** Restart all threads that are waiting on the condition variable, + * @return 0 or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond); + +/** Wait on the condition variable, unlocking the provided mutex. + * The mutex must be locked before entering this function! + * The mutex is re-locked once the condition variable is signaled. + * @return 0 when it is signaled, or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mut); + +/** Waits for at most 'ms' milliseconds, and returns 0 if the condition + * variable is signaled, SDL_MUTEX_TIMEDOUT if the condition is not + * signaled in the allotted time, and -1 on error. + * On some platforms this function is implemented by looping with a delay + * of 1 ms, and so should be avoided if possible. + */ +extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms); + +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_mutex_h */ + diff --git a/other/sdl/include/SDL_name.h b/other/sdl/include/SDL_name.h new file mode 100644 index 0000000..511619a --- /dev/null +++ b/other/sdl/include/SDL_name.h @@ -0,0 +1,11 @@ + +#ifndef _SDLname_h_ +#define _SDLname_h_ + +#if defined(__STDC__) || defined(__cplusplus) +#define NeedFunctionPrototypes 1 +#endif + +#define SDL_NAME(X) SDL_##X + +#endif /* _SDLname_h_ */ diff --git a/other/sdl/include/SDL_opengl.h b/other/sdl/include/SDL_opengl.h new file mode 100644 index 0000000..c479a3a --- /dev/null +++ b/other/sdl/include/SDL_opengl.h @@ -0,0 +1,6556 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_opengl.h + * This is a simple file to encapsulate the OpenGL API headers + */ + +#include "SDL_config.h" + +#ifdef __WIN32__ +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX /* Don't defined min() and max() */ +#endif +#include <windows.h> +#endif +#ifndef NO_SDL_GLEXT +#define __glext_h_ /* Don't let gl.h include glext.h */ +#endif +#if defined(__MACOSX__) +#include <OpenGL/gl.h> /* Header File For The OpenGL Library */ +#include <OpenGL/glu.h> /* Header File For The GLU Library */ +#elif defined(__MACOS__) +#include <gl.h> /* Header File For The OpenGL Library */ +#include <glu.h> /* Header File For The GLU Library */ +#else +#include <GL/gl.h> /* Header File For The OpenGL Library */ +#include <GL/glu.h> /* Header File For The GLU Library */ +#endif +#ifndef NO_SDL_GLEXT +#undef __glext_h_ +#endif + +/** @name GLext.h + * This file taken from "GLext.h" from the Jeff Molofee OpenGL tutorials. + * It is included here because glext.h is not available on some systems. + * If you don't want this version included, simply define "NO_SDL_GLEXT" + */ +/*@{*/ +#ifndef NO_SDL_GLEXT +#if !defined(__glext_h_) && !defined(GL_GLEXT_LEGACY) +#define __glext_h_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** License Applicability. Except to the extent portions of this file are +** made subject to an alternative license as permitted in the SGI Free +** Software License B, Version 1.1 (the "License"), the contents of this +** file are subject only to the provisions of the License. You may not use +** this file except in compliance with the License. You may obtain a copy +** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 +** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: +** +** http://oss.sgi.com/projects/FreeB +** +** Note that, as provided in the License, the Software is distributed on an +** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS +** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND +** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A +** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. +** +** Original Code. The Original Code is: OpenGL Sample Implementation, +** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, +** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc. +** Copyright in any portions created by third parties is as indicated +** elsewhere herein. All Rights Reserved. +** +** Additional Notice Provisions: This software was created using the +** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has +** not been independently verified as being compliant with the OpenGL(R) +** version 1.2.1 Specification. +*/ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#define WIN32_LEAN_AND_MEAN 1 +#include <windows.h> +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif +#ifndef GLAPI +#define GLAPI extern +#endif + +/*************************************************************/ + +/* Header file version number, required by OpenGL ABI for Linux */ +/* glext.h last updated 2005/06/20 */ +/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */ +#define GL_GLEXT_VERSION 29 + +#ifndef GL_VERSION_1_2 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_RESCALE_NORMAL 0x803A +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#endif + +#ifndef GL_ARB_imaging +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BLEND_COLOR 0x8005 +#define GL_FUNC_ADD 0x8006 +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_BLEND_EQUATION 0x8009 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_CONVOLUTION_1D 0x8010 +#define GL_CONVOLUTION_2D 0x8011 +#define GL_SEPARABLE_2D 0x8012 +#define GL_CONVOLUTION_BORDER_MODE 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS 0x8015 +#define GL_REDUCE 0x8016 +#define GL_CONVOLUTION_FORMAT 0x8017 +#define GL_CONVOLUTION_WIDTH 0x8018 +#define GL_CONVOLUTION_HEIGHT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 +#define GL_HISTOGRAM 0x8024 +#define GL_PROXY_HISTOGRAM 0x8025 +#define GL_HISTOGRAM_WIDTH 0x8026 +#define GL_HISTOGRAM_FORMAT 0x8027 +#define GL_HISTOGRAM_RED_SIZE 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C +#define GL_HISTOGRAM_SINK 0x802D +#define GL_MINMAX 0x802E +#define GL_MINMAX_FORMAT 0x802F +#define GL_MINMAX_SINK 0x8030 +#define GL_TABLE_TOO_LARGE 0x8031 +#define GL_COLOR_MATRIX 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB +#define GL_COLOR_TABLE 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 +#define GL_PROXY_COLOR_TABLE 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 +#define GL_COLOR_TABLE_SCALE 0x80D6 +#define GL_COLOR_TABLE_BIAS 0x80D7 +#define GL_COLOR_TABLE_FORMAT 0x80D8 +#define GL_COLOR_TABLE_WIDTH 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF +#define GL_CONSTANT_BORDER 0x8151 +#define GL_REPLICATE_BORDER 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR 0x8154 +#endif + +#ifndef GL_VERSION_1_3 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#endif + +#ifndef GL_VERSION_1_4 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#endif + +#ifndef GL_VERSION_1_5 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_FOG_COORD_SRC GL_FOG_COORDINATE_SOURCE +#define GL_FOG_COORD GL_FOG_COORDINATE +#define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE +#define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE +#define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE +#define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER +#define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING +#define GL_SRC0_RGB GL_SOURCE0_RGB +#define GL_SRC1_RGB GL_SOURCE1_RGB +#define GL_SRC2_RGB GL_SOURCE2_RGB +#define GL_SRC0_ALPHA GL_SOURCE0_ALPHA +#define GL_SRC1_ALPHA GL_SOURCE1_ALPHA +#define GL_SRC2_ALPHA GL_SOURCE2_ALPHA +#endif + +#ifndef GL_VERSION_2_0 +#define GL_BLEND_EQUATION_RGB GL_BLEND_EQUATION +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_COORDS 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#endif + +#ifndef GL_ARB_multitexture +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 +#endif + +#ifndef GL_ARB_transpose_matrix +#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6 +#endif + +#ifndef GL_ARB_multisample +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +#endif + +#ifndef GL_ARB_texture_env_add +#endif + +#ifndef GL_ARB_texture_cube_map +#define GL_NORMAL_MAP_ARB 0x8511 +#define GL_REFLECTION_MAP_ARB 0x8512 +#define GL_TEXTURE_CUBE_MAP_ARB 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C +#endif + +#ifndef GL_ARB_texture_compression +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +#endif + +#ifndef GL_ARB_texture_border_clamp +#define GL_CLAMP_TO_BORDER_ARB 0x812D +#endif + +#ifndef GL_ARB_point_parameters +#define GL_POINT_SIZE_MIN_ARB 0x8126 +#define GL_POINT_SIZE_MAX_ARB 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 +#endif + +#ifndef GL_ARB_vertex_blend +#define GL_MAX_VERTEX_UNITS_ARB 0x86A4 +#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5 +#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6 +#define GL_VERTEX_BLEND_ARB 0x86A7 +#define GL_CURRENT_WEIGHT_ARB 0x86A8 +#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9 +#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA +#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB +#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC +#define GL_WEIGHT_ARRAY_ARB 0x86AD +#define GL_MODELVIEW0_ARB 0x1700 +#define GL_MODELVIEW1_ARB 0x850A +#define GL_MODELVIEW2_ARB 0x8722 +#define GL_MODELVIEW3_ARB 0x8723 +#define GL_MODELVIEW4_ARB 0x8724 +#define GL_MODELVIEW5_ARB 0x8725 +#define GL_MODELVIEW6_ARB 0x8726 +#define GL_MODELVIEW7_ARB 0x8727 +#define GL_MODELVIEW8_ARB 0x8728 +#define GL_MODELVIEW9_ARB 0x8729 +#define GL_MODELVIEW10_ARB 0x872A +#define GL_MODELVIEW11_ARB 0x872B +#define GL_MODELVIEW12_ARB 0x872C +#define GL_MODELVIEW13_ARB 0x872D +#define GL_MODELVIEW14_ARB 0x872E +#define GL_MODELVIEW15_ARB 0x872F +#define GL_MODELVIEW16_ARB 0x8730 +#define GL_MODELVIEW17_ARB 0x8731 +#define GL_MODELVIEW18_ARB 0x8732 +#define GL_MODELVIEW19_ARB 0x8733 +#define GL_MODELVIEW20_ARB 0x8734 +#define GL_MODELVIEW21_ARB 0x8735 +#define GL_MODELVIEW22_ARB 0x8736 +#define GL_MODELVIEW23_ARB 0x8737 +#define GL_MODELVIEW24_ARB 0x8738 +#define GL_MODELVIEW25_ARB 0x8739 +#define GL_MODELVIEW26_ARB 0x873A +#define GL_MODELVIEW27_ARB 0x873B +#define GL_MODELVIEW28_ARB 0x873C +#define GL_MODELVIEW29_ARB 0x873D +#define GL_MODELVIEW30_ARB 0x873E +#define GL_MODELVIEW31_ARB 0x873F +#endif + +#ifndef GL_ARB_matrix_palette +#define GL_MATRIX_PALETTE_ARB 0x8840 +#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841 +#define GL_MAX_PALETTE_MATRICES_ARB 0x8842 +#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843 +#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844 +#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845 +#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846 +#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847 +#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848 +#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849 +#endif + +#ifndef GL_ARB_texture_env_combine +#define GL_COMBINE_ARB 0x8570 +#define GL_COMBINE_RGB_ARB 0x8571 +#define GL_COMBINE_ALPHA_ARB 0x8572 +#define GL_SOURCE0_RGB_ARB 0x8580 +#define GL_SOURCE1_RGB_ARB 0x8581 +#define GL_SOURCE2_RGB_ARB 0x8582 +#define GL_SOURCE0_ALPHA_ARB 0x8588 +#define GL_SOURCE1_ALPHA_ARB 0x8589 +#define GL_SOURCE2_ALPHA_ARB 0x858A +#define GL_OPERAND0_RGB_ARB 0x8590 +#define GL_OPERAND1_RGB_ARB 0x8591 +#define GL_OPERAND2_RGB_ARB 0x8592 +#define GL_OPERAND0_ALPHA_ARB 0x8598 +#define GL_OPERAND1_ALPHA_ARB 0x8599 +#define GL_OPERAND2_ALPHA_ARB 0x859A +#define GL_RGB_SCALE_ARB 0x8573 +#define GL_ADD_SIGNED_ARB 0x8574 +#define GL_INTERPOLATE_ARB 0x8575 +#define GL_SUBTRACT_ARB 0x84E7 +#define GL_CONSTANT_ARB 0x8576 +#define GL_PRIMARY_COLOR_ARB 0x8577 +#define GL_PREVIOUS_ARB 0x8578 +#endif + +#ifndef GL_ARB_texture_env_crossbar +#endif + +#ifndef GL_ARB_texture_env_dot3 +#define GL_DOT3_RGB_ARB 0x86AE +#define GL_DOT3_RGBA_ARB 0x86AF +#endif + +#ifndef GL_ARB_texture_mirrored_repeat +#define GL_MIRRORED_REPEAT_ARB 0x8370 +#endif + +#ifndef GL_ARB_depth_texture +#define GL_DEPTH_COMPONENT16_ARB 0x81A5 +#define GL_DEPTH_COMPONENT24_ARB 0x81A6 +#define GL_DEPTH_COMPONENT32_ARB 0x81A7 +#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A +#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B +#endif + +#ifndef GL_ARB_shadow +#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C +#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D +#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E +#endif + +#ifndef GL_ARB_shadow_ambient +#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF +#endif + +#ifndef GL_ARB_window_pos +#endif + +#ifndef GL_ARB_vertex_program +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF +#endif + +#ifndef GL_ARB_fragment_program +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 +#endif + +#ifndef GL_ARB_vertex_buffer_object +#define GL_BUFFER_SIZE_ARB 0x8764 +#define GL_BUFFER_USAGE_ARB 0x8765 +#define GL_ARRAY_BUFFER_ARB 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 +#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F +#define GL_READ_ONLY_ARB 0x88B8 +#define GL_WRITE_ONLY_ARB 0x88B9 +#define GL_READ_WRITE_ARB 0x88BA +#define GL_BUFFER_ACCESS_ARB 0x88BB +#define GL_BUFFER_MAPPED_ARB 0x88BC +#define GL_BUFFER_MAP_POINTER_ARB 0x88BD +#define GL_STREAM_DRAW_ARB 0x88E0 +#define GL_STREAM_READ_ARB 0x88E1 +#define GL_STREAM_COPY_ARB 0x88E2 +#define GL_STATIC_DRAW_ARB 0x88E4 +#define GL_STATIC_READ_ARB 0x88E5 +#define GL_STATIC_COPY_ARB 0x88E6 +#define GL_DYNAMIC_DRAW_ARB 0x88E8 +#define GL_DYNAMIC_READ_ARB 0x88E9 +#define GL_DYNAMIC_COPY_ARB 0x88EA +#endif + +#ifndef GL_ARB_occlusion_query +#define GL_QUERY_COUNTER_BITS_ARB 0x8864 +#define GL_CURRENT_QUERY_ARB 0x8865 +#define GL_QUERY_RESULT_ARB 0x8866 +#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 +#define GL_SAMPLES_PASSED_ARB 0x8914 +#endif + +#ifndef GL_ARB_shader_objects +#define GL_PROGRAM_OBJECT_ARB 0x8B40 +#define GL_SHADER_OBJECT_ARB 0x8B48 +#define GL_OBJECT_TYPE_ARB 0x8B4E +#define GL_OBJECT_SUBTYPE_ARB 0x8B4F +#define GL_FLOAT_VEC2_ARB 0x8B50 +#define GL_FLOAT_VEC3_ARB 0x8B51 +#define GL_FLOAT_VEC4_ARB 0x8B52 +#define GL_INT_VEC2_ARB 0x8B53 +#define GL_INT_VEC3_ARB 0x8B54 +#define GL_INT_VEC4_ARB 0x8B55 +#define GL_BOOL_ARB 0x8B56 +#define GL_BOOL_VEC2_ARB 0x8B57 +#define GL_BOOL_VEC3_ARB 0x8B58 +#define GL_BOOL_VEC4_ARB 0x8B59 +#define GL_FLOAT_MAT2_ARB 0x8B5A +#define GL_FLOAT_MAT3_ARB 0x8B5B +#define GL_FLOAT_MAT4_ARB 0x8B5C +#define GL_SAMPLER_1D_ARB 0x8B5D +#define GL_SAMPLER_2D_ARB 0x8B5E +#define GL_SAMPLER_3D_ARB 0x8B5F +#define GL_SAMPLER_CUBE_ARB 0x8B60 +#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 +#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 +#define GL_SAMPLER_2D_RECT_ARB 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 +#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 +#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 +#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 +#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 +#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 +#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 +#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 +#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 +#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 +#endif + +#ifndef GL_ARB_vertex_shader +#define GL_VERTEX_SHADER_ARB 0x8B31 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A +#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D +#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 +#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A +#endif + +#ifndef GL_ARB_fragment_shader +#define GL_FRAGMENT_SHADER_ARB 0x8B30 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B +#endif + +#ifndef GL_ARB_shading_language_100 +#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C +#endif + +#ifndef GL_ARB_texture_non_power_of_two +#endif + +#ifndef GL_ARB_point_sprite +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif + +#ifndef GL_ARB_fragment_program_shadow +#endif + +#ifndef GL_ARB_draw_buffers +#define GL_MAX_DRAW_BUFFERS_ARB 0x8824 +#define GL_DRAW_BUFFER0_ARB 0x8825 +#define GL_DRAW_BUFFER1_ARB 0x8826 +#define GL_DRAW_BUFFER2_ARB 0x8827 +#define GL_DRAW_BUFFER3_ARB 0x8828 +#define GL_DRAW_BUFFER4_ARB 0x8829 +#define GL_DRAW_BUFFER5_ARB 0x882A +#define GL_DRAW_BUFFER6_ARB 0x882B +#define GL_DRAW_BUFFER7_ARB 0x882C +#define GL_DRAW_BUFFER8_ARB 0x882D +#define GL_DRAW_BUFFER9_ARB 0x882E +#define GL_DRAW_BUFFER10_ARB 0x882F +#define GL_DRAW_BUFFER11_ARB 0x8830 +#define GL_DRAW_BUFFER12_ARB 0x8831 +#define GL_DRAW_BUFFER13_ARB 0x8832 +#define GL_DRAW_BUFFER14_ARB 0x8833 +#define GL_DRAW_BUFFER15_ARB 0x8834 +#endif + +#ifndef GL_ARB_texture_rectangle +#define GL_TEXTURE_RECTANGLE_ARB 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 +#endif + +#ifndef GL_ARB_color_buffer_float +#define GL_RGBA_FLOAT_MODE_ARB 0x8820 +#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A +#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B +#define GL_CLAMP_READ_COLOR_ARB 0x891C +#define GL_FIXED_ONLY_ARB 0x891D +#endif + +#ifndef GL_ARB_half_float_pixel +#define GL_HALF_FLOAT_ARB 0x140B +#endif + +#ifndef GL_ARB_texture_float +#define GL_TEXTURE_RED_TYPE_ARB 0x8C10 +#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 +#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 +#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 +#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 +#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 +#define GL_RGBA32F_ARB 0x8814 +#define GL_RGB32F_ARB 0x8815 +#define GL_ALPHA32F_ARB 0x8816 +#define GL_INTENSITY32F_ARB 0x8817 +#define GL_LUMINANCE32F_ARB 0x8818 +#define GL_LUMINANCE_ALPHA32F_ARB 0x8819 +#define GL_RGBA16F_ARB 0x881A +#define GL_RGB16F_ARB 0x881B +#define GL_ALPHA16F_ARB 0x881C +#define GL_INTENSITY16F_ARB 0x881D +#define GL_LUMINANCE16F_ARB 0x881E +#define GL_LUMINANCE_ALPHA16F_ARB 0x881F +#endif + +#ifndef GL_ARB_pixel_buffer_object +#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF +#endif + +#ifndef GL_EXT_abgr +#define GL_ABGR_EXT 0x8000 +#endif + +#ifndef GL_EXT_blend_color +#define GL_CONSTANT_COLOR_EXT 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002 +#define GL_CONSTANT_ALPHA_EXT 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004 +#define GL_BLEND_COLOR_EXT 0x8005 +#endif + +#ifndef GL_EXT_polygon_offset +#define GL_POLYGON_OFFSET_EXT 0x8037 +#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038 +#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039 +#endif + +#ifndef GL_EXT_texture +#define GL_ALPHA4_EXT 0x803B +#define GL_ALPHA8_EXT 0x803C +#define GL_ALPHA12_EXT 0x803D +#define GL_ALPHA16_EXT 0x803E +#define GL_LUMINANCE4_EXT 0x803F +#define GL_LUMINANCE8_EXT 0x8040 +#define GL_LUMINANCE12_EXT 0x8041 +#define GL_LUMINANCE16_EXT 0x8042 +#define GL_LUMINANCE4_ALPHA4_EXT 0x8043 +#define GL_LUMINANCE6_ALPHA2_EXT 0x8044 +#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 +#define GL_LUMINANCE12_ALPHA4_EXT 0x8046 +#define GL_LUMINANCE12_ALPHA12_EXT 0x8047 +#define GL_LUMINANCE16_ALPHA16_EXT 0x8048 +#define GL_INTENSITY_EXT 0x8049 +#define GL_INTENSITY4_EXT 0x804A +#define GL_INTENSITY8_EXT 0x804B +#define GL_INTENSITY12_EXT 0x804C +#define GL_INTENSITY16_EXT 0x804D +#define GL_RGB2_EXT 0x804E +#define GL_RGB4_EXT 0x804F +#define GL_RGB5_EXT 0x8050 +#define GL_RGB8_EXT 0x8051 +#define GL_RGB10_EXT 0x8052 +#define GL_RGB12_EXT 0x8053 +#define GL_RGB16_EXT 0x8054 +#define GL_RGBA2_EXT 0x8055 +#define GL_RGBA4_EXT 0x8056 +#define GL_RGB5_A1_EXT 0x8057 +#define GL_RGBA8_EXT 0x8058 +#define GL_RGB10_A2_EXT 0x8059 +#define GL_RGBA12_EXT 0x805A +#define GL_RGBA16_EXT 0x805B +#define GL_TEXTURE_RED_SIZE_EXT 0x805C +#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D +#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E +#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061 +#define GL_REPLACE_EXT 0x8062 +#define GL_PROXY_TEXTURE_1D_EXT 0x8063 +#define GL_PROXY_TEXTURE_2D_EXT 0x8064 +#define GL_TEXTURE_TOO_LARGE_EXT 0x8065 +#endif + +#ifndef GL_EXT_texture3D +#define GL_PACK_SKIP_IMAGES_EXT 0x806B +#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C +#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D +#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E +#define GL_TEXTURE_3D_EXT 0x806F +#define GL_PROXY_TEXTURE_3D_EXT 0x8070 +#define GL_TEXTURE_DEPTH_EXT 0x8071 +#define GL_TEXTURE_WRAP_R_EXT 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073 +#endif + +#ifndef GL_SGIS_texture_filter4 +#define GL_FILTER4_SGIS 0x8146 +#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147 +#endif + +#ifndef GL_EXT_subtexture +#endif + +#ifndef GL_EXT_copy_texture +#endif + +#ifndef GL_EXT_histogram +#define GL_HISTOGRAM_EXT 0x8024 +#define GL_PROXY_HISTOGRAM_EXT 0x8025 +#define GL_HISTOGRAM_WIDTH_EXT 0x8026 +#define GL_HISTOGRAM_FORMAT_EXT 0x8027 +#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C +#define GL_HISTOGRAM_SINK_EXT 0x802D +#define GL_MINMAX_EXT 0x802E +#define GL_MINMAX_FORMAT_EXT 0x802F +#define GL_MINMAX_SINK_EXT 0x8030 +#define GL_TABLE_TOO_LARGE_EXT 0x8031 +#endif + +#ifndef GL_EXT_convolution +#define GL_CONVOLUTION_1D_EXT 0x8010 +#define GL_CONVOLUTION_2D_EXT 0x8011 +#define GL_SEPARABLE_2D_EXT 0x8012 +#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015 +#define GL_REDUCE_EXT 0x8016 +#define GL_CONVOLUTION_FORMAT_EXT 0x8017 +#define GL_CONVOLUTION_WIDTH_EXT 0x8018 +#define GL_CONVOLUTION_HEIGHT_EXT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023 +#endif + +#ifndef GL_SGI_color_matrix +#define GL_COLOR_MATRIX_SGI 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB +#endif + +#ifndef GL_SGI_color_table +#define GL_COLOR_TABLE_SGI 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2 +#define GL_PROXY_COLOR_TABLE_SGI 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5 +#define GL_COLOR_TABLE_SCALE_SGI 0x80D6 +#define GL_COLOR_TABLE_BIAS_SGI 0x80D7 +#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8 +#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF +#endif + +#ifndef GL_SGIS_pixel_texture +#define GL_PIXEL_TEXTURE_SGIS 0x8353 +#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354 +#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355 +#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356 +#endif + +#ifndef GL_SGIX_pixel_texture +#define GL_PIXEL_TEX_GEN_SGIX 0x8139 +#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B +#endif + +#ifndef GL_SGIS_texture4D +#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130 +#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131 +#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132 +#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133 +#define GL_TEXTURE_4D_SGIS 0x8134 +#define GL_PROXY_TEXTURE_4D_SGIS 0x8135 +#define GL_TEXTURE_4DSIZE_SGIS 0x8136 +#define GL_TEXTURE_WRAP_Q_SGIS 0x8137 +#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138 +#define GL_TEXTURE_4D_BINDING_SGIS 0x814F +#endif + +#ifndef GL_SGI_texture_color_table +#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC +#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD +#endif + +#ifndef GL_EXT_cmyka +#define GL_CMYK_EXT 0x800C +#define GL_CMYKA_EXT 0x800D +#define GL_PACK_CMYK_HINT_EXT 0x800E +#define GL_UNPACK_CMYK_HINT_EXT 0x800F +#endif + +#ifndef GL_EXT_texture_object +#define GL_TEXTURE_PRIORITY_EXT 0x8066 +#define GL_TEXTURE_RESIDENT_EXT 0x8067 +#define GL_TEXTURE_1D_BINDING_EXT 0x8068 +#define GL_TEXTURE_2D_BINDING_EXT 0x8069 +#define GL_TEXTURE_3D_BINDING_EXT 0x806A +#endif + +#ifndef GL_SGIS_detail_texture +#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095 +#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096 +#define GL_LINEAR_DETAIL_SGIS 0x8097 +#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098 +#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099 +#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A +#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B +#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C +#endif + +#ifndef GL_SGIS_sharpen_texture +#define GL_LINEAR_SHARPEN_SGIS 0x80AD +#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE +#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF +#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0 +#endif + +#ifndef GL_EXT_packed_pixels +#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036 +#endif + +#ifndef GL_SGIS_texture_lod +#define GL_TEXTURE_MIN_LOD_SGIS 0x813A +#define GL_TEXTURE_MAX_LOD_SGIS 0x813B +#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C +#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D +#endif + +#ifndef GL_SGIS_multisample +#define GL_MULTISAMPLE_SGIS 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F +#define GL_SAMPLE_MASK_SGIS 0x80A0 +#define GL_1PASS_SGIS 0x80A1 +#define GL_2PASS_0_SGIS 0x80A2 +#define GL_2PASS_1_SGIS 0x80A3 +#define GL_4PASS_0_SGIS 0x80A4 +#define GL_4PASS_1_SGIS 0x80A5 +#define GL_4PASS_2_SGIS 0x80A6 +#define GL_4PASS_3_SGIS 0x80A7 +#define GL_SAMPLE_BUFFERS_SGIS 0x80A8 +#define GL_SAMPLES_SGIS 0x80A9 +#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA +#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB +#define GL_SAMPLE_PATTERN_SGIS 0x80AC +#endif + +#ifndef GL_EXT_rescale_normal +#define GL_RESCALE_NORMAL_EXT 0x803A +#endif + +#ifndef GL_EXT_vertex_array +#define GL_VERTEX_ARRAY_EXT 0x8074 +#define GL_NORMAL_ARRAY_EXT 0x8075 +#define GL_COLOR_ARRAY_EXT 0x8076 +#define GL_INDEX_ARRAY_EXT 0x8077 +#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 +#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 +#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A +#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B +#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C +#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D +#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E +#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F +#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 +#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 +#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 +#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 +#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 +#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 +#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 +#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 +#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A +#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B +#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C +#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D +#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E +#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F +#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 +#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 +#endif + +#ifndef GL_EXT_misc_attribute +#endif + +#ifndef GL_SGIS_generate_mipmap +#define GL_GENERATE_MIPMAP_SGIS 0x8191 +#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 +#endif + +#ifndef GL_SGIX_clipmap +#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170 +#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171 +#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172 +#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173 +#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174 +#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175 +#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176 +#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177 +#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178 +#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D +#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E +#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F +#endif + +#ifndef GL_SGIX_shadow +#define GL_TEXTURE_COMPARE_SGIX 0x819A +#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B +#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C +#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D +#endif + +#ifndef GL_SGIS_texture_edge_clamp +#define GL_CLAMP_TO_EDGE_SGIS 0x812F +#endif + +#ifndef GL_SGIS_texture_border_clamp +#define GL_CLAMP_TO_BORDER_SGIS 0x812D +#endif + +#ifndef GL_EXT_blend_minmax +#define GL_FUNC_ADD_EXT 0x8006 +#define GL_MIN_EXT 0x8007 +#define GL_MAX_EXT 0x8008 +#define GL_BLEND_EQUATION_EXT 0x8009 +#endif + +#ifndef GL_EXT_blend_subtract +#define GL_FUNC_SUBTRACT_EXT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B +#endif + +#ifndef GL_EXT_blend_logic_op +#endif + +#ifndef GL_SGIX_interlace +#define GL_INTERLACE_SGIX 0x8094 +#endif + +#ifndef GL_SGIX_pixel_tiles +#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E +#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F +#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140 +#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141 +#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142 +#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143 +#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144 +#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145 +#endif + +#ifndef GL_SGIS_texture_select +#define GL_DUAL_ALPHA4_SGIS 0x8110 +#define GL_DUAL_ALPHA8_SGIS 0x8111 +#define GL_DUAL_ALPHA12_SGIS 0x8112 +#define GL_DUAL_ALPHA16_SGIS 0x8113 +#define GL_DUAL_LUMINANCE4_SGIS 0x8114 +#define GL_DUAL_LUMINANCE8_SGIS 0x8115 +#define GL_DUAL_LUMINANCE12_SGIS 0x8116 +#define GL_DUAL_LUMINANCE16_SGIS 0x8117 +#define GL_DUAL_INTENSITY4_SGIS 0x8118 +#define GL_DUAL_INTENSITY8_SGIS 0x8119 +#define GL_DUAL_INTENSITY12_SGIS 0x811A +#define GL_DUAL_INTENSITY16_SGIS 0x811B +#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C +#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D +#define GL_QUAD_ALPHA4_SGIS 0x811E +#define GL_QUAD_ALPHA8_SGIS 0x811F +#define GL_QUAD_LUMINANCE4_SGIS 0x8120 +#define GL_QUAD_LUMINANCE8_SGIS 0x8121 +#define GL_QUAD_INTENSITY4_SGIS 0x8122 +#define GL_QUAD_INTENSITY8_SGIS 0x8123 +#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124 +#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125 +#endif + +#ifndef GL_SGIX_sprite +#define GL_SPRITE_SGIX 0x8148 +#define GL_SPRITE_MODE_SGIX 0x8149 +#define GL_SPRITE_AXIS_SGIX 0x814A +#define GL_SPRITE_TRANSLATION_SGIX 0x814B +#define GL_SPRITE_AXIAL_SGIX 0x814C +#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D +#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E +#endif + +#ifndef GL_SGIX_texture_multi_buffer +#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E +#endif + +#ifndef GL_EXT_point_parameters +#define GL_POINT_SIZE_MIN_EXT 0x8126 +#define GL_POINT_SIZE_MAX_EXT 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 +#define GL_DISTANCE_ATTENUATION_EXT 0x8129 +#endif + +#ifndef GL_SGIS_point_parameters +#define GL_POINT_SIZE_MIN_SGIS 0x8126 +#define GL_POINT_SIZE_MAX_SGIS 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128 +#define GL_DISTANCE_ATTENUATION_SGIS 0x8129 +#endif + +#ifndef GL_SGIX_instruments +#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180 +#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181 +#endif + +#ifndef GL_SGIX_texture_scale_bias +#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179 +#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A +#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B +#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C +#endif + +#ifndef GL_SGIX_framezoom +#define GL_FRAMEZOOM_SGIX 0x818B +#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C +#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D +#endif + +#ifndef GL_SGIX_tag_sample_buffer +#endif + +#ifndef GL_FfdMaskSGIX +#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001 +#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002 +#endif + +#ifndef GL_SGIX_polynomial_ffd +#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194 +#define GL_TEXTURE_DEFORMATION_SGIX 0x8195 +#define GL_DEFORMATIONS_MASK_SGIX 0x8196 +#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197 +#endif + +#ifndef GL_SGIX_reference_plane +#define GL_REFERENCE_PLANE_SGIX 0x817D +#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E +#endif + +#ifndef GL_SGIX_flush_raster +#endif + +#ifndef GL_SGIX_depth_texture +#define GL_DEPTH_COMPONENT16_SGIX 0x81A5 +#define GL_DEPTH_COMPONENT24_SGIX 0x81A6 +#define GL_DEPTH_COMPONENT32_SGIX 0x81A7 +#endif + +#ifndef GL_SGIS_fog_function +#define GL_FOG_FUNC_SGIS 0x812A +#define GL_FOG_FUNC_POINTS_SGIS 0x812B +#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C +#endif + +#ifndef GL_SGIX_fog_offset +#define GL_FOG_OFFSET_SGIX 0x8198 +#define GL_FOG_OFFSET_VALUE_SGIX 0x8199 +#endif + +#ifndef GL_HP_image_transform +#define GL_IMAGE_SCALE_X_HP 0x8155 +#define GL_IMAGE_SCALE_Y_HP 0x8156 +#define GL_IMAGE_TRANSLATE_X_HP 0x8157 +#define GL_IMAGE_TRANSLATE_Y_HP 0x8158 +#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159 +#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A +#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B +#define GL_IMAGE_MAG_FILTER_HP 0x815C +#define GL_IMAGE_MIN_FILTER_HP 0x815D +#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E +#define GL_CUBIC_HP 0x815F +#define GL_AVERAGE_HP 0x8160 +#define GL_IMAGE_TRANSFORM_2D_HP 0x8161 +#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162 +#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163 +#endif + +#ifndef GL_HP_convolution_border_modes +#define GL_IGNORE_BORDER_HP 0x8150 +#define GL_CONSTANT_BORDER_HP 0x8151 +#define GL_REPLICATE_BORDER_HP 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154 +#endif + +#ifndef GL_INGR_palette_buffer +#endif + +#ifndef GL_SGIX_texture_add_env +#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE +#endif + +#ifndef GL_EXT_color_subtable +#endif + +#ifndef GL_PGI_vertex_hints +#define GL_VERTEX_DATA_HINT_PGI 0x1A22A +#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B +#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C +#define GL_MAX_VERTEX_HINT_PGI 0x1A22D +#define GL_COLOR3_BIT_PGI 0x00010000 +#define GL_COLOR4_BIT_PGI 0x00020000 +#define GL_EDGEFLAG_BIT_PGI 0x00040000 +#define GL_INDEX_BIT_PGI 0x00080000 +#define GL_MAT_AMBIENT_BIT_PGI 0x00100000 +#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000 +#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000 +#define GL_MAT_EMISSION_BIT_PGI 0x00800000 +#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000 +#define GL_MAT_SHININESS_BIT_PGI 0x02000000 +#define GL_MAT_SPECULAR_BIT_PGI 0x04000000 +#define GL_NORMAL_BIT_PGI 0x08000000 +#define GL_TEXCOORD1_BIT_PGI 0x10000000 +#define GL_TEXCOORD2_BIT_PGI 0x20000000 +#define GL_TEXCOORD3_BIT_PGI 0x40000000 +#define GL_TEXCOORD4_BIT_PGI 0x80000000 +#define GL_VERTEX23_BIT_PGI 0x00000004 +#define GL_VERTEX4_BIT_PGI 0x00000008 +#endif + +#ifndef GL_PGI_misc_hints +#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8 +#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD +#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE +#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202 +#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203 +#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204 +#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C +#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D +#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E +#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F +#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210 +#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211 +#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216 +#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217 +#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218 +#define GL_FULL_STIPPLE_HINT_PGI 0x1A219 +#define GL_CLIP_NEAR_HINT_PGI 0x1A220 +#define GL_CLIP_FAR_HINT_PGI 0x1A221 +#define GL_WIDE_LINE_HINT_PGI 0x1A222 +#define GL_BACK_NORMALS_HINT_PGI 0x1A223 +#endif + +#ifndef GL_EXT_paletted_texture +#define GL_COLOR_INDEX1_EXT 0x80E2 +#define GL_COLOR_INDEX2_EXT 0x80E3 +#define GL_COLOR_INDEX4_EXT 0x80E4 +#define GL_COLOR_INDEX8_EXT 0x80E5 +#define GL_COLOR_INDEX12_EXT 0x80E6 +#define GL_COLOR_INDEX16_EXT 0x80E7 +#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED +#endif + +#ifndef GL_EXT_clip_volume_hint +#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0 +#endif + +#ifndef GL_SGIX_list_priority +#define GL_LIST_PRIORITY_SGIX 0x8182 +#endif + +#ifndef GL_SGIX_ir_instrument1 +#define GL_IR_INSTRUMENT1_SGIX 0x817F +#endif + +#ifndef GL_SGIX_calligraphic_fragment +#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183 +#endif + +#ifndef GL_SGIX_texture_lod_bias +#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E +#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F +#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190 +#endif + +#ifndef GL_SGIX_shadow_ambient +#define GL_SHADOW_AMBIENT_SGIX 0x80BF +#endif + +#ifndef GL_EXT_index_texture +#endif + +#ifndef GL_EXT_index_material +#define GL_INDEX_MATERIAL_EXT 0x81B8 +#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9 +#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA +#endif + +#ifndef GL_EXT_index_func +#define GL_INDEX_TEST_EXT 0x81B5 +#define GL_INDEX_TEST_FUNC_EXT 0x81B6 +#define GL_INDEX_TEST_REF_EXT 0x81B7 +#endif + +#ifndef GL_EXT_index_array_formats +#define GL_IUI_V2F_EXT 0x81AD +#define GL_IUI_V3F_EXT 0x81AE +#define GL_IUI_N3F_V2F_EXT 0x81AF +#define GL_IUI_N3F_V3F_EXT 0x81B0 +#define GL_T2F_IUI_V2F_EXT 0x81B1 +#define GL_T2F_IUI_V3F_EXT 0x81B2 +#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3 +#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4 +#endif + +#ifndef GL_EXT_compiled_vertex_array +#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8 +#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9 +#endif + +#ifndef GL_EXT_cull_vertex +#define GL_CULL_VERTEX_EXT 0x81AA +#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB +#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC +#endif + +#ifndef GL_SGIX_ycrcb +#define GL_YCRCB_422_SGIX 0x81BB +#define GL_YCRCB_444_SGIX 0x81BC +#endif + +#ifndef GL_SGIX_fragment_lighting +#define GL_FRAGMENT_LIGHTING_SGIX 0x8400 +#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401 +#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402 +#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403 +#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404 +#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405 +#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406 +#define GL_LIGHT_ENV_MODE_SGIX 0x8407 +#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408 +#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409 +#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A +#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B +#define GL_FRAGMENT_LIGHT0_SGIX 0x840C +#define GL_FRAGMENT_LIGHT1_SGIX 0x840D +#define GL_FRAGMENT_LIGHT2_SGIX 0x840E +#define GL_FRAGMENT_LIGHT3_SGIX 0x840F +#define GL_FRAGMENT_LIGHT4_SGIX 0x8410 +#define GL_FRAGMENT_LIGHT5_SGIX 0x8411 +#define GL_FRAGMENT_LIGHT6_SGIX 0x8412 +#define GL_FRAGMENT_LIGHT7_SGIX 0x8413 +#endif + +#ifndef GL_IBM_rasterpos_clip +#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262 +#endif + +#ifndef GL_HP_texture_lighting +#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167 +#define GL_TEXTURE_POST_SPECULAR_HP 0x8168 +#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169 +#endif + +#ifndef GL_EXT_draw_range_elements +#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8 +#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9 +#endif + +#ifndef GL_WIN_phong_shading +#define GL_PHONG_WIN 0x80EA +#define GL_PHONG_HINT_WIN 0x80EB +#endif + +#ifndef GL_WIN_specular_fog +#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC +#endif + +#ifndef GL_EXT_light_texture +#define GL_FRAGMENT_MATERIAL_EXT 0x8349 +#define GL_FRAGMENT_NORMAL_EXT 0x834A +#define GL_FRAGMENT_COLOR_EXT 0x834C +#define GL_ATTENUATION_EXT 0x834D +#define GL_SHADOW_ATTENUATION_EXT 0x834E +#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F +#define GL_TEXTURE_LIGHT_EXT 0x8350 +#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351 +#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352 +/* reuse GL_FRAGMENT_DEPTH_EXT */ +#endif + +#ifndef GL_SGIX_blend_alpha_minmax +#define GL_ALPHA_MIN_SGIX 0x8320 +#define GL_ALPHA_MAX_SGIX 0x8321 +#endif + +#ifndef GL_SGIX_impact_pixel_texture +#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX 0x8184 +#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX 0x8185 +#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX 0x8186 +#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187 +#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188 +#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX 0x8189 +#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX 0x818A +#endif + +#ifndef GL_EXT_bgra +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 +#endif + +#ifndef GL_SGIX_async +#define GL_ASYNC_MARKER_SGIX 0x8329 +#endif + +#ifndef GL_SGIX_async_pixel +#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C +#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D +#define GL_ASYNC_READ_PIXELS_SGIX 0x835E +#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F +#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360 +#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361 +#endif + +#ifndef GL_SGIX_async_histogram +#define GL_ASYNC_HISTOGRAM_SGIX 0x832C +#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D +#endif + +#ifndef GL_INTEL_texture_scissor +#endif + +#ifndef GL_INTEL_parallel_arrays +#define GL_PARALLEL_ARRAYS_INTEL 0x83F4 +#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5 +#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6 +#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7 +#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8 +#endif + +#ifndef GL_HP_occlusion_test +#define GL_OCCLUSION_TEST_HP 0x8165 +#define GL_OCCLUSION_TEST_RESULT_HP 0x8166 +#endif + +#ifndef GL_EXT_pixel_transform +#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330 +#define GL_PIXEL_MAG_FILTER_EXT 0x8331 +#define GL_PIXEL_MIN_FILTER_EXT 0x8332 +#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333 +#define GL_CUBIC_EXT 0x8334 +#define GL_AVERAGE_EXT 0x8335 +#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336 +#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337 +#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338 +#endif + +#ifndef GL_EXT_pixel_transform_color_table +#endif + +#ifndef GL_EXT_shared_texture_palette +#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB +#endif + +#ifndef GL_EXT_separate_specular_color +#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8 +#define GL_SINGLE_COLOR_EXT 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA +#endif + +#ifndef GL_EXT_secondary_color +#define GL_COLOR_SUM_EXT 0x8458 +#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D +#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E +#endif + +#ifndef GL_EXT_texture_perturb_normal +#define GL_PERTURB_EXT 0x85AE +#define GL_TEXTURE_NORMAL_EXT 0x85AF +#endif + +#ifndef GL_EXT_multi_draw_arrays +#endif + +#ifndef GL_EXT_fog_coord +#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 +#define GL_FOG_COORDINATE_EXT 0x8451 +#define GL_FRAGMENT_DEPTH_EXT 0x8452 +#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456 +#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 +#endif + +#ifndef GL_REND_screen_coordinates +#define GL_SCREEN_COORDINATES_REND 0x8490 +#define GL_INVERTED_SCREEN_W_REND 0x8491 +#endif + +#ifndef GL_EXT_coordinate_frame +#define GL_TANGENT_ARRAY_EXT 0x8439 +#define GL_BINORMAL_ARRAY_EXT 0x843A +#define GL_CURRENT_TANGENT_EXT 0x843B +#define GL_CURRENT_BINORMAL_EXT 0x843C +#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E +#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F +#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440 +#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441 +#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442 +#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443 +#define GL_MAP1_TANGENT_EXT 0x8444 +#define GL_MAP2_TANGENT_EXT 0x8445 +#define GL_MAP1_BINORMAL_EXT 0x8446 +#define GL_MAP2_BINORMAL_EXT 0x8447 +#endif + +#ifndef GL_EXT_texture_env_combine +#define GL_COMBINE_EXT 0x8570 +#define GL_COMBINE_RGB_EXT 0x8571 +#define GL_COMBINE_ALPHA_EXT 0x8572 +#define GL_RGB_SCALE_EXT 0x8573 +#define GL_ADD_SIGNED_EXT 0x8574 +#define GL_INTERPOLATE_EXT 0x8575 +#define GL_CONSTANT_EXT 0x8576 +#define GL_PRIMARY_COLOR_EXT 0x8577 +#define GL_PREVIOUS_EXT 0x8578 +#define GL_SOURCE0_RGB_EXT 0x8580 +#define GL_SOURCE1_RGB_EXT 0x8581 +#define GL_SOURCE2_RGB_EXT 0x8582 +#define GL_SOURCE0_ALPHA_EXT 0x8588 +#define GL_SOURCE1_ALPHA_EXT 0x8589 +#define GL_SOURCE2_ALPHA_EXT 0x858A +#define GL_OPERAND0_RGB_EXT 0x8590 +#define GL_OPERAND1_RGB_EXT 0x8591 +#define GL_OPERAND2_RGB_EXT 0x8592 +#define GL_OPERAND0_ALPHA_EXT 0x8598 +#define GL_OPERAND1_ALPHA_EXT 0x8599 +#define GL_OPERAND2_ALPHA_EXT 0x859A +#endif + +#ifndef GL_APPLE_specular_vector +#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0 +#endif + +#ifndef GL_APPLE_transform_hint +#define GL_TRANSFORM_HINT_APPLE 0x85B1 +#endif + +#ifndef GL_SGIX_fog_scale +#define GL_FOG_SCALE_SGIX 0x81FC +#define GL_FOG_SCALE_VALUE_SGIX 0x81FD +#endif + +#ifndef GL_SUNX_constant_data +#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5 +#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6 +#endif + +#ifndef GL_SUN_global_alpha +#define GL_GLOBAL_ALPHA_SUN 0x81D9 +#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA +#endif + +#ifndef GL_SUN_triangle_list +#define GL_RESTART_SUN 0x0001 +#define GL_REPLACE_MIDDLE_SUN 0x0002 +#define GL_REPLACE_OLDEST_SUN 0x0003 +#define GL_TRIANGLE_LIST_SUN 0x81D7 +#define GL_REPLACEMENT_CODE_SUN 0x81D8 +#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0 +#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1 +#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2 +#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3 +#define GL_R1UI_V3F_SUN 0x85C4 +#define GL_R1UI_C4UB_V3F_SUN 0x85C5 +#define GL_R1UI_C3F_V3F_SUN 0x85C6 +#define GL_R1UI_N3F_V3F_SUN 0x85C7 +#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8 +#define GL_R1UI_T2F_V3F_SUN 0x85C9 +#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA +#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB +#endif + +#ifndef GL_SUN_vertex +#endif + +#ifndef GL_EXT_blend_func_separate +#define GL_BLEND_DST_RGB_EXT 0x80C8 +#define GL_BLEND_SRC_RGB_EXT 0x80C9 +#define GL_BLEND_DST_ALPHA_EXT 0x80CA +#define GL_BLEND_SRC_ALPHA_EXT 0x80CB +#endif + +#ifndef GL_INGR_color_clamp +#define GL_RED_MIN_CLAMP_INGR 0x8560 +#define GL_GREEN_MIN_CLAMP_INGR 0x8561 +#define GL_BLUE_MIN_CLAMP_INGR 0x8562 +#define GL_ALPHA_MIN_CLAMP_INGR 0x8563 +#define GL_RED_MAX_CLAMP_INGR 0x8564 +#define GL_GREEN_MAX_CLAMP_INGR 0x8565 +#define GL_BLUE_MAX_CLAMP_INGR 0x8566 +#define GL_ALPHA_MAX_CLAMP_INGR 0x8567 +#endif + +#ifndef GL_INGR_interlace_read +#define GL_INTERLACE_READ_INGR 0x8568 +#endif + +#ifndef GL_EXT_stencil_wrap +#define GL_INCR_WRAP_EXT 0x8507 +#define GL_DECR_WRAP_EXT 0x8508 +#endif + +#ifndef GL_EXT_422_pixels +#define GL_422_EXT 0x80CC +#define GL_422_REV_EXT 0x80CD +#define GL_422_AVERAGE_EXT 0x80CE +#define GL_422_REV_AVERAGE_EXT 0x80CF +#endif + +#ifndef GL_NV_texgen_reflection +#define GL_NORMAL_MAP_NV 0x8511 +#define GL_REFLECTION_MAP_NV 0x8512 +#endif + +#ifndef GL_EXT_texture_cube_map +#define GL_NORMAL_MAP_EXT 0x8511 +#define GL_REFLECTION_MAP_EXT 0x8512 +#define GL_TEXTURE_CUBE_MAP_EXT 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C +#endif + +#ifndef GL_SUN_convolution_border_modes +#define GL_WRAP_BORDER_SUN 0x81D4 +#endif + +#ifndef GL_EXT_texture_env_add +#endif + +#ifndef GL_EXT_texture_lod_bias +#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD +#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 +#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 +#endif + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif + +#ifndef GL_EXT_vertex_weighting +#define GL_MODELVIEW0_STACK_DEPTH_EXT GL_MODELVIEW_STACK_DEPTH +#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502 +#define GL_MODELVIEW0_MATRIX_EXT GL_MODELVIEW_MATRIX +#define GL_MODELVIEW1_MATRIX_EXT 0x8506 +#define GL_VERTEX_WEIGHTING_EXT 0x8509 +#define GL_MODELVIEW0_EXT GL_MODELVIEW +#define GL_MODELVIEW1_EXT 0x850A +#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B +#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C +#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D +#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E +#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F +#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510 +#endif + +#ifndef GL_NV_light_max_exponent +#define GL_MAX_SHININESS_NV 0x8504 +#define GL_MAX_SPOT_EXPONENT_NV 0x8505 +#endif + +#ifndef GL_NV_vertex_array_range +#define GL_VERTEX_ARRAY_RANGE_NV 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E +#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F +#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 +#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 +#endif + +#ifndef GL_NV_register_combiners +#define GL_REGISTER_COMBINERS_NV 0x8522 +#define GL_VARIABLE_A_NV 0x8523 +#define GL_VARIABLE_B_NV 0x8524 +#define GL_VARIABLE_C_NV 0x8525 +#define GL_VARIABLE_D_NV 0x8526 +#define GL_VARIABLE_E_NV 0x8527 +#define GL_VARIABLE_F_NV 0x8528 +#define GL_VARIABLE_G_NV 0x8529 +#define GL_CONSTANT_COLOR0_NV 0x852A +#define GL_CONSTANT_COLOR1_NV 0x852B +#define GL_PRIMARY_COLOR_NV 0x852C +#define GL_SECONDARY_COLOR_NV 0x852D +#define GL_SPARE0_NV 0x852E +#define GL_SPARE1_NV 0x852F +#define GL_DISCARD_NV 0x8530 +#define GL_E_TIMES_F_NV 0x8531 +#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 +#define GL_UNSIGNED_IDENTITY_NV 0x8536 +#define GL_UNSIGNED_INVERT_NV 0x8537 +#define GL_EXPAND_NORMAL_NV 0x8538 +#define GL_EXPAND_NEGATE_NV 0x8539 +#define GL_HALF_BIAS_NORMAL_NV 0x853A +#define GL_HALF_BIAS_NEGATE_NV 0x853B +#define GL_SIGNED_IDENTITY_NV 0x853C +#define GL_SIGNED_NEGATE_NV 0x853D +#define GL_SCALE_BY_TWO_NV 0x853E +#define GL_SCALE_BY_FOUR_NV 0x853F +#define GL_SCALE_BY_ONE_HALF_NV 0x8540 +#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 +#define GL_COMBINER_INPUT_NV 0x8542 +#define GL_COMBINER_MAPPING_NV 0x8543 +#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 +#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 +#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 +#define GL_COMBINER_MUX_SUM_NV 0x8547 +#define GL_COMBINER_SCALE_NV 0x8548 +#define GL_COMBINER_BIAS_NV 0x8549 +#define GL_COMBINER_AB_OUTPUT_NV 0x854A +#define GL_COMBINER_CD_OUTPUT_NV 0x854B +#define GL_COMBINER_SUM_OUTPUT_NV 0x854C +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D +#define GL_NUM_GENERAL_COMBINERS_NV 0x854E +#define GL_COLOR_SUM_CLAMP_NV 0x854F +#define GL_COMBINER0_NV 0x8550 +#define GL_COMBINER1_NV 0x8551 +#define GL_COMBINER2_NV 0x8552 +#define GL_COMBINER3_NV 0x8553 +#define GL_COMBINER4_NV 0x8554 +#define GL_COMBINER5_NV 0x8555 +#define GL_COMBINER6_NV 0x8556 +#define GL_COMBINER7_NV 0x8557 +/* reuse GL_TEXTURE0_ARB */ +/* reuse GL_TEXTURE1_ARB */ +/* reuse GL_ZERO */ +/* reuse GL_NONE */ +/* reuse GL_FOG */ +#endif + +#ifndef GL_NV_fog_distance +#define GL_FOG_DISTANCE_MODE_NV 0x855A +#define GL_EYE_RADIAL_NV 0x855B +#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C +/* reuse GL_EYE_PLANE */ +#endif + +#ifndef GL_NV_texgen_emboss +#define GL_EMBOSS_LIGHT_NV 0x855D +#define GL_EMBOSS_CONSTANT_NV 0x855E +#define GL_EMBOSS_MAP_NV 0x855F +#endif + +#ifndef GL_NV_blend_square +#endif + +#ifndef GL_NV_texture_env_combine4 +#define GL_COMBINE4_NV 0x8503 +#define GL_SOURCE3_RGB_NV 0x8583 +#define GL_SOURCE3_ALPHA_NV 0x858B +#define GL_OPERAND3_RGB_NV 0x8593 +#define GL_OPERAND3_ALPHA_NV 0x859B +#endif + +#ifndef GL_MESA_resize_buffers +#endif + +#ifndef GL_MESA_window_pos +#endif + +#ifndef GL_EXT_texture_compression_s3tc +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif + +#ifndef GL_IBM_cull_vertex +#define GL_CULL_VERTEX_IBM 103050 +#endif + +#ifndef GL_IBM_multimode_draw_arrays +#endif + +#ifndef GL_IBM_vertex_array_lists +#define GL_VERTEX_ARRAY_LIST_IBM 103070 +#define GL_NORMAL_ARRAY_LIST_IBM 103071 +#define GL_COLOR_ARRAY_LIST_IBM 103072 +#define GL_INDEX_ARRAY_LIST_IBM 103073 +#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074 +#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075 +#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076 +#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077 +#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080 +#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081 +#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082 +#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083 +#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084 +#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085 +#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086 +#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087 +#endif + +#ifndef GL_SGIX_subsample +#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0 +#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1 +#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2 +#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3 +#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4 +#endif + +#ifndef GL_SGIX_ycrcb_subsample +#endif + +#ifndef GL_SGIX_ycrcba +#define GL_YCRCB_SGIX 0x8318 +#define GL_YCRCBA_SGIX 0x8319 +#endif + +#ifndef GL_SGI_depth_pass_instrument +#define GL_DEPTH_PASS_INSTRUMENT_SGIX 0x8310 +#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311 +#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312 +#endif + +#ifndef GL_3DFX_texture_compression_FXT1 +#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0 +#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1 +#endif + +#ifndef GL_3DFX_multisample +#define GL_MULTISAMPLE_3DFX 0x86B2 +#define GL_SAMPLE_BUFFERS_3DFX 0x86B3 +#define GL_SAMPLES_3DFX 0x86B4 +#define GL_MULTISAMPLE_BIT_3DFX 0x20000000 +#endif + +#ifndef GL_3DFX_tbuffer +#endif + +#ifndef GL_EXT_multisample +#define GL_MULTISAMPLE_EXT 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F +#define GL_SAMPLE_MASK_EXT 0x80A0 +#define GL_1PASS_EXT 0x80A1 +#define GL_2PASS_0_EXT 0x80A2 +#define GL_2PASS_1_EXT 0x80A3 +#define GL_4PASS_0_EXT 0x80A4 +#define GL_4PASS_1_EXT 0x80A5 +#define GL_4PASS_2_EXT 0x80A6 +#define GL_4PASS_3_EXT 0x80A7 +#define GL_SAMPLE_BUFFERS_EXT 0x80A8 +#define GL_SAMPLES_EXT 0x80A9 +#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA +#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB +#define GL_SAMPLE_PATTERN_EXT 0x80AC +#define GL_MULTISAMPLE_BIT_EXT 0x20000000 +#endif + +#ifndef GL_SGIX_vertex_preclip +#define GL_VERTEX_PRECLIP_SGIX 0x83EE +#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF +#endif + +#ifndef GL_SGIX_convolution_accuracy +#define GL_CONVOLUTION_HINT_SGIX 0x8316 +#endif + +#ifndef GL_SGIX_resample +#define GL_PACK_RESAMPLE_SGIX 0x842C +#define GL_UNPACK_RESAMPLE_SGIX 0x842D +#define GL_RESAMPLE_REPLICATE_SGIX 0x842E +#define GL_RESAMPLE_ZERO_FILL_SGIX 0x842F +#define GL_RESAMPLE_DECIMATE_SGIX 0x8430 +#endif + +#ifndef GL_SGIS_point_line_texgen +#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0 +#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1 +#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2 +#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3 +#define GL_EYE_POINT_SGIS 0x81F4 +#define GL_OBJECT_POINT_SGIS 0x81F5 +#define GL_EYE_LINE_SGIS 0x81F6 +#define GL_OBJECT_LINE_SGIS 0x81F7 +#endif + +#ifndef GL_SGIS_texture_color_mask +#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF +#endif + +#ifndef GL_EXT_texture_env_dot3 +#define GL_DOT3_RGB_EXT 0x8740 +#define GL_DOT3_RGBA_EXT 0x8741 +#endif + +#ifndef GL_ATI_texture_mirror_once +#define GL_MIRROR_CLAMP_ATI 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743 +#endif + +#ifndef GL_NV_fence +#define GL_ALL_COMPLETED_NV 0x84F2 +#define GL_FENCE_STATUS_NV 0x84F3 +#define GL_FENCE_CONDITION_NV 0x84F4 +#endif + +#ifndef GL_IBM_texture_mirrored_repeat +#define GL_MIRRORED_REPEAT_IBM 0x8370 +#endif + +#ifndef GL_NV_evaluators +#define GL_EVAL_2D_NV 0x86C0 +#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1 +#define GL_MAP_TESSELLATION_NV 0x86C2 +#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3 +#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4 +#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5 +#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6 +#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7 +#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8 +#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9 +#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA +#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB +#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC +#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD +#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE +#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF +#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0 +#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1 +#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2 +#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3 +#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4 +#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5 +#define GL_MAX_MAP_TESSELLATION_NV 0x86D6 +#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7 +#endif + +#ifndef GL_NV_packed_depth_stencil +#define GL_DEPTH_STENCIL_NV 0x84F9 +#define GL_UNSIGNED_INT_24_8_NV 0x84FA +#endif + +#ifndef GL_NV_register_combiners2 +#define GL_PER_STAGE_CONSTANTS_NV 0x8535 +#endif + +#ifndef GL_NV_texture_compression_vtc +#endif + +#ifndef GL_NV_texture_rectangle +#define GL_TEXTURE_RECTANGLE_NV 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8 +#endif + +#ifndef GL_NV_texture_shader +#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C +#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D +#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E +#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 +#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA +#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB +#define GL_DSDT_MAG_INTENSITY_NV 0x86DC +#define GL_SHADER_CONSISTENT_NV 0x86DD +#define GL_TEXTURE_SHADER_NV 0x86DE +#define GL_SHADER_OPERATION_NV 0x86DF +#define GL_CULL_MODES_NV 0x86E0 +#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 +#define GL_OFFSET_TEXTURE_2D_MATRIX_NV GL_OFFSET_TEXTURE_MATRIX_NV +#define GL_OFFSET_TEXTURE_2D_SCALE_NV GL_OFFSET_TEXTURE_SCALE_NV +#define GL_OFFSET_TEXTURE_2D_BIAS_NV GL_OFFSET_TEXTURE_BIAS_NV +#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 +#define GL_CONST_EYE_NV 0x86E5 +#define GL_PASS_THROUGH_NV 0x86E6 +#define GL_CULL_FRAGMENT_NV 0x86E7 +#define GL_OFFSET_TEXTURE_2D_NV 0x86E8 +#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 +#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA +#define GL_DOT_PRODUCT_NV 0x86EC +#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED +#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE +#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 +#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 +#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 +#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 +#define GL_HILO_NV 0x86F4 +#define GL_DSDT_NV 0x86F5 +#define GL_DSDT_MAG_NV 0x86F6 +#define GL_DSDT_MAG_VIB_NV 0x86F7 +#define GL_HILO16_NV 0x86F8 +#define GL_SIGNED_HILO_NV 0x86F9 +#define GL_SIGNED_HILO16_NV 0x86FA +#define GL_SIGNED_RGBA_NV 0x86FB +#define GL_SIGNED_RGBA8_NV 0x86FC +#define GL_SIGNED_RGB_NV 0x86FE +#define GL_SIGNED_RGB8_NV 0x86FF +#define GL_SIGNED_LUMINANCE_NV 0x8701 +#define GL_SIGNED_LUMINANCE8_NV 0x8702 +#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 +#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 +#define GL_SIGNED_ALPHA_NV 0x8705 +#define GL_SIGNED_ALPHA8_NV 0x8706 +#define GL_SIGNED_INTENSITY_NV 0x8707 +#define GL_SIGNED_INTENSITY8_NV 0x8708 +#define GL_DSDT8_NV 0x8709 +#define GL_DSDT8_MAG8_NV 0x870A +#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B +#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C +#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D +#define GL_HI_SCALE_NV 0x870E +#define GL_LO_SCALE_NV 0x870F +#define GL_DS_SCALE_NV 0x8710 +#define GL_DT_SCALE_NV 0x8711 +#define GL_MAGNITUDE_SCALE_NV 0x8712 +#define GL_VIBRANCE_SCALE_NV 0x8713 +#define GL_HI_BIAS_NV 0x8714 +#define GL_LO_BIAS_NV 0x8715 +#define GL_DS_BIAS_NV 0x8716 +#define GL_DT_BIAS_NV 0x8717 +#define GL_MAGNITUDE_BIAS_NV 0x8718 +#define GL_VIBRANCE_BIAS_NV 0x8719 +#define GL_TEXTURE_BORDER_VALUES_NV 0x871A +#define GL_TEXTURE_HI_SIZE_NV 0x871B +#define GL_TEXTURE_LO_SIZE_NV 0x871C +#define GL_TEXTURE_DS_SIZE_NV 0x871D +#define GL_TEXTURE_DT_SIZE_NV 0x871E +#define GL_TEXTURE_MAG_SIZE_NV 0x871F +#endif + +#ifndef GL_NV_texture_shader2 +#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF +#endif + +#ifndef GL_NV_vertex_array_range2 +#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 +#endif + +#ifndef GL_NV_vertex_program +#define GL_VERTEX_PROGRAM_NV 0x8620 +#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 +#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 +#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 +#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 +#define GL_CURRENT_ATTRIB_NV 0x8626 +#define GL_PROGRAM_LENGTH_NV 0x8627 +#define GL_PROGRAM_STRING_NV 0x8628 +#define GL_MODELVIEW_PROJECTION_NV 0x8629 +#define GL_IDENTITY_NV 0x862A +#define GL_INVERSE_NV 0x862B +#define GL_TRANSPOSE_NV 0x862C +#define GL_INVERSE_TRANSPOSE_NV 0x862D +#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E +#define GL_MAX_TRACK_MATRICES_NV 0x862F +#define GL_MATRIX0_NV 0x8630 +#define GL_MATRIX1_NV 0x8631 +#define GL_MATRIX2_NV 0x8632 +#define GL_MATRIX3_NV 0x8633 +#define GL_MATRIX4_NV 0x8634 +#define GL_MATRIX5_NV 0x8635 +#define GL_MATRIX6_NV 0x8636 +#define GL_MATRIX7_NV 0x8637 +#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 +#define GL_CURRENT_MATRIX_NV 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 +#define GL_PROGRAM_PARAMETER_NV 0x8644 +#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 +#define GL_PROGRAM_TARGET_NV 0x8646 +#define GL_PROGRAM_RESIDENT_NV 0x8647 +#define GL_TRACK_MATRIX_NV 0x8648 +#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 +#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A +#define GL_PROGRAM_ERROR_POSITION_NV 0x864B +#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 +#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 +#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 +#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 +#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 +#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 +#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 +#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 +#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 +#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 +#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A +#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B +#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C +#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D +#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E +#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F +#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 +#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 +#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 +#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 +#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 +#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 +#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 +#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 +#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 +#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 +#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A +#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B +#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C +#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D +#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E +#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F +#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 +#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 +#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 +#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 +#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 +#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 +#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 +#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 +#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 +#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 +#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A +#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B +#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C +#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D +#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E +#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F +#endif + +#ifndef GL_SGIX_texture_coordinate_clamp +#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369 +#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A +#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B +#endif + +#ifndef GL_SGIX_scalebias_hint +#define GL_SCALEBIAS_HINT_SGIX 0x8322 +#endif + +#ifndef GL_OML_interlace +#define GL_INTERLACE_OML 0x8980 +#define GL_INTERLACE_READ_OML 0x8981 +#endif + +#ifndef GL_OML_subsample +#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982 +#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983 +#endif + +#ifndef GL_OML_resample +#define GL_PACK_RESAMPLE_OML 0x8984 +#define GL_UNPACK_RESAMPLE_OML 0x8985 +#define GL_RESAMPLE_REPLICATE_OML 0x8986 +#define GL_RESAMPLE_ZERO_FILL_OML 0x8987 +#define GL_RESAMPLE_AVERAGE_OML 0x8988 +#define GL_RESAMPLE_DECIMATE_OML 0x8989 +#endif + +#ifndef GL_NV_copy_depth_to_color +#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E +#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F +#endif + +#ifndef GL_ATI_envmap_bumpmap +#define GL_BUMP_ROT_MATRIX_ATI 0x8775 +#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776 +#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777 +#define GL_BUMP_TEX_UNITS_ATI 0x8778 +#define GL_DUDV_ATI 0x8779 +#define GL_DU8DV8_ATI 0x877A +#define GL_BUMP_ENVMAP_ATI 0x877B +#define GL_BUMP_TARGET_ATI 0x877C +#endif + +#ifndef GL_ATI_fragment_shader +#define GL_FRAGMENT_SHADER_ATI 0x8920 +#define GL_REG_0_ATI 0x8921 +#define GL_REG_1_ATI 0x8922 +#define GL_REG_2_ATI 0x8923 +#define GL_REG_3_ATI 0x8924 +#define GL_REG_4_ATI 0x8925 +#define GL_REG_5_ATI 0x8926 +#define GL_REG_6_ATI 0x8927 +#define GL_REG_7_ATI 0x8928 +#define GL_REG_8_ATI 0x8929 +#define GL_REG_9_ATI 0x892A +#define GL_REG_10_ATI 0x892B +#define GL_REG_11_ATI 0x892C +#define GL_REG_12_ATI 0x892D +#define GL_REG_13_ATI 0x892E +#define GL_REG_14_ATI 0x892F +#define GL_REG_15_ATI 0x8930 +#define GL_REG_16_ATI 0x8931 +#define GL_REG_17_ATI 0x8932 +#define GL_REG_18_ATI 0x8933 +#define GL_REG_19_ATI 0x8934 +#define GL_REG_20_ATI 0x8935 +#define GL_REG_21_ATI 0x8936 +#define GL_REG_22_ATI 0x8937 +#define GL_REG_23_ATI 0x8938 +#define GL_REG_24_ATI 0x8939 +#define GL_REG_25_ATI 0x893A +#define GL_REG_26_ATI 0x893B +#define GL_REG_27_ATI 0x893C +#define GL_REG_28_ATI 0x893D +#define GL_REG_29_ATI 0x893E +#define GL_REG_30_ATI 0x893F +#define GL_REG_31_ATI 0x8940 +#define GL_CON_0_ATI 0x8941 +#define GL_CON_1_ATI 0x8942 +#define GL_CON_2_ATI 0x8943 +#define GL_CON_3_ATI 0x8944 +#define GL_CON_4_ATI 0x8945 +#define GL_CON_5_ATI 0x8946 +#define GL_CON_6_ATI 0x8947 +#define GL_CON_7_ATI 0x8948 +#define GL_CON_8_ATI 0x8949 +#define GL_CON_9_ATI 0x894A +#define GL_CON_10_ATI 0x894B +#define GL_CON_11_ATI 0x894C +#define GL_CON_12_ATI 0x894D +#define GL_CON_13_ATI 0x894E +#define GL_CON_14_ATI 0x894F +#define GL_CON_15_ATI 0x8950 +#define GL_CON_16_ATI 0x8951 +#define GL_CON_17_ATI 0x8952 +#define GL_CON_18_ATI 0x8953 +#define GL_CON_19_ATI 0x8954 +#define GL_CON_20_ATI 0x8955 +#define GL_CON_21_ATI 0x8956 +#define GL_CON_22_ATI 0x8957 +#define GL_CON_23_ATI 0x8958 +#define GL_CON_24_ATI 0x8959 +#define GL_CON_25_ATI 0x895A +#define GL_CON_26_ATI 0x895B +#define GL_CON_27_ATI 0x895C +#define GL_CON_28_ATI 0x895D +#define GL_CON_29_ATI 0x895E +#define GL_CON_30_ATI 0x895F +#define GL_CON_31_ATI 0x8960 +#define GL_MOV_ATI 0x8961 +#define GL_ADD_ATI 0x8963 +#define GL_MUL_ATI 0x8964 +#define GL_SUB_ATI 0x8965 +#define GL_DOT3_ATI 0x8966 +#define GL_DOT4_ATI 0x8967 +#define GL_MAD_ATI 0x8968 +#define GL_LERP_ATI 0x8969 +#define GL_CND_ATI 0x896A +#define GL_CND0_ATI 0x896B +#define GL_DOT2_ADD_ATI 0x896C +#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D +#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E +#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F +#define GL_NUM_PASSES_ATI 0x8970 +#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 +#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 +#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 +#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 +#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 +#define GL_SWIZZLE_STR_ATI 0x8976 +#define GL_SWIZZLE_STQ_ATI 0x8977 +#define GL_SWIZZLE_STR_DR_ATI 0x8978 +#define GL_SWIZZLE_STQ_DQ_ATI 0x8979 +#define GL_SWIZZLE_STRQ_ATI 0x897A +#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B +#define GL_RED_BIT_ATI 0x00000001 +#define GL_GREEN_BIT_ATI 0x00000002 +#define GL_BLUE_BIT_ATI 0x00000004 +#define GL_2X_BIT_ATI 0x00000001 +#define GL_4X_BIT_ATI 0x00000002 +#define GL_8X_BIT_ATI 0x00000004 +#define GL_HALF_BIT_ATI 0x00000008 +#define GL_QUARTER_BIT_ATI 0x00000010 +#define GL_EIGHTH_BIT_ATI 0x00000020 +#define GL_SATURATE_BIT_ATI 0x00000040 +#define GL_COMP_BIT_ATI 0x00000002 +#define GL_NEGATE_BIT_ATI 0x00000004 +#define GL_BIAS_BIT_ATI 0x00000008 +#endif + +#ifndef GL_ATI_pn_triangles +#define GL_PN_TRIANGLES_ATI 0x87F0 +#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1 +#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2 +#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3 +#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4 +#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5 +#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6 +#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7 +#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8 +#endif + +#ifndef GL_ATI_vertex_array_object +#define GL_STATIC_ATI 0x8760 +#define GL_DYNAMIC_ATI 0x8761 +#define GL_PRESERVE_ATI 0x8762 +#define GL_DISCARD_ATI 0x8763 +#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764 +#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765 +#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766 +#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767 +#endif + +#ifndef GL_EXT_vertex_shader +#define GL_VERTEX_SHADER_EXT 0x8780 +#define GL_VERTEX_SHADER_BINDING_EXT 0x8781 +#define GL_OP_INDEX_EXT 0x8782 +#define GL_OP_NEGATE_EXT 0x8783 +#define GL_OP_DOT3_EXT 0x8784 +#define GL_OP_DOT4_EXT 0x8785 +#define GL_OP_MUL_EXT 0x8786 +#define GL_OP_ADD_EXT 0x8787 +#define GL_OP_MADD_EXT 0x8788 +#define GL_OP_FRAC_EXT 0x8789 +#define GL_OP_MAX_EXT 0x878A +#define GL_OP_MIN_EXT 0x878B +#define GL_OP_SET_GE_EXT 0x878C +#define GL_OP_SET_LT_EXT 0x878D +#define GL_OP_CLAMP_EXT 0x878E +#define GL_OP_FLOOR_EXT 0x878F +#define GL_OP_ROUND_EXT 0x8790 +#define GL_OP_EXP_BASE_2_EXT 0x8791 +#define GL_OP_LOG_BASE_2_EXT 0x8792 +#define GL_OP_POWER_EXT 0x8793 +#define GL_OP_RECIP_EXT 0x8794 +#define GL_OP_RECIP_SQRT_EXT 0x8795 +#define GL_OP_SUB_EXT 0x8796 +#define GL_OP_CROSS_PRODUCT_EXT 0x8797 +#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798 +#define GL_OP_MOV_EXT 0x8799 +#define GL_OUTPUT_VERTEX_EXT 0x879A +#define GL_OUTPUT_COLOR0_EXT 0x879B +#define GL_OUTPUT_COLOR1_EXT 0x879C +#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D +#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E +#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F +#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0 +#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1 +#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2 +#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3 +#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4 +#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5 +#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6 +#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7 +#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8 +#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9 +#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA +#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB +#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC +#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD +#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE +#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF +#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0 +#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1 +#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2 +#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3 +#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4 +#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5 +#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6 +#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7 +#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8 +#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9 +#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA +#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB +#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC +#define GL_OUTPUT_FOG_EXT 0x87BD +#define GL_SCALAR_EXT 0x87BE +#define GL_VECTOR_EXT 0x87BF +#define GL_MATRIX_EXT 0x87C0 +#define GL_VARIANT_EXT 0x87C1 +#define GL_INVARIANT_EXT 0x87C2 +#define GL_LOCAL_CONSTANT_EXT 0x87C3 +#define GL_LOCAL_EXT 0x87C4 +#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5 +#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6 +#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7 +#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8 +#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9 +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE +#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF +#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0 +#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1 +#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2 +#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3 +#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4 +#define GL_X_EXT 0x87D5 +#define GL_Y_EXT 0x87D6 +#define GL_Z_EXT 0x87D7 +#define GL_W_EXT 0x87D8 +#define GL_NEGATIVE_X_EXT 0x87D9 +#define GL_NEGATIVE_Y_EXT 0x87DA +#define GL_NEGATIVE_Z_EXT 0x87DB +#define GL_NEGATIVE_W_EXT 0x87DC +#define GL_ZERO_EXT 0x87DD +#define GL_ONE_EXT 0x87DE +#define GL_NEGATIVE_ONE_EXT 0x87DF +#define GL_NORMALIZED_RANGE_EXT 0x87E0 +#define GL_FULL_RANGE_EXT 0x87E1 +#define GL_CURRENT_VERTEX_EXT 0x87E2 +#define GL_MVP_MATRIX_EXT 0x87E3 +#define GL_VARIANT_VALUE_EXT 0x87E4 +#define GL_VARIANT_DATATYPE_EXT 0x87E5 +#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6 +#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7 +#define GL_VARIANT_ARRAY_EXT 0x87E8 +#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9 +#define GL_INVARIANT_VALUE_EXT 0x87EA +#define GL_INVARIANT_DATATYPE_EXT 0x87EB +#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC +#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED +#endif + +#ifndef GL_ATI_vertex_streams +#define GL_MAX_VERTEX_STREAMS_ATI 0x876B +#define GL_VERTEX_STREAM0_ATI 0x876C +#define GL_VERTEX_STREAM1_ATI 0x876D +#define GL_VERTEX_STREAM2_ATI 0x876E +#define GL_VERTEX_STREAM3_ATI 0x876F +#define GL_VERTEX_STREAM4_ATI 0x8770 +#define GL_VERTEX_STREAM5_ATI 0x8771 +#define GL_VERTEX_STREAM6_ATI 0x8772 +#define GL_VERTEX_STREAM7_ATI 0x8773 +#define GL_VERTEX_SOURCE_ATI 0x8774 +#endif + +#ifndef GL_ATI_element_array +#define GL_ELEMENT_ARRAY_ATI 0x8768 +#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769 +#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A +#endif + +#ifndef GL_SUN_mesh_array +#define GL_QUAD_MESH_SUN 0x8614 +#define GL_TRIANGLE_MESH_SUN 0x8615 +#endif + +#ifndef GL_SUN_slice_accum +#define GL_SLICE_ACCUM_SUN 0x85CC +#endif + +#ifndef GL_NV_multisample_filter_hint +#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 +#endif + +#ifndef GL_NV_depth_clamp +#define GL_DEPTH_CLAMP_NV 0x864F +#endif + +#ifndef GL_NV_occlusion_query +#define GL_PIXEL_COUNTER_BITS_NV 0x8864 +#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 +#define GL_PIXEL_COUNT_NV 0x8866 +#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 +#endif + +#ifndef GL_NV_point_sprite +#define GL_POINT_SPRITE_NV 0x8861 +#define GL_COORD_REPLACE_NV 0x8862 +#define GL_POINT_SPRITE_R_MODE_NV 0x8863 +#endif + +#ifndef GL_NV_texture_shader3 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853 +#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854 +#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857 +#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858 +#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859 +#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A +#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B +#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C +#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D +#define GL_HILO8_NV 0x885E +#define GL_SIGNED_HILO8_NV 0x885F +#define GL_FORCE_BLUE_TO_ONE_NV 0x8860 +#endif + +#ifndef GL_NV_vertex_program1_1 +#endif + +#ifndef GL_EXT_shadow_funcs +#endif + +#ifndef GL_EXT_stencil_two_side +#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 +#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 +#endif + +#ifndef GL_ATI_text_fragment_shader +#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200 +#endif + +#ifndef GL_APPLE_client_storage +#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 +#endif + +#ifndef GL_APPLE_element_array +#define GL_ELEMENT_ARRAY_APPLE 0x8768 +#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8769 +#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x876A +#endif + +#ifndef GL_APPLE_fence +#define GL_DRAW_PIXELS_APPLE 0x8A0A +#define GL_FENCE_APPLE 0x8A0B +#endif + +#ifndef GL_APPLE_vertex_array_object +#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5 +#endif + +#ifndef GL_APPLE_vertex_array_range +#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E +#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F +#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521 +#define GL_STORAGE_CACHED_APPLE 0x85BE +#define GL_STORAGE_SHARED_APPLE 0x85BF +#endif + +#ifndef GL_APPLE_ycbcr_422 +#define GL_YCBCR_422_APPLE 0x85B9 +#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB +#endif + +#ifndef GL_S3_s3tc +#define GL_RGB_S3TC 0x83A0 +#define GL_RGB4_S3TC 0x83A1 +#define GL_RGBA_S3TC 0x83A2 +#define GL_RGBA4_S3TC 0x83A3 +#endif + +#ifndef GL_ATI_draw_buffers +#define GL_MAX_DRAW_BUFFERS_ATI 0x8824 +#define GL_DRAW_BUFFER0_ATI 0x8825 +#define GL_DRAW_BUFFER1_ATI 0x8826 +#define GL_DRAW_BUFFER2_ATI 0x8827 +#define GL_DRAW_BUFFER3_ATI 0x8828 +#define GL_DRAW_BUFFER4_ATI 0x8829 +#define GL_DRAW_BUFFER5_ATI 0x882A +#define GL_DRAW_BUFFER6_ATI 0x882B +#define GL_DRAW_BUFFER7_ATI 0x882C +#define GL_DRAW_BUFFER8_ATI 0x882D +#define GL_DRAW_BUFFER9_ATI 0x882E +#define GL_DRAW_BUFFER10_ATI 0x882F +#define GL_DRAW_BUFFER11_ATI 0x8830 +#define GL_DRAW_BUFFER12_ATI 0x8831 +#define GL_DRAW_BUFFER13_ATI 0x8832 +#define GL_DRAW_BUFFER14_ATI 0x8833 +#define GL_DRAW_BUFFER15_ATI 0x8834 +#endif + +#ifndef GL_ATI_pixel_format_float +#define GL_TYPE_RGBA_FLOAT_ATI 0x8820 +#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835 +#endif + +#ifndef GL_ATI_texture_env_combine3 +#define GL_MODULATE_ADD_ATI 0x8744 +#define GL_MODULATE_SIGNED_ADD_ATI 0x8745 +#define GL_MODULATE_SUBTRACT_ATI 0x8746 +#endif + +#ifndef GL_ATI_texture_float +#define GL_RGBA_FLOAT32_ATI 0x8814 +#define GL_RGB_FLOAT32_ATI 0x8815 +#define GL_ALPHA_FLOAT32_ATI 0x8816 +#define GL_INTENSITY_FLOAT32_ATI 0x8817 +#define GL_LUMINANCE_FLOAT32_ATI 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 +#define GL_RGBA_FLOAT16_ATI 0x881A +#define GL_RGB_FLOAT16_ATI 0x881B +#define GL_ALPHA_FLOAT16_ATI 0x881C +#define GL_INTENSITY_FLOAT16_ATI 0x881D +#define GL_LUMINANCE_FLOAT16_ATI 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F +#endif + +#ifndef GL_NV_float_buffer +#define GL_FLOAT_R_NV 0x8880 +#define GL_FLOAT_RG_NV 0x8881 +#define GL_FLOAT_RGB_NV 0x8882 +#define GL_FLOAT_RGBA_NV 0x8883 +#define GL_FLOAT_R16_NV 0x8884 +#define GL_FLOAT_R32_NV 0x8885 +#define GL_FLOAT_RG16_NV 0x8886 +#define GL_FLOAT_RG32_NV 0x8887 +#define GL_FLOAT_RGB16_NV 0x8888 +#define GL_FLOAT_RGB32_NV 0x8889 +#define GL_FLOAT_RGBA16_NV 0x888A +#define GL_FLOAT_RGBA32_NV 0x888B +#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C +#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D +#define GL_FLOAT_RGBA_MODE_NV 0x888E +#endif + +#ifndef GL_NV_fragment_program +#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 +#define GL_FRAGMENT_PROGRAM_NV 0x8870 +#define GL_MAX_TEXTURE_COORDS_NV 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 +#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 +#define GL_PROGRAM_ERROR_STRING_NV 0x8874 +#endif + +#ifndef GL_NV_half_float +#define GL_HALF_FLOAT_NV 0x140B +#endif + +#ifndef GL_NV_pixel_data_range +#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878 +#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879 +#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A +#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B +#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C +#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D +#endif + +#ifndef GL_NV_primitive_restart +#define GL_PRIMITIVE_RESTART_NV 0x8558 +#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559 +#endif + +#ifndef GL_NV_texture_expand_normal +#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F +#endif + +#ifndef GL_NV_vertex_program2 +#endif + +#ifndef GL_ATI_map_object_buffer +#endif + +#ifndef GL_ATI_separate_stencil +#define GL_STENCIL_BACK_FUNC_ATI 0x8800 +#define GL_STENCIL_BACK_FAIL_ATI 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803 +#endif + +#ifndef GL_ATI_vertex_attrib_array_object +#endif + +#ifndef GL_OES_read_format +#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B +#endif + +#ifndef GL_EXT_depth_bounds_test +#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890 +#define GL_DEPTH_BOUNDS_EXT 0x8891 +#endif + +#ifndef GL_EXT_texture_mirror_clamp +#define GL_MIRROR_CLAMP_EXT 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 +#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 +#endif + +#ifndef GL_EXT_blend_equation_separate +#define GL_BLEND_EQUATION_RGB_EXT GL_BLEND_EQUATION +#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D +#endif + +#ifndef GL_MESA_pack_invert +#define GL_PACK_INVERT_MESA 0x8758 +#endif + +#ifndef GL_MESA_ycbcr_texture +#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB +#define GL_YCBCR_MESA 0x8757 +#endif + +#ifndef GL_EXT_pixel_buffer_object +#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF +#endif + +#ifndef GL_NV_fragment_program_option +#endif + +#ifndef GL_NV_fragment_program2 +#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 +#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 +#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 +#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 +#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 +#endif + +#ifndef GL_NV_vertex_program2_option +/* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */ +/* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */ +#endif + +#ifndef GL_NV_vertex_program3 +/* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */ +#endif + +#ifndef GL_EXT_framebuffer_object +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +#endif + +#ifndef GL_GREMEDY_string_marker +#endif + + +/*************************************************************/ + +#include <stddef.h> +#ifndef GL_VERSION_2_0 +/* GL type for program/shader text */ +typedef char GLchar; /* native character */ +#endif + +#ifndef GL_VERSION_1_5 +/* GL types for handling large vertex buffer objects */ +typedef ptrdiff_t GLintptr; +typedef ptrdiff_t GLsizeiptr; +#endif + +#ifndef GL_ARB_vertex_buffer_object +/* GL types for handling large vertex buffer objects */ +typedef ptrdiff_t GLintptrARB; +typedef ptrdiff_t GLsizeiptrARB; +#endif + +#ifndef GL_ARB_shader_objects +/* GL types for handling shader object handles and program/shader text */ +typedef char GLcharARB; /* native character */ +typedef unsigned int GLhandleARB; /* shader object handle */ +#endif + +/* GL types for "half" precision (s10e5) float data in host memory */ +#ifndef GL_ARB_half_float_pixel +typedef unsigned short GLhalfARB; +#endif + +#ifndef GL_NV_half_float +typedef unsigned short GLhalfNV; +#endif + +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf); +GLAPI void APIENTRY glBlendEquation (GLenum); +GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); +GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei); +GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei); +GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint); +GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei); +GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); +GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); +GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); +GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean); +GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean); +GLAPI void APIENTRY glResetHistogram (GLenum); +GLAPI void APIENTRY glResetMinmax (GLenum); +GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); +typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif + +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTexture (GLenum); +GLAPI void APIENTRY glClientActiveTexture (GLenum); +GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble); +GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat); +GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint); +GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort); +GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *); +GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *); +GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *); +GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *); +GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *); +GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean); +GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img); +#endif + +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glFogCoordf (GLfloat); +GLAPI void APIENTRY glFogCoordfv (const GLfloat *); +GLAPI void APIENTRY glFogCoordd (GLdouble); +GLAPI void APIENTRY glFogCoorddv (const GLdouble *); +GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei); +GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); +GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat); +GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *); +GLAPI void APIENTRY glPointParameteri (GLenum, GLint); +GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *); +GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte); +GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *); +GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *); +GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *); +GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint); +GLAPI void APIENTRY glSecondaryColor3iv (const GLint *); +GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *); +GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte); +GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *); +GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint); +GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *); +GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort); +GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *); +GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos2dv (const GLdouble *); +GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos2fv (const GLfloat *); +GLAPI void APIENTRY glWindowPos2i (GLint, GLint); +GLAPI void APIENTRY glWindowPos2iv (const GLint *); +GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort); +GLAPI void APIENTRY glWindowPos2sv (const GLshort *); +GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos3dv (const GLdouble *); +GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos3fv (const GLfloat *); +GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint); +GLAPI void APIENTRY glWindowPos3iv (const GLint *); +GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glWindowPos3sv (const GLshort *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); +#endif + +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *); +GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *); +GLAPI GLboolean APIENTRY glIsQuery (GLuint); +GLAPI void APIENTRY glBeginQuery (GLenum, GLuint); +GLAPI void APIENTRY glEndQuery (GLenum); +GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *); +GLAPI void APIENTRY glBindBuffer (GLenum, GLuint); +GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *); +GLAPI GLboolean APIENTRY glIsBuffer (GLuint); +GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum); +GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *); +GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *); +GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum); +GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum); +GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data); +typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params); +#endif + +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum); +GLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *); +GLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint); +GLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint); +GLAPI void APIENTRY glAttachShader (GLuint, GLuint); +GLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *); +GLAPI void APIENTRY glCompileShader (GLuint); +GLAPI GLuint APIENTRY glCreateProgram (void); +GLAPI GLuint APIENTRY glCreateShader (GLenum); +GLAPI void APIENTRY glDeleteProgram (GLuint); +GLAPI void APIENTRY glDeleteShader (GLuint); +GLAPI void APIENTRY glDetachShader (GLuint, GLuint); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint); +GLAPI void APIENTRY glEnableVertexAttribArray (GLuint); +GLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +GLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); +GLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *); +GLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *); +GLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); +GLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); +GLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *); +GLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *); +GLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *); +GLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *); +GLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *); +GLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *); +GLAPI GLboolean APIENTRY glIsProgram (GLuint); +GLAPI GLboolean APIENTRY glIsShader (GLuint); +GLAPI void APIENTRY glLinkProgram (GLuint); +GLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *); +GLAPI void APIENTRY glUseProgram (GLuint); +GLAPI void APIENTRY glUniform1f (GLint, GLfloat); +GLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform1i (GLint, GLint); +GLAPI void APIENTRY glUniform2i (GLint, GLint, GLint); +GLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glValidateProgram (GLuint); +GLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble); +GLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat); +GLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort); +GLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *); +GLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *); +GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); +GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *); +GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *); +GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *); +GLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *); +GLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *); +GLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *); +GLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *); +GLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *); +GLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); +typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length); +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_ARB_multitexture +#define GL_ARB_multitexture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTextureARB (GLenum); +GLAPI void APIENTRY glClientActiveTextureARB (GLenum); +GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble); +GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat); +GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint); +GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort); +GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *); +GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *); +GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *); +GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *); +GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); +#endif + +#ifndef GL_ARB_transpose_matrix +#define GL_ARB_transpose_matrix 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *); +GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *); +GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *); +GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +#endif + +#ifndef GL_ARB_multisample +#define GL_ARB_multisample 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert); +#endif + +#ifndef GL_ARB_texture_env_add +#define GL_ARB_texture_env_add 1 +#endif + +#ifndef GL_ARB_texture_cube_map +#define GL_ARB_texture_cube_map 1 +#endif + +#ifndef GL_ARB_texture_compression +#define GL_ARB_texture_compression 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img); +#endif + +#ifndef GL_ARB_texture_border_clamp +#define GL_ARB_texture_border_clamp 1 +#endif + +#ifndef GL_ARB_point_parameters +#define GL_ARB_point_parameters 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat); +GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); +#endif + +#ifndef GL_ARB_vertex_blend +#define GL_ARB_vertex_blend 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *); +GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *); +GLAPI void APIENTRY glWeightivARB (GLint, const GLint *); +GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *); +GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *); +GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *); +GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *); +GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *); +GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glVertexBlendARB (GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); +typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights); +typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights); +typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights); +typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights); +typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights); +typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); +#endif + +#ifndef GL_ARB_matrix_palette +#define GL_ARB_matrix_palette 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint); +GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *); +GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *); +GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *); +GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); +typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_ARB_texture_env_combine +#define GL_ARB_texture_env_combine 1 +#endif + +#ifndef GL_ARB_texture_env_crossbar +#define GL_ARB_texture_env_crossbar 1 +#endif + +#ifndef GL_ARB_texture_env_dot3 +#define GL_ARB_texture_env_dot3 1 +#endif + +#ifndef GL_ARB_texture_mirrored_repeat +#define GL_ARB_texture_mirrored_repeat 1 +#endif + +#ifndef GL_ARB_depth_texture +#define GL_ARB_depth_texture 1 +#endif + +#ifndef GL_ARB_shadow +#define GL_ARB_shadow 1 +#endif + +#ifndef GL_ARB_shadow_ambient +#define GL_ARB_shadow_ambient 1 +#endif + +#ifndef GL_ARB_window_pos +#define GL_ARB_window_pos 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *); +GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *); +GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint); +GLAPI void APIENTRY glWindowPos2ivARB (const GLint *); +GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort); +GLAPI void APIENTRY glWindowPos2svARB (const GLshort *); +GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *); +GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *); +GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint); +GLAPI void APIENTRY glWindowPos3ivARB (const GLint *); +GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glWindowPos3svARB (const GLshort *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); +#endif + +#ifndef GL_ARB_vertex_program +#define GL_ARB_vertex_program 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble); +GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat); +GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort); +GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *); +GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *); +GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); +GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *); +GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *); +GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *); +GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *); +GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *); +GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *); +GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *); +GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *); +GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); +GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint); +GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint); +GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint); +GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *); +GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *); +GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *); +GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *); +GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *); +GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *); +GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *); +GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *); +GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *); +GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *); +GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *); +GLAPI GLboolean APIENTRY glIsProgramARB (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string); +typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); +#endif + +#ifndef GL_ARB_fragment_program +#define GL_ARB_fragment_program 1 +/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */ +#endif + +#ifndef GL_ARB_vertex_buffer_object +#define GL_ARB_vertex_buffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint); +GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *); +GLAPI GLboolean APIENTRY glIsBufferARB (GLuint); +GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); +GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *); +GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *); +GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum); +GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum); +GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); +typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params); +#endif + +#ifndef GL_ARB_occlusion_query +#define GL_ARB_occlusion_query 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *); +GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *); +GLAPI GLboolean APIENTRY glIsQueryARB (GLuint); +GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint); +GLAPI void APIENTRY glEndQueryARB (GLenum); +GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params); +#endif + +#ifndef GL_ARB_shader_objects +#define GL_ARB_shader_objects 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB); +GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum); +GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB); +GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum); +GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *); +GLAPI void APIENTRY glCompileShaderARB (GLhandleARB); +GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void); +GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB); +GLAPI void APIENTRY glLinkProgramARB (GLhandleARB); +GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB); +GLAPI void APIENTRY glValidateProgramARB (GLhandleARB); +GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat); +GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glUniform1iARB (GLint, GLint); +GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint); +GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *); +GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *); +GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *); +GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *); +GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); +GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *); +GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *); +GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); +GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *); +GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *); +GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); +typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType); +typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length); +typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void); +typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj); +typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#endif + +#ifndef GL_ARB_vertex_shader +#define GL_ARB_vertex_shader 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *); +GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); +GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +#endif + +#ifndef GL_ARB_fragment_shader +#define GL_ARB_fragment_shader 1 +#endif + +#ifndef GL_ARB_shading_language_100 +#define GL_ARB_shading_language_100 1 +#endif + +#ifndef GL_ARB_texture_non_power_of_two +#define GL_ARB_texture_non_power_of_two 1 +#endif + +#ifndef GL_ARB_point_sprite +#define GL_ARB_point_sprite 1 +#endif + +#ifndef GL_ARB_fragment_program_shadow +#define GL_ARB_fragment_program_shadow 1 +#endif + +#ifndef GL_ARB_draw_buffers +#define GL_ARB_draw_buffers 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); +#endif + +#ifndef GL_ARB_texture_rectangle +#define GL_ARB_texture_rectangle 1 +#endif + +#ifndef GL_ARB_color_buffer_float +#define GL_ARB_color_buffer_float 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClampColorARB (GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); +#endif + +#ifndef GL_ARB_half_float_pixel +#define GL_ARB_half_float_pixel 1 +#endif + +#ifndef GL_ARB_texture_float +#define GL_ARB_texture_float 1 +#endif + +#ifndef GL_ARB_pixel_buffer_object +#define GL_ARB_pixel_buffer_object 1 +#endif + +#ifndef GL_EXT_abgr +#define GL_EXT_abgr 1 +#endif + +#ifndef GL_EXT_blend_color +#define GL_EXT_blend_color 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); +#endif + +#ifndef GL_EXT_polygon_offset +#define GL_EXT_polygon_offset 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); +#endif + +#ifndef GL_EXT_texture +#define GL_EXT_texture 1 +#endif + +#ifndef GL_EXT_texture3D +#define GL_EXT_texture3D 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); +#endif + +#ifndef GL_SGIS_texture_filter4 +#define GL_SGIS_texture_filter4 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); +typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#endif + +#ifndef GL_EXT_subtexture +#define GL_EXT_subtexture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); +#endif + +#ifndef GL_EXT_copy_texture +#define GL_EXT_copy_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint); +GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); +GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei); +GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif + +#ifndef GL_EXT_histogram +#define GL_EXT_histogram 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean); +GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean); +GLAPI void APIENTRY glResetHistogramEXT (GLenum); +GLAPI void APIENTRY glResetMinmaxEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); +#endif + +#ifndef GL_EXT_convolution +#define GL_EXT_convolution 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint); +GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei); +GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); +GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); +GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); +#endif + +#ifndef GL_EXT_color_matrix +#define GL_EXT_color_matrix 1 +#endif + +#ifndef GL_SGI_color_table +#define GL_SGI_color_table 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei); +GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params); +#endif + +#ifndef GL_SGIX_pixel_texture +#define GL_SGIX_pixel_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenSGIX (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); +#endif + +#ifndef GL_SGIS_pixel_texture +#define GL_SGIS_pixel_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint); +GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *); +GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat); +GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *); +GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *); +GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params); +#endif + +#ifndef GL_SGIS_texture4D +#define GL_SGIS_texture4D 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels); +#endif + +#ifndef GL_SGI_texture_color_table +#define GL_SGI_texture_color_table 1 +#endif + +#ifndef GL_EXT_cmyka +#define GL_EXT_cmyka 1 +#endif + +#ifndef GL_EXT_texture_object +#define GL_EXT_texture_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *); +GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint); +GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *); +GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint); +GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures); +typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#endif + +#ifndef GL_SGIS_detail_texture +#define GL_SGIS_detail_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *); +GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#endif + +#ifndef GL_SGIS_sharpen_texture +#define GL_SGIS_sharpen_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *); +GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#endif + +#ifndef GL_EXT_packed_pixels +#define GL_EXT_packed_pixels 1 +#endif + +#ifndef GL_SGIS_texture_lod +#define GL_SGIS_texture_lod 1 +#endif + +#ifndef GL_SGIS_multisample +#define GL_SGIS_multisample 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean); +GLAPI void APIENTRY glSamplePatternSGIS (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); +#endif + +#ifndef GL_EXT_rescale_normal +#define GL_EXT_rescale_normal 1 +#endif + +#ifndef GL_EXT_vertex_array +#define GL_EXT_vertex_array 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glArrayElementEXT (GLint); +GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); +GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei); +GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *); +GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *); +GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); +GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); +GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); +GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); +typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer); +typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params); +typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); +#endif + +#ifndef GL_EXT_misc_attribute +#define GL_EXT_misc_attribute 1 +#endif + +#ifndef GL_SGIS_generate_mipmap +#define GL_SGIS_generate_mipmap 1 +#endif + +#ifndef GL_SGIX_clipmap +#define GL_SGIX_clipmap 1 +#endif + +#ifndef GL_SGIX_shadow +#define GL_SGIX_shadow 1 +#endif + +#ifndef GL_SGIS_texture_edge_clamp +#define GL_SGIS_texture_edge_clamp 1 +#endif + +#ifndef GL_SGIS_texture_border_clamp +#define GL_SGIS_texture_border_clamp 1 +#endif + +#ifndef GL_EXT_blend_minmax +#define GL_EXT_blend_minmax 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); +#endif + +#ifndef GL_EXT_blend_subtract +#define GL_EXT_blend_subtract 1 +#endif + +#ifndef GL_EXT_blend_logic_op +#define GL_EXT_blend_logic_op 1 +#endif + +#ifndef GL_SGIX_interlace +#define GL_SGIX_interlace 1 +#endif + +#ifndef GL_SGIX_pixel_tiles +#define GL_SGIX_pixel_tiles 1 +#endif + +#ifndef GL_SGIX_texture_select +#define GL_SGIX_texture_select 1 +#endif + +#ifndef GL_SGIX_sprite +#define GL_SGIX_sprite 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat); +GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *); +GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint); +GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params); +#endif + +#ifndef GL_SGIX_texture_multi_buffer +#define GL_SGIX_texture_multi_buffer 1 +#endif + +#ifndef GL_EXT_point_parameters +#define GL_EXT_point_parameters 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat); +GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); +#endif + +#ifndef GL_SGIS_point_parameters +#define GL_SGIS_point_parameters 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat); +GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +#endif + +#ifndef GL_SGIX_instruments +#define GL_SGIX_instruments 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLint APIENTRY glGetInstrumentsSGIX (void); +GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *); +GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *); +GLAPI void APIENTRY glReadInstrumentsSGIX (GLint); +GLAPI void APIENTRY glStartInstrumentsSGIX (void); +GLAPI void APIENTRY glStopInstrumentsSGIX (GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); +typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p); +typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker); +typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); +#endif + +#ifndef GL_SGIX_texture_scale_bias +#define GL_SGIX_texture_scale_bias 1 +#endif + +#ifndef GL_SGIX_framezoom +#define GL_SGIX_framezoom 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameZoomSGIX (GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); +#endif + +#ifndef GL_SGIX_tag_sample_buffer +#define GL_SGIX_tag_sample_buffer 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTagSampleBufferSGIX (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); +#endif + +#ifndef GL_SGIX_polynomial_ffd +#define GL_SGIX_polynomial_ffd 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *); +GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *); +GLAPI void APIENTRY glDeformSGIX (GLbitfield); +GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask); +#endif + +#ifndef GL_SGIX_reference_plane +#define GL_SGIX_reference_plane 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); +#endif + +#ifndef GL_SGIX_flush_raster +#define GL_SGIX_flush_raster 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushRasterSGIX (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); +#endif + +#ifndef GL_SGIX_depth_texture +#define GL_SGIX_depth_texture 1 +#endif + +#ifndef GL_SGIS_fog_function +#define GL_SGIS_fog_function 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *); +GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); +#endif + +#ifndef GL_SGIX_fog_offset +#define GL_SGIX_fog_offset 1 +#endif + +#ifndef GL_HP_image_transform +#define GL_HP_image_transform 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint); +GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params); +#endif + +#ifndef GL_HP_convolution_border_modes +#define GL_HP_convolution_border_modes 1 +#endif + +#ifndef GL_SGIX_texture_add_env +#define GL_SGIX_texture_add_env 1 +#endif + +#ifndef GL_EXT_color_subtable +#define GL_EXT_color_subtable 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#endif + +#ifndef GL_PGI_vertex_hints +#define GL_PGI_vertex_hints 1 +#endif + +#ifndef GL_PGI_misc_hints +#define GL_PGI_misc_hints 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glHintPGI (GLenum, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); +#endif + +#ifndef GL_EXT_paletted_texture +#define GL_EXT_paletted_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); +GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *); +GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#endif + +#ifndef GL_EXT_clip_volume_hint +#define GL_EXT_clip_volume_hint 1 +#endif + +#ifndef GL_SGIX_list_priority +#define GL_SGIX_list_priority 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat); +GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *); +GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint); +GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params); +#endif + +#ifndef GL_SGIX_ir_instrument1 +#define GL_SGIX_ir_instrument1 1 +#endif + +#ifndef GL_SGIX_calligraphic_fragment +#define GL_SGIX_calligraphic_fragment 1 +#endif + +#ifndef GL_SGIX_texture_lod_bias +#define GL_SGIX_texture_lod_bias 1 +#endif + +#ifndef GL_SGIX_shadow_ambient +#define GL_SGIX_shadow_ambient 1 +#endif + +#ifndef GL_EXT_index_texture +#define GL_EXT_index_texture 1 +#endif + +#ifndef GL_EXT_index_material +#define GL_EXT_index_material 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); +#endif + +#ifndef GL_EXT_index_func +#define GL_EXT_index_func 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); +#endif + +#ifndef GL_EXT_index_array_formats +#define GL_EXT_index_array_formats 1 +#endif + +#ifndef GL_EXT_compiled_vertex_array +#define GL_EXT_compiled_vertex_array 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei); +GLAPI void APIENTRY glUnlockArraysEXT (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); +#endif + +#ifndef GL_EXT_cull_vertex +#define GL_EXT_cull_vertex 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *); +GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); +#endif + +#ifndef GL_SGIX_ycrcb +#define GL_SGIX_ycrcb 1 +#endif + +#ifndef GL_SGIX_fragment_lighting +#define GL_SGIX_fragment_lighting 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum); +GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint); +GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat); +GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *); +GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint); +GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *); +GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint); +GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); +#endif + +#ifndef GL_IBM_rasterpos_clip +#define GL_IBM_rasterpos_clip 1 +#endif + +#ifndef GL_HP_texture_lighting +#define GL_HP_texture_lighting 1 +#endif + +#ifndef GL_EXT_draw_range_elements +#define GL_EXT_draw_range_elements 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); +#endif + +#ifndef GL_WIN_phong_shading +#define GL_WIN_phong_shading 1 +#endif + +#ifndef GL_WIN_specular_fog +#define GL_WIN_specular_fog 1 +#endif + +#ifndef GL_EXT_light_texture +#define GL_EXT_light_texture 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyTextureEXT (GLenum); +GLAPI void APIENTRY glTextureLightEXT (GLenum); +GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); +#endif + +#ifndef GL_SGIX_blend_alpha_minmax +#define GL_SGIX_blend_alpha_minmax 1 +#endif + +#ifndef GL_EXT_bgra +#define GL_EXT_bgra 1 +#endif + +#ifndef GL_SGIX_async +#define GL_SGIX_async 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint); +GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *); +GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *); +GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei); +GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei); +GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); +typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); +typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp); +typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); +#endif + +#ifndef GL_SGIX_async_pixel +#define GL_SGIX_async_pixel 1 +#endif + +#ifndef GL_SGIX_async_histogram +#define GL_SGIX_async_histogram 1 +#endif + +#ifndef GL_INTEL_parallel_arrays +#define GL_INTEL_parallel_arrays 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *); +GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *); +GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *); +GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer); +typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); +#endif + +#ifndef GL_HP_occlusion_test +#define GL_HP_occlusion_test 1 +#endif + +#ifndef GL_EXT_pixel_transform +#define GL_EXT_pixel_transform 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint); +GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat); +GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +#endif + +#ifndef GL_EXT_pixel_transform_color_table +#define GL_EXT_pixel_transform_color_table 1 +#endif + +#ifndef GL_EXT_shared_texture_palette +#define GL_EXT_shared_texture_palette 1 +#endif + +#ifndef GL_EXT_separate_specular_color +#define GL_EXT_separate_specular_color 1 +#endif + +#ifndef GL_EXT_secondary_color +#define GL_EXT_secondary_color 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte); +GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *); +GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *); +GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *); +GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint); +GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *); +GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *); +GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte); +GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *); +GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint); +GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *); +GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort); +GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *); +GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_EXT_texture_perturb_normal +#define GL_EXT_texture_perturb_normal 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureNormalEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); +#endif + +#ifndef GL_EXT_multi_draw_arrays +#define GL_EXT_multi_draw_arrays 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei); +GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); +#endif + +#ifndef GL_EXT_fog_coord +#define GL_EXT_fog_coord 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogCoordfEXT (GLfloat); +GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *); +GLAPI void APIENTRY glFogCoorddEXT (GLdouble); +GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *); +GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_REND_screen_coordinates +#define GL_REND_screen_coordinates 1 +#endif + +#ifndef GL_EXT_coordinate_frame +#define GL_EXT_coordinate_frame 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte); +GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *); +GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *); +GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *); +GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint); +GLAPI void APIENTRY glTangent3ivEXT (const GLint *); +GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glTangent3svEXT (const GLshort *); +GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte); +GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *); +GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *); +GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *); +GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint); +GLAPI void APIENTRY glBinormal3ivEXT (const GLint *); +GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glBinormal3svEXT (const GLshort *); +GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); +typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz); +typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz); +typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz); +typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz); +typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz); +typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz); +typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz); +typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz); +typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz); +typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_EXT_texture_env_combine +#define GL_EXT_texture_env_combine 1 +#endif + +#ifndef GL_APPLE_specular_vector +#define GL_APPLE_specular_vector 1 +#endif + +#ifndef GL_APPLE_transform_hint +#define GL_APPLE_transform_hint 1 +#endif + +#ifndef GL_SGIX_fog_scale +#define GL_SGIX_fog_scale 1 +#endif + +#ifndef GL_SUNX_constant_data +#define GL_SUNX_constant_data 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFinishTextureSUNX (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); +#endif + +#ifndef GL_SUN_global_alpha +#define GL_SUN_global_alpha 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte); +GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort); +GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint); +GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat); +GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble); +GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte); +GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort); +GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); +#endif + +#ifndef GL_SUN_triangle_list +#define GL_SUN_triangle_list 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint); +GLAPI void APIENTRY glReplacementCodeusSUN (GLushort); +GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte); +GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *); +GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *); +GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *); +GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer); +#endif + +#ifndef GL_SUN_vertex +#define GL_SUN_vertex 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat); +GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *); +GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *); +GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#endif + +#ifndef GL_EXT_blend_func_separate +#define GL_EXT_blend_func_separate 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif + +#ifndef GL_INGR_blend_func_separate +#define GL_INGR_blend_func_separate 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif + +#ifndef GL_INGR_color_clamp +#define GL_INGR_color_clamp 1 +#endif + +#ifndef GL_INGR_interlace_read +#define GL_INGR_interlace_read 1 +#endif + +#ifndef GL_EXT_stencil_wrap +#define GL_EXT_stencil_wrap 1 +#endif + +#ifndef GL_EXT_422_pixels +#define GL_EXT_422_pixels 1 +#endif + +#ifndef GL_NV_texgen_reflection +#define GL_NV_texgen_reflection 1 +#endif + +#ifndef GL_SUN_convolution_border_modes +#define GL_SUN_convolution_border_modes 1 +#endif + +#ifndef GL_EXT_texture_env_add +#define GL_EXT_texture_env_add 1 +#endif + +#ifndef GL_EXT_texture_lod_bias +#define GL_EXT_texture_lod_bias 1 +#endif + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#endif + +#ifndef GL_EXT_vertex_weighting +#define GL_EXT_vertex_weighting 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexWeightfEXT (GLfloat); +GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *); +GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer); +#endif + +#ifndef GL_NV_light_max_exponent +#define GL_NV_light_max_exponent 1 +#endif + +#ifndef GL_NV_vertex_array_range +#define GL_NV_vertex_array_range 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); +GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer); +#endif + +#ifndef GL_NV_register_combiners +#define GL_NV_register_combiners 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *); +GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat); +GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *); +GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint); +GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean); +GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params); +#endif + +#ifndef GL_NV_fog_distance +#define GL_NV_fog_distance 1 +#endif + +#ifndef GL_NV_texgen_emboss +#define GL_NV_texgen_emboss 1 +#endif + +#ifndef GL_NV_blend_square +#define GL_NV_blend_square 1 +#endif + +#ifndef GL_NV_texture_env_combine4 +#define GL_NV_texture_env_combine4 1 +#endif + +#ifndef GL_MESA_resize_buffers +#define GL_MESA_resize_buffers 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glResizeBuffersMESA (void); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); +#endif + +#ifndef GL_MESA_window_pos +#define GL_MESA_window_pos 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *); +GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *); +GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint); +GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *); +GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort); +GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *); +GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *); +GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *); +GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint); +GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *); +GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort); +GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *); +GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *); +GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *); +GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *); +GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); +#endif + +#ifndef GL_IBM_cull_vertex +#define GL_IBM_cull_vertex 1 +#endif + +#ifndef GL_IBM_multimode_draw_arrays +#define GL_IBM_multimode_draw_arrays 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint); +GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride); +#endif + +#ifndef GL_IBM_vertex_array_lists +#define GL_IBM_vertex_array_lists 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint); +GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); +GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); +#endif + +#ifndef GL_SGIX_subsample +#define GL_SGIX_subsample 1 +#endif + +#ifndef GL_SGIX_ycrcba +#define GL_SGIX_ycrcba 1 +#endif + +#ifndef GL_SGIX_ycrcb_subsample +#define GL_SGIX_ycrcb_subsample 1 +#endif + +#ifndef GL_SGIX_depth_pass_instrument +#define GL_SGIX_depth_pass_instrument 1 +#endif + +#ifndef GL_3DFX_texture_compression_FXT1 +#define GL_3DFX_texture_compression_FXT1 1 +#endif + +#ifndef GL_3DFX_multisample +#define GL_3DFX_multisample 1 +#endif + +#ifndef GL_3DFX_tbuffer +#define GL_3DFX_tbuffer 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTbufferMask3DFX (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); +#endif + +#ifndef GL_EXT_multisample +#define GL_EXT_multisample 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean); +GLAPI void APIENTRY glSamplePatternEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); +#endif + +#ifndef GL_SGIX_vertex_preclip +#define GL_SGIX_vertex_preclip 1 +#endif + +#ifndef GL_SGIX_convolution_accuracy +#define GL_SGIX_convolution_accuracy 1 +#endif + +#ifndef GL_SGIX_resample +#define GL_SGIX_resample 1 +#endif + +#ifndef GL_SGIS_point_line_texgen +#define GL_SGIS_point_line_texgen 1 +#endif + +#ifndef GL_SGIS_texture_color_mask +#define GL_SGIS_texture_color_mask 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#endif + +#ifndef GL_SGIX_igloo_interface +#define GL_SGIX_igloo_interface 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params); +#endif + +#ifndef GL_EXT_texture_env_dot3 +#define GL_EXT_texture_env_dot3 1 +#endif + +#ifndef GL_ATI_texture_mirror_once +#define GL_ATI_texture_mirror_once 1 +#endif + +#ifndef GL_NV_fence +#define GL_NV_fence 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *); +GLAPI GLboolean APIENTRY glIsFenceNV (GLuint); +GLAPI GLboolean APIENTRY glTestFenceNV (GLuint); +GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glFinishFenceNV (GLuint); +GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); +typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); +#endif + +#ifndef GL_NV_evaluators +#define GL_NV_evaluators 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *); +GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *); +GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *); +GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points); +typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); +#endif + +#ifndef GL_NV_packed_depth_stencil +#define GL_NV_packed_depth_stencil 1 +#endif + +#ifndef GL_NV_register_combiners2 +#define GL_NV_register_combiners2 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *); +GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); +#endif + +#ifndef GL_NV_texture_compression_vtc +#define GL_NV_texture_compression_vtc 1 +#endif + +#ifndef GL_NV_texture_rectangle +#define GL_NV_texture_rectangle 1 +#endif + +#ifndef GL_NV_texture_shader +#define GL_NV_texture_shader 1 +#endif + +#ifndef GL_NV_texture_shader2 +#define GL_NV_texture_shader2 1 +#endif + +#ifndef GL_NV_vertex_array_range2 +#define GL_NV_vertex_array_range2 1 +#endif + +#ifndef GL_NV_vertex_program +#define GL_NV_vertex_program 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *); +GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint); +GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *); +GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *); +GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *); +GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *); +GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *); +GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *); +GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *); +GLAPI GLboolean APIENTRY glIsProgramNV (GLuint); +GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *); +GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *); +GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *); +GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *); +GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *); +GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *); +GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum); +GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *); +GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble); +GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat); +GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort); +GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *); +GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *); +GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *); +GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); +GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *); +GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *); +GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *); +GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *); +GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *); +GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *); +GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *); +GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *); +GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *); +GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *); +GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params); +typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program); +typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v); +typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v); +#endif + +#ifndef GL_SGIX_texture_coordinate_clamp +#define GL_SGIX_texture_coordinate_clamp 1 +#endif + +#ifndef GL_SGIX_scalebias_hint +#define GL_SGIX_scalebias_hint 1 +#endif + +#ifndef GL_OML_interlace +#define GL_OML_interlace 1 +#endif + +#ifndef GL_OML_subsample +#define GL_OML_subsample 1 +#endif + +#ifndef GL_OML_resample +#define GL_OML_resample 1 +#endif + +#ifndef GL_NV_copy_depth_to_color +#define GL_NV_copy_depth_to_color 1 +#endif + +#ifndef GL_ATI_envmap_bumpmap +#define GL_ATI_envmap_bumpmap 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *); +GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *); +GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param); +#endif + +#ifndef GL_ATI_fragment_shader +#define GL_ATI_fragment_shader 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint); +GLAPI void APIENTRY glBindFragmentShaderATI (GLuint); +GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint); +GLAPI void APIENTRY glBeginFragmentShaderATI (void); +GLAPI void APIENTRY glEndFragmentShaderATI (void); +GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum); +GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum); +GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); +typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle); +typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value); +#endif + +#ifndef GL_ATI_pn_triangles +#define GL_ATI_pn_triangles 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint); +GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); +#endif + +#ifndef GL_ATI_vertex_array_object +#define GL_ATI_vertex_array_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum); +GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint); +GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum); +GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glFreeObjectBufferATI (GLuint); +GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint); +GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *); +GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *); +GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint); +GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage); +typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params); +#endif + +#ifndef GL_EXT_vertex_shader +#define GL_EXT_vertex_shader 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVertexShaderEXT (void); +GLAPI void APIENTRY glEndVertexShaderEXT (void); +GLAPI void APIENTRY glBindVertexShaderEXT (GLuint); +GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint); +GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint); +GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint); +GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint); +GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint); +GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint); +GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint); +GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *); +GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *); +GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *); +GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *); +GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *); +GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *); +GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *); +GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *); +GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *); +GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *); +GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *); +GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint); +GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint); +GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum); +GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum); +GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum); +GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum); +GLAPI GLuint APIENTRY glBindParameterEXT (GLenum); +GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum); +GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *); +GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *); +GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *); +GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *); +GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range); +typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1); +typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr); +typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr); +typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr); +typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr); +typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr); +typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr); +typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr); +typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr); +typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr); +typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr); +typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr); +typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value); +typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap); +typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data); +typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +#endif + +#ifndef GL_ATI_vertex_streams +#define GL_ATI_vertex_streams 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort); +GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *); +GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint); +GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *); +GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat); +GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble); +GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *); +GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort); +GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *); +GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint); +GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *); +GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *); +GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *); +GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint); +GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *); +GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *); +GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *); +GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint); +GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *); +GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *); +GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte); +GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *); +GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort); +GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *); +GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint); +GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *); +GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *); +GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *); +GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum); +GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint); +GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param); +#endif + +#ifndef GL_ATI_element_array +#define GL_ATI_element_array 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *); +GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei); +GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count); +#endif + +#ifndef GL_SUN_mesh_array +#define GL_SUN_mesh_array 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); +#endif + +#ifndef GL_SUN_slice_accum +#define GL_SUN_slice_accum 1 +#endif + +#ifndef GL_NV_multisample_filter_hint +#define GL_NV_multisample_filter_hint 1 +#endif + +#ifndef GL_NV_depth_clamp +#define GL_NV_depth_clamp 1 +#endif + +#ifndef GL_NV_occlusion_query +#define GL_NV_occlusion_query 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *); +GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *); +GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint); +GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint); +GLAPI void APIENTRY glEndOcclusionQueryNV (void); +GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *); +GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params); +#endif + +#ifndef GL_NV_point_sprite +#define GL_NV_point_sprite 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint); +GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +#endif + +#ifndef GL_NV_texture_shader3 +#define GL_NV_texture_shader3 1 +#endif + +#ifndef GL_NV_vertex_program1_1 +#define GL_NV_vertex_program1_1 1 +#endif + +#ifndef GL_EXT_shadow_funcs +#define GL_EXT_shadow_funcs 1 +#endif + +#ifndef GL_EXT_stencil_two_side +#define GL_EXT_stencil_two_side 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); +#endif + +#ifndef GL_ATI_text_fragment_shader +#define GL_ATI_text_fragment_shader 1 +#endif + +#ifndef GL_APPLE_client_storage +#define GL_APPLE_client_storage 1 +#endif + +#ifndef GL_APPLE_element_array +#define GL_APPLE_element_array 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *); +GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei); +GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei); +GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei); +GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#endif + +#ifndef GL_APPLE_fence +#define GL_APPLE_fence 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *); +GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *); +GLAPI void APIENTRY glSetFenceAPPLE (GLuint); +GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint); +GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint); +GLAPI void APIENTRY glFinishFenceAPPLE (GLuint); +GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint); +GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); +typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name); +typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); +#endif + +#ifndef GL_APPLE_vertex_array_object +#define GL_APPLE_vertex_array_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint); +GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *); +GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); +#endif + +#ifndef GL_APPLE_vertex_array_range +#define GL_APPLE_vertex_array_range 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *); +GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *); +GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); +typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param); +#endif + +#ifndef GL_APPLE_ycbcr_422 +#define GL_APPLE_ycbcr_422 1 +#endif + +#ifndef GL_S3_s3tc +#define GL_S3_s3tc 1 +#endif + +#ifndef GL_ATI_draw_buffers +#define GL_ATI_draw_buffers 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); +#endif + +#ifndef GL_ATI_pixel_format_float +#define GL_ATI_pixel_format_float 1 +/* This is really a WGL extension, but defines some associated GL enums. + * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string. + */ +#endif + +#ifndef GL_ATI_texture_env_combine3 +#define GL_ATI_texture_env_combine3 1 +#endif + +#ifndef GL_ATI_texture_float +#define GL_ATI_texture_float 1 +#endif + +#ifndef GL_NV_float_buffer +#define GL_NV_float_buffer 1 +#endif + +#ifndef GL_NV_fragment_program +#define GL_NV_fragment_program 1 +/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */ +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); +GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble); +GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *); +GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *); +GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *); +GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#endif + +#ifndef GL_NV_half_float +#define GL_NV_half_float 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *); +GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *); +GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *); +GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *); +GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *); +GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *); +GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV); +GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *); +GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *); +GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *); +GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *); +GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV); +GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *); +GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *); +GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *); +GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *); +GLAPI void APIENTRY glFogCoordhNV (GLhalfNV); +GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *); +GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *); +GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV); +GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *); +GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV); +GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); +GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *); +GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s); +typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog); +typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +#endif + +#ifndef GL_NV_pixel_data_range +#define GL_NV_pixel_data_range 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *); +GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer); +typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); +#endif + +#ifndef GL_NV_primitive_restart +#define GL_NV_primitive_restart 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveRestartNV (void); +GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); +#endif + +#ifndef GL_NV_texture_expand_normal +#define GL_NV_texture_expand_normal 1 +#endif + +#ifndef GL_NV_vertex_program2 +#define GL_NV_vertex_program2 1 +#endif + +#ifndef GL_ATI_map_object_buffer +#define GL_ATI_map_object_buffer 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint); +GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); +#endif + +#ifndef GL_ATI_separate_stencil +#define GL_ATI_separate_stencil 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum); +GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#endif + +#ifndef GL_ATI_vertex_attrib_array_object +#define GL_ATI_vertex_attrib_array_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint); +GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *); +GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params); +#endif + +#ifndef GL_OES_read_format +#define GL_OES_read_format 1 +#endif + +#ifndef GL_EXT_depth_bounds_test +#define GL_EXT_depth_bounds_test 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); +#endif + +#ifndef GL_EXT_texture_mirror_clamp +#define GL_EXT_texture_mirror_clamp 1 +#endif + +#ifndef GL_EXT_blend_equation_separate +#define GL_EXT_blend_equation_separate 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); +#endif + +#ifndef GL_MESA_pack_invert +#define GL_MESA_pack_invert 1 +#endif + +#ifndef GL_MESA_ycbcr_texture +#define GL_MESA_ycbcr_texture 1 +#endif + +#ifndef GL_EXT_pixel_buffer_object +#define GL_EXT_pixel_buffer_object 1 +#endif + +#ifndef GL_NV_fragment_program_option +#define GL_NV_fragment_program_option 1 +#endif + +#ifndef GL_NV_fragment_program2 +#define GL_NV_fragment_program2 1 +#endif + +#ifndef GL_NV_vertex_program2_option +#define GL_NV_vertex_program2_option 1 +#endif + +#ifndef GL_NV_vertex_program3 +#define GL_NV_vertex_program3 1 +#endif + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint); +GLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint); +GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *); +GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei); +GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *); +GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint); +GLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint); +GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *); +GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *); +GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum); +GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint); +GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint); +GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint); +GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint); +GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *); +GLAPI void APIENTRY glGenerateMipmapEXT (GLenum); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); +#endif + +#ifndef GL_GREMEDY_string_marker +#define GL_GREMEDY_string_marker 1 +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *); +#endif /* GL_GLEXT_PROTOTYPES */ +typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string); +#endif + + +#ifdef __cplusplus +} +#endif + +#endif +#endif /* NO_SDL_GLEXT */ +/*@}*/ diff --git a/other/sdl/include/SDL_platform.h b/other/sdl/include/SDL_platform.h new file mode 100644 index 0000000..11d8673 --- /dev/null +++ b/other/sdl/include/SDL_platform.h @@ -0,0 +1,110 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_platform.h + * Try to get a standard set of platform defines + */ + +#ifndef _SDL_platform_h +#define _SDL_platform_h + +#if defined(_AIX) +#undef __AIX__ +#define __AIX__ 1 +#endif +#if defined(__BEOS__) +#undef __BEOS__ +#define __BEOS__ 1 +#endif +#if defined(__HAIKU__) +#undef __HAIKU__ +#define __HAIKU__ 1 +#endif +#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__) +#undef __BSDI__ +#define __BSDI__ 1 +#endif +#if defined(_arch_dreamcast) +#undef __DREAMCAST__ +#define __DREAMCAST__ 1 +#endif +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +#undef __FREEBSD__ +#define __FREEBSD__ 1 +#endif +#if defined(__HAIKU__) +#undef __HAIKU__ +#define __HAIKU__ 1 +#endif +#if defined(hpux) || defined(__hpux) || defined(__hpux__) +#undef __HPUX__ +#define __HPUX__ 1 +#endif +#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE) +#undef __IRIX__ +#define __IRIX__ 1 +#endif +#if defined(linux) || defined(__linux) || defined(__linux__) +#undef __LINUX__ +#define __LINUX__ 1 +#endif +#if defined(__APPLE__) +#undef __MACOSX__ +#define __MACOSX__ 1 +#elif defined(macintosh) +#undef __MACOS__ +#define __MACOS__ 1 +#endif +#if defined(__NetBSD__) +#undef __NETBSD__ +#define __NETBSD__ 1 +#endif +#if defined(__OpenBSD__) +#undef __OPENBSD__ +#define __OPENBSD__ 1 +#endif +#if defined(__OS2__) +#undef __OS2__ +#define __OS2__ 1 +#endif +#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE) +#undef __OSF__ +#define __OSF__ 1 +#endif +#if defined(__QNXNTO__) +#undef __QNXNTO__ +#define __QNXNTO__ 1 +#endif +#if defined(riscos) || defined(__riscos) || defined(__riscos__) +#undef __RISCOS__ +#define __RISCOS__ 1 +#endif +#if defined(__SVR4) +#undef __SOLARIS__ +#define __SOLARIS__ 1 +#endif +#if defined(WIN32) || defined(_WIN32) +#undef __WIN32__ +#define __WIN32__ 1 +#endif + +#endif /* _SDL_platform_h */ diff --git a/other/sdl/include/SDL_quit.h b/other/sdl/include/SDL_quit.h new file mode 100644 index 0000000..6d82e7e --- /dev/null +++ b/other/sdl/include/SDL_quit.h @@ -0,0 +1,55 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_quit.h + * Include file for SDL quit event handling + */ + +#ifndef _SDL_quit_h +#define _SDL_quit_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +/** @file SDL_quit.h + * An SDL_QUITEVENT is generated when the user tries to close the application + * window. If it is ignored or filtered out, the window will remain open. + * If it is not ignored or filtered, it is queued normally and the window + * is allowed to close. When the window is closed, screen updates will + * complete, but have no effect. + * + * SDL_Init() installs signal handlers for SIGINT (keyboard interrupt) + * and SIGTERM (system termination request), if handlers do not already + * exist, that generate SDL_QUITEVENT events as well. There is no way + * to determine the cause of an SDL_QUITEVENT, but setting a signal + * handler in your application will override the default generation of + * quit events for that signal. + */ + +/** @file SDL_quit.h + * There are no functions directly affecting the quit event + */ + +#define SDL_QuitRequested() \ + (SDL_PumpEvents(), SDL_PeepEvents(NULL,0,SDL_PEEKEVENT,SDL_QUITMASK)) + +#endif /* _SDL_quit_h */ diff --git a/other/sdl/include/SDL_rwops.h b/other/sdl/include/SDL_rwops.h new file mode 100644 index 0000000..a450119 --- /dev/null +++ b/other/sdl/include/SDL_rwops.h @@ -0,0 +1,155 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_rwops.h + * This file provides a general interface for SDL to read and write + * data sources. It can easily be extended to files, memory, etc. + */ + +#ifndef _SDL_rwops_h +#define _SDL_rwops_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the read/write operation structure -- very basic */ + +typedef struct SDL_RWops { + /** Seek to 'offset' relative to whence, one of stdio's whence values: + * SEEK_SET, SEEK_CUR, SEEK_END + * Returns the final offset in the data source. + */ + int (SDLCALL *seek)(struct SDL_RWops *context, int offset, int whence); + + /** Read up to 'maxnum' objects each of size 'size' from the data + * source to the area pointed at by 'ptr'. + * Returns the number of objects read, or -1 if the read failed. + */ + int (SDLCALL *read)(struct SDL_RWops *context, void *ptr, int size, int maxnum); + + /** Write exactly 'num' objects each of size 'objsize' from the area + * pointed at by 'ptr' to data source. + * Returns 'num', or -1 if the write failed. + */ + int (SDLCALL *write)(struct SDL_RWops *context, const void *ptr, int size, int num); + + /** Close and free an allocated SDL_FSops structure */ + int (SDLCALL *close)(struct SDL_RWops *context); + + Uint32 type; + union { +#if defined(__WIN32__) && !defined(__SYMBIAN32__) + struct { + int append; + void *h; + struct { + void *data; + int size; + int left; + } buffer; + } win32io; +#endif +#ifdef HAVE_STDIO_H + struct { + int autoclose; + FILE *fp; + } stdio; +#endif + struct { + Uint8 *base; + Uint8 *here; + Uint8 *stop; + } mem; + struct { + void *data1; + } unknown; + } hidden; + +} SDL_RWops; + + +/** @name Functions to create SDL_RWops structures from various data sources */ +/*@{*/ + +extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFile(const char *file, const char *mode); + +#ifdef HAVE_STDIO_H +extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFP(FILE *fp, int autoclose); +#endif + +extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromMem(void *mem, int size); +extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromConstMem(const void *mem, int size); + +extern DECLSPEC SDL_RWops * SDLCALL SDL_AllocRW(void); +extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area); + +/*@}*/ + +/** @name Seek Reference Points */ +/*@{*/ +#define RW_SEEK_SET 0 /**< Seek from the beginning of data */ +#define RW_SEEK_CUR 1 /**< Seek relative to current read point */ +#define RW_SEEK_END 2 /**< Seek relative to the end of data */ +/*@}*/ + +/** @name Macros to easily read and write from an SDL_RWops structure */ +/*@{*/ +#define SDL_RWseek(ctx, offset, whence) (ctx)->seek(ctx, offset, whence) +#define SDL_RWtell(ctx) (ctx)->seek(ctx, 0, RW_SEEK_CUR) +#define SDL_RWread(ctx, ptr, size, n) (ctx)->read(ctx, ptr, size, n) +#define SDL_RWwrite(ctx, ptr, size, n) (ctx)->write(ctx, ptr, size, n) +#define SDL_RWclose(ctx) (ctx)->close(ctx) +/*@}*/ + +/** @name Read an item of the specified endianness and return in native format */ +/*@{*/ +extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops *src); +extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops *src); +extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops *src); +extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops *src); +extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops *src); +extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops *src); +/*@}*/ + +/** @name Write an item of native format to the specified endianness */ +/*@{*/ +extern DECLSPEC int SDLCALL SDL_WriteLE16(SDL_RWops *dst, Uint16 value); +extern DECLSPEC int SDLCALL SDL_WriteBE16(SDL_RWops *dst, Uint16 value); +extern DECLSPEC int SDLCALL SDL_WriteLE32(SDL_RWops *dst, Uint32 value); +extern DECLSPEC int SDLCALL SDL_WriteBE32(SDL_RWops *dst, Uint32 value); +extern DECLSPEC int SDLCALL SDL_WriteLE64(SDL_RWops *dst, Uint64 value); +extern DECLSPEC int SDLCALL SDL_WriteBE64(SDL_RWops *dst, Uint64 value); +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_rwops_h */ diff --git a/other/sdl/include/SDL_stdinc.h b/other/sdl/include/SDL_stdinc.h new file mode 100644 index 0000000..e1f85fb --- /dev/null +++ b/other/sdl/include/SDL_stdinc.h @@ -0,0 +1,620 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_stdinc.h + * This is a general header that includes C language support + */ + +#ifndef _SDL_stdinc_h +#define _SDL_stdinc_h + +#include "SDL_config.h" + + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_STDIO_H +#include <stdio.h> +#endif +#if defined(STDC_HEADERS) +# include <stdlib.h> +# include <stddef.h> +# include <stdarg.h> +#else +# if defined(HAVE_STDLIB_H) +# include <stdlib.h> +# elif defined(HAVE_MALLOC_H) +# include <malloc.h> +# endif +# if defined(HAVE_STDDEF_H) +# include <stddef.h> +# endif +# if defined(HAVE_STDARG_H) +# include <stdarg.h> +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H) +# include <memory.h> +# endif +# include <string.h> +#endif +#ifdef HAVE_STRINGS_H +# include <strings.h> +#endif +#if defined(HAVE_INTTYPES_H) +# include <inttypes.h> +#elif defined(HAVE_STDINT_H) +# include <stdint.h> +#endif +#ifdef HAVE_CTYPE_H +# include <ctype.h> +#endif +#if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) +# include <iconv.h> +#endif + +/** The number of elements in an array */ +#define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) +#define SDL_TABLESIZE(table) SDL_arraysize(table) + +/* Use proper C++ casts when compiled as C++ to be compatible with the option + -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above. */ +#ifdef __cplusplus +#define SDL_reinterpret_cast(type, expression) reinterpret_cast<type>(expression) +#define SDL_static_cast(type, expression) static_cast<type>(expression) +#else +#define SDL_reinterpret_cast(type, expression) ((type)(expression)) +#define SDL_static_cast(type, expression) ((type)(expression)) +#endif + +/** @name Basic data types */ +/*@{*/ +typedef enum { + SDL_FALSE = 0, + SDL_TRUE = 1 +} SDL_bool; + +typedef int8_t Sint8; +typedef uint8_t Uint8; +typedef int16_t Sint16; +typedef uint16_t Uint16; +typedef int32_t Sint32; +typedef uint32_t Uint32; + +#ifdef SDL_HAS_64BIT_TYPE +typedef int64_t Sint64; +#ifndef SYMBIAN32_GCCE +typedef uint64_t Uint64; +#endif +#else +/* This is really just a hack to prevent the compiler from complaining */ +typedef struct { + Uint32 hi; + Uint32 lo; +} Uint64, Sint64; +#endif + +/*@}*/ + +/** @name Make sure the types really have the right sizes */ +/*@{*/ +#define SDL_COMPILE_TIME_ASSERT(name, x) \ + typedef int SDL_dummy_ ## name[(x) * 2 - 1] + +SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1); +SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1); +SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2); +SDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2); +SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4); +SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4); +SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8); +SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8); +/*@}*/ + +/** @name Enum Size Check + * Check to make sure enums are the size of ints, for structure packing. + * For both Watcom C/C++ and Borland C/C++ the compiler option that makes + * enums having the size of an int must be enabled. + * This is "-b" for Borland C/C++ and "-ei" for Watcom C/C++ (v11). + */ +/* Enable enums always int in CodeWarrior (for MPW use "-enum int") */ +#ifdef __MWERKS__ +#pragma enumsalwaysint on +#endif + +typedef enum { + DUMMY_ENUM_VALUE +} SDL_DUMMY_ENUM; + +#ifndef __NDS__ +SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int)); +#endif +/*@}*/ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HAVE_MALLOC +#define SDL_malloc malloc +#else +extern DECLSPEC void * SDLCALL SDL_malloc(size_t size); +#endif + +#ifdef HAVE_CALLOC +#define SDL_calloc calloc +#else +extern DECLSPEC void * SDLCALL SDL_calloc(size_t nmemb, size_t size); +#endif + +#ifdef HAVE_REALLOC +#define SDL_realloc realloc +#else +extern DECLSPEC void * SDLCALL SDL_realloc(void *mem, size_t size); +#endif + +#ifdef HAVE_FREE +#define SDL_free free +#else +extern DECLSPEC void SDLCALL SDL_free(void *mem); +#endif + +#if defined(HAVE_ALLOCA) && !defined(alloca) +# if defined(HAVE_ALLOCA_H) +# include <alloca.h> +# elif defined(__GNUC__) +# define alloca __builtin_alloca +# elif defined(_MSC_VER) +# include <malloc.h> +# define alloca _alloca +# elif defined(__WATCOMC__) +# include <malloc.h> +# elif defined(__BORLANDC__) +# include <malloc.h> +# elif defined(__DMC__) +# include <stdlib.h> +# elif defined(__AIX__) + #pragma alloca +# elif defined(__MRC__) + void *alloca (unsigned); +# else + char *alloca (); +# endif +#endif +#ifdef HAVE_ALLOCA +#define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count)) +#define SDL_stack_free(data) +#else +#define SDL_stack_alloc(type, count) (type*)SDL_malloc(sizeof(type)*(count)) +#define SDL_stack_free(data) SDL_free(data) +#endif + +#ifdef HAVE_GETENV +#define SDL_getenv getenv +#else +extern DECLSPEC char * SDLCALL SDL_getenv(const char *name); +#endif + +#ifdef HAVE_PUTENV +#define SDL_putenv putenv +#else +extern DECLSPEC int SDLCALL SDL_putenv(const char *variable); +#endif + +#ifdef HAVE_QSORT +#define SDL_qsort qsort +#else +extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, + int (*compare)(const void *, const void *)); +#endif + +#ifdef HAVE_ABS +#define SDL_abs abs +#else +#define SDL_abs(X) ((X) < 0 ? -(X) : (X)) +#endif + +#define SDL_min(x, y) (((x) < (y)) ? (x) : (y)) +#define SDL_max(x, y) (((x) > (y)) ? (x) : (y)) + +#ifdef HAVE_CTYPE_H +#define SDL_isdigit(X) isdigit(X) +#define SDL_isspace(X) isspace(X) +#define SDL_toupper(X) toupper(X) +#define SDL_tolower(X) tolower(X) +#else +#define SDL_isdigit(X) (((X) >= '0') && ((X) <= '9')) +#define SDL_isspace(X) (((X) == ' ') || ((X) == '\t') || ((X) == '\r') || ((X) == '\n')) +#define SDL_toupper(X) (((X) >= 'a') && ((X) <= 'z') ? ('A'+((X)-'a')) : (X)) +#define SDL_tolower(X) (((X) >= 'A') && ((X) <= 'Z') ? ('a'+((X)-'A')) : (X)) +#endif + +#ifdef HAVE_MEMSET +#define SDL_memset memset +#else +extern DECLSPEC void * SDLCALL SDL_memset(void *dst, int c, size_t len); +#endif + +#if defined(__GNUC__) && defined(i386) +#define SDL_memset4(dst, val, len) \ +do { \ + int u0, u1, u2; \ + __asm__ __volatile__ ( \ + "cld\n\t" \ + "rep ; stosl\n\t" \ + : "=&D" (u0), "=&a" (u1), "=&c" (u2) \ + : "0" (dst), "1" (val), "2" (SDL_static_cast(Uint32, len)) \ + : "memory" ); \ +} while(0) +#endif +#ifndef SDL_memset4 +#define SDL_memset4(dst, val, len) \ +do { \ + unsigned _count = (len); \ + unsigned _n = (_count + 3) / 4; \ + Uint32 *_p = SDL_static_cast(Uint32 *, dst); \ + Uint32 _val = (val); \ + if (len == 0) break; \ + switch (_count % 4) { \ + case 0: do { *_p++ = _val; \ + case 3: *_p++ = _val; \ + case 2: *_p++ = _val; \ + case 1: *_p++ = _val; \ + } while ( --_n ); \ + } \ +} while(0) +#endif + +/* We can count on memcpy existing on Mac OS X and being well-tuned. */ +#if defined(__MACH__) && defined(__APPLE__) +#define SDL_memcpy(dst, src, len) memcpy(dst, src, len) +#elif defined(__GNUC__) && defined(i386) +#define SDL_memcpy(dst, src, len) \ +do { \ + int u0, u1, u2; \ + __asm__ __volatile__ ( \ + "cld\n\t" \ + "rep ; movsl\n\t" \ + "testb $2,%b4\n\t" \ + "je 1f\n\t" \ + "movsw\n" \ + "1:\ttestb $1,%b4\n\t" \ + "je 2f\n\t" \ + "movsb\n" \ + "2:" \ + : "=&c" (u0), "=&D" (u1), "=&S" (u2) \ + : "0" (SDL_static_cast(unsigned, len)/4), "q" (len), "1" (dst),"2" (src) \ + : "memory" ); \ +} while(0) +#endif +#ifndef SDL_memcpy +#ifdef HAVE_MEMCPY +#define SDL_memcpy memcpy +#elif defined(HAVE_BCOPY) +#define SDL_memcpy(d, s, n) bcopy((s), (d), (n)) +#else +extern DECLSPEC void * SDLCALL SDL_memcpy(void *dst, const void *src, size_t len); +#endif +#endif + +/* We can count on memcpy existing on Mac OS X and being well-tuned. */ +#if defined(__MACH__) && defined(__APPLE__) +#define SDL_memcpy4(dst, src, len) memcpy(dst, src, (len)*4) +#elif defined(__GNUC__) && defined(i386) +#define SDL_memcpy4(dst, src, len) \ +do { \ + int ecx, edi, esi; \ + __asm__ __volatile__ ( \ + "cld\n\t" \ + "rep ; movsl" \ + : "=&c" (ecx), "=&D" (edi), "=&S" (esi) \ + : "0" (SDL_static_cast(unsigned, len)), "1" (dst), "2" (src) \ + : "memory" ); \ +} while(0) +#endif +#ifndef SDL_memcpy4 +#define SDL_memcpy4(dst, src, len) SDL_memcpy(dst, src, (len) << 2) +#endif + +#if defined(__GNUC__) && defined(i386) +#define SDL_revcpy(dst, src, len) \ +do { \ + int u0, u1, u2; \ + char *dstp = SDL_static_cast(char *, dst); \ + char *srcp = SDL_static_cast(char *, src); \ + int n = (len); \ + if ( n >= 4 ) { \ + __asm__ __volatile__ ( \ + "std\n\t" \ + "rep ; movsl\n\t" \ + "cld\n\t" \ + : "=&c" (u0), "=&D" (u1), "=&S" (u2) \ + : "0" (n >> 2), \ + "1" (dstp+(n-4)), "2" (srcp+(n-4)) \ + : "memory" ); \ + } \ + switch (n & 3) { \ + case 3: dstp[2] = srcp[2]; \ + case 2: dstp[1] = srcp[1]; \ + case 1: dstp[0] = srcp[0]; \ + break; \ + default: \ + break; \ + } \ +} while(0) +#endif +#ifndef SDL_revcpy +extern DECLSPEC void * SDLCALL SDL_revcpy(void *dst, const void *src, size_t len); +#endif + +#ifdef HAVE_MEMMOVE +#define SDL_memmove memmove +#elif defined(HAVE_BCOPY) +#define SDL_memmove(d, s, n) bcopy((s), (d), (n)) +#else +#define SDL_memmove(dst, src, len) \ +do { \ + if ( dst < src ) { \ + SDL_memcpy(dst, src, len); \ + } else { \ + SDL_revcpy(dst, src, len); \ + } \ +} while(0) +#endif + +#ifdef HAVE_MEMCMP +#define SDL_memcmp memcmp +#else +extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len); +#endif + +#ifdef HAVE_STRLEN +#define SDL_strlen strlen +#else +extern DECLSPEC size_t SDLCALL SDL_strlen(const char *string); +#endif + +#ifdef HAVE_STRLCPY +#define SDL_strlcpy strlcpy +#else +extern DECLSPEC size_t SDLCALL SDL_strlcpy(char *dst, const char *src, size_t maxlen); +#endif + +#ifdef HAVE_STRLCAT +#define SDL_strlcat strlcat +#else +extern DECLSPEC size_t SDLCALL SDL_strlcat(char *dst, const char *src, size_t maxlen); +#endif + +#ifdef HAVE_STRDUP +#define SDL_strdup strdup +#else +extern DECLSPEC char * SDLCALL SDL_strdup(const char *string); +#endif + +#ifdef HAVE__STRREV +#define SDL_strrev _strrev +#else +extern DECLSPEC char * SDLCALL SDL_strrev(char *string); +#endif + +#ifdef HAVE__STRUPR +#define SDL_strupr _strupr +#else +extern DECLSPEC char * SDLCALL SDL_strupr(char *string); +#endif + +#ifdef HAVE__STRLWR +#define SDL_strlwr _strlwr +#else +extern DECLSPEC char * SDLCALL SDL_strlwr(char *string); +#endif + +#ifdef HAVE_STRCHR +#define SDL_strchr strchr +#elif defined(HAVE_INDEX) +#define SDL_strchr index +#else +extern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c); +#endif + +#ifdef HAVE_STRRCHR +#define SDL_strrchr strrchr +#elif defined(HAVE_RINDEX) +#define SDL_strrchr rindex +#else +extern DECLSPEC char * SDLCALL SDL_strrchr(const char *string, int c); +#endif + +#ifdef HAVE_STRSTR +#define SDL_strstr strstr +#else +extern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle); +#endif + +#ifdef HAVE_ITOA +#define SDL_itoa itoa +#else +#define SDL_itoa(value, string, radix) SDL_ltoa((long)value, string, radix) +#endif + +#ifdef HAVE__LTOA +#define SDL_ltoa _ltoa +#else +extern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix); +#endif + +#ifdef HAVE__UITOA +#define SDL_uitoa _uitoa +#else +#define SDL_uitoa(value, string, radix) SDL_ultoa((long)value, string, radix) +#endif + +#ifdef HAVE__ULTOA +#define SDL_ultoa _ultoa +#else +extern DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *string, int radix); +#endif + +#ifdef HAVE_STRTOL +#define SDL_strtol strtol +#else +extern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, int base); +#endif + +#ifdef HAVE_STRTOUL +#define SDL_strtoul strtoul +#else +extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, char **endp, int base); +#endif + +#ifdef SDL_HAS_64BIT_TYPE + +#ifdef HAVE__I64TOA +#define SDL_lltoa _i64toa +#else +extern DECLSPEC char* SDLCALL SDL_lltoa(Sint64 value, char *string, int radix); +#endif + +#ifdef HAVE__UI64TOA +#define SDL_ulltoa _ui64toa +#else +extern DECLSPEC char* SDLCALL SDL_ulltoa(Uint64 value, char *string, int radix); +#endif + +#ifdef HAVE_STRTOLL +#define SDL_strtoll strtoll +#else +extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, int base); +#endif + +#ifdef HAVE_STRTOULL +#define SDL_strtoull strtoull +#else +extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *string, char **endp, int base); +#endif + +#endif /* SDL_HAS_64BIT_TYPE */ + +#ifdef HAVE_STRTOD +#define SDL_strtod strtod +#else +extern DECLSPEC double SDLCALL SDL_strtod(const char *string, char **endp); +#endif + +#ifdef HAVE_ATOI +#define SDL_atoi atoi +#else +#define SDL_atoi(X) SDL_strtol(X, NULL, 0) +#endif + +#ifdef HAVE_ATOF +#define SDL_atof atof +#else +#define SDL_atof(X) SDL_strtod(X, NULL) +#endif + +#ifdef HAVE_STRCMP +#define SDL_strcmp strcmp +#else +extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2); +#endif + +#ifdef HAVE_STRNCMP +#define SDL_strncmp strncmp +#else +extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen); +#endif + +#ifdef HAVE_STRCASECMP +#define SDL_strcasecmp strcasecmp +#elif defined(HAVE__STRICMP) +#define SDL_strcasecmp _stricmp +#else +extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); +#endif + +#ifdef HAVE_STRNCASECMP +#define SDL_strncasecmp strncasecmp +#elif defined(HAVE__STRNICMP) +#define SDL_strncasecmp _strnicmp +#else +extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen); +#endif + +#ifdef HAVE_SSCANF +#define SDL_sscanf sscanf +#else +extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, ...); +#endif + +#ifdef HAVE_SNPRINTF +#define SDL_snprintf snprintf +#else +extern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...); +#endif + +#ifdef HAVE_VSNPRINTF +#define SDL_vsnprintf vsnprintf +#else +extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap); +#endif + +/** @name SDL_ICONV Error Codes + * The SDL implementation of iconv() returns these error codes + */ +/*@{*/ +#define SDL_ICONV_ERROR (size_t)-1 +#define SDL_ICONV_E2BIG (size_t)-2 +#define SDL_ICONV_EILSEQ (size_t)-3 +#define SDL_ICONV_EINVAL (size_t)-4 +/*@}*/ + +#if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) +#define SDL_iconv_t iconv_t +#define SDL_iconv_open iconv_open +#define SDL_iconv_close iconv_close +#else +typedef struct _SDL_iconv_t *SDL_iconv_t; +extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, const char *fromcode); +extern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd); +#endif +extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); +/** This function converts a string between encodings in one pass, returning a + * string that must be freed with SDL_free() or NULL on error. + */ +extern DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, const char *fromcode, const char *inbuf, size_t inbytesleft); +#define SDL_iconv_utf8_locale(S) SDL_iconv_string("", "UTF-8", S, SDL_strlen(S)+1) +#define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2", "UTF-8", S, SDL_strlen(S)+1) +#define SDL_iconv_utf8_ucs4(S) (Uint32 *)SDL_iconv_string("UCS-4", "UTF-8", S, SDL_strlen(S)+1) + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_stdinc_h */ diff --git a/other/sdl/include/SDL_syswm.h b/other/sdl/include/SDL_syswm.h new file mode 100644 index 0000000..716dddc --- /dev/null +++ b/other/sdl/include/SDL_syswm.h @@ -0,0 +1,225 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_syswm.h + * Include file for SDL custom system window manager hooks + */ + +#ifndef _SDL_syswm_h +#define _SDL_syswm_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_version.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @file SDL_syswm.h + * Your application has access to a special type of event 'SDL_SYSWMEVENT', + * which contains window-manager specific information and arrives whenever + * an unhandled window event occurs. This event is ignored by default, but + * you can enable it with SDL_EventState() + */ +#ifdef SDL_PROTOTYPES_ONLY +struct SDL_SysWMinfo; +typedef struct SDL_SysWMinfo SDL_SysWMinfo; +#else + +/* This is the structure for custom window manager events */ +#if defined(SDL_VIDEO_DRIVER_X11) +#if defined(__APPLE__) && defined(__MACH__) +/* conflicts with Quickdraw.h */ +#define Cursor X11Cursor +#endif + +#include <X11/Xlib.h> +#include <X11/Xatom.h> + +#if defined(__APPLE__) && defined(__MACH__) +/* matches the re-define above */ +#undef Cursor +#endif + +/** These are the various supported subsystems under UNIX */ +typedef enum { + SDL_SYSWM_X11 +} SDL_SYSWM_TYPE; + +/** The UNIX custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union { + XEvent xevent; + } event; +}; + +/** The UNIX custom window manager information structure. + * When this structure is returned, it holds information about which + * low level system it is using, and will be one of SDL_SYSWM_TYPE. + */ +typedef struct SDL_SysWMinfo { + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union { + struct { + Display *display; /**< The X11 display */ + Window window; /**< The X11 display window */ + /** These locking functions should be called around + * any X11 functions using the display variable, + * but not the gfxdisplay variable. + * They lock the event thread, so should not be + * called around event functions or from event filters. + */ + /*@{*/ + void (*lock_func)(void); + void (*unlock_func)(void); + /*@}*/ + + /** @name Introduced in SDL 1.0.2 */ + /*@{*/ + Window fswindow; /**< The X11 fullscreen window */ + Window wmwindow; /**< The X11 managed input window */ + /*@}*/ + + /** @name Introduced in SDL 1.2.12 */ + /*@{*/ + Display *gfxdisplay; /**< The X11 display to which rendering is done */ + /*@}*/ + } x11; + } info; +} SDL_SysWMinfo; + +#elif defined(SDL_VIDEO_DRIVER_NANOX) +#include <microwin/nano-X.h> + +/** The generic custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + int data; +}; + +/** The windows custom window manager information structure */ +typedef struct SDL_SysWMinfo { + SDL_version version ; + GR_WINDOW_ID window ; /* The display window */ +} SDL_SysWMinfo; + +#elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI) +#define WIN32_LEAN_AND_MEAN +#include <windows.h> + +/** The windows custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + HWND hwnd; /**< The window for the message */ + UINT msg; /**< The type of message */ + WPARAM wParam; /**< WORD message parameter */ + LPARAM lParam; /**< LONG message parameter */ +}; + +/** The windows custom window manager information structure */ +typedef struct SDL_SysWMinfo { + SDL_version version; + HWND window; /**< The Win32 display window */ + HGLRC hglrc; /**< The OpenGL context, if any */ +} SDL_SysWMinfo; + +#elif defined(SDL_VIDEO_DRIVER_RISCOS) + +/** RISC OS custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + int eventCode; /**< The window for the message */ + int pollBlock[64]; +}; + +/** The RISC OS custom window manager information structure */ +typedef struct SDL_SysWMinfo { + SDL_version version; + int wimpVersion; /**< Wimp version running under */ + int taskHandle; /**< The RISC OS task handle */ + int window; /**< The RISC OS display window */ +} SDL_SysWMinfo; + +#elif defined(SDL_VIDEO_DRIVER_PHOTON) +#include <sys/neutrino.h> +#include <Ph.h> + +/** The QNX custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + int data; +}; + +/** The QNX custom window manager information structure */ +typedef struct SDL_SysWMinfo { + SDL_version version; + int data; +} SDL_SysWMinfo; + +#else + +/** The generic custom event structure */ +struct SDL_SysWMmsg { + SDL_version version; + int data; +}; + +/** The generic custom window manager information structure */ +typedef struct SDL_SysWMinfo { + SDL_version version; + int data; +} SDL_SysWMinfo; + +#endif /* video driver type */ + +#endif /* SDL_PROTOTYPES_ONLY */ + +/* Function prototypes */ +/** + * This function gives you custom hooks into the window manager information. + * It fills the structure pointed to by 'info' with custom information and + * returns 1 if the function is implemented. If it's not implemented, or + * the version member of the 'info' structure is invalid, it returns 0. + * + * You typically use this function like this: + * @code + * SDL_SysWMInfo info; + * SDL_VERSION(&info.version); + * if ( SDL_GetWMInfo(&info) ) { ... } + * @endcode + */ +extern DECLSPEC int SDLCALL SDL_GetWMInfo(SDL_SysWMinfo *info); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_syswm_h */ diff --git a/other/sdl/include/SDL_thread.h b/other/sdl/include/SDL_thread.h new file mode 100644 index 0000000..1ca9a1b --- /dev/null +++ b/other/sdl/include/SDL_thread.h @@ -0,0 +1,120 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_thread_h +#define _SDL_thread_h + +/** @file SDL_thread.h + * Header for the SDL thread management routines + * + * @note These are independent of the other SDL routines. + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +/* Thread synchronization primitives */ +#include "SDL_mutex.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** The SDL thread structure, defined in SDL_thread.c */ +struct SDL_Thread; +typedef struct SDL_Thread SDL_Thread; + +/** Create a thread */ +#if ((defined(__WIN32__) && !defined(HAVE_LIBC)) || defined(__OS2__)) && !defined(__SYMBIAN32__) +/** + * We compile SDL into a DLL on OS/2. This means, that it's the DLL which + * creates a new thread for the calling process with the SDL_CreateThread() + * API. There is a problem with this, that only the RTL of the SDL.DLL will + * be initialized for those threads, and not the RTL of the calling application! + * To solve this, we make a little hack here. + * We'll always use the caller's _beginthread() and _endthread() APIs to + * start a new thread. This way, if it's the SDL.DLL which uses this API, + * then the RTL of SDL.DLL will be used to create the new thread, and if it's + * the application, then the RTL of the application will be used. + * So, in short: + * Always use the _beginthread() and _endthread() of the calling runtime library! + */ +#define SDL_PASSED_BEGINTHREAD_ENDTHREAD +#ifndef _WIN32_WCE +#include <process.h> /* This has _beginthread() and _endthread() defined! */ +#endif + +#ifdef __OS2__ +typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void *arg); +typedef void (*pfnSDL_CurrentEndThread)(void); +#elif __GNUC__ +typedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned (__stdcall *func)(void *), void *arg, + unsigned, unsigned *threadID); +typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +#else +typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, + unsigned (__stdcall *func)(void *), void *arg, + unsigned, unsigned *threadID); +typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); +#endif + +extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); + +#ifdef __OS2__ +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthread, _endthread) +#elif defined(_WIN32_WCE) +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, NULL, NULL) +#else +#define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthreadex, _endthreadex) +#endif +#else +extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data); +#endif + +/** Get the 32-bit thread identifier for the current thread */ +extern DECLSPEC Uint32 SDLCALL SDL_ThreadID(void); + +/** Get the 32-bit thread identifier for the specified thread, + * equivalent to SDL_ThreadID() if the specified thread is NULL. + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetThreadID(SDL_Thread *thread); + +/** Wait for a thread to finish. + * The return code for the thread function is placed in the area + * pointed to by 'status', if 'status' is not NULL. + */ +extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status); + +/** Forcefully kill a thread without worrying about its state */ +extern DECLSPEC void SDLCALL SDL_KillThread(SDL_Thread *thread); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_thread_h */ diff --git a/other/sdl/include/SDL_timer.h b/other/sdl/include/SDL_timer.h new file mode 100644 index 0000000..d7cd024 --- /dev/null +++ b/other/sdl/include/SDL_timer.h @@ -0,0 +1,125 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_timer_h +#define _SDL_timer_h + +/** @file SDL_timer.h + * Header for the SDL time management routines + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the OS scheduler timeslice, in milliseconds */ +#define SDL_TIMESLICE 10 + +/** This is the maximum resolution of the SDL timer on all platforms */ +#define TIMER_RESOLUTION 10 /**< Experimentally determined */ + +/** + * Get the number of milliseconds since the SDL library initialization. + * Note that this value wraps if the program runs for more than ~49 days. + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); + +/** Wait a specified number of milliseconds before returning */ +extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); + +/** Function prototype for the timer callback function */ +typedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval); + +/** + * Set a callback to run after the specified number of milliseconds has + * elapsed. The callback function is passed the current timer interval + * and returns the next timer interval. If the returned value is the + * same as the one passed in, the periodic alarm continues, otherwise a + * new alarm is scheduled. If the callback returns 0, the periodic alarm + * is cancelled. + * + * To cancel a currently running timer, call SDL_SetTimer(0, NULL); + * + * The timer callback function may run in a different thread than your + * main code, and so shouldn't call any functions from within itself. + * + * The maximum resolution of this timer is 10 ms, which means that if + * you request a 16 ms timer, your callback will run approximately 20 ms + * later on an unloaded system. If you wanted to set a flag signaling + * a frame update at 30 frames per second (every 33 ms), you might set a + * timer for 30 ms: + * @code SDL_SetTimer((33/10)*10, flag_update); @endcode + * + * If you use this function, you need to pass SDL_INIT_TIMER to SDL_Init(). + * + * Under UNIX, you should not use raise or use SIGALRM and this function + * in the same program, as it is implemented using setitimer(). You also + * should not use this function in multi-threaded applications as signals + * to multi-threaded apps have undefined behavior in some implementations. + * + * This function returns 0 if successful, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback); + +/** @name New timer API + * New timer API, supports multiple timers + * Written by Stephane Peter <megastep@lokigames.com> + */ +/*@{*/ + +/** + * Function prototype for the new timer callback function. + * The callback function is passed the current timer interval and returns + * the next timer interval. If the returned value is the same as the one + * passed in, the periodic alarm continues, otherwise a new alarm is + * scheduled. If the callback returns 0, the periodic alarm is cancelled. + */ +typedef Uint32 (SDLCALL *SDL_NewTimerCallback)(Uint32 interval, void *param); + +/** Definition of the timer ID type */ +typedef struct _SDL_TimerID *SDL_TimerID; + +/** Add a new timer to the pool of timers already running. + * Returns a timer ID, or NULL when an error occurs. + */ +extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param); + +/** + * Remove one of the multiple timers knowing its ID. + * Returns a boolean value indicating success. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID t); + +/*@}*/ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_timer_h */ diff --git a/other/sdl/include/SDL_types.h b/other/sdl/include/SDL_types.h new file mode 100644 index 0000000..cfa3523 --- /dev/null +++ b/other/sdl/include/SDL_types.h @@ -0,0 +1,28 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_types.h + * @deprecated Use SDL_stdinc.h instead. + */ + +/* DEPRECATED */ +#include "SDL_stdinc.h" diff --git a/other/sdl/include/SDL_version.h b/other/sdl/include/SDL_version.h new file mode 100644 index 0000000..fa02c3f --- /dev/null +++ b/other/sdl/include/SDL_version.h @@ -0,0 +1,91 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_version.h + * This header defines the current SDL version + */ + +#ifndef _SDL_version_h +#define _SDL_version_h + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @name Version Number + * Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL + */ +/*@{*/ +#define SDL_MAJOR_VERSION 1 +#define SDL_MINOR_VERSION 2 +#define SDL_PATCHLEVEL 14 +/*@}*/ + +typedef struct SDL_version { + Uint8 major; + Uint8 minor; + Uint8 patch; +} SDL_version; + +/** + * This macro can be used to fill a version structure with the compile-time + * version of the SDL library. + */ +#define SDL_VERSION(X) \ +{ \ + (X)->major = SDL_MAJOR_VERSION; \ + (X)->minor = SDL_MINOR_VERSION; \ + (X)->patch = SDL_PATCHLEVEL; \ +} + +/** This macro turns the version numbers into a numeric value: + * (1,2,3) -> (1203) + * This assumes that there will never be more than 100 patchlevels + */ +#define SDL_VERSIONNUM(X, Y, Z) \ + ((X)*1000 + (Y)*100 + (Z)) + +/** This is the version number macro for the current SDL version */ +#define SDL_COMPILEDVERSION \ + SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL) + +/** This macro will evaluate to true if compiled with SDL at least X.Y.Z */ +#define SDL_VERSION_ATLEAST(X, Y, Z) \ + (SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) + +/** This function gets the version of the dynamically linked SDL library. + * it should NOT be used to fill a version structure, instead you should + * use the SDL_Version() macro. + */ +extern DECLSPEC const SDL_version * SDLCALL SDL_Linked_Version(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_version_h */ diff --git a/other/sdl/include/SDL_video.h b/other/sdl/include/SDL_video.h new file mode 100644 index 0000000..8f7f305 --- /dev/null +++ b/other/sdl/include/SDL_video.h @@ -0,0 +1,951 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** @file SDL_video.h + * Header file for access to the SDL raw framebuffer window + */ + +#ifndef _SDL_video_h +#define _SDL_video_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_rwops.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** @name Transparency definitions + * These define alpha as the opacity of a surface + */ +/*@{*/ +#define SDL_ALPHA_OPAQUE 255 +#define SDL_ALPHA_TRANSPARENT 0 +/*@}*/ + +/** @name Useful data types */ +/*@{*/ +typedef struct SDL_Rect { + Sint16 x, y; + Uint16 w, h; +} SDL_Rect; + +typedef struct SDL_Color { + Uint8 r; + Uint8 g; + Uint8 b; + Uint8 unused; +} SDL_Color; +#define SDL_Colour SDL_Color + +typedef struct SDL_Palette { + int ncolors; + SDL_Color *colors; +} SDL_Palette; +/*@}*/ + +/** Everything in the pixel format structure is read-only */ +typedef struct SDL_PixelFormat { + SDL_Palette *palette; + Uint8 BitsPerPixel; + Uint8 BytesPerPixel; + Uint8 Rloss; + Uint8 Gloss; + Uint8 Bloss; + Uint8 Aloss; + Uint8 Rshift; + Uint8 Gshift; + Uint8 Bshift; + Uint8 Ashift; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + Uint32 Amask; + + /** RGB color key information */ + Uint32 colorkey; + /** Alpha value information (per-surface alpha) */ + Uint8 alpha; +} SDL_PixelFormat; + +/** This structure should be treated as read-only, except for 'pixels', + * which, if not NULL, contains the raw pixel data for the surface. + */ +typedef struct SDL_Surface { + Uint32 flags; /**< Read-only */ + SDL_PixelFormat *format; /**< Read-only */ + int w, h; /**< Read-only */ + Uint16 pitch; /**< Read-only */ + void *pixels; /**< Read-write */ + int offset; /**< Private */ + + /** Hardware-specific surface info */ + struct private_hwdata *hwdata; + + /** clipping information */ + SDL_Rect clip_rect; /**< Read-only */ + Uint32 unused1; /**< for binary compatibility */ + + /** Allow recursive locks */ + Uint32 locked; /**< Private */ + + /** info for fast blit mapping to other surfaces */ + struct SDL_BlitMap *map; /**< Private */ + + /** format version, bumped at every change to invalidate blit maps */ + unsigned int format_version; /**< Private */ + + /** Reference count -- used when freeing surface */ + int refcount; /**< Read-mostly */ +} SDL_Surface; + +/** @name SDL_Surface Flags + * These are the currently supported flags for the SDL_surface + */ +/*@{*/ + +/** Available for SDL_CreateRGBSurface() or SDL_SetVideoMode() */ +/*@{*/ +#define SDL_SWSURFACE 0x00000000 /**< Surface is in system memory */ +#define SDL_HWSURFACE 0x00000001 /**< Surface is in video memory */ +#define SDL_ASYNCBLIT 0x00000004 /**< Use asynchronous blits if possible */ +/*@}*/ + +/** Available for SDL_SetVideoMode() */ +/*@{*/ +#define SDL_ANYFORMAT 0x10000000 /**< Allow any video depth/pixel-format */ +#define SDL_HWPALETTE 0x20000000 /**< Surface has exclusive palette */ +#define SDL_DOUBLEBUF 0x40000000 /**< Set up double-buffered video mode */ +#define SDL_FULLSCREEN 0x80000000 /**< Surface is a full screen display */ +#define SDL_OPENGL 0x00000002 /**< Create an OpenGL rendering context */ +#define SDL_OPENGLBLIT 0x0000000A /**< Create an OpenGL rendering context and use it for blitting */ +#define SDL_RESIZABLE 0x00000010 /**< This video mode may be resized */ +#define SDL_NOFRAME 0x00000020 /**< No window caption or edge frame */ +/*@}*/ + +/** Used internally (read-only) */ +/*@{*/ +#define SDL_HWACCEL 0x00000100 /**< Blit uses hardware acceleration */ +#define SDL_SRCCOLORKEY 0x00001000 /**< Blit uses a source color key */ +#define SDL_RLEACCELOK 0x00002000 /**< Private flag */ +#define SDL_RLEACCEL 0x00004000 /**< Surface is RLE encoded */ +#define SDL_SRCALPHA 0x00010000 /**< Blit uses source alpha blending */ +#define SDL_PREALLOC 0x01000000 /**< Surface uses preallocated memory */ +/*@}*/ + +/*@}*/ + +/** Evaluates to true if the surface needs to be locked before access */ +#define SDL_MUSTLOCK(surface) \ + (surface->offset || \ + ((surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_RLEACCEL)) != 0)) + +/** typedef for private surface blitting functions */ +typedef int (*SDL_blit)(struct SDL_Surface *src, SDL_Rect *srcrect, + struct SDL_Surface *dst, SDL_Rect *dstrect); + + +/** Useful for determining the video hardware capabilities */ +typedef struct SDL_VideoInfo { + Uint32 hw_available :1; /**< Flag: Can you create hardware surfaces? */ + Uint32 wm_available :1; /**< Flag: Can you talk to a window manager? */ + Uint32 UnusedBits1 :6; + Uint32 UnusedBits2 :1; + Uint32 blit_hw :1; /**< Flag: Accelerated blits HW --> HW */ + Uint32 blit_hw_CC :1; /**< Flag: Accelerated blits with Colorkey */ + Uint32 blit_hw_A :1; /**< Flag: Accelerated blits with Alpha */ + Uint32 blit_sw :1; /**< Flag: Accelerated blits SW --> HW */ + Uint32 blit_sw_CC :1; /**< Flag: Accelerated blits with Colorkey */ + Uint32 blit_sw_A :1; /**< Flag: Accelerated blits with Alpha */ + Uint32 blit_fill :1; /**< Flag: Accelerated color fill */ + Uint32 UnusedBits3 :16; + Uint32 video_mem; /**< The total amount of video memory (in K) */ + SDL_PixelFormat *vfmt; /**< Value: The format of the video surface */ + int current_w; /**< Value: The current video mode width */ + int current_h; /**< Value: The current video mode height */ +} SDL_VideoInfo; + + +/** @name Overlay Formats + * The most common video overlay formats. + * For an explanation of these pixel formats, see: + * http://www.webartz.com/fourcc/indexyuv.htm + * + * For information on the relationship between color spaces, see: + * http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html + */ +/*@{*/ +#define SDL_YV12_OVERLAY 0x32315659 /**< Planar mode: Y + V + U (3 planes) */ +#define SDL_IYUV_OVERLAY 0x56555949 /**< Planar mode: Y + U + V (3 planes) */ +#define SDL_YUY2_OVERLAY 0x32595559 /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */ +#define SDL_UYVY_OVERLAY 0x59565955 /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */ +#define SDL_YVYU_OVERLAY 0x55595659 /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */ +/*@}*/ + +/** The YUV hardware video overlay */ +typedef struct SDL_Overlay { + Uint32 format; /**< Read-only */ + int w, h; /**< Read-only */ + int planes; /**< Read-only */ + Uint16 *pitches; /**< Read-only */ + Uint8 **pixels; /**< Read-write */ + + /** @name Hardware-specific surface info */ + /*@{*/ + struct private_yuvhwfuncs *hwfuncs; + struct private_yuvhwdata *hwdata; + /*@{*/ + + /** @name Special flags */ + /*@{*/ + Uint32 hw_overlay :1; /**< Flag: This overlay hardware accelerated? */ + Uint32 UnusedBits :31; + /*@}*/ +} SDL_Overlay; + + +/** Public enumeration for setting the OpenGL window attributes. */ +typedef enum { + SDL_GL_RED_SIZE, + SDL_GL_GREEN_SIZE, + SDL_GL_BLUE_SIZE, + SDL_GL_ALPHA_SIZE, + SDL_GL_BUFFER_SIZE, + SDL_GL_DOUBLEBUFFER, + SDL_GL_DEPTH_SIZE, + SDL_GL_STENCIL_SIZE, + SDL_GL_ACCUM_RED_SIZE, + SDL_GL_ACCUM_GREEN_SIZE, + SDL_GL_ACCUM_BLUE_SIZE, + SDL_GL_ACCUM_ALPHA_SIZE, + SDL_GL_STEREO, + SDL_GL_MULTISAMPLEBUFFERS, + SDL_GL_MULTISAMPLESAMPLES, + SDL_GL_ACCELERATED_VISUAL, + SDL_GL_SWAP_CONTROL +} SDL_GLattr; + +/** @name flags for SDL_SetPalette() */ +/*@{*/ +#define SDL_LOGPAL 0x01 +#define SDL_PHYSPAL 0x02 +/*@}*/ + +/* Function prototypes */ + +/** + * @name Video Init and Quit + * These functions are used internally, and should not be used unless you + * have a specific need to specify the video driver you want to use. + * You should normally use SDL_Init() or SDL_InitSubSystem(). + */ +/*@{*/ +/** + * Initializes the video subsystem. Sets up a connection + * to the window manager, etc, and determines the current video mode and + * pixel format, but does not initialize a window or graphics mode. + * Note that event handling is activated by this routine. + * + * If you use both sound and video in your application, you need to call + * SDL_Init() before opening the sound device, otherwise under Win32 DirectX, + * you won't be able to set full-screen display modes. + */ +extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name, Uint32 flags); +extern DECLSPEC void SDLCALL SDL_VideoQuit(void); +/*@}*/ + +/** + * This function fills the given character buffer with the name of the + * video driver, and returns a pointer to it if the video driver has + * been initialized. It returns NULL if no driver has been initialized. + */ +extern DECLSPEC char * SDLCALL SDL_VideoDriverName(char *namebuf, int maxlen); + +/** + * This function returns a pointer to the current display surface. + * If SDL is doing format conversion on the display surface, this + * function returns the publicly visible surface, not the real video + * surface. + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_GetVideoSurface(void); + +/** + * This function returns a read-only pointer to information about the + * video hardware. If this is called before SDL_SetVideoMode(), the 'vfmt' + * member of the returned structure will contain the pixel format of the + * "best" video mode. + */ +extern DECLSPEC const SDL_VideoInfo * SDLCALL SDL_GetVideoInfo(void); + +/** + * Check to see if a particular video mode is supported. + * It returns 0 if the requested mode is not supported under any bit depth, + * or returns the bits-per-pixel of the closest available mode with the + * given width and height. If this bits-per-pixel is different from the + * one used when setting the video mode, SDL_SetVideoMode() will succeed, + * but will emulate the requested bits-per-pixel with a shadow surface. + * + * The arguments to SDL_VideoModeOK() are the same ones you would pass to + * SDL_SetVideoMode() + */ +extern DECLSPEC int SDLCALL SDL_VideoModeOK(int width, int height, int bpp, Uint32 flags); + +/** + * Return a pointer to an array of available screen dimensions for the + * given format and video flags, sorted largest to smallest. Returns + * NULL if there are no dimensions available for a particular format, + * or (SDL_Rect **)-1 if any dimension is okay for the given format. + * + * If 'format' is NULL, the mode list will be for the format given + * by SDL_GetVideoInfo()->vfmt + */ +extern DECLSPEC SDL_Rect ** SDLCALL SDL_ListModes(SDL_PixelFormat *format, Uint32 flags); + +/** + * Set up a video mode with the specified width, height and bits-per-pixel. + * + * If 'bpp' is 0, it is treated as the current display bits per pixel. + * + * If SDL_ANYFORMAT is set in 'flags', the SDL library will try to set the + * requested bits-per-pixel, but will return whatever video pixel format is + * available. The default is to emulate the requested pixel format if it + * is not natively available. + * + * If SDL_HWSURFACE is set in 'flags', the video surface will be placed in + * video memory, if possible, and you may have to call SDL_LockSurface() + * in order to access the raw framebuffer. Otherwise, the video surface + * will be created in system memory. + * + * If SDL_ASYNCBLIT is set in 'flags', SDL will try to perform rectangle + * updates asynchronously, but you must always lock before accessing pixels. + * SDL will wait for updates to complete before returning from the lock. + * + * If SDL_HWPALETTE is set in 'flags', the SDL library will guarantee + * that the colors set by SDL_SetColors() will be the colors you get. + * Otherwise, in 8-bit mode, SDL_SetColors() may not be able to set all + * of the colors exactly the way they are requested, and you should look + * at the video surface structure to determine the actual palette. + * If SDL cannot guarantee that the colors you request can be set, + * i.e. if the colormap is shared, then the video surface may be created + * under emulation in system memory, overriding the SDL_HWSURFACE flag. + * + * If SDL_FULLSCREEN is set in 'flags', the SDL library will try to set + * a fullscreen video mode. The default is to create a windowed mode + * if the current graphics system has a window manager. + * If the SDL library is able to set a fullscreen video mode, this flag + * will be set in the surface that is returned. + * + * If SDL_DOUBLEBUF is set in 'flags', the SDL library will try to set up + * two surfaces in video memory and swap between them when you call + * SDL_Flip(). This is usually slower than the normal single-buffering + * scheme, but prevents "tearing" artifacts caused by modifying video + * memory while the monitor is refreshing. It should only be used by + * applications that redraw the entire screen on every update. + * + * If SDL_RESIZABLE is set in 'flags', the SDL library will allow the + * window manager, if any, to resize the window at runtime. When this + * occurs, SDL will send a SDL_VIDEORESIZE event to you application, + * and you must respond to the event by re-calling SDL_SetVideoMode() + * with the requested size (or another size that suits the application). + * + * If SDL_NOFRAME is set in 'flags', the SDL library will create a window + * without any title bar or frame decoration. Fullscreen video modes have + * this flag set automatically. + * + * This function returns the video framebuffer surface, or NULL if it fails. + * + * If you rely on functionality provided by certain video flags, check the + * flags of the returned surface to make sure that functionality is available. + * SDL will fall back to reduced functionality if the exact flags you wanted + * are not available. + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_SetVideoMode + (int width, int height, int bpp, Uint32 flags); + +/** @name SDL_Update Functions + * These functions should not be called while 'screen' is locked. + */ +/*@{*/ +/** + * Makes sure the given list of rectangles is updated on the given screen. + */ +extern DECLSPEC void SDLCALL SDL_UpdateRects + (SDL_Surface *screen, int numrects, SDL_Rect *rects); +/** + * If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire + * screen. + */ +extern DECLSPEC void SDLCALL SDL_UpdateRect + (SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h); +/*@}*/ + +/** + * On hardware that supports double-buffering, this function sets up a flip + * and returns. The hardware will wait for vertical retrace, and then swap + * video buffers before the next video surface blit or lock will return. + * On hardware that doesn not support double-buffering, this is equivalent + * to calling SDL_UpdateRect(screen, 0, 0, 0, 0); + * The SDL_DOUBLEBUF flag must have been passed to SDL_SetVideoMode() when + * setting the video mode for this function to perform hardware flipping. + * This function returns 0 if successful, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_Flip(SDL_Surface *screen); + +/** + * Set the gamma correction for each of the color channels. + * The gamma values range (approximately) between 0.1 and 10.0 + * + * If this function isn't supported directly by the hardware, it will + * be emulated using gamma ramps, if available. If successful, this + * function returns 0, otherwise it returns -1. + */ +extern DECLSPEC int SDLCALL SDL_SetGamma(float red, float green, float blue); + +/** + * Set the gamma translation table for the red, green, and blue channels + * of the video hardware. Each table is an array of 256 16-bit quantities, + * representing a mapping between the input and output for that channel. + * The input is the index into the array, and the output is the 16-bit + * gamma value at that index, scaled to the output color precision. + * + * You may pass NULL for any of the channels to leave it unchanged. + * If the call succeeds, it will return 0. If the display driver or + * hardware does not support gamma translation, or otherwise fails, + * this function will return -1. + */ +extern DECLSPEC int SDLCALL SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue); + +/** + * Retrieve the current values of the gamma translation tables. + * + * You must pass in valid pointers to arrays of 256 16-bit quantities. + * Any of the pointers may be NULL to ignore that channel. + * If the call succeeds, it will return 0. If the display driver or + * hardware does not support gamma translation, or otherwise fails, + * this function will return -1. + */ +extern DECLSPEC int SDLCALL SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue); + +/** + * Sets a portion of the colormap for the given 8-bit surface. If 'surface' + * is not a palettized surface, this function does nothing, returning 0. + * If all of the colors were set as passed to SDL_SetColors(), it will + * return 1. If not all the color entries were set exactly as given, + * it will return 0, and you should look at the surface palette to + * determine the actual color palette. + * + * When 'surface' is the surface associated with the current display, the + * display colormap will be updated with the requested colors. If + * SDL_HWPALETTE was set in SDL_SetVideoMode() flags, SDL_SetColors() + * will always return 1, and the palette is guaranteed to be set the way + * you desire, even if the window colormap has to be warped or run under + * emulation. + */ +extern DECLSPEC int SDLCALL SDL_SetColors(SDL_Surface *surface, + SDL_Color *colors, int firstcolor, int ncolors); + +/** + * Sets a portion of the colormap for a given 8-bit surface. + * 'flags' is one or both of: + * SDL_LOGPAL -- set logical palette, which controls how blits are mapped + * to/from the surface, + * SDL_PHYSPAL -- set physical palette, which controls how pixels look on + * the screen + * Only screens have physical palettes. Separate change of physical/logical + * palettes is only possible if the screen has SDL_HWPALETTE set. + * + * The return value is 1 if all colours could be set as requested, and 0 + * otherwise. + * + * SDL_SetColors() is equivalent to calling this function with + * flags = (SDL_LOGPAL|SDL_PHYSPAL). + */ +extern DECLSPEC int SDLCALL SDL_SetPalette(SDL_Surface *surface, int flags, + SDL_Color *colors, int firstcolor, + int ncolors); + +/** + * Maps an RGB triple to an opaque pixel value for a given pixel format + */ +extern DECLSPEC Uint32 SDLCALL SDL_MapRGB +(const SDL_PixelFormat * const format, + const Uint8 r, const Uint8 g, const Uint8 b); + +/** + * Maps an RGBA quadruple to a pixel value for a given pixel format + */ +extern DECLSPEC Uint32 SDLCALL SDL_MapRGBA +(const SDL_PixelFormat * const format, + const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); + +/** + * Maps a pixel value into the RGB components for a given pixel format + */ +extern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, + const SDL_PixelFormat * const fmt, + Uint8 *r, Uint8 *g, Uint8 *b); + +/** + * Maps a pixel value into the RGBA components for a given pixel format + */ +extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, + const SDL_PixelFormat * const fmt, + Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); + +/** @sa SDL_CreateRGBSurface */ +#define SDL_AllocSurface SDL_CreateRGBSurface +/** + * Allocate and free an RGB surface (must be called after SDL_SetVideoMode) + * If the depth is 4 or 8 bits, an empty palette is allocated for the surface. + * If the depth is greater than 8 bits, the pixel format is set using the + * flags '[RGB]mask'. + * If the function runs out of memory, it will return NULL. + * + * The 'flags' tell what kind of surface to create. + * SDL_SWSURFACE means that the surface should be created in system memory. + * SDL_HWSURFACE means that the surface should be created in video memory, + * with the same format as the display surface. This is useful for surfaces + * that will not change much, to take advantage of hardware acceleration + * when being blitted to the display surface. + * SDL_ASYNCBLIT means that SDL will try to perform asynchronous blits with + * this surface, but you must always lock it before accessing the pixels. + * SDL will wait for current blits to finish before returning from the lock. + * SDL_SRCCOLORKEY indicates that the surface will be used for colorkey blits. + * If the hardware supports acceleration of colorkey blits between + * two surfaces in video memory, SDL will try to place the surface in + * video memory. If this isn't possible or if there is no hardware + * acceleration available, the surface will be placed in system memory. + * SDL_SRCALPHA means that the surface will be used for alpha blits and + * if the hardware supports hardware acceleration of alpha blits between + * two surfaces in video memory, to place the surface in video memory + * if possible, otherwise it will be placed in system memory. + * If the surface is created in video memory, blits will be _much_ faster, + * but the surface format must be identical to the video surface format, + * and the only way to access the pixels member of the surface is to use + * the SDL_LockSurface() and SDL_UnlockSurface() calls. + * If the requested surface actually resides in video memory, SDL_HWSURFACE + * will be set in the flags member of the returned surface. If for some + * reason the surface could not be placed in video memory, it will not have + * the SDL_HWSURFACE flag set, and will be created in system memory instead. + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurface + (Uint32 flags, int width, int height, int depth, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); +/** @sa SDL_CreateRGBSurface */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels, + int width, int height, int depth, int pitch, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); +extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface *surface); + +/** + * SDL_LockSurface() sets up a surface for directly accessing the pixels. + * Between calls to SDL_LockSurface()/SDL_UnlockSurface(), you can write + * to and read from 'surface->pixels', using the pixel format stored in + * 'surface->format'. Once you are done accessing the surface, you should + * use SDL_UnlockSurface() to release it. + * + * Not all surfaces require locking. If SDL_MUSTLOCK(surface) evaluates + * to 0, then you can read and write to the surface at any time, and the + * pixel format of the surface will not change. In particular, if the + * SDL_HWSURFACE flag is not given when calling SDL_SetVideoMode(), you + * will not need to lock the display surface before accessing it. + * + * No operating system or library calls should be made between lock/unlock + * pairs, as critical system locks may be held during this time. + * + * SDL_LockSurface() returns 0, or -1 if the surface couldn't be locked. + */ +extern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface *surface); +extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface); + +/** + * Load a surface from a seekable SDL data source (memory or file.) + * If 'freesrc' is non-zero, the source will be closed after being read. + * Returns the new surface, or NULL if there was an error. + * The new surface should be freed with SDL_FreeSurface(). + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc); + +/** Convenience macro -- load a surface from a file */ +#define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1) + +/** + * Save a surface to a seekable SDL data source (memory or file.) + * If 'freedst' is non-zero, the source will be closed after being written. + * Returns 0 if successful or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_SaveBMP_RW + (SDL_Surface *surface, SDL_RWops *dst, int freedst); + +/** Convenience macro -- save a surface to a file */ +#define SDL_SaveBMP(surface, file) \ + SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), 1) + +/** + * Sets the color key (transparent pixel) in a blittable surface. + * If 'flag' is SDL_SRCCOLORKEY (optionally OR'd with SDL_RLEACCEL), + * 'key' will be the transparent pixel in the source image of a blit. + * SDL_RLEACCEL requests RLE acceleration for the surface if present, + * and removes RLE acceleration if absent. + * If 'flag' is 0, this function clears any current color key. + * This function returns 0, or -1 if there was an error. + */ +extern DECLSPEC int SDLCALL SDL_SetColorKey + (SDL_Surface *surface, Uint32 flag, Uint32 key); + +/** + * This function sets the alpha value for the entire surface, as opposed to + * using the alpha component of each pixel. This value measures the range + * of transparency of the surface, 0 being completely transparent to 255 + * being completely opaque. An 'alpha' value of 255 causes blits to be + * opaque, the source pixels copied to the destination (the default). Note + * that per-surface alpha can be combined with colorkey transparency. + * + * If 'flag' is 0, alpha blending is disabled for the surface. + * If 'flag' is SDL_SRCALPHA, alpha blending is enabled for the surface. + * OR:ing the flag with SDL_RLEACCEL requests RLE acceleration for the + * surface; if SDL_RLEACCEL is not specified, the RLE accel will be removed. + * + * The 'alpha' parameter is ignored for surfaces that have an alpha channel. + */ +extern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint8 alpha); + +/** + * Sets the clipping rectangle for the destination surface in a blit. + * + * If the clip rectangle is NULL, clipping will be disabled. + * If the clip rectangle doesn't intersect the surface, the function will + * return SDL_FALSE and blits will be completely clipped. Otherwise the + * function returns SDL_TRUE and blits to the surface will be clipped to + * the intersection of the surface area and the clipping rectangle. + * + * Note that blits are automatically clipped to the edges of the source + * and destination surfaces. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface *surface, const SDL_Rect *rect); + +/** + * Gets the clipping rectangle for the destination surface in a blit. + * 'rect' must be a pointer to a valid rectangle which will be filled + * with the correct values. + */ +extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect); + +/** + * Creates a new surface of the specified format, and then copies and maps + * the given surface to it so the blit of the converted surface will be as + * fast as possible. If this function fails, it returns NULL. + * + * The 'flags' parameter is passed to SDL_CreateRGBSurface() and has those + * semantics. You can also pass SDL_RLEACCEL in the flags parameter and + * SDL will try to RLE accelerate colorkey and alpha blits in the resulting + * surface. + * + * This function is used internally by SDL_DisplayFormat(). + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface + (SDL_Surface *src, SDL_PixelFormat *fmt, Uint32 flags); + +/** + * This performs a fast blit from the source surface to the destination + * surface. It assumes that the source and destination rectangles are + * the same size. If either 'srcrect' or 'dstrect' are NULL, the entire + * surface (src or dst) is copied. The final blit rectangles are saved + * in 'srcrect' and 'dstrect' after all clipping is performed. + * If the blit is successful, it returns 0, otherwise it returns -1. + * + * The blit function should not be called on a locked surface. + * + * The blit semantics for surfaces with and without alpha and colorkey + * are defined as follows: + * + * RGBA->RGB: + * SDL_SRCALPHA set: + * alpha-blend (using alpha-channel). + * SDL_SRCCOLORKEY ignored. + * SDL_SRCALPHA not set: + * copy RGB. + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * RGB values of the source colour key, ignoring alpha in the + * comparison. + * + * RGB->RGBA: + * SDL_SRCALPHA set: + * alpha-blend (using the source per-surface alpha value); + * set destination alpha to opaque. + * SDL_SRCALPHA not set: + * copy RGB, set destination alpha to source per-surface alpha value. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * source colour key. + * + * RGBA->RGBA: + * SDL_SRCALPHA set: + * alpha-blend (using the source alpha channel) the RGB values; + * leave destination alpha untouched. [Note: is this correct?] + * SDL_SRCCOLORKEY ignored. + * SDL_SRCALPHA not set: + * copy all of RGBA to the destination. + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * RGB values of the source colour key, ignoring alpha in the + * comparison. + * + * RGB->RGB: + * SDL_SRCALPHA set: + * alpha-blend (using the source per-surface alpha value). + * SDL_SRCALPHA not set: + * copy RGB. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * source colour key. + * + * If either of the surfaces were in video memory, and the blit returns -2, + * the video memory was lost, so it should be reloaded with artwork and + * re-blitted: + * @code + * while ( SDL_BlitSurface(image, imgrect, screen, dstrect) == -2 ) { + * while ( SDL_LockSurface(image) < 0 ) + * Sleep(10); + * -- Write image pixels to image->pixels -- + * SDL_UnlockSurface(image); + * } + * @endcode + * + * This happens under DirectX 5.0 when the system switches away from your + * fullscreen application. The lock will also fail until you have access + * to the video memory again. + * + * You should call SDL_BlitSurface() unless you know exactly how SDL + * blitting works internally and how to use the other blit functions. + */ +#define SDL_BlitSurface SDL_UpperBlit + +/** This is the public blit function, SDL_BlitSurface(), and it performs + * rectangle validation and clipping before passing it to SDL_LowerBlit() + */ +extern DECLSPEC int SDLCALL SDL_UpperBlit + (SDL_Surface *src, SDL_Rect *srcrect, + SDL_Surface *dst, SDL_Rect *dstrect); +/** This is a semi-private blit function and it performs low-level surface + * blitting only. + */ +extern DECLSPEC int SDLCALL SDL_LowerBlit + (SDL_Surface *src, SDL_Rect *srcrect, + SDL_Surface *dst, SDL_Rect *dstrect); + +/** + * This function performs a fast fill of the given rectangle with 'color' + * The given rectangle is clipped to the destination surface clip area + * and the final fill rectangle is saved in the passed in pointer. + * If 'dstrect' is NULL, the whole surface will be filled with 'color' + * The color should be a pixel of the format used by the surface, and + * can be generated by the SDL_MapRGB() function. + * This function returns 0 on success, or -1 on error. + */ +extern DECLSPEC int SDLCALL SDL_FillRect + (SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color); + +/** + * This function takes a surface and copies it to a new surface of the + * pixel format and colors of the video framebuffer, suitable for fast + * blitting onto the display surface. It calls SDL_ConvertSurface() + * + * If you want to take advantage of hardware colorkey or alpha blit + * acceleration, you should set the colorkey and alpha value before + * calling this function. + * + * If the conversion fails or runs out of memory, it returns NULL + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormat(SDL_Surface *surface); + +/** + * This function takes a surface and copies it to a new surface of the + * pixel format and colors of the video framebuffer (if possible), + * suitable for fast alpha blitting onto the display surface. + * The new surface will always have an alpha channel. + * + * If you want to take advantage of hardware colorkey or alpha blit + * acceleration, you should set the colorkey and alpha value before + * calling this function. + * + * If the conversion fails or runs out of memory, it returns NULL + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormatAlpha(SDL_Surface *surface); + + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name YUV video surface overlay functions */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/** This function creates a video output overlay + * Calling the returned surface an overlay is something of a misnomer because + * the contents of the display surface underneath the area where the overlay + * is shown is undefined - it may be overwritten with the converted YUV data. + */ +extern DECLSPEC SDL_Overlay * SDLCALL SDL_CreateYUVOverlay(int width, int height, + Uint32 format, SDL_Surface *display); + +/** Lock an overlay for direct access, and unlock it when you are done */ +extern DECLSPEC int SDLCALL SDL_LockYUVOverlay(SDL_Overlay *overlay); +extern DECLSPEC void SDLCALL SDL_UnlockYUVOverlay(SDL_Overlay *overlay); + +/** Blit a video overlay to the display surface. + * The contents of the video surface underneath the blit destination are + * not defined. + * The width and height of the destination rectangle may be different from + * that of the overlay, but currently only 2x scaling is supported. + */ +extern DECLSPEC int SDLCALL SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect); + +/** Free a video overlay */ +extern DECLSPEC void SDLCALL SDL_FreeYUVOverlay(SDL_Overlay *overlay); + +/*@}*/ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name OpenGL support functions. */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/** + * Dynamically load an OpenGL library, or the default one if path is NULL + * + * If you do this, you need to retrieve all of the GL functions used in + * your program from the dynamic library using SDL_GL_GetProcAddress(). + */ +extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); + +/** + * Get the address of a GL function + */ +extern DECLSPEC void * SDLCALL SDL_GL_GetProcAddress(const char* proc); + +/** + * Set an attribute of the OpenGL subsystem before intialization. + */ +extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); + +/** + * Get an attribute of the OpenGL subsystem from the windowing + * interface, such as glX. This is of course different from getting + * the values from SDL's internal OpenGL subsystem, which only + * stores the values you request before initialization. + * + * Developers should track the values they pass into SDL_GL_SetAttribute + * themselves if they want to retrieve these values. + */ +extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int* value); + +/** + * Swap the OpenGL buffers, if double-buffering is supported. + */ +extern DECLSPEC void SDLCALL SDL_GL_SwapBuffers(void); + +/** @name OpenGL Internal Functions + * Internal functions that should not be called unless you have read + * and understood the source code for these functions. + */ +/*@{*/ +extern DECLSPEC void SDLCALL SDL_GL_UpdateRects(int numrects, SDL_Rect* rects); +extern DECLSPEC void SDLCALL SDL_GL_Lock(void); +extern DECLSPEC void SDLCALL SDL_GL_Unlock(void); +/*@}*/ + +/*@}*/ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/** @name Window Manager Functions */ +/** These functions allow interaction with the window manager, if any. */ /*@{*/ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/** + * Sets the title and icon text of the display window (UTF-8 encoded) + */ +extern DECLSPEC void SDLCALL SDL_WM_SetCaption(const char *title, const char *icon); +/** + * Gets the title and icon text of the display window (UTF-8 encoded) + */ +extern DECLSPEC void SDLCALL SDL_WM_GetCaption(char **title, char **icon); + +/** + * Sets the icon for the display window. + * This function must be called before the first call to SDL_SetVideoMode(). + * It takes an icon surface, and a mask in MSB format. + * If 'mask' is NULL, the entire icon surface will be used as the icon. + */ +extern DECLSPEC void SDLCALL SDL_WM_SetIcon(SDL_Surface *icon, Uint8 *mask); + +/** + * This function iconifies the window, and returns 1 if it succeeded. + * If the function succeeds, it generates an SDL_APPACTIVE loss event. + * This function is a noop and returns 0 in non-windowed environments. + */ +extern DECLSPEC int SDLCALL SDL_WM_IconifyWindow(void); + +/** + * Toggle fullscreen mode without changing the contents of the screen. + * If the display surface does not require locking before accessing + * the pixel information, then the memory pointers will not change. + * + * If this function was able to toggle fullscreen mode (change from + * running in a window to fullscreen, or vice-versa), it will return 1. + * If it is not implemented, or fails, it returns 0. + * + * The next call to SDL_SetVideoMode() will set the mode fullscreen + * attribute based on the flags parameter - if SDL_FULLSCREEN is not + * set, then the display will be windowed by default where supported. + * + * This is currently only implemented in the X11 video driver. + */ +extern DECLSPEC int SDLCALL SDL_WM_ToggleFullScreen(SDL_Surface *surface); + +typedef enum { + SDL_GRAB_QUERY = -1, + SDL_GRAB_OFF = 0, + SDL_GRAB_ON = 1, + SDL_GRAB_FULLSCREEN /**< Used internally */ +} SDL_GrabMode; +/** + * This function allows you to set and query the input grab state of + * the application. It returns the new input grab state. + * + * Grabbing means that the mouse is confined to the application window, + * and nearly all keyboard input is passed directly to the application, + * and not interpreted by a window manager, if any. + */ +extern DECLSPEC SDL_GrabMode SDLCALL SDL_WM_GrabInput(SDL_GrabMode mode); + +/*@}*/ + +/** @internal Not in public API at the moment - do not use! */ +extern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect, + SDL_Surface *dst, SDL_Rect *dstrect); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* _SDL_video_h */ diff --git a/other/sdl/include/begin_code.h b/other/sdl/include/begin_code.h new file mode 100644 index 0000000..2274809 --- /dev/null +++ b/other/sdl/include/begin_code.h @@ -0,0 +1,191 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file begin_code.h + * This file sets things up for C dynamic library function definitions, + * static inlined functions, and structures aligned at 4-byte alignment. + * If you don't like ugly C preprocessor code, don't look at this file. :) + */ + +/** + * @file begin_code.h + * This shouldn't be nested -- included it around code only. + */ +#ifdef _begin_code_h +#error Nested inclusion of begin_code.h +#endif +#define _begin_code_h + +/** + * @def DECLSPEC + * Some compilers use a special export keyword + */ +#ifndef DECLSPEC +# if defined(__BEOS__) || defined(__HAIKU__) +# if defined(__GNUC__) +# define DECLSPEC __declspec(dllexport) +# else +# define DECLSPEC __declspec(export) +# endif +# elif defined(__WIN32__) +# ifdef __BORLANDC__ +# ifdef BUILD_SDL +# define DECLSPEC +# else +# define DECLSPEC __declspec(dllimport) +# endif +# else +# define DECLSPEC __declspec(dllexport) +# endif +# elif defined(__OS2__) +# ifdef __WATCOMC__ +# ifdef BUILD_SDL +# define DECLSPEC __declspec(dllexport) +# else +# define DECLSPEC +# endif +# elif defined (__GNUC__) && __GNUC__ < 4 +# /* Added support for GCC-EMX <v4.x */ +# /* this is needed for XFree86/OS2 developement */ +# /* F. Ambacher(anakor@snafu.de) 05.2008 */ +# ifdef BUILD_SDL +# define DECLSPEC __declspec(dllexport) +# else +# define DECLSPEC +# endif +# else +# define DECLSPEC +# endif +# else +# if defined(__GNUC__) && __GNUC__ >= 4 +# define DECLSPEC __attribute__ ((visibility("default"))) +# else +# define DECLSPEC +# endif +# endif +#endif + +/** + * @def SDLCALL + * By default SDL uses the C calling convention + */ +#ifndef SDLCALL +# if defined(__WIN32__) && !defined(__GNUC__) +# define SDLCALL __cdecl +# elif defined(__OS2__) +# if defined (__GNUC__) && __GNUC__ < 4 +# /* Added support for GCC-EMX <v4.x */ +# /* this is needed for XFree86/OS2 developement */ +# /* F. Ambacher(anakor@snafu.de) 05.2008 */ +# define SDLCALL _cdecl +# else +# /* On other compilers on OS/2, we use the _System calling convention */ +# /* to be compatible with every compiler */ +# define SDLCALL _System +# endif +# else +# define SDLCALL +# endif +#endif /* SDLCALL */ + +#ifdef __SYMBIAN32__ +#ifndef EKA2 +#undef DECLSPEC +#define DECLSPEC +#elif !defined(__WINS__) +#undef DECLSPEC +#define DECLSPEC __declspec(dllexport) +#endif /* !EKA2 */ +#endif /* __SYMBIAN32__ */ + +/** + * @file begin_code.h + * Force structure packing at 4 byte alignment. + * This is necessary if the header is included in code which has structure + * packing set to an alternate value, say for loading structures from disk. + * The packing is reset to the previous value in close_code.h + */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) +#ifdef _MSC_VER +#pragma warning(disable: 4103) +#endif +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#pragma pack(push,4) +#elif (defined(__MWERKS__) && defined(__MACOS__)) +#pragma options align=mac68k4byte +#pragma enumsalwaysint on +#endif /* Compiler needs structure packing set */ + +/** + * @def SDL_INLINE_OKAY + * Set up compiler-specific options for inlining functions + */ +#ifndef SDL_INLINE_OKAY +#ifdef __GNUC__ +#define SDL_INLINE_OKAY +#else +/* Add any special compiler-specific cases here */ +#if defined(_MSC_VER) || defined(__BORLANDC__) || \ + defined(__DMC__) || defined(__SC__) || \ + defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__DECC) || defined(__EABI__) +#ifndef __inline__ +#define __inline__ __inline +#endif +#define SDL_INLINE_OKAY +#else +#if !defined(__MRC__) && !defined(_SGI_SOURCE) +#ifndef __inline__ +#define __inline__ inline +#endif +#define SDL_INLINE_OKAY +#endif /* Not a funky compiler */ +#endif /* Visual C++ */ +#endif /* GNU C */ +#endif /* SDL_INLINE_OKAY */ + +/** + * @def __inline__ + * If inlining isn't supported, remove "__inline__", turning static + * inlined functions into static functions (resulting in code bloat + * in all files which include the offending header files) + */ +#ifndef SDL_INLINE_OKAY +#define __inline__ +#endif + +/** + * @def NULL + * Apparently this is needed by several Windows compilers + */ +#if !defined(__MACH__) +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif /* NULL */ +#endif /* ! Mac OS X - breaks precompiled headers */ diff --git a/other/sdl/include/close_code.h b/other/sdl/include/close_code.h new file mode 100644 index 0000000..46a0720 --- /dev/null +++ b/other/sdl/include/close_code.h @@ -0,0 +1,46 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2009 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +/** + * @file close_code.h + * This file reverses the effects of begin_code.h and should be included + * after you finish any function and structure declarations in your headers + */ + +#undef _begin_code_h + +/** + * @file close_code.h + * Reset structure packing at previous byte alignment + */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__WATCOMC__) || defined(__BORLANDC__) +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#if (defined(__MWERKS__) && defined(__MACOS__)) +#pragma options align=reset +#pragma enumsalwaysint reset +#else +#pragma pack(pop) +#endif +#endif /* Compiler needs structure packing set */ + diff --git a/other/sdl/lib32/SDL.lib b/other/sdl/lib32/SDL.lib new file mode 100644 index 0000000..f4e860f Binary files /dev/null and b/other/sdl/lib32/SDL.lib differ diff --git a/other/sdl/lib32/SDLmain.lib b/other/sdl/lib32/SDLmain.lib new file mode 100644 index 0000000..825c03b Binary files /dev/null and b/other/sdl/lib32/SDLmain.lib differ diff --git a/other/sdl/lib64/SDL.lib b/other/sdl/lib64/SDL.lib new file mode 100644 index 0000000..489ba5d Binary files /dev/null and b/other/sdl/lib64/SDL.lib differ diff --git a/other/sdl/lib64/SDLmain.lib b/other/sdl/lib64/SDLmain.lib new file mode 100644 index 0000000..b5f8e8f Binary files /dev/null and b/other/sdl/lib64/SDLmain.lib differ diff --git a/other/sdl/sdl.lua b/other/sdl/sdl.lua new file mode 100644 index 0000000..84702bb --- /dev/null +++ b/other/sdl/sdl.lua @@ -0,0 +1,85 @@ +SDL = { + basepath = PathDir(ModuleFilename()), + + OptFind = function (name, required) + local check = function(option, settings) + option.value = false + option.use_pkgconfig = false + option.use_winlib = 0 + option.use_osxframework = false + option.lib_path = nil + + if family ~= "windows" and ExecuteSilent("pkg-config sdl") == 0 then + option.value = true + option.use_pkgconfig = true + end + + if platform == "win32" then + option.value = true + option.use_winlib = 32 + elseif platform == "win64" then + option.value = true + option.use_winlib = 64 + end + + if platform == "macosx" then + option.value = true + option.use_osxframework = true + option.use_pkgconfig = false + end + end + + local apply = function(option, settings) + if option.use_pkgconfig == true then + settings.cc.flags:Add("`pkg-config sdl --cflags`") + settings.link.flags:Add("`pkg-config sdl --libs`") + end + + if option.use_osxframework == true then + client_settings.link.frameworks:Add("SDL") + client_settings.cc.includes:Add("/Library/Frameworks/SDL.framework/Headers") + end + + if option.use_winlib > 0 then + settings.cc.includes:Add(SDL.basepath .. "/include") + if option.use_winlib == 32 then + settings.link.libpath:Add(SDL.basepath .. "/lib32") + else + settings.link.libpath:Add(SDL.basepath .. "/lib64") + end + settings.link.libs:Add("SDL") + settings.link.libs:Add("SDLmain") + end + end + + local save = function(option, output) + output:option(option, "value") + output:option(option, "use_pkgconfig") + output:option(option, "use_winlib") + output:option(option, "use_osxframework") + end + + local display = function(option) + if option.value == true then + if option.use_pkgconfig == true then return "using pkg-config" end + if option.use_winlib == 32 then return "using supplied win32 libraries" end + if option.use_winlib == 64 then return "using supplied win64 libraries" end + if option.use_osxframework == true then return "using osx framework" end + return "using unknown method" + else + if option.required then + return "not found (required)" + else + return "not found (optional)" + end + end + end + + local o = MakeOption(name, 0, check, save, display) + o.Apply = apply + o.include_path = nil + o.lib_path = nil + o.required = required + return o + end +} diff --git a/other/sdl/sdlnotes.txt b/other/sdl/sdlnotes.txt new file mode 100644 index 0000000..bb9fb09 --- /dev/null +++ b/other/sdl/sdlnotes.txt @@ -0,0 +1,3 @@ +NOTE. This is a really stripped down version of SDL only used +to compile teeworlds for windows. For a complete release of +SDL, please visit their site at http://www.libsdl.org. \ No newline at end of file diff --git a/scripts/AndroidAppSettings.cfg b/scripts/AndroidAppSettings.cfg new file mode 100644 index 0000000..1c3b34c --- /dev/null +++ b/scripts/AndroidAppSettings.cfg @@ -0,0 +1,247 @@ +# The application settings for Android libSDL port + +# Specify application name (e.x. My Application) +AppName="DDraceNetwork Client" + +# Specify reversed site name of application (e.x. com.mysite.myapp) +AppFullName=tw.ddnet + +# Application version code (integer) +AppVersionCode=0730 + +# Application user-visible version name (string) +AppVersionName="7.3" + +# Specify path to download application data in zip archive in the form 'Description|URL|MirrorURL^Description2|URL2|MirrorURL2^...' +# If you'll start Description with '!' symbol it will be enabled by default, other downloads should be selected by user from startup config menu +# If the URL in in the form ':dir/file.dat:http://URL/' it will be downloaded as binary BLOB to the application dir and not unzipped +# If the URL does not contain 'http://' it is treated as file from 'project/jni/application/src/AndroidData' dir - +# these files are put inside .apk package by build system +# Also please avoid 'https://' URLs, many Android devices do not have trust certificates and will fail to connect to SF.net over HTTPS +AppDataDownloadUrl="Game data|data.zip" + +# Reset SDL config when updating application to the new version (y) / (n) +ResetSdlConfigForThisVersion=y + +# Delete application data files when upgrading (specify file/dir paths separated by spaces) +DeleteFilesOnUpgrade="%" + +# Here you may type readme text, which will be shown during startup. Format is: +# Text in English, use \\\\n to separate lines (that's four backslashes)^de:Text in Deutsch^ru:Text in Russian^button:Button that will open some URL:http://url-to-open/ +ReadmeText='Tap left joystick to jump' + +# libSDL version to use (1.2/1.3/2.0) +LibSdlVersion=1.2 + +# Specify screen orientation: (v)ertical/(p)ortrait or (h)orizontal/(l)andscape +ScreenOrientation=h + +# Video color depth - 16 BPP is the fastest and supported for all modes, 24 bpp is supported only +# with SwVideoMode=y, SDL_OPENGL mode supports everything. (16)/(24)/(32) +VideoDepthBpp=24 + +# Enable OpenGL depth buffer (needed only for 3-d applications, small speed decrease) (y) or (n) +NeedDepthBuffer=n + +# Enable OpenGL stencil buffer (needed only for 3-d applications, small speed decrease) (y) or (n) +NeedStencilBuffer=n + +# Try to use GLES 2.x context - will revert to GLES 1.X if unsupported by device +# you need this option only if you're developing 3-d app (y) or (n) +NeedGles2=n + +# Application uses software video buffer - you're calling SDL_SetVideoMode() without SDL_HWSURFACE and without SDL_OPENGL, +# this will allow small speed optimization. Enable this even when you're using SDL_HWSURFACE. (y) or (n) +SwVideoMode=n + +# Application video output will be resized to fit into native device screen (y)/(n) +SdlVideoResize=n + +# Application resizing will keep 4:3 aspect ratio, with black bars at sides (y)/(n) +SdlVideoResizeKeepAspect=n + +# Do not allow device to sleep when the application is in foreground, set this for video players or apps which use accelerometer +InhibitSuspend=y + +# Create Android service, so the app is less likely to be killed while in background +CreateService= + +# Application does not call SDL_Flip() or SDL_UpdateRects() appropriately, or draws from non-main thread - +# enabling the compatibility mode will force screen update every 100 milliseconds, which is laggy and inefficient (y) or (n) +CompatibilityHacks=n + +# Application initializes SDL audio/video inside static constructors (which is bad, you won't be able to run ndk-gdb) (y)/(n) +CompatibilityHacksStaticInit=n + +# On-screen Android soft text input emulates hardware keyboard, this will only work with Hackers Keyboard app (y)/(n) +CompatibilityHacksTextInputEmulatesHwKeyboard=n + +# Hack for broken devices: prevent audio chopping, by sleeping a bit after pushing each audio chunk (y)/(n) +CompatibilityHacksPreventAudioChopping=n + +# Hack for broken apps: application ignores audio buffer size returned by SDL (y)/(n) +CompatibilityHacksAppIgnoresAudioBufferSize=n + +# Hack for VCMI: preload additional shared libraries before aplication start +CompatibilityHacksAdditionalPreloadedSharedLibraries="" + +# Hack for Free Heroes 2, which redraws the screen inside SDL_PumpEvents(): slow and compatible SDL event queue - +# do not use it with accelerometer/gyroscope, or your app may freeze at random (y)/(n) +CompatibilityHacksSlowCompatibleEventQueue=n + +# Save and restore OpenGL state when drawing on-screen keyboard for apps that use SDL_OPENGL +CompatibilityHacksTouchscreenKeyboardSaveRestoreOpenGLState=n + +# Application uses SDL_UpdateRects() properly, and does not draw in any region outside those rects. +# This improves drawing speed, but I know only one application that does that, and it's written by me (y)/(n) +CompatibilityHacksProperUsageOfSDL_UpdateRects= + +# Application uses mouse (y) or (n), this will show mouse emulation dialog to the user +AppUsesMouse=y + +# Application needs two-button mouse, will also enable advanced point-and-click features (y) or (n) +AppNeedsTwoButtonMouse=n + +# Right mouse button can do long-press/drag&drop action, necessary for some games (y) or (n) +# If you disable it, swiping with two fingers will send mouse wheel events +RightMouseButtonLongPress= + +# Show SDL mouse cursor, for applications that do not draw cursor at all (y) or (n) +ShowMouseCursor=n + +# Generate more touch events, by default SDL generates one event per one video frame, this is useful for drawing apps (y) or (n) +GenerateSubframeTouchEvents= + +# Force relative (laptop) mouse movement mode, useful when both on-screen keyboard and mouse are needed (y) or (n) +ForceRelativeMouseMode=n + +# Application needs arrow keys (y) or (n), will show on-screen dpad/joystick (y) or (n) +AppNeedsArrowKeys=n + +# Application needs text input (y) or (n), enables button for text input on screen +AppNeedsTextInput=y + +# Application uses joystick (y) or (n), the on-screen DPAD will be used as joystick 0 axes 0-1 +AppUsesJoystick=y + +# Application uses second on-screen joystick, as SDL joystick 0 axes 2-3 (y)/(n) +AppUsesSecondJoystick=y + +# Application uses third on-screen joystick, as SDL joystick 0 axes 20-21 (y)/(n) +AppUsesThirdJoystick=n + +# Application uses accelerometer (y) or (n), the accelerometer will be used as joystick 1 axes 0-1 and 5-7 +AppUsesAccelerometer=n + +# Application uses gyroscope (y) or (n), the gyroscope will be used as joystick 1 axes 2-4 +AppUsesGyroscope=n + +# Application uses multitouch (y) or (n), multitouch events are passed as SDL_JOYBALLMOTION events for the joystick 0 +AppUsesMultitouch=n + +# Application records audio (it will use any available source, such a s microphone) +# API is defined in file SDL_android.h: int SDL_ANDROID_OpenAudioRecording(SDL_AudioSpec *spec); void SDL_ANDROID_CloseAudioRecording(void); +# This option will add additional permission to Android manifest (y)/(n) +AppRecordsAudio=n + +# Application needs to access SD card. If your data files are bigger than 5 Mb, enable it. (y) / (n) +AccessSdCard= + +# Application needs Internet access. If you disable it, you'll have to bundle all your data files inside .apk (y) / (n) +AccessInternet= + +# Immersive mode - Android will hide on-screen Home/Back keys. Looks bad if you invoke Android keyboard. (y) / (n) +ImmersiveMode=y + +# Application implements Android-specific routines to put to background, and will not draw anything to screen +# between SDL_ACTIVEEVENT lost / gained notifications - you should check for them +# rigth after SDL_Flip(), if (n) then SDL_Flip() will block till app in background (y) or (n) +# This option is reported to be buggy, sometimes failing to restore video state +NonBlockingSwapBuffers=n + +# Redefine common hardware keys to SDL keysyms +# BACK hardware key is available on all devices, MENU is available on pre-ICS devices, other keys may be absent +# SEARCH and CALL by default return same keycode as DPAD_CENTER - one of those keys is available on most devices +# Use word NO_REMAP if you want to preserve native functionality for certain key (volume keys are 3-rd and 4-th) +# Keys: TOUCHSCREEN (works only when AppUsesMouse=n), DPAD_CENTER/SEARCH, VOLUMEUP, VOLUMEDOWN, MENU, BACK, CAMERA +RedefinedKeys="SPACE RETURN NO_REMAP NO_REMAP" + +# Number of virtual keyboard keys (currently 6 is maximum) +AppTouchscreenKeyboardKeysAmount=6 + +# Redefine on-screen keyboard keys to SDL keysyms - 6 keyboard keys + 4 multitouch gestures (zoom in/out and rotate left/right) +RedefinedKeysScreenKb="RETURN PAGEDOWN PAGEUP TAB F5 F6" + +# Names for on-screen keyboard keys, such as Fire, Jump, Run etc, separated by spaces, they are used in SDL config menu +RedefinedKeysScreenKbNames="Hook Next_weapon Previous_weapon Show_scores Jump Spectate" + +# On-screen keys theme +# 0 = Ultimate Droid by Sean Stieber (green, with gamepad joystick) +# 1 = Simple Theme by Beholder (white, with gamepad joystick) +# 2 = Sun by Sirea (yellow, with round joystick) +# 3 = Keen by Gerstrong (multicolor, with round joystick) +TouchscreenKeysTheme=2 + +# Redefine gamepad keys to SDL keysyms, button order is: +# A B X Y L1 R1 L2 R2 LThumb RThumb +RedefinedKeysGamepad="RETURN PAGEDOWN TAB T SPACE RCTRL RETURN RCTRL SPACE PAGEDOWN" + +# How long to show startup menu button, in msec, 0 to disable startup menu +StartupMenuButtonTimeout=3000 + +# Menu items to hide from startup menu, available menu items: +# SettingsMenu.OkButton SettingsMenu.DummyMenu SettingsMenu.MainMenu SettingsMenuMisc.DownloadConfig SettingsMenuMisc.OptionalDownloadConfig SettingsMenuMisc.AudioConfig SettingsMenuMisc.VideoSettingsConfig SettingsMenuMisc.ShowReadme SettingsMenuMisc.GyroscopeCalibration SettingsMenuMisc.ResetToDefaultsConfig SettingsMenuMouse.MouseConfigMainMenu SettingsMenuMouse.DisplaySizeConfig SettingsMenuMouse.LeftClickConfig SettingsMenuMouse.RightClickConfig SettingsMenuMouse.AdditionalMouseConfig SettingsMenuMouse.JoystickMouseConfig SettingsMenuMouse.TouchPressureMeasurementTool SettingsMenuMouse.CalibrateTouchscreenMenu SettingsMenuKeyboard.KeyboardConfigMainMenu SettingsMenuKeyboard.ScreenKeyboardSizeConfig SettingsMenuKeyboard.ScreenKeyboardDrawSizeConfig SettingsMenuKeyboard.ScreenKeyboardThemeConfig SettingsMenuKeyboard.ScreenKeyboardTransparencyConfig SettingsMenuKeyboard.RemapHwKeysConfig SettingsMenuKeyboard.RemapScreenKbConfig SettingsMenuKeyboard.ScreenGesturesConfig SettingsMenuKeyboard.CustomizeScreenKbLayout +HiddenMenuOptions='SettingsMenuMisc.OptionalDownloadConfig SettingsMenuMouse.DisplaySizeConfig' + +# Menu items to show at startup - this is Java code snippet, leave empty for default +# new SettingsMenuMisc.ShowReadme(), (AppUsesMouse \&\& \! ForceRelativeMouseMode \? new SettingsMenuMouse.DisplaySizeConfig(true) : new SettingsMenu.DummyMenu()), new SettingsMenuMisc.OptionalDownloadConfig(true), new SettingsMenuMisc.GyroscopeCalibration() +# Available menu items: +# SettingsMenu.OkButton SettingsMenu.DummyMenu SettingsMenu.MainMenu SettingsMenuMisc.DownloadConfig SettingsMenuMisc.OptionalDownloadConfig SettingsMenuMisc.AudioConfig SettingsMenuMisc.VideoSettingsConfig SettingsMenuMisc.ShowReadme SettingsMenuMisc.GyroscopeCalibration SettingsMenuMisc.ResetToDefaultsConfig SettingsMenuMouse.MouseConfigMainMenu SettingsMenuMouse.DisplaySizeConfig SettingsMenuMouse.LeftClickConfig SettingsMenuMouse.RightClickConfig SettingsMenuMouse.AdditionalMouseConfig SettingsMenuMouse.JoystickMouseConfig SettingsMenuMouse.TouchPressureMeasurementTool SettingsMenuMouse.CalibrateTouchscreenMenu SettingsMenuKeyboard.KeyboardConfigMainMenu SettingsMenuKeyboard.ScreenKeyboardSizeConfig SettingsMenuKeyboard.ScreenKeyboardDrawSizeConfig SettingsMenuKeyboard.ScreenKeyboardThemeConfig SettingsMenuKeyboard.ScreenKeyboardTransparencyConfig SettingsMenuKeyboard.RemapHwKeysConfig SettingsMenuKeyboard.RemapScreenKbConfig SettingsMenuKeyboard.ScreenGesturesConfig SettingsMenuKeyboard.CustomizeScreenKbLayout +FirstStartMenuOptions='' + +# Enable multi-ABI binary, with hardware FPU support - it will also work on old devices, +# but .apk size is 2x bigger (y) / (n) / (x86) / (all) +MultiABI='all' + +# Minimum amount of RAM application requires, in Mb, SDL will print warning to user if it's lower +AppMinimumRAM=0 + +# Optional shared libraries to compile - removing some of them will save space +# MP3 support by libMAD is encumbered by patents and libMAD is GPL-ed +# Available libraries: mad (GPL-ed!) sdl_mixer sdl_image sdl_ttf sdl_net sdl_blitpool sdl_gfx sdl_sound intl xml2 lua jpeg png ogg flac tremor vorbis freetype xerces curl theora fluidsynth lzma lzo2 mikmod openal timidity zzip bzip2 yaml-cpp python boost_date_time boost_filesystem boost_iostreams boost_program_options boost_regex boost_signals boost_system boost_thread glu avcodec avdevice avfilter avformat avresample avutil swscale swresample bzip2 +CompiledLibraries="sdl_image freetype glu ogg opus opusfile curl" + +# Application uses custom build script AndroidBuild.sh instead of Android.mk (y) or (n) +CustomBuildScript=n + +# Aditional CFLAGS for application +AppCflags='-O3' + +# Additional LDFLAGS for application +AppLdflags='-lEGL' + +# If application has headers with the same name as system headers, this option tries to fix compiler flags to make it compilable +AppOverlapsSystemHeaders=n + +# Build only following subdirs (empty will build all dirs, ignored with custom script) +AppSubdirsBuild='src/src src/src/base/confusables.c src/src/base/system.c src/src/engine src/src/engine/client src/src/engine/shared src/src/engine/external/pnglite src/src/engine/external/wavpack src/src/engine/external/md5 src/src/engine/external/json-parser/json.cpp src/src/game src/src/game/client/* src/src/game/editor src/src/game/generated/protocol.cpp src/src/game/generated/client_data.cpp' + +# Exclude these files from build +AppBuildExclude='' + +# Application command line parameters, including app name as 0-th param +AppCmdline='' + +# Screen size is used by Google Play to prevent an app to be installed on devices with smaller screens +# Minimum screen size that application supports: (s)mall / (m)edium / (l)arge +MinimumScreenSize=n + +# Your AdMob Publisher ID, (n) if you don't want advertisements +AdmobPublisherId=n + +# Your AdMob test device ID, to receive a test ad +AdmobTestDeviceId= + +# Your AdMob banner size (BANNER/IAB_BANNER/IAB_LEADERBOARD/IAB_MRECT/IAB_WIDE_SKYSCRAPER/SMART_BANNER) +AdmobBannerSize= + diff --git a/scripts/SDL_keysym.h b/scripts/SDL_keysym.h new file mode 100644 index 0000000..ff44a03 --- /dev/null +++ b/scripts/SDL_keysym.h @@ -0,0 +1,311 @@ +/* + SDL - Simple DirectMedia Layer + Copyright (C) 1997-2006 Sam Lantinga + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Sam Lantinga + slouken@libsdl.org +*/ + +#ifndef _SDL_keysym_h +#define _SDL_keysym_h + +/* What we really want is a mapping of every raw key on the keyboard. + To support international keyboards, we use the range 0xA1 - 0xFF + as international virtual keycodes. We'll follow in the footsteps of X11... + The names of the keys + */ + +typedef enum { + /* The keyboard syms have been cleverly chosen to map to ASCII */ + SDLK_UNKNOWN = 0, + SDLK_FIRST = 0, + SDLK_BACKSPACE = 8, + SDLK_TAB = 9, + SDLK_CLEAR = 12, + SDLK_RETURN = 13, + SDLK_PAUSE = 19, + SDLK_ESCAPE = 27, + SDLK_SPACE = 32, + SDLK_EXCLAIM = 33, + SDLK_QUOTEDBL = 34, + SDLK_HASH = 35, + SDLK_DOLLAR = 36, + SDLK_AMPERSAND = 38, + SDLK_QUOTE = 39, + SDLK_LEFTPAREN = 40, + SDLK_RIGHTPAREN = 41, + SDLK_ASTERISK = 42, + SDLK_PLUS = 43, + SDLK_COMMA = 44, + SDLK_MINUS = 45, + SDLK_PERIOD = 46, + SDLK_SLASH = 47, + SDLK_0 = 48, + SDLK_1 = 49, + SDLK_2 = 50, + SDLK_3 = 51, + SDLK_4 = 52, + SDLK_5 = 53, + SDLK_6 = 54, + SDLK_7 = 55, + SDLK_8 = 56, + SDLK_9 = 57, + SDLK_COLON = 58, + SDLK_SEMICOLON = 59, + SDLK_LESS = 60, + SDLK_EQUALS = 61, + SDLK_GREATER = 62, + SDLK_QUESTION = 63, + SDLK_AT = 64, + /* + Skip uppercase letters + */ + SDLK_LEFTBRACKET = 91, + SDLK_BACKSLASH = 92, + SDLK_RIGHTBRACKET = 93, + SDLK_CARET = 94, + SDLK_UNDERSCORE = 95, + SDLK_BACKQUOTE = 96, + SDLK_a = 97, + SDLK_b = 98, + SDLK_c = 99, + SDLK_d = 100, + SDLK_e = 101, + SDLK_f = 102, + SDLK_g = 103, + SDLK_h = 104, + SDLK_i = 105, + SDLK_j = 106, + SDLK_k = 107, + SDLK_l = 108, + SDLK_m = 109, + SDLK_n = 110, + SDLK_o = 111, + SDLK_p = 112, + SDLK_q = 113, + SDLK_r = 114, + SDLK_s = 115, + SDLK_t = 116, + SDLK_u = 117, + SDLK_v = 118, + SDLK_w = 119, + SDLK_x = 120, + SDLK_y = 121, + SDLK_z = 122, + SDLK_DELETE = 127, + /* End of ASCII mapped keysyms */ + + /* International keyboard syms */ + SDLK_WORLD_0 = 160, /* 0xA0 */ + SDLK_WORLD_1 = 161, + SDLK_WORLD_2 = 162, + SDLK_WORLD_3 = 163, + SDLK_WORLD_4 = 164, + SDLK_WORLD_5 = 165, + SDLK_WORLD_6 = 166, + SDLK_WORLD_7 = 167, + SDLK_WORLD_8 = 168, + SDLK_WORLD_9 = 169, + SDLK_WORLD_10 = 170, + SDLK_WORLD_11 = 171, + SDLK_WORLD_12 = 172, + SDLK_WORLD_13 = 173, + SDLK_WORLD_14 = 174, + SDLK_WORLD_15 = 175, + SDLK_WORLD_16 = 176, + SDLK_WORLD_17 = 177, + SDLK_WORLD_18 = 178, + SDLK_WORLD_19 = 179, + SDLK_WORLD_20 = 180, + SDLK_WORLD_21 = 181, + SDLK_WORLD_22 = 182, + SDLK_WORLD_23 = 183, + SDLK_WORLD_24 = 184, + SDLK_WORLD_25 = 185, + SDLK_WORLD_26 = 186, + SDLK_WORLD_27 = 187, + SDLK_WORLD_28 = 188, + SDLK_WORLD_29 = 189, + SDLK_WORLD_30 = 190, + SDLK_WORLD_31 = 191, + SDLK_WORLD_32 = 192, + SDLK_WORLD_33 = 193, + SDLK_WORLD_34 = 194, + SDLK_WORLD_35 = 195, + SDLK_WORLD_36 = 196, + SDLK_WORLD_37 = 197, + SDLK_WORLD_38 = 198, + SDLK_WORLD_39 = 199, + SDLK_WORLD_40 = 200, + SDLK_WORLD_41 = 201, + SDLK_WORLD_42 = 202, + SDLK_WORLD_43 = 203, + SDLK_WORLD_44 = 204, + SDLK_WORLD_45 = 205, + SDLK_WORLD_46 = 206, + SDLK_WORLD_47 = 207, + SDLK_WORLD_48 = 208, + SDLK_WORLD_49 = 209, + SDLK_WORLD_50 = 210, + SDLK_WORLD_51 = 211, + SDLK_WORLD_52 = 212, + SDLK_WORLD_53 = 213, + SDLK_WORLD_54 = 214, + SDLK_WORLD_55 = 215, + SDLK_WORLD_56 = 216, + SDLK_WORLD_57 = 217, + SDLK_WORLD_58 = 218, + SDLK_WORLD_59 = 219, + SDLK_WORLD_60 = 220, + SDLK_WORLD_61 = 221, + SDLK_WORLD_62 = 222, + SDLK_WORLD_63 = 223, + SDLK_WORLD_64 = 224, + SDLK_WORLD_65 = 225, + SDLK_WORLD_66 = 226, + SDLK_WORLD_67 = 227, + SDLK_WORLD_68 = 228, + SDLK_WORLD_69 = 229, + SDLK_WORLD_70 = 230, + SDLK_WORLD_71 = 231, + SDLK_WORLD_72 = 232, + SDLK_WORLD_73 = 233, + SDLK_WORLD_74 = 234, + SDLK_WORLD_75 = 235, + SDLK_WORLD_76 = 236, + SDLK_WORLD_77 = 237, + SDLK_WORLD_78 = 238, + SDLK_WORLD_79 = 239, + SDLK_WORLD_80 = 240, + SDLK_WORLD_81 = 241, + SDLK_WORLD_82 = 242, + SDLK_WORLD_83 = 243, + SDLK_WORLD_84 = 244, + SDLK_WORLD_85 = 245, + SDLK_WORLD_86 = 246, + SDLK_WORLD_87 = 247, + SDLK_WORLD_88 = 248, + SDLK_WORLD_89 = 249, + SDLK_WORLD_90 = 250, + SDLK_WORLD_91 = 251, + SDLK_WORLD_92 = 252, + SDLK_WORLD_93 = 253, + SDLK_WORLD_94 = 254, + SDLK_WORLD_95 = 255, /* 0xFF */ + + /* Numeric keypad */ + SDLK_KP0 = 256, + SDLK_KP1 = 257, + SDLK_KP2 = 258, + SDLK_KP3 = 259, + SDLK_KP4 = 260, + SDLK_KP5 = 261, + SDLK_KP6 = 262, + SDLK_KP7 = 263, + SDLK_KP8 = 264, + SDLK_KP9 = 265, + SDLK_KP_PERIOD = 266, + SDLK_KP_DIVIDE = 267, + SDLK_KP_MULTIPLY = 268, + SDLK_KP_MINUS = 269, + SDLK_KP_PLUS = 270, + SDLK_KP_ENTER = 271, + SDLK_KP_EQUALS = 272, + + /* Arrows + Home/End pad */ + SDLK_UP = 273, + SDLK_DOWN = 274, + SDLK_RIGHT = 275, + SDLK_LEFT = 276, + SDLK_INSERT = 277, + SDLK_HOME = 278, + SDLK_END = 279, + SDLK_PAGEUP = 280, + SDLK_PAGEDOWN = 281, + + /* Function keys */ + SDLK_F1 = 282, + SDLK_F2 = 283, + SDLK_F3 = 284, + SDLK_F4 = 285, + SDLK_F5 = 286, + SDLK_F6 = 287, + SDLK_F7 = 288, + SDLK_F8 = 289, + SDLK_F9 = 290, + SDLK_F10 = 291, + SDLK_F11 = 292, + SDLK_F12 = 293, + SDLK_F13 = 294, + SDLK_F14 = 295, + SDLK_F15 = 296, + + /* Key state modifier keys */ + SDLK_NUMLOCK = 300, + SDLK_CAPSLOCK = 301, + SDLK_SCROLLOCK = 302, + SDLK_RSHIFT = 303, + SDLK_LSHIFT = 304, + SDLK_RCTRL = 305, + SDLK_LCTRL = 306, + SDLK_RALT = 307, + SDLK_LALT = 308, + SDLK_RMETA = 309, + SDLK_LMETA = 310, + SDLK_LSUPER = 311, /* Left "Windows" key */ + SDLK_RSUPER = 312, /* Right "Windows" key */ + SDLK_MODE = 313, /* "Alt Gr" key */ + SDLK_COMPOSE = 314, /* Multi-key compose key */ + + /* Miscellaneous function keys */ + SDLK_HELP = 315, + SDLK_PRINT = 316, + SDLK_SYSREQ = 317, + SDLK_BREAK = 318, + SDLK_MENU = 319, + SDLK_POWER = 320, /* Power Macintosh power key */ + SDLK_EURO = 321, /* Some european keyboards */ + SDLK_UNDO = 322, /* Atari keyboard has Undo */ + + /* Add any other keys here */ + + SDLK_LAST +} SDLKey; + +/* Enumeration of valid key mods (possibly OR'd together) */ +typedef enum { + KMOD_NONE = 0x0000, + KMOD_LSHIFT= 0x0001, + KMOD_RSHIFT= 0x0002, + KMOD_LCTRL = 0x0040, + KMOD_RCTRL = 0x0080, + KMOD_LALT = 0x0100, + KMOD_RALT = 0x0200, + KMOD_LMETA = 0x0400, + KMOD_RMETA = 0x0800, + KMOD_NUM = 0x1000, + KMOD_CAPS = 0x2000, + KMOD_MODE = 0x4000, + KMOD_RESERVED = 0x8000 +} SDLMod; + +#define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) +#define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) +#define KMOD_ALT (KMOD_LALT|KMOD_RALT) +#define KMOD_META (KMOD_LMETA|KMOD_RMETA) + +#endif /* _SDL_keysym_h */ diff --git a/scripts/build.py b/scripts/build.py new file mode 100644 index 0000000..a06338b --- /dev/null +++ b/scripts/build.py @@ -0,0 +1,292 @@ +import imp, optparse, os, re, shutil, sys, zipfile +from optparse import OptionParser +if sys.version_info[0] == 2: + import urllib + url_lib = urllib +elif sys.version_info[0] == 3: + import urllib.request + url_lib = urllib.request +match = re.search('(.*)/', sys.argv[0]) +if match != None: + os.chdir(match.group(1)) +os.chdir('../') + +url_bam = "http://github.com/matricks/bam/zipball/master" +url_DDRace = "http://github.com/GreYFoX/DDRace/zipball/master" +url_teeworlds = "http://github.com/teeworlds/teeworlds/zipball/master" +release_type = "server_release client_release" + +arguments = OptionParser() +arguments.add_option("-b", "--url_bam", dest = "url_bam") +arguments.add_option("-t", "--url_DDRace", dest = "url_DDRace") +arguments.add_option("-r", "--release_type", dest = "release_type") +(options, arguments) = arguments.parse_args() +if options.url_bam == None: + options.url_bam = url_bam +if options.url_DDRace == None: + options.url_DDRace = url_DDRace +if options.release_type == None: + options.release_type = release_type + +bam = options.url_bam[7:].split("/") +version_bam = re.search(r"\d\.\d\.\d", bam[len(bam)-1]) +if version_bam: + version_bam = version_bam.group(0) +else: + version_bam = "trunk" +teeworlds = options.url_DDRace[7:].split("/") +version_teeworlds = re.search(r"\d\.\d\.\d", teeworlds[len(teeworlds)-1]) +if version_teeworlds: + version_teeworlds = version_teeworlds.group(0) +else: + version_teeworlds = "trunk" + +bam_execution_path = "" +if version_bam < "0.3.0": + bam_execution_path = "src%s" % os.sep + +name = "DDRace" + +flag_clean = True +flag_download = True +flag_unpack = True +flag_build_bam = True +flag_build_teeworlds = True +flag_make_release = True + +if os.name == "nt": + platform = "win32" +else: + # get name + osname = os.popen("uname").readline().strip().lower() + if osname == "darwin": + osname = "osx" + + # get arch + machine = os.popen("uname -m").readline().strip().lower() + arch = "unknown" + + if machine[0] == "i" and machine[2:] == "86": + arch = "x86" + elif machine == "x86_64": + arch = "x86_64" + elif "power" in machine.lower(): + arch = "ppc" + + platform = osname + "_" + arch + +print("%s-%s-%s" % (name, version_teeworlds, platform)) + +root_dir = os.getcwd() + os.sep +work_dir = root_dir + "scripts/work" + +def fetch_file(url): + try: + print("trying %s" % url) + real_url = url_lib.urlopen(url).geturl() + local = real_url.split("/") + local = local[len(local)-1].split("?") + local = local[0] + url_lib.urlretrieve(real_url, local) + return local + except: + return False + +def unzip(filename, where): + try: + z = zipfile.ZipFile(filename, "r") + except: + return False + list = "\n" + for name in z.namelist(): + list += "%s\n" % name + try: os.makedirs(where+"/"+os.path.dirname(name)) + except: pass + + try: + f = open(where+"/"+name, "wb") + f.write(z.read(name)) + f.close() + except: pass + + z.close() + + directory = "[^/\n]*?/" + part_1 = "(?<=\n)" + part_2 = "[^/\n]+(?=\n)" + regular_expression = r"%s%s" % (part_1, part_2) + main_directory = re.search(regular_expression, list) + while main_directory == None: + part_1 += directory + regular_expression = r"%s%s" % (part_1, part_2) + main_directory = re.search(regular_expression, list) + main_directory = re.search(r".*/", "./%s" % main_directory.group(0)) + return main_directory.group(0) + +def bail(reason): + print(reason) + os.chdir(work_dir) + sys.exit(-1) + +def clean(): + print("*** cleaning ***") + try: shutil.rmtree(work_dir) + except: pass + +def file_exists(file): + try: + open(file).close() + return True + except: + return False; + +def search_object(directory, object): + directory = os.listdir(directory) + for entry in directory: + match = re.search(object, entry) + if match != None: + return entry + +# clean +if flag_clean: + clean() + +# make dir +try: os.mkdir(work_dir) +except: pass + +# change dir +os.chdir(work_dir) + +# download +if flag_download: + print("*** downloading bam source package ***") + src_package_bam = fetch_file(options.url_bam) + if src_package_bam: + if version_bam == 'trunk': + version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_bam) + if version: + version_bam = version.group(1) + else: + bail("couldn't find bam source package and couldn't download it") + + print("*** downloading %s source package ***" % name) + src_package_teeworlds = fetch_file(options.url_DDRace) + if src_package_teeworlds: + if version_teeworlds == 'trunk': + version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_teeworlds) + if version: + version_teeworlds = version.group(1) + else: + bail("couldn't find %s source package and couldn't download it" % name) + +# unpack +if flag_unpack: + print("*** unpacking source ***") + if hasattr(locals(), 'src_package_bam') == False: + src_package_bam = search_object(work_dir, r"bam.*?\.") + if not src_package_bam: + bail("couldn't find bam source package") + src_dir_bam = unzip(src_package_bam, ".") + if not src_dir_bam: + bail("couldn't unpack bam source package") + + if hasattr(locals(), 'src_package_teeworlds') == False: + src_package_teeworlds = search_object(work_dir, r"teeworlds.*?\.") + if not src_package_bam: + bail("couldn't find %s source package" % name) + src_dir_teeworlds = unzip(src_package_teeworlds, ".") + if not src_dir_teeworlds: + bail("couldn't unpack %s source package" % name) + +# build bam +if flag_build_bam: + print("*** building bam ***") + os.chdir("%s/%s" % (work_dir, src_dir_bam)) + if os.name == "nt": + bam_compiled = False + compiler_bam = ["cl", "gcc"] + for compiler in compiler_bam: + if compiler == "cl": + os.system("make_win32_msvc.bat") + elif compiler == "gcc": + os.system("make_win32_mingw.bat") + if file_exists("%sbam.exe" % bam_execution_path) == True: + bam_compiled = True + break + if bam_compiled == False: + bail("failed to build bam") + else: + os.system("sh make_unix.sh") + if file_exists("%sbam" % bam_execution_path) == False: + bail("failed to build bam") + os.chdir(work_dir) + +# build the game +if flag_build_teeworlds: + print("*** building %s ***" % name) + if hasattr(locals(), 'src_dir_bam') == False: + src_dir_bam = search_object(work_dir, r"bam[^\.]*$") + os.sep + if src_dir_bam: + directory = src_dir_bam + bam_execution_path + file = r"bam" + if os.name == "nt": + file += r"\.exe" + if not search_object(directory, file): + bail("couldn't find bam") + else: + bail("couldn't find bam") + if hasattr(locals(), 'src_dir_teeworlds') == False: + src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") + if not src_dir_teeworlds: + bail("couldn't find %s source" % name) + command = 1 + if os.name == "nt": + file = open("build.bat", "wb") + content = "@echo off\n" + content += "@REM check if we already have the tools in the environment\n" + content += "if exist \"%VCINSTALLDIR%\" (\ngoto compile\n)\n" + content += "@REM Check for Visual Studio\n" + content += "if exist \"%VS100COMNTOOLS%\" (\nset VSPATH=\"%VS100COMNTOOLS%\"\ngoto set_env\n)\n" + content += "if exist \"%VS90COMNTOOLS%\" (\nset VSPATH=\"%VS90COMNTOOLS%\"\ngoto set_env\n)\n" + content += "if exist \"%VS80COMNTOOLS%\" (\nset VSPATH=\"%VS80COMNTOOLS%\"\ngoto set_env\n)\n\n" + content += "echo You need Microsoft Visual Studio 8, 9 or 10 installed\n" + content += "exit\n" + content += "@ setup the environment\n" + content += ":set_env\n" + content += "call %VSPATH%vsvars32.bat\n\n" + content += ":compile\n" + content += 'cd %s\n"%s\\%s%sbam" config\n"%s\\%s%sbam" %s' % (src_dir_teeworlds, work_dir, src_dir_bam, bam_execution_path, work_dir, src_dir_bam, bam_execution_path, options.release_type) + file.write(content.encode()) + file.close() + command = os.system("build.bat") + else: + os.chdir(src_dir_teeworlds) + command = os.system("%s/%s%sbam %s" % (work_dir, src_dir_bam, bam_execution_path, options.release_type)) + if command != 0: + bail("failed to build %s" % name) + os.chdir(work_dir) + +# make release +if flag_make_release: + print("*** making release ***") + if hasattr(locals(), 'src_dir_teeworlds') == False: + src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") + if not src_dir_teeworlds: + bail("couldn't find %s source" % name) + os.chdir(src_dir_teeworlds) + command = '"%s/%s/scripts/make_release.py" %s %s' % (work_dir, src_dir_teeworlds, version_teeworlds, platform) + if os.name != "nt": + command = "python %s" % command + if os.system(command) != 0: + bail("failed to make a relase of %s" % name) + final_output = "FAIL" + for f in os.listdir("."): + if version_teeworlds in f and platform in f and name in f and (".zip" in f or ".tar.gz" in f): + final_output = f + os.chdir(work_dir) + shutil.copy("%s/%s" % (src_dir_teeworlds, final_output), "../"+final_output) + os.chdir(root_dir) + clean() + +print("*** all done ***") diff --git a/scripts/check_header_guards.py b/scripts/check_header_guards.py new file mode 100644 index 0000000..bece10e --- /dev/null +++ b/scripts/check_header_guards.py @@ -0,0 +1,35 @@ +import os + + +PATH = "../src/" + + +def check_file(filename): + file = open(filename) + while 1: + line = file.readline() + if len(line) == 0: + break + if line[0] == "/" or line[0] == "*" or line[0] == "\r" or line[0] == "\n" or line[0] == "\t": + continue + if line[:7] == "#ifndef": + hg = "#ifndef " + ("_".join(filename.split(PATH)[1].split("/"))[:-2]).upper() + "_H" + if line[:-1] != hg: + print "Wrong header guard in " + filename + else: + print "Missing header guard in " + filename + break + file.close() + + + +def check_dir(dir): + list = os.listdir(dir) + for file in list: + if os.path.isdir(dir+file): + if file != "external" and file != "generated": + check_dir(dir+file+"/") + elif file[-2:] == ".h" and file != "keynames.h": + check_file(dir+file) + +check_dir(PATH) diff --git a/scripts/cmd5.py b/scripts/cmd5.py new file mode 100644 index 0000000..f21f7bb --- /dev/null +++ b/scripts/cmd5.py @@ -0,0 +1,36 @@ +import hashlib, sys, re, os + +alphanum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".encode() + +def cstrip(lines): + d = "".encode() + for l in lines: + l = re.sub("#.*".encode(), "".encode(), l) + l = re.sub("//.*".encode(), "".encode(), l) + d += l + " ".encode() + d = re.sub("\/\*.*?\*/".encode(), "".encode(), d) # remove /* */ comments + d = d.replace("\t".encode(), " ".encode()) # tab to space + d = re.sub(" *".encode(), " ".encode(), d) # remove double spaces + d = re.sub("".encode(), "".encode(), d) # remove /* */ comments + + d = d.strip() + + # this eats up cases like 'n {' + i = 1 + while i < len(d)-2: + if d[i:i + 1] == " ".encode(): + if not (d[i - 1:i] in alphanum and d[i+1:i + 2] in alphanum): + d = d[:i] + d[i + 1:] + i += 1 + return d + +f = "".encode() +for filename in sys.argv[1:]: + f += cstrip([l.strip() for l in open(filename, "rb")]) + +hash = hashlib.md5(f).hexdigest().lower()[16:] +#TODO 0.7: improve nethash creation +if hash == "3dc531e4296de555": + hash = "626fce9a778df4d4" +print('#define GAME_NETVERSION_HASH "%s"' % hash) +print('#define GIT_SHORTREV_HASH "%s"' % os.popen('git rev-parse HEAD').readline(8)) diff --git a/scripts/compiler.py b/scripts/compiler.py new file mode 100644 index 0000000..726785e --- /dev/null +++ b/scripts/compiler.py @@ -0,0 +1,658 @@ +#!/usr/bin/python + +import sys +import struct +import os + +option_ptrsize = struct.calcsize("P") +option_intsize = struct.calcsize("l") +option_floatsize = struct.calcsize("f") +option_inttype = "long" +option_floattype = "float" + +class node: + def __init__(self): + self.values = [] + self.children = [] + self.parent = 0 + + def name(self): + if len(self.values): + return self.values[0] + return "" + + def debug_print(self, level): + print (" "*level) + " ".join(self.values), + if len(self.children): + print "{" + for c in self.children: + c.debug_print(level+1) + print (" "*level)+"}" + else: + print "" + + def debug_root(self): + for c in self.children: + c.debug_print(0) + + # TODO: should return list of items in the tree, + def gather(self, str): + def recurse(parts, path, node): + if not len(parts): + r = {} + path = path + "." + node.values[0] + r = [node] + #print "found", path + return r + + l = [] + for c in node.children: + if parts[0] == "*" or c.values[0] == parts[0]: + if len(node.values): + if len(path): + l += recurse(parts[1:], path+"."+node.values[0], c) + else: + l += recurse(parts[1:], node.values[0], c) + else: + l += recurse(parts[1:], path, c) + return l + + parts = str.split(".") + return recurse(parts, "", self) + + def find_node(self, str): + parts = str.split(".") + node = self + for part in parts: + if len(part) == 0: + continue + if part == "parent": + node = node.parent + else: + found = 0 + for c in node.children: + if part == c.values[0]: + node = c + found = 1 + break + + if node == self: + return + return node + + def get_single(self, str): + parts = str.split("@") + index = -1 + if len(parts) == 2: + index = int(parts[1]) + + node = self + if len(parts[0]): + node = self.find_node(parts[0]) + + if not node: + print "failed to get", str + return Null + + if index == -1: + return node.get_path()[1:] + return node.values[index] + + def get_path(self): + if self.parent == 0: + return "" + return self.parent.get_path() + "." + self.values[0] + + def get_single_name(self, str): + return self.get_path()[1:] + "." + str + +class parser: + lines = [] + + def parse_node(self, this_node): + while len(self.lines): + line = self.lines.pop(0) # grab line + + fields = line.strip().split() # TODO: improve this to handle strings with spaces + if not len(fields): + continue + + if fields[-1] == '{': + new_node = node() + new_node.parent = this_node + new_node.values = fields[:-1] + this_node.children += [new_node] + self.parse_node(new_node) + elif fields[-1] == '}': + break + else: + new_node = node() + new_node.parent = this_node + new_node.values = fields + this_node.children += [new_node] + + def parse_file(self, filename): + self.lines = file(filename).readlines() + n = node() + self.parse_node(n) + return n + +def parse_file(filename): + return parser().parse_file(filename) + +class pointer: + def __init__(self, index, target): + self.index = index + self.target = target + +class data_constructor: + def __init__(self): + self.data = "" + self.trans = 0 + self.pointers = [] + self.targets = {} + self.enums = {} + + def get_type(self, s): + return self.trans.types[s] + + def allocate(self, size): + index = len(self.data) + self.data += "\0"*size + return index + + def add_pointer(self, index, target): + self.pointers += [pointer(index, target)] + + def add_enum(self, name, value): + self.enums[name] = value + + def get_enum_value(self, name): + if not name in self.enums: + print "ERROR: couldn't find enum '%s'" % (name) + return self.enums[name] + + def add_target(self, target, index): + # TODO: warn about duplicates + #print "add_target(target='%s' index=%d)" % (target, index) + self.targets[target] = index + + def write(self, index, size, data): + try: + self.data = self.data[:index] + data + self.data[index+size:] + except: + print "write error:" + print "\tself.data =", self.data + print "\tdata =", data + + def patch_pointers(self): + for p in self.pointers: + if p.target in self.targets: + i = self.targets[p.target] + #print "ptr @ %d -> %s -> %d" % (p.index, p.target, i) + data = struct.pack("P", i) + self.write(p.index, len(data), data) + else: + print "ERROR: couldn't find target '%s' for pointer at %d" % (p.target, p.index) + +class type: + def __init__(self): + self.name = "" + + def size(self): + pass + +class structure: + def __init__(self): + self.name = "" + self.members = [] + + def size(self): + s = 0 + for m in self.members: + s += m.size() + return s + + def emit_header_code(self, out): + print >>out, "struct", self.name + print >>out, "{" + for m in self.members: + for l in m.get_code(): + print >>out, "\t" + l + print >>out, "};" + print >>out, "" + + def emit_source_code(self, out): + print >>out, "static void patch_ptr_%s(%s *self, char *base)" % (self.name, self.name) + print >>out, "{" + for m in self.members: + for l in m.get_patch_code("self", "base"): + print >>out, "\t" + l + print >>out, "}" + print >>out, "" + + def emit_data(self, cons, index, src_data): + #print self.name+":" + member_index = index + for m in self.members: + #print "\t" + m.name + m.emit_data(cons, member_index, src_data) + member_index += m.size() + +class variable: + def __init__(self): + self.expr = "" + self.type = "" + self.subtype = "" + + def get_code(self): + return [] + + def get_patch_code(self, ptrname, basename): + return [] + + def emit_data(self, cons, index, src_data): + pass + +class variable_int(variable): + def get_code(self): + return ["%s %s;" % (option_inttype, self.name)] + def size(self): + return option_intsize + def emit_data(self, cons, index, src_data): + try: + value = int(self.expr) + except: + value = int(src_data.get_single(self.expr)) + #print "int", self.name, "=", value, "@", index + data = struct.pack("l", value) + cons.write(index, len(data), data) + +class variable_float(variable): + def get_code(self): + return ["%s %s;" % (option_floattype, self.name)] + def size(self): + return option_floatsize + def emit_data(self, cons, index, src_data): + try: + value = float(self.expr) + except: + value = float(src_data.get_single(self.expr)) + #print "int", self.name, "=", value, "@", index + data = struct.pack("f", value) + cons.write(index, len(data), data) + +class variable_string(variable): + def get_code(self): + return ["char *%s;" % (self.name)] + def get_patch_code(self, ptrname, basename): + return ["patch_ptr((char **)&(%s->%s), %s);" % (ptrname, self.name, basename)] + def size(self): + return option_ptrsize + def emit_data(self, cons, index, src_data): + string = src_data.get_single(self.expr) + string = string.strip()[1:-1] # skip " and " + + string_index = cons.allocate(len(string)+1) + cons.write(string_index, len(string), string) + + data = struct.pack("P", string_index) # TODO: solve this + cons.write(index, len(data), data) + +class variable_ptr(variable): + def get_code(self): + return ["%s *%s;" % (self.subtype, self.name)] + def get_patch_code(self, ptrname, basename): + return ["patch_ptr((char**)&(%s->%s), %s);" % (ptrname, self.name, basename)] + def size(self): + return option_ptrsize + def emit_data(self, cons, index, src_data): + target = src_data.get_single(self.expr) + cons.add_pointer(index, target) + +class variable_enum(variable): + def get_code(self): + return ["long *%s;" % (self.name)] + def size(self): + return option_intsize + def emit_data(self, cons, index, src_data): + target = src_data.get_single(self.expr) + data = struct.pack("l", cons.get_enum_value(target)) + cons.write(index, len(data), data) + +class variable_instance(variable): + def get_code(self): + return ["%s %s;" % (self.subtype, self.name)] + def get_patch_code(self, ptrname, basename): + return ["patch_ptr_%s(&(%s->%s), %s);" % (self.subtype, ptrname, self.name, basename)] + def size(self): + return self.translator.types[self.subtype].size() + def emit_data(self, cons, index, src_data): + target = src_data.find_node(self.expr) + translator.types[self.subtype].emit_data(cons, index, target) + #target = + #cons.add_pointer(index, target) + +class variable_array(variable): + def get_code(self): + return ["long num_%s;" % self.name, + "%s *%s;" % (self.subtype, self.name)] + def get_patch_code(self, ptrname, baseptr): + code = [] + code += ["patch_ptr((char**)&(%s->%s), %s);" % (ptrname, self.name, baseptr)] + code += ["for(int i = 0; i < %s->num_%s; i++)" % (ptrname, self.name)] + code += ["\tpatch_ptr_%s(%s->%s+i, %s);" % (self.subtype, ptrname, self.name, baseptr)] + return code + def emit_data(self, cons, index, src_data): + array_data = src_data.gather(self.expr) + array_type = cons.get_type(self.subtype) + size = array_type.size()*len(array_data) + + #print "packing array", self.name + #print "\ttype =", array_type.name + #print "\tsize =", array_type.size() + array_index = cons.allocate(size) + data = struct.pack("lP", len(array_data), array_index) # TODO: solve this + cons.write(index, len(data), data) + + member_index = array_index + for node in array_data: + cons.add_target(node.get_path()[1:], member_index) + array_type.emit_data(cons, member_index, node) + member_index += array_type.size() + #print "array", member_index + + def size(self): + return option_ptrsize+option_intsize + +class const_arrayint: + def __init__(self): + self.name = "" + self.values = [] + + def emit_header_code(self, out): + print >>out, "enum" + print >>out, "{" + for i in xrange(0, len(self.values)): + print >>out, "\t%s_%s = %d," % (self.name.upper(), self.values[i].upper(), i) + + print >>out, "\tNUM_%sS = %d" % (self.name.upper(), len(self.values)) + print >>out, "};" + print >>out, "" + +class translator: + def __init__(self): + self.types = {} + self.structs = [] + self.constants = [] + self.data = 0 + self.srcdata = 0 + + self.types["int"] = variable_int() + self.types["float"] = variable_float() + self.types["string"] = variable_string() + self.types["ptr"] = variable_ptr() + self.types["array"] = variable_array() + + def parse_variable(self, node): + if len(node.values) != 4: + print node.values + raise "error parsing variable" + + type = node.values[0] + subtype = "" + if type == "int": + v = variable_int() + elif type == "enum": + v = variable_enum() + elif type == "float": + v = variable_float() + elif type == "string": + v = variable_string() + else: + # complex type + parts = type.split(":") + if len(parts) != 2: + raise "can't emit code for variable %s of type %s" % (self.name, self.type) + elif parts[0] == "ptr": + subtype = parts[1] + v = variable_ptr() + elif parts[0] == "instance": + subtype = parts[1] + v = variable_instance() + elif parts[0] == "array": + subtype = parts[1] + v = variable_array() + else: + raise "can't emit code for variable %s of type %s" % (self.name, self.type) + + v.translator = self + v.type = node.values[0] + v.subtype = subtype + v.name = node.values[1] + assignment = node.values[2] + v.expr = node.values[3] + if assignment != "=": + raise "error parsing variable. expected =" + return v + + def parse_struct(self, node): + if len(node.values) != 2: + raise "error parsing struct" + s = structure() + s.name = node.values[1] + + for statement in node.children: + s.members += [self.parse_variable(statement)] + return s + + def parse_constant(self, node): + if len(node.values) != 5: + print node.values + raise "error parsing constant" + + type = node.values[1] + name = node.values[2] + assignment = node.values[3] + expression = node.values[4] + + if assignment != "=": + print node.values + raise "error parsing constant" + + ints = const_arrayint() + ints.name = name + + items = self.srcdata.gather(expression) + for c in items: + ints.values += [c.name()] + self.constants += [ints] + + def parse(self, script, srcdata): + self.srcdata = srcdata + for statement in script.children: + if statement.values[0] == "struct": + s = self.parse_struct(statement) + self.structs += [s] + self.types[s.name] = s + elif statement.values[0] == "const": + self.parse_constant(statement) + else: + raise "unknown statement:" + statement + + def emit_header_code(self, out): + for c in self.constants: + c.emit_header_code(out) + + for s in self.structs: + s.emit_header_code(out) + print >>out, "" + print >>out, "struct data_container *load_data_from_file(const char *filename);" + print >>out, "struct data_container *load_data_from_memory(unsigned char *filename);" + print >>out, "" + + + def emit_source_code(self, out, header_filename): + print >>out, ''' + +#include "%s" +#include <stdio.h> +#include <stdlib.h> + +static void patch_ptr(char **ptr, char *base) +{ + *ptr = base+(size_t)(*ptr); +} +''' % header_filename + + for s in self.structs: + s.emit_source_code(out) + print >>out, ''' + +data_container *load_data_from_memory(unsigned char *mem) +{ + if(mem[0] != sizeof(void*)) + return 0; + if(mem[1] != sizeof(long)) + return 0; + if(mem[2] != sizeof(float)) + return 0; + + /* patch all pointers */ + data_container *con = (data_container*)(mem + 4); + patch_ptr_data_container(con, (char *)con); + return con; +} + +data_container *load_data_from_file(const char *filename) +{ + unsigned char *data = 0; + int size; + + /* open file */ + FILE *f = fopen(filename, "rb"); + + /* get size */ + fseek(f, 0, SEEK_END); + size = ftell(f); + fseek(f, 0, SEEK_SET); + + /* allocate, read data and close file */ + data = (unsigned char *)malloc(size); + fread(data, 1, size, f); + fclose(f); + + return load_data_from_memory(data); +} + +''' + + def emit_data(self): + for s in self.structs: + if s.name == "data_container": + #print "found data_container" + cons = data_constructor() + cons.trans = self + i = cons.allocate(s.size()) + s.emit_data(cons, i, self.srcdata) + cons.patch_pointers() + header = struct.pack("bbbb", option_ptrsize, option_intsize, option_floatsize, 0) + return header + cons.data + +def create_translator(script, srcdata): + t = translator() + t.parse(script, srcdata) + return t + +def validate(script, validator): + def validate_values(values, check): + if not len(check) or check[0] == "*": + print "too many values" + return + p = check[0].split(":") + type = p[0] + name = p[1] + + # TODO: check type and stuff + + # recurse + if len(values) > 1: + if not len(check): + print "unexpected value" + validate_values(values[1:], check[1:]) + else: + if len(check) > 1 and check[1] != "*": + print "to few values" + + if len(script.values): + validate_values(script.values, validator.values) + + for child in script.children: + tag = child.values[0] + n = validator.find_node("tag:"+tag) + if not n: + found = 0 + for vc in validator.children: + if "ident:" in vc.values[0]: + validate(child, vc) + print vc.values[0] + found = 1 + break + + if not found: + print "error:", tag, "not found" + else: + print "tag:"+tag + validate(child, n) + +input_filename = sys.argv[1] +script_filename = sys.argv[2] + +output_filename = 0 +coutput_filename = 0 +header_filename = 0 +source_filename = 0 +sheader_filename = 0 + +if sys.argv[3] == '-h': + header_filename = sys.argv[4] +elif sys.argv[3] == '-s': + source_filename = sys.argv[4] + sheader_filename = sys.argv[5] +elif sys.argv[3] == '-d': + output_filename = sys.argv[4] +elif sys.argv[3] == '-c': + coutput_filename = sys.argv[4] + +srcdata = parse_file(input_filename) +script = parse_file(script_filename) + +translator = create_translator(script, srcdata) + +if header_filename: + translator.emit_header_code(file(header_filename, "w")) +if source_filename: + translator.emit_source_code(file(source_filename, "w"), os.path.basename(sheader_filename)) + +if output_filename: + rawdata = translator.emit_data() + file(output_filename, "wb").write(rawdata) +if coutput_filename: + i = 0 + rawdata = translator.emit_data() + f = file(coutput_filename, "w") + + print >>f,"unsigned char internal_data[] = {" + print >>f,str(ord(rawdata[0])), + for d in rawdata[1:]: + s = ","+str(ord(d)) + print >>f,s, + i += len(s)+1 + + if i >= 70: + print >>f,"" + i = 0 + print >>f,"" + print >>f,"};" + print >>f,"" + f.close() diff --git a/scripts/copyright.py b/scripts/copyright.py new file mode 100644 index 0000000..269ac7a --- /dev/null +++ b/scripts/copyright.py @@ -0,0 +1,65 @@ +import os, re, sys +match = re.search('(.*)/', sys.argv[0]) +if match != None: + os.chdir(match.group(1)) +os.chdir('../') + +notice = [b"/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n", b"/* If you are missing that file, acquire a complete release at teeworlds.com. */\n"] +exclude = ["src%sengine%sexternal" % (os.sep, os.sep), "src%sosxlaunch" % os.sep] +updated_files = 0 + +def fix_copyright_notice(filename): + global updated_files + f = open(filename, "rb") + lines = f.readlines() + f.close() + + i = 0 + length_lines = len(lines) + if length_lines > 0: + while i <= length_lines and (lines[i].decode("utf-8").lstrip()[:2] == "//" or lines[i].decode("utf-8").lstrip()[:2] == "/*" and lines[i].decode("utf-8").rstrip()[-2:] == "*/") and ("Magnus" in lines[i].decode("utf-8") or "magnus" in lines[i].decode("utf-8") or "Auvinen" in lines[i].decode("utf-8") or "auvinen" in lines[i].decode("utf-8") or "license" in lines[i].decode("utf-8") or "teeworlds" in lines[i].decode("utf-8")): + i += 1 + length_notice = len(notice) + if i > 0: + j = 0 + while lines[j] == notice[j]: + j += 1 + if j == length_notice: + return + k = j + j = 0 + while j < length_notice -1 - k: + lines = [notice[j]] + lines + j += 1 + while j < length_notice: + lines[j] = notice[j] + j += 1 + if length_lines == 0 or i == 0: + j = length_notice - 1 + while j >= 0: + lines = [notice[j]] + lines + j -= 1 + open(filename, "wb").writelines(lines) + updated_files += 1 + +skip = False +for root, dirs, files in os.walk("src"): + for excluding in exclude: + if root[:len(excluding)] == excluding: + skip = True + break + if skip == True: + skip = False + continue + for name in files: + filename = os.path.join(root, name) + + if filename[-2:] != ".c" and filename[-4:] != ".cpp" and filename[-2:] != ".h": + continue + + fix_copyright_notice(filename) + +output = "file" +if updated_files != 1: + output += "s" +print("*** updated %d %s ***" % (updated_files, output)) diff --git a/scripts/count_source.sh b/scripts/count_source.sh new file mode 100644 index 0000000..0f4a6a6 --- /dev/null +++ b/scripts/count_source.sh @@ -0,0 +1 @@ +svn blame `svn -R ls | grep ^src | grep -v external | grep -v /$ | grep -v \.txt` | python scripts/process_blame.py diff --git a/scripts/dat2c.py b/scripts/dat2c.py new file mode 100644 index 0000000..09517ca --- /dev/null +++ b/scripts/dat2c.py @@ -0,0 +1,17 @@ +import sys + +data = file(sys.argv[1], "rb").read() + +i = 0 +print "unsigned char", sys.argv[2], "[] = {" +print str(ord(data[0])), +for d in data[1:]: + s = ","+str(ord(d)) + print s, + i += len(s)+1 + + if i >= 70: + print "" + i = 0 +print "" +print "};" diff --git a/scripts/font_converter.py b/scripts/font_converter.py new file mode 100644 index 0000000..09d2217 --- /dev/null +++ b/scripts/font_converter.py @@ -0,0 +1,148 @@ +from __future__ import with_statement +import struct +import sys +import re + +def convert(input, output): + with open(input, "r") as in_file: + with open(output, "w") as out_file: + def build_dic(parts): + dic = {} + + for part in parts: + key, value = part.split('=') + + try: + dic[key] = int(value) + except: + dic[key] = value + + return dic + + def get_entry(line): + while line[-1] == "\r" or line[-1] == "\n": + line = line[0:-1] + parts = [] + + quote = 0 + part = "" + + for c in line: + if c == "\"": + quote = 1-quote + elif c == " " and not quote: + if part: + parts.append(part) + part = "" + else: + part += c + + if part: + parts.append(part) + + type = parts[0] + + dic = build_dic(parts[1:]) + + return type, dic + + def write_int16(val): + out_file.write(struct.pack('<h', val)) + + def write_info(dic): + write_int16(dic["size"]) + + def write_common(dic): + write_int16(dic["scaleW"]) + write_int16(dic["scaleH"]) + write_int16(dic["lineHeight"]) + write_int16(dic["base"]) + + def write_page(dic): + pass + + def write_chars(dic): + pass + + def write_char(dic): + write_int16(dic["x"]) + write_int16(dic["y"]) + write_int16(dic["width"]) + write_int16(dic["height"]) + write_int16(dic["xoffset"]) + write_int16(dic["yoffset"]) + write_int16(dic["xadvance"]) + + def write_default_char(): + write_int16(0) + write_int16(0) + write_int16(0) + write_int16(0) + write_int16(0) + write_int16(0) + write_int16(0) + + def write_kernings(dic): + pass + + def write_kerning(dic): + write_int16(dic["amount"]) + + def write_default_kerning(): + write_int16(0) + + chars = [] + kernings = [] + for i in range(256): + chars.append(None) + for i in range(256*256): + kernings.append(None) + + def save_char(dic): + if dic["id"] < 256: + chars[dic["id"]] = dic + + def save_kerning(dic): + kernings[dic["first"] + dic["second"]*256] = dic + + write_table = { + "info": write_info, + "common": write_common, + "page": write_page, + "chars": write_chars, + "char": save_char, + "kernings": write_kernings, + "kerning": save_kerning + } + + for line in in_file: + type, dic = get_entry(line) + + write_table[type](dic) + + for i in range(256): + if chars[i]: + write_char(chars[i]) + else: + write_default_char() + + for i in range(256*256): + if kernings[i]: + write_kerning(kernings[i]) + else: + write_default_kerning() + +if len(sys.argv) >= 2: + print "converting..." + + filenames = sys.argv[1:] + for filename in filenames: + input = filename + output = re.sub("fnt$", "tfnt", input) + + print "input: %s, output: %s" % (input, output) + convert(input, output) + print "done!" +else: + print "font converter! converts .fnt files to teeworlds .tfnt" + print "usage: font_converter <input>" diff --git a/scripts/font_installer.sh b/scripts/font_installer.sh new file mode 100644 index 0000000..5b99b68 --- /dev/null +++ b/scripts/font_installer.sh @@ -0,0 +1,3 @@ +echo Generating .fnts... +../../font_generator/a.out +python ../scripts/font_converter.py default*.fnt diff --git a/scripts/gen_keys.py b/scripts/gen_keys.py new file mode 100644 index 0000000..51a659d --- /dev/null +++ b/scripts/gen_keys.py @@ -0,0 +1,65 @@ +import sys, os + +# genereate keys.h file +f = file("src/engine/keys.h", "w") + +keynames = [] +for i in range(0, 512): + keynames += ["&%d"%i] + +print >>f, "#ifndef ENGINE_KEYS_H" +print >>f, "#define ENGINE_KEYS_H" +print >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */' +print >>f, "enum" +print >>f, "{" + +highestid = 0 +for line in open("scripts/SDL_keysym.h"): + l = line.strip().split("=") + if len(l) == 2 and "SDLK_" in line: + key = l[0].strip().replace("SDLK_", "KEY_") + value = int(l[1].split(",")[0].strip()) + print >>f, "\t%s = %d,"%(key, value) + + keynames[value] = key.replace("KEY_", "").lower() + + if value > highestid: + highestid =value + +print >>f, "\tKEY_MOUSE_1 = %d,"%(highestid+1); keynames[highestid+1] = "mouse1" +print >>f, "\tKEY_MOUSE_2 = %d,"%(highestid+2); keynames[highestid+2] = "mouse2" +print >>f, "\tKEY_MOUSE_3 = %d,"%(highestid+3); keynames[highestid+3] = "mouse3" +print >>f, "\tKEY_MOUSE_4 = %d,"%(highestid+4); keynames[highestid+4] = "mouse4" +print >>f, "\tKEY_MOUSE_5 = %d,"%(highestid+5); keynames[highestid+5] = "mouse5" +print >>f, "\tKEY_MOUSE_6 = %d,"%(highestid+6); keynames[highestid+6] = "mouse6" +print >>f, "\tKEY_MOUSE_7 = %d,"%(highestid+7); keynames[highestid+7] = "mouse7" +print >>f, "\tKEY_MOUSE_8 = %d,"%(highestid+8); keynames[highestid+8] = "mouse8" +print >>f, "\tKEY_MOUSE_WHEEL_UP = %d,"%(highestid+9); keynames[highestid+9] = "mousewheelup" +print >>f, "\tKEY_MOUSE_WHEEL_DOWN = %d,"%(highestid+10); keynames[highestid+10] = "mousewheeldown" +print >>f, "\tKEY_MOUSE_9 = %d,"%(highestid+11); keynames[highestid+11] = "mouse9" +print >>f, "\tKEY_LAST," + +print >>f, "};" +print >>f, "" +print >>f, "#endif" + +# generate keynames.c file +f = file("src/engine/client/keynames.h", "w") +print >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */' +print >>f, '' +print >>f, '#ifndef KEYS_INCLUDE' +print >>f, '#error do not include this header!' +print >>f, '#endif' +print >>f, '' +print >>f, "#include <string.h>" +print >>f, "" +print >>f, "const char g_aaKeyStrings[512][16] =" +print >>f, "{" +for n in keynames: + print >>f, '\t"%s",'%n + +print >>f, "};" +print >>f, "" + +f.close() + diff --git a/scripts/linecount.sh b/scripts/linecount.sh new file mode 100644 index 0000000..7b2116e --- /dev/null +++ b/scripts/linecount.sh @@ -0,0 +1,2 @@ +#!/bin/sh +wc `find . -iname *.cpp` `find . -iname *.h` `find . -iname *.c` diff --git a/scripts/make_android.sh b/scripts/make_android.sh new file mode 100644 index 0000000..5da957a --- /dev/null +++ b/scripts/make_android.sh @@ -0,0 +1,27 @@ +# This is how I build DDNet for Android: + +# Cloning the building repo with the SDL port for Android by Pelya +cd /media +git clone https://github.com/pelya/commandergenius.git + +# Get the most recent DDNet source +cd /media/commandergenius/project/jni/application/teeworlds +rm -rf src master.zip* +wget "https://github.com/ddnet/ddnet/archive/master.zip" +unzip ddnet-master.zip +mv ddnet-master src +mkdir src/src/game/generated +# Also the generated files don't get generated, copy them by hand +cp /media/ddrace/src/game/generated/* src/src/game/generated +rm -rf AndroidData +./AndroidPreBuild.sh + +# Actual compilation, needs a key to sign +cd /media/commandergenius +ln -s teeworlds project/jni/application/src +./changeAppSettings.sh -a +android update project -p project +./build.sh +jarsigner -verbose -keystore ~/.android/release.keystore -storepass MYSECRETPASS -sigalg MD5withRSA -digestalg SHA1 project/bin/MainActivity-release-unsigned.apk androidreleasekey +zipalign 4 project/bin/MainActivity-release-unsigned.apk project/bin/MainActivity-release.apk +scp project/bin/MainActivity-release.apk ddnet:/var/www/downloads/DDNet-$VERSION.apk diff --git a/scripts/make_docs.sh b/scripts/make_docs.sh new file mode 100644 index 0000000..3ad7ccf --- /dev/null +++ b/scripts/make_docs.sh @@ -0,0 +1 @@ +perl docs/tool/NaturalDocs -i src/game -i src/engine -xi src/engine/external -p docs/conf -o html docs/output diff --git a/scripts/make_release.py b/scripts/make_release.py new file mode 100644 index 0000000..fcba319 --- /dev/null +++ b/scripts/make_release.py @@ -0,0 +1,225 @@ +import shutil, os, sys, zipfile + +#valid_platforms = ["win32", "linux86", "linux86_64", "src"] + +if len(sys.argv) != 3: + print("wrong number of arguments") + print(sys.argv[0], "VERSION PLATFORM") + sys.exit(-1) + +name = "DDNet" +version = sys.argv[1] +platform = sys.argv[2] +exe_ext = "" +use_zip = 0 +use_gz = 1 +use_dmg = 0 +use_bundle = 0 +include_data = True +include_exe = True +include_src = False + +if platform == "src": + include_data = True + include_exe = False + include_src = True + use_zip = 1 + use_gz = 1 + +#if not platform in valid_platforms: +# print("not a valid platform") +# print(valid_platforms) +# sys.exit(-1) + +if platform == 'win32' or platform == 'win64': + exe_ext = ".exe" + use_zip = 1 + use_gz = 0 +if platform == 'osx': + use_dmg = 1 + use_gz = 0 + use_bundle = 1 + +def copydir(src, dst, excl=[]): + for root, dirs, files in os.walk(src, topdown=True): + if "/." in root or "\\." in root: + continue + for name in dirs: + if name[0] != '.': + os.mkdir(os.path.join(dst, root, name)) + for name in files: + if name[0] != '.': + shutil.copy(os.path.join(root, name), os.path.join(dst, root, name)) + +package = "%s-%s-%s" %(name, version, platform) +package_dir = package + +print("cleaning target") +shutil.rmtree(package_dir, True) +os.mkdir(package_dir) + +print("adding files") +shutil.copy("license.txt", package_dir) +shutil.copy("storage.cfg", package_dir) +shutil.copy("autoexec_server.cfg", package_dir) + +if include_data and not use_bundle: + os.mkdir(os.path.join(package_dir, "data")) + copydir("data", package_dir) + if platform[:3] == "win": + shutil.copy("other/config_directory.bat", package_dir) + shutil.copy("SDL.dll", package_dir) + shutil.copy("freetype.dll", package_dir) + if platform == "win32": + shutil.copy("libgcc_s_sjlj-1.dll", package_dir) + shutil.copy("libidn-11.dll", package_dir) + elif platform == "win64": + shutil.copy("libgcc_s_seh-1.dll", package_dir) + shutil.copy("libwinpthread-1.dll", package_dir) + shutil.copy("libogg-0.dll", package_dir) + shutil.copy("libopus-0.dll", package_dir) + shutil.copy("libopusfile-0.dll", package_dir) + #shutil.copy("libmysql.dll", package_dir) + #shutil.copy("mysqlcppconn.dll", package_dir) + shutil.copy("libcurl.dll", package_dir) + shutil.copy("libeay32.dll", package_dir) + shutil.copy("ssleay32.dll", package_dir) + shutil.copy("zlib1.dll", package_dir) + +if include_exe and not use_bundle: + shutil.copy(name+exe_ext, package_dir) + shutil.copy(name+"-Server"+exe_ext, package_dir) + shutil.copy("dilate"+exe_ext, package_dir) + shutil.copy("config_store"+exe_ext, package_dir) + shutil.copy("config_retrieve"+exe_ext, package_dir) + #shutil.copy(name+"-Server_sql"+exe_ext, package_dir) + +if include_src: + for p in ["src", "scripts", "datasrc", "other", "objs"]: + os.mkdir(os.path.join(package_dir, p)) + copydir(p, package_dir) + shutil.copy("bam.lua", package_dir) + shutil.copy("configure.lua", package_dir) + +if use_bundle: + bins = [name, name+'-Server', 'dilate', 'config_store', 'config_retrieve', 'serverlaunch'] + platforms = ('x86', 'x86_64', 'ppc') + for bin in bins: + to_lipo = [] + for p in platforms: + fname = bin+'_'+p + if os.path.isfile(fname): + to_lipo.append(fname) + if to_lipo: + os.system("lipo -create -output "+bin+" "+" ".join(to_lipo)) + + # create Teeworlds appfolder + clientbundle_content_dir = os.path.join(package_dir, "DDNet.app/Contents") + clientbundle_bin_dir = os.path.join(clientbundle_content_dir, "MacOS") + clientbundle_resource_dir = os.path.join(clientbundle_content_dir, "Resources") + clientbundle_framework_dir = os.path.join(clientbundle_content_dir, "Frameworks") + binary_path = clientbundle_bin_dir + "/" + name+exe_ext + os.mkdir(os.path.join(package_dir, "DDNet.app")) + os.mkdir(clientbundle_content_dir) + os.mkdir(clientbundle_bin_dir) + os.mkdir(clientbundle_resource_dir) + os.mkdir(clientbundle_framework_dir) + os.mkdir(os.path.join(clientbundle_resource_dir, "data")) + copydir("data", clientbundle_resource_dir) + + + shutil.copy("other/icons/DDNet.icns", clientbundle_resource_dir) + #shutil.copy("other/icons/Teeworlds.icns", clientbundle_resource_dir) + shutil.copy(name+exe_ext, clientbundle_bin_dir) + os.system("install_name_tool -change /opt/X11/lib/libfreetype.6.dylib @executable_path/../Frameworks/libfreetype.6.dylib " + binary_path) + os.system("install_name_tool -change /Library/Frameworks/SDL.framework/SDL @executable_path/../Frameworks/SDL.framework/SDL " + binary_path) + os.system("cp -R /Library/Frameworks/SDL.framework " + clientbundle_framework_dir) + os.system("cp /opt/X11/lib/libfreetype.6.dylib " + clientbundle_framework_dir) + file(os.path.join(clientbundle_content_dir, "Info.plist"), "w").write(""" +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleExecutable</key> + <string>DDNet</string> + <key>CFBundleIconFile</key> + <string>DDNet</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>%s</string> + <key>CFBundleIdentifier</key> + <string>org.DDNetClient.app</string> +</dict> +</plist> + """ % (version)) + file(os.path.join(clientbundle_content_dir, "PkgInfo"), "w").write("APPL????") + + # create Teeworlds Server appfolder + serverbundle_content_dir = os.path.join(package_dir, "DDNet-Server.app/Contents") + serverbundle_bin_dir = os.path.join(serverbundle_content_dir, "MacOS") + serverbundle_resource_dir = os.path.join(serverbundle_content_dir, "Resources") + os.mkdir(os.path.join(package_dir, "DDNet-Server.app")) + os.mkdir(serverbundle_content_dir) + os.mkdir(serverbundle_bin_dir) + os.mkdir(serverbundle_resource_dir) + os.mkdir(os.path.join(serverbundle_resource_dir, "data")) + os.mkdir(os.path.join(serverbundle_resource_dir, "data/maps")) + os.mkdir(os.path.join(serverbundle_resource_dir, "data/mapres")) + copydir("data/maps", serverbundle_resource_dir) + shutil.copy("other/icons/DDNet-Server.icns", serverbundle_resource_dir) + shutil.copy(name+"-Server"+exe_ext, serverbundle_bin_dir) + shutil.copy("serverlaunch"+exe_ext, serverbundle_bin_dir + "/"+name+"_server") + file(os.path.join(serverbundle_content_dir, "Info.plist"), "w").write(""" +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleExecutable</key> + <string>DDNet_server</string> + <key>CFBundleIconFile</key> + <string>DDNet-Server</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>%s</string> +</dict> +</plist> + """ % (version)) + file(os.path.join(serverbundle_content_dir, "PkgInfo"), "w").write("APPL????") + +if use_zip: + print("making zip archive") + zf = zipfile.ZipFile("%s.zip" % package, 'w', zipfile.ZIP_DEFLATED) + + for root, dirs, files in os.walk(package_dir, topdown=True): + for name in files: + n = os.path.join(root, name) + zf.write(n, n) + #zf.printdir() + zf.close() + +if use_gz: + print("making tar.gz archive") + os.system("tar czf %s.tar.gz %s" % (package, package_dir)) + +if use_dmg: + print("making disk image") + os.system("rm -f %s.dmg %s_temp.dmg" % (package, package)) + os.system("hdiutil create -srcfolder %s -volname DDNet -quiet %s_temp" % (package_dir, package)) + os.system("hdiutil convert %s_temp.dmg -format UDBZ -o %s.dmg -quiet" % (package, package)) + os.system("rm -f %s_temp.dmg" % package) + +print("done") diff --git a/scripts/make_src.py b/scripts/make_src.py new file mode 100644 index 0000000..33e0f92 --- /dev/null +++ b/scripts/make_src.py @@ -0,0 +1,41 @@ +import os, shutil, zipfile, sys + +if len(sys.argv) <= 1: + print "%s VERSION [SVN TREE]" % sys.argv[0] + sys.exit(-1) + +version = sys.argv[1] +svn_tree = "tags/release-%s" % version + +if len(sys.argv) > 2: + svn_tree = sys.argv[2] + +# make clean +if 1: + try: shutil.rmtree("srcwork") + except: pass + try: os.mkdir("srcwork") + except: pass + +root_dir = os.getcwd() + "/srcwork" + +# change dir +os.chdir(root_dir) + +# fix bam +#if 1: +# os.system("svn export http://stalverk80.se/svn/bam bam") +# z = zipfile.ZipFile("../bam.zip", "w") +# for root, dirs, files in os.walk("bam"): +# for f in files: +# z.write(root+"/"+ f) +# z.close() + +if 1: + os.system("svn export svn://svn.teeworlds.com/teeworlds/%s teeworlds" % svn_tree) + os.chdir("teeworlds") + os.system("python scripts/make_release.py %s src" % version) + os.chdir(root_dir) + for f in os.listdir("teeworlds"): + if "teeworlds" in f and "src" in f and (".zip" in f or ".tar.gz" in f): + shutil.copy("teeworlds/"+f, "../" + f) diff --git a/scripts/mass_server.py b/scripts/mass_server.py new file mode 100644 index 0000000..d9a304d --- /dev/null +++ b/scripts/mass_server.py @@ -0,0 +1,50 @@ +#from random import choice + +import random +import os + +masterservers = ["localhost 8300"] + +maps = [ + ["dm1", "dm2", "dm6"], + ["dm1", "dm2", "dm6"], + ["ctf1", "ctf2", "ctf3"], +] + +servernames = [ + "%s playhouse", + "%s own server", +] + +nicks = [] +for l in file("scripts/nicks.txt"): + nicks += l.replace(":port80c.se.quakenet.org 353 matricks_ = #pcw :", "").strip().split() +inick = 0 + +def get_nick(): + global inick, nicks + inick = (inick+1)%len(nicks) + return nicks[inick].replace("`", "\`") + +for s in xrange(0, 350): + cmd = "./fake_server_d_d " + cmd += '-n "%s" ' % (random.choice(servernames) % get_nick()) + for m in masterservers: + cmd += '-m %s '%m + + max = random.randint(2, 16) + cmd += "-x %d " % max + + t = random.randint(0, 2) + + cmd += '-a "%s" ' % random.choice(maps[t]) + cmd += '-g %d ' % random.randint(0, 100) + cmd += '-t %d ' % t # dm, tdm, ctf + cmd += "-f %d " % random.randint(0, 1) # password protected + + for p in xrange(0, random.randint(0, max)): + cmd += '-p "%s" %d ' % (get_nick(), random.randint(0, 20)) + + print cmd + os.popen2(cmd) + diff --git a/scripts/netobj.py b/scripts/netobj.py new file mode 100644 index 0000000..d8c5a7c --- /dev/null +++ b/scripts/netobj.py @@ -0,0 +1,430 @@ +import sys, os + +line_count = 0 + +class variable: + name = "unknown" + def __init__(self, args, name): + global line_count + self.name = name + self.line = line_count + def emit_declaration(self): + return ["\tint %s;" % self.name] + def linedef(self): + return "#line %d" % self.line + def emit_secure(self, parent): + return [] + def emit_unpack(self): + return ["msg.%s = msg_unpack_int();" % self.name] + def emit_unpack_check(self): + return [] + def emit_pack(self): + return ["\t\tmsg_pack_int(%s);" % self.name] + +class var_any(variable): + def __init__(self, args, name): + variable.__init__(self, args, name) + +class var_range(variable): + def __init__(self, args, name): + variable.__init__(self, args, name) + self.min = args[0] + self.max = args[1] + def emit_unpack_check(self): + return ["if(msg.%s < %s || msg.%s > %s) { msg_failed_on = \"%s\"; return 0; }" % (self.name, self.min, self.name, self.max, self.name)] + def emit_secure(self, parent): + return [self.linedef(), "obj->%s = netobj_clamp_int(\"%s.%s\", obj->%s, %s, %s);" % (self.name, parent.name, self.name, self.name, self.min, self.max)] + +class var_string(variable): + def __init__(self, args, name): + variable.__init__(self, args, name) + +class var_string(variable): + def __init__(self, args, name): + variable.__init__(self, args, name) + def emit_declaration(self): + return ["\tconst char *%s;" % self.name] + def emit_unpack(self): + return ["msg.%s = msg_unpack_string();" % self.name] + def emit_pack(self): + return ["\t\tmsg_pack_string(%s, -1);" % self.name] + +class object: + def __init__(self, line): + fields = line.split() + self.name = fields[1] + self.extends = None + if len(fields) == 4 and fields[2] == "extends": + self.extends = fields[3] + self.enum_name = "NETOBJTYPE_%s" % self.name.upper() + self.struct_name = "NETOBJ_%s" % self.name.upper() + self.members = [] + + def parse(self, lines): + global line_count + for index in xrange(0, len(lines)): + line_count += 1 + line = lines[index] + if not len(line): + continue + + if line == "end": + return lines[index+1:] + else: + # check for argument + fields = line.split(")", 1) + if len(fields) == 2: + names = [line.strip() for line in fields[1].split(",")] + l = fields[0].split("(", 1) + type = l[0] + args = [line.strip() for line in l[1].split(",")] + else: + l = fields[0].split(None, 1) + type = l[0] + args = [] + names = [line.strip() for line in l[1].split(",")] + + for name in names: + create_string = 'var_%s(%s, "%s")' % (type, args, name) + new_member = eval(create_string) + self.members += [new_member] + + raise BaseException("Parse error") + + def emit_declaration(self): + lines = [] + if self.extends: + lines += ["struct %s : public NETOBJ_%s\n {" % (self.struct_name, self.extends.upper())] + else: + lines += ["struct %s\n {" % self.struct_name] + for m in self.members: + lines += m.emit_declaration() + lines += ["};"] + return lines + + def emit_secure(self): + lines = [] + for m in self.members: + lines += m.emit_secure(self) + return lines + +class message: + def __init__(self, line): + fields = line.split() + self.name = fields[1] + self.enum_name = "NETMSGTYPE_%s" % self.name.upper() + self.struct_name = "NETMSG_%s" % self.name.upper() + self.members = [] + + def parse(self, lines): + global line_count + for index in xrange(0, len(lines)): + line_count += 1 + line = lines[index] + if not len(line): + continue + + if line == "end": + return lines[index+1:] + else: + # check for argument + fields = line.split(")", 1) + if len(fields) == 2: + names = [line.strip() for line in fields[1].split(",")] + l = fields[0].split("(", 1) + type = l[0] + args = [line.strip() for line in l[1].split(",")] + else: + l = fields[0].split(None, 1) + type = l[0] + args = [] + names = [line.strip() for line in l[1].split(",")] + + for name in names: + create_string = 'var_%s(%s, "%s")' % (type, args, name) + new_member = eval(create_string) + self.members += [new_member] + + raise BaseException("Parse error") + + def emit_declaration(self): + lines = [] + lines += ["struct %s\n {" % self.struct_name] + for m in self.members: + lines += m.emit_declaration() + lines += ["\tvoid pack(int flags)"] + lines += ["\t{"] + lines += ["\t\tmsg_pack_start(%s, flags);" % self.enum_name] + for m in self.members: + lines += m.emit_pack() + lines += ["\t\tmsg_pack_end();"] + lines += ["\t}"] + lines += ["};"] + return lines + + def emit_unpack(self): + lines = [] + for m in self.members: + lines += m.emit_unpack() + for m in self.members: + lines += m.emit_unpack_check() + return lines + + def emit_pack(self): + lines = [] + for m in self.members: + lines += m.emit_pack() + return lines + + +class event(object): + def __init__(self, line): + object.__init__(self, line) + self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() + self.struct_name = "NETEVENT_%s" % self.name.upper() + +class raw_reader: + def __init__(self): + self.raw_lines = [] + def parse(self, lines): + global line_count + for index in xrange(0, len(lines)): + line_count += 1 + line = lines[index] + if not len(line): + continue + + if line == "end": + return lines[index+1:] + else: + self.raw_lines += [line] + + raise BaseException("Parse error") + +class proto: + def __init__(self): + self.objects = [] + self.messages = [] + self.source_raw = [] + self.header_raw = [] + +def load(filename): + # read the file + global line_count + line_count = 0 + lines = [line.split("//", 2)[0].strip() for line in file(filename).readlines()] + + p = proto() + + while len(lines): + line_count += 1 + line = lines[0] + + if not len(line): + del lines[0] + continue + + fields = line.split(None, 1) + + del lines[0] + + if fields[0] == "object": + new_obj = object(line) + lines = new_obj.parse(lines) + p.objects += [new_obj] + elif fields[0] == "message": + new_msg = message(line) + lines = new_msg.parse(lines) + p.messages += [new_msg] + elif fields[0] == "event": + new_obj = event(line) + lines = new_obj.parse(lines) + p.objects += [new_obj] + elif fields[0] == "raw_source": + raw = raw_reader() + lines = raw.parse(lines) + p.source_raw += raw.raw_lines + elif fields[0] == "raw_header": + raw = raw_reader() + lines = raw.parse(lines) + p.header_raw += raw.raw_lines + else: + print "error, strange line:", line + + return p + +def emit_header_file(f, p): + for l in p.header_raw: + print >>f, l + + if 1: # emit the enum table for objects + print >>f, "enum {" + print >>f, "\tNETOBJTYPE_INVALID=0," + for obj in p.objects: + print >>f, "\t%s," % obj.enum_name + print >>f, "\tNUM_NETOBJTYPES" + print >>f, "};" + print >>f, "" + + if 1: # emit the enum table for messages + print >>f, "enum {" + print >>f, "\tNETMSGTYPE_INVALID=0," + for msg in p.messages: + print >>f, "\t%s," % msg.enum_name + print >>f, "\tNUM_NETMSGTYPES" + print >>f, "};" + print >>f, "" + + print >>f, "int netobj_secure(int type, void *data, int size);" + print >>f, "const char *netobj_get_name(int type);" + print >>f, "int netobj_num_corrections();" + print >>f, "const char *netobj_corrected_on();" + print >>f, "" + print >>f, "void *netmsg_secure_unpack(int type);" + print >>f, "const char *netmsg_get_name(int type);" + print >>f, "const char *netmsg_failed_on();" + print >>f, "" + + for obj in p.objects: + for l in obj.emit_declaration(): + print >>f, l + print >>f, "" + + for msg in p.messages: + for l in msg.emit_declaration(): + print >>f, l + print >>f, "" + +def emit_source_file(f, p, protofilename): + print >>f, "#line 1 \"%s\"" % os.path.abspath(protofilename).replace("\\", "\\\\") + + for l in p.source_raw: + print >>f, l + + print >>f, "const char *msg_failed_on = \"\";" + print >>f, "const char *obj_corrected_on = \"\";" + print >>f, "static int num_corrections = 0;" + print >>f, "int netobj_num_corrections() { return num_corrections; }" + print >>f, "const char *netobj_corrected_on() { return obj_corrected_on; }" + print >>f, "const char *netmsg_failed_on() { return msg_failed_on; }" + print >>f, "" + print >>f, "static int netobj_clamp_int(const char *error_msg, int v, int min, int max)" + print >>f, "{" + print >>f, "\tif(v<min) { obj_corrected_on = error_msg; num_corrections++; return min; }" + print >>f, "\tif(v>max) { obj_corrected_on = error_msg; num_corrections++; return max; }" + print >>f, "\treturn v;" + print >>f, "}" + print >>f, "" + + if 1: # names + print >>f, "static const char *object_names[] = {" + print >>f, "\t" + '"invalid",' + for obj in p.objects: + print >>f, '\t"%s",' % obj.name + print >>f, '\t""' + print >>f, "};" + print >>f, "" + + if 1: # secure functions + print >>f, "static int secure_object_invalid(void *data, int size) { return 0; }" + for obj in p.objects: + print >>f, "static int secure_%s(void *data, int size)" % obj.name + print >>f, "{" + print >>f, "\t%s *obj = (%s *)data;" % (obj.struct_name, obj.struct_name) + print >>f, "\t(void)obj;" # to get rid of "unused variable" warning + print >>f, "\tif(size != sizeof(%s)) return -1;" % obj.struct_name + if obj.extends: + print >>f, "\tif(secure_%s(data, sizeof(NETOBJ_%s)) != 0) return -1;" % (obj.extends, obj.extends.upper()) + + for l in obj.emit_secure(): + print >>f, "\t" + l + print >>f, "\treturn 0;"; + print >>f, "}" + print >>f, "" + + if 1: # secure function table + print >>f, "typedef int(*SECUREFUNC)(void *data, int size);" + print >>f, "static SECUREFUNC secure_funcs[] = {" + print >>f, "\t" + 'secure_object_invalid,' + for obj in p.objects: + print >>f, "\tsecure_%s," % obj.name + print >>f, "\t" + '0x0' + print >>f, "};" + print >>f, "" + + if 1: + print >>f, "int netobj_secure(int type, void *data, int size)" + print >>f, "{" + print >>f, "\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;" + print >>f, "\treturn secure_funcs[type](data, size);" + print >>f, "};" + print >>f, "" + + if 1: + print >>f, "const char *netobj_get_name(int type)" + print >>f, "{" + print >>f, "\tif(type < 0 || type >= NUM_NETOBJTYPES) return \"(invalid)\";" + print >>f, "\treturn object_names[type];" + print >>f, "};" + print >>f, "" + + if 1: # names + print >>f, "static const char *message_names[] = {" + print >>f, "\t" + '"invalid",' + for msg in p.messages: + print >>f, '\t"%s",' % msg.name + print >>f, '\t""' + print >>f, "};" + print >>f, "" + + if 1: # secure functions + print >>f, "static void *secure_unpack_invalid() { return 0; }" + for msg in p.messages: + print >>f, "static void *secure_unpack_%s()" % msg.name + print >>f, "{" + print >>f, "\tstatic %s msg;" % msg.struct_name + for l in msg.emit_unpack(): + print >>f, "\t" + l + print >>f, "\treturn &msg;"; + print >>f, "}" + print >>f, "" + + if 1: # secure function table + print >>f, "typedef void *(*SECUREUNPACKFUNC)();" + print >>f, "static SECUREUNPACKFUNC secure_unpack_funcs[] = {" + print >>f, "\t" + 'secure_unpack_invalid,' + for msg in p.messages: + print >>f, "\tsecure_unpack_%s," % msg.name + print >>f, "\t" + '0x0' + print >>f, "};" + print >>f, "" + + if 1: + print >>f, "void *netmsg_secure_unpack(int type)" + print >>f, "{" + print >>f, "\tvoid *msg;" + print >>f, "\tmsg_failed_on = \"\";" + print >>f, "\tif(type < 0 || type >= NUM_NETMSGTYPES) return 0;" + print >>f, "\tmsg = secure_unpack_funcs[type]();" + print >>f, "\tif(msg_unpack_error()) return 0;" + print >>f, "\treturn msg;" + print >>f, "};" + print >>f, "" + + if 1: + print >>f, "const char *netmsg_get_name(int type)" + print >>f, "{" + print >>f, "\tif(type < 0 || type >= NUM_NETMSGTYPES) return \"(invalid)\";" + print >>f, "\treturn message_names[type];" + print >>f, "};" + print >>f, "" + +if sys.argv[1] == "header": + p = load(sys.argv[2]) + emit_header_file(file(sys.argv[3], "w"), p) +elif sys.argv[1] == "source": + p = load(sys.argv[2]) + emit_source_file(file(sys.argv[3], "w"), p, sys.argv[2]) +else: + print "invalid command" + sys.exit(-1) diff --git a/scripts/nicks.txt b/scripts/nicks.txt new file mode 100644 index 0000000..ffab5fd --- /dev/null +++ b/scripts/nicks.txt @@ -0,0 +1,32 @@ +:port80c.se.quakenet.org 353 matricks_ = #pcw :SPQR|Snapshot em0k1d n1sse iTouch|HedaN Hyeen Mattzki i9`Nilzon matricks_ WCG|Johan format` |ceMan PREGE lololollalalal kishe|Pookie polisen Rambo-ohsite firre15 ais-nax Obbmaster diskoturk SR|KinG gone-andytheman [FG]AkO cfg-gunnar proshit|Benis raaEW bengan-- Loser^ zNEKS Fokka Ping28|kwnztahh Palo^ partyZAH NillePillopio discover J-N ios Cajanen Bsite`oZe haxxcoto Hell[v]SOVA rabies Lampard2k7 DeFuN Linkan bjorniss Soet-DgR-_-[A] BridgeMill|Mod1 +:port80c.se.quakenet.org 353 matricks_ = #pcw :Mutt Hofvits [G][L][H][f] dahlgren Zervantes ben_dover fanfanfanfan ibersklan-ruyrl Grismusen Ploxzish Ejwin^mp Poontuus sintr0z hbfs___dSq Bombastic sasdd ErNoI TaizK UnLess Astan SwS-Garcia WyH|spliffstar lololololol Simixiz SD|barkeN MOOE keekz Centern Xzide^^ N43-HYPER LeaW`3D hotnils Lectra`MAEKTIG fnytt frtyschoooooooo insanity|DavidO dr-tom MIM wayu n9ef dinmammaamamam eppel Fess1g wardh hzapRingMeisteR kidneb xplayn Lajgarn flaxe HEJJADANNE +:port80c.se.quakenet.org 353 matricks_ = #pcw :Big^F Bsite`layd hejehjhk hsd1rrruffe AroooooN lexx_ lucchi AriGold DeDDu maflip eMO-aboOoOo Ramos6 ruub bjuse Chawn r3t _ogg kAerhu AIE|malle KimIO-SWE LooOOLiiiZ333eN kullersten Poke_- DryNox KoSmurfen ExakTT Gs|T1AO vtine|MAAAUNS heroX Twind [wc3]-Chiwi[CL] chilirec|raimat SeeWaR erdussel TROPP- exay franky540 ActionBarbie mHz\ZTK`sleep RRP^Jaffa cookiemonstAH WarL|thiDe Oskar^ qK-iMaz Nacka VILLIG-Booyah Beltdjur SoX-cOUPE kund|playz BCS|Winter +:port80c.se.quakenet.org 353 matricks_ = #pcw :Pajsarn svamp tfs\a TruqN babben hr-gil mapD|endoZz gnomie bostrom kA-WANGA kNNas Abxtract|pilshe vogga koolaid-krille DeVixx jwn rdl-- Kee FjuNe koolaid-iskn Pr0`Z10d3y snowsky vibes Nikjou vtine|zlivero OmGaAA mAJ|Britt hekla [0]apa kEy [F]Kaela bananskalFTW|da jeb` vampyren H0JT4R0LJ4 SheVa^ mAxXI Lectro FtN bajajajajajajja mZ`WIGGE dAMI^ moll3 GitfaN boisan [cs]-sNT Ex`Novag[jb] PPB|everest[wa] xiver- KulaN N43-xhady pluffenFOSHO wilho +:port80c.se.quakenet.org 353 matricks_ = #pcw :Nilsson^Arvika nRe`SmitH Ice`Lie[jb] sukki elgenkek drt0FF TaZ- Caesarion Limonaatipoika robf[S] DNAtive broder lolipop jollsy Genander Ballo_Ong Musikant|musicu ToY|Machine nerf|dupl0x gopy` fn\EXESSION FreZZ joharn _Folz [D]KvasteN daeeawewasdfadf CamelRyttArn Xabian HinzeL qRoN _dARUUF CUC|MiniMe^Away hewnk ASTRA|ove xideR Krigarn^ nIw|PlixxaN nMe|| Plumpen S0DA|BorrE teddis daboomb Bongo` Unknownperson TTA`BAdh SefuTzu`AWAY QRLGRIM neraz +:port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|Fudge Guggztah etojk Lindgrene [V]ZAIKON BmF^Off Wf`jeager\aw Havsmanet-ehn krisa hojhoj alfonz RoBBY faB|mHk Cheeser Admin1337 DoFFrR Caution- mZ`NoKaas HR|bramhultz`` mxyzptlk luder^myfish i`pikoL ZhenjkEe^^-777 Mansvalp sajje1996 v4de Redical`quexOFF n^sdadasJo eXITD`aw teknikvm-jaoel FLIPP-Shapen ALEJKO cliz^ acequeen Ferato Shudde sinsKal`ply frittlol Deadlier Farbrorspurk FizaH` \Azash sWingY fb\ekN xtreck addeadam KneKk azkiN rinxzor +:port80c.se.quakenet.org 353 matricks_ = #pcw :ArneH asdn brunte GeN|HollywoodHu bL\ZuND UNNEBERZ Synthetic|Xorci portoni saxparty|imso Inti |RnE oFFily Sp|DiamaNt Rhombus Nebrek kelamies Thingg BFB|incedeNt TAZzen whinan J0nte p12|wiggie okaJ mZ`Raztad FABF R3|sNELL blaupunkt2 Norrland-WaHoO maccan Ben---- aimD aLTOR EVIG|Falken nilsso bamstAr aGona`scalper reign[m4]n inzejN|ZoneX imag1ne a^meda|EYIE conejito puhaaa clime dsp123 mario_o bRRRA litextra|wezy TG|SaTaN Mando Weiche- wezzan +:port80c.se.quakenet.org 353 matricks_ = #pcw :Labe mp`serve soulK [V]Gudiikzt4r XampeD fs\dcube TrolleRovarN Emptyy SG-daskep0t Byssan Bernts1 SG|YAhoo KOKKA rL`SnowZen^ hIGHTECH__ aPPeLk4k4n otto^_ backs`wouL DeaGJIa mONGOLOJD|kree xekafutuwu uris vagrant ^a^cklet neaK-spiN nozter Arve S0oker GotticH pr0n^ traff`mElissA BC|Kebab2000 CipRi andor-- barbara- traff`lizze harserver3on3 RalleTruss EAES EKEMAN Cowafuckingdogk superlime LokY Hockey-Syvve Gigi qk-WyverN Larsito spendex eiviN und`feelme +:port80c.se.quakenet.org 353 matricks_ = #pcw :aderblasu yHYSS Cmore WaskE lodiz NachiMux Bodde kiiM Claddy TTAgital soker2on2plz mixzxz TmY- KrabbateN HAKKAKDGK VarsKo^aW Fuzak GZ`Kirra^^ mhaji Full|Hytra saxy0z0z0z Akapulka|urban CaZzpeR DarkLink FALLE- AmoZ mADSEN inetpro asd1 [100fps]elgit0 loltih GOLIATH`JONKAN sn1tch_4qs ischi87 Wazee LLLgHOST Derotti flw mandis daskdkad BlixteN_OFF Mjada-Hickdead Eazy-game|pAjk DulleN Sp3karn aimstar^mWd voffsi asdas Keo-muAz Liviu^^ vLaNskyldig +:port80c.se.quakenet.org 353 matricks_ = #pcw :sdfgdfg [4]bappo polackn [42]xeelol basseeee LuppaN eSport|RoxoR Heat2 Helgon`KEXITAN vaxxus|kY kaarel_ i-Link`Slobbo DazOFF Lectra`VolveR [51N19E]Mdr NFTS_aptand pd\cilleh wirram Ag- kn1^ROSA Nixt0n @Josi berrtill mikl ut|brbr LoLiz3N Ishootudie HaGa1 Tetrispro|Veloc Stilig firin Local`Bhz goodR N-Bot GangstA^Niise CLOCKK MaGeN churru` tB-SidW playm8|DjwaNdz PenisPasta sbd-phuntanN Sh4cky vED kimpann mylvis ville_12345678 MeLL^-Q sio\chaez +:port80c.se.quakenet.org 353 matricks_ = #pcw :PLAYER|ZOMG KappeZ^ pennpenn FatzoooO Snark^ Laakko FreddaN zure fiSKen vaccA[cx] Beart FD|Phoenix latrviabaatvik saffu tveka`StiKo HubbaBubbaBoyz q5^n3imad RETARDED pLym|Muffe GYG|RagnarssoN rF|neddemIRC HydrOO ollee sliff Eaten_Alive bollih\away fisarn Fanboyz\qcube Oish Da5|Poppo brottare mHz\xAantic [blueprint|Sn] SneZ WarQ|TriZ^ webcore|R3D95 rubeiiin`1st elius j0mppe- Zwoltex hebbe lallala vAH_ cp^traxzzlol Kung-Fonz Sprattelvatten inzejn[M] +:port80c.se.quakenet.org 353 matricks_ = #pcw :IR|psN backs`Fester Linus CreEckDeztrox _hillztaah IrLo bissen jonjonjon giant^da princip-xtinct smaakskcake [P]use ZerOSh00TS WarQ|Mathilda [P]nikkz sEasiun N43-PuNKy PuttEE Sp|SaLo^| zErios Klerburgare Silikon|Laxen e`zejN hejkanin Zien volvers promizer yewlar HeJ_hEj`aw jeakk rilleh x1ofdewm Swift^ Infinit3 RattiSorsa Ludvika|keken `m1r0n robbagg PillaD-Goss3N Apa`MAx |1g|LegoBilen Ainish [EN]Xanti aviad- puFFFin hejbabuirabakal Hodja WildHead +:port80c.se.quakenet.org 353 matricks_ = #pcw :Lo2P VadeHs|FortFarN Bollhuvve ebayer BEckzOFF Gonzo9014 DarkmindTheGrea trwon nena_ skillbill TpN-Rille^OFF Apl- zune[N] matsinyyyy spyyr stkiih MOSSEN Mathiaz dot222222222 MUFFINN DIMMamxxx xtinct BANZAI|Unders siCKO^^ ALEXMAN GM95 PinkDeagle Chlebo WiNk0 NITR0 Mykos Immortal-King Brodda inzejN|TiGeR Jaaanpoo GZ`SneLF |Ahoehoe R4mzi sadasda FoSho zOOM^ HEHEO2 princip-HermiN^ SUPERFASTTEC yohanseN n23|folieN-_- muffins crakkiz tmd-vdF Ello^ +:port80c.se.quakenet.org 353 matricks_ = #pcw :WOTS|christian |F|6|F|Volle Sp4rv3N Nibbler|LAN BVG|Anonim HENNING Local`sNl ifektO whipee\ vaxxus|gtv cL\\ninjaaraben r4jz_- vaxxus|nIc vaxxus|aVd Beastie^ Meier bjarne-_-12 Kalhygge|aBc inspet nuLLifY zlF BLAN|sUPERJAK biggy flon-sebbe fjurtis-otrolig Kalhygge|naXo Playgr0und Bamsar^Bwhl Kalhygge|meXA Kindow sylta pZi paraL^Deja BlasTmaN-tB deeh` [5b]CW|maxii AceDude_- LG^Panik GoA-Het^y|OFF sTr1nG^AFK zxn^off denbette^BNC ZoniX^Off LG^bruzken +:port80c.se.quakenet.org 353 matricks_ = #pcw :Zip^BNC ANONZOFF c`FoOjegerOff Ordspil^afk zanoJ-off bakhoj^off VeLuX^BNC p-zkarp Error404 Nivius^^ DP^OFF|SILENTY VICKY SkytteNOFF nAz JC|RedeTeZ^BNC hooligan`away Splutt|BNC svennjeavlnOFF aNTWAn CB|knubbiz-`AWA bliztr NB|freq[N] kOllEH deML|StoLeN\OFF DOED|EnRIz erN^BNC^AW jompa Cha0tix^OFF Pinstrup-off wolves-munkaway skoogan airhead^OFF Jeffie D5|Lindahl^OFF onaqui skinK aNders|BNC KadaveR^ valtsu_ sledz[aw] Cryptztahh`off FleexOFF stycket +:port80c.se.quakenet.org 353 matricks_ = #pcw :xGx_kmn^off WC anto_o GAndroo^aw schmaCk|icko lyngordon wUULF tX|Dzenan dERG0 chansurf HW|eriksson SG|Hornet xTz`ReXor^off_ syn4psE catsie skize Hezxy tomater HildaOFF nEXIN-tirre [NeutroN] ^sne WoA|dfish xTz`xNitroX^off exero koiz drastic`aVoid Checky_OFF Graxor LinusOFF_ nesc|Meibi` crezz eLiaZ unrea CharlieE eco`nejked tompA^ exp3rt Moejoe FloraCs|Aora Kalhygge|z1 iksO fake[n]ick FloraCsAora inzejN|Jonse ZoRoXo FD|tVEKA XMG\Gngs brrave^Borta +:port80c.se.quakenet.org 353 matricks_ = #pcw :aLpi-AtroOFF mustafakrister PEWPEW MiRRE`OFFLiNE Mixxarna-WejK^ gP|Deex cAD-BNC1 tomh BnCinzejn henka snacjsar EnE|vilsN TixoNBnc shifty|ossi WSOP|fredada MortenSoccer kiimpan [E]Polle^ doke muuuie Androoz SIXO wtai|tryckveard [sc]-falle Tele\weRRe`OFF Martin_- annette-away iGwtRealT3cH gUsk smekarn Onttu xVera`kreeeeee Somppiaeae LasseMan [SS]BoZo inzejn[A] HR|WINESY ^^juh0^^ BYS`vojnik nejmzah Sh1ft-_- Thunder-str R22du sankan DDark MtM PlayN-ziNk^Aw +:port80c.se.quakenet.org 353 matricks_ = #pcw :pd|firren GROSSER LIMEDNULKE HellkaN Mattan tzeron`g0ne Mr-Zorky HoD-Espen BAdhBNC ahlt ramoneur roxon_ dOFF`bth WcG|memphis Jules_ Hye Toot Justicia hajpad-Ante Fia`T8im e5g-Re\FILM hjort iNet\fjollabero Jeespoks SH|Thonk ztar`oFF Widow[away] mj\away CheatoN^BNC LAPPHOREoff dO`esn paal`aw Prayon emFFF zeLo FluBBa dalleBNC aTer waah|off kdo^ C_OFFE Dynis|AWAY miniwolbc BpN^away ReF^Zzz kyAx-OFF therazorsedge vT-viggolito CaLm[mC] Fredde^ acuBNC +:port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|HollyWood _ArvedssoN^BNC Rayan Mastodonten kempa Blizo`bnc SnIpa Suspected`Bnc1 Neftus dO`RadeoN Madicken daniel123 D-Line|m00jsi osbnc2 AWskian quality`BNC2 inzite`chad CHiLLiPiLl^bnc swaftan QlintoN iTouch|LundiN vandalizm Qslig[FM] makke Tele\wHomp^bnc steamacc4sale Playbackvxo asiQ^BNC Cash-Flow deniiX ITFYTD olssonn nehyd [421]Bihaz- CrilleeOFF elicious`wE111A sndOFF`Ass_slac kusn Myscobnc shade`nu [1Ramlosa] j1m1bnc TPI-piggerN +:port80c.se.quakenet.org 353 matricks_ = #pcw :gedis`AFK mX|Ximer3`BNC Rofel Std samhOFF tG`JeBuu roxz peace`zwa _jacce dRELL tetta bubbenBNC`[GA] __viktor ture frell newbcake k00HOOHO-- makkan Bihaz_- joacim _simon sajje1995 emf|zupppiyoyoy elixyr forfam|bOFF elitasson _sockan Gulle der-Andy RexorN NER|M0wz`aw n0pL_OFF AdamBNC kRIIL falCoOFF ajz antein splexan DNX Team-Unic_bnc2 Team-Unic_bnc1 Team-dH^Jacki3 |F|6|F|Penelo SCUMMY-OFF goL|GustiS^away koppar MartinsBNC xANIZ\bnc chilLboY +:port80c.se.quakenet.org 353 matricks_ = #pcw :Erik2son powerbnc2 Nizer Qeamer tobiasmatss swsBNC `Tobb Pyret Gv\MortiOFF aTschi xamber123 _borre boeka`kankeOFF reaction-bnc1 wiggan Zenhto TUX|ximmy hariiss HS|JagaleX^Offl ohm-bnc4 Iam hawkztr wibbaan Stamina\Proteus rME st4rl\heawen cursed-^^ _LarssoN_ Empis KnaspeR freez Deja-OFF QseBNC ninjaFREDDE ReTrez^Bnc^Away Divid0 mosklubba XnoW MozzyOFF mZ`Freddy Kladden^bnc alkh`aw Prood nIIICKOOOOO CR^SquierBNC H9jE^ b`hoffenOFF grikko sevonOFF +:port80c.se.quakenet.org 353 matricks_ = #pcw :Vexey avdunkad Rizley razzz BJARTMAR PlayHardGoFat Bubstah Gaffel [imbaOFF]sajkez mooaern emric Znap Hyso[csP] Kvasten^-off @Fabi Ind`laaKen amsrOFF Stamina\Achtung aceit\MorianA- c^KNDOO DAJMEN`AW runpuff Drunke fisken10 Let_It_Whip Poxi boeka`zeppOFF bodil avlid^bnc markisen`bnc qurry oBiee PZ|FiC-Aw Jonirl_gone luttman _micro Cr33d^Away Anderss^OFF rasmus11 axl0n17 pAjk Vibban\OFF zAt-off `tyrantBNC HB`off|djnatnat mP`off|Redfir3 TS|kolben_afk +:port80c.se.quakenet.org 353 matricks_ = #pcw :Manual\AFK mP`off|Redbot RetardacE ewh`FL1NK\away TaeferN`aw Divan^KaLa^BNC Divan^myRan^BNC DUMBASS`BNC sudden21 Cyber`Mnisaway [BFF]-REeLexX AEEEEEEEEEEEEEE ZMLB-Odis deaf-cs|Lille Ninjan` bojer^off freaKKKy_BNC Replay` GuFFe D3nim smn-_- jerry[bnc] D`timex a5\eqiNawaY inviz maRkN_ Brodda^SKOLAN zG|CBB^Off TisPik_off AFK^[TC]pvp chiva0FF hughi-off amokz^BNC SteelpliX^BNC Bioonic nIELSENoFF OFF|fZoe OliverL2`AWAY babb Chuck_N SNOEN^OFF [CYBER]niijaz +:port80c.se.quakenet.org 353 matricks_ = #pcw :LilleGris^BnC zG|Flod__ \lEGO`OFF LinusOFF SaX`Gubbi`OFF kolmio m|Smith Mitt3 iluen haMp gDesigns Reb_6ff blank|tox^off Unf[BNC]JLS SYNTEK|bArk FJERLEND PerSpelmann toXq` ieS|make`away pwang12 wajk\aw InV^Raccoon-OFF ComsyS ElakSomFan^^ @m3z @pimpo @MYM|Muesli`off ADAMeh^zzzz DLM^b1ue^Off Hootarn croz kylan_off ing\\tsabNC Offson n1mez`off spanier^off dieNasty`brb [D]Bamb DKB|Night[oFF] Basket-off xS|HeliuM Hardcorehilda attixoff thorr_ minib +:port80c.se.quakenet.org 353 matricks_ = #pcw :rwn ironic|Haunted khalannz PCW-Poker spitz Hiippari- iMrClean C5|Jakobervaek Casa`berssaBNC gamer`away myNKOFF Tjalfeen^off_ ^cooling noisi-a-way JennaDD mySKi-[a]ngeh mav0FF sanoj\ dicti KLADDIS`AWAY OFF|ShAmOnE dollface WoC^RuFi selo|elloAFK LnC-Kezse kn1^Mole__ haVec- BorgareN^ steddan Verga PawP SAAAID onemind`xent dyfu`viciouz Ice`OFF_ kEbAbMaNnEn gamax|luN_ guragoa`off xorTon Kirka bruikki SkarvaNOFF empton nessaia|noHn-OF iNet\xerp +:port80c.se.quakenet.org 353 matricks_ = #pcw :]5[kbz tjaeder sulaN^OFFLAJN Relayish mr-o oxido drulen CR1M3Z^off_ ziNx` Local`MickeMann deaf-cs|Brajen cL\\ninjaBNC tomh^soet eriik^ Carn4tioN`away Rapt0r KAAAALLLEE`BNC raY^^ aNnaa` ^apan LpY|p0sh[kol] dempAWAY zuxen\OFF aztro ToggeN [A1]No_52 [A1]etuxia Jusa Playm|DjToppi- Bodoom BCS^OFF|mkiss skau ThumbSucker^BNC tOFF-FuSe fnpOFF|aes ^SlappFisa^ Bhz`OFF Unf[BNC]Lion b00z\away Raised|ProBlem [A]fittb extinct`zake blike|AplE`oFF eNtiC MeLLKeR +:port80c.se.quakenet.org 353 matricks_ = #pcw :SNELHEST Nexo rkO`aw zG|Numse_ Maff n9way|mIkLo bEnz SpiderA _cgx GZ`cAD RICK1DAH fun|Skippsen INFAME|eRIKa\aw SS|xtinqt _mys|da HolySmoke Rq hoorai\naolein qutip mYth|schnaLz_M rengo`off aRa|Voilala^Off skilleAWAY BCS^OFF|dexer @FSHost-com aeom`away tvekaOFF`haMME Smog^ PartyPoker Sp|SpeTLighT^OF [Fixx]Olle sIMMe`offline panik_herman avu\partz0r rekyL^_- BCS^OFF|AMPARI Fluen^BNC Wkd^off eXm-SunnY^ ^hej Kniks DiXeR`off rfwdm_ TPI_piggerN_ Mataza|off +:port80c.se.quakenet.org 353 matricks_ = #pcw :epzBNC Ampro @hardstep goL|craJpAW WwG-Muste E|Evil^off MADREFLEX`rhZ adde` Crazy^SpexXI Jerker alq-andreA H1Xer aGILITY`POLYMOX Joker^BNC Mohkis [LEGE]HeJLeN^ Caprice Intgen`BAERB{J} VILLIG-7thAWAY Neehajd`BNC Batti LewfeN^Off Ravnn sky\bangz0ff`` SkenaN^bnc GladPanda fausti pittins^BNC SaX|f|Gubbi^ rM|pIx^^ Rms- RANGERBOY`aw FixxeR^ Edvnz uga BoSS|Benal`BNC sjonasm8k PND\s humpyskump SKOVDE|Snasi @HighTech @spam-scan @S @Q @[-hoorai-] STEN11 +:port80c.se.quakenet.org 353 matricks_ = #pcw :Voteski xP|Puhbaer^off Yoshi_ CWE`Flippen CeveRR [ShaKa]CoOoL`AW h3h3 LnC-iNZANEoff_ Wu-djaoff Zerooo Pieper_ chica`SanziLOFF BB4FRAGS|XTM`A limespOFF`malle oPS|JBbnc staphe G`Quix NItron\bnc c55-feros hejx HighG`wdE_OFF eco`zN Myt willybob`bnc Rh-G^TippeR^ JUHP-BNC|Jumert mthz Moldskred MxG\\MailBoX MeejtAWAY [c]eKipz dkz`xfx zaped`off ptrNo_OFF Jeamu c`Crelle-R^off rew`away Ak-87^ TOOOMMY\off L2D_-_Rappi Ghost^BNC _AraCi SKytteN^ ^StoKer^ +:port80c.se.quakenet.org 353 matricks_ = #pcw :zNei mYth|LucK3r n-N|TarriC poohi hamasbnc Coutz1 Char|ieBoY AZ^LEVING-BNC plike^HuliaN___ uR`saniOFF Gtrip|Hebo`OFF Redical`Score IceBlu EvilEye_bnc maaxi`off [AWAY]Darkling Noobet|StajOFF bjarne-_- zG|Eriksen^Off venom^off mHuen utini_off eveni\OFF Xqe MefistoFX`oFF bas-off|f4me TRiCK`iDfye MAAUNS CamiK^ GrQnaerten blike|amns`oFF sandersan Lt`HipPus Mossepo siOFF \zimze`BNC R33t Gs\BaZe^OFF zaney drateR^OFF Free1337 off|Hunter ifrit apfelmus +:port80c.se.quakenet.org 353 matricks_ = #pcw :eu-off|Blade jfl-oFF`miD Uniline charlie` painkiller`kool OFF|ShOcK telk0^BNC gh|jack^off EX-adrin^bnc w\Hairboi osfa|puddy^off CruisE-OFF- [A1]EnGud kungeeN^^ CMAX|[m]addilo Sk-off|MichYs9N NTL-Sentinal Tjalfuglen^off KapteWN`BNC cichlide^AWAY ChomP`away paltieBNC^[cz] WGV|PwnZ^Off pidde-_- TELETUBBIE Ecka fazer|NoxtrnOFF Lolad-net^ diRectAWAY evil|parasite xultRoNaw genics^BNC steri`off RaliAWAY oxid`zsiltsoff xazury`bnc IRLHELTEN r0ntti +:port80c.se.quakenet.org 353 matricks_ = #pcw :searon_ Saturn` Nimra jOHNSONN KegleN^AFK JC|PlaNke d4NNY`0fflajn MuGGe^Bnc _4P|StyLish^bnc s8`swinnnk Jackkis F`off`NickyH F5_rakkeeee Thuriaz inzym Moriz edom z1ax^0FFL1NE eXm-nex0r|bNc unstuck|L- aimstyle`vzn\a Gaylorden WrD ShadowOfAMaN gh|8Ball^off Retard-- SAGG-Lipton backyard\KoWORK awaylen BCS^OFF|Pipe TPI`Ferro fredde` xeet_ BlaZe180 Macan_ biblas^BNC Cyeclone Vali[away] BK|awayman armoryh oKend _cB-Us3-Bnc_ Kefir [nerd]Kurr3 diff --git a/scripts/png.py b/scripts/png.py new file mode 100644 index 0000000..739b1a7 --- /dev/null +++ b/scripts/png.py @@ -0,0 +1,102 @@ +import struct, zlib, sys + +class image: + w = 0 + h = 0 + data = [] + +def read_tga(f): + image = f.read() + img_type = struct.unpack("<B", image[2:3])[0] + img_bpp = struct.unpack("<B", image[16:17])[0] + img_width = struct.unpack("<H", image[12:14])[0] + img_height = struct.unpack("<H", image[14:16])[0] + + if img_type != 2 or img_bpp != 32: + print "image must be a RGBA" + + start = 18+struct.unpack("B", image[0])[0] + end = start + img_width*img_height*4 + image_data = image[start:end] # fetch raw data + return image_data + +def write_tga(f, w, h, bpp, data): + f.write(struct.pack("<BBBHHBHHHHBB", 0, 0, 2, 0, 0, 0, 0, 0, w, h, bpp, 0) + data) + + + + + +def load_png(f): + def read(fmt): return struct.unpack("!"+fmt, f.read(struct.calcsize("!"+fmt))) + def skip(count): f.read(count) + + # read signature + if read("cccccccc") != ('\x89', 'P', 'N', 'G', '\r', '\n', '\x1a', '\n'): + return 0 + + # read chunks + width = -1 + height = -1 + imagedata = "" + while 1: + size, id = read("I4s") + if id == "IHDR": # read header + width, height, bpp, colortype, compression, filter, interlace = read("IIBBBBB") + if bpp != 8 or compression != 0 or filter != 0 or interlace != 0 or (colortype != 2 and colortype != 6): + print "can't handle png of this type" + print width, height, bpp, colortype, compression, filter, interlace + return 0 + skip(4) + elif id == "IDAT": + imagedata += f.read(size) + skip(4) # read data + elif id == "IEND": + break # we are done! \o/ + else: + skip(size+4) # skip unknown chunks + + # decompress image data + rawdata = map(ord, zlib.decompress(imagedata)) + + # apply per scanline filters + pitch = width*4+1 + bpp = 4 + imgdata = [] + prevline = [0 for x in xrange(0, (width+1)*bpp)] + for y in xrange(0,height): + filter = rawdata[pitch*y] + pixeldata = rawdata[pitch*y+1:pitch*y+pitch] + thisline = [0 for x in xrange(0,bpp)] + def paeth(a, b, c): + p = a + b - c + pa = abs(p - a) + pb = abs(p - b) + pc = abs(p - c) + if pa <= pb and pa <= pc: + return a + if pb <= pc: + return b + return c + + if filter == 0: f = lambda a,b,c: 0 + elif filter == 1: f = lambda a,b,c: a + elif filter == 2: f = lambda a,b,c: b + elif filter == 3: f = lambda a,b,c: (a+b)/2 + elif filter == 4: f = paeth + + for x in xrange(0, width*bpp): + thisline += [(pixeldata[x] + f(thisline[x], prevline[x+bpp], prevline[x])) % 256] + + prevline = thisline + imgdata += thisline[4:] + + raw = "" + for x in imgdata: + raw += struct.pack("B", x) + + #print len(raw), width*height*4 + write_tga(file("test2.tga", "w"), width, height, 32, raw) + return 0 + +load_png(file("butterfly2.png", "rb")) \ No newline at end of file diff --git a/scripts/process_blame.py b/scripts/process_blame.py new file mode 100644 index 0000000..ae2c55b --- /dev/null +++ b/scripts/process_blame.py @@ -0,0 +1,12 @@ +import sys +user_map = {"kma":"matricks", "teetow":"matricks", "jlha":"matricks", "jdv":"void", "jaf":"serp"} +users = {} +for line in sys.stdin: + fields = line.split() + name = user_map.get(fields[1], fields[1]) + users[name] = users.get(name, 0) + 1 + +total = reduce(lambda x,y: x+y, users.values()) +for u in users: + print "%6s %6d %s" % ("%03.2f"%(users[u]*100.0/total), users[u], u) +print "%03.2f %6d %s" % (100, total, "Total") diff --git a/scripts/refactor_count.py b/scripts/refactor_count.py new file mode 100644 index 0000000..8fdec46 --- /dev/null +++ b/scripts/refactor_count.py @@ -0,0 +1,351 @@ +import os, re, sys + +alphanum = "0123456789abcdefghijklmnopqrstuvwzyxABCDEFGHIJKLMNOPQRSTUVWXYZ_" +cpp_keywords = ["auto", "const", "double", "float", "int", "short", "struct", "unsigned", # C +"break", "continue", "else", "for", "long", "signed", "switch", "void", +"case", "default", "enum", "goto", "register", "sizeof", "typedef", "volatile", +"char", "do", "extern", "if", "return", "static", "union", "while", + +"asm", "dynamic_cast", "namespace", "reinterpret_cast", "try", # C++ +"bool", "explicit", "new", "static_cast", "typeid", +"catch", "false", "operator", "template", "typename", +"class", "friend", "private", "this", "using", +"const_cast", "inline", "public", "throw", "virtual", +"delete", "mutable", "protected", "true", "wchar_t"] + +allowed_words = [] + +#allowed_words += ["bitmap_left", "advance", "glyph"] # ft2 + + +allowed_words += ["qsort"] # stdio / stdlib +allowed_words += ["size_t", "cosf", "sinf", "asinf", "acosf", "atanf", "powf", "fabs", "rand", "powf", "fmod", "sqrtf"] # math.h +allowed_words += ["time_t", "time", "strftime", "localtime"] # time.h +allowed_words += [ # system.h + "int64", + "dbg_assert", "dbg_msg", "dbg_break", "dbg_logger_stdout", "dbg_logger_debugger", "dbg_logger_file", + "mem_alloc", "mem_zero", "mem_free", "mem_copy", "mem_move", "mem_comp", "mem_stats", "total_allocations", "allocated", + "thread_create", "thread_sleep", "lock_wait", "lock_create", "lock_release", "lock_destroy", "swap_endian", + "io_open", "io_read", "io_read", "io_write", "io_flush", "io_close", "io_seek", "io_skip", "io_tell", "io_length", + "str_comp", "str_length", "str_quickhash", "str_format", "str_copy", "str_comp_nocase", "str_sanitize", "str_append", + "str_comp_num", "str_find_nocase", "str_sanitize_strong", "str_uppercase", "str_toint", "str_tofloat", + "str_utf8_encode", "str_utf8_rewind", "str_utf8_forward", "str_utf8_decode", "str_sanitize_cc", "str_skip_whitespaces", + "fs_makedir", "fs_listdir", "fs_storage_path", "fs_is_dir", + "net_init", "net_addr_comp", "net_host_lookup", "net_addr_str", "type", "port", "net_addr_from_str", + "net_udp_create", "net_udp_send", "net_udp_recv", "net_udp_close", "net_socket_read_wait", + "net_stats", "sent_bytes", "recv_bytes", "recv_packets", "sent_packets", + "time_get", "time_freq", "time_timestamp"] + +allowed_words += ["vec2", "vec3", "vec4", "round", "clamp", "length", "dot", "normalize", "frandom", "mix", "distance", "min", + "closest_point_on_line", "max", "absolute"] # math.hpp +allowed_words += [ # tl + "array", "sorted_array", "string", + "all", "sort", "add", "remove_index", "remove", "delete_all", "set_size", + "base_ptr", "size", "swap", "empty", "front", "pop_front", "find_binary", "find_linear", "clear", "range", "end", "cstr", + "partition_linear", "partition_binary"] +allowed_words += ["fx2f", "f2fx"] # fixed point math + +def CheckIdentifier(ident): + return False + +class Checker: + def CheckStart(self, checker, filename): + pass + def CheckLine(self, checker, line): + pass + def CheckEnd(self, checker): + pass + +class FilenameExtentionChecker(Checker): + def __init__(self): + self.allowed = [".cpp", ".h"] + def CheckStart(self, checker, filename): + ext = os.path.splitext(filename)[1] + if not ext in self.allowed: + checker.Error("file extention '%s' is not allowed" % ext) + +class IncludeChecker(Checker): + def __init__(self): + self.disallowed_headers = ["stdio.h", "stdlib.h", "string.h", "memory.h"] + def CheckLine(self, checker, line): + if "#include" in line: + include_file = "" + if '<' in line: + include_file = line.split('<')[1].split(">")[0] + #if not "/" in include_file: + # checker.Error("%s is not allowed" % include_file) + elif '"' in line: + include_file = line.split('"')[1] + + #print include_file + if include_file in self.disallowed_headers: + checker.Error("%s is not allowed" % include_file) + +class HeaderGuardChecker(Checker): + def CheckStart(self, checker, filename): + self.check = ".h" in filename + self.guard = "#ifndef " + filename[4:].replace("/", "_").replace(".hpp", "").replace(".h", "").upper() + "_H" + def CheckLine(self, checker, line): + if self.check: + #if "#" in line: + self.check = False + #if not self.check: + if line.strip() == self.guard: + pass + else: + checker.Error("malformed or missing header guard. Should be '%s'" % self.guard) + +class CommentChecker(Checker): + def CheckLine(self, checker, line): + if line.strip()[-2:] == "*/" and "/*" in line: + checker.Error("single line multiline comment") + +class FileChecker: + def __init__(self): + self.checkers = [] + self.checkers += [FilenameExtentionChecker()] + self.checkers += [HeaderGuardChecker()] + self.checkers += [IncludeChecker()] + self.checkers += [CommentChecker()] + + def Error(self, errormessage): + self.current_errors += [(self.current_line, errormessage)] + + def CheckLine(self, line): + for c in self.checkers: + c.CheckLine(self, line) + return True + + def CheckFile(self, filename): + self.current_file = filename + self.current_line = 0 + self.current_errors = [] + for c in self.checkers: + c.CheckStart(self, filename) + + for line in file(filename).readlines(): + self.current_line += 1 + if "ignore_check" in line: + continue + self.CheckLine(line) + + for c in self.checkers: + c.CheckEnd(self) + + def GetErrors(self): + return self.current_errors + +def cstrip(lines): + d = "" + for l in lines: + if "ignore_convention" in l: + continue + l = re.sub("^[\t ]*#.*", "", l) + l = re.sub("//.*", "", l) + l = re.sub('\".*?\"', '"String"', l) # remove strings + d += l.strip() + " " + d = re.sub('\/\*.*?\*\/', "", d) # remove /* */ comments + d = d.replace("\t", " ") # tab to space + d = re.sub(" *", " ", d) # remove double spaces + #d = re.sub("", "", d) # remove /* */ comments + + d = d.strip() + + # this eats up cases like 'n {' + i = 1 + while i < len(d)-2: + if d[i] == ' ': + if not (d[i-1] in alphanum and d[i+1] in alphanum): + d = d[:i] + d[i+1:] + i += 1 + return d + +#def stripstrings(data): +# return re.sub('\".*?\"', 'STRING', data) + +def get_identifiers(data): + idents = {} + data = " "+data+" " + regexp = re.compile("[^a-zA-Z0-9_][a-zA-Z_][a-zA-Z0-9_]+[^a-zA-Z0-9_]") + start = 0 + while 1: + m = regexp.search(data, start) + + if m == None: + break + start = m.end()-1 + name = data[m.start()+1:m.end()-1] + if name in idents: + idents[name] += 1 + else: + idents[name] = 1 + return idents + +grand_total = 0 +grand_offenders = 0 + +gen_html = 1 + +if gen_html: + print "<head>" + print '<link href="/style.css" rel="stylesheet" type="text/css" />' + print "</head>" + print "<body>" + + + + print '<div id="outer">' + + print '<div id="top_left"><div id="top_right"><div id="top_mid">' + print '<a href="/"><img src="/images/twlogo.png" alt="teeworlds logo" /></a>' + print '</div></div></div>' + + print '<div id="menu_left"><div id="menu_right"><div id="menu_mid">' + print '</div></div></div>' + + print '<div id="tlc"><div id="trc"><div id="tb"> </div></div></div>' + print '<div id="lb"><div id="rb"><div id="mid">' + print '<div id="container">' + + print '<p class="topic_text">' + print '<h1>Code Refactoring Progress</h1>' + print '''This is generated by a script that find identifiers in the code + that doesn't conform to the code standard. Right now it only shows headers + because they need to be fixed before we can do the rest of the source. + This is a ROUGH estimate of the progress''' + print '</p>' + + print '<p class="topic_text">' + print '<table>' + #print "<tr><td><b>%</b></td><td><b>#</b></td><td><b>File</b></td><td><b>Offenders</b></td></tr>" + +line_order = 1 +total_files = 0 +complete_files = 0 +total_errors = 0 + +for (root,dirs,files) in os.walk("src"): + for filename in files: + filename = os.path.join(root, filename) + if "/." in filename or "/external/" in filename or "/base/" in filename or "/generated/" in filename: + continue + if "src/osxlaunch/client.h" in filename: # ignore this file, ObjC file + continue + if "e_config_variables.h" in filename: # ignore config files + continue + if "src/game/variables.hpp" in filename: # ignore config files + continue + + if not (".hpp" in filename or ".h" in filename or ".cpp" in filename): + continue + + #total_files += 1 + + #if not "src/engine/client/ec_client.cpp" in filename: + # continue + + f = FileChecker() + f.CheckFile(filename) + num_errors = len(f.GetErrors()) + total_errors += num_errors + + if num_errors: + print '<tr style="background: #e0e0e0"><td colspan="2">%s, %d errors</td></tr>' % (filename, num_errors), + for line, msg in f.GetErrors(): + print '<tr"><td>%d</td><td>%s</td></tr>' % (line, msg) + #print '<table>' + #GetErrors() + + + + + if 0: + text = cstrip(file(filename).readlines()) # remove all preprocessor stuff and comments + #text = stripstrings(text) # remove strings (does not solve all cases however) + #print text + + idents = get_identifiers(text) + offenders = 0 + total = 0 + offender_list = {} + for name in idents: + #print name + if len(name) <= 2: # skip things that are too small + continue + if name in cpp_keywords: # skip keywords + continue + if name in allowed_words: # skip allowed keywords + continue + + total += idents[name] + if name != name.lower(): # strip names that are not only lower case + continue + offender_list[name] = idents[name] + if not gen_html: + print "[%d] %s"%(idents[name], name) + offenders += idents[name] + + grand_total += total + grand_offenders += offenders + + if total == 0: + total = 1 + + line_order = -line_order + + + done = int((1-(offenders / float(total))) * 100) + if done == 100: + complete_files += 1 + + if done != 100 and gen_html: + color = "#ffa0a0" + if done > 20: + color = "#ffd080" + if done > 50: + color = "#ffff80" + if done > 75: + color = "#e0ff80" + if done == 100: + color = "#80ff80" + + line_color = "#f0efd5" + if line_order > 0: + line_color = "#ffffff" + + offender_string = "" + count = 0 + for name in offender_list: + count += 1 + offender_string += "[%d]%s " % (offender_list[name], name) + + if count%5 == 0: + offender_string += "<br/>" + + print '<tr style="background: %s">' % line_color, + print '<td style="text-align: right; background: %s"><b>%d%%</b></td><td style="text-align: center">%d</td><td>%s</td>' % (color, done, offenders, filename), + print '<td style="text-align: right">%s</td>' % offender_string + print "</tr>" + count = 0 + +if gen_html: + print "</table>" + + print "<h1>%d errors</h1>" % total_errors + + + if 0: + print "<h1>%.1f%% Identifiers done</h1>" % ((1-(grand_offenders / float(grand_total))) * 100) + print "%d left of %d" % (grand_offenders, grand_total) + print "<h1>%.1f%% Files done</h1>" % ((complete_files / float(total_files)) * 100) + print "%d left of %d" % (total_files-complete_files, total_files) + + print "</p>" + print "<div style='clear:both;'></div>" + print '</div>' + print '</div></div></div>' + + print '<div id="blc"><div id="brc"><div id="bb"> </div></div></div>' + print '</div>' + + print "</body>" diff --git a/scripts/tw_api.py b/scripts/tw_api.py new file mode 100644 index 0000000..36cc5f5 --- /dev/null +++ b/scripts/tw_api.py @@ -0,0 +1,270 @@ +# coding: utf-8 +from socket import * +import struct +import sys +import threading +import time + + + +NUM_MASTERSERVERS = 4 +MASTERSERVER_PORT = 8300 + +TIMEOUT = 2 + +SERVERTYPE_NORMAL = 0 +SERVERTYPE_LEGACY = 1 + +PACKET_GETLIST = "\x20\x00\x00\x00\x00\x00\xff\xff\xff\xffreqt" +PACKET_GETLIST2 = "\x20\x00\x00\x00\x00\x00\xff\xff\xff\xffreq2" +PACKET_GETINFO = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgief" +PACKET_GETINFO2 = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgie2" + "\x00" +PACKET_GETINFO3 = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgie3" + "\x00" + + + +class Server_Info(threading.Thread): + + def __init__(self, address, type): + self.address = address + self.type = type + self.finished = False + threading.Thread.__init__(self, target = self.run) + + def run(self): + self.info = None + if self.type == SERVERTYPE_NORMAL: + self.info = get_server_info3(self.address) + elif self.type == SERVERTYPE_LEGACY: + self.info = get_server_info(self.address) + if self.info: + self.info = get_server_info2(self.address) + self.finished = True + + +def get_server_info(address): + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT); + sock.sendto(PACKET_GETINFO, address) + data, addr = sock.recvfrom(1024) + sock.close() + + data = data[14:] # skip header + slots = data.split("\x00") + + server_info = {} + server_info["version"] = slots[0] + server_info["name"] = slots[1] + server_info["map"] = slots[2] + server_info["gametype"] = slots[3] + server_info["flags"] = int(slots[4]) + server_info["progression"] = int(slots[5]) + server_info["num_players"] = int(slots[6]) + server_info["max_players"] = int(slots[7]) + server_info["players"] = [] + + for i in xrange(0, server_info["num_players"]): + player = {} + player["name"] = slots[8+i*2] + player["score"] = int(slots[8+i*2+1]) + server_info["players"].append(player) + + return server_info + + except: + sock.close() + return None + + +def get_server_info2(address): + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT); + sock.sendto(PACKET_GETINFO2, address) + data, addr = sock.recvfrom(1024) + sock.close() + + data = data[14:] # skip header + slots = data.split("\x00") + + server_info = {} + server_info["token"] = slots[0] + server_info["version"] = slots[1] + server_info["name"] = slots[2] + server_info["map"] = slots[3] + server_info["gametype"] = slots[4] + server_info["flags"] = int(slots[5]) + server_info["progression"] = int(slots[6]) + server_info["num_players"] = int(slots[7]) + server_info["max_players"] = int(slots[8]) + server_info["players"] = [] + + for i in xrange(0, server_info["num_players"]): + player = {} + player["name"] = slots[9+i*2] + player["score"] = int(slots[9+i*2+1]) + server_info["players"].append(player) + + return server_info + + except: + sock.close() + return None + + +def get_server_info3(address): + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT); + sock.sendto(PACKET_GETINFO3, address) + data, addr = sock.recvfrom(1400) + sock.close() + + data = data[14:] # skip header + slots = data.split("\x00") + + server_info = {} + server_info["token"] = slots[0] + server_info["version"] = slots[1] + server_info["name"] = slots[2] + server_info["map"] = slots[3] + server_info["gametype"] = slots[4] + server_info["flags"] = int(slots[5]) + server_info["num_players"] = int(slots[6]) + server_info["max_players"] = int(slots[7]) + server_info["num_clients"] = int(slots[8]) + server_info["max_clients"] = int(slots[9]) + server_info["players"] = [] + + for i in xrange(0, server_info["num_clients"]): + player = {} + player["name"] = slots[10+i*5] + player["clan"] = slots[10+i*5+1] + player["country"] = int(slots[10+i*5+2]) + player["score"] = int(slots[10+i*5+3]) + if int(slots[10+i*5+4]): + player["player"] = True + else: + player["player"] = False + server_info["players"].append(player) + + return server_info + + except: + sock.close() + return None + + + +class Master_Server_Info(threading.Thread): + + def __init__(self, address): + self.address = address + self.finished = False + threading.Thread.__init__(self, target = self.run) + + def run(self): + self.servers = get_list(self.address) + get_list2(self.address) + self.finished = True + + +def get_list(address): + servers = [] + + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT) + sock.sendto(PACKET_GETLIST, address) + + while 1: + data, addr = sock.recvfrom(1024) + + data = data[14:] + num_servers = len(data) / 6 + + for n in range(0, num_servers): + ip = ".".join(map(str, map(ord, data[n*6:n*6+4]))) + port = ord(data[n*6+5]) * 256 + ord(data[n*6+4]) + servers += [[(ip, port), SERVERTYPE_LEGACY]] + + except: + sock.close() + + return servers + + +def get_list2(address): + servers = [] + + try: + sock = socket(AF_INET, SOCK_DGRAM) + sock.settimeout(TIMEOUT) + sock.sendto(PACKET_GETLIST2, address) + + while 1: + data, addr = sock.recvfrom(1400) + + data = data[14:] + num_servers = len(data) / 18 + + for n in range(0, num_servers): + if data[n*18:n*18+12] == "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff": + ip = ".".join(map(str, map(ord, data[n*18+12:n*18+16]))) + else: + ip = ":".join(map(str, map(ord, data[n*18:n*18+16]))) + port = (ord(data[n*18+16])<<8) + ord(data[n*18+17]) + servers += [[(ip, port), SERVERTYPE_NORMAL]] + + except: + sock.close() + + return servers + + + +master_servers = [] + +for i in range(1, NUM_MASTERSERVERS+1): + m = Master_Server_Info(("master%d.teeworlds.com"%i, MASTERSERVER_PORT)) + master_servers.append(m) + m.start() + time.sleep(0.001) # avoid issues + +servers = [] + +while len(master_servers) != 0: + if master_servers[0].finished == True: + if master_servers[0].servers: + servers += master_servers[0].servers + del master_servers[0] + time.sleep(0.001) # be nice + +servers_info = [] + +print str(len(servers)) + " servers" + +for server in servers: + s = Server_Info(server[0], server[1]) + servers_info.append(s) + s.start() + time.sleep(0.001) # avoid issues + +num_players = 0 +num_clients = 0 + +while len(servers_info) != 0: + if servers_info[0].finished == True: + + if servers_info[0].info: + num_players += servers_info[0].info["num_players"] + if servers_info[0].type == SERVERTYPE_NORMAL: + num_clients += servers_info[0].info["num_clients"] + else: + num_clients += servers_info[0].info["num_players"] + + del servers_info[0] + + time.sleep(0.001) # be nice + +print str(num_players) + " players and " + str(num_clients-num_players) + " spectators" diff --git a/src/base/color.h b/src/base/color.h new file mode 100644 index 0000000..4b2d7b1 --- /dev/null +++ b/src/base/color.h @@ -0,0 +1,167 @@ + +#ifndef BASE_COLOR_H +#define BASE_COLOR_H + +#include "math.h" +#include "vmath.h" + +/* + Title: Color handling +*/ + +/* + Function: HueToRgb + Converts Hue to RGB +*/ +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; +} + +inline float RgbToHue(vec3 rgb) +{ + float h_min = min(min(rgb.r, rgb.g), rgb.b); + float h_max = max(max(rgb.r, rgb.g), rgb.b); + + float hue = 0.0f; + + if(h_max == rgb.r) + hue = (rgb.g-rgb.b) / (h_max-h_min); + else if(h_max == rgb.g) + hue = 2.0f + (rgb.b-rgb.r) / (h_max-h_min); + else + hue = 4.0f + (rgb.r-rgb.g) / (h_max-h_min); + + hue /= 6.0f; + + if(hue < 0.0f) + hue += 1.0f; + + return hue; +} + +/* + Function: HslToRgb + Converts HSL to RGB +*/ +inline vec3 HslToRgb(vec3 HSL) +{ + if(HSL.s == 0.0f) + return vec3(HSL.l, HSL.l, HSL.l); + else + { + float v2 = HSL.l < 0.5f ? HSL.l * (1.0f + HSL.s) : (HSL.l+HSL.s) - (HSL.s*HSL.l); + float v1 = 2.0f * HSL.l - v2; + + return vec3(HueToRgb(v1, v2, HSL.h + (1.0f/3.0f)), HueToRgb(v1, v2, HSL.h), HueToRgb(v1, v2, HSL.h - (1.0f/3.0f))); + } +} + +inline vec3 HsvToRgb(vec3 hsv) +{ + int h = int(hsv.x * 6.0f); + float f = hsv.x * 6.0f - h; + float p = hsv.z * (1.0f - hsv.y); + float q = hsv.z * (1.0f - hsv.y * f); + float t = hsv.z * (1.0f - hsv.y * (1.0f - f)); + + vec3 rgb = vec3(0.0f, 0.0f, 0.0f); + + switch(h % 6) + { + case 0: + rgb.r = hsv.z; + rgb.g = t; + rgb.b = p; + break; + + case 1: + rgb.r = q; + rgb.g = hsv.z; + rgb.b = p; + break; + + case 2: + rgb.r = p; + rgb.g = hsv.z; + rgb.b = t; + break; + + case 3: + rgb.r = p; + rgb.g = q; + rgb.b = hsv.z; + break; + + case 4: + rgb.r = t; + rgb.g = p; + rgb.b = hsv.z; + break; + + case 5: + rgb.r = hsv.z; + rgb.g = p; + rgb.b = q; + break; + } + + return rgb; +} + +inline vec3 RgbToHsv(vec3 rgb) +{ + float h_min = min(min(rgb.r, rgb.g), rgb.b); + float h_max = max(max(rgb.r, rgb.g), rgb.b); + + // hue + float hue = 0.0f; + + if(h_max == h_min) + hue = 0.0f; + else if(h_max == rgb.r) + hue = (rgb.g-rgb.b) / (h_max-h_min); + else if(h_max == rgb.g) + hue = 2.0f + (rgb.b-rgb.r) / (h_max-h_min); + else + hue = 4.0f + (rgb.r-rgb.g) / (h_max-h_min); + + hue /= 6.0f; + + if(hue < 0.0f) + hue += 1.0f; + + // saturation + float s = 0.0f; + if(h_max != 0.0f) + s = (h_max - h_min)/h_max; + + // lightness + float l = h_max; + + return vec3(hue, s, l); +} + +/* + Function: HexToRgba + Converts Hex to Rgba + + Remarks: Hex should be RGBA8 +*/ +inline vec4 HexToRgba(int hex) +{ + vec4 c; + c.r = ((hex >> 24) & 0xFF) / 255.0f; + c.g = ((hex >> 16) & 0xFF) / 255.0f; + c.b = ((hex >> 8) & 0xFF) / 255.0f; + c.a = (hex & 0xFF) / 255.0f; + + return c; +} + +#endif diff --git a/src/base/confusables.c b/src/base/confusables.c new file mode 100644 index 0000000..798c905 --- /dev/null +++ b/src/base/confusables.c @@ -0,0 +1,95 @@ +int str_utf8_is_confusable(int smaller, int bigger) +{ + switch(smaller) + { + case 0x0020: return bigger == 0x00A0 || bigger == 0x1680 || bigger == 0x2000 || bigger == 0x2001 || bigger == 0x2002 || bigger == 0x2003 || bigger == 0x2004 || bigger == 0x2005 || bigger == 0x2006 || bigger == 0x2007 || bigger == 0x2008 || bigger == 0x2009 || bigger == 0x200A || bigger == 0x2028 || bigger == 0x2029 || bigger == 0x202F || bigger == 0x205F; + case 0x0021: return bigger == 0x01C3 || bigger == 0x2D51 || bigger == 0xFF01; + case 0x0022: return bigger == 0x02BA || bigger == 0x02DD || bigger == 0x02EE || bigger == 0x02F6 || bigger == 0x05F2 || bigger == 0x05F4 || bigger == 0x1CD3 || bigger == 0x201C || bigger == 0x201D || bigger == 0x201F || bigger == 0x2033 || bigger == 0x2036 || bigger == 0x3003 || bigger == 0xFF02; + case 0x0025: return bigger == 0x066A || bigger == 0x2052; + case 0x0026: return bigger == 0xA778; + case 0x0027: return bigger == 0x0060 || bigger == 0x00B4 || bigger == 0x02B9 || bigger == 0x02BB || bigger == 0x02BC || bigger == 0x02BD || bigger == 0x02BE || bigger == 0x02C8 || bigger == 0x02CA || bigger == 0x02CB || bigger == 0x02F4 || bigger == 0x0374 || bigger == 0x0384 || bigger == 0x055A || bigger == 0x055D || bigger == 0x05D9 || bigger == 0x05F3 || bigger == 0x07F4 || bigger == 0x07F5 || bigger == 0x144A || bigger == 0x16CC || bigger == 0x1FBD || bigger == 0x1FBF || bigger == 0x1FEF || bigger == 0x1FFD || bigger == 0x1FFE || bigger == 0x2018 || bigger == 0x2019 || bigger == 0x201B || bigger == 0x2032 || bigger == 0x2035 || bigger == 0xA78C || bigger == 0xFF07 || bigger == 0xFF40; + case 0x0028: return bigger == 0x2768 || bigger == 0x2772 || bigger == 0x3014 || bigger == 0xFD3E || bigger == 0xFF3B; + case 0x0029: return bigger == 0x2769 || bigger == 0x2773 || bigger == 0x3015 || bigger == 0xFD3F || bigger == 0xFF3D; + case 0x002A: return bigger == 0x066D || bigger == 0x204E || bigger == 0x2217 || bigger == 0x1031F; + case 0x002B: return bigger == 0x16ED || bigger == 0x2795 || bigger == 0x1029B; + case 0x002C: return bigger == 0x00B8 || bigger == 0x060D || bigger == 0x066B || bigger == 0x201A || bigger == 0xA4F9; + case 0x002D: return bigger == 0x02D7 || bigger == 0x06D4 || bigger == 0x2010 || bigger == 0x2011 || bigger == 0x2012 || bigger == 0x2013 || bigger == 0x2043 || bigger == 0x2212 || bigger == 0x2796 || bigger == 0x2CBA || bigger == 0xFE58; + case 0x002E: return bigger == 0x0660 || bigger == 0x06F0 || bigger == 0x0701 || bigger == 0x0702 || bigger == 0x2024 || bigger == 0xA4F8 || bigger == 0xA60E || bigger == 0x10A50 || bigger == 0x1D16D; + case 0x002F: return bigger == 0x1735 || bigger == 0x2041 || bigger == 0x2044 || bigger == 0x2215 || bigger == 0x2571 || bigger == 0x27CB || bigger == 0x29F8 || bigger == 0x2CC6 || bigger == 0x2F03 || bigger == 0x3033 || bigger == 0x31D3 || bigger == 0x4E3F; + case 0x0030: return bigger == 0x004F; + case 0x0031: return bigger == 0x006C; + case 0x0032: return bigger == 0x01A7 || bigger == 0x03E8 || bigger == 0x14BF || bigger == 0xA644 || bigger == 0xA75A || bigger == 0x1D7D0 || bigger == 0x1D7DA || bigger == 0x1D7E4 || bigger == 0x1D7EE || bigger == 0x1D7F8; + case 0x0033: return bigger == 0x01B7 || bigger == 0x021C || bigger == 0x0417 || bigger == 0x04E0 || bigger == 0x2CCC || bigger == 0xA76A || bigger == 0xA7AB || bigger == 0x118CA || bigger == 0x1D7D1 || bigger == 0x1D7DB || bigger == 0x1D7E5 || bigger == 0x1D7EF || bigger == 0x1D7F9; + case 0x0034: return bigger == 0x13CE || bigger == 0x118AF || bigger == 0x1D7D2 || bigger == 0x1D7DC || bigger == 0x1D7E6 || bigger == 0x1D7F0 || bigger == 0x1D7FA; + case 0x0035: return bigger == 0x01BC || bigger == 0x118BB || bigger == 0x1D7D3 || bigger == 0x1D7DD || bigger == 0x1D7E7 || bigger == 0x1D7F1 || bigger == 0x1D7FB; + case 0x0036: return bigger == 0x0431 || bigger == 0x13EE || bigger == 0x2CD2 || bigger == 0x118D5 || bigger == 0x1D7D4 || bigger == 0x1D7DE || bigger == 0x1D7E8 || bigger == 0x1D7F2 || bigger == 0x1D7FC; + case 0x0037: return bigger == 0x118C6 || bigger == 0x1D7D5 || bigger == 0x1D7DF || bigger == 0x1D7E9 || bigger == 0x1D7F3 || bigger == 0x1D7FD; + case 0x0038: return bigger == 0x0222 || bigger == 0x0223 || bigger == 0x09EA || bigger == 0x0A6A || bigger == 0x0B03 || bigger == 0x1031A || bigger == 0x1D7D6 || bigger == 0x1D7E0 || bigger == 0x1D7EA || bigger == 0x1D7F4 || bigger == 0x1D7FE || bigger == 0x1E8CB; + case 0x0039: return bigger == 0x09ED || bigger == 0x0A67 || bigger == 0x0B68 || bigger == 0x2CCA || bigger == 0xA76E || bigger == 0x118AC || bigger == 0x118CC || bigger == 0x118D6 || bigger == 0x1D7D7 || bigger == 0x1D7E1 || bigger == 0x1D7EB || bigger == 0x1D7F5 || bigger == 0x1D7FF; + case 0x003A: return bigger == 0x02D0 || bigger == 0x02F8 || bigger == 0x0589 || bigger == 0x05C3 || bigger == 0x0703 || bigger == 0x0704 || bigger == 0x0903 || bigger == 0x0A83 || bigger == 0x16EC || bigger == 0x1803 || bigger == 0x1809 || bigger == 0x205A || bigger == 0x2236 || bigger == 0xA4FD || bigger == 0xA789 || bigger == 0xFE30 || bigger == 0xFF1A; + case 0x003B: return bigger == 0x037E; + case 0x003C: return bigger == 0x02C2 || bigger == 0x1438 || bigger == 0x16B2 || bigger == 0x2039 || bigger == 0x276E; + case 0x003D: return bigger == 0x1400 || bigger == 0x2E40 || bigger == 0x30A0 || bigger == 0xA4FF; + case 0x003E: return bigger == 0x02C3 || bigger == 0x1433 || bigger == 0x203A || bigger == 0x276F; + case 0x003F: return bigger == 0x0241 || bigger == 0x0294 || bigger == 0x097D || bigger == 0x13AE; + case 0x0041: return bigger == 0x0391 || bigger == 0x0410 || bigger == 0x13AA || bigger == 0x15C5 || bigger == 0x1D00 || bigger == 0xA4EE || bigger == 0xFF21 || bigger == 0x102A0 || bigger == 0x1D400 || bigger == 0x1D434 || bigger == 0x1D468 || bigger == 0x1D49C || bigger == 0x1D4D0 || bigger == 0x1D504 || bigger == 0x1D538 || bigger == 0x1D56C || bigger == 0x1D5A0 || bigger == 0x1D5D4 || bigger == 0x1D608 || bigger == 0x1D63C || bigger == 0x1D670 || bigger == 0x1D6A8 || bigger == 0x1D6E2 || bigger == 0x1D71C || bigger == 0x1D756 || bigger == 0x1D790; + case 0x0042: return bigger == 0x0392 || bigger == 0x0412 || bigger == 0x13F4 || bigger == 0x15F7 || bigger == 0x212C || bigger == 0xA4D0 || bigger == 0xA7B4 || bigger == 0xFF22 || bigger == 0x10282 || bigger == 0x102A1 || bigger == 0x10301 || bigger == 0x1D401 || bigger == 0x1D435 || bigger == 0x1D469 || bigger == 0x1D4D1 || bigger == 0x1D505 || bigger == 0x1D539 || bigger == 0x1D56D || bigger == 0x1D5A1 || bigger == 0x1D5D5 || bigger == 0x1D609 || bigger == 0x1D63D || bigger == 0x1D671 || bigger == 0x1D6A9 || bigger == 0x1D6E3 || bigger == 0x1D71D || bigger == 0x1D757 || bigger == 0x1D791; + case 0x0043: return bigger == 0x03F9 || bigger == 0x0421 || bigger == 0x13DF || bigger == 0x2102 || bigger == 0x212D || bigger == 0x216D || bigger == 0x2CA4 || bigger == 0xA4DA || bigger == 0xFF23 || bigger == 0x102A2 || bigger == 0x10302 || bigger == 0x10415 || bigger == 0x1051C || bigger == 0x118E9 || bigger == 0x118F2 || bigger == 0x1D402 || bigger == 0x1D436 || bigger == 0x1D46A || bigger == 0x1D49E || bigger == 0x1D4D2 || bigger == 0x1D56E || bigger == 0x1D5A2 || bigger == 0x1D5D6 || bigger == 0x1D60A || bigger == 0x1D63E || bigger == 0x1D672 || bigger == 0x1F74C; + case 0x0044: return bigger == 0x13A0 || bigger == 0x15DE || bigger == 0x15EA || bigger == 0x2145 || bigger == 0x216E || bigger == 0xA4D3 || bigger == 0x1D403 || bigger == 0x1D437 || bigger == 0x1D46B || bigger == 0x1D49F || bigger == 0x1D4D3 || bigger == 0x1D507 || bigger == 0x1D53B || bigger == 0x1D56F || bigger == 0x1D5A3 || bigger == 0x1D5D7 || bigger == 0x1D60B || bigger == 0x1D63F || bigger == 0x1D673; + case 0x0045: return bigger == 0x0395 || bigger == 0x0415 || bigger == 0x13AC || bigger == 0x2130 || bigger == 0x22FF || bigger == 0x2D39 || bigger == 0xA4F0 || bigger == 0xFF25 || bigger == 0x10286 || bigger == 0x118A6 || bigger == 0x118AE || bigger == 0x1D404 || bigger == 0x1D438 || bigger == 0x1D46C || bigger == 0x1D4D4 || bigger == 0x1D508 || bigger == 0x1D53C || bigger == 0x1D570 || bigger == 0x1D5A4 || bigger == 0x1D5D8 || bigger == 0x1D60C || bigger == 0x1D640 || bigger == 0x1D674 || bigger == 0x1D6AC || bigger == 0x1D6E6 || bigger == 0x1D720 || bigger == 0x1D75A || bigger == 0x1D794; + case 0x0046: return bigger == 0x03DC || bigger == 0x15B4 || bigger == 0x2131 || bigger == 0xA4DD || bigger == 0xA798 || bigger == 0x10287 || bigger == 0x102A5 || bigger == 0x10525 || bigger == 0x118A2 || bigger == 0x118C2 || bigger == 0x1D405 || bigger == 0x1D439 || bigger == 0x1D46D || bigger == 0x1D4D5 || bigger == 0x1D509 || bigger == 0x1D53D || bigger == 0x1D571 || bigger == 0x1D5A5 || bigger == 0x1D5D9 || bigger == 0x1D60D || bigger == 0x1D641 || bigger == 0x1D675 || bigger == 0x1D7CA; + case 0x0047: return bigger == 0x050C || bigger == 0x13C0 || bigger == 0x13F3 || bigger == 0xA4D6 || bigger == 0x1D406 || bigger == 0x1D43A || bigger == 0x1D46E || bigger == 0x1D4A2 || bigger == 0x1D4D6 || bigger == 0x1D50A || bigger == 0x1D53E || bigger == 0x1D572 || bigger == 0x1D5A6 || bigger == 0x1D5DA || bigger == 0x1D60E || bigger == 0x1D642 || bigger == 0x1D676; + case 0x0048: return bigger == 0x0397 || bigger == 0x041D || bigger == 0x13BB || bigger == 0x157C || bigger == 0x210B || bigger == 0x210C || bigger == 0x210D || bigger == 0x2C8E || bigger == 0xA4E7 || bigger == 0xFF28 || bigger == 0x102CF || bigger == 0x1D407 || bigger == 0x1D43B || bigger == 0x1D46F || bigger == 0x1D4D7 || bigger == 0x1D573 || bigger == 0x1D5A7 || bigger == 0x1D5DB || bigger == 0x1D60F || bigger == 0x1D643 || bigger == 0x1D677 || bigger == 0x1D6AE || bigger == 0x1D6E8 || bigger == 0x1D722 || bigger == 0x1D75C || bigger == 0x1D796; + case 0x0049: return bigger == 0x006C; + case 0x004A: return bigger == 0x037F || bigger == 0x0408 || bigger == 0x13AB || bigger == 0x148D || bigger == 0xA4D9 || bigger == 0xA7B2 || bigger == 0xFF2A || bigger == 0x1D409 || bigger == 0x1D43D || bigger == 0x1D471 || bigger == 0x1D4A5 || bigger == 0x1D4D9 || bigger == 0x1D50D || bigger == 0x1D541 || bigger == 0x1D575 || bigger == 0x1D5A9 || bigger == 0x1D5DD || bigger == 0x1D611 || bigger == 0x1D645 || bigger == 0x1D679; + case 0x004B: return bigger == 0x039A || bigger == 0x041A || bigger == 0x13E6 || bigger == 0x16D5 || bigger == 0x212A || bigger == 0x2C94 || bigger == 0xA4D7 || bigger == 0xFF2B || bigger == 0x10518 || bigger == 0x1D40A || bigger == 0x1D43E || bigger == 0x1D472 || bigger == 0x1D4A6 || bigger == 0x1D4DA || bigger == 0x1D50E || bigger == 0x1D542 || bigger == 0x1D576 || bigger == 0x1D5AA || bigger == 0x1D5DE || bigger == 0x1D612 || bigger == 0x1D646 || bigger == 0x1D67A || bigger == 0x1D6B1 || bigger == 0x1D6EB || bigger == 0x1D725 || bigger == 0x1D75F || bigger == 0x1D799; + case 0x004C: return bigger == 0x13DE || bigger == 0x14AA || bigger == 0x2112 || bigger == 0x216C || bigger == 0x2CD0 || bigger == 0xA4E1 || bigger == 0x1041B || bigger == 0x10526 || bigger == 0x118A3 || bigger == 0x118B2 || bigger == 0x1D40B || bigger == 0x1D43F || bigger == 0x1D473 || bigger == 0x1D4DB || bigger == 0x1D50F || bigger == 0x1D543 || bigger == 0x1D577 || bigger == 0x1D5AB || bigger == 0x1D5DF || bigger == 0x1D613 || bigger == 0x1D647 || bigger == 0x1D67B; + case 0x004D: return bigger == 0x039C || bigger == 0x03FA || bigger == 0x041C || bigger == 0x13B7 || bigger == 0x15F0 || bigger == 0x16D6 || bigger == 0x2133 || bigger == 0x216F || bigger == 0x2C98 || bigger == 0xA4DF || bigger == 0xFF2D || bigger == 0x102B0 || bigger == 0x10311 || bigger == 0x1D40C || bigger == 0x1D440 || bigger == 0x1D474 || bigger == 0x1D4DC || bigger == 0x1D510 || bigger == 0x1D544 || bigger == 0x1D578 || bigger == 0x1D5AC || bigger == 0x1D5E0 || bigger == 0x1D614 || bigger == 0x1D648 || bigger == 0x1D67C || bigger == 0x1D6B3 || bigger == 0x1D6ED || bigger == 0x1D727 || bigger == 0x1D761 || bigger == 0x1D79B; + case 0x004E: return bigger == 0x039D || bigger == 0x2115 || bigger == 0x2C9A || bigger == 0xA4E0 || bigger == 0xFF2E || bigger == 0x10513 || bigger == 0x1D40D || bigger == 0x1D441 || bigger == 0x1D475 || bigger == 0x1D4A9 || bigger == 0x1D4DD || bigger == 0x1D511 || bigger == 0x1D579 || bigger == 0x1D5AD || bigger == 0x1D5E1 || bigger == 0x1D615 || bigger == 0x1D649 || bigger == 0x1D67D || bigger == 0x1D6B4 || bigger == 0x1D6EE || bigger == 0x1D728 || bigger == 0x1D762 || bigger == 0x1D79C; + case 0x004F: return bigger == 0x039F || bigger == 0x041E || bigger == 0x0555 || bigger == 0x07C0 || bigger == 0x09E6 || bigger == 0x0B20 || bigger == 0x0B66 || bigger == 0x0D20 || bigger == 0x2C9E || bigger == 0x2D54 || bigger == 0x3007 || bigger == 0xA4F3 || bigger == 0xFF2F || bigger == 0x10292 || bigger == 0x102AB || bigger == 0x10404 || bigger == 0x10516 || bigger == 0x114D0 || bigger == 0x118B5 || bigger == 0x118E0 || bigger == 0x1D40E || bigger == 0x1D442 || bigger == 0x1D476 || bigger == 0x1D4AA || bigger == 0x1D4DE || bigger == 0x1D512 || bigger == 0x1D546 || bigger == 0x1D57A || bigger == 0x1D5AE || bigger == 0x1D5E2 || bigger == 0x1D616 || bigger == 0x1D64A || bigger == 0x1D67E || bigger == 0x1D6B6 || bigger == 0x1D6F0 || bigger == 0x1D72A || bigger == 0x1D764 || bigger == 0x1D79E || bigger == 0x1D7CE || bigger == 0x1D7D8 || bigger == 0x1D7E2 || bigger == 0x1D7EC || bigger == 0x1D7F6; + case 0x0050: return bigger == 0x03A1 || bigger == 0x0420 || bigger == 0x13E2 || bigger == 0x146D || bigger == 0x2119 || bigger == 0x2CA2 || bigger == 0xA4D1 || bigger == 0xFF30 || bigger == 0x10295 || bigger == 0x1D40F || bigger == 0x1D443 || bigger == 0x1D477 || bigger == 0x1D4AB || bigger == 0x1D4DF || bigger == 0x1D513 || bigger == 0x1D57B || bigger == 0x1D5AF || bigger == 0x1D5E3 || bigger == 0x1D617 || bigger == 0x1D64B || bigger == 0x1D67F || bigger == 0x1D6B8 || bigger == 0x1D6F2 || bigger == 0x1D72C || bigger == 0x1D766 || bigger == 0x1D7A0; + case 0x0051: return bigger == 0x211A || bigger == 0x2D55 || bigger == 0x1D410 || bigger == 0x1D444 || bigger == 0x1D478 || bigger == 0x1D4AC || bigger == 0x1D4E0 || bigger == 0x1D514 || bigger == 0x1D57C || bigger == 0x1D5B0 || bigger == 0x1D5E4 || bigger == 0x1D618 || bigger == 0x1D64C || bigger == 0x1D680; + case 0x0052: return bigger == 0x01A6 || bigger == 0x13A1 || bigger == 0x13D2 || bigger == 0x1587 || bigger == 0x211B || bigger == 0x211C || bigger == 0x211D || bigger == 0xA4E3 || bigger == 0x1D411 || bigger == 0x1D445 || bigger == 0x1D479 || bigger == 0x1D4E1 || bigger == 0x1D57D || bigger == 0x1D5B1 || bigger == 0x1D5E5 || bigger == 0x1D619 || bigger == 0x1D64D || bigger == 0x1D681; + case 0x0053: return bigger == 0x0405 || bigger == 0x054F || bigger == 0x13D5 || bigger == 0x13DA || bigger == 0xA4E2 || bigger == 0xFF33 || bigger == 0x10296 || bigger == 0x10420 || bigger == 0x1D412 || bigger == 0x1D446 || bigger == 0x1D47A || bigger == 0x1D4AE || bigger == 0x1D4E2 || bigger == 0x1D516 || bigger == 0x1D54A || bigger == 0x1D57E || bigger == 0x1D5B2 || bigger == 0x1D5E6 || bigger == 0x1D61A || bigger == 0x1D64E || bigger == 0x1D682; + case 0x0054: return bigger == 0x03A4 || bigger == 0x0422 || bigger == 0x13A2 || bigger == 0x22A4 || bigger == 0x27D9 || bigger == 0x2CA6 || bigger == 0xA4D4 || bigger == 0xFF34 || bigger == 0x10297 || bigger == 0x102B1 || bigger == 0x10315 || bigger == 0x118BC || bigger == 0x1D413 || bigger == 0x1D447 || bigger == 0x1D47B || bigger == 0x1D4AF || bigger == 0x1D4E3 || bigger == 0x1D517 || bigger == 0x1D54B || bigger == 0x1D57F || bigger == 0x1D5B3 || bigger == 0x1D5E7 || bigger == 0x1D61B || bigger == 0x1D64F || bigger == 0x1D683 || bigger == 0x1D6BB || bigger == 0x1D6F5 || bigger == 0x1D72F || bigger == 0x1D769 || bigger == 0x1D7A3 || bigger == 0x1F768; + case 0x0055: return bigger == 0x054D || bigger == 0x144C || bigger == 0x222A || bigger == 0x22C3 || bigger == 0xA4F4 || bigger == 0x118B8 || bigger == 0x1D414 || bigger == 0x1D448 || bigger == 0x1D47C || bigger == 0x1D4B0 || bigger == 0x1D4E4 || bigger == 0x1D518 || bigger == 0x1D54C || bigger == 0x1D580 || bigger == 0x1D5B4 || bigger == 0x1D5E8 || bigger == 0x1D61C || bigger == 0x1D650 || bigger == 0x1D684; + case 0x0056: return bigger == 0x0474 || bigger == 0x0667 || bigger == 0x06F7 || bigger == 0x13D9 || bigger == 0x142F || bigger == 0x2164 || bigger == 0x2D38 || bigger == 0xA4E6 || bigger == 0x1051D || bigger == 0x118A0 || bigger == 0x1D415 || bigger == 0x1D449 || bigger == 0x1D47D || bigger == 0x1D4B1 || bigger == 0x1D4E5 || bigger == 0x1D519 || bigger == 0x1D54D || bigger == 0x1D581 || bigger == 0x1D5B5 || bigger == 0x1D5E9 || bigger == 0x1D61D || bigger == 0x1D651 || bigger == 0x1D685; + case 0x0057: return bigger == 0x051C || bigger == 0x13B3 || bigger == 0x13D4 || bigger == 0xA4EA || bigger == 0x118E6 || bigger == 0x118EF || bigger == 0x1D416 || bigger == 0x1D44A || bigger == 0x1D47E || bigger == 0x1D4B2 || bigger == 0x1D4E6 || bigger == 0x1D51A || bigger == 0x1D54E || bigger == 0x1D582 || bigger == 0x1D5B6 || bigger == 0x1D5EA || bigger == 0x1D61E || bigger == 0x1D652 || bigger == 0x1D686; + case 0x0058: return bigger == 0x03A7 || bigger == 0x0425 || bigger == 0x166D || bigger == 0x16B7 || bigger == 0x2169 || bigger == 0x2573 || bigger == 0x2CAC || bigger == 0x2D5D || bigger == 0xA4EB || bigger == 0xA7B3 || bigger == 0xFF38 || bigger == 0x10290 || bigger == 0x102B4 || bigger == 0x10317 || bigger == 0x10322 || bigger == 0x10527 || bigger == 0x118EC || bigger == 0x1D417 || bigger == 0x1D44B || bigger == 0x1D47F || bigger == 0x1D4B3 || bigger == 0x1D4E7 || bigger == 0x1D51B || bigger == 0x1D54F || bigger == 0x1D583 || bigger == 0x1D5B7 || bigger == 0x1D5EB || bigger == 0x1D61F || bigger == 0x1D653 || bigger == 0x1D687 || bigger == 0x1D6BE || bigger == 0x1D6F8 || bigger == 0x1D732 || bigger == 0x1D76C || bigger == 0x1D7A6; + case 0x0059: return bigger == 0x03A5 || bigger == 0x03D2 || bigger == 0x04AE || bigger == 0x13A9 || bigger == 0x13BD || bigger == 0x2CA8 || bigger == 0xA4EC || bigger == 0xFF39 || bigger == 0x102B2 || bigger == 0x118A4 || bigger == 0x1D418 || bigger == 0x1D44C || bigger == 0x1D480 || bigger == 0x1D4B4 || bigger == 0x1D4E8 || bigger == 0x1D51C || bigger == 0x1D550 || bigger == 0x1D584 || bigger == 0x1D5B8 || bigger == 0x1D5EC || bigger == 0x1D620 || bigger == 0x1D654 || bigger == 0x1D688 || bigger == 0x1D6BC || bigger == 0x1D6F6 || bigger == 0x1D730 || bigger == 0x1D76A || bigger == 0x1D7A4; + case 0x005A: return bigger == 0x0396 || bigger == 0x13C3 || bigger == 0x2124 || bigger == 0x2128 || bigger == 0xA4DC || bigger == 0xFF3A || bigger == 0x102F5 || bigger == 0x118A9 || bigger == 0x118E5 || bigger == 0x1D419 || bigger == 0x1D44D || bigger == 0x1D481 || bigger == 0x1D4B5 || bigger == 0x1D4E9 || bigger == 0x1D585 || bigger == 0x1D5B9 || bigger == 0x1D5ED || bigger == 0x1D621 || bigger == 0x1D655 || bigger == 0x1D689 || bigger == 0x1D6AD || bigger == 0x1D6E7 || bigger == 0x1D721 || bigger == 0x1D75B || bigger == 0x1D795; + case 0x005C: return bigger == 0x2216 || bigger == 0x27CD || bigger == 0x29F5 || bigger == 0x29F9 || bigger == 0x2F02 || bigger == 0x31D4 || bigger == 0x4E36 || bigger == 0xFE68 || bigger == 0xFF3C; + case 0x005E: return bigger == 0x02C4 || bigger == 0x02C6; + case 0x005F: return bigger == 0x07FA || bigger == 0xFE4D || bigger == 0xFE4E || bigger == 0xFE4F; + case 0x0061: return bigger == 0x0251 || bigger == 0x03B1 || bigger == 0x0430 || bigger == 0x237A || bigger == 0xFF41 || bigger == 0x1D41A || bigger == 0x1D44E || bigger == 0x1D482 || bigger == 0x1D4B6 || bigger == 0x1D4EA || bigger == 0x1D51E || bigger == 0x1D552 || bigger == 0x1D586 || bigger == 0x1D5BA || bigger == 0x1D5EE || bigger == 0x1D622 || bigger == 0x1D656 || bigger == 0x1D68A || bigger == 0x1D6C2 || bigger == 0x1D6FC || bigger == 0x1D736 || bigger == 0x1D770 || bigger == 0x1D7AA; + case 0x0062: return bigger == 0x0184 || bigger == 0x042C || bigger == 0x13CF || bigger == 0x15AF || bigger == 0x1D41B || bigger == 0x1D44F || bigger == 0x1D483 || bigger == 0x1D4B7 || bigger == 0x1D4EB || bigger == 0x1D51F || bigger == 0x1D553 || bigger == 0x1D587 || bigger == 0x1D5BB || bigger == 0x1D5EF || bigger == 0x1D623 || bigger == 0x1D657 || bigger == 0x1D68B; + case 0x0063: return bigger == 0x03F2 || bigger == 0x0441 || bigger == 0x1D04 || bigger == 0x217D || bigger == 0x2CA5 || bigger == 0xFF43 || bigger == 0x1043D || bigger == 0x1D41C || bigger == 0x1D450 || bigger == 0x1D484 || bigger == 0x1D4B8 || bigger == 0x1D4EC || bigger == 0x1D520 || bigger == 0x1D554 || bigger == 0x1D588 || bigger == 0x1D5BC || bigger == 0x1D5F0 || bigger == 0x1D624 || bigger == 0x1D658 || bigger == 0x1D68C; + case 0x0064: return bigger == 0x0501 || bigger == 0x13E7 || bigger == 0x146F || bigger == 0x2146 || bigger == 0x217E || bigger == 0xA4D2 || bigger == 0x1D41D || bigger == 0x1D451 || bigger == 0x1D485 || bigger == 0x1D4B9 || bigger == 0x1D4ED || bigger == 0x1D521 || bigger == 0x1D555 || bigger == 0x1D589 || bigger == 0x1D5BD || bigger == 0x1D5F1 || bigger == 0x1D625 || bigger == 0x1D659 || bigger == 0x1D68D; + case 0x0065: return bigger == 0x0435 || bigger == 0x04BD || bigger == 0x212E || bigger == 0x212F || bigger == 0x2147 || bigger == 0xAB32 || bigger == 0xFF45 || bigger == 0x1D41E || bigger == 0x1D452 || bigger == 0x1D486 || bigger == 0x1D4EE || bigger == 0x1D522 || bigger == 0x1D556 || bigger == 0x1D58A || bigger == 0x1D5BE || bigger == 0x1D5F2 || bigger == 0x1D626 || bigger == 0x1D65A || bigger == 0x1D68E; + case 0x0066: return bigger == 0x017F || bigger == 0x0584 || bigger == 0x1E9D || bigger == 0xA799 || bigger == 0xAB35 || bigger == 0x1D41F || bigger == 0x1D453 || bigger == 0x1D487 || bigger == 0x1D4BB || bigger == 0x1D4EF || bigger == 0x1D523 || bigger == 0x1D557 || bigger == 0x1D58B || bigger == 0x1D5BF || bigger == 0x1D5F3 || bigger == 0x1D627 || bigger == 0x1D65B || bigger == 0x1D68F; + case 0x0067: return bigger == 0x018D || bigger == 0x0261 || bigger == 0x0581 || bigger == 0x1D83 || bigger == 0x210A || bigger == 0xFF47 || bigger == 0x1D420 || bigger == 0x1D454 || bigger == 0x1D488 || bigger == 0x1D4F0 || bigger == 0x1D524 || bigger == 0x1D558 || bigger == 0x1D58C || bigger == 0x1D5C0 || bigger == 0x1D5F4 || bigger == 0x1D628 || bigger == 0x1D65C || bigger == 0x1D690; + case 0x0068: return bigger == 0x04BB || bigger == 0x0570 || bigger == 0x13C2 || bigger == 0x210E || bigger == 0xFF48 || bigger == 0x1D421 || bigger == 0x1D489 || bigger == 0x1D4BD || bigger == 0x1D4F1 || bigger == 0x1D525 || bigger == 0x1D559 || bigger == 0x1D58D || bigger == 0x1D5C1 || bigger == 0x1D5F5 || bigger == 0x1D629 || bigger == 0x1D65D || bigger == 0x1D691; + case 0x0069: return bigger == 0x0131 || bigger == 0x0269 || bigger == 0x026A || bigger == 0x02DB || bigger == 0x037A || bigger == 0x03B9 || bigger == 0x0456 || bigger == 0x04CF || bigger == 0x13A5 || bigger == 0x1FBE || bigger == 0x2139 || bigger == 0x2148 || bigger == 0x2170 || bigger == 0x2373 || bigger == 0xA647 || bigger == 0xFF49 || bigger == 0x118C3 || bigger == 0x1D422 || bigger == 0x1D456 || bigger == 0x1D48A || bigger == 0x1D4BE || bigger == 0x1D4F2 || bigger == 0x1D526 || bigger == 0x1D55A || bigger == 0x1D58E || bigger == 0x1D5C2 || bigger == 0x1D5F6 || bigger == 0x1D62A || bigger == 0x1D65E || bigger == 0x1D692 || bigger == 0x1D6A4 || bigger == 0x1D6CA || bigger == 0x1D704 || bigger == 0x1D73E || bigger == 0x1D778 || bigger == 0x1D7B2; + case 0x006A: return bigger == 0x03F3 || bigger == 0x0458 || bigger == 0x2149 || bigger == 0xFF4A || bigger == 0x1D423 || bigger == 0x1D457 || bigger == 0x1D48B || bigger == 0x1D4BF || bigger == 0x1D4F3 || bigger == 0x1D527 || bigger == 0x1D55B || bigger == 0x1D58F || bigger == 0x1D5C3 || bigger == 0x1D5F7 || bigger == 0x1D62B || bigger == 0x1D65F || bigger == 0x1D693; + case 0x006B: return bigger == 0x0138 || bigger == 0x03BA || bigger == 0x03F0 || bigger == 0x043A || bigger == 0x1D0B || bigger == 0x2C95 || bigger == 0x1D424 || bigger == 0x1D458 || bigger == 0x1D48C || bigger == 0x1D4C0 || bigger == 0x1D4F4 || bigger == 0x1D528 || bigger == 0x1D55C || bigger == 0x1D590 || bigger == 0x1D5C4 || bigger == 0x1D5F8 || bigger == 0x1D62C || bigger == 0x1D660 || bigger == 0x1D694 || bigger == 0x1D6CB || bigger == 0x1D6DE || bigger == 0x1D705 || bigger == 0x1D718 || bigger == 0x1D73F || bigger == 0x1D752 || bigger == 0x1D779 || bigger == 0x1D78C || bigger == 0x1D7B3 || bigger == 0x1D7C6; + case 0x006C: return bigger == 0x007C || bigger == 0x0196 || bigger == 0x01C0 || bigger == 0x0399 || bigger == 0x0406 || bigger == 0x04C0 || bigger == 0x05C0 || bigger == 0x05D5 || bigger == 0x05DF || bigger == 0x0627 || bigger == 0x0661 || bigger == 0x06F1 || bigger == 0x07CA || bigger == 0x16C1 || bigger == 0x2110 || bigger == 0x2111 || bigger == 0x2113 || bigger == 0x2160 || bigger == 0x217C || bigger == 0x2223 || bigger == 0x2C92 || bigger == 0x2D4F || bigger == 0xA4F2 || bigger == 0xFE8D || bigger == 0xFE8E || bigger == 0xFF29 || bigger == 0xFF4C || bigger == 0xFFE8 || bigger == 0x1028A || bigger == 0x10309 || bigger == 0x10320 || bigger == 0x1D408 || bigger == 0x1D425 || bigger == 0x1D43C || bigger == 0x1D459 || bigger == 0x1D470 || bigger == 0x1D48D || bigger == 0x1D4C1 || bigger == 0x1D4D8 || bigger == 0x1D4F5 || bigger == 0x1D529 || bigger == 0x1D540 || bigger == 0x1D55D || bigger == 0x1D574 || bigger == 0x1D591 || bigger == 0x1D5A8 || bigger == 0x1D5C5 || bigger == 0x1D5DC || bigger == 0x1D5F9 || bigger == 0x1D610 || bigger == 0x1D62D || bigger == 0x1D644 || bigger == 0x1D661 || bigger == 0x1D678 || bigger == 0x1D695 || bigger == 0x1D6B0 || bigger == 0x1D6EA || bigger == 0x1D724 || bigger == 0x1D75E || bigger == 0x1D798 || bigger == 0x1D7CF || bigger == 0x1D7D9 || bigger == 0x1D7E3 || bigger == 0x1D7ED || bigger == 0x1D7F7 || bigger == 0x1E8C7 || bigger == 0x1EE00 || bigger == 0x1EE80; + case 0x006D: return bigger == 0x028D || bigger == 0x043C || bigger == 0x1D0D || bigger == 0x217F || bigger == 0xAB51 || bigger == 0x11700 || bigger == 0x118E3 || bigger == 0x1D426 || bigger == 0x1D45A || bigger == 0x1D48E || bigger == 0x1D4C2 || bigger == 0x1D4F6 || bigger == 0x1D52A || bigger == 0x1D55E || bigger == 0x1D592 || bigger == 0x1D5C6 || bigger == 0x1D5FA || bigger == 0x1D62E || bigger == 0x1D662 || bigger == 0x1D696; + case 0x006E: return bigger == 0x03C0 || bigger == 0x03D6 || bigger == 0x043F || bigger == 0x0578 || bigger == 0x057C || bigger == 0x1D28 || bigger == 0x213C || bigger == 0x1D427 || bigger == 0x1D45B || bigger == 0x1D48F || bigger == 0x1D4C3 || bigger == 0x1D4F7 || bigger == 0x1D52B || bigger == 0x1D55F || bigger == 0x1D593 || bigger == 0x1D5C7 || bigger == 0x1D5FB || bigger == 0x1D62F || bigger == 0x1D663 || bigger == 0x1D697 || bigger == 0x1D6D1 || bigger == 0x1D6E1 || bigger == 0x1D70B || bigger == 0x1D71B || bigger == 0x1D745 || bigger == 0x1D755 || bigger == 0x1D77F || bigger == 0x1D78F || bigger == 0x1D7B9 || bigger == 0x1D7C9; + case 0x006F: return bigger == 0x03BF || bigger == 0x03C3 || bigger == 0x043E || bigger == 0x0585 || bigger == 0x05E1 || bigger == 0x0647 || bigger == 0x0665 || bigger == 0x06BE || bigger == 0x06C1 || bigger == 0x06D5 || bigger == 0x06F5 || bigger == 0x0966 || bigger == 0x0A66 || bigger == 0x0AE6 || bigger == 0x0BE6 || bigger == 0x0C02 || bigger == 0x0C66 || bigger == 0x0C82 || bigger == 0x0CE6 || bigger == 0x0D02 || bigger == 0x0D66 || bigger == 0x0D82 || bigger == 0x0E50 || bigger == 0x0ED0 || bigger == 0x101D || bigger == 0x1040 || bigger == 0x10FF || bigger == 0x1D0F || bigger == 0x1D11 || bigger == 0x2134 || bigger == 0x2C9F || bigger == 0xAB3D || bigger == 0xFBA6 || bigger == 0xFBA7 || bigger == 0xFBA8 || bigger == 0xFBA9 || bigger == 0xFBAA || bigger == 0xFBAB || bigger == 0xFBAC || bigger == 0xFBAD || bigger == 0xFEE9 || bigger == 0xFEEA || bigger == 0xFEEB || bigger == 0xFEEC || bigger == 0xFF4F || bigger == 0x1042C || bigger == 0x118C8 || bigger == 0x118D7 || bigger == 0x1D428 || bigger == 0x1D45C || bigger == 0x1D490 || bigger == 0x1D4F8 || bigger == 0x1D52C || bigger == 0x1D560 || bigger == 0x1D594 || bigger == 0x1D5C8 || bigger == 0x1D5FC || bigger == 0x1D630 || bigger == 0x1D664 || bigger == 0x1D698 || bigger == 0x1D6D0 || bigger == 0x1D6D4 || bigger == 0x1D70A || bigger == 0x1D70E || bigger == 0x1D744 || bigger == 0x1D748 || bigger == 0x1D77E || bigger == 0x1D782 || bigger == 0x1D7B8 || bigger == 0x1D7BC || bigger == 0x1EE24 || bigger == 0x1EE64 || bigger == 0x1EE84; + case 0x0070: return bigger == 0x03C1 || bigger == 0x03F1 || bigger == 0x0440 || bigger == 0x2374 || bigger == 0x2CA3 || bigger == 0xFF50 || bigger == 0x1D429 || bigger == 0x1D45D || bigger == 0x1D491 || bigger == 0x1D4C5 || bigger == 0x1D4F9 || bigger == 0x1D52D || bigger == 0x1D561 || bigger == 0x1D595 || bigger == 0x1D5C9 || bigger == 0x1D5FD || bigger == 0x1D631 || bigger == 0x1D665 || bigger == 0x1D699 || bigger == 0x1D6D2 || bigger == 0x1D6E0 || bigger == 0x1D70C || bigger == 0x1D71A || bigger == 0x1D746 || bigger == 0x1D754 || bigger == 0x1D780 || bigger == 0x1D78E || bigger == 0x1D7BA || bigger == 0x1D7C8; + case 0x0071: return bigger == 0x051B || bigger == 0x0563 || bigger == 0x0566 || bigger == 0x1D42A || bigger == 0x1D45E || bigger == 0x1D492 || bigger == 0x1D4C6 || bigger == 0x1D4FA || bigger == 0x1D52E || bigger == 0x1D562 || bigger == 0x1D596 || bigger == 0x1D5CA || bigger == 0x1D5FE || bigger == 0x1D632 || bigger == 0x1D666 || bigger == 0x1D69A; + case 0x0072: return bigger == 0x0433 || bigger == 0x1D26 || bigger == 0x2C85 || bigger == 0xAB47 || bigger == 0xAB48 || bigger == 0x1D42B || bigger == 0x1D45F || bigger == 0x1D493 || bigger == 0x1D4C7 || bigger == 0x1D4FB || bigger == 0x1D52F || bigger == 0x1D563 || bigger == 0x1D597 || bigger == 0x1D5CB || bigger == 0x1D5FF || bigger == 0x1D633 || bigger == 0x1D667 || bigger == 0x1D69B; + case 0x0073: return bigger == 0x01BD || bigger == 0x0455 || bigger == 0xA731 || bigger == 0xFF53 || bigger == 0x10448 || bigger == 0x118C1 || bigger == 0x1D42C || bigger == 0x1D460 || bigger == 0x1D494 || bigger == 0x1D4C8 || bigger == 0x1D4FC || bigger == 0x1D530 || bigger == 0x1D564 || bigger == 0x1D598 || bigger == 0x1D5CC || bigger == 0x1D600 || bigger == 0x1D634 || bigger == 0x1D668 || bigger == 0x1D69C; + case 0x0074: return bigger == 0x03C4 || bigger == 0x0442 || bigger == 0x1D1B || bigger == 0x1D42D || bigger == 0x1D461 || bigger == 0x1D495 || bigger == 0x1D4C9 || bigger == 0x1D4FD || bigger == 0x1D531 || bigger == 0x1D565 || bigger == 0x1D599 || bigger == 0x1D5CD || bigger == 0x1D601 || bigger == 0x1D635 || bigger == 0x1D669 || bigger == 0x1D69D || bigger == 0x1D6D5 || bigger == 0x1D70F || bigger == 0x1D749 || bigger == 0x1D783 || bigger == 0x1D7BD; + case 0x0075: return bigger == 0x028B || bigger == 0x03C5 || bigger == 0x0446 || bigger == 0x057D || bigger == 0x1D1C || bigger == 0xA79F || bigger == 0xAB4E || bigger == 0xAB52 || bigger == 0x118D8 || bigger == 0x1D42E || bigger == 0x1D462 || bigger == 0x1D496 || bigger == 0x1D4CA || bigger == 0x1D4FE || bigger == 0x1D532 || bigger == 0x1D566 || bigger == 0x1D59A || bigger == 0x1D5CE || bigger == 0x1D602 || bigger == 0x1D636 || bigger == 0x1D66A || bigger == 0x1D69E || bigger == 0x1D6D6 || bigger == 0x1D710 || bigger == 0x1D74A || bigger == 0x1D784 || bigger == 0x1D7BE; + case 0x0076: return bigger == 0x03BD || bigger == 0x0475 || bigger == 0x05D8 || bigger == 0x1D20 || bigger == 0x2174 || bigger == 0x2228 || bigger == 0x22C1 || bigger == 0xFF56 || bigger == 0x118C0 || bigger == 0x1D42F || bigger == 0x1D463 || bigger == 0x1D497 || bigger == 0x1D4CB || bigger == 0x1D4FF || bigger == 0x1D533 || bigger == 0x1D567 || bigger == 0x1D59B || bigger == 0x1D5CF || bigger == 0x1D603 || bigger == 0x1D637 || bigger == 0x1D66B || bigger == 0x1D69F || bigger == 0x1D6CE || bigger == 0x1D708 || bigger == 0x1D742 || bigger == 0x1D77C || bigger == 0x1D7B6; + case 0x0077: return bigger == 0x026F || bigger == 0x0461 || bigger == 0x051D || bigger == 0x0561 || bigger == 0x1D21 || bigger == 0x1170E || bigger == 0x1170F || bigger == 0x1D430 || bigger == 0x1D464 || bigger == 0x1D498 || bigger == 0x1D4CC || bigger == 0x1D500 || bigger == 0x1D534 || bigger == 0x1D568 || bigger == 0x1D59C || bigger == 0x1D5D0 || bigger == 0x1D604 || bigger == 0x1D638 || bigger == 0x1D66C || bigger == 0x1D6A0; + case 0x0078: return bigger == 0x00D7 || bigger == 0x0445 || bigger == 0x1541 || bigger == 0x157D || bigger == 0x166E || bigger == 0x2179 || bigger == 0x292B || bigger == 0x292C || bigger == 0x2A2F || bigger == 0xFF58 || bigger == 0x1D431 || bigger == 0x1D465 || bigger == 0x1D499 || bigger == 0x1D4CD || bigger == 0x1D501 || bigger == 0x1D535 || bigger == 0x1D569 || bigger == 0x1D59D || bigger == 0x1D5D1 || bigger == 0x1D605 || bigger == 0x1D639 || bigger == 0x1D66D || bigger == 0x1D6A1; + case 0x0079: return bigger == 0x0263 || bigger == 0x028F || bigger == 0x03B3 || bigger == 0x0443 || bigger == 0x04AF || bigger == 0x10E7 || bigger == 0x1D8C || bigger == 0x1EFF || bigger == 0x213D || bigger == 0xAB5A || bigger == 0xFF59 || bigger == 0x118DC || bigger == 0x1D432 || bigger == 0x1D466 || bigger == 0x1D49A || bigger == 0x1D4CE || bigger == 0x1D502 || bigger == 0x1D536 || bigger == 0x1D56A || bigger == 0x1D59E || bigger == 0x1D5D2 || bigger == 0x1D606 || bigger == 0x1D63A || bigger == 0x1D66E || bigger == 0x1D6A2 || bigger == 0x1D6C4 || bigger == 0x1D6FE || bigger == 0x1D738 || bigger == 0x1D772 || bigger == 0x1D7AC; + case 0x007A: return bigger == 0x1D22 || bigger == 0x118C4 || bigger == 0x1D433 || bigger == 0x1D467 || bigger == 0x1D49B || bigger == 0x1D4CF || bigger == 0x1D503 || bigger == 0x1D537 || bigger == 0x1D56B || bigger == 0x1D59F || bigger == 0x1D5D3 || bigger == 0x1D607 || bigger == 0x1D63B || bigger == 0x1D66F || bigger == 0x1D6A3; + case 0x007B: return bigger == 0x2774 || bigger == 0x1D114; + case 0x007D: return bigger == 0x2775; + case 0x007E: return bigger == 0x02DC || bigger == 0x1FC0 || bigger == 0x2053 || bigger == 0x223C; + default: return 0; + } +} diff --git a/src/base/confusables.h b/src/base/confusables.h new file mode 100644 index 0000000..a93d657 --- /dev/null +++ b/src/base/confusables.h @@ -0,0 +1,16 @@ +#ifndef BASE_CONFUSABLES_H +#define BASE_CONFUSABLES_H + +#include "detect.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int str_utf8_is_confusable(int smaller, int bigger); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/base/detect.h b/src/base/detect.h new file mode 100644 index 0000000..4608493 --- /dev/null +++ b/src/base/detect.h @@ -0,0 +1,171 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_DETECT_H +#define BASE_DETECT_H + +/* + this file detected the family, platform and architecture + to compile for. +*/ + +/* platforms */ + +/* windows Family */ +#if defined(WIN64) || defined(_WIN64) + /* Hmm, is this IA64 or x86-64? */ + #define CONF_FAMILY_WINDOWS 1 + #define CONF_FAMILY_STRING "windows" + #define CONF_PLATFORM_WIN64 1 + #define CONF_PLATFORM_STRING "win64" +#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) + #define CONF_FAMILY_WINDOWS 1 + #define CONF_FAMILY_STRING "windows" + #define CONF_PLATFORM_WIN32 1 + #define CONF_PLATFORM_STRING "win32" +#endif + +/* unix family */ +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_FREEBSD 1 + #define CONF_PLATFORM_STRING "freebsd" +#endif + +#if defined(__NetBSD__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_NETBSD 1 + #define CONF_PLATFORM_STRING "netbsd" +#endif + +#if defined(__OpenBSD__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_OPENBSD 1 + #define CONF_PLATFORM_STRING "openbsd" +#endif + +#if defined(__LINUX__) || defined(__linux__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_LINUX 1 + #if defined(__ANDROID__) + #define CONF_PLATFORM_STRING "android" + #else + #define CONF_PLATFORM_STRING "linux" + #endif +#endif + +#if defined(__GNU__) || defined(__gnu__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_HURD 1 + #define CONF_PLATFORM_STRING "gnu" +#endif + +#if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_MACOSX 1 + #define CONF_PLATFORM_STRING "macosx" +#endif + +#if defined(__sun) + #define CONF_FAMILY_UNIX 1 + #define CONF_FAMILY_STRING "unix" + #define CONF_PLATFORM_SOLARIS 1 + #define CONF_PLATFORM_STRING "solaris" +#endif + +/* beos family */ +#if defined(__BeOS) || defined(__BEOS__) + #define CONF_FAMILY_BEOS 1 + #define CONF_FAMILY_STRING "beos" + #define CONF_PLATFORM_BEOS 1 + #define CONF_PLATFORM_STRING "beos" +#endif + + +/* use gcc endianness definitions when available */ +#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun) + #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + #include <sys/endian.h> + #else + #include <endian.h> + #endif + + #if __BYTE_ORDER == __LITTLE_ENDIAN + #define CONF_ARCH_ENDIAN_LITTLE 1 + #elif __BYTE_ORDER == __BIG_ENDIAN + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + + +/* architectures */ +#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32) + #define CONF_ARCH_IA32 1 + #define CONF_ARCH_STRING "ia32" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__ia64__) || defined(_M_IA64) + #define CONF_ARCH_IA64 1 + #define CONF_ARCH_STRING "ia64" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64) + #define CONF_ARCH_AMD64 1 + #define CONF_ARCH_STRING "amd64" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_LITTLE 1 + #endif +#endif + +#if defined(__powerpc__) || defined(__ppc__) + #define CONF_ARCH_PPC 1 + #define CONF_ARCH_STRING "ppc" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + +#if defined(__sparc__) + #define CONF_ARCH_SPARC 1 + #define CONF_ARCH_STRING "sparc" + #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) + #define CONF_ARCH_ENDIAN_BIG 1 + #endif +#endif + +#if defined(__ARMEB__) + #define CONF_ARCH_ARM 1 + #define CONF_ARCH_STRING "arm" + #define CONF_ARCH_ENDIAN_BIG 1 +#endif + +#if defined(__ARMEL__) + #define CONF_ARCH_ARM 1 + #define CONF_ARCH_STRING "arm" + #define CONF_ARCH_ENDIAN_LITTLE 1 +#endif + +#ifndef CONF_FAMILY_STRING +#define CONF_FAMILY_STRING "unknown" +#endif + +#ifndef CONF_PLATFORM_STRING +#define CONF_PLATFORM_STRING "unknown" +#endif + +#ifndef CONF_ARCH_STRING +#define CONF_ARCH_STRING "unknown" +#endif + +#endif diff --git a/src/base/math.h b/src/base/math.h new file mode 100644 index 0000000..07b0639 --- /dev/null +++ b/src/base/math.h @@ -0,0 +1,70 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_MATH_H +#define BASE_MATH_H + +#include <stdlib.h> + +template <typename T> +inline T clamp(T val, T min, T max) +{ + if(val < min) + return min; + if(val > max) + return max; + return val; +} + +inline float sign(float f) +{ + return f<0.0f?-1.0f:1.0f; +} + +inline int round_to_int(float f) +{ + if(f > 0) + return (int)(f+0.5f); + return (int)(f-0.5f); +} + +template<typename T, typename TB> +inline T mix(const T a, const T b, TB amount) +{ + return a + (b-a)*amount; +} + +inline float frandom() { return rand()/(float)(RAND_MAX); } + +// float to fixed +inline int f2fx(float v) { return (int)(v*(float)(1<<10)); } +inline float fx2f(int v) { return v*(1.0f/(1<<10)); } + +inline int gcd(int a, int b) +{ + while(b != 0) + { + int c = a % b; + a = b; + b = c; + } + return a; +} + +class fxp +{ + int value; +public: + void set(int v) { value = v; } + int get() const { return value; } + fxp &operator = (int v) { value = v<<10; return *this; } + fxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; } + operator float() const { return value/(float)(1<<10); } +}; + +const float pi = 3.1415926535897932384626433f; + +template <typename T> inline T min(T a, T b) { return a<b?a:b; } +template <typename T> inline T max(T a, T b) { return a>b?a:b; } +template <typename T> inline T absolute(T a) { return a<T(0)?-a:a; } + +#endif // BASE_MATH_H diff --git a/src/base/system.c b/src/base/system.c new file mode 100644 index 0000000..b52016e --- /dev/null +++ b/src/base/system.c @@ -0,0 +1,2554 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <stdlib.h> +#include <stdio.h> +#include <stdarg.h> +#include <string.h> +#include <ctype.h> +#include <time.h> + +#include "system.h" +#include "confusables.h" + +#include <sys/types.h> +#include <sys/stat.h> + +#if defined(WEBSOCKETS) + #include "engine/shared/websockets.h" +#endif + +#if defined(CONF_FAMILY_UNIX) + #include <sys/time.h> + #include <unistd.h> + + /* unix net includes */ + #include <sys/socket.h> + #include <sys/ioctl.h> + #include <errno.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) + // some lock and pthread functions are already defined in headers + // included from Carbon.h + // this prevents having duplicate definitions of those + #define _lock_set_user_ + #define _task_user_ + + #include <Carbon/Carbon.h> + #endif + + #if defined(__ANDROID__) + #include <android/log.h> + #endif + +#elif defined(CONF_FAMILY_WINDOWS) + #define WIN32_LEAN_AND_MEAN + #undef _WIN32_WINNT + #define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */ + #include <windows.h> + #include <winsock2.h> + #include <ws2tcpip.h> + #include <fcntl.h> + #include <direct.h> + #include <errno.h> + #include <process.h> + #include <shellapi.h> + #include <wincrypt.h> +#else + #error NOT IMPLEMENTED +#endif + +#if defined(CONF_PLATFORM_SOLARIS) + #include <sys/filio.h> +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +#ifdef FUZZING +static unsigned char gs_NetData[1024]; +static int gs_NetPosition = 0; +static int gs_NetSize = 0; +#endif + +IOHANDLE io_stdin() { return (IOHANDLE)stdin; } +IOHANDLE io_stdout() { return (IOHANDLE)stdout; } +IOHANDLE io_stderr() { return (IOHANDLE)stderr; } + +static DBG_LOGGER loggers[16]; +static int num_loggers = 0; + +static NETSTATS network_stats = {0}; +static MEMSTATS memory_stats = {0}; + +static NETSOCKET invalid_socket = {NETTYPE_INVALID, -1, -1}; + +#define AF_WEBSOCKET_INET (0xee) + +void dbg_logger(DBG_LOGGER logger) +{ + loggers[num_loggers++] = logger; +} + +void dbg_assert_imp(const char *filename, int line, int test, const char *msg) +{ + if(!test) + { + dbg_msg("assert", "%s(%d): %s", filename, line, msg); + dbg_break(); + } +} + +void dbg_break() +{ + *((volatile unsigned*)0) = 0x0; +} + +#if !defined(CONF_PLATFORM_MACOSX) +#define QUEUE_SIZE 16 + +typedef struct +{ + char q[QUEUE_SIZE][1024*4]; + int begin; + int end; + SEMAPHORE mutex; + SEMAPHORE notempty; + SEMAPHORE notfull; +} Queue; + +static int dbg_msg_threaded = 0; +static Queue log_queue; + +int queue_empty(Queue *q) +{ + return q->begin == q->end; +} + +int queue_full(Queue *q) +{ + return ((q->end+1) % QUEUE_SIZE) == q->begin; +} + +void dbg_msg_thread(void *v) +{ + char str[1024*4]; + int i; + int f; + while(1) + { + semaphore_wait(&log_queue.notempty); + semaphore_wait(&log_queue.mutex); + f = queue_full(&log_queue); + + str_copy(str, log_queue.q[log_queue.begin], sizeof(str)); + + log_queue.begin = (log_queue.begin + 1) % QUEUE_SIZE; + + if(f) + semaphore_signal(&log_queue.notfull); + + if(!queue_empty(&log_queue)) + semaphore_signal(&log_queue.notempty); + + semaphore_signal(&log_queue.mutex); + + for(i = 0; i < num_loggers; i++) + loggers[i](str); + } +} + +void dbg_enable_threaded() +{ + Queue *q; + void *Thread; + + q = &log_queue; + q->begin = 0; + q->end = 0; + semaphore_init(&q->mutex); + semaphore_init(&q->notempty); + semaphore_init(&q->notfull); + semaphore_signal(&q->mutex); + semaphore_signal(&q->notfull); + + dbg_msg_threaded = 1; + + Thread = thread_init(dbg_msg_thread, 0); + thread_detach(Thread); +} +#endif + +void dbg_msg(const char *sys, const char *fmt, ...) +{ + va_list args; + char *msg; + int len; + + //str_format(str, sizeof(str), "[%08x][%s]: ", (int)time(0), sys); + time_t rawtime; + struct tm* timeinfo; + char timestr [80]; + + time ( &rawtime ); + timeinfo = localtime ( &rawtime ); + + strftime (timestr,sizeof(timestr),"%y-%m-%d %H:%M:%S",timeinfo); + +#if !defined(CONF_PLATFORM_MACOSX) + if(dbg_msg_threaded) + { + int e; + semaphore_wait(&log_queue.notfull); + semaphore_wait(&log_queue.mutex); + e = queue_empty(&log_queue); + + str_format(log_queue.q[log_queue.end], sizeof(log_queue.q[log_queue.end]), "[%s][%s]: ", timestr, sys); + + len = strlen(log_queue.q[log_queue.end]); + msg = (char *)log_queue.q[log_queue.end] + len; + + va_start(args, fmt); +#if defined(CONF_FAMILY_WINDOWS) + _vsnprintf(msg, sizeof(log_queue.q[log_queue.end])-len, fmt, args); +#else + vsnprintf(msg, sizeof(log_queue.q[log_queue.end])-len, fmt, args); +#endif + va_end(args); + + log_queue.end = (log_queue.end + 1) % QUEUE_SIZE; + + if(e) + semaphore_signal(&log_queue.notempty); + + if(!queue_full(&log_queue)) + semaphore_signal(&log_queue.notfull); + + semaphore_signal(&log_queue.mutex); + } + else +#endif + { + char str[1024*4]; + int i; + + str_format(str, sizeof(str), "[%s][%s]: ", timestr, sys); + + len = strlen(str); + msg = (char *)str + len; + + va_start(args, fmt); +#if defined(CONF_FAMILY_WINDOWS) + _vsnprintf(msg, sizeof(str)-len, fmt, args); +#else + vsnprintf(msg, sizeof(str)-len, fmt, args); +#endif + va_end(args); + + for(i = 0; i < num_loggers; i++) + loggers[i](str); + } +} + +static void logger_stdout(const char *line) +{ + printf("%s\n", line); + fflush(stdout); +#if defined(__ANDROID__) + __android_log_print(ANDROID_LOG_INFO, "DDNet", "%s", line); +#endif +} + +static void logger_debugger(const char *line) +{ +#if defined(CONF_FAMILY_WINDOWS) + OutputDebugString(line); + OutputDebugString("\n"); +#endif +} + + +static IOHANDLE logfile = 0; +static void logger_file(const char *line) +{ + io_write(logfile, line, strlen(line)); + io_write_newline(logfile); + io_flush(logfile); +} + +void dbg_logger_stdout() { dbg_logger(logger_stdout); } + +void dbg_logger_debugger() { dbg_logger(logger_debugger); } +void dbg_logger_file(const char *filename) +{ + logfile = io_open(filename, IOFLAG_WRITE); + if(logfile) + dbg_logger(logger_file); + else + dbg_msg("dbg/logger", "failed to open '%s' for logging", filename); + +} +/* */ + +typedef struct MEMHEADER +{ + const char *filename; + int line; + int size; + struct MEMHEADER *prev; + struct MEMHEADER *next; +} MEMHEADER; + +typedef struct MEMTAIL +{ + int guard; +} MEMTAIL; + +static struct MEMHEADER *first = 0; +static const int MEM_GUARD_VAL = 0xbaadc0de; + +void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment) +{ + /* TODO: fix alignment */ + /* TODO: add debugging */ + MEMTAIL *tail; + MEMHEADER *header = (struct MEMHEADER *)malloc(size+sizeof(MEMHEADER)+sizeof(MEMTAIL)); + dbg_assert(header != 0, "mem_alloc failure"); + if(!header) + return NULL; + tail = (struct MEMTAIL *)(((char*)(header+1))+size); + header->size = size; + header->filename = filename; + header->line = line; + + memory_stats.allocated += header->size; + memory_stats.total_allocations++; + memory_stats.active_allocations++; + + tail->guard = MEM_GUARD_VAL; + + header->prev = (MEMHEADER *)0; + header->next = first; + if(first) + first->prev = header; + first = header; + + /*dbg_msg("mem", "++ %p", header+1); */ + return header+1; +} + +void mem_free(void *p) +{ + if(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); + } +} + +void mem_debug_dump(IOHANDLE file) +{ + char buf[1024]; + MEMHEADER *header = first; + if(!file) + file = io_open("memory.txt", IOFLAG_WRITE); + + if(file) + { + while(header) + { + str_format(buf, sizeof(buf), "%s(%d): %d", header->filename, header->line, header->size); + io_write(file, buf, strlen(buf)); + io_write_newline(file); + header = header->next; + } + + io_close(file); + } +} + + +void mem_copy(void *dest, const void *source, unsigned size) +{ + memcpy(dest, source, size); +} + +void mem_move(void *dest, const void *source, unsigned size) +{ + memmove(dest, source, size); +} + +void mem_zero(void *block,unsigned size) +{ + memset(block, 0, size); +} + +int mem_check_imp() +{ + MEMHEADER *header = first; + while(header) + { + MEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size); + if(tail->guard != MEM_GUARD_VAL) + { + dbg_msg("mem", "Memory check failed at %s(%d): %d", header->filename, header->line, header->size); + return 0; + } + header = header->next; + } + + return 1; +} + +IOHANDLE io_open(const char *filename, int flags) +{ + if(flags == IOFLAG_READ) + return (IOHANDLE)fopen(filename, "rb"); + if(flags == IOFLAG_WRITE) + return (IOHANDLE)fopen(filename, "wb"); + return 0x0; +} + +unsigned io_read(IOHANDLE io, void *buffer, unsigned size) +{ + return fread(buffer, 1, size, (FILE*)io); +} + +unsigned io_skip(IOHANDLE io, int size) +{ + fseek((FILE*)io, size, SEEK_CUR); + return size; +} + +int io_seek(IOHANDLE io, int offset, int origin) +{ + int real_origin; + + switch(origin) + { + case IOSEEK_START: + real_origin = SEEK_SET; + break; + case IOSEEK_CUR: + real_origin = SEEK_CUR; + break; + case IOSEEK_END: + real_origin = SEEK_END; + break; + default: + return -1; + } + + return fseek((FILE*)io, offset, real_origin); +} + +long int io_tell(IOHANDLE io) +{ + return ftell((FILE*)io); +} + +long int io_length(IOHANDLE io) +{ + long int length; + io_seek(io, 0, IOSEEK_END); + length = io_tell(io); + io_seek(io, 0, IOSEEK_START); + return length; +} + +unsigned io_write(IOHANDLE io, const void *buffer, unsigned size) +{ + return fwrite(buffer, 1, size, (FILE*)io); +} + +unsigned io_write_newline(IOHANDLE io) +{ +#if defined(CONF_FAMILY_WINDOWS) + return fwrite("\r\n", 1, 2, (FILE*)io); +#else + return fwrite("\n", 1, 1, (FILE*)io); +#endif +} + +int io_close(IOHANDLE io) +{ + fclose((FILE*)io); + return 1; +} + +int io_flush(IOHANDLE io) +{ + fflush((FILE*)io); + return 0; +} + +void *thread_init(void (*threadfunc)(void *), void *u) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_t id; + pthread_create(&id, NULL, (void *(*)(void*))threadfunc, u); + return (void*)id; +#elif defined(CONF_FAMILY_WINDOWS) + return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadfunc, u, 0, NULL); +#else + #error not implemented +#endif +} + +void thread_wait(void *thread) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_join((pthread_t)thread, NULL); +#elif defined(CONF_FAMILY_WINDOWS) + WaitForSingleObject((HANDLE)thread, INFINITE); +#else + #error not implemented +#endif +} + +void thread_destroy(void *thread) +{ +#if defined(CONF_FAMILY_UNIX) + void *r = 0; + pthread_join((pthread_t)thread, &r); +#else + /*#error not implemented*/ +#endif +} + +void thread_yield() +{ +#if defined(CONF_FAMILY_UNIX) + sched_yield(); +#elif defined(CONF_FAMILY_WINDOWS) + Sleep(0); +#else + #error not implemented +#endif +} + +void thread_sleep(int milliseconds) +{ +#if defined(CONF_FAMILY_UNIX) + usleep(milliseconds*1000); +#elif defined(CONF_FAMILY_WINDOWS) + Sleep(milliseconds); +#else + #error not implemented +#endif +} + +void thread_detach(void *thread) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_detach((pthread_t)(thread)); +#elif defined(CONF_FAMILY_WINDOWS) + CloseHandle(thread); +#else + #error not implemented +#endif +} + + + + +#if defined(CONF_FAMILY_UNIX) +typedef pthread_mutex_t LOCKINTERNAL; +#elif defined(CONF_FAMILY_WINDOWS) +typedef CRITICAL_SECTION LOCKINTERNAL; +#else + #error not implemented on this platform +#endif + +LOCK lock_create() +{ + LOCKINTERNAL *lock = (LOCKINTERNAL*)mem_alloc(sizeof(LOCKINTERNAL), 4); + +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_init(lock, 0x0); +#elif defined(CONF_FAMILY_WINDOWS) + InitializeCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif + return (LOCK)lock; +} + +void lock_destroy(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_destroy((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + DeleteCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif + mem_free(lock); +} + +int lock_trylock(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + return pthread_mutex_trylock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + return !TryEnterCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +void lock_wait(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_lock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + EnterCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +void lock_unlock(LOCK lock) +{ +#if defined(CONF_FAMILY_UNIX) + pthread_mutex_unlock((LOCKINTERNAL *)lock); +#elif defined(CONF_FAMILY_WINDOWS) + LeaveCriticalSection((LPCRITICAL_SECTION)lock); +#else + #error not implemented on this platform +#endif +} + +#if !defined(CONF_PLATFORM_MACOSX) + #if defined(CONF_FAMILY_UNIX) + void semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); } + void semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); } + void semaphore_signal(SEMAPHORE *sem) { sem_post(sem); } + void semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); } + #elif defined(CONF_FAMILY_WINDOWS) + void semaphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); } + void semaphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, INFINITE); } + void semaphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); } + void semaphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); } + #else + #error not implemented on this platform + #endif +#endif + +static int new_tick = -1; + +void set_new_tick() +{ + new_tick = 1; +} + +/* ----- time ----- */ +int64 time_get() +{ + static int64 last = 0; + if(!new_tick) + return last; + if(new_tick != -1) + new_tick = 0; + +#if defined(CONF_FAMILY_UNIX) + struct timeval val; + gettimeofday(&val, NULL); + last = (int64)val.tv_sec*(int64)1000000+(int64)val.tv_usec; + return last; +#elif defined(CONF_FAMILY_WINDOWS) + { + int64 t; + QueryPerformanceCounter((PLARGE_INTEGER)&t); + if(t<last) /* for some reason, QPC can return values in the past */ + return last; + last = t; + return t; + } +#else + #error not implemented +#endif +} + +int64 time_freq() +{ +#if defined(CONF_FAMILY_UNIX) + return 1000000; +#elif defined(CONF_FAMILY_WINDOWS) + int64 t; + QueryPerformanceFrequency((PLARGE_INTEGER)&t); + return t; +#else + #error not implemented +#endif +} + +/* ----- network ----- */ +static void netaddr_to_sockaddr_in(const NETADDR *src, struct sockaddr_in *dest) +{ + mem_zero(dest, sizeof(struct sockaddr_in)); + if(src->type != NETTYPE_IPV4 && src->type != NETTYPE_WEBSOCKET_IPV4) + { + dbg_msg("system", "couldn't convert NETADDR of type %d to ipv4", src->type); + return; + } + + dest->sin_family = AF_INET; + dest->sin_port = htons(src->port); + mem_copy(&dest->sin_addr.s_addr, src->ip, 4); +} + +static void netaddr_to_sockaddr_in6(const NETADDR *src, struct sockaddr_in6 *dest) +{ + mem_zero(dest, sizeof(struct sockaddr_in6)); + if(src->type != NETTYPE_IPV6) + { + dbg_msg("system", "couldn't not convert NETADDR of type %d to ipv6", src->type); + return; + } + + dest->sin6_family = AF_INET6; + dest->sin6_port = htons(src->port); + mem_copy(&dest->sin6_addr.s6_addr, src->ip, 16); +} + +static void sockaddr_to_netaddr(const struct sockaddr *src, NETADDR *dst) +{ + if(src->sa_family == AF_INET) + { + mem_zero(dst, sizeof(NETADDR)); + dst->type = NETTYPE_IPV4; + dst->port = htons(((struct sockaddr_in*)src)->sin_port); + mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); + } + else if(src->sa_family == AF_WEBSOCKET_INET) + { + mem_zero(dst, sizeof(NETADDR)); + dst->type = NETTYPE_WEBSOCKET_IPV4; + dst->port = htons(((struct sockaddr_in*)src)->sin_port); + mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); + } + else if(src->sa_family == AF_INET6) + { + mem_zero(dst, sizeof(NETADDR)); + dst->type = NETTYPE_IPV6; + dst->port = htons(((struct sockaddr_in6*)src)->sin6_port); + mem_copy(dst->ip, &((struct sockaddr_in6*)src)->sin6_addr.s6_addr, 16); + } + else + { + mem_zero(dst, sizeof(struct sockaddr)); + dbg_msg("system", "couldn't convert sockaddr of family %d", src->sa_family); + } +} + +int net_addr_comp(const NETADDR *a, const NETADDR *b) +{ + return mem_comp(a, b, sizeof(NETADDR)); +} + +void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port) +{ + if(addr->type == NETTYPE_IPV4 || addr->type == NETTYPE_WEBSOCKET_IPV4) + { + if(add_port != 0) + str_format(string, max_length, "%d.%d.%d.%d:%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3], addr->port); + else + str_format(string, max_length, "%d.%d.%d.%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3]); + } + else if(addr->type == NETTYPE_IPV6) + { + if(add_port != 0) + str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", + (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], + (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15], + addr->port); + else + str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]", + (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], + (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15]); + } + else + str_format(string, max_length, "unknown type %d", addr->type); +} + +static int priv_net_extract(const char *hostname, char *host, int max_host, int *port) +{ + int i; + + *port = 0; + host[0] = 0; + + if(hostname[0] == '[') + { + // ipv6 mode + for(i = 1; i < max_host && hostname[i] && hostname[i] != ']'; i++) + host[i-1] = hostname[i]; + host[i-1] = 0; + if(hostname[i] != ']') // malformatted + return -1; + + i++; + if(hostname[i] == ':') + *port = atol(hostname+i+1); + } + else + { + // generic mode (ipv4, hostname etc) + for(i = 0; i < max_host-1 && hostname[i] && hostname[i] != ':'; i++) + host[i] = hostname[i]; + host[i] = 0; + + if(hostname[i] == ':') + *port = atol(hostname+i+1); + } + + return 0; +} + +int net_host_lookup(const char *hostname, NETADDR *addr, int types) +{ + struct addrinfo hints; + struct addrinfo *result = NULL; + int e; + char host[256]; + int port = 0; + + if(priv_net_extract(hostname, host, sizeof(host), &port)) + return -1; + + 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) + hints.ai_family = AF_INET; + else if(types == NETTYPE_IPV6) + hints.ai_family = AF_INET6; + + e = getaddrinfo(host, NULL, &hints, &result); + + if(!result) + return -1; + + if(e != 0) + { + freeaddrinfo(result); + return -1; + } + + sockaddr_to_netaddr(result->ai_addr, addr); + addr->port = port; + freeaddrinfo(result); + return 0; +} + +static int parse_int(int *out, const char **str) +{ + int i = 0; + *out = 0; + if(**str < '0' || **str > '9') + return -1; + + i = **str - '0'; + (*str)++; + + while(1) + { + if(**str < '0' || **str > '9') + { + *out = i; + return 0; + } + + i = (i*10) + (**str - '0'); + (*str)++; + } + + return 0; +} + +static int parse_char(char c, const char **str) +{ + if(**str != c) return -1; + (*str)++; + return 0; +} + +static int parse_uint8(unsigned char *out, const char **str) +{ + int i; + if(parse_int(&i, str) != 0) return -1; + if(i < 0 || i > 0xff) return -1; + *out = i; + return 0; +} + +static int parse_uint16(unsigned short *out, const char **str) +{ + int i; + if(parse_int(&i, str) != 0) return -1; + if(i < 0 || i > 0xffff) return -1; + *out = i; + return 0; +} + +int net_addr_from_str(NETADDR *addr, const char *string) +{ + const char *str = string; + mem_zero(addr, sizeof(NETADDR)); + + if(str[0] == '[') + { + /* ipv6 */ + struct sockaddr_in6 sa6; + char buf[128]; + int i; + str++; + for(i = 0; i < 127 && str[i] && str[i] != ']'; i++) + buf[i] = str[i]; + buf[i] = 0; + str += i; +#if defined(CONF_FAMILY_WINDOWS) + { + int size; + sa6.sin6_family = AF_INET6; + size = (int)sizeof(sa6); + if(WSAStringToAddress(buf, AF_INET6, NULL, (struct sockaddr *)&sa6, &size) != 0) + return -1; + } +#else + sa6.sin6_family = AF_INET6; + + if(inet_pton(AF_INET6, buf, &sa6.sin6_addr) != 1) + return -1; +#endif + sockaddr_to_netaddr((struct sockaddr *)&sa6, addr); + + if(*str == ']') + { + str++; + if(*str == ':') + { + str++; + if(parse_uint16(&addr->port, &str)) + return -1; + } + } + else + return -1; + + return 0; + } + else + { + /* ipv4 */ + if(parse_uint8(&addr->ip[0], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[1], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[2], &str)) return -1; + if(parse_char('.', &str)) return -1; + if(parse_uint8(&addr->ip[3], &str)) return -1; + if(*str == ':') + { + str++; + if(parse_uint16(&addr->port, &str)) return -1; + } + + addr->type = NETTYPE_IPV4; + } + + return 0; +} + +static void priv_net_close_socket(int sock) +{ +#if defined(CONF_FAMILY_WINDOWS) + closesocket(sock); +#else + close(sock); +#endif +} + +static int priv_net_close_all_sockets(NETSOCKET sock) +{ + /* close down ipv4 */ + if(sock.ipv4sock >= 0) + { + priv_net_close_socket(sock.ipv4sock); + sock.ipv4sock = -1; + sock.type &= ~NETTYPE_IPV4; + } + +#if defined(WEBSOCKETS) + /* close down websocket_ipv4 */ + if(sock.web_ipv4sock >= 0) + { + websocket_destroy(sock.web_ipv4sock); + sock.web_ipv4sock = -1; + sock.type &= ~NETTYPE_WEBSOCKET_IPV4; + } +#endif + + /* close down ipv6 */ + if(sock.ipv6sock >= 0) + { + priv_net_close_socket(sock.ipv6sock); + sock.ipv6sock = -1; + sock.type &= ~NETTYPE_IPV6; + } + return 0; +} + +static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, int sockaddrlen) +{ + int sock, e; + + /* create socket */ + sock = socket(domain, type, 0); + if(sock < 0) + { +#if defined(CONF_FAMILY_WINDOWS) + char buf[128]; + int error = WSAGetLastError(); + if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) + buf[0] = 0; + dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, error, buf); +#else + dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); +#endif + return -1; + } + +#if defined(CONF_FAMILY_UNIX) + /* on tcp sockets set SO_REUSEADDR + to fix port rebind on restart */ + if (domain == AF_INET && type == SOCK_STREAM) + { + int option = 1; + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); + } +#endif + + /* set to IPv6 only if thats what we are creating */ +#if defined(IPV6_V6ONLY) /* windows sdk 6.1 and higher */ + if(domain == AF_INET6) + { + int ipv6only = 1; + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6only, sizeof(ipv6only)); + } +#endif + + /* bind the socket */ + e = bind(sock, addr, sockaddrlen); + if(e != 0) + { +#if defined(CONF_FAMILY_WINDOWS) + char buf[128]; + int error = WSAGetLastError(); + if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) + buf[0] = 0; + dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, error, buf); +#else + dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); +#endif + priv_net_close_socket(sock); + return -1; + } + + /* return the newly created socket */ + return sock; +} + +NETSOCKET net_udp_create(NETADDR bindaddr) +{ + NETSOCKET sock = invalid_socket; + NETADDR tmpbindaddr = bindaddr; + int broadcast = 1; + int recvsize = 65536; + + if(bindaddr.type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV4; + netaddr_to_sockaddr_in(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr)); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV4; + sock.ipv4sock = socket; + + /* set boardcast */ + setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); + + /* set receive buffer size */ + setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); + + { + /* set DSCP/TOS */ + int iptos = 0x10 /* IPTOS_LOWDELAY */; + //int iptos = 46; /* High Priority */ + setsockopt(socket, IPPROTO_IP, IP_TOS, (char*)&iptos, sizeof(iptos)); + } + } + } + +#if defined(WEBSOCKETS) + if(bindaddr.type&NETTYPE_WEBSOCKET_IPV4) + { + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_WEBSOCKET_IPV4; + + char addr_str[NETADDR_MAXSTRSIZE]; + net_addr_str(&tmpbindaddr, addr_str, sizeof(addr_str), 0); + socket = websocket_create(addr_str, tmpbindaddr.port); + + if (socket >= 0) { + sock.type |= NETTYPE_WEBSOCKET_IPV4; + sock.web_ipv4sock = socket; + } + } +#endif + + if(bindaddr.type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV6; + netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET6, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr)); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV6; + sock.ipv6sock = socket; + + /* set boardcast */ + setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); + + /* set receive buffer size */ + setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); + + { + /* set DSCP/TOS */ + int iptos = 0x10 /* IPTOS_LOWDELAY */; + //int iptos = 46; /* High Priority */ + setsockopt(socket, IPPROTO_IP, IP_TOS, (char*)&iptos, sizeof(iptos)); + } + } + } + + /* set non-blocking */ + net_set_non_blocking(sock); + +#ifdef FUZZING + IOHANDLE file = io_open("bar.txt", IOFLAG_READ); + gs_NetPosition = 0; + gs_NetSize = io_length(file); + io_read(file, gs_NetData, 1024); + io_close(file); +#endif /* FUZZING */ + + /* return */ + return sock; +} + +int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size) +{ +#ifndef FUZZING + int d = -1; + + if(addr->type&NETTYPE_IPV4) + { + if(sock.ipv4sock >= 0) + { + struct sockaddr_in sa; + if(addr->type&NETTYPE_LINK_BROADCAST) + { + mem_zero(&sa, sizeof(sa)); + sa.sin_port = htons(addr->port); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = INADDR_BROADCAST; + } + else + netaddr_to_sockaddr_in(addr, &sa); + + d = sendto((int)sock.ipv4sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + } + else + dbg_msg("net", "can't send ipv4 traffic to this socket"); + } + +#if defined(WEBSOCKETS) + if(addr->type&NETTYPE_WEBSOCKET_IPV4) + { + if(sock.web_ipv4sock >= 0) + d = websocket_send(sock.web_ipv4sock, (const unsigned char*)data, size, addr->port); + else + dbg_msg("net", "can't send websocket_ipv4 traffic to this socket"); + } +#endif + + if(addr->type&NETTYPE_IPV6) + { + if(sock.ipv6sock >= 0) + { + struct sockaddr_in6 sa; + if(addr->type&NETTYPE_LINK_BROADCAST) + { + mem_zero(&sa, sizeof(sa)); + sa.sin6_port = htons(addr->port); + sa.sin6_family = AF_INET6; + sa.sin6_addr.s6_addr[0] = 0xff; /* multicast */ + sa.sin6_addr.s6_addr[1] = 0x02; /* link local scope */ + sa.sin6_addr.s6_addr[15] = 1; /* all nodes */ + } + else + netaddr_to_sockaddr_in6(addr, &sa); + + d = sendto((int)sock.ipv6sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); + } + else + dbg_msg("net", "can't send ipv6 traffic to this socket"); + } + /* + else + dbg_msg("net", "can't send to network of type %d", addr->type); + */ + + /*if(d < 0) + { + 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); + dbg_msg("net", "\taddr = %s", addrstr); + + }*/ + network_stats.sent_bytes += size; + network_stats.sent_packets++; + return d; +#else + return size; +#endif /* FUZZING */ +} + +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize) +{ +#ifndef FUZZING + char sockaddrbuf[128]; + socklen_t fromlen;// = sizeof(sockaddrbuf); + int bytes = 0; + + if(bytes == 0 && sock.ipv4sock >= 0) + { + fromlen = sizeof(struct sockaddr_in); + bytes = recvfrom(sock.ipv4sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + } + + if(bytes <= 0 && sock.ipv6sock >= 0) + { + fromlen = sizeof(struct sockaddr_in6); + bytes = recvfrom(sock.ipv6sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); + } + +#if defined(WEBSOCKETS) + if(bytes <= 0 && sock.web_ipv4sock >= 0) + { + fromlen = sizeof(struct sockaddr); + bytes = websocket_recv(sock.web_ipv4sock, data, maxsize, (struct sockaddr_in *)&sockaddrbuf, fromlen); + ((struct sockaddr_in *)&sockaddrbuf)->sin_family = AF_WEBSOCKET_INET; + } +#endif + + if(bytes > 0) + { + sockaddr_to_netaddr((struct sockaddr *)&sockaddrbuf, addr); + network_stats.recv_bytes += bytes; + network_stats.recv_packets++; + return bytes; + } + else if(bytes == 0) + return 0; + return -1; /* error */ +#else + addr->type = NETTYPE_IPV4; + addr->port = 11111; + addr->ip[0] = 127; + addr->ip[1] = 0; + addr->ip[2] = 0; + addr->ip[3] = 1; + + int CurrentData = 0; + while (gs_NetPosition < gs_NetSize && CurrentData < maxsize) + { + if(gs_NetData[gs_NetPosition] == '\n') + { + gs_NetPosition++; + break; + } + + ((unsigned char*)data)[CurrentData] = gs_NetData[gs_NetPosition]; + CurrentData++; + gs_NetPosition++; + } + + if (gs_NetPosition >= gs_NetSize) + exit(0); + + return CurrentData; +#endif /* FUZZING */ +} + +int net_udp_close(NETSOCKET sock) +{ + return priv_net_close_all_sockets(sock); +} + +NETSOCKET net_tcp_create(NETADDR bindaddr) +{ + NETSOCKET sock = invalid_socket; + NETADDR tmpbindaddr = bindaddr; + + if(bindaddr.type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV4; + netaddr_to_sockaddr_in(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr)); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV4; + sock.ipv4sock = socket; + } + } + + if(bindaddr.type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + int socket = -1; + + /* bind, we should check for error */ + tmpbindaddr.type = NETTYPE_IPV6; + netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); + socket = priv_net_create_socket(AF_INET6, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr)); + if(socket >= 0) + { + sock.type |= NETTYPE_IPV6; + sock.ipv6sock = socket; + } + } + + /* return */ + return sock; +} + +int net_set_non_blocking(NETSOCKET sock) +{ + unsigned long mode = 1; + if(sock.ipv4sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + if(sock.ipv6sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + return 0; +} + +int net_set_blocking(NETSOCKET sock) +{ + unsigned long mode = 0; + if(sock.ipv4sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + if(sock.ipv6sock >= 0) + { +#if defined(CONF_FAMILY_WINDOWS) + ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#else + ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); +#endif + } + + return 0; +} + +int net_tcp_listen(NETSOCKET sock, int backlog) +{ + int err = -1; + if(sock.ipv4sock >= 0) + err = listen(sock.ipv4sock, backlog); + if(sock.ipv6sock >= 0) + err = listen(sock.ipv6sock, backlog); + return err; +} + +int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) +{ + int s; + socklen_t sockaddr_len; + + *new_sock = invalid_socket; + + if(sock.ipv4sock >= 0) + { + struct sockaddr_in addr; + sockaddr_len = sizeof(addr); + + s = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len); + + if (s != -1) + { + sockaddr_to_netaddr((const struct sockaddr *)&addr, a); + new_sock->type = NETTYPE_IPV4; + new_sock->ipv4sock = s; + return s; + } + } + + if(sock.ipv6sock >= 0) + { + struct sockaddr_in6 addr; + sockaddr_len = sizeof(addr); + + s = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len); + + if (s != -1) + { + sockaddr_to_netaddr((const struct sockaddr *)&addr, a); + new_sock->type = NETTYPE_IPV6; + new_sock->ipv6sock = s; + return s; + } + } + + return -1; +} + +int net_tcp_connect(NETSOCKET sock, const NETADDR *a) +{ + if(a->type&NETTYPE_IPV4) + { + struct sockaddr_in addr; + netaddr_to_sockaddr_in(a, &addr); + return connect(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr)); + } + + if(a->type&NETTYPE_IPV6) + { + struct sockaddr_in6 addr; + netaddr_to_sockaddr_in6(a, &addr); + return connect(sock.ipv6sock, (struct sockaddr *)&addr, sizeof(addr)); + } + + return -1; +} + +int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr) +{ + int res = 0; + + net_set_non_blocking(sock); + res = net_tcp_connect(sock, &bindaddr); + net_set_blocking(sock); + + return res; +} + +int net_tcp_send(NETSOCKET sock, const void *data, int size) +{ + int bytes = -1; + + if(sock.ipv4sock >= 0) + bytes = send((int)sock.ipv4sock, (const char*)data, size, 0); + if(sock.ipv6sock >= 0) + bytes = send((int)sock.ipv6sock, (const char*)data, size, 0); + + return bytes; +} + +int net_tcp_recv(NETSOCKET sock, void *data, int maxsize) +{ + int bytes = -1; + + if(sock.ipv4sock >= 0) + bytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0); + if(sock.ipv6sock >= 0) + bytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0); + + return bytes; +} + +int net_tcp_close(NETSOCKET sock) +{ + return priv_net_close_all_sockets(sock); +} + +int net_errno() +{ +#if defined(CONF_FAMILY_WINDOWS) + return WSAGetLastError(); +#else + return errno; +#endif +} + +int net_would_block() +{ +#if defined(CONF_FAMILY_WINDOWS) + return net_errno() == WSAEWOULDBLOCK; +#else + return net_errno() == EWOULDBLOCK; +#endif +} + +int net_init() +{ +#if defined(CONF_FAMILY_WINDOWS) + WSADATA wsaData; + int err = WSAStartup(MAKEWORD(1, 1), &wsaData); + dbg_assert(err == 0, "network initialization failed."); + return err==0?0:1; +#endif + + return 0; +} + +int fs_listdir_info(const char *dir, FS_LISTDIR_INFO_CALLBACK cb, int type, void *user) +{ +#if defined(CONF_FAMILY_WINDOWS) + WIN32_FIND_DATA finddata; + HANDLE handle; + char buffer[1024*2]; + int length; + str_format(buffer, sizeof(buffer), "%s/*", dir); + + handle = FindFirstFileA(buffer, &finddata); + + if (handle == INVALID_HANDLE_VALUE) + return 0; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + /* add all the entries */ + do + { + str_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length); + if(cb(finddata.cFileName, fs_getmtime(buffer), fs_is_dir(buffer), type, user)) + break; + } + while (FindNextFileA(handle, &finddata)); + + FindClose(handle); + return 0; +#else + struct dirent *entry; + char buffer[1024*2]; + int length; + DIR *d = opendir(dir); + + if(!d) + return 0; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + while((entry = readdir(d)) != NULL) + { + str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + if(cb(entry->d_name, fs_getmtime(buffer), fs_is_dir(buffer), type, user)) + break; + } + + /* close the directory and return */ + closedir(d); + return 0; +#endif +} + +int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) +{ +#if defined(CONF_FAMILY_WINDOWS) + WIN32_FIND_DATA finddata; + HANDLE handle; + char buffer[1024*2]; + int length; + str_format(buffer, sizeof(buffer), "%s/*", dir); + + handle = FindFirstFileA(buffer, &finddata); + + if (handle == INVALID_HANDLE_VALUE) + return 0; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + /* add all the entries */ + do + { + str_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length); + if(cb(finddata.cFileName, fs_is_dir(buffer), type, user)) + break; + } + while (FindNextFileA(handle, &finddata)); + + FindClose(handle); + return 0; +#else + struct dirent *entry; + char buffer[1024*2]; + int length; + DIR *d = opendir(dir); + + if(!d) + return 0; + + str_format(buffer, sizeof(buffer), "%s/", dir); + length = str_length(buffer); + + while((entry = readdir(d)) != NULL) + { + str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); + if(cb(entry->d_name, fs_is_dir(buffer), type, user)) + break; + } + + /* close the directory and return */ + closedir(d); + return 0; +#endif +} + +int fs_storage_path(const char *appname, char *path, int max) +{ +#if defined(CONF_FAMILY_WINDOWS) + char *home = getenv("APPDATA"); + if(!home) + return -1; + _snprintf(path, max, "%s/%s", home, appname); + return 0; +#else + char *home = getenv("HOME"); +#if !defined(CONF_PLATFORM_MACOSX) + int i; +#endif + if(!home) + return -1; + +#if defined(CONF_PLATFORM_MACOSX) + snprintf(path, max, "%s/Library/Application Support/%s", home, appname); +#else + snprintf(path, max, "%s/.%s", home, appname); + for(i = strlen(home)+2; path[i]; i++) + path[i] = tolower(path[i]); +#endif + + return 0; +#endif +} + +int fs_makedir(const char *path) +{ +#if defined(CONF_FAMILY_WINDOWS) + if(_mkdir(path) == 0) + return 0; + if(errno == EEXIST) + return 0; + return -1; +#else + if(mkdir(path, 0755) == 0) + return 0; + if(errno == EEXIST) + return 0; + return -1; +#endif +} + +int fs_is_dir(const char *path) +{ +#if defined(CONF_FAMILY_WINDOWS) + /* TODO: do this smarter */ + WIN32_FIND_DATA finddata; + HANDLE handle; + char buffer[1024*2]; + str_format(buffer, sizeof(buffer), "%s/*", path); + + if ((handle = FindFirstFileA(buffer, &finddata)) == INVALID_HANDLE_VALUE) + return 0; + + FindClose(handle); + return 1; +#else + struct stat sb; + if (stat(path, &sb) == -1) + return 0; + + if (S_ISDIR(sb.st_mode)) + return 1; + else + return 0; +#endif +} + +time_t fs_getmtime(const char *path) +{ + struct stat sb; + if (stat(path, &sb) == -1) + return 0; + + return sb.st_mtime; +} + +int fs_chdir(const char *path) +{ + if(fs_is_dir(path)) + { + if(chdir(path)) + return 1; + else + return 0; + } + else + return 1; +} + +char *fs_getcwd(char *buffer, int buffer_size) +{ + if(buffer == 0) + return 0; +#if defined(CONF_FAMILY_WINDOWS) + return _getcwd(buffer, buffer_size); +#else + return getcwd(buffer, buffer_size); +#endif +} + +int fs_parent_dir(char *path) +{ + char *parent = 0; + for(; *path; ++path) + { + if(*path == '/' || *path == '\\') + parent = path; + } + + if(parent) + { + *parent = 0; + return 0; + } + return 1; +} + +int fs_remove(const char *filename) +{ + if(remove(filename) != 0) + return 1; + return 0; +} + +int fs_rename(const char *oldname, const char *newname) +{ +#if defined(CONF_FAMILY_WINDOWS) + if(MoveFileEx(oldname, newname, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != 0) + return 1; +#else + if(rename(oldname, newname) != 0) + return 1; +#endif + return 0; +} + +void swap_endian(void *data, unsigned elem_size, unsigned num) +{ + char *src = (char*) data; + char *dst = src + (elem_size - 1); + + while(num) + { + unsigned n = elem_size>>1; + char tmp; + while(n) + { + tmp = *src; + *src = *dst; + *dst = tmp; + + src++; + dst--; + n--; + } + + src = src + (elem_size>>1); + dst = src + (elem_size - 1); + num--; + } +} + +int net_socket_read_wait(NETSOCKET sock, int time) +{ + struct timeval tv; + fd_set readfds; + int sockid; + + tv.tv_sec = time / 1000000; + tv.tv_usec = time % 1000000; + sockid = 0; + + FD_ZERO(&readfds); + if(sock.ipv4sock >= 0) + { + FD_SET(sock.ipv4sock, &readfds); + sockid = sock.ipv4sock; + } + if(sock.ipv6sock >= 0) + { + FD_SET(sock.ipv6sock, &readfds); + if(sock.ipv6sock > sockid) + sockid = sock.ipv6sock; + } +#if defined(WEBSOCKETS) + if(sock.web_ipv4sock >= 0) + { + int maxfd = websocket_fd_set(sock.web_ipv4sock, &readfds); + if (maxfd > sockid) + sockid = maxfd; + } +#endif + + /* don't care about writefds and exceptfds */ + if(time < 0) + select(sockid+1, &readfds, NULL, NULL, NULL); + else + select(sockid+1, &readfds, NULL, NULL, &tv); + + if(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds)) + return 1; + + if(sock.ipv6sock >= 0 && FD_ISSET(sock.ipv6sock, &readfds)) + return 1; + + return 0; +} + +int time_timestamp() +{ + return time(0); +} + +void str_append(char *dst, const char *src, int dst_size) +{ + int s = strlen(dst); + int i = 0; + while(s < dst_size) + { + dst[s] = src[i]; + if(!src[i]) /* check for null termination */ + break; + s++; + i++; + } + + dst[dst_size-1] = 0; /* assure null termination */ +} + +void str_copy(char *dst, const char *src, int dst_size) +{ + strncpy(dst, src, dst_size); + dst[dst_size-1] = 0; /* assure null termination */ +} + +int str_length(const char *str) +{ + return (int)strlen(str); +} + +int str_format(char *buffer, int buffer_size, const char *format, ...) +{ + int ret; +#if defined(CONF_FAMILY_WINDOWS) + va_list ap; + va_start(ap, format); + ret = _vsnprintf(buffer, buffer_size, format, ap); + va_end(ap); +#else + va_list ap; + va_start(ap, format); + ret = vsnprintf(buffer, buffer_size, format, ap); + va_end(ap); +#endif + + buffer[buffer_size-1] = 0; /* assure null termination */ + return ret; +} + +char *str_trim_words(char *str, int words) +{ + while (words && *str) + { + if (isspace(*str) && !isspace(*(str + 1))) + words--; + str++; + } + return str; +} + +/* makes sure that the string only contains the characters between 32 and 127 */ +void str_sanitize_strong(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + *str &= 0x7f; + if(*str < 32) + *str = 32; + str++; + } +} + +/* makes sure that the string only contains the characters between 32 and 255 */ +void str_sanitize_cc(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + if(*str < 32) + *str = ' '; + str++; + } +} + +/* makes sure that the string only contains the characters between 32 and 255 + \r\n\t */ +void str_sanitize(char *str_in) +{ + unsigned char *str = (unsigned char *)str_in; + while(*str) + { + if(*str < 32 && !(*str == '\r') && !(*str == '\n') && !(*str == '\t')) + *str = ' '; + str++; + } +} + +char *str_skip_to_whitespace(char *str) +{ + while(*str && (*str != ' ' && *str != '\t' && *str != '\n')) + str++; + return str; +} + +char *str_skip_whitespaces(char *str) +{ + while(*str && (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r')) + str++; + return str; +} + +/* case */ +int str_comp_nocase(const char *a, const char *b) +{ +#if defined(CONF_FAMILY_WINDOWS) + return _stricmp(a,b); +#else + return strcasecmp(a,b); +#endif +} + +int str_comp_nocase_num(const char *a, const char *b, const int num) +{ +#if defined(CONF_FAMILY_WINDOWS) + return _strnicmp(a, b, num); +#else + return strncasecmp(a, b, num); +#endif +} + +int str_comp(const char *a, const char *b) +{ + return strcmp(a, b); +} + +int str_comp_num(const char *a, const char *b, const int num) +{ + return strncmp(a, b, num); +} + +int str_comp_filenames(const char *a, const char *b) +{ + int result; + + for(; *a && *b; ++a, ++b) + { + if(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9') + { + result = 0; + do + { + if(!result) + result = *a - *b; + ++a; ++b; + } + while(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9'); + + if(*a >= '0' && *a <= '9') + return 1; + else if(*b >= '0' && *b <= '9') + return -1; + else if(result) + return result; + } + + if(*a != *b) + break; + } + return *a - *b; +} + +const char *str_find_nocase(const char *haystack, const char *needle) +{ + while(*haystack) /* native implementation */ + { + const char *a = haystack; + const char *b = needle; + while(*a && *b && tolower(*a) == tolower(*b)) + { + a++; + b++; + } + if(!(*b)) + return haystack; + haystack++; + } + + return 0; +} + + +const char *str_find(const char *haystack, const char *needle) +{ + while(*haystack) /* native implementation */ + { + const char *a = haystack; + const char *b = needle; + while(*a && *b && *a == *b) + { + a++; + b++; + } + if(!(*b)) + return haystack; + haystack++; + } + + return 0; +} + +void str_hex(char *dst, int dst_size, const void *data, int data_size) +{ + static const char hex[] = "0123456789ABCDEF"; + int b; + + for(b = 0; b < data_size && b < dst_size/4-4; b++) + { + dst[b*3] = hex[((const unsigned char *)data)[b]>>4]; + dst[b*3+1] = hex[((const unsigned char *)data)[b]&0xf]; + dst[b*3+2] = ' '; + dst[b*3+3] = 0; + } +} + +void str_timestamp_ex(time_t time_data, char *buffer, int buffer_size, const char *format) +{ + struct tm *time_info; + + time_info = localtime(&time_data); + strftime(buffer, buffer_size, format, time_info); + buffer[buffer_size-1] = 0; /* assure null termination */ +} + +void str_timestamp(char *buffer, int buffer_size) +{ + time_t time_data; + time(&time_data); + str_timestamp_ex(time_data, buffer, buffer_size, "%Y-%m-%d_%H-%M-%S"); +} + +int mem_comp(const void *a, const void *b, int size) +{ + return memcmp(a,b,size); +} + +const MEMSTATS *mem_stats() +{ + return &memory_stats; +} + +void net_stats(NETSTATS *stats_inout) +{ + *stats_inout = network_stats; +} + +void gui_messagebox(const char *title, const char *message) +{ +#if defined(CONF_PLATFORM_MACOSX) + DialogRef theItem; + DialogItemIndex itemIndex; + + /* FIXME: really needed? can we rely on glfw? */ + /* HACK - get events without a bundle */ + ProcessSerialNumber psn; + GetCurrentProcess(&psn); + TransformProcessType(&psn,kProcessTransformToForegroundApplication); + SetFrontProcess(&psn); + /* END HACK */ + + CreateStandardAlert(kAlertStopAlert, + CFStringCreateWithCString(NULL, title, kCFStringEncodingASCII), + CFStringCreateWithCString(NULL, message, kCFStringEncodingASCII), + NULL, + &theItem); + + RunStandardAlert(theItem, NULL, &itemIndex); +#elif defined(CONF_FAMILY_UNIX) + static char cmd[1024]; + int err; + /* use xmessage which is available on nearly every X11 system */ + snprintf(cmd, sizeof(cmd), "xmessage -center -title '%s' '%s'", + title, + message); + + err = system(cmd); + dbg_msg("gui/msgbox", "result = %i", err); +#elif defined(CONF_FAMILY_WINDOWS) + MessageBox(NULL, + message, + title, + MB_ICONEXCLAMATION | MB_OK); +#else + /* this is not critical */ + #warning not implemented +#endif +} + +int str_isspace(char c) { return c == ' ' || c == '\n' || c == '\t'; } + +char str_uppercase(char c) +{ + if(c >= 'a' && c <= 'z') + return 'A' + (c-'a'); + return c; +} + +int str_toint(const char *str) { return atoi(str); } +int str_toint_base(const char *str, int base) { return strtol(str, NULL, base); } +float str_tofloat(const char *str) { return atof(str); } + + +int str_utf8_comp_names(const char *a, const char *b) +{ + int codeA; + int codeB; + int diff; + + while(*a && *b) + { + do + { + codeA = str_utf8_decode(&a); + } + while(*a && !str_utf8_isspace(codeA)); + + do + { + codeB = str_utf8_decode(&b); + } + while(*b && !str_utf8_isspace(codeB)); + + diff = codeA - codeB; + + if((diff < 0 && !str_utf8_is_confusable(codeA, codeB)) + || (diff > 0 && !str_utf8_is_confusable(codeB, codeA))) + return diff; + } + + return *a - *b; +} + +int str_utf8_isspace(int code) +{ + return code > 0x20 && code != 0xA0 && code != 0x034F && code != 0x2800 && + (code < 0x2000 || code > 0x200F) && (code < 0x2028 || code > 0x202F) && + (code < 0x205F || code > 0x2064) && (code < 0x206A || code > 0x206F) && + (code < 0xFE00 || code > 0xFE0F) && code != 0xFEFF && + (code < 0xFFF9 || code > 0xFFFC); +} + +const char *str_utf8_skip_whitespaces(const char *str) +{ + const char *str_old; + int code; + + while(*str) + { + str_old = str; + code = str_utf8_decode(&str); + + // check if unicode is not empty + if(str_utf8_isspace(code)) + { + return str_old; + } + } + + return str; +} + +int str_utf8_isstart(char c) +{ + if((c&0xC0) == 0x80) /* 10xxxxxx */ + return 0; + return 1; +} + +int str_utf8_rewind(const char *str, int cursor) +{ + while(cursor) + { + cursor--; + if(str_utf8_isstart(*(str + cursor))) + break; + } + return cursor; +} + +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 */ + { + if(!buf[1]) return cursor+1; + return cursor+2; + } + else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ + { + if(!buf[1]) return cursor+1; + if(!buf[2]) return cursor+2; + return cursor+3; + } + else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ + { + if(!buf[1]) return cursor+1; + if(!buf[2]) return cursor+2; + if(!buf[3]) return cursor+3; + return cursor+4; + } + + /* invalid */ + return cursor+1; +} + +int str_utf8_encode(char *ptr, int chr) +{ + /* encode */ + if(chr <= 0x7F) + { + ptr[0] = (char)chr; + return 1; + } + else if(chr <= 0x7FF) + { + ptr[0] = 0xC0|((chr>>6)&0x1F); + ptr[1] = 0x80|(chr&0x3F); + return 2; + } + else if(chr <= 0xFFFF) + { + ptr[0] = 0xE0|((chr>>12)&0x0F); + ptr[1] = 0x80|((chr>>6)&0x3F); + ptr[2] = 0x80|(chr&0x3F); + return 3; + } + else if(chr <= 0x10FFFF) + { + ptr[0] = 0xF0|((chr>>18)&0x07); + ptr[1] = 0x80|((chr>>12)&0x3F); + ptr[2] = 0x80|((chr>>6)&0x3F); + ptr[3] = 0x80|(chr&0x3F); + return 4; + } + + return 0; +} + +static unsigned char str_byte_next(const char **ptr) +{ + unsigned char byte = **ptr; + (*ptr)++; + return byte; +} + +static void str_byte_rewind(const char **ptr) +{ + (*ptr)--; +} + +int str_utf8_decode(const char **ptr) +{ + // As per https://encoding.spec.whatwg.org/#utf-8-decoder. + unsigned char utf8_lower_boundary = 0x80; + unsigned char utf8_upper_boundary = 0xBF; + int utf8_code_point = 0; + int utf8_bytes_seen = 0; + int utf8_bytes_needed = 0; + while(1) + { + unsigned char byte = str_byte_next(ptr); + if(utf8_bytes_needed == 0) + { + if(byte <= 0x7F) + { + return byte; + } + else if(0xC2 <= byte && byte <= 0xDF) + { + utf8_bytes_needed = 1; + utf8_code_point = byte - 0xC0; + } + else if(0xE0 <= byte && byte <= 0xEF) + { + if(byte == 0xE0) utf8_lower_boundary = 0xA0; + if(byte == 0xED) utf8_upper_boundary = 0x9F; + utf8_bytes_needed = 2; + utf8_code_point = byte - 0xE0; + } + else if(0xF0 <= byte && byte <= 0xF4) + { + if(byte == 0xF0) utf8_lower_boundary = 0x90; + if(byte == 0xF4) utf8_upper_boundary = 0x8F; + utf8_bytes_needed = 3; + utf8_code_point = byte - 0xF0; + } + else + { + return -1; // Error. + } + utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed); + continue; + } + if(!(utf8_lower_boundary <= byte && byte <= utf8_upper_boundary)) + { + // Resetting variables not necessary, will be done when + // the function is called again. + str_byte_rewind(ptr); + return -1; + } + utf8_lower_boundary = 0x80; + utf8_upper_boundary = 0xBF; + utf8_bytes_seen += 1; + utf8_code_point = utf8_code_point + ((byte - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen))); + if(utf8_bytes_seen != utf8_bytes_needed) + { + continue; + } + // Resetting variables not necessary, see above. + return utf8_code_point; + } +} + +int str_utf8_check(const char *str) +{ + int codepoint; + while((codepoint = str_utf8_decode(&str))) + { + if(codepoint == -1) + { + return 0; + } + } + return 1; +} + + +unsigned str_quickhash(const char *str) +{ + unsigned hash = 5381; + for(; *str; str++) + hash = ((hash << 5) + hash) + (*str); /* hash * 33 + c */ + return hash; +} + +int pid() +{ +#if defined(CONF_FAMILY_WINDOWS) + return _getpid(); +#else + return getpid(); +#endif +} + +void shell_execute(const char *file) +{ +#if defined(CONF_FAMILY_WINDOWS) + ShellExecute(NULL, NULL, file, NULL, NULL, SW_SHOWDEFAULT); +#elif defined(CONF_FAMILY_UNIX) + char* argv[2]; + argv[0] = (char*) file; + argv[1] = NULL; + pid_t pid = fork(); + if(!pid) + execv(file, argv); +#endif +} + +int os_compare_version(int major, int minor) +{ +#if defined(CONF_FAMILY_WINDOWS) + OSVERSIONINFO ver; + mem_zero(&ver, sizeof(OSVERSIONINFO)); + ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&ver); + if(ver.dwMajorVersion > major || (ver.dwMajorVersion == major && ver.dwMinorVersion > minor)) + return 1; + else if(ver.dwMajorVersion == major && ver.dwMinorVersion == minor) + return 0; + else + return -1; +#else + return 0; // unimplemented +#endif +} + +struct SECURE_RANDOM_DATA +{ + int initialized; +#if defined(CONF_FAMILY_WINDOWS) + HCRYPTPROV provider; +#else + IOHANDLE urandom; +#endif +}; + +static struct SECURE_RANDOM_DATA secure_random_data = { 0 }; + +int secure_random_init() +{ + if(secure_random_data.initialized) + { + return 0; + } +#if defined(CONF_FAMILY_WINDOWS) + if(CryptAcquireContext(&secure_random_data.provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + { + secure_random_data.initialized = 1; + return 0; + } + else + { + return 1; + } +#else + secure_random_data.urandom = io_open("/dev/urandom", IOFLAG_READ); + if(secure_random_data.urandom) + { + secure_random_data.initialized = 1; + return 0; + } + else + { + return 1; + } +#endif +} + +void secure_random_fill(void *bytes, size_t length) +{ + if(!secure_random_data.initialized) + { + dbg_msg("secure", "called secure_random_fill before secure_random_init"); + dbg_break(); + } +#if defined(CONF_FAMILY_WINDOWS) + if(!CryptGenRandom(secure_random_data.provider, length, bytes)) + { + dbg_msg("secure", "CryptGenRandom failed, last_error=%d", GetLastError()); + dbg_break(); + } +#else + if(length != io_read(secure_random_data.urandom, bytes, length)) + { + dbg_msg("secure", "io_read returned with a short read"); + dbg_break(); + } +#endif +} + +int secure_rand() +{ + unsigned int i; + secure_random_fill(&i, sizeof(i)); + return (int)(i%RAND_MAX); +} + +#if defined(__cplusplus) +} +#endif diff --git a/src/base/system.h b/src/base/system.h new file mode 100644 index 0000000..cb5be47 --- /dev/null +++ b/src/base/system.h @@ -0,0 +1,1396 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +/* + Title: OS Abstraction +*/ + +#ifndef BASE_SYSTEM_H +#define BASE_SYSTEM_H + +#include "detect.h" +#include "stddef.h" +#include <time.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* Group: Debug */ +/* + 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) +void dbg_assert_imp(const char *filename, int line, int test, const char *msg); + + +#ifdef __clang_analyzer__ +#include <assert.h> +#undef dbg_assert +#define dbg_assert(test,msg) assert(test) +#endif + +/* + Function: dbg_break + Breaks into the debugger. + + Remarks: + Does nothing in release version of the library. + + See Also: + <dbg_assert> +*/ +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> +*/ +void dbg_msg(const char *sys, const char *fmt, ...); + +/* Group: Memory */ + +/* + 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. + + See Also: + <mem_free> +*/ +void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment); +#define mem_alloc(s,a) mem_alloc_debug(__FILE__, __LINE__, (s), (a)) + +/* + 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> +*/ +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> +*/ +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> +*/ +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 +*/ +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 + >0 - Block a is greater then block b +*/ +int mem_comp(const void *a, const void *b, int size); + +/* + Function: mem_check + Validates the heap + 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") + +/* Group: File IO */ +enum { + IOFLAG_READ = 1, + IOFLAG_WRITE = 2, + IOFLAG_RANDOM = 4, + + IOSEEK_START = 0, + IOSEEK_CUR = 1, + IOSEEK_END = 2 +}; + +typedef struct IOINTERNAL *IOHANDLE; + +/* + Function: io_open + Opens a file. + + Parameters: + filename - File to open. + flags - A set of flags. IOFLAG_READ, IOFLAG_WRITE, IOFLAG_RANDOM. + + Returns: + Returns a handle to the file on success and 0 on failure. + +*/ +IOHANDLE io_open(const char *filename, int flags); + +/* + Function: io_read + Reads data into a buffer from a file. + + Parameters: + 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. + +*/ +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. +*/ +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. +*/ +unsigned io_write(IOHANDLE io, const void *buffer, unsigned size); + +/* + Function: io_write_newline + Writes newline to file. + + Parameters: + io - Handle to the file. + + Returns: + Number of bytes written. +*/ +unsigned io_write_newline(IOHANDLE io); + +/* + 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. +*/ +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. +*/ +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. +*/ +long int io_length(IOHANDLE io); + +/* + Function: io_close + Closes a file. + + Parameters: + io - Handle to the file. + + Returns: + Returns 0 on success. +*/ +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. +*/ +int io_flush(IOHANDLE io); + + +/* + Function: io_stdin + Returns an <IOHANDLE> to the standard input. +*/ +IOHANDLE io_stdin(); + +/* + Function: io_stdout + Returns an <IOHANDLE> to the standard output. +*/ +IOHANDLE io_stdout(); + +/* + Function: io_stderr + Returns an <IOHANDLE> to the standard error. +*/ +IOHANDLE io_stderr(); + + +/* Group: Threads */ + +/* + Function: thread_sleep + Suspends the current thread for a given period. + + Parameters: + milliseconds - Number of milliseconds to sleep. +*/ +void thread_sleep(int milliseconds); + +/* + Function: thread_init + Creates a new thread. + + Parameters: + threadfunc - Entry point for the new thread. + user - Pointer to pass to the thread. + +*/ +void *thread_init(void (*threadfunc)(void *), void *user); + +/* + Function: thread_wait + Waits for a thread to be done or destroyed. + + Parameters: + thread - Thread to wait for. +*/ +void thread_wait(void *thread); + +/* + Function: thread_destroy + Destroys a thread. + + Parameters: + thread - Thread to destroy. +*/ +void thread_destroy(void *thread); + +/* + Function: thread_yeild + Yeild the current threads execution slice. +*/ +void thread_yield(); + +/* + Function: thread_detach + Puts the thread in the detached thread, guaranteeing that + resources of the thread will be freed immediately when the + thread terminates. + + Parameters: + thread - Thread to detach +*/ +void thread_detach(void *thread); + +/* Group: Locks */ +typedef void* LOCK; + +LOCK lock_create(); +void lock_destroy(LOCK lock); + +int lock_trylock(LOCK lock); +void lock_wait(LOCK lock); +void lock_unlock(LOCK lock); + + +/* Group: Semaphores */ + +#if !defined(CONF_PLATFORM_MACOSX) + #if defined(CONF_FAMILY_UNIX) + #include <semaphore.h> + typedef sem_t SEMAPHORE; + #elif defined(CONF_FAMILY_WINDOWS) + typedef void* SEMAPHORE; + #else + #error missing sempahore implementation + #endif + + void semaphore_init(SEMAPHORE *sem); + void semaphore_wait(SEMAPHORE *sem); + void semaphore_signal(SEMAPHORE *sem); + void semaphore_destroy(SEMAPHORE *sem); +#endif + +/* Group: Timer */ +#ifdef __GNUC__ +/* if compiled with -pedantic-errors it will complain about long + not being a C90 thing. +*/ +__extension__ typedef long long int64; +#else +typedef long long int64; +#endif + +void set_new_tick(); + +/* + Function: time_get + Fetches a sample from a high resolution timer. + + Returns: + Current value of the timer. + + Remarks: + To know how fast the timer is ticking, see <time_freq>. +*/ +int64 time_get(); + +/* + Function: time_freq + Returns the frequency of the high resolution timer. + + Returns: + Returns the frequency of the high resolution timer. +*/ +int64 time_freq(); + +/* + Function: time_timestamp + Retrives the current time as a UNIX timestamp + + Returns: + The time as a UNIX timestamp +*/ +int time_timestamp(); + +/* Group: Network General */ +typedef struct +{ + int type; + int ipv4sock; + int ipv6sock; + int web_ipv4sock; +} NETSOCKET; + +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, + NETTYPE_LINK_BROADCAST = 4, + NETTYPE_WEBSOCKET_IPV4 = 8, + NETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6|NETTYPE_WEBSOCKET_IPV4 +}; + +typedef struct +{ + unsigned int type; + unsigned char ip[16]; + unsigned short port; +} NETADDR; + +/* + Function: net_init + Initiates network functionallity. + + Returns: + Returns 0 on success, + + Remarks: + You must call this function before using any other network + functions. +*/ +int net_init(); + +/* + Function: net_host_lookup + Does a hostname lookup by name and fills out the passed + NETADDR struct with the recieved details. + + Returns: + 0 on success. +*/ +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 + >0 - Address a is greater then address b +*/ +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. + add_port - add port to string or not + + Remarks: + - The string will always be zero terminated + +*/ +void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port); + +/* + 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. +*/ +int net_addr_from_str(NETADDR *addr, const char *string); + +/* Group: Network UDP */ + +/* + Function: net_udp_create + Creates a UDP socket and binds it to a port. + + Parameters: + bindaddr - Address to bind the socket to. + + Returns: + On success it returns an handle to the socket. On failure it + returns NETSOCKET_INVALID. +*/ +NETSOCKET net_udp_create(NETADDR bindaddr); + +/* + Function: net_udp_send + Sends a packet over an UDP socket. + + Parameters: + sock - Socket to use. + 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. +*/ +int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size); + +/* + Function: net_udp_recv + Recives a packet over an UDP socket. + + Parameters: + sock - Socket to use. + 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. +*/ +int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize); + +/* + Function: net_udp_close + Closes an UDP socket. + + Parameters: + sock - Socket to close. + + Returns: + Returns 0 on success. -1 on error. +*/ +int net_udp_close(NETSOCKET sock); + + +/* Group: Network TCP */ + +/* + Function: net_tcp_create + Creates a TCP socket. + + Parameters: + bindaddr - Address to bind the socket to. + + Returns: + On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID. +*/ +NETSOCKET net_tcp_create(NETADDR bindaddr); + +/* + 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. +*/ +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. +*/ +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. +*/ +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 + be fetched. +*/ +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. +*/ +int net_tcp_close(NETSOCKET sock); + +/* Group: Strings */ + +/* + 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. +*/ +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. + dst_size - Size of the buffer dst. + + Remarks: + - The strings are treated as zero-termineted strings. + - Garantees that dst string will contain zero-termination. +*/ +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. +*/ +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. + format - printf formating string. + ... - Parameters for the formating. + + Returns: + Length of written string + + Remarks: + - See the C manual for syntax for the printf formating string. + - The strings are treated as zero-termineted strings. + - Garantees that dst string will contain zero-termination. +*/ +int str_format(char *buffer, int buffer_size, const char *format, ...); + +/* + Function: str_trim_words + Trims specific number of words at the start of a string. + + Parameters: + str - String to trim the words from. + words - Count of words to trim. + + Returns: + Trimmed string + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +char *str_trim_words(char *str, int words); + +/* + Function: str_sanitize_strong + Replaces all characters below 32 and above 127 with whitespace. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +void str_sanitize_strong(char *str); + +/* + Function: str_sanitize_cc + Replaces all characters below 32 with whitespace. + + Parameters: + str - String to sanitize. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +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. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +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. + + Returns: + Pointer to the first whitespace character found + within the string. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +char *str_skip_to_whitespace(char *str); + +/* + Function: str_skip_whitespaces + Skips leading whitespace characters(' ', '\t', '\n', '\r'). + + Parameters: + str - Pointer to the string. + + Returns: + Pointer to the first non-whitespace character found + within the string. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +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: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-termineted strings. +*/ +int str_comp_nocase(const char *a, const char *b); + +/* + Function: str_comp_nocase_num + Compares up to num characters of two strings case insensitive. + + Parameters: + a - String to compare. + b - String to compare. + num - Maximum characters to compare + + Returns: + <0 - String a is lesser than string b + 0 - String a is equal to string b + >0 - String a is greater than string b + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-termineted strings. +*/ +int str_comp_nocase_num(const char *a, const char *b, const int num); + +/* + Function: str_comp + Compares to strings case sensitive. + + Parameters: + a - String to compare. + b - String to compare. + + 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 + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +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: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +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: + <0 - String a is lesser then string b + 0 - String a is equal to string b + >0 - String a is greater then string b + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +int str_comp_filenames(const char *a, const char *b); + +/* + Function: str_find_nocase + Finds a string inside another string case insensitive. + + 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. + + Remarks: + - Only garanted to work with a-z/A-Z. + - The strings are treated as zero-termineted strings. +*/ +const char *str_find_nocase(const char *haystack, const char *needle); + +/* + Function: str_find + Finds a string inside another string case sensitive. + + 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. + + Remarks: + - The strings are treated as zero-termineted strings. +*/ +const char *str_find(const char *haystack, const char *needle); + +/* + Function: str_hex + Takes a datablock and generates a hexstring of it. + + Parameters: + dst - Buffer to fill with hex data + dst_size - size of the buffer + data - Data to turn into hex + data - Size of the data + + Remarks: + - The desination buffer will be zero-terminated +*/ +void str_hex(char *dst, int dst_size, const void *data, int data_size); + +/* + Function: str_timestamp + Copies a time stamp in the format year-month-day_hour-minute-second to the string. + + Parameters: + buffer - Pointer to a buffer that shall receive the time stamp string. + buffer_size - Size of the buffer. + + Remarks: + - Guarantees that buffer string will contain zero-termination. +*/ +void str_timestamp(char *buffer, int buffer_size); +void str_timestamp_ex(time_t time, char *buffer, int buffer_size, const char *format); + +/* Group: Filesystem */ + +/* + 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. +*/ +typedef int (*FS_LISTDIR_CALLBACK)(const char *name, int is_dir, int dir_type, void *user); +typedef int (*FS_LISTDIR_INFO_CALLBACK)(const char *name, time_t date, int is_dir, int dir_type, void *user); +int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user); +int fs_listdir_info(const char *dir, FS_LISTDIR_INFO_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. +*/ +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 + - Returns %APPDATA%/Appname on Windows based systems +*/ +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. +*/ +int fs_is_dir(const char *path); + +/* + Function: fs_getmtime + Gets the modification time of a file +*/ +time_t fs_getmtime(const char *path); + +/* + Function: fs_chdir + Changes current working directory + + Returns: + Returns 0 on success, 1 on failure. +*/ +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. +*/ +char *fs_getcwd(char *buffer, int buffer_size); + +/* + Function: fs_parent_dir + Get the parent directory of a directory + + Parameters: + path - The directory string + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The string is treated as zero-termineted string. +*/ +int fs_parent_dir(char *path); + +/* + Function: fs_remove + Deletes the file with the specified name. + + Parameters: + filename - The file to delete + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +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 + + Returns: + Returns 0 on success, 1 on failure. + + Remarks: + - The strings are treated as zero-terminated strings. +*/ +int fs_rename(const char *oldname, const char *newname); + +/* + Group: Undocumented +*/ + + +/* + Function: net_tcp_connect_non_blocking + + DOCTODO: serp +*/ +int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr); + +/* + Function: net_set_non_blocking + + DOCTODO: serp +*/ +int net_set_non_blocking(NETSOCKET sock); + +/* + Function: net_set_non_blocking + + DOCTODO: serp +*/ +int net_set_blocking(NETSOCKET sock); + +/* + Function: net_errno + + DOCTODO: serp +*/ +int net_errno(); + +/* + Function: net_would_block + + DOCTODO: serp +*/ +int net_would_block(); + +int net_socket_read_wait(NETSOCKET sock, int time); + +void mem_debug_dump(IOHANDLE file); + +void swap_endian(void *data, unsigned elem_size, unsigned num); + + +typedef void (*DBG_LOGGER)(const char *line); +void dbg_logger(DBG_LOGGER logger); + +#if !defined(CONF_PLATFORM_MACOSX) +void dbg_enable_threaded(); +#endif +void dbg_logger_stdout(); +void dbg_logger_debugger(); +void dbg_logger_file(const char *filename); + +typedef struct +{ + int allocated; + int active_allocations; + int total_allocations; +} MEMSTATS; + +const MEMSTATS *mem_stats(); + +typedef struct +{ + int sent_packets; + int sent_bytes; + int recv_packets; + int recv_bytes; +} NETSTATS; + + +void net_stats(NETSTATS *stats); + +int str_toint(const char *str); +int str_toint_base(const char *str, int base); +float str_tofloat(const char *str); +int str_isspace(char c); +char str_uppercase(char c); +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 +*/ +void gui_messagebox(const char *title, const char *message); + +int str_utf8_comp_names(const char *a, const char *b); + +int str_utf8_isspace(int code); + +int str_utf8_isstart(char c); + +const char *str_utf8_skip_whitespaces(const char *str); + +/* + Function: str_utf8_rewind + Moves a cursor backwards in an utf8 string + + Parameters: + str - utf8 string + cursor - position in the string + + Returns: + New cursor position. + + Remarks: + - Won't move the cursor less then 0 +*/ +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. + + Remarks: + - Won't move the cursor beyond the zero termination marker +*/ +int str_utf8_forward(const char *str, int cursor); + +/* + Function: str_utf8_decode + Decodes a utf8 codepoint + + Parameters: + ptr - Pointer to a utf8 string. This pointer will be moved forward. + + Returns: + The Unicode codepoint. -1 for invalid input and 0 for end of string. + + Remarks: + - This function will also move the pointer forward. + - You may call this function again after an error occured. +*/ +int str_utf8_decode(const char **ptr); + +/* + Function: str_utf8_encode + Encode an utf8 character + + Parameters: + ptr - Pointer to a buffer that should receive the data. Should be able to hold at least 4 bytes. + + Returns: + Number of bytes put into the buffer. + + Remarks: + - Does not do zero termination of the string. +*/ +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. + + Remarks: + - The string is treated as zero-terminated utf8 string. +*/ +int str_utf8_check(const char *str); + +int pid(); + +/* + Function: shell_execute + Executes a given file. +*/ +void shell_execute(const char *file); + +/* + Function: os_compare_version + Compares the OS version to a given major and minor. + + Parameters: + major - Major version to compare to. + minor - Minor version to compare to. + + Returns: + 1 - OS version higher. + 0 - OS version same. + -1 - OS version lower. +*/ +int os_compare_version(int major, int minor); + +/* + Function: secure_random_init + Initializes the secure random module. + You *MUST* check the return value of this function. + + Returns: + 0 - Initialization succeeded. + 1 - Initialization failed. +*/ +int secure_random_init(); + +/* + Function: secure_random_fill + Fills the buffer with the specified amount of random bytes. + + Parameters: + buffer - Pointer to the start of the buffer. + length - Length of the buffer. +*/ +void secure_random_fill(void *bytes, size_t length); + +/* + Function: secure_rand + Returns random int (replacement for rand()). +*/ +int secure_rand(); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/base/tl/algorithm.h b/src/base/tl/algorithm.h new file mode 100644 index 0000000..27d0db3 --- /dev/null +++ b/src/base/tl/algorithm.h @@ -0,0 +1,137 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ALGORITHM_H +#define BASE_TL_ALGORITHM_H + +#include "base/tl/range.h" + + +/* + insert 4 + v + 1 2 3 4 5 6 + +*/ + + +template<class R, class T> +R partition_linear(R range, T value) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + concept_sorted::check(range); + + for(; !range.empty(); range.pop_front()) + { + if(!(range.front() < value)) + return range; + } + return range; +} + + +template<class R, class T> +R partition_binary(R range, T value) +{ + concept_empty::check(range); + concept_index::check(range); + 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; + if(range.index(pivot) < value) + range = range.slice(pivot+1, range.size()-1); + else + range = range.slice(0, pivot+1); + } + return range; +} + +template<class R, class T> +R find_linear(R range, T value) +{ + concept_empty::check(range); + concept_forwarditeration::check(range); + for(; !range.empty(); range.pop_front()) + if(value == range.front()) + break; + return range; +} + +template<class R, class T> +R find_binary(R range, T value) +{ + range = partition_linear(range, value); + if(range.empty()) return range; + if(range.front() == value) return range; + return R(); +} + + +template<class R> +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()) + { + R section = range; + typename R::type *prev = §ion.front(); + section.pop_front(); + for(; !section.empty(); section.pop_front()) + { + typename R::type *cur = §ion.front(); + if(*cur < *prev) + swap(*cur, *prev); + prev = cur; + } + } +} + +/* +template<class R> +void sort_quick(R range) +{ + concept_index::check(range); +}*/ + + +template<class R> +void sort(R range) +{ + sort_bubble(range); +} + + +template<class R> +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; +} + +#endif // TL_FILE_ALGORITHMS_HPP diff --git a/src/base/tl/allocator.h b/src/base/tl/allocator.h new file mode 100644 index 0000000..d12347e --- /dev/null +++ b/src/base/tl/allocator.h @@ -0,0 +1,17 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ALLOCATOR_H +#define BASE_TL_ALLOCATOR_H + +template <class T> +class allocator_default +{ +public: + static T *alloc() { return new T; } + static void free(T *p) { delete p; } + + static T *alloc_array(int size) { return new T [size]; } + static void free_array(T *p) { delete [] p; } +}; + +#endif // TL_FILE_ALLOCATOR_HPP diff --git a/src/base/tl/array.h b/src/base/tl/array.h new file mode 100644 index 0000000..cfa70d9 --- /dev/null +++ b/src/base/tl/array.h @@ -0,0 +1,344 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_ARRAY_H +#define BASE_TL_ARRAY_H + +#include "base/tl/range.h" +#include "base/tl/allocator.h" + + +/* + 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 optimize() to reduce the needed space. +*/ +template <class T, class ALLOCATOR = allocator_default<T> > +class array : private ALLOCATOR +{ + void init() + { + list = 0x0; + clear(); + } + +public: + typedef plain_range<T> range; + + /* + Function: array constructor + */ + array() + { + init(); + } + + /* + Function: array copy constructor + */ + array(const array &other) + { + init(); + set_size(other.size()); + for(int i = 0; i < size(); i++) + (*this)[i] = other[i]; + } + + + /* + Function: array destructor + */ + ~array() + { + ALLOCATOR::free_array(list); + list = 0x0; + } + + + /* + Function: delete_all + + Remarks: + - Invalidates ranges + */ + void delete_all() + { + for(int i = 0; i < size(); i++) + delete list[i]; + clear(); + } + + + /* + Function: clear + + Remarks: + - Invalidates ranges + */ + void clear() + { + ALLOCATOR::free_array(list); + list_size = 1; + list = ALLOCATOR::alloc_array(list_size); + num_elements = 0; + } + + /* + Function: size + */ + int size() const + { + return num_elements; + } + + /* + Function: remove_index_fast + + Remarks: + - Invalidates ranges + */ + void remove_index_fast(int index) + { + list[index] = list[num_elements-1]; + set_size(size()-1); + } + + /* + Function: remove_fast + + Remarks: + - Invalidates ranges + */ + void remove_fast(const T& item) + { + for(int i = 0; i < size(); i++) + if(list[i] == item) + { + remove_index_fast(i); + return; + } + } + + /* + Function: remove_index + + Remarks: + - Invalidates ranges + */ + void remove_index(int index) + { + for(int i = index+1; i < num_elements; i++) + list[i-1] = list[i]; + + set_size(size()-1); + } + + /* + Function: remove + + Remarks: + - Invalidates ranges + */ + bool remove(const T& item) + { + for(int i = 0; i < size(); i++) + if(list[i] == item) + { + remove_index(i); + return true; + } + return false; + } + + /* + Function: add + Adds an item to the array. + + Arguments: + item - Item to add. + + Remarks: + - Invalidates ranges + - See remarks about <array> how the array grows. + */ + int add(const T& item) + { + incsize(); + set_size(size()+1); + list[num_elements-1] = item; + return num_elements-1; + } + + /* + Function: insert + Inserts an item into the array at a specified location. + + Arguments: + item - Item to insert. + r - Range where to insert the item + + Remarks: + - Invalidates ranges + - See remarks about <array> how the array grows. + */ + int insert(const T& item, range r) + { + 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; + } + + /* + Function: operator[] + */ + T& operator[] (int index) + { + return list[index]; + } + + /* + Function: const operator[] + */ + const T& operator[] (int index) const + { + return list[index]; + } + + /* + Function: base_ptr + */ + T *base_ptr() + { + return list; + } + + /* + Function: base_ptr + */ + const T *base_ptr() const + { + return list; + } + + /* + Function: set_size + Resizes the array to the specified size. + + Arguments: + new_size - The new size for the array. + */ + void set_size(int new_size) + { + if(list_size < new_size) + alloc(new_size); + num_elements = new_size; + } + + /* + 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 + */ + void hint_size(int hint) + { + if(num_elements < hint) + alloc(hint); + } + + + /* + Function: optimize + Removes unnessasary data, returns how many bytes was earned. + + Remarks: + - Invalidates ranges + */ + int optimize() + { + int before = memusage(); + alloc(num_elements); + return before - memusage(); + } + + /* + Function: memusage + Returns how much memory this dynamic array is using + */ + int memusage() + { + return sizeof(array) + sizeof(T)*list_size; + } + + /* + Function: operator=(array) + + Remarks: + - Invalidates ranges + */ + array &operator = (const array &other) + { + set_size(other.size()); + for(int i = 0; i < size(); i++) + (*this)[i] = other[i]; + return *this; + } + + /* + Function: all + Returns a range that contains the whole array. + */ + range all() { return range(list, list+num_elements); } +protected: + + void incsize() + { + if(num_elements == list_size) + { + if(list_size < 2) + 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; + list = new_list; + } + + T *list; + int list_size; + int num_elements; +}; + +#endif // TL_FILE_ARRAY_HPP diff --git a/src/base/tl/base.h b/src/base/tl/base.h new file mode 100644 index 0000000..ce77db8 --- /dev/null +++ b/src/base/tl/base.h @@ -0,0 +1,21 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_BASE_H +#define BASE_TL_BASE_H + +#include <base/system.h> + +inline void tl_assert(bool statement) +{ + dbg_assert(statement, "assert!"); +} + +template<class T> +inline void swap(T &a, T &b) +{ + T c = b; + b = a; + a = c; +} + +#endif diff --git a/src/base/tl/range.h b/src/base/tl/range.h new file mode 100644 index 0000000..8f8f23c --- /dev/null +++ b/src/base/tl/range.h @@ -0,0 +1,234 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_RANGE_H +#define BASE_TL_RANGE_H + +#include "base/tl/base.h" + +/* + Group: Range concepts +*/ + +/* + Concept: concept_empty + + template<class T> + struct range + { + bool empty() const; + }; +*/ +struct concept_empty +{ + template<typename T> static void check(T &t) { if(0) t.empty(); }; +}; + +/* + Concept: concept_index + + template<class T> + struct range + { + T &index(size_t); + }; +*/ +struct concept_index +{ + template<typename T> static void check(T &t) { if(0) t.index(0); }; +}; + +/* + Concept: concept_size + + template<class T> + struct range + { + size_t size(); + }; +*/ +struct concept_size +{ + template<typename T> static void check(T &t) { if(0) t.size(); }; +}; + +/* + Concept: concept_slice + + template<class T> + struct range + { + range slice(size_t start, size_t count); + }; +*/ +struct concept_slice +{ + template<typename T> static void check(T &t) { if(0) t.slice(0, 0); }; +}; + +/* + Concept: concept_sorted + + template<class T> + struct range + { + void sorted(); + }; +*/ +struct concept_sorted +{ + template<typename T> static void check(T &t) { if(0) t.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 +{ + template<typename T> static void check(T &t) { if(0) { t.front(); t.pop_front(); } }; +}; + +/* + 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 +{ + template<typename T> static void check(T &t) { if(0) { t.back(); t.pop_back(); } }; +}; + + +/* + Group: Range classes +*/ + + +/* + Class: plain_range + + Concepts: + <concept_empty> + <concept_index> + <concept_slice> + <concept_forwardinteration> + <concept_backwardinteration> +*/ +template<class T> +class plain_range +{ +public: + typedef T type; + plain_range() + { + begin = 0x0; + end = 0x0; + } + + plain_range(const plain_range &r) + { + *this = r; + } + + plain_range(T *b, T *e) + { + begin = b; + end = e; + } + + bool empty() const { return begin >= end; } + void pop_front() { tl_assert(!empty()); begin++; } + void pop_back() { tl_assert(!empty()); end--; } + T& front() { tl_assert(!empty()); return *begin; } + T& back() { tl_assert(!empty()); return *(end-1); } + T& index(unsigned i) { tl_assert(i < (unsigned)(end-begin)); return begin[i]; } + unsigned size() const { return (unsigned)(end-begin); } + plain_range slice(unsigned startindex, unsigned endindex) + { + return plain_range(begin+startindex, begin+endindex); + } + +protected: + T *begin; + T *end; +}; + +/* + Class: plain_range_sorted + + Concepts: + Same as <plain_range> but with these additions: + <concept_sorted> +*/ +template<class T> +class plain_range_sorted : public plain_range<T> +{ + typedef plain_range<T> parent; +public: + /* sorted concept */ + void sorted() const { } + + plain_range_sorted() + {} + + plain_range_sorted(const plain_range_sorted &r) + { + *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); + } +}; + +template<class R> +class reverse_range +{ +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); +} +template<class R> R reverse(reverse_range<R> 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 new file mode 100644 index 0000000..1bc77e8 --- /dev/null +++ b/src/base/tl/sorted_array.h @@ -0,0 +1,44 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_SORTED_ARRAY_H +#define BASE_TL_SORTED_ARRAY_H + +#include "base/tl/algorithm.h" +#include "base/tl/array.h" + +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; + + int add(const T& item) + { + return parent::insert(item, partition_binary(all(), item)); + } + + int add_unsorted(const T& item) + { + return parent::add(item); + } + + void sort_range() + { + sort(all()); + } + + + /* + Function: all + Returns a sorted range that contains the whole array. + */ + range all() { return range(parent::list, parent::list+parent::num_elements); } +}; + +#endif // TL_FILE_SORTED_ARRAY_HPP diff --git a/src/base/tl/string.h b/src/base/tl/string.h new file mode 100644 index 0000000..d93f758 --- /dev/null +++ b/src/base/tl/string.h @@ -0,0 +1,70 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_TL_STRING_H +#define BASE_TL_STRING_H + +#include "base/tl/base.h" +#include "base/tl/allocator.h" + +template<class ALLOCATOR > +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(); + if(other) + 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; } +}; + +/* normal allocated string */ +typedef string_base<allocator_default<char> > string; + +#endif // TL_FILE_STRING_HPP diff --git a/src/base/tl/threading.h b/src/base/tl/threading.h new file mode 100644 index 0000000..7acb2c0 --- /dev/null +++ b/src/base/tl/threading.h @@ -0,0 +1,115 @@ + +#pragma once + +#include "../system.h" + +/* + atomic_inc - should return the value after increment + atomic_dec - should return the value after decrement + atomic_compswap - should return the value before the eventual swap + sync_barrier - creates a full hardware fence +*/ + +#if defined(__GNUC__) + + inline unsigned atomic_inc(volatile unsigned *pValue) + { + return __sync_add_and_fetch(pValue, 1); + } + + inline unsigned atomic_dec(volatile unsigned *pValue) + { + return __sync_add_and_fetch(pValue, -1); + } + + inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) + { + return __sync_val_compare_and_swap(pValue, comperand, value); + } + + inline void sync_barrier() + { + __sync_synchronize(); + } + +#elif defined(_MSC_VER) + #include <intrin.h> + + #define WIN32_LEAN_AND_MEAN + #include <windows.h> + + inline unsigned atomic_inc(volatile unsigned *pValue) + { + return _InterlockedIncrement((volatile long *)pValue); + } + + inline unsigned atomic_dec(volatile unsigned *pValue) + { + return _InterlockedDecrement((volatile long *)pValue); + } + + inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) + { + return _InterlockedCompareExchange((volatile long *)pValue, (long)value, (long)comperand); + } + + inline void sync_barrier() + { + MemoryBarrier(); + } +#else + #error missing atomic implementation for this compiler +#endif + +#if defined(CONF_PLATFORM_MACOSX) + /* + use semaphore provided by SDL on macosx + */ +#else + class semaphore + { + SEMAPHORE sem; + public: + semaphore() { semaphore_init(&sem); } + ~semaphore() { semaphore_destroy(&sem); } + void wait() { semaphore_wait(&sem); } + void signal() { semaphore_signal(&sem); } + }; +#endif + +class lock +{ + friend class scope_lock; + + LOCK var; + + void take() { lock_wait(var); } + void release() { lock_unlock(var); } + +public: + lock() + { + var = lock_create(); + } + + ~lock() + { + lock_destroy(var); + } +}; + +class scope_lock +{ + lock *var; +public: + scope_lock(lock *l) + { + var = l; + var->take(); + } + + ~scope_lock() + { + var->release(); + } +}; diff --git a/src/base/vmath.h b/src/base/vmath.h new file mode 100644 index 0000000..0880a25 --- /dev/null +++ b/src/base/vmath.h @@ -0,0 +1,215 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef BASE_VMATH_H +#define BASE_VMATH_H + +#include <math.h> + +// ------------------------------------ + +template<typename T> +class vector2_base +{ +public: + union { T x,u; }; + union { T y,v; }; + + vector2_base() {} + vector2_base(T nx, T 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); } + 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 vector3_base(x/v, y/v); } + vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); } + + 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; } + const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; } + const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this; } + const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; } + const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this; } + const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; } + + bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead + bool operator !=(const vector2_base &v) const { return x != v.x || y != v.y; } + + operator const T* () { return &x; } +}; + + +template<typename T> +inline T length(const vector2_base<T> &a) +{ + return sqrtf(a.x*a.x + a.y*a.y); +} + +template<typename T> +inline T distance(const vector2_base<T> a, const vector2_base<T> &b) +{ + return length(a-b); +} + +template<typename T> +inline T dot(const vector2_base<T> a, const vector2_base<T> &b) +{ + return a.x*b.x + a.y*b.y; +} + +template<typename T> +inline vector2_base<T> normalize(const vector2_base<T> &v) +{ + T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y)); + return vector2_base<T>(v.x*l, v.y*l); +} + +typedef vector2_base<float> vec2; +typedef vector2_base<bool> bvec2; +typedef vector2_base<int> ivec2; + +template<typename T> +inline vector2_base<T> closest_point_on_line(vector2_base<T> line_point0, vector2_base<T> line_point1, vector2_base<T> target_point) +{ + vector2_base<T> c = target_point - line_point0; + vector2_base<T> v = (line_point1 - line_point0); + v = normalize(v); + T d = length(line_point0-line_point1); + T t = dot(v, c)/d; + return mix(line_point0, line_point1, clamp(t, (T)0, (T)1)); + /* + if (t < 0) t = 0; + if (t > 1.0f) return 1.0f; + return t;*/ +} + +// ------------------------------------ +template<typename T> +class vector3_base +{ +public: + union { T x,r,h; }; + union { T y,g,s; }; + union { T z,b,v,l; }; + + vector3_base() {} + vector3_base(T nx, T ny, T nz) + { + x = nx; + 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); } + vector3_base operator -() const { return vector3_base(-x, -y, -z); } + 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); } + 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); } + vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); } + + 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; } + 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; } + const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } + + bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead + + operator const T* () { return &x; } +}; + +template<typename T> +inline T length(const vector3_base<T> &a) +{ + return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z); +} + +template<typename T> +inline T distance(const vector3_base<T> &a, const vector3_base<T> &b) +{ + return length(a-b); +} + +template<typename T> +inline T dot(const vector3_base<T> &a, const vector3_base<T> &b) +{ + return a.x*b.x + a.y*b.y + a.z*b.z; +} + +template<typename T> +inline vector3_base<T> normalize(const vector3_base<T> &v) +{ + T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y + v.z*v.z)); + return vector3_base<T>(v.x*l, v.y*l, v.z*l); +} + +template<typename T> +inline vector3_base<T> cross(const vector3_base<T> &a, const vector3_base<T> &b) +{ + return vector3_base<T>( + a.y*b.z - a.z*b.y, + a.z*b.x - a.x*b.z, + a.x*b.y - a.y*b.x); +} + +typedef vector3_base<float> vec3; +typedef vector3_base<bool> bvec3; +typedef vector3_base<int> ivec3; + +// ------------------------------------ + +template<typename T> +class vector4_base +{ +public: + union { T x,r; }; + union { T y,g; }; + union { T z,b; }; + union { T w,a; }; + + vector4_base() {} + vector4_base(T nx, T ny, T nz, T nw) + { + x = nx; + y = ny; + 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); } + 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; } + 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 T v) { x *= v; y *= v; z *= v; w *= v; return *this; } + 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 T v) { x /= v; y /= v; z /= v; w /= v; return *this; } + const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } + + bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead + + operator const T* () { return &x; } +}; + +typedef vector4_base<float> vec4; +typedef vector4_base<bool> bvec4; +typedef vector4_base<int> ivec4; + +#endif diff --git a/src/engine/client.h b/src/engine/client.h new file mode 100644 index 0000000..1b9bfb2 --- /dev/null +++ b/src/engine/client.h @@ -0,0 +1,223 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_H +#define ENGINE_CLIENT_H +#include "kernel.h" + +#include "message.h" +#include <engine/friends.h> +#include <engine/shared/config.h> +#include <versionsrv/versionsrv.h> +#include <game/generated/protocol.h> + +enum +{ + RECORDER_MANUAL=0, + RECORDER_AUTO=1, + RECORDER_RACE=2, + RECORDER_MAX=3, +}; + +class IClient : public IInterface +{ + MACRO_INTERFACE("client", 0) +protected: + // quick access to state of the client + int m_State; + + // quick access to time variables + int m_PrevGameTick[2]; + int m_CurGameTick[2]; + float m_GameIntraTick[2]; + float m_GameTickTime[2]; + + int m_PredTick[2]; + float m_PredIntraTick[2]; + + float m_LocalTime; + float m_RenderFrameTime; + + int m_GameTickSpeed; +public: + int m_LocalIDs[2]; + char m_aNews[NEWS_SIZE]; + + CNetObj_PlayerInput m_DummyInput; + + bool m_DummySendConnInfo; + + class CSnapItem + { + public: + int m_Type; + int m_ID; + int m_DataSize; + }; + + /* Constants: Client States + STATE_OFFLINE - The client is offline. + STATE_CONNECTING - The client is trying to connect to a server. + STATE_LOADING - The client has connected to a server and is loading resources. + STATE_ONLINE - The client is connected to a server and running the game. + STATE_DEMOPLAYBACK - The client is playing a demo + STATE_QUITING - The client is quiting. + */ + + enum + { + STATE_OFFLINE=0, + STATE_CONNECTING, + STATE_LOADING, + STATE_ONLINE, + STATE_DEMOPLAYBACK, + STATE_QUITING, + }; + + // + inline int State() const { return m_State; } + + // tick time access + inline int PrevGameTick() const { return m_PrevGameTick[g_Config.m_ClDummy]; } + inline int GameTick() const { return m_CurGameTick[g_Config.m_ClDummy]; } + inline int PredGameTick() const { return m_PredTick[g_Config.m_ClDummy]; } + inline float IntraGameTick() const { return m_GameIntraTick[g_Config.m_ClDummy]; } + inline float PredIntraGameTick() const { return m_PredIntraTick[g_Config.m_ClDummy]; } + inline float GameTickTime() const { return m_GameTickTime[g_Config.m_ClDummy]; } + inline int GameTickSpeed() const { return m_GameTickSpeed; } + + // other time access + inline float RenderFrameTime() const { return m_RenderFrameTime; } + inline float LocalTime() const { return m_LocalTime; } + + // actions + virtual void Connect(const char *pAddress) = 0; + virtual void Disconnect() = 0; + + // dummy + virtual void DummyDisconnect(const char *pReason) = 0; + virtual void DummyConnect() = 0; + virtual bool DummyConnected() = 0; + virtual bool DummyConnecting() = 0; + + virtual void Restart() = 0; + virtual void Quit() = 0; + virtual const char *DemoPlayer_Play(const char *pFilename, int StorageType) = 0; + virtual void DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder) = 0; + virtual void DemoRecorder_HandleAutoStart() = 0; + virtual void DemoRecorder_Stop(int Recorder) = 0; + virtual class IDemoRecorder *DemoRecorder(int Recorder) = 0; + virtual void AutoScreenshot_Start() = 0; + virtual void AutoStatScreenshot_Start() = 0; + virtual void ServerBrowserUpdate() = 0; + + // networking + virtual void EnterGame() = 0; + + // + virtual const char *MapDownloadName() = 0; + virtual int MapDownloadAmount() = 0; + virtual int MapDownloadTotalsize() = 0; + + // input + virtual int *GetInput(int Tick) = 0; + virtual bool InputExists(int Tick) = 0; + + // remote console + virtual void RconAuth(const char *pUsername, const char *pPassword) = 0; + virtual bool RconAuthed() = 0; + virtual bool UseTempRconCommands() = 0; + virtual void Rcon(const char *pLine) = 0; + + // server info + virtual void GetServerInfo(class CServerInfo *pServerInfo) = 0; + + virtual void CheckVersionUpdate() = 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; + virtual void *SnapGetItem(int SnapID, int Index, CSnapItem *pItem) = 0; + virtual void SnapInvalidateItem(int SnapID, int Index) = 0; + + virtual void SnapSetStaticsize(int ItemType, int Size) = 0; + + virtual int SendMsg(CMsgPacker *pMsg, int Flags) = 0; + virtual int SendMsgExY(CMsgPacker *pMsg, int Flags, bool System=true, int NetClient=1) = 0; + + template<class T> + int SendPackMsg(T *pMsg, int Flags) + { + CMsgPacker Packer(pMsg->MsgID()); + if(pMsg->Pack(&Packer)) + return -1; + return SendMsg(&Packer, Flags); + } + + // + virtual const char *ErrorString() = 0; + virtual const char *LatestVersion() = 0; + virtual bool ConnectionProblems() = 0; + + virtual bool SoundInitFailed() = 0; + + virtual int GetDebugFont() = 0; + + //DDRace + + virtual const char* GetCurrentMap() = 0; + virtual int GetCurrentMapCrc() = 0; + virtual const char* RaceRecordStart(const char *pFilename) = 0; + virtual void RaceRecordStop() = 0; + virtual bool RaceRecordIsRecording() = 0; + + virtual void DemoSliceBegin() = 0; + virtual void DemoSliceEnd() = 0; + virtual void DemoSlice(const char *pDstPath) = 0; + + virtual void RequestDDNetSrvList() = 0; + virtual bool EditorHasUnsavedData() = 0; + + virtual IFriends* Foes() = 0; +}; + +class IGameClient : public IInterface +{ + MACRO_INTERFACE("gameclient", 0) +protected: +public: + virtual void OnConsoleInit() = 0; + + virtual void OnRconLine(const char *pLine) = 0; + virtual void OnInit() = 0; + virtual void OnNewSnapshot() = 0; + virtual void OnEnterGame() = 0; + virtual void OnShutdown() = 0; + virtual void OnRender() = 0; + virtual void OnStateChange(int NewState, int OldState) = 0; + virtual void OnConnected() = 0; + virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, bool IsDummy = 0) = 0; + virtual void OnPredict() = 0; + virtual void OnActivateEditor() = 0; + + virtual int OnSnapInput(int *pData) = 0; + virtual void SendDummyInfo(bool Start) = 0; + virtual void ResetDummyInput() = 0; + virtual const CNetObj_PlayerInput &getPlayerInput(int dummy) = 0; + + virtual const char *GetItemName(int Type) = 0; + virtual const char *Version() = 0; + virtual const char *NetVersion() = 0; + + virtual void OnDummyDisconnect() = 0; +}; + +extern IGameClient *CreateGameClient(); +#endif diff --git a/src/engine/client/backend_sdl.cpp b/src/engine/client/backend_sdl.cpp new file mode 100644 index 0000000..8c7cdd9 --- /dev/null +++ b/src/engine/client/backend_sdl.cpp @@ -0,0 +1,717 @@ +#include <base/detect.h> + +#if defined(CONF_FAMILY_WINDOWS) + // For FlashWindowEx, FLASHWINFO, FLASHW_TRAY + #define _WIN32_WINNT 0x0501 + #define WINVER 0x0501 +#endif + +#include "SDL.h" +#include "SDL_syswm.h" +#if defined(__ANDROID__) + #define GL_GLEXT_PROTOTYPES + #include <GLES/gl.h> + #include <GLES/glext.h> + #include <GL/glu.h> + #define glOrtho glOrthof + #include <SDL_android.h> +#else + #include "SDL_opengl.h" +#endif + +#if defined(SDL_VIDEO_DRIVER_X11) + #include <X11/Xutil.h> + #include <X11/Xlib.h> +#endif + +#include <engine/shared/config.h> +#include <base/tl/threading.h> + +#include "graphics_threaded.h" +#include "backend_sdl.h" + +// ------------ CGraphicsBackend_Threaded + +void CGraphicsBackend_Threaded::ThreadFunc(void *pUser) +{ + #ifdef CONF_PLATFORM_MACOSX + CAutoreleasePool AutoreleasePool; + #endif + CGraphicsBackend_Threaded *pThis = (CGraphicsBackend_Threaded *)pUser; + + while(!pThis->m_Shutdown) + { + pThis->m_Activity.wait(); + if(pThis->m_pBuffer) + { + pThis->m_pProcessor->RunBuffer(pThis->m_pBuffer); + sync_barrier(); + pThis->m_pBuffer = 0x0; + pThis->m_BufferDone.signal(); + } + } +} + +CGraphicsBackend_Threaded::CGraphicsBackend_Threaded() +{ + m_pBuffer = 0x0; + m_pProcessor = 0x0; + m_pThread = 0x0; +} + +void CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor) +{ + m_Shutdown = false; + m_pProcessor = pProcessor; + m_pThread = thread_init(ThreadFunc, this); + m_BufferDone.signal(); +} + +void CGraphicsBackend_Threaded::StopProcessor() +{ + m_Shutdown = true; + m_Activity.signal(); + thread_wait(m_pThread); + thread_destroy(m_pThread); +} + +void CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer) +{ + WaitForIdle(); + m_pBuffer = pBuffer; + m_Activity.signal(); +} + +bool CGraphicsBackend_Threaded::IsIdle() const +{ + return m_pBuffer == 0x0; +} + +void CGraphicsBackend_Threaded::WaitForIdle() +{ + while(m_pBuffer != 0x0) + m_BufferDone.wait(); +} + + +// ------------ CCommandProcessorFragment_General + +void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand) +{ + pCommand->m_pSemaphore->signal(); +} + +bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand * pBaseCommand) +{ + switch(pBaseCommand->m_Cmd) + { + case CCommandBuffer::CMD_NOP: break; + case CCommandBuffer::CMD_SIGNAL: Cmd_Signal(static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break; + default: return false; + } + + return true; +} + +// ------------ CCommandProcessorFragment_OpenGL + +int CCommandProcessorFragment_OpenGL::TexFormatToOpenGLFormat(int TexFormat) +{ + if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB; + if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_ALPHA; + if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA; + return GL_RGBA; +} + +unsigned char CCommandProcessorFragment_OpenGL::Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp) +{ + int Value = 0; + for(int x = 0; x < ScaleW; x++) + for(int y = 0; y < ScaleH; y++) + Value += pData[((v+y)*w+(u+x))*Bpp+Offset]; + return Value/(ScaleW*ScaleH); +} + +void *CCommandProcessorFragment_OpenGL::Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData) +{ + unsigned char *pTmpData; + int ScaleW = Width/NewWidth; + int ScaleH = Height/NewHeight; + + int Bpp = 3; + if(Format == CCommandBuffer::TEXFORMAT_RGBA) + Bpp = 4; + + pTmpData = (unsigned char *)mem_alloc(NewWidth*NewHeight*Bpp, 1); + + int c = 0; + for(int y = 0; y < NewHeight; y++) + for(int x = 0; x < NewWidth; x++, c++) + { + pTmpData[c*Bpp] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 0, ScaleW, ScaleH, Bpp); + pTmpData[c*Bpp+1] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 1, ScaleW, ScaleH, Bpp); + pTmpData[c*Bpp+2] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 2, ScaleW, ScaleH, Bpp); + if(Bpp == 4) + pTmpData[c*Bpp+3] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 3, ScaleW, ScaleH, Bpp); + } + + return pTmpData; +} + +void CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &State) +{ + // blend + switch(State.m_BlendMode) + { + case CCommandBuffer::BLEND_NONE: + glDisable(GL_BLEND); + break; + case CCommandBuffer::BLEND_ALPHA: + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + break; + case CCommandBuffer::BLEND_ADDITIVE: + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + break; + default: + dbg_msg("render", "unknown blendmode %d\n", State.m_BlendMode); + }; + + // clip + if(State.m_ClipEnable) + { + glScissor(State.m_ClipX, State.m_ClipY, State.m_ClipW, State.m_ClipH); + glEnable(GL_SCISSOR_TEST); + } + else + glDisable(GL_SCISSOR_TEST); + + // texture + if(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES) + { + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, m_aTextures[State.m_Texture].m_Tex); + } + else + glDisable(GL_TEXTURE_2D); + + switch(State.m_WrapMode) + { + case CCommandBuffer::WRAP_REPEAT: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + break; + case CCommandBuffer::WRAP_CLAMP: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + break; + default: + dbg_msg("render", "unknown wrapmode %d\n", State.m_WrapMode); + }; + + // screen mapping + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(State.m_ScreenTL.x, State.m_ScreenBR.x, State.m_ScreenBR.y, State.m_ScreenTL.y, 1.0f, 10.f); +} + +void CCommandProcessorFragment_OpenGL::Cmd_Init(const SCommand_Init *pCommand) +{ + m_pTextureMemoryUsage = pCommand->m_pTextureMemoryUsage; +} + +void CCommandProcessorFragment_OpenGL::Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand) +{ + glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); + glTexSubImage2D(GL_TEXTURE_2D, 0, pCommand->m_X, pCommand->m_Y, pCommand->m_Width, pCommand->m_Height, + TexFormatToOpenGLFormat(pCommand->m_Format), GL_UNSIGNED_BYTE, pCommand->m_pData); + mem_free(pCommand->m_pData); +} + +void CCommandProcessorFragment_OpenGL::Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand) +{ + glDeleteTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); + *m_pTextureMemoryUsage -= m_aTextures[pCommand->m_Slot].m_MemSize; +} + +void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand) +{ + int Width = pCommand->m_Width; + int Height = pCommand->m_Height; + void *pTexData = pCommand->m_pData; + + // resample if needed + if(pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGBA || pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGB) + { + int MaxTexSize; + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxTexSize); + if(Width > MaxTexSize || Height > MaxTexSize) + { + do + { + Width>>=1; + Height>>=1; + } + while(Width > MaxTexSize || Height > MaxTexSize); + + void *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData)); + mem_free(pTexData); + pTexData = pTmpData; + } + else if(Width > 16 && Height > 16 && (pCommand->m_Flags&CCommandBuffer::TEXFLAG_QUALITY) == 0) + { + Width>>=1; + Height>>=1; + + void *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData)); + mem_free(pTexData); + pTexData = pTmpData; + } + } + + int Oglformat = TexFormatToOpenGLFormat(pCommand->m_Format); + int StoreOglformat = TexFormatToOpenGLFormat(pCommand->m_StoreFormat); + +#if defined(__ANDROID__) + StoreOglformat = Oglformat; +#else + if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_COMPRESSED) + { + switch(StoreOglformat) + { + case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB_ARB; break; + case GL_ALPHA: StoreOglformat = GL_COMPRESSED_ALPHA_ARB; break; + case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA_ARB; break; + default: StoreOglformat = GL_COMPRESSED_RGBA_ARB; + } + } +#endif + glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); + glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); + + if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, Width, Height, 0, Oglformat, GL_UNSIGNED_BYTE, pTexData); + } + else + { + 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 + m_aTextures[pCommand->m_Slot].m_MemSize = Width*Height*pCommand->m_PixelSize; + while(Width > 2 && Height > 2) + { + Width>>=1; + Height>>=1; + m_aTextures[pCommand->m_Slot].m_MemSize += Width*Height*pCommand->m_PixelSize; + } + *m_pTextureMemoryUsage += m_aTextures[pCommand->m_Slot].m_MemSize; + + mem_free(pTexData); +} + +void CCommandProcessorFragment_OpenGL::Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand) +{ + glClearColor(pCommand->m_Color.r, pCommand->m_Color.g, pCommand->m_Color.b, 0.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand) +{ + SetState(pCommand->m_State); + + glVertexPointer(3, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices); + glTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*3); + glColorPointer(4, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*5); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + + switch(pCommand->m_PrimType) + { + case CCommandBuffer::PRIMTYPE_QUADS: +#if defined(__ANDROID__) + for( unsigned i = 0, j = pCommand->m_PrimCount; i < j; i++ ) + glDrawArrays(GL_TRIANGLE_FAN, i*4, 4); +#else + glDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount*4); +#endif + break; + case CCommandBuffer::PRIMTYPE_LINES: + glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2); + break; + case CCommandBuffer::PRIMTYPE_TRIANGLES: + glDrawArrays(GL_TRIANGLES, 0, pCommand->m_PrimCount*3); + break; + default: + dbg_msg("render", "unknown primtype %d\n", pCommand->m_Cmd); + }; +} + +void CCommandProcessorFragment_OpenGL::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand) +{ + // fetch image data + GLint aViewport[4] = {0,0,0,0}; + glGetIntegerv(GL_VIEWPORT, aViewport); + + int w = aViewport[2]; + int h = aViewport[3]; + + // we allocate one more row to use when we are flipping the texture + unsigned char *pPixelData = (unsigned char *)mem_alloc(w*(h+1)*3, 1); + unsigned char *pTempRow = pPixelData+w*h*3; + + // fetch the pixels + GLint Alignment; + glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment); + 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(int y = 0; y < h/2; y++) + { + mem_copy(pTempRow, pPixelData+y*w*3, w*3); + 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); + } + + // fill in the information + pCommand->m_pImage->m_Width = w; + pCommand->m_pImage->m_Height = h; + pCommand->m_pImage->m_Format = CImageInfo::FORMAT_RGB; + pCommand->m_pImage->m_pData = pPixelData; +} + +CCommandProcessorFragment_OpenGL::CCommandProcessorFragment_OpenGL() +{ + mem_zero(m_aTextures, sizeof(m_aTextures)); + m_pTextureMemoryUsage = 0; +} + +bool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand * pBaseCommand) +{ + switch(pBaseCommand->m_Cmd) + { + case CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break; + case CCommandBuffer::CMD_TEXTURE_CREATE: Cmd_Texture_Create(static_cast<const CCommandBuffer::SCommand_Texture_Create *>(pBaseCommand)); break; + case CCommandBuffer::CMD_TEXTURE_DESTROY: Cmd_Texture_Destroy(static_cast<const CCommandBuffer::SCommand_Texture_Destroy *>(pBaseCommand)); break; + case CCommandBuffer::CMD_TEXTURE_UPDATE: Cmd_Texture_Update(static_cast<const CCommandBuffer::SCommand_Texture_Update *>(pBaseCommand)); break; + case CCommandBuffer::CMD_CLEAR: Cmd_Clear(static_cast<const CCommandBuffer::SCommand_Clear *>(pBaseCommand)); break; + case CCommandBuffer::CMD_RENDER: Cmd_Render(static_cast<const CCommandBuffer::SCommand_Render *>(pBaseCommand)); break; + case CCommandBuffer::CMD_SCREENSHOT: Cmd_Screenshot(static_cast<const CCommandBuffer::SCommand_Screenshot *>(pBaseCommand)); break; + default: return false; + } + + return true; +} + + +// ------------ CCommandProcessorFragment_SDL + +void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand) +{ + m_GLContext = pCommand->m_Context; + GL_MakeCurrent(m_GLContext); + + // set some default settings + glEnable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glAlphaFunc(GL_GREATER, 0); + glEnable(GL_ALPHA_TEST); + glDepthMask(0); +} + +void CCommandProcessorFragment_SDL::Cmd_Shutdown(const SCommand_Shutdown *pCommand) +{ + GL_ReleaseContext(m_GLContext); +} + +void CCommandProcessorFragment_SDL::Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand) +{ + GL_SwapBuffers(m_GLContext); + + if(pCommand->m_Finish) + glFinish(); +} + +void CCommandProcessorFragment_SDL::Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand) +{ + // TODO: fix this code on osx or windows + SDL_Rect **ppModes = SDL_ListModes(NULL, SDL_OPENGL|SDL_GL_DOUBLEBUFFER|SDL_FULLSCREEN); + if(ppModes == NULL) + { + // no modes + *pCommand->m_pNumModes = 0; + } + else if(ppModes == (SDL_Rect**)-1) + { + // no modes + *pCommand->m_pNumModes = 0; + } + else + { + int NumModes = 0; + for(int i = 0; ppModes[i]; ++i) + { + if(NumModes == pCommand->m_MaxModes) + break; + pCommand->m_pModes[NumModes].m_Width = ppModes[i]->w; + pCommand->m_pModes[NumModes].m_Height = ppModes[i]->h; + pCommand->m_pModes[NumModes].m_Red = 8; + pCommand->m_pModes[NumModes].m_Green = 8; + pCommand->m_pModes[NumModes].m_Blue = 8; + NumModes++; + } + + *pCommand->m_pNumModes = NumModes; + } +} + +CCommandProcessorFragment_SDL::CCommandProcessorFragment_SDL() +{ +} + +bool CCommandProcessorFragment_SDL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) +{ + switch(pBaseCommand->m_Cmd) + { + case CCommandBuffer::CMD_SWAP: Cmd_Swap(static_cast<const CCommandBuffer::SCommand_Swap *>(pBaseCommand)); break; + case CCommandBuffer::CMD_VIDEOMODES: Cmd_VideoModes(static_cast<const CCommandBuffer::SCommand_VideoModes *>(pBaseCommand)); break; + case CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break; + case CMD_SHUTDOWN: Cmd_Shutdown(static_cast<const SCommand_Shutdown *>(pBaseCommand)); break; + default: return false; + } + + return true; +} + +// ------------ CCommandProcessor_SDL_OpenGL + +void CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer) +{ + unsigned CmdIndex = 0; + while(1) + { + const CCommandBuffer::SCommand *pBaseCommand = pBuffer->GetCommand(&CmdIndex); + if(pBaseCommand == 0x0) + break; + + if(m_OpenGL.RunCommand(pBaseCommand)) + continue; + + if(m_SDL.RunCommand(pBaseCommand)) + continue; + + if(m_General.RunCommand(pBaseCommand)) + continue; + + dbg_msg("graphics", "unknown command %d", pBaseCommand->m_Cmd); + } +} + +// ------------ CGraphicsBackend_SDL_OpenGL + +int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags) +{ + if(!SDL_WasInit(SDL_INIT_VIDEO)) + { + if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) + { + dbg_msg("gfx", "unable to init SDL video: %s", SDL_GetError()); + return -1; + } + + #ifdef CONF_FAMILY_WINDOWS + if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention + putenv("SDL_VIDEO_WINDOW_POS=center"); // ignore_convention + #endif + } + + const SDL_VideoInfo *pInfo = SDL_GetVideoInfo(); + SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows + + // use current resolution as default +#ifndef __ANDROID__ + if(*Width == 0 || *Height == 0) +#endif + { + *Width = pInfo->current_w; + *Height = pInfo->current_h; + } + + + + // set flags + int SdlFlags = SDL_OPENGL; + if(Flags&IGraphicsBackend::INITFLAG_RESIZABLE) + SdlFlags |= SDL_RESIZABLE; + + if(pInfo->hw_available) // ignore_convention + SdlFlags |= SDL_HWSURFACE; + else + SdlFlags |= SDL_SWSURFACE; + + if(pInfo->blit_hw) // ignore_convention + SdlFlags |= SDL_HWACCEL; + + dbg_assert(!(Flags&IGraphicsBackend::INITFLAG_BORDERLESS) + || !(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN), + "only one of borderless and fullscreen may be activated at the same time"); + + if(Flags&IGraphicsBackend::INITFLAG_BORDERLESS) + SdlFlags |= SDL_NOFRAME; + + if(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN) + SdlFlags |= SDL_FULLSCREEN; + + // set gl attributes + if(FsaaSamples) + { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, FsaaSamples); + } + else + { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); + } + + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, Flags&IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0); + + // set caption + SDL_WM_SetCaption(pName, pName); + + // create window + m_pScreenSurface = SDL_SetVideoMode(*Width, *Height, 0, SdlFlags); + if(!m_pScreenSurface) + { + dbg_msg("gfx", "unable to set video mode: %s", SDL_GetError()); + //*pCommand->m_pResult = -1; + return -1; + } + + SDL_ShowCursor(0); + + // fetch gl contexts and release the context from this thread + m_GLContext = GL_GetCurrentContext(); + GL_ReleaseContext(m_GLContext); + + // start the command processor + m_pProcessor = new CCommandProcessor_SDL_OpenGL; + StartProcessor(m_pProcessor); + + // issue init commands for OpenGL and SDL + CCommandBuffer CmdBuffer(1024, 512); + CCommandProcessorFragment_OpenGL::SCommand_Init CmdOpenGL; + CmdOpenGL.m_pTextureMemoryUsage = &m_TextureMemoryUsage; + CmdBuffer.AddCommand(CmdOpenGL); + CCommandProcessorFragment_SDL::SCommand_Init CmdSDL; + CmdSDL.m_Context = m_GLContext; + CmdBuffer.AddCommand(CmdSDL); + RunBuffer(&CmdBuffer); + WaitForIdle(); + + // return + return 0; +} + +int CGraphicsBackend_SDL_OpenGL::Shutdown() +{ + // issue a shutdown command + CCommandBuffer CmdBuffer(1024, 512); + CCommandProcessorFragment_SDL::SCommand_Shutdown Cmd; + CmdBuffer.AddCommand(Cmd); + RunBuffer(&CmdBuffer); + WaitForIdle(); + + // stop and delete the processor + StopProcessor(); + delete m_pProcessor; + m_pProcessor = 0; + + SDL_QuitSubSystem(SDL_INIT_VIDEO); + return 0; +} + +int CGraphicsBackend_SDL_OpenGL::MemoryUsage() const +{ + return m_TextureMemoryUsage; +} + +void CGraphicsBackend_SDL_OpenGL::Minimize() +{ + SDL_WM_IconifyWindow(); +} + +void CGraphicsBackend_SDL_OpenGL::Maximize() +{ + // TODO: SDL +} + +int CGraphicsBackend_SDL_OpenGL::WindowActive() +{ + return SDL_GetAppState()&SDL_APPINPUTFOCUS; +} + +int CGraphicsBackend_SDL_OpenGL::WindowOpen() +{ + return SDL_GetAppState()&SDL_APPACTIVE; +} + +void CGraphicsBackend_SDL_OpenGL::NotifyWindow() +{ + // get window handle + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if(!SDL_GetWMInfo(&info)) + { + dbg_msg("gfx", "unable to obtain window handle"); + return; + } + + #if defined(CONF_FAMILY_WINDOWS) + FLASHWINFO desc; + desc.cbSize = sizeof(desc); + desc.hwnd = info.window; + desc.dwFlags = FLASHW_TRAY; + desc.uCount = 3; // flash 3 times + desc.dwTimeout = 0; + + FlashWindowEx(&desc); + #elif defined(SDL_VIDEO_DRIVER_X11) && !defined(CONF_PLATFORM_MACOSX) + Display *dpy = info.info.x11.display; + Window win; + if(m_pScreenSurface->flags & SDL_FULLSCREEN) + win = info.info.x11.fswindow; + else + win = info.info.x11.wmwindow; + + // Old hints + XWMHints *wmhints; + wmhints = XAllocWMHints(); + wmhints->flags = XUrgencyHint; + XSetWMHints(dpy, win, wmhints); + XFree(wmhints); + + // More modern way of notifying + static Atom demandsAttention = XInternAtom(dpy, "_NET_WM_STATE_DEMANDS_ATTENTION", true); + static Atom wmState = XInternAtom(dpy, "_NET_WM_STATE", true); + XChangeProperty(dpy, win, wmState, XA_ATOM, 32, PropModeReplace, + (unsigned char *) &demandsAttention, 1); + #endif +} + + +IGraphicsBackend *CreateGraphicsBackend() { return new CGraphicsBackend_SDL_OpenGL; } diff --git a/src/engine/client/backend_sdl.h b/src/engine/client/backend_sdl.h new file mode 100644 index 0000000..66e9df8 --- /dev/null +++ b/src/engine/client/backend_sdl.h @@ -0,0 +1,312 @@ + +#include "SDL.h" + +#include "graphics_threaded.h" + + + +// platform dependent implementations for transfering render context from the main thread to the graphics thread +// TODO: when SDL 1.3 comes, this can be removed +#if defined(CONF_FAMILY_WINDOWS) + struct SGLContext + { + HDC m_hDC; + HGLRC m_hGLRC; + }; + + static SGLContext GL_GetCurrentContext() + { + SGLContext Context; + Context.m_hDC = wglGetCurrentDC(); + Context.m_hGLRC = wglGetCurrentContext(); + return Context; + } + + static void GL_MakeCurrent(const SGLContext &Context) { wglMakeCurrent(Context.m_hDC, Context.m_hGLRC); } + static void GL_ReleaseContext(const SGLContext &Context) { wglMakeCurrent(NULL, NULL); } + static void GL_SwapBuffers(const SGLContext &Context) { SwapBuffers(Context.m_hDC); } +#elif defined(CONF_PLATFORM_MACOSX) + + #include <objc/objc-runtime.h> + + class semaphore + { + SDL_sem *sem; + public: + semaphore() { sem = SDL_CreateSemaphore(0); } + ~semaphore() { SDL_DestroySemaphore(sem); } + void wait() { SDL_SemWait(sem); } + void signal() { SDL_SemPost(sem); } + }; + + struct SGLContext + { + id m_Context; + }; + + static SGLContext GL_GetCurrentContext() + { + SGLContext Context; + Class NSOpenGLContextClass = (Class) objc_getClass("NSOpenGLContext"); + SEL selector = sel_registerName("currentContext"); + Context.m_Context = objc_msgSend((objc_object*) NSOpenGLContextClass, selector); + return Context; + } + + static void GL_MakeCurrent(const SGLContext &Context) + { + SEL selector = sel_registerName("makeCurrentContext"); + objc_msgSend(Context.m_Context, selector); + } + + static void GL_ReleaseContext(const SGLContext &Context) + { + Class NSOpenGLContextClass = (Class) objc_getClass("NSOpenGLContext"); + SEL selector = sel_registerName("clearCurrentContext"); + objc_msgSend((objc_object*) NSOpenGLContextClass, selector); + } + + static void GL_SwapBuffers(const SGLContext &Context) + { + SEL selector = sel_registerName("flushBuffer"); + objc_msgSend(Context.m_Context, selector); + } + + class CAutoreleasePool + { + private: + id m_Pool; + + public: + CAutoreleasePool() + { + Class NSAutoreleasePoolClass = (Class) objc_getClass("NSAutoreleasePool"); + m_Pool = class_createInstance(NSAutoreleasePoolClass, 0); + SEL selector = sel_registerName("init"); + objc_msgSend(m_Pool, selector); + } + + ~CAutoreleasePool() + { + SEL selector = sel_registerName("drain"); + objc_msgSend(m_Pool, selector); + } + }; + +#elif defined(CONF_FAMILY_UNIX) + +#if defined(__ANDROID__) + + #include <EGL/egl.h> + + struct SGLContext + { + EGLDisplay m_Display; + EGLSurface m_SurfaceDraw; + EGLSurface m_SurfaceRead; + EGLContext m_Context; + }; + + static SGLContext GL_GetCurrentContext() + { + SGLContext Context; + Context.m_Display = eglGetCurrentDisplay(); + Context.m_SurfaceDraw = eglGetCurrentSurface(EGL_DRAW); + Context.m_SurfaceRead = eglGetCurrentSurface(EGL_READ); + Context.m_Context = eglGetCurrentContext(); + return Context; + } + + static void GL_MakeCurrent(const SGLContext &Context) + { + eglMakeCurrent(Context.m_Display, Context.m_SurfaceDraw, Context.m_SurfaceRead, Context.m_Context); + } + static void GL_ReleaseContext(const SGLContext &Context) + { + eglMakeCurrent(Context.m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + } + static void GL_SwapBuffers(const SGLContext &Context) + { + // eglSwapBuffers(Context.m_Display, Context.m_SurfaceDraw); + SDL_GL_SwapBuffers(); // This will also draw on-screen keyboard + } + +#else + + #include <GL/glx.h> + + struct SGLContext + { + Display *m_pDisplay; + GLXDrawable m_Drawable; + GLXContext m_Context; + }; + + static SGLContext GL_GetCurrentContext() + { + SGLContext Context; + Context.m_pDisplay = glXGetCurrentDisplay(); + Context.m_Drawable = glXGetCurrentDrawable(); + Context.m_Context = glXGetCurrentContext(); + return Context; + } + + static void GL_MakeCurrent(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, Context.m_Drawable, Context.m_Context); } + static void GL_ReleaseContext(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, None, 0x0); } + static void GL_SwapBuffers(const SGLContext &Context) { glXSwapBuffers(Context.m_pDisplay, Context.m_Drawable); } + +#endif +#else + #error missing implementation +#endif + + +// basic threaded backend, abstract, missing init and shutdown functions +class CGraphicsBackend_Threaded : public IGraphicsBackend +{ +public: + // constructed on the main thread, the rest of the functions is runned on the render thread + class ICommandProcessor + { + public: + virtual ~ICommandProcessor() {} + virtual void RunBuffer(CCommandBuffer *pBuffer) = 0; + }; + + CGraphicsBackend_Threaded(); + + virtual void RunBuffer(CCommandBuffer *pBuffer); + virtual bool IsIdle() const; + virtual void WaitForIdle(); + +protected: + void StartProcessor(ICommandProcessor *pProcessor); + void StopProcessor(); + +private: + ICommandProcessor *m_pProcessor; + CCommandBuffer * volatile m_pBuffer; + volatile bool m_Shutdown; + semaphore m_Activity; + semaphore m_BufferDone; + void *m_pThread; + + static void ThreadFunc(void *pUser); +}; + +// takes care of implementation independent operations +class CCommandProcessorFragment_General +{ + void Cmd_Nop(); + void Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand); +public: + bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand); +}; + +// takes care of opengl related rendering +class CCommandProcessorFragment_OpenGL +{ + struct CTexture + { + GLuint m_Tex; + int m_MemSize; + }; + CTexture m_aTextures[CCommandBuffer::MAX_TEXTURES]; + volatile int *m_pTextureMemoryUsage; + +public: + enum + { + CMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_OPENGL, + }; + + struct SCommand_Init : public CCommandBuffer::SCommand + { + SCommand_Init() : SCommand(CMD_INIT) {} + volatile int *m_pTextureMemoryUsage; + }; + +private: + static int TexFormatToOpenGLFormat(int TexFormat); + static unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp); + static void *Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData); + + void SetState(const CCommandBuffer::SState &State); + + void Cmd_Init(const SCommand_Init *pCommand); + void Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand); + void Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand); + void Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand); + void Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand); + void Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand); + void Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand); + +public: + CCommandProcessorFragment_OpenGL(); + + bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand); +}; + +// takes care of sdl related commands +class CCommandProcessorFragment_SDL +{ + // SDL stuff + SGLContext m_GLContext; +public: + enum + { + CMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_SDL, + CMD_SHUTDOWN, + }; + + struct SCommand_Init : public CCommandBuffer::SCommand + { + SCommand_Init() : SCommand(CMD_INIT) {} + SGLContext m_Context; + }; + + struct SCommand_Shutdown : public CCommandBuffer::SCommand + { + SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {} + }; + +private: + void Cmd_Init(const SCommand_Init *pCommand); + void Cmd_Shutdown(const SCommand_Shutdown *pCommand); + void Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand); + void Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand); +public: + CCommandProcessorFragment_SDL(); + + bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); +}; + +// command processor impelementation, uses the fragments to combine into one processor +class CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandProcessor +{ + CCommandProcessorFragment_OpenGL m_OpenGL; + CCommandProcessorFragment_SDL m_SDL; + CCommandProcessorFragment_General m_General; +public: + virtual void RunBuffer(CCommandBuffer *pBuffer); +}; + +// graphics backend implemented with SDL and OpenGL +class CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded +{ + SDL_Surface *m_pScreenSurface; + ICommandProcessor *m_pProcessor; + SGLContext m_GLContext; + volatile int m_TextureMemoryUsage; +public: + virtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags); + virtual int Shutdown(); + + virtual int MemoryUsage() const; + + virtual void Minimize(); + virtual void Maximize(); + virtual int WindowActive(); + virtual int WindowOpen(); + virtual void NotifyWindow(); +}; diff --git a/src/engine/client/client.cpp b/src/engine/client/client.cpp new file mode 100644 index 0000000..bcc691f --- /dev/null +++ b/src/engine/client/client.cpp @@ -0,0 +1,3464 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <new> + +#include <time.h> +#include <stdlib.h> // qsort +#include <stdarg.h> +#include <string.h> +#include <climits> + +#include <base/math.h> +#include <base/vmath.h> +#include <base/system.h> + +#include <game/client/components/menus.h> +#include <game/client/gameclient.h> + +#include <engine/client.h> +#include <engine/config.h> +#include <engine/console.h> +#include <engine/editor.h> +#include <engine/engine.h> +#include <engine/graphics.h> +#include <engine/input.h> +#include <engine/keys.h> +#include <engine/map.h> +#include <engine/masterserver.h> +#include <engine/serverbrowser.h> +#include <engine/sound.h> +#include <engine/storage.h> +#include <engine/textrender.h> + +#include <engine/shared/config.h> +#include <engine/shared/compression.h> +#include <engine/shared/datafile.h> +#include <engine/shared/demo.h> +#include <engine/shared/filecollection.h> +#include <engine/shared/mapchecker.h> +#include <engine/shared/network.h> +#include <engine/shared/packer.h> +#include <engine/shared/protocol.h> +#include <engine/shared/ringbuffer.h> +#include <engine/shared/snapshot.h> +#include <engine/shared/fifoconsole.h> + +#include <game/version.h> + +#include <mastersrv/mastersrv.h> +#include <versionsrv/versionsrv.h> + +#include <engine/client/serverbrowser.h> + +#if defined(CONF_FAMILY_WINDOWS) + #define _WIN32_WINNT 0x0501 + #define WIN32_LEAN_AND_MEAN + #include <windows.h> +#endif + +#include "friends.h" +#include "serverbrowser.h" +#include "fetcher.h" +#include "updater.h" +#include "client.h" + +#include <zlib.h> + +#include "SDL.h" +#ifdef main +#undef main +#endif + +void CGraph::Init(float Min, float Max) +{ + m_Min = Min; + m_Max = Max; + m_Index = 0; +} + +void CGraph::ScaleMax() +{ + int i = 0; + m_Max = 0; + for(i = 0; i < MAX_VALUES; i++) + { + if(m_aValues[i] > m_Max) + m_Max = m_aValues[i]; + } +} + +void CGraph::ScaleMin() +{ + int i = 0; + m_Min = m_Max; + for(i = 0; i < MAX_VALUES; i++) + { + if(m_aValues[i] < m_Min) + m_Min = m_aValues[i]; + } +} + +void CGraph::Add(float v, float r, float g, float b) +{ + m_Index = (m_Index+1)&(MAX_VALUES-1); + m_aValues[m_Index] = v; + m_aColors[m_Index][0] = r; + m_aColors[m_Index][1] = g; + m_aColors[m_Index][2] = b; +} + +void CGraph::Render(IGraphics *pGraphics, int Font, float x, float y, float w, float h, const char *pDescription) +{ + //m_pGraphics->BlendNormal(); + + + pGraphics->TextureSet(-1); + + pGraphics->QuadsBegin(); + pGraphics->SetColor(0, 0, 0, 0.75f); + IGraphics::CQuadItem QuadItem(x, y, w, h); + pGraphics->QuadsDrawTL(&QuadItem, 1); + pGraphics->QuadsEnd(); + + pGraphics->LinesBegin(); + pGraphics->SetColor(0.95f, 0.95f, 0.95f, 1.00f); + IGraphics::CLineItem LineItem(x, y+h/2, x+w, y+h/2); + pGraphics->LinesDraw(&LineItem, 1); + pGraphics->SetColor(0.5f, 0.5f, 0.5f, 0.75f); + IGraphics::CLineItem Array[2] = { + IGraphics::CLineItem(x, y+(h*3)/4, x+w, y+(h*3)/4), + IGraphics::CLineItem(x, y+h/4, x+w, y+h/4)}; + pGraphics->LinesDraw(Array, 2); + for(int i = 1; i < MAX_VALUES; i++) + { + float a0 = (i-1)/(float)MAX_VALUES; + float a1 = i/(float)MAX_VALUES; + int i0 = (m_Index+i-1)&(MAX_VALUES-1); + int i1 = (m_Index+i)&(MAX_VALUES-1); + + float v0 = (m_aValues[i0]-m_Min) / (m_Max-m_Min); + float v1 = (m_aValues[i1]-m_Min) / (m_Max-m_Min); + + IGraphics::CColorVertex Array[2] = { + IGraphics::CColorVertex(0, m_aColors[i0][0], m_aColors[i0][1], m_aColors[i0][2], 0.75f), + IGraphics::CColorVertex(1, m_aColors[i1][0], m_aColors[i1][1], m_aColors[i1][2], 0.75f)}; + pGraphics->SetColorVertex(Array, 2); + IGraphics::CLineItem LineItem(x+a0*w, y+h-v0*h, x+a1*w, y+h-v1*h); + pGraphics->LinesDraw(&LineItem, 1); + + } + pGraphics->LinesEnd(); + + pGraphics->TextureSet(Font); + pGraphics->QuadsBegin(); + pGraphics->QuadsText(x+2, y+h-16, 16, pDescription); + + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "%.2f", m_Max); + pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+2, 16, aBuf); + + str_format(aBuf, sizeof(aBuf), "%.2f", m_Min); + pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+h-16, 16, aBuf); + pGraphics->QuadsEnd(); +} + + +void CSmoothTime::Init(int64 Target) +{ + m_Snap = time_get(); + m_Current = Target; + m_Target = Target; + m_aAdjustSpeed[0] = 0.3f; + m_aAdjustSpeed[1] = 0.3f; + m_Graph.Init(0.0f, 0.5f); +} + +void CSmoothTime::SetAdjustSpeed(int Direction, float Value) +{ + m_aAdjustSpeed[Direction] = Value; +} + +int64 CSmoothTime::Get(int64 Now) +{ + int64 c = m_Current + (Now - m_Snap); + int64 t = m_Target + (Now - m_Snap); + + // it's faster to adjust upward instead of downward + // we might need to adjust these abit + + float AdjustSpeed = m_aAdjustSpeed[0]; + if(t > c) + AdjustSpeed = m_aAdjustSpeed[1]; + + float a = ((Now-m_Snap)/(float)time_freq()) * AdjustSpeed; + if(a > 1.0f) + a = 1.0f; + + int64 r = c + (int64)((t-c)*a); + + m_Graph.Add(a+0.5f,1,1,1); + + return r; +} + +void CSmoothTime::UpdateInt(int64 Target) +{ + int64 Now = time_get(); + m_Current = Get(Now); + m_Snap = Now; + m_Target = Target; +} + +void CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection) +{ + int UpdateTimer = 1; + + if(TimeLeft < 0) + { + int IsSpike = 0; + if(TimeLeft < -50) + { + IsSpike = 1; + + m_SpikeCounter += 5; + if(m_SpikeCounter > 50) + m_SpikeCounter = 50; + } + + if(IsSpike && m_SpikeCounter < 15) + { + // ignore this ping spike + UpdateTimer = 0; + pGraph->Add(TimeLeft, 1,1,0); + } + else + { + pGraph->Add(TimeLeft, 1,0,0); + if(m_aAdjustSpeed[AdjustDirection] < 30.0f) + m_aAdjustSpeed[AdjustDirection] *= 2.0f; + } + } + else + { + if(m_SpikeCounter) + m_SpikeCounter--; + + pGraph->Add(TimeLeft, 0,1,0); + + m_aAdjustSpeed[AdjustDirection] *= 0.95f; + if(m_aAdjustSpeed[AdjustDirection] < 2.0f) + m_aAdjustSpeed[AdjustDirection] = 2.0f; + } + + if(UpdateTimer) + UpdateInt(Target); +} + + +CClient::CClient() : m_DemoPlayer(&m_SnapshotDelta) +{ + m_DemoRecorder[0] = CDemoRecorder(&m_SnapshotDelta); + m_DemoRecorder[1] = CDemoRecorder(&m_SnapshotDelta); + m_DemoRecorder[2] = CDemoRecorder(&m_SnapshotDelta); + + m_pEditor = 0; + m_pInput = 0; + m_pGraphics = 0; + m_pSound = 0; + m_pGameClient = 0; + m_pMap = 0; + m_pConsole = 0; + + m_RenderFrameTime = 0.0001f; + m_RenderFrameTimeLow = 1.0f; + m_RenderFrameTimeHigh = 0.0f; + m_RenderFrames = 0; + m_LastRenderTime = time_get(); + + m_GameTickSpeed = SERVER_TICK_SPEED; + + m_WindowMustRefocus = 0; + m_SnapCrcErrors = 0; + m_AutoScreenshotRecycle = false; + m_AutoStatScreenshotRecycle = false; + m_EditorActive = false; + + m_AckGameTick[0] = -1; + m_AckGameTick[1] = -1; + m_CurrentRecvTick[0] = 0; + m_CurrentRecvTick[1] = 0; + m_RconAuthed[0] = 0; + m_RconAuthed[1] = 0; + m_RconPassword[0] = '\0'; + + // version-checking + m_aVersionStr[0] = '0'; + m_aVersionStr[1] = 0; + + // pinging + m_PingStartTime = 0; + + // + m_aCurrentMap[0] = 0; + m_CurrentMapCrc = 0; + + // + m_aCmdConnect[0] = 0; + + // map download + m_aMapdownloadFilename[0] = 0; + m_aMapdownloadName[0] = 0; + m_pMapdownloadTask = 0; + m_MapdownloadFile = 0; + m_MapdownloadChunk = 0; + m_MapdownloadCrc = 0; + m_MapdownloadAmount = -1; + m_MapdownloadTotalsize = -1; + + m_CurrentServerInfoRequestTime = -1; + + m_CurrentInput[0] = 0; + m_CurrentInput[1] = 0; + m_LastDummy = 0; + m_LastDummy2 = 0; + m_LocalIDs[0] = 0; + m_LocalIDs[1] = 0; + m_Fire = 0; + + mem_zero(&m_aInputs, sizeof(m_aInputs)); + mem_zero(&m_DummyInput, sizeof(m_DummyInput)); + mem_zero(&HammerInput, sizeof(HammerInput)); + HammerInput.m_Fire = 0; + + m_State = IClient::STATE_OFFLINE; + m_aServerAddressStr[0] = 0; + + mem_zero(m_aSnapshots, sizeof(m_aSnapshots)); + m_SnapshotStorage[0].Init(); + m_SnapshotStorage[1].Init(); + m_ReceivedSnapshots[0] = 0; + m_ReceivedSnapshots[1] = 0; + + m_VersionInfo.m_State = CVersionInfo::STATE_INIT; + + if (g_Config.m_ClDummy == 0) + m_LastDummyConnectTime = 0; + + m_DDNetSrvListTokenSet = false; +} + +// ----- send functions ----- +int CClient::SendMsg(CMsgPacker *pMsg, int Flags) +{ + return SendMsgEx(pMsg, Flags, false); +} + +int CClient::SendMsgEx(CMsgPacker *pMsg, int Flags, bool System) +{ + CNetChunk Packet; + + if(State() == IClient::STATE_OFFLINE) + return 0; + + mem_zero(&Packet, sizeof(CNetChunk)); + + Packet.m_ClientID = 0; + Packet.m_pData = pMsg->Data(); + Packet.m_DataSize = pMsg->Size(); + + // HACK: modify the message id in the packet and store the system flag + if(*((unsigned char*)Packet.m_pData) == 1 && System && Packet.m_DataSize == 1) + dbg_break(); + + *((unsigned char*)Packet.m_pData) <<= 1; + if(System) + *((unsigned char*)Packet.m_pData) |= 1; + + if(Flags&MSGFLAG_VITAL) + Packet.m_Flags |= NETSENDFLAG_VITAL; + if(Flags&MSGFLAG_FLUSH) + Packet.m_Flags |= NETSENDFLAG_FLUSH; + + if(Flags&MSGFLAG_RECORD) + { + for(int i = 0; i < RECORDER_MAX; i++) + if(m_DemoRecorder[i].IsRecording()) + m_DemoRecorder[i].RecordMessage(Packet.m_pData, Packet.m_DataSize); + } + + if(!(Flags&MSGFLAG_NOSEND)) + { + m_NetClient[g_Config.m_ClDummy].Send(&Packet); + } + + return 0; +} + +void CClient::SendInfo() +{ + CMsgPacker Msg(NETMSG_INFO); + Msg.AddString(GameClient()->NetVersion(), 128); + Msg.AddString(g_Config.m_Password, 128); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); +} + + +void CClient::SendEnterGame() +{ + CMsgPacker Msg(NETMSG_ENTERGAME); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); +} + +void CClient::SendReady() +{ + CMsgPacker Msg(NETMSG_READY); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); +} + +void CClient::SendMapRequest() +{ + if(m_MapdownloadFile) + io_close(m_MapdownloadFile); + m_MapdownloadFile = Storage()->OpenFile(m_aMapdownloadFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA); + Msg.AddInt(m_MapdownloadChunk); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); +} + +void CClient::RconAuth(const char *pName, const char *pPassword) +{ + if(RconAuthed()) + return; + + str_copy(m_RconPassword, pPassword, sizeof(m_RconPassword)); + + CMsgPacker Msg(NETMSG_RCON_AUTH); + Msg.AddString(pName, 32); + Msg.AddString(pPassword, 32); + Msg.AddInt(1); + SendMsgEx(&Msg, MSGFLAG_VITAL); +} + +void CClient::Rcon(const char *pCmd) +{ + CServerInfo Info; + GetServerInfo(&Info); + + CMsgPacker Msg(NETMSG_RCON_CMD); + Msg.AddString(pCmd, 256); + SendMsgEx(&Msg, MSGFLAG_VITAL); +} + +bool CClient::ConnectionProblems() +{ + return m_NetClient[g_Config.m_ClDummy].GotProblems() != 0; +} + +void CClient::DirectInput(int *pInput, int Size) +{ + int i; + CMsgPacker Msg(NETMSG_INPUT); + Msg.AddInt(m_AckGameTick[g_Config.m_ClDummy]); + Msg.AddInt(m_PredTick[g_Config.m_ClDummy]); + Msg.AddInt(Size); + + for(i = 0; i < Size/4; i++) + Msg.AddInt(pInput[i]); + + SendMsgEx(&Msg, 0); +} + +void CClient::SendInput() +{ + int64 Now = time_get(); + + if(m_PredTick[g_Config.m_ClDummy] <= 0) + return; + + // fetch input + int Size = GameClient()->OnSnapInput(m_aInputs[g_Config.m_ClDummy][m_CurrentInput[g_Config.m_ClDummy]].m_aData); + + if(Size) + { + // pack input + CMsgPacker Msg(NETMSG_INPUT); + Msg.AddInt(m_AckGameTick[g_Config.m_ClDummy]); + Msg.AddInt(m_PredTick[g_Config.m_ClDummy]); + Msg.AddInt(Size); + + m_aInputs[g_Config.m_ClDummy][m_CurrentInput[g_Config.m_ClDummy]].m_Tick = m_PredTick[g_Config.m_ClDummy]; + m_aInputs[g_Config.m_ClDummy][m_CurrentInput[g_Config.m_ClDummy]].m_PredictedTime = m_PredictedTime.Get(Now); + m_aInputs[g_Config.m_ClDummy][m_CurrentInput[g_Config.m_ClDummy]].m_Time = Now; + + // pack it + for(int i = 0; i < Size/4; i++) + Msg.AddInt(m_aInputs[g_Config.m_ClDummy][m_CurrentInput[g_Config.m_ClDummy]].m_aData[i]); + + m_CurrentInput[g_Config.m_ClDummy]++; + m_CurrentInput[g_Config.m_ClDummy]%=200; + + SendMsgEx(&Msg, MSGFLAG_FLUSH); + } + + if(m_LastDummy != (bool)g_Config.m_ClDummy) + { + m_DummyInput = GameClient()->getPlayerInput(!g_Config.m_ClDummy); + m_LastDummy = g_Config.m_ClDummy; + + if (g_Config.m_ClDummyResetOnSwitch) + { + m_DummyInput.m_Jump = 0; + m_DummyInput.m_Hook = 0; + if(m_DummyInput.m_Fire & 1) + m_DummyInput.m_Fire++; + m_DummyInput.m_Direction = 0; + GameClient()->ResetDummyInput(); + } + } + + if(!g_Config.m_ClDummy) + m_LocalIDs[0] = ((CGameClient *)GameClient())->m_Snap.m_LocalClientID; + else + m_LocalIDs[1] = ((CGameClient *)GameClient())->m_Snap.m_LocalClientID; + + if(m_DummyConnected) + { + if(!g_Config.m_ClDummyHammer) + { + if(m_Fire != 0) + { + m_DummyInput.m_Fire = HammerInput.m_Fire; + m_Fire = 0; + } + + if(!Size && (!m_DummyInput.m_Direction && !m_DummyInput.m_Jump && !m_DummyInput.m_Hook)) + return; + + // pack input + CMsgPacker Msg(NETMSG_INPUT); + Msg.AddInt(m_AckGameTick[!g_Config.m_ClDummy]); + Msg.AddInt(m_PredTick[!g_Config.m_ClDummy]); + Msg.AddInt(sizeof(m_DummyInput)); + + // pack it + for(unsigned int i = 0; i < sizeof(m_DummyInput)/4; i++) + Msg.AddInt(((int*) &m_DummyInput)[i]); + + SendMsgExY(&Msg, MSGFLAG_FLUSH, true, !g_Config.m_ClDummy); + } + else + { + if ((((float) m_Fire / 12.5) - (int ((float) m_Fire / 12.5))) > 0.01) + { + m_Fire++; + return; + } + m_Fire++; + + HammerInput.m_Fire+=2; + HammerInput.m_WantedWeapon = 1; + + vec2 Main = ((CGameClient *)GameClient())->m_LocalCharacterPos; + vec2 Dummy = ((CGameClient *)GameClient())->m_aClients[m_LocalIDs[!g_Config.m_ClDummy]].m_Predicted.m_Pos; + vec2 Dir = Main - Dummy; + HammerInput.m_TargetX = Dir.x; + HammerInput.m_TargetY = Dir.y; + + // pack input + CMsgPacker Msg(NETMSG_INPUT); + Msg.AddInt(m_AckGameTick[!g_Config.m_ClDummy]); + Msg.AddInt(m_PredTick[!g_Config.m_ClDummy]); + Msg.AddInt(sizeof(HammerInput)); + + // pack it + for(unsigned int i = 0; i < sizeof(HammerInput)/4; i++) + Msg.AddInt(((int*) &HammerInput)[i]); + + SendMsgExY(&Msg, MSGFLAG_FLUSH, true, !g_Config.m_ClDummy); + } + } +} + +const char *CClient::LatestVersion() +{ + return m_aVersionStr; +} + +// TODO: OPT: do this alot smarter! +int *CClient::GetInput(int Tick) +{ + int Best = -1; + for(int i = 0; i < 200; i++) + { + if(m_aInputs[g_Config.m_ClDummy][i].m_Tick <= Tick && (Best == -1 || m_aInputs[g_Config.m_ClDummy][Best].m_Tick < m_aInputs[g_Config.m_ClDummy][i].m_Tick)) + Best = i; + } + + if(Best != -1) + return (int *)m_aInputs[g_Config.m_ClDummy][Best].m_aData; + return 0; +} + +bool CClient::InputExists(int Tick) +{ + for(int i = 0; i < 200; i++) + if(m_aInputs[g_Config.m_ClDummy][i].m_Tick == Tick) + return true; + return false; +} + +// ------ state handling ----- +void CClient::SetState(int s) +{ + if(m_State == IClient::STATE_QUITING) + return; + + int Old = m_State; + if(g_Config.m_Debug) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "state change. last=%d current=%d", m_State, s); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + m_State = s; + if(Old != s) + GameClient()->OnStateChange(m_State, Old); +} + +// called when the map is loaded and we should init for a new round +void CClient::OnEnterGame() +{ + // reset input + int i; + for(i = 0; i < 200; i++) + { + m_aInputs[0][i].m_Tick = -1; + m_aInputs[1][i].m_Tick = -1; + } + m_CurrentInput[0] = 0; + m_CurrentInput[1] = 0; + + // reset snapshots + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = 0; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = 0; + m_SnapshotStorage[g_Config.m_ClDummy].PurgeAll(); + m_ReceivedSnapshots[g_Config.m_ClDummy] = 0; + m_SnapshotParts = 0; + m_PredTick[g_Config.m_ClDummy] = 0; + m_CurrentRecvTick[g_Config.m_ClDummy] = 0; + m_CurGameTick[g_Config.m_ClDummy] = 0; + m_PrevGameTick[g_Config.m_ClDummy] = 0; + + if (g_Config.m_ClDummy == 0) + m_LastDummyConnectTime = 0; + + GameClient()->OnEnterGame(); +} + +void CClient::EnterGame() +{ + if(State() == IClient::STATE_DEMOPLAYBACK) + return; + + // now we will wait for two snapshots + // to finish the connection + SendEnterGame(); + OnEnterGame(); + + ServerInfoRequest(); // fresh one for timeout protection + m_TimeoutCodeSent[0] = false; + m_TimeoutCodeSent[1] = false; +} + +void CClient::Connect(const char *pAddress) +{ + char aBuf[512]; + int Port = 8303; + + Disconnect(); + + str_copy(m_aServerAddressStr, pAddress, sizeof(m_aServerAddressStr)); + + str_format(aBuf, sizeof(aBuf), "connecting to '%s'", m_aServerAddressStr); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + + ServerInfoRequest(); + if(net_host_lookup(m_aServerAddressStr, &m_ServerAddress, m_NetClient[0].NetType()) != 0) + { + char aBufMsg[256]; + str_format(aBufMsg, sizeof(aBufMsg), "could not find the address of %s, connecting to localhost", aBuf); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBufMsg); + net_host_lookup("localhost", &m_ServerAddress, m_NetClient[0].NetType()); + } + + m_RconAuthed[0] = 0; + if(m_ServerAddress.port == 0) + m_ServerAddress.port = Port; + m_NetClient[0].Connect(&m_ServerAddress); + SetState(IClient::STATE_CONNECTING); + + for(int i = 0; i < RECORDER_MAX; i++) + if(m_DemoRecorder[i].IsRecording()) + DemoRecorder_Stop(i); + + m_InputtimeMarginGraph.Init(-150.0f, 150.0f); + m_GametimeMarginGraph.Init(-150.0f, 150.0f); +} + +void CClient::DisconnectWithReason(const char *pReason) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "disconnecting. reason='%s'", pReason?pReason:"unknown"); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + + // stop demo playback and recorder + m_DemoPlayer.Stop(); + for(int i = 0; i < RECORDER_MAX; i++) + DemoRecorder_Stop(i); + + // + m_RconAuthed[0] = 0; + m_UseTempRconCommands = 0; + m_pConsole->DeregisterTempAll(); + m_NetClient[0].Disconnect(pReason); + SetState(IClient::STATE_OFFLINE); + m_pMap->Unload(); + + // disable all downloads + m_MapdownloadChunk = 0; + if(m_pMapdownloadTask) + m_pMapdownloadTask->Abort(); + if(m_MapdownloadFile) + io_close(m_MapdownloadFile); + m_MapdownloadFile = 0; + m_MapdownloadCrc = 0; + m_MapdownloadTotalsize = -1; + m_MapdownloadAmount = 0; + + // clear the current server info + mem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); + mem_zero(&m_ServerAddress, sizeof(m_ServerAddress)); + + // clear snapshots + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = 0; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = 0; + m_ReceivedSnapshots[g_Config.m_ClDummy] = 0; +} + +void CClient::Disconnect() +{ + if(m_DummyConnected) + DummyDisconnect(0); + DisconnectWithReason(0); +} + +bool CClient::DummyConnected() +{ + return m_DummyConnected; +} + +bool CClient::DummyConnecting() +{ + return !m_DummyConnected && m_LastDummyConnectTime > 0 && m_LastDummyConnectTime + GameTickSpeed() * 5 > GameTick(); +} + +void CClient::DummyConnect() +{ + if(m_LastDummyConnectTime > 0 && m_LastDummyConnectTime + GameTickSpeed() * 5 > GameTick()) + return; + + if(m_NetClient[0].State() != NET_CONNSTATE_ONLINE && m_NetClient[0].State() != NET_CONNSTATE_PENDING) + return; + + if(m_DummyConnected) + return; + + m_LastDummyConnectTime = GameTick(); + + m_RconAuthed[1] = 0; + + m_DummySendConnInfo = true; + + //connecting to the server + m_NetClient[1].Connect(&m_ServerAddress); +} + +void CClient::DummyDisconnect(const char *pReason) +{ + if(!m_DummyConnected) + return; + + m_NetClient[1].Disconnect(pReason); + g_Config.m_ClDummy = 0; + m_RconAuthed[1] = 0; + m_DummyConnected = false; + GameClient()->OnDummyDisconnect(); +} + +int CClient::SendMsgExY(CMsgPacker *pMsg, int Flags, bool System, int NetClient) +{ + CNetChunk Packet; + + mem_zero(&Packet, sizeof(CNetChunk)); + + Packet.m_ClientID = 0; + Packet.m_pData = pMsg->Data(); + Packet.m_DataSize = pMsg->Size(); + + // HACK: modify the message id in the packet and store the system flag + if(*((unsigned char*)Packet.m_pData) == 1 && System && Packet.m_DataSize == 1) + dbg_break(); + + *((unsigned char*)Packet.m_pData) <<= 1; + if(System) + *((unsigned char*)Packet.m_pData) |= 1; + + if(Flags&MSGFLAG_VITAL) + Packet.m_Flags |= NETSENDFLAG_VITAL; + if(Flags&MSGFLAG_FLUSH) + Packet.m_Flags |= NETSENDFLAG_FLUSH; + + m_NetClient[NetClient].Send(&Packet); + return 0; +} + +void CClient::DummyInfo() +{ + CNetMsg_Cl_ChangeInfo Msg; + Msg.m_pName = g_Config.m_ClDummyName; + Msg.m_pClan = g_Config.m_ClDummyClan; + Msg.m_Country = g_Config.m_ClDummyCountry; + Msg.m_pSkin = g_Config.m_ClDummySkin; + Msg.m_UseCustomColor = g_Config.m_ClDummyUseCustomColor; + Msg.m_ColorBody = g_Config.m_ClDummyColorBody; + Msg.m_ColorFeet = g_Config.m_ClDummyColorFeet; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + SendMsgExY(&Packer, MSGFLAG_VITAL); +} + +void CClient::GetServerInfo(CServerInfo *pServerInfo) +{ + mem_copy(pServerInfo, &m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); + + if(m_DemoPlayer.IsPlaying() && g_Config.m_ClDemoAssumeRace) + str_copy(pServerInfo->m_aGameType, "DDraceNetwork", 14); +} + +void CClient::ServerInfoRequest() +{ + mem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); + m_CurrentServerInfoRequestTime = 0; +} + +int CClient::LoadData() +{ + m_DebugFont = Graphics()->LoadTexture("debug_font.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, IGraphics::TEXLOAD_NORESAMPLE); + return 1; +} + +// --- + +void *CClient::SnapGetItem(int SnapID, int Index, CSnapItem *pItem) +{ + CSnapshotItem *i; + dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); + i = m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap->GetItem(Index); + pItem->m_DataSize = m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap->GetItemSize(Index); + pItem->m_Type = i->Type(); + pItem->m_ID = i->ID(); + return (void *)i->Data(); +} + +void CClient::SnapInvalidateItem(int SnapID, int Index) +{ + CSnapshotItem *i; + dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); + i = m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap->GetItem(Index); + if(i) + { + if((char *)i < (char *)m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap || (char *)i > (char *)m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap + m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_SnapSize) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "snap invalidate problem"); + if((char *)i >= (char *)m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pSnap && (char *)i < (char *)m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pSnap + m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_SnapSize) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "snap invalidate problem"); + i->m_TypeAndID = -1; + } +} + +void *CClient::SnapFindItem(int SnapID, int Type, int ID) +{ + // TODO: linear search. should be fixed. + int i; + + if(!m_aSnapshots[g_Config.m_ClDummy][SnapID]) + return 0x0; + + for(i = 0; i < m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pSnap->NumItems(); i++) + { + CSnapshotItem *pItem = m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pAltSnap->GetItem(i); + if(pItem->Type() == Type && pItem->ID() == ID) + return (void *)pItem->Data(); + } + return 0x0; +} + +int CClient::SnapNumItems(int SnapID) +{ + dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); + if(!m_aSnapshots[g_Config.m_ClDummy][SnapID]) + return 0; + return m_aSnapshots[g_Config.m_ClDummy][SnapID]->m_pSnap->NumItems(); +} + +void CClient::SnapSetStaticsize(int ItemType, int Size) +{ + m_SnapshotDelta.SetStaticsize(ItemType, Size); +} + + +void CClient::DebugRender() +{ + static NETSTATS Prev, Current; + static int64 LastSnap = 0; + static float FrameTimeAvg = 0; + int64 Now = time_get(); + char aBuffer[512]; + + if(!g_Config.m_Debug) + return; + + //m_pGraphics->BlendNormal(); + Graphics()->TextureSet(m_DebugFont); + Graphics()->MapScreen(0,0,Graphics()->ScreenWidth(),Graphics()->ScreenHeight()); + Graphics()->QuadsBegin(); + + if(time_get()-LastSnap > time_freq()) + { + LastSnap = time_get(); + Prev = Current; + net_stats(&Current); + } + + /* + eth = 14 + ip = 20 + udp = 8 + total = 42 + */ + FrameTimeAvg = FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f; + str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d", + m_CurGameTick[g_Config.m_ClDummy], m_PredTick[g_Config.m_ClDummy], + mem_stats()->allocated/1024, + mem_stats()->total_allocations, + Graphics()->MemoryUsage()/1024, + (int)(1.0f/FrameTimeAvg + 0.5f)); + Graphics()->QuadsText(2, 2, 16, aBuffer); + + + { + int SendPackets = (Current.sent_packets-Prev.sent_packets); + int SendBytes = (Current.sent_bytes-Prev.sent_bytes); + int SendTotal = SendBytes + SendPackets*42; + int RecvPackets = (Current.recv_packets-Prev.recv_packets); + int RecvBytes = (Current.recv_bytes-Prev.recv_bytes); + int RecvTotal = RecvBytes + RecvPackets*42; + + if(!SendPackets) SendPackets++; + if(!RecvPackets) RecvPackets++; + str_format(aBuffer, sizeof(aBuffer), "send: %3d %5d+%4d=%5d (%3d kbps) avg: %5d\nrecv: %3d %5d+%4d=%5d (%3d kbps) avg: %5d", + SendPackets, SendBytes, SendPackets*42, SendTotal, (SendTotal*8)/1024, SendBytes/SendPackets, + RecvPackets, RecvBytes, RecvPackets*42, RecvTotal, (RecvTotal*8)/1024, RecvBytes/RecvPackets); + Graphics()->QuadsText(2, 14, 16, aBuffer); + } + + // render rates + { + int y = 0; + int i; + for(i = 0; i < 256; i++) + { + if(m_SnapshotDelta.GetDataRate(i)) + { + str_format(aBuffer, sizeof(aBuffer), "%4d %20s: %8d %8d %8d", i, GameClient()->GetItemName(i), m_SnapshotDelta.GetDataRate(i)/8, m_SnapshotDelta.GetDataUpdates(i), + (m_SnapshotDelta.GetDataRate(i)/m_SnapshotDelta.GetDataUpdates(i))/8); + Graphics()->QuadsText(2, 100+y*12, 16, aBuffer); + y++; + } + } + } + + str_format(aBuffer, sizeof(aBuffer), "pred: %d ms", + (int)((m_PredictedTime.Get(Now)-m_GameTime[g_Config.m_ClDummy].Get(Now))*1000/(float)time_freq())); + Graphics()->QuadsText(2, 70, 16, aBuffer); + Graphics()->QuadsEnd(); + + // render graphs + if(g_Config.m_DbgGraphs) + { + //Graphics()->MapScreen(0,0,400.0f,300.0f); + float w = Graphics()->ScreenWidth()/4.0f; + float h = Graphics()->ScreenHeight()/6.0f; + float sp = Graphics()->ScreenWidth()/100.0f; + float x = Graphics()->ScreenWidth()-w-sp; + + m_FpsGraph.ScaleMax(); + m_FpsGraph.ScaleMin(); + m_FpsGraph.Render(Graphics(), m_DebugFont, x, sp*5, w, h, "FPS"); + m_InputtimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp, w, h, "Prediction Margin"); + m_GametimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp+h+sp, w, h, "Gametime Margin"); + } +} + +void CClient::Restart() +{ + char aBuf[512]; + shell_execute(Storage()->GetBinaryPath(PLAT_CLIENT_EXEC, aBuf, sizeof aBuf)); + Quit(); +} + +void CClient::Quit() +{ + SetState(IClient::STATE_QUITING); +} + +const char *CClient::ErrorString() +{ + return m_NetClient[0].ErrorString(); +} + +void CClient::Render() +{ + if(g_Config.m_ClOverlayEntities) + { + vec3 bg = HslToRgb(vec3(g_Config.m_ClBackgroundEntitiesHue/255.0f, g_Config.m_ClBackgroundEntitiesSat/255.0f, g_Config.m_ClBackgroundEntitiesLht/255.0f)); + Graphics()->Clear(bg.r, bg.g, bg.b); + } + else + { + vec3 bg = HslToRgb(vec3(g_Config.m_ClBackgroundHue/255.0f, g_Config.m_ClBackgroundSat/255.0f, g_Config.m_ClBackgroundLht/255.0f)); + Graphics()->Clear(bg.r, bg.g, bg.b); + } + + GameClient()->OnRender(); + DebugRender(); + + if(State() == IClient::STATE_ONLINE && g_Config.m_ClAntiPingLimit) + { + int64 Now = time_get(); + g_Config.m_ClAntiPing = (m_PredictedTime.Get(Now)-m_GameTime[g_Config.m_ClDummy].Get(Now))*1000/(float)time_freq() > g_Config.m_ClAntiPingLimit; + } +} + +vec3 CClient::GetColorV3(int v) +{ + return HslToRgb(vec3(((v>>16)&0xff)/255.0f, ((v>>8)&0xff)/255.0f, 0.5f+(v&0xff)/255.0f*0.5f)); +} + +const char *CClient::LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc) +{ + static char aErrorMsg[128]; + + SetState(IClient::STATE_LOADING); + + if(!m_pMap->Load(pFilename)) + { + str_format(aErrorMsg, sizeof(aErrorMsg), "map '%s' not found", pFilename); + return aErrorMsg; + } + + // get the crc of the map + if(m_pMap->Crc() != WantedCrc) + { + str_format(aErrorMsg, sizeof(aErrorMsg), "map differs from the server. %08x != %08x", m_pMap->Crc(), WantedCrc); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aErrorMsg); + m_pMap->Unload(); + return aErrorMsg; + } + + // stop demo recording if we loaded a new map + for(int i = 0; i < RECORDER_MAX; i++) + DemoRecorder_Stop(i); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "loaded map '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); + m_ReceivedSnapshots[g_Config.m_ClDummy] = 0; + + str_copy(m_aCurrentMap, pName, sizeof(m_aCurrentMap)); + m_CurrentMapCrc = m_pMap->Crc(); + + return 0x0; +} + + + +const char *CClient::LoadMapSearch(const char *pMapName, int WantedCrc) +{ + const char *pError = 0; + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "loading map, map=%s wanted crc=%08x", pMapName, WantedCrc); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); + SetState(IClient::STATE_LOADING); + + // try the normal maps folder + str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); + pError = LoadMap(pMapName, aBuf, WantedCrc); + if(!pError) + return pError; + + // try the downloaded maps + str_format(aBuf, sizeof(aBuf), "downloadedmaps/%s_%08x.map", pMapName, WantedCrc); + pError = LoadMap(pMapName, aBuf, WantedCrc); + if(!pError) + return pError; + + // search for the map within subfolders + char aFilename[128]; + str_format(aFilename, sizeof(aFilename), "%s.map", pMapName); + if(Storage()->FindFile(aFilename, "maps", IStorage::TYPE_ALL, aBuf, sizeof(aBuf))) + pError = LoadMap(pMapName, aBuf, WantedCrc); + + return pError; +} + +int CClient::PlayerScoreNameComp(const void *a, const void *b) +{ + CServerInfo::CClient *p0 = (CServerInfo::CClient *)a; + CServerInfo::CClient *p1 = (CServerInfo::CClient *)b; + if(p0->m_Player && !p1->m_Player) + return -1; + if(!p0->m_Player && p1->m_Player) + return 1; + if(p0->m_Score > p1->m_Score) + return -1; + if(p0->m_Score < p1->m_Score) + return 1; + return str_comp_nocase(p0->m_aName, p1->m_aName); +} + +void CClient::ProcessConnlessPacket(CNetChunk *pPacket) +{ + // version server + if(m_VersionInfo.m_State == CVersionInfo::STATE_READY && net_addr_comp(&pPacket->m_Address, &m_VersionInfo.m_VersionServeraddr.m_Addr) == 0) + { + // version info + if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)) && + mem_comp(pPacket->m_pData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)) == 0) + { + char *pVersionData = (char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION); + int aCurVersion[] = {0,0,0}, aNewVersion[] = {0,0,0}; + sscanf(pVersionData, "%d.%d.%d", aNewVersion, aNewVersion+1, aNewVersion+2); + sscanf(GAME_RELEASE_VERSION, "%d.%d.%d", aCurVersion, aCurVersion+1, aCurVersion+2); + bool VersionMatch = mem_comp(aCurVersion, aNewVersion, sizeof aCurVersion) >= 0; + + char aVersion[sizeof(GAME_RELEASE_VERSION)]; + str_copy(aVersion, pVersionData, sizeof(aVersion)); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "version does %s (%s)", + VersionMatch ? "match" : "NOT match", + aVersion); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/version", aBuf); + + // assume version is out of date when version-data doesn't match + if(!VersionMatch) + str_copy(m_aVersionStr, aVersion, sizeof(m_aVersionStr)); + + // request the news + CNetChunk Packet; + mem_zero(&Packet, sizeof(Packet)); + Packet.m_ClientID = -1; + Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; + Packet.m_pData = VERSIONSRV_GETNEWS; + Packet.m_DataSize = sizeof(VERSIONSRV_GETNEWS); + Packet.m_Flags = NETSENDFLAG_CONNLESS; + m_NetClient[g_Config.m_ClDummy].Send(&Packet); + + RequestDDNetSrvList(); + + // request the map version list now + mem_zero(&Packet, sizeof(Packet)); + Packet.m_ClientID = -1; + Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; + Packet.m_pData = VERSIONSRV_GETMAPLIST; + Packet.m_DataSize = sizeof(VERSIONSRV_GETMAPLIST); + Packet.m_Flags = NETSENDFLAG_CONNLESS; + m_NetClient[g_Config.m_ClDummy].Send(&Packet); + } + + // news + if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_NEWS) + NEWS_SIZE) && + mem_comp(pPacket->m_pData, VERSIONSRV_NEWS, sizeof(VERSIONSRV_NEWS)) == 0) + { + if (mem_comp(m_aNews, (char*)pPacket->m_pData + sizeof(VERSIONSRV_NEWS), NEWS_SIZE)) + g_Config.m_UiPage = CMenus::PAGE_NEWS; + + mem_copy(m_aNews, (char*)pPacket->m_pData + sizeof(VERSIONSRV_NEWS), NEWS_SIZE); + + IOHANDLE newsFile = m_pStorage->OpenFile("ddnet-news.txt", IOFLAG_WRITE, IStorage::TYPE_SAVE); + if (newsFile) + { + io_write(newsFile, m_aNews, sizeof(m_aNews)); + io_close(newsFile); + } + } + + // ddnet server list + // Packet: VERSIONSRV_DDNETLIST + char[4] Token + int16 comp_length + int16 plain_length + char[comp_length] + if(pPacket->m_DataSize >= (int)(sizeof(VERSIONSRV_DDNETLIST) + 8) && + mem_comp(pPacket->m_pData, VERSIONSRV_DDNETLIST, sizeof(VERSIONSRV_DDNETLIST)) == 0 && + mem_comp((char*)pPacket->m_pData+sizeof(VERSIONSRV_DDNETLIST), m_aDDNetSrvListToken, 4) == 0) + { + // reset random token + m_DDNetSrvListTokenSet = false; + int CompLength = *(short*)((char*)pPacket->m_pData+(sizeof(VERSIONSRV_DDNETLIST)+4)); + int PlainLength = *(short*)((char*)pPacket->m_pData+(sizeof(VERSIONSRV_DDNETLIST)+6)); + + if (pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_DDNETLIST) + 8 + CompLength)) + { + char aBuf[16384]; + uLongf DstLen = sizeof(aBuf); + const char *pComp = (char*)pPacket->m_pData+sizeof(VERSIONSRV_DDNETLIST)+8; + + // do decompression of serverlist + if (uncompress((Bytef*)aBuf, &DstLen, (Bytef*)pComp, CompLength) == Z_OK && (int)DstLen == PlainLength) + { + bool ListChanged = true; + + IOHANDLE File = m_pStorage->OpenFile("ddnet-servers.json", IOFLAG_READ, IStorage::TYPE_SAVE); + if (File) + { + char aBuf2[16384]; + io_read(File, aBuf2, sizeof(aBuf2)); + io_close(File); + if (str_comp(aBuf, aBuf2) == 0) + ListChanged = false; + } + + // decompression successful, write plain file + if (ListChanged) + { + IOHANDLE File = m_pStorage->OpenFile("ddnet-servers.json", IOFLAG_WRITE, IStorage::TYPE_SAVE); + if (File) + { + io_write(File, aBuf, PlainLength); + io_close(File); + } + if(g_Config.m_UiPage == CMenus::PAGE_DDNET) + m_ServerBrowser.Refresh(IServerBrowser::TYPE_DDNET); + } + } + } + } + + // map version list + if(pPacket->m_DataSize >= (int)sizeof(VERSIONSRV_MAPLIST) && + mem_comp(pPacket->m_pData, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)) == 0) + { + int Size = pPacket->m_DataSize-sizeof(VERSIONSRV_MAPLIST); + int Num = Size/sizeof(CMapVersion); + m_MapChecker.AddMaplist((CMapVersion *)((char*)pPacket->m_pData+sizeof(VERSIONSRV_MAPLIST)), Num); + } + } + + //server count from master server + if(pPacket->m_DataSize == (int) sizeof(SERVERBROWSE_COUNT) + 2 && mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) + { + unsigned char *pP = (unsigned char*) pPacket->m_pData; + pP += sizeof(SERVERBROWSE_COUNT); + int ServerCount = ((*pP)<<8) | *(pP+1); + int ServerID = -1; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + NETADDR tmp = m_pMasterServer->GetAddr(i); + if(net_addr_comp(&pPacket->m_Address, &tmp) == 0) + { + ServerID = i; + break; + } + } + if(ServerCount > -1 && ServerID != -1) + { + m_pMasterServer->SetCount(ServerID, ServerCount); + if(g_Config.m_Debug) + dbg_msg("MasterCount", "Server %d got %d servers", ServerID, ServerCount); + } + } + // server list from master server + if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_LIST) && + mem_comp(pPacket->m_pData, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)) == 0) + { + // check for valid master server address + bool Valid = false; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; ++i) + { + if(m_pMasterServer->IsValid(i)) + { + NETADDR Addr = m_pMasterServer->GetAddr(i); + if(net_addr_comp(&pPacket->m_Address, &Addr) == 0) + { + Valid = true; + break; + } + } + } + if(!Valid) + return; + + int Size = pPacket->m_DataSize-sizeof(SERVERBROWSE_LIST); + int Num = Size/sizeof(CMastersrvAddr); + CMastersrvAddr *pAddrs = (CMastersrvAddr *)((char*)pPacket->m_pData+sizeof(SERVERBROWSE_LIST)); + for(int i = 0; i < Num; i++) + { + NETADDR Addr; + + static unsigned char IPV4Mapping[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF }; + + // copy address + if(!mem_comp(IPV4Mapping, pAddrs[i].m_aIp, sizeof(IPV4Mapping))) + { + mem_zero(&Addr, sizeof(Addr)); + Addr.type = NETTYPE_IPV4; + Addr.ip[0] = pAddrs[i].m_aIp[12]; + Addr.ip[1] = pAddrs[i].m_aIp[13]; + Addr.ip[2] = pAddrs[i].m_aIp[14]; + Addr.ip[3] = pAddrs[i].m_aIp[15]; + } + else + { + Addr.type = NETTYPE_IPV6; + 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); + } + } + + // server info + if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_INFO) && mem_comp(pPacket->m_pData, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0) + { + // we got ze info + CUnpacker Up; + CServerInfo Info = {0}; + + CServerBrowser::CServerEntry *pEntry = m_ServerBrowser.Find(pPacket->m_Address); + // Don't add info if we already got info64 + if(pEntry && pEntry->m_Info.m_MaxClients > VANILLA_MAX_CLIENTS) + return; + + 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)); + str_copy(Info.m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aName)); + str_copy(Info.m_aMap, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aMap)); + str_copy(Info.m_aGameType, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aGameType)); + Info.m_Flags = str_toint(Up.GetString()); + Info.m_NumPlayers = str_toint(Up.GetString()); + Info.m_MaxPlayers = str_toint(Up.GetString()); + Info.m_NumClients = str_toint(Up.GetString()); + Info.m_MaxClients = str_toint(Up.GetString()); + + // don't add invalid info to the server browser list + if(Info.m_NumClients < 0 || Info.m_NumClients > MAX_CLIENTS || Info.m_MaxClients < 0 || Info.m_MaxClients > MAX_CLIENTS || + Info.m_NumPlayers < 0 || Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers < 0 || Info.m_MaxPlayers > Info.m_MaxClients) + return; + + net_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress), true); + + for(int i = 0; i < Info.m_NumClients; i++) + { + str_copy(Info.m_aClients[i].m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aName)); + str_copy(Info.m_aClients[i].m_aClan, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aClan)); + Info.m_aClients[i].m_Country = str_toint(Up.GetString()); + Info.m_aClients[i].m_Score = str_toint(Up.GetString()); + Info.m_aClients[i].m_Player = str_toint(Up.GetString()) != 0 ? true : false; + } + + if(!Up.Error()) + { + // sort players + qsort(Info.m_aClients, Info.m_NumClients, sizeof(*Info.m_aClients), PlayerScoreNameComp); + + pEntry = m_ServerBrowser.Find(pPacket->m_Address); + if (!pEntry || !pEntry->m_GotInfo) + m_ServerBrowser.Set(pPacket->m_Address, IServerBrowser::SET_TOKEN, Token, &Info); + + if(net_addr_comp(&m_ServerAddress, &pPacket->m_Address) == 0) + { + if(m_CurrentServerInfo.m_MaxClients <= VANILLA_MAX_CLIENTS) + { + mem_copy(&m_CurrentServerInfo, &Info, sizeof(m_CurrentServerInfo)); + m_CurrentServerInfo.m_NetAddr = m_ServerAddress; + m_CurrentServerInfoRequestTime = -1; + } + } + + if (Is64Player(&Info)) + { + pEntry = m_ServerBrowser.Find(pPacket->m_Address); + if (pEntry) + { + pEntry->m_Is64 = true; + m_ServerBrowser.RequestImpl64(pEntry->m_Addr, pEntry); // Force a quick update + //m_ServerBrowser.QueueRequest(pEntry); + } + } + } + } + + // server info 64 + if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_INFO64) && mem_comp(pPacket->m_pData, SERVERBROWSE_INFO64, sizeof(SERVERBROWSE_INFO64)) == 0) + { + // we got ze info + CUnpacker Up; + CServerInfo NewInfo = {0}; + CServerBrowser::CServerEntry *pEntry = m_ServerBrowser.Find(pPacket->m_Address); + CServerInfo &Info = NewInfo; + + if (pEntry) + Info = pEntry->m_Info; + + Up.Reset((unsigned char*)pPacket->m_pData+sizeof(SERVERBROWSE_INFO64), pPacket->m_DataSize-sizeof(SERVERBROWSE_INFO64)); + int Token = str_toint(Up.GetString()); + str_copy(Info.m_aVersion, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aVersion)); + str_copy(Info.m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aName)); + str_copy(Info.m_aMap, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aMap)); + str_copy(Info.m_aGameType, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aGameType)); + Info.m_Flags = str_toint(Up.GetString()); + Info.m_NumPlayers = str_toint(Up.GetString()); + Info.m_MaxPlayers = str_toint(Up.GetString()); + Info.m_NumClients = str_toint(Up.GetString()); + Info.m_MaxClients = str_toint(Up.GetString()); + + // don't add invalid info to the server browser list + if(Info.m_NumClients < 0 || Info.m_NumClients > MAX_CLIENTS || Info.m_MaxClients < 0 || Info.m_MaxClients > MAX_CLIENTS || + Info.m_NumPlayers < 0 || Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers < 0 || Info.m_MaxPlayers > Info.m_MaxClients) + return; + + net_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress), true); + + int Offset = Up.GetInt(); + + for(int i = max(Offset, 0); i < max(Offset, 0) + 24 && i < MAX_CLIENTS; i++) + { + str_copy(Info.m_aClients[i].m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aName)); + str_copy(Info.m_aClients[i].m_aClan, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aClan)); + Info.m_aClients[i].m_Country = str_toint(Up.GetString()); + Info.m_aClients[i].m_Score = str_toint(Up.GetString()); + Info.m_aClients[i].m_Player = str_toint(Up.GetString()) != 0 ? true : false; + } + + if(!Up.Error()) + { + // sort players + if (Offset + 24 >= Info.m_NumClients) + qsort(Info.m_aClients, Info.m_NumClients, sizeof(*Info.m_aClients), PlayerScoreNameComp); + + m_ServerBrowser.Set(pPacket->m_Address, IServerBrowser::SET_TOKEN, Token, &Info); + + if(net_addr_comp(&m_ServerAddress, &pPacket->m_Address) == 0) + { + mem_copy(&m_CurrentServerInfo, &Info, sizeof(m_CurrentServerInfo)); + m_CurrentServerInfo.m_NetAddr = m_ServerAddress; + m_CurrentServerInfoRequestTime = -1; + } + } + } +} + +void CClient::ProcessServerPacket(CNetChunk *pPacket) +{ + 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 + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_MAP_CHANGE) + { + const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES); + int MapCrc = Unpacker.GetInt(); + int MapSize = Unpacker.GetInt(); + const char *pError = 0; + + if(Unpacker.Error()) + return; + + if(m_DummyConnected) + DummyDisconnect(0); + + // check for valid standard map + if(!m_MapChecker.IsMapValid(pMap, MapCrc, MapSize)) + pError = "invalid standard map"; + + for(int i = 0; pMap[i]; i++) // protect the player from nasty map names + { + if(pMap[i] == '/' || pMap[i] == '\\') + pError = "strange character in map name"; + } + + if(MapSize < 0) + pError = "invalid map size"; + + if(pError) + DisconnectWithReason(pError); + else + { + pError = LoadMapSearch(pMap, MapCrc); + + if(!pError) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "loading done"); + SendReady(); + } + else + { + str_format(m_aMapdownloadFilename, sizeof(m_aMapdownloadFilename), "downloadedmaps/%s_%08x.map", pMap, MapCrc); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "starting to download map to '%s'", m_aMapdownloadFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", aBuf); + + m_MapdownloadChunk = 0; + str_copy(m_aMapdownloadName, pMap, sizeof(m_aMapdownloadName)); + + m_MapdownloadCrc = MapCrc; + m_MapdownloadTotalsize = MapSize; + m_MapdownloadAmount = 0; + + ResetMapDownload(); + + if(g_Config.m_ClHttpMapDownload) + { + char aUrl[256]; + char aFilename[64]; + char aEscaped[128]; + str_format(aFilename, sizeof(aFilename), "%s_%08x.map", pMap, MapCrc); + Fetcher()->Escape(aEscaped, sizeof(aEscaped), aFilename); + str_format(aUrl, sizeof(aUrl), "http://%s/%s", g_Config.m_ClDDNetMapServer, aEscaped); + m_pMapdownloadTask = new CFetchTask(true); + Fetcher()->QueueAdd(m_pMapdownloadTask, aUrl, m_aMapdownloadFilename, IStorage::TYPE_SAVE); + } + else + SendMapRequest(); + } + } + } + else if(Msg == NETMSG_MAP_DATA) + { + int Last = Unpacker.GetInt(); + int MapCRC = Unpacker.GetInt(); + int Chunk = Unpacker.GetInt(); + int Size = Unpacker.GetInt(); + const unsigned char *pData = Unpacker.GetRaw(Size); + + // check for errors + if(Unpacker.Error() || Size <= 0 || MapCRC != m_MapdownloadCrc || Chunk != m_MapdownloadChunk || !m_MapdownloadFile) + return; + + io_write(m_MapdownloadFile, pData, Size); + + m_MapdownloadAmount += Size; + + if(Last) + { + if(m_MapdownloadFile) + io_close(m_MapdownloadFile); + FinishMapDownload(); + } + else + { + // request new chunk + m_MapdownloadChunk++; + + CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA); + Msg.AddInt(m_MapdownloadChunk); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); + + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "requested chunk %d", m_MapdownloadChunk); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client/network", aBuf); + } + } + } + else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_CON_READY) + { + GameClient()->OnConnected(); + } + else if(Msg == NETMSG_PING) + { + CMsgPacker Msg(NETMSG_PING_REPLY); + SendMsgEx(&Msg, 0); + } + else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_ADD) + { + const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); + const char *pHelp = Unpacker.GetString(CUnpacker::SANITIZE_CC); + const char *pParams = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(Unpacker.Error() == 0) + m_pConsole->RegisterTemp(pName, pParams, CFGFLAG_SERVER, pHelp); + } + else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_CMD_REM) + { + const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(Unpacker.Error() == 0) + m_pConsole->DeregisterTemp(pName); + } + else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_AUTH_STATUS) + { + int Result = Unpacker.GetInt(); + if(Unpacker.Error() == 0) + m_RconAuthed[g_Config.m_ClDummy] = Result; + int Old = m_UseTempRconCommands; + m_UseTempRconCommands = Unpacker.GetInt(); + if(Unpacker.Error() != 0) + m_UseTempRconCommands = 0; + if(Old != 0 && m_UseTempRconCommands == 0) + m_pConsole->DeregisterTempAll(); + } + else if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Msg == NETMSG_RCON_LINE) + { + const char *pLine = Unpacker.GetString(); + if(Unpacker.Error() == 0) + GameClient()->OnRconLine(pLine); + } + else if(Msg == NETMSG_PING_REPLY) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "latency %.2f", (time_get() - m_PingStartTime)*1000 / (float)time_freq()); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client/network", aBuf); + } + else if(Msg == NETMSG_INPUTTIMING) + { + int InputPredTick = Unpacker.GetInt(); + int TimeLeft = Unpacker.GetInt(); + int64 Now = time_get(); + + // adjust our prediction time + int64 Target = 0; + for(int k = 0; k < 200; k++) + { + if(m_aInputs[g_Config.m_ClDummy][k].m_Tick == InputPredTick) + { + Target = m_aInputs[g_Config.m_ClDummy][k].m_PredictedTime + (Now - m_aInputs[g_Config.m_ClDummy][k].m_Time); + Target = Target - (int64)(((TimeLeft-PREDICTION_MARGIN)/1000.0f)*time_freq()); + break; + } + } + + if(Target) + m_PredictedTime.Update(&m_InputtimeMarginGraph, Target, TimeLeft, 1); + } + else if(Msg == NETMSG_SNAP || Msg == NETMSG_SNAPSINGLE || Msg == NETMSG_SNAPEMPTY) + { + int NumParts = 1; + int Part = 0; + int GameTick = Unpacker.GetInt(); + int DeltaTick = GameTick-Unpacker.GetInt(); + int PartSize = 0; + int Crc = 0; + int CompleteSize = 0; + const char *pData = 0; + + // only allow packets from the server we actually want + if(net_addr_comp(&pPacket->m_Address, &m_ServerAddress)) + return; + + // we are not allowed to process snapshot yet + if(State() < IClient::STATE_LOADING) + return; + + if(Msg == NETMSG_SNAP) + { + NumParts = Unpacker.GetInt(); + Part = Unpacker.GetInt(); + } + + if(Msg != NETMSG_SNAPEMPTY) + { + Crc = Unpacker.GetInt(); + PartSize = Unpacker.GetInt(); + } + + pData = (const char *)Unpacker.GetRaw(PartSize); + + if(Unpacker.Error()) + return; + + if(GameTick >= m_CurrentRecvTick[g_Config.m_ClDummy]) + { + if(GameTick != m_CurrentRecvTick[g_Config.m_ClDummy]) + { + m_SnapshotParts = 0; + m_CurrentRecvTick[g_Config.m_ClDummy] = GameTick; + } + + // TODO: clean this up abit + mem_copy((char*)m_aSnapshotIncomingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, PartSize); + m_SnapshotParts |= 1<<Part; + + if(m_SnapshotParts == (unsigned)((1<<NumParts)-1)) + { + static CSnapshot Emptysnap; + CSnapshot *pDeltaShot = &Emptysnap; + int PurgeTick; + void *pDeltaData; + int DeltaSize; + unsigned char aTmpBuffer2[CSnapshot::MAX_SIZE]; + unsigned char aTmpBuffer3[CSnapshot::MAX_SIZE]; + CSnapshot *pTmpBuffer3 = (CSnapshot*)aTmpBuffer3; // Fix compiler warning for strict-aliasing + int SnapSize; + + CompleteSize = (NumParts-1) * MAX_SNAPSHOT_PACKSIZE + PartSize; + + // reset snapshoting + m_SnapshotParts = 0; + + // find snapshot that we should use as delta + Emptysnap.Clear(); + + // find delta + if(DeltaTick >= 0) + { + int DeltashotSize = m_SnapshotStorage[g_Config.m_ClDummy].Get(DeltaTick, 0, &pDeltaShot, 0); + + if(DeltashotSize < 0) + { + // couldn't find the delta snapshots that the server used + // to compress this snapshot. force the server to resync + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "error, couldn't find the delta snapshot"); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + + // ack snapshot + // TODO: combine this with the input message + m_AckGameTick[g_Config.m_ClDummy] = -1; + return; + } + } + + // decompress snapshot + pDeltaData = m_SnapshotDelta.EmptyDelta(); + DeltaSize = sizeof(int)*3; + + if(CompleteSize) + { + int IntSize = CVariableInt::Decompress(m_aSnapshotIncomingData, CompleteSize, aTmpBuffer2); + + if(IntSize < 0) // failure during decompression, bail + return; + + pDeltaData = aTmpBuffer2; + DeltaSize = IntSize; + } + + // unpack delta + SnapSize = m_SnapshotDelta.UnpackDelta(pDeltaShot, pTmpBuffer3, pDeltaData, DeltaSize); + if(SnapSize < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "delta unpack failed!"); + return; + } + + if(Msg != NETMSG_SNAPEMPTY && pTmpBuffer3->Crc() != Crc) + { + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "snapshot crc error #%d - tick=%d wantedcrc=%d gotcrc=%d compressed_size=%d delta_tick=%d", + m_SnapCrcErrors, GameTick, Crc, pTmpBuffer3->Crc(), CompleteSize, DeltaTick); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + + m_SnapCrcErrors++; + if(m_SnapCrcErrors > 10) + { + // to many errors, send reset + m_AckGameTick[g_Config.m_ClDummy] = -1; + SendInput(); + m_SnapCrcErrors = 0; + } + return; + } + else + { + if(m_SnapCrcErrors) + m_SnapCrcErrors--; + } + + // purge old snapshots + PurgeTick = DeltaTick; + if(m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] && m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick < PurgeTick) + PurgeTick = m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick; + if(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] && m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick < PurgeTick) + PurgeTick = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick; + m_SnapshotStorage[g_Config.m_ClDummy].PurgeUntil(PurgeTick); + + // add new + m_SnapshotStorage[g_Config.m_ClDummy].Add(GameTick, time_get(), SnapSize, pTmpBuffer3, 1); + + // for antiping: if the projectile netobjects from the server contains extra data, this is removed and the original content restored before recording demo + unsigned char aExtraInfoRemoved[CSnapshot::MAX_SIZE]; + mem_copy(aExtraInfoRemoved, pTmpBuffer3, SnapSize); + CServerInfo Info; + GetServerInfo(&Info); + if(IsDDNet(&Info)) + SnapshotRemoveExtraInfo(aExtraInfoRemoved); + + // add snapshot to demo + for(int i = 0; i < RECORDER_MAX; i++) + { + if(m_DemoRecorder[i].IsRecording()) + { + // write snapshot + m_DemoRecorder[i].RecordSnapshot(GameTick, aExtraInfoRemoved, SnapSize); + } + } + + // apply snapshot, cycle pointers + m_ReceivedSnapshots[g_Config.m_ClDummy]++; + + m_CurrentRecvTick[g_Config.m_ClDummy] = GameTick; + + // we got two snapshots until we see us self as connected + if(m_ReceivedSnapshots[g_Config.m_ClDummy] == 2) + { + // start at 200ms and work from there + m_PredictedTime.Init(GameTick*time_freq()/50); + m_PredictedTime.SetAdjustSpeed(1, 1000.0f); + m_GameTime[g_Config.m_ClDummy].Init((GameTick-1)*time_freq()/50); + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = m_SnapshotStorage[g_Config.m_ClDummy].m_pFirst; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = m_SnapshotStorage[g_Config.m_ClDummy].m_pLast; + m_LocalStartTime = time_get(); + SetState(IClient::STATE_ONLINE); + DemoRecorder_HandleAutoStart(); + } + + // adjust game time + if(m_ReceivedSnapshots[g_Config.m_ClDummy] > 2) + { + int64 Now = m_GameTime[g_Config.m_ClDummy].Get(time_get()); + int64 TickStart = GameTick*time_freq()/50; + int64 TimeLeft = (TickStart-Now)*1000 / time_freq(); + m_GameTime[g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0); + } + + if(m_ReceivedSnapshots[g_Config.m_ClDummy] > 50 && !m_TimeoutCodeSent[g_Config.m_ClDummy]) + { + if(IsDDNet(&m_CurrentServerInfo)) + { + m_TimeoutCodeSent[g_Config.m_ClDummy] = true; + CNetMsg_Cl_Say Msg; + Msg.m_Team = 0; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "/timeout %s", g_Config.m_ClDummy ? g_Config.m_ClDummyTimeoutCode : g_Config.m_ClTimeoutCode); + Msg.m_pMessage = aBuf; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + SendMsgExY(&Packer, MSGFLAG_VITAL, false, g_Config.m_ClDummy); + } + } + + // ack snapshot + m_AckGameTick[g_Config.m_ClDummy] = GameTick; + } + } + } + } + else + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 || Msg == NETMSGTYPE_SV_EXTRAPROJECTILE) + { + // game message + for(int i = 0; i < RECORDER_MAX; i++) + if(m_DemoRecorder[i].IsRecording()) + m_DemoRecorder[i].RecordMessage(pPacket->m_pData, pPacket->m_DataSize); + + GameClient()->OnMessage(Msg, &Unpacker); + } + } +} + +void CClient::ProcessServerPacketDummy(CNetChunk *pPacket) +{ + 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) + { + if(Msg == NETMSG_CON_READY) + { + m_DummyConnected = true; + g_Config.m_ClDummy = 1; + Rcon("crashmeplx"); + if(m_RconAuthed[0]) + RconAuth("", m_RconPassword); + } + else if(Msg == NETMSG_SNAP || Msg == NETMSG_SNAPSINGLE || Msg == NETMSG_SNAPEMPTY) + { + int NumParts = 1; + int Part = 0; + int GameTick = Unpacker.GetInt(); + int DeltaTick = GameTick-Unpacker.GetInt(); + int PartSize = 0; + int Crc = 0; + int CompleteSize = 0; + const char *pData = 0; + + // only allow packets from the server we actually want + if(net_addr_comp(&pPacket->m_Address, &m_ServerAddress)) + return; + + // we are not allowed to process snapshot yet + if(State() < IClient::STATE_LOADING) + return; + + if(Msg == NETMSG_SNAP) + { + NumParts = Unpacker.GetInt(); + Part = Unpacker.GetInt(); + } + + if(Msg != NETMSG_SNAPEMPTY) + { + Crc = Unpacker.GetInt(); + PartSize = Unpacker.GetInt(); + } + + pData = (const char *)Unpacker.GetRaw(PartSize); + + if(Unpacker.Error()) + return; + + if(GameTick >= m_CurrentRecvTick[!g_Config.m_ClDummy]) + { + if(GameTick != m_CurrentRecvTick[!g_Config.m_ClDummy]) + { + m_SnapshotParts = 0; + m_CurrentRecvTick[!g_Config.m_ClDummy] = GameTick; + } + + // TODO: clean this up abit + mem_copy((char*)m_aSnapshotIncomingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, PartSize); + m_SnapshotParts |= 1<<Part; + + if(m_SnapshotParts == (unsigned)((1<<NumParts)-1)) + { + static CSnapshot Emptysnap; + CSnapshot *pDeltaShot = &Emptysnap; + int PurgeTick; + void *pDeltaData; + int DeltaSize; + unsigned char aTmpBuffer2[CSnapshot::MAX_SIZE]; + unsigned char aTmpBuffer3[CSnapshot::MAX_SIZE]; + CSnapshot *pTmpBuffer3 = (CSnapshot*)aTmpBuffer3; // Fix compiler warning for strict-aliasing + int SnapSize; + + CompleteSize = (NumParts-1) * MAX_SNAPSHOT_PACKSIZE + PartSize; + + // reset snapshoting + m_SnapshotParts = 0; + + // find snapshot that we should use as delta + Emptysnap.Clear(); + + // find delta + if(DeltaTick >= 0) + { + int DeltashotSize = m_SnapshotStorage[!g_Config.m_ClDummy].Get(DeltaTick, 0, &pDeltaShot, 0); + + if(DeltashotSize < 0) + { + // couldn't find the delta snapshots that the server used + // to compress this snapshot. force the server to resync + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "error, couldn't find the delta snapshot"); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + + // ack snapshot + // TODO: combine this with the input message + m_AckGameTick[!g_Config.m_ClDummy] = -1; + return; + } + } + + // decompress snapshot + pDeltaData = m_SnapshotDelta.EmptyDelta(); + DeltaSize = sizeof(int)*3; + + if(CompleteSize) + { + int IntSize = CVariableInt::Decompress(m_aSnapshotIncomingData, CompleteSize, aTmpBuffer2); + + if(IntSize < 0) // failure during decompression, bail + return; + + pDeltaData = aTmpBuffer2; + DeltaSize = IntSize; + } + + // unpack delta + SnapSize = m_SnapshotDelta.UnpackDelta(pDeltaShot, pTmpBuffer3, pDeltaData, DeltaSize); + if(SnapSize < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "delta unpack failed!"); + return; + } + + if(Msg != NETMSG_SNAPEMPTY && pTmpBuffer3->Crc() != Crc) + { + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "snapshot crc error #%d - tick=%d wantedcrc=%d gotcrc=%d compressed_size=%d delta_tick=%d", + m_SnapCrcErrors, GameTick, Crc, pTmpBuffer3->Crc(), CompleteSize, DeltaTick); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + + m_SnapCrcErrors++; + if(m_SnapCrcErrors > 10) + { + // to many errors, send reset + m_AckGameTick[!g_Config.m_ClDummy] = -1; + SendInput(); + m_SnapCrcErrors = 0; + } + return; + } + else + { + if(m_SnapCrcErrors) + m_SnapCrcErrors--; + } + + // purge old snapshots + PurgeTick = DeltaTick; + if(m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV] && m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV]->m_Tick < PurgeTick) + PurgeTick = m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV]->m_Tick; + if(m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT] && m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick < PurgeTick) + PurgeTick = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick; + m_SnapshotStorage[!g_Config.m_ClDummy].PurgeUntil(PurgeTick); + + // add new + m_SnapshotStorage[!g_Config.m_ClDummy].Add(GameTick, time_get(), SnapSize, pTmpBuffer3, 1); + + // apply snapshot, cycle pointers + m_ReceivedSnapshots[!g_Config.m_ClDummy]++; + + m_CurrentRecvTick[!g_Config.m_ClDummy] = GameTick; + + // we got two snapshots until we see us self as connected + if(m_ReceivedSnapshots[!g_Config.m_ClDummy] == 2) + { + // start at 200ms and work from there + //m_PredictedTime[!g_Config.m_ClDummy].Init(GameTick*time_freq()/50); + //m_PredictedTime[!g_Config.m_ClDummy].SetAdjustSpeed(1, 1000.0f); + m_GameTime[!g_Config.m_ClDummy].Init((GameTick-1)*time_freq()/50); + m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV] = m_SnapshotStorage[!g_Config.m_ClDummy].m_pFirst; + m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT] = m_SnapshotStorage[!g_Config.m_ClDummy].m_pLast; + m_LocalStartTime = time_get(); + SetState(IClient::STATE_ONLINE); + } + + // adjust game time + if(m_ReceivedSnapshots[!g_Config.m_ClDummy] > 2) + { + int64 Now = m_GameTime[!g_Config.m_ClDummy].Get(time_get()); + int64 TickStart = GameTick*time_freq()/50; + int64 TimeLeft = (TickStart-Now)*1000 / time_freq(); + m_GameTime[!g_Config.m_ClDummy].Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0); + } + + // ack snapshot + m_AckGameTick[!g_Config.m_ClDummy] = GameTick; + } + } + } + } + else + { + GameClient()->OnMessage(Msg, &Unpacker, 1); + } +} + +void CClient::ResetMapDownload() +{ + if(m_pMapdownloadTask){ + delete m_pMapdownloadTask; + m_pMapdownloadTask = NULL; + } + m_MapdownloadFile = 0; + m_MapdownloadAmount = 0; +} + +void CClient::FinishMapDownload() +{ + const char *pError; + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "download complete, loading map"); + + int prev = m_MapdownloadTotalsize; + m_MapdownloadTotalsize = -1; + + // load map + pError = LoadMap(m_aMapdownloadName, m_aMapdownloadFilename, m_MapdownloadCrc); + if(!pError) + { + ResetMapDownload(); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "loading done"); + SendReady(); + } + else if(m_pMapdownloadTask) + { + ResetMapDownload(); + m_MapdownloadTotalsize = prev; + SendMapRequest(); + } + else{ + if(m_MapdownloadFile) + io_close(m_MapdownloadFile); + ResetMapDownload(); + DisconnectWithReason(pError); + } +} + +void CClient::PumpNetwork() +{ + for(int i=0; i<3; i++) + { + m_NetClient[i].Update(); + } + + if(State() != IClient::STATE_DEMOPLAYBACK) + { + // check for errors + if(State() != IClient::STATE_OFFLINE && State() != IClient::STATE_QUITING && m_NetClient[0].State() == NETSTATE_OFFLINE) + { + SetState(IClient::STATE_OFFLINE); + Disconnect(); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "offline error='%s'", m_NetClient[0].ErrorString()); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + } + + // + if(State() == IClient::STATE_CONNECTING && m_NetClient[0].State() == NETSTATE_ONLINE) + { + // we switched to online + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", "connected, sending info"); + SetState(IClient::STATE_LOADING); + SendInfo(); + } + } + + // process packets + CNetChunk Packet; + for(int i=0; i < 3; i++) + { + while(m_NetClient[i].Recv(&Packet)) + { + if(Packet.m_ClientID == -1 || i > 1) + { + ProcessConnlessPacket(&Packet); + } + else if(i > 0 && i < 2) + { + if(g_Config.m_ClDummy) + ProcessServerPacket(&Packet); //self + else + ProcessServerPacketDummy(&Packet); //multiclient + } + else + { + if(g_Config.m_ClDummy) + ProcessServerPacketDummy(&Packet); //multiclient + else + ProcessServerPacket(&Packet); //self + } + } + } +} + +void CClient::OnDemoPlayerSnapshot(void *pData, int Size) +{ + // update ticks, they could have changed + const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); + CSnapshotStorage::CHolder *pTemp; + m_CurGameTick[g_Config.m_ClDummy] = pInfo->m_Info.m_CurrentTick; + m_PrevGameTick[g_Config.m_ClDummy] = pInfo->m_PreviousTick; + + // handle snapshots + pTemp = m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = pTemp; + + mem_copy(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pSnap, pData, Size); + mem_copy(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pAltSnap, pData, Size); + + GameClient()->OnNewSnapshot(); +} + +void CClient::OnDemoPlayerMessage(void *pData, int Size) +{ + CUnpacker Unpacker; + Unpacker.Reset(pData, Size); + + // unpack msgid and system flag + int Msg = Unpacker.GetInt(); + int Sys = Msg&1; + Msg >>= 1; + + if(Unpacker.Error()) + return; + + if(!Sys) + GameClient()->OnMessage(Msg, &Unpacker); +} +/* +const IDemoPlayer::CInfo *client_demoplayer_getinfo() +{ + static DEMOPLAYBACK_INFO ret; + const DEMOREC_PLAYBACKINFO *info = m_DemoPlayer.Info(); + ret.first_tick = info->first_tick; + ret.last_tick = info->last_tick; + ret.current_tick = info->current_tick; + ret.paused = info->paused; + ret.speed = info->speed; + return &ret; +}*/ + +/* +void DemoPlayer()->SetPos(float percent) +{ + demorec_playback_set(percent); +} + +void DemoPlayer()->SetSpeed(float speed) +{ + demorec_playback_setspeed(speed); +} + +void DemoPlayer()->SetPause(int paused) +{ + if(paused) + demorec_playback_pause(); + else + demorec_playback_unpause(); +}*/ + +void CClient::Update() +{ + if(State() == IClient::STATE_DEMOPLAYBACK) + { + m_DemoPlayer.Update(); + if(m_DemoPlayer.IsPlaying()) + { + // update timers + const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); + m_CurGameTick[g_Config.m_ClDummy] = pInfo->m_Info.m_CurrentTick; + m_PrevGameTick[g_Config.m_ClDummy] = pInfo->m_PreviousTick; + m_GameIntraTick[g_Config.m_ClDummy] = pInfo->m_IntraTick; + m_GameTickTime[g_Config.m_ClDummy] = pInfo->m_TickTime; + } + else + { + // disconnect on error + Disconnect(); + } + } + else if(State() == IClient::STATE_ONLINE && m_ReceivedSnapshots[g_Config.m_ClDummy] >= 3) + { + if(m_ReceivedSnapshots[!g_Config.m_ClDummy] >= 3) + { + // switch dummy snapshot + int64 Now = m_GameTime[!g_Config.m_ClDummy].Get(time_get()); + while(1) + { + CSnapshotStorage::CHolder *pCur = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]; + int64 TickStart = (pCur->m_Tick)*time_freq()/50; + + if(TickStart < Now) + { + CSnapshotStorage::CHolder *pNext = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext; + if(pNext) + { + m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV] = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]; + m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT] = pNext; + + // set ticks + m_CurGameTick[!g_Config.m_ClDummy] = m_aSnapshots[!g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick; + m_PrevGameTick[!g_Config.m_ClDummy] = m_aSnapshots[!g_Config.m_ClDummy][SNAP_PREV]->m_Tick; + } + else + break; + } + else + break; + } + } + + // switch snapshot + int Repredict = 0; + int64 Freq = time_freq(); + int64 Now = m_GameTime[g_Config.m_ClDummy].Get(time_get()); + int64 PredNow = m_PredictedTime.Get(time_get()); + + while(1) + { + CSnapshotStorage::CHolder *pCur = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]; + int64 TickStart = (pCur->m_Tick)*time_freq()/50; + + if(TickStart < Now) + { + CSnapshotStorage::CHolder *pNext = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pNext; + if(pNext) + { + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = pNext; + + // set ticks + m_CurGameTick[g_Config.m_ClDummy] = m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick; + m_PrevGameTick[g_Config.m_ClDummy] = m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick; + + if (m_LastDummy2 == (bool)g_Config.m_ClDummy && m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] && m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]) + { + GameClient()->OnNewSnapshot(); + Repredict = 1; + } + } + else + break; + } + else + break; + } + + if (m_LastDummy2 != (bool)g_Config.m_ClDummy) + { + m_LastDummy2 = g_Config.m_ClDummy; + } + + if(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] && m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]) + { + int64 CurtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick)*time_freq()/50; + int64 PrevtickStart = (m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick)*time_freq()/50; + int PrevPredTick = (int)(PredNow*50/time_freq()); + int NewPredTick = PrevPredTick+1; + + m_GameIntraTick[g_Config.m_ClDummy] = (Now - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + m_GameTickTime[g_Config.m_ClDummy] = (Now - PrevtickStart) / (float)Freq; //(float)SERVER_TICK_SPEED); + + CurtickStart = NewPredTick*time_freq()/50; + PrevtickStart = PrevPredTick*time_freq()/50; + m_PredIntraTick[g_Config.m_ClDummy] = (PredNow - PrevtickStart) / (float)(CurtickStart-PrevtickStart); + + if(NewPredTick < m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick-SERVER_TICK_SPEED || NewPredTick > m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick+SERVER_TICK_SPEED) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "prediction time reset!"); + m_PredictedTime.Init(m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick*time_freq()/50); + } + + if(NewPredTick > m_PredTick[g_Config.m_ClDummy]) + { + m_PredTick[g_Config.m_ClDummy] = NewPredTick; + Repredict = 1; + + // send input + SendInput(); + } + } + + // only do sane predictions + if(Repredict) + { + if(m_PredTick[g_Config.m_ClDummy] > m_CurGameTick[g_Config.m_ClDummy] && m_PredTick[g_Config.m_ClDummy] < m_CurGameTick[g_Config.m_ClDummy]+50) + GameClient()->OnPredict(); + } + + // fetch server info if we don't have it + if(State() >= IClient::STATE_LOADING && + m_CurrentServerInfoRequestTime >= 0 && + time_get() > m_CurrentServerInfoRequestTime) + { + m_ServerBrowser.Request(m_ServerAddress); + m_CurrentServerInfoRequestTime = time_get()+time_freq()*2; + } + } + + // STRESS TEST: join the server again + if(g_Config.m_DbgStress) + { + static int64 ActionTaken = 0; + int64 Now = time_get(); + if(State() == IClient::STATE_OFFLINE) + { + if(Now > ActionTaken+time_freq()*2) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "reconnecting!"); + Connect(g_Config.m_DbgStressServer); + ActionTaken = Now; + } + } + else + { + if(Now > ActionTaken+time_freq()*(10+g_Config.m_DbgStress)) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "disconnecting!"); + Disconnect(); + ActionTaken = Now; + } + } + } + + // pump the network + PumpNetwork(); + if(m_pMapdownloadTask) + { + if(m_pMapdownloadTask->State() == CFetchTask::STATE_DONE) + FinishMapDownload(); + else if(m_pMapdownloadTask->State() == CFetchTask::STATE_ERROR) + { + dbg_msg("webdl", "HTTP failed falling back to gameserver."); + ResetMapDownload(); + SendMapRequest(); + } + else if(m_pMapdownloadTask->State() == CFetchTask::STATE_ABORTED) + { + delete m_pMapdownloadTask; + m_pMapdownloadTask = 0; + } + } + + + // update the maser server registry + MasterServer()->Update(); + + // update the server browser + m_ServerBrowser.Update(m_ResortServerBrowser); + m_ResortServerBrowser = false; +} + +void CClient::VersionUpdate() +{ + if(m_VersionInfo.m_State == CVersionInfo::STATE_INIT) + { + Engine()->HostLookup(&m_VersionInfo.m_VersionServeraddr, g_Config.m_ClDDNetVersionServer, m_NetClient[0].NetType()); + m_VersionInfo.m_State = CVersionInfo::STATE_START; + } + else if(m_VersionInfo.m_State == CVersionInfo::STATE_START) + { + if(m_VersionInfo.m_VersionServeraddr.m_Job.Status() == CJob::STATE_DONE) + { + CNetChunk Packet; + + mem_zero(&Packet, sizeof(Packet)); + + m_VersionInfo.m_VersionServeraddr.m_Addr.port = VERSIONSRV_PORT; + + Packet.m_ClientID = -1; + Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; + Packet.m_pData = VERSIONSRV_GETVERSION; + Packet.m_DataSize = sizeof(VERSIONSRV_GETVERSION); + Packet.m_Flags = NETSENDFLAG_CONNLESS; + + m_NetClient[0].Send(&Packet); + m_VersionInfo.m_State = CVersionInfo::STATE_READY; + } + } +} + +void CClient::CheckVersionUpdate() +{ + m_VersionInfo.m_State = CVersionInfo::STATE_START; +} + +void CClient::RegisterInterfaces() +{ + Kernel()->RegisterInterface(static_cast<IDemoRecorder*>(&m_DemoRecorder[RECORDER_MANUAL])); + Kernel()->RegisterInterface(static_cast<IDemoPlayer*>(&m_DemoPlayer)); + Kernel()->RegisterInterface(static_cast<IServerBrowser*>(&m_ServerBrowser)); + Kernel()->RegisterInterface(static_cast<IFetcher*>(&m_Fetcher)); +#if !defined(CONF_PLATFORM_MACOSX) && !defined(__ANDROID__) + Kernel()->RegisterInterface(static_cast<IUpdater*>(&m_Updater)); +#endif + Kernel()->RegisterInterface(static_cast<IFriends*>(&m_Friends)); + Kernel()->ReregisterInterface(static_cast<IFriends*>(&m_Foes)); +} + +void CClient::InitInterfaces() +{ + // fetch interfaces + m_pEngine = Kernel()->RequestInterface<IEngine>(); + m_pEditor = Kernel()->RequestInterface<IEditor>(); + //m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); + m_pSound = Kernel()->RequestInterface<IEngineSound>(); + m_pGameClient = Kernel()->RequestInterface<IGameClient>(); + m_pInput = Kernel()->RequestInterface<IEngineInput>(); + m_pMap = Kernel()->RequestInterface<IEngineMap>(); + m_pMasterServer = Kernel()->RequestInterface<IEngineMasterServer>(); + m_pFetcher = Kernel()->RequestInterface<IFetcher>(); +#if !defined(CONF_PLATFORM_MACOSX) && !defined(__ANDROID__) + m_pUpdater = Kernel()->RequestInterface<IUpdater>(); +#endif + m_pStorage = Kernel()->RequestInterface<IStorage>(); + + m_DemoEditor.Init(m_pGameClient->NetVersion(), &m_SnapshotDelta, m_pConsole, m_pStorage); + + m_ServerBrowser.SetBaseInfo(&m_NetClient[2], m_pGameClient->NetVersion()); + + m_Fetcher.Init(); + +#if !defined(CONF_PLATFORM_MACOSX) && !defined(__ANDROID__) + m_Updater.Init(); +#endif + + m_Friends.Init(); + m_Foes.Init(true); + + IOHANDLE newsFile = m_pStorage->OpenFile("ddnet-news.txt", IOFLAG_READ, IStorage::TYPE_SAVE); + if (newsFile) + { + io_read(newsFile, m_aNews, NEWS_SIZE); + io_close(newsFile); + } +} + +void CClient::Run() +{ + m_LocalStartTime = time_get(); + m_SnapshotParts = 0; + + srand(time(NULL)); + + // init SDL + { + if(SDL_Init(0) < 0) + { + dbg_msg("client", "unable to init SDL base: %s", SDL_GetError()); + return; + } + + atexit(SDL_Quit); // ignore_convention + } + + // init graphics + { + if(g_Config.m_GfxThreadedOld) + m_pGraphics = CreateEngineGraphicsThreaded(); + else + m_pGraphics = CreateEngineGraphics(); + + bool RegisterFail = false; + RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IEngineGraphics*>(m_pGraphics)); // register graphics as both + RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IGraphics*>(m_pGraphics)); + + if(RegisterFail || m_pGraphics->Init() != 0) + { + dbg_msg("client", "couldn't init graphics"); + return; + } + } + + // init sound, allowed to fail + m_SoundInitFailed = Sound()->Init() != 0; + + // open socket + { + NETADDR BindAddr; + if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // got bindaddr + BindAddr.type = NETTYPE_ALL; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + } + for(int i = 0; i < 3; i++) + { + do + { + BindAddr.port = (secure_rand() % 64511) + 1024; + } + while(!m_NetClient[i].Open(BindAddr, 0)); + } + } + + // init font rendering + Kernel()->RequestInterface<IEngineTextRender>()->Init(); + + // init the input + Input()->Init(); + + // start refreshing addresses while we load + MasterServer()->RefreshAddresses(m_NetClient[0].NetType()); + + // init the editor + m_pEditor->Init(); + + + // load data + if(!LoadData()) + return; + + GameClient()->OnInit(); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "version %s", GameClient()->NetVersion()); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + + // connect to the server if wanted + /* + if(config.cl_connect[0] != 0) + Connect(config.cl_connect); + config.cl_connect[0] = 0; + */ + + // + m_FpsGraph.Init(0.0f, 200.0f); + + // never start with the editor + g_Config.m_ClEditor = 0; + + Input()->MouseModeRelative(); + + // process pending commands + m_pConsole->StoreCommands(false); + + bool LastD = false; + bool LastQ = false; + bool LastE = false; + bool LastG = false; + + while (1) + { + // + VersionUpdate(); + + // handle pending connects + if(m_aCmdConnect[0]) + { + str_copy(g_Config.m_UiServerAddress, m_aCmdConnect, sizeof(g_Config.m_UiServerAddress)); + Connect(m_aCmdConnect); + m_aCmdConnect[0] = 0; + } + + // progress on dummy connect if security token handshake skipped/passed + if (m_DummySendConnInfo && !m_NetClient[1].SecurityTokenUnknown()) + { + m_DummySendConnInfo = false; + + // send client info + CMsgPacker MsgInfo(NETMSG_INFO); + MsgInfo.AddString(GameClient()->NetVersion(), 128); + MsgInfo.AddString(g_Config.m_Password, 128); + SendMsgExY(&MsgInfo, MSGFLAG_VITAL|MSGFLAG_FLUSH, true, 1); + + // update netclient + m_NetClient[1].Update(); + + // send ready + CMsgPacker MsgReady(NETMSG_READY); + SendMsgExY(&MsgReady, MSGFLAG_VITAL|MSGFLAG_FLUSH, true, 1); + + // startinfo + GameClient()->SendDummyInfo(true); + + // send enter game an finish the connection + CMsgPacker MsgEnter(NETMSG_ENTERGAME); + SendMsgExY(&MsgEnter, MSGFLAG_VITAL|MSGFLAG_FLUSH, true, 1); + } + + // update input + if(Input()->Update()) + break; // SDL_QUIT +#if !defined(CONF_PLATFORM_MACOSX) && !defined(__ANDROID__) + Updater()->Update(); +#endif + + // update sound + Sound()->Update(); + + // release focus + if(!m_pGraphics->WindowActive()) + { + if(m_WindowMustRefocus == 0) + Input()->MouseModeAbsolute(); + m_WindowMustRefocus = 1; + } + else if (g_Config.m_DbgFocus && Input()->KeyPressed(KEY_ESCAPE)) + { + Input()->MouseModeAbsolute(); + m_WindowMustRefocus = 1; + } + + // refocus + if(m_WindowMustRefocus && m_pGraphics->WindowActive()) + { + if(m_WindowMustRefocus < 3) + { + Input()->MouseModeAbsolute(); + m_WindowMustRefocus++; + } + + if(m_WindowMustRefocus >= 3 || Input()->KeyPressed(KEY_MOUSE_1)) + { + Input()->MouseModeRelative(); + m_WindowMustRefocus = 0; + } + } + + // panic quit button + if(CtrlShiftKey('q', LastQ)) + { + Quit(); + break; + } + + if(CtrlShiftKey('d', LastD)) + g_Config.m_Debug ^= 1; + + if(CtrlShiftKey('g', LastG)) + g_Config.m_DbgGraphs ^= 1; + + if(CtrlShiftKey('e', LastE)) + { + g_Config.m_ClEditor = g_Config.m_ClEditor^1; + Input()->MouseModeRelative(); + } + + /* + if(!gfx_window_open()) + break; + */ + + // render + { + if(g_Config.m_ClEditor) + { + if(!m_EditorActive) + { + GameClient()->OnActivateEditor(); + m_EditorActive = true; + } + } + else if(m_EditorActive) + m_EditorActive = false; + + Update(); + + if((g_Config.m_GfxBackgroundRender || m_pGraphics->WindowOpen()) && (!g_Config.m_GfxAsyncRenderOld || m_pGraphics->IsIdle())) + { + m_RenderFrames++; + + // update frametime + int64 Now = time_get(); + m_RenderFrameTime = (Now - m_LastRenderTime) / (float)time_freq(); + if(m_RenderFrameTime < m_RenderFrameTimeLow) + m_RenderFrameTimeLow = m_RenderFrameTime; + if(m_RenderFrameTime > m_RenderFrameTimeHigh) + m_RenderFrameTimeHigh = m_RenderFrameTime; + m_FpsGraph.Add(1.0f/m_RenderFrameTime, 1,1,1); + + m_LastRenderTime = Now; + + if(g_Config.m_DbgStress) + { + if((m_RenderFrames%10) == 0) + { + if(!m_EditorActive) + Render(); + else + { + m_pEditor->UpdateAndRender(); + DebugRender(); + } + m_pGraphics->Swap(); + } + } + else + { + if(!m_EditorActive) + Render(); + else + { + m_pEditor->UpdateAndRender(); + DebugRender(); + } + m_pGraphics->Swap(); + } + } + if(Input()->VideoRestartNeeded()) + { + m_pGraphics->Init(); + LoadData(); + GameClient()->OnInit(); + } + } + + AutoScreenshot_Cleanup(); + + // check conditions + if(State() == IClient::STATE_QUITING) + break; + + // beNice + if(g_Config.m_ClCpuThrottle) + net_socket_read_wait(m_NetClient[0].m_Socket, g_Config.m_ClCpuThrottle * 1000); + //thread_sleep(g_Config.m_ClCpuThrottle); + else if(g_Config.m_DbgStress || (g_Config.m_ClCpuThrottleInactive && !m_pGraphics->WindowActive())) + thread_sleep(5); + + if(g_Config.m_DbgHitch) + { + thread_sleep(g_Config.m_DbgHitch); + g_Config.m_DbgHitch = 0; + } + + // update local time + m_LocalTime = (time_get()-m_LocalStartTime)/(float)time_freq(); + } + + GameClient()->OnShutdown(); + Disconnect(); + + m_pGraphics->Shutdown(); + m_pSound->Shutdown(); + + // shutdown SDL + { + SDL_Quit(); + } +} + +bool CClient::CtrlShiftKey(int Key, bool &Last) +{ + if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && !Last && Input()->KeyPressed(Key)) + { + Last = true; + return true; + } + else if (Last && !Input()->KeyPressed(Key)) + Last = false; + + return false; +} + +void CClient::Con_Connect(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + str_copy(pSelf->m_aCmdConnect, pResult->GetString(0), sizeof(pSelf->m_aCmdConnect)); +} + +void CClient::Con_Disconnect(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->Disconnect(); +} + +void CClient::Con_DummyConnect(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DummyConnect(); +} + +void CClient::Con_DummyDisconnect(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DummyDisconnect(0); +} + +void CClient::Con_Quit(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->Quit(); +} + +void CClient::Con_Minimize(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->Graphics()->Minimize(); +} + +void CClient::Con_Ping(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + + CMsgPacker Msg(NETMSG_PING); + pSelf->SendMsgEx(&Msg, 0); + pSelf->m_PingStartTime = time_get(); +} + +void CClient::AutoScreenshot_Start() +{ + if(g_Config.m_ClAutoScreenshot) + { + Graphics()->TakeScreenshot("auto/autoscreen"); + m_AutoScreenshotRecycle = true; + } +} + +void CClient::AutoStatScreenshot_Start() +{ + if(g_Config.m_ClAutoStatboardScreenshot) + { + Graphics()->TakeScreenshot("auto/stats/autoscreen"); + m_AutoStatScreenshotRecycle = true; + } +} + +void CClient::AutoScreenshot_Cleanup() +{ + if(m_AutoScreenshotRecycle) + { + if(g_Config.m_ClAutoScreenshotMax) + { + // clean up auto taken screens + CFileCollection AutoScreens; + AutoScreens.Init(Storage(), "screenshots/auto", "autoscreen", ".png", g_Config.m_ClAutoScreenshotMax); + } + m_AutoScreenshotRecycle = false; + } +} + +void CClient::AutoStatScreenshot_Cleanup() +{ + if(m_AutoStatScreenshotRecycle) + { + if(g_Config.m_ClAutoStatboardScreenshotMax) + { + // clean up auto taken screens + CFileCollection AutoScreens; + AutoScreens.Init(Storage(), "screenshots/auto/stats", "autoscreen", ".png", g_Config.m_ClAutoStatboardScreenshotMax); + } + m_AutoStatScreenshotRecycle = false; + } +} + +void CClient::Con_Screenshot(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->Graphics()->TakeScreenshot(0); +} + +void CClient::Con_Rcon(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->Rcon(pResult->GetString(0)); +} + +void CClient::Con_RconAuth(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->RconAuth("", pResult->GetString(0)); +} + +void CClient::Con_AddFavorite(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + NETADDR Addr; + if(net_addr_from_str(&Addr, pResult->GetString(0)) == 0) + pSelf->m_ServerBrowser.AddFavorite(Addr); +} + +void CClient::Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + NETADDR Addr; + if(net_addr_from_str(&Addr, pResult->GetString(0)) == 0) + pSelf->m_ServerBrowser.RemoveFavorite(Addr); +} + +void CClient::DemoSliceBegin() +{ + const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); + g_Config.m_ClDemoSliceBegin = pInfo->m_Info.m_CurrentTick; +} + +void CClient::DemoSliceEnd() +{ + const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); + g_Config.m_ClDemoSliceEnd = pInfo->m_Info.m_CurrentTick; +} + +void CClient::Con_DemoSliceBegin(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DemoSliceBegin(); +} + +void CClient::Con_DemoSliceEnd(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DemoSliceEnd(); +} + +void CClient::DemoSlice(const char *pDstPath) +{ + if (m_DemoPlayer.IsPlaying()) + { + const char *pDemoFileName = m_DemoPlayer.GetDemoFileName(); + m_DemoEditor.Slice(pDemoFileName, pDstPath, g_Config.m_ClDemoSliceBegin, g_Config.m_ClDemoSliceEnd); + } +} + +const char *CClient::DemoPlayer_Play(const char *pFilename, int StorageType) +{ + int Crc; + const char *pError; + Disconnect(); + m_NetClient[0].ResetErrorString(); + + // try to start playback + m_DemoPlayer.SetListner(this); + + if(m_DemoPlayer.Load(Storage(), m_pConsole, pFilename, StorageType)) + return "error loading demo"; + + // load map + Crc = (m_DemoPlayer.Info()->m_Header.m_aMapCrc[0]<<24)| + (m_DemoPlayer.Info()->m_Header.m_aMapCrc[1]<<16)| + (m_DemoPlayer.Info()->m_Header.m_aMapCrc[2]<<8)| + (m_DemoPlayer.Info()->m_Header.m_aMapCrc[3]); + pError = LoadMapSearch(m_DemoPlayer.Info()->m_Header.m_aMapName, Crc); + if(pError) + { + DisconnectWithReason(pError); + return pError; + } + + GameClient()->OnConnected(); + + // setup buffers + mem_zero(m_aDemorecSnapshotData, sizeof(m_aDemorecSnapshotData)); + + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT] = &m_aDemorecSnapshotHolders[SNAP_CURRENT]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV] = &m_aDemorecSnapshotHolders[SNAP_PREV]; + + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][0]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][1]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_SnapSize = 0; + m_aSnapshots[g_Config.m_ClDummy][SNAP_CURRENT]->m_Tick = -1; + + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][0]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][1]; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_SnapSize = 0; + m_aSnapshots[g_Config.m_ClDummy][SNAP_PREV]->m_Tick = -1; + + // enter demo playback state + SetState(IClient::STATE_DEMOPLAYBACK); + + m_DemoPlayer.Play(); + GameClient()->OnEnterGame(); + + return 0; +} + +void CClient::Con_Play(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DemoPlayer_Play(pResult->GetString(0), IStorage::TYPE_ALL); +} + +void CClient::Con_DemoPlay(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + if(pSelf->m_DemoPlayer.IsPlaying()){ + if(pSelf->m_DemoPlayer.BaseInfo()->m_Paused){ + pSelf->m_DemoPlayer.Unpause(); + } + else{ + pSelf->m_DemoPlayer.Pause(); + } + } +} + +void CClient::DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder) +{ + if(State() != IClient::STATE_ONLINE) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demorec/record", "client is not online"); + else + { + char aFilename[128]; + if(WithTimestamp) + { + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", pFilename, aDate); + } + else + str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pFilename); + m_DemoRecorder[Recorder].Start(Storage(), m_pConsole, aFilename, GameClient()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "client"); + } +} + +void CClient::DemoRecorder_HandleAutoStart() +{ + if(g_Config.m_ClAutoDemoRecord) + { + DemoRecorder_Stop(RECORDER_AUTO); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "auto/%s", m_aCurrentMap); + DemoRecorder_Start(aBuf, true, RECORDER_AUTO); + if(g_Config.m_ClAutoDemoMax) + { + // clean up auto recorded demos + CFileCollection AutoDemos; + AutoDemos.Init(Storage(), "demos/auto", "" /* empty for wild card */, ".demo", g_Config.m_ClAutoDemoMax); + } + } +} + +void CClient::DemoRecorder_Stop(int Recorder) +{ + m_DemoRecorder[Recorder].Stop(); +} + +void CClient::DemoRecorder_AddDemoMarker(int Recorder) +{ + m_DemoRecorder[Recorder].AddDemoMarker(); +} + +class IDemoRecorder *CClient::DemoRecorder(int Recorder) +{ + return &m_DemoRecorder[Recorder]; +} + +void CClient::Con_Record(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + if(pResult->NumArguments()) + pSelf->DemoRecorder_Start(pResult->GetString(0), false, RECORDER_MANUAL); + else + pSelf->DemoRecorder_Start(pSelf->m_aCurrentMap, true, RECORDER_MANUAL); +} + +void CClient::Con_StopRecord(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DemoRecorder_Stop(RECORDER_MANUAL); +} + +void CClient::Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData) +{ + CClient *pSelf = (CClient *)pUserData; + pSelf->DemoRecorder_AddDemoMarker(RECORDER_MANUAL); + pSelf->DemoRecorder_AddDemoMarker(RECORDER_RACE); + pSelf->DemoRecorder_AddDemoMarker(RECORDER_AUTO); +} + +void CClient::ServerBrowserUpdate() +{ + m_ResortServerBrowser = true; +} + +void CClient::ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CClient *)pUserData)->ServerBrowserUpdate(); +} + +void CClient::RegisterCommands() +{ + m_pConsole = Kernel()->RequestInterface<IConsole>(); + // register server dummy commands for tab completion + m_pConsole->Register("kick", "i[id] ?r[reason]", CFGFLAG_SERVER, 0, 0, "Kick player with specified id for any reason"); + m_pConsole->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER, 0, 0, "Ban player with ip/id for x minutes for any reason"); + m_pConsole->Register("unban", "s[ip]", CFGFLAG_SERVER, 0, 0, "Unban ip"); + m_pConsole->Register("bans", "", CFGFLAG_SERVER, 0, 0, "Show banlist"); + m_pConsole->Register("status", "", CFGFLAG_SERVER, 0, 0, "List players"); + m_pConsole->Register("shutdown", "", CFGFLAG_SERVER, 0, 0, "Shut down"); + m_pConsole->Register("record", "s[file]", CFGFLAG_SERVER, 0, 0, "Record to a file"); + m_pConsole->Register("stoprecord", "", CFGFLAG_SERVER, 0, 0, "Stop recording"); + m_pConsole->Register("reload", "", CFGFLAG_SERVER, 0, 0, "Reload the map"); + + m_pConsole->Register("dummy_connect", "", CFGFLAG_CLIENT, Con_DummyConnect, this, "connect dummy"); + m_pConsole->Register("dummy_disconnect", "", CFGFLAG_CLIENT, Con_DummyDisconnect, this, "disconnect dummy"); + + m_pConsole->Register("quit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); + m_pConsole->Register("exit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); + m_pConsole->Register("minimize", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Minimize, this, "Minimize Teeworlds"); + m_pConsole->Register("connect", "s[host|ip]", CFGFLAG_CLIENT, Con_Connect, this, "Connect to the specified host/ip"); + m_pConsole->Register("disconnect", "", CFGFLAG_CLIENT, Con_Disconnect, this, "Disconnect from the server"); + m_pConsole->Register("ping", "", CFGFLAG_CLIENT, Con_Ping, this, "Ping the current server"); + m_pConsole->Register("screenshot", "", CFGFLAG_CLIENT, Con_Screenshot, this, "Take a screenshot"); + m_pConsole->Register("rcon", "r[rcon-command]", CFGFLAG_CLIENT, Con_Rcon, this, "Send specified command to rcon"); + m_pConsole->Register("rcon_auth", "s[password]", CFGFLAG_CLIENT, Con_RconAuth, this, "Authenticate to rcon"); + m_pConsole->Register("play", "r[file]", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Play, this, "Play the file specified"); + m_pConsole->Register("record", "?s[file]", CFGFLAG_CLIENT, Con_Record, this, "Record to the file"); + m_pConsole->Register("stoprecord", "", CFGFLAG_CLIENT, Con_StopRecord, this, "Stop recording"); + m_pConsole->Register("add_demomarker", "", CFGFLAG_CLIENT, Con_AddDemoMarker, this, "Add demo timeline marker"); + m_pConsole->Register("add_favorite", "s[host|ip]", CFGFLAG_CLIENT, Con_AddFavorite, this, "Add a server as a favorite"); + m_pConsole->Register("remove_favorite", "s[host|ip]", CFGFLAG_CLIENT, Con_RemoveFavorite, this, "Remove a server from favorites"); + m_pConsole->Register("demo_slice_start", "", CFGFLAG_CLIENT, Con_DemoSliceBegin, this, ""); + m_pConsole->Register("demo_slice_end", "", CFGFLAG_CLIENT, Con_DemoSliceEnd, this, ""); + m_pConsole->Register("demo_play", "", CFGFLAG_CLIENT, Con_DemoPlay, this, "Play demo"); + + // used for server browser update + m_pConsole->Chain("br_filter_string", ConchainServerBrowserUpdate, this); + m_pConsole->Chain("br_filter_gametype", ConchainServerBrowserUpdate, this); + m_pConsole->Chain("br_filter_serveraddress", ConchainServerBrowserUpdate, this); + + // DDRace + + + #define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, 0, 0, help); + #include <game/ddracecommands.h> +} + +static CClient *CreateClient() +{ + CClient *pClient = static_cast<CClient *>(mem_alloc(sizeof(CClient), 1)); + mem_zero(pClient, sizeof(CClient)); + return new(pClient) CClient; +} + +/* + Server Time + Client Mirror Time + Client Predicted Time + + Snapshot Latency + Downstream latency + + Prediction Latency + Upstream latency +*/ + +#if defined(CONF_PLATFORM_MACOSX) || defined(__ANDROID__) +extern "C" int SDL_main(int argc, char **argv_) // ignore_convention +{ + const char **argv = const_cast<const char **>(argv_); +#else +int main(int argc, const char **argv) // ignore_convention +{ +#endif +#if defined(CONF_FAMILY_WINDOWS) + for(int i = 1; i < argc; i++) // ignore_convention + { + if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention + { + FreeConsole(); + break; + } + } +#endif + +#if !defined(CONF_PLATFORM_MACOSX) + dbg_enable_threaded(); +#endif + + if(secure_random_init() != 0) + { + dbg_msg("secure", "could not initialize secure RNG"); + return -1; + } + + CClient *pClient = CreateClient(); + IKernel *pKernel = IKernel::Create(); + pKernel->RegisterInterface(pClient); + pClient->RegisterInterfaces(); + + // create the components + IEngine *pEngine = CreateEngine("Teeworlds"); + IConsole *pConsole = CreateConsole(CFGFLAG_CLIENT); + IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_CLIENT, argc, argv); // ignore_convention + IConfig *pConfig = CreateConfig(); + IEngineSound *pEngineSound = CreateEngineSound(); + IEngineInput *pEngineInput = CreateEngineInput(); + IEngineTextRender *pEngineTextRender = CreateEngineTextRender(); + IEngineMap *pEngineMap = CreateEngineMap(); + IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); + + { + bool RegisterFail = false; + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineSound*>(pEngineSound)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ISound*>(pEngineSound)); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineInput*>(pEngineInput)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IInput*>(pEngineInput)); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineTextRender*>(pEngineTextRender)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ITextRender*>(pEngineTextRender)); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap)); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer)); + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateEditor()); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateGameClient()); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); + + if(RegisterFail) + return -1; + } + + pEngine->Init(); + pConfig->Init(); + pEngineMasterServer->Init(); + pEngineMasterServer->Load(); + + // register all console commands + pClient->RegisterCommands(); + + pKernel->RequestInterface<IGameClient>()->OnConsoleInit(); + + // init client's interfaces + pClient->InitInterfaces(); + + // execute config file + IOHANDLE File = pStorage->OpenFile(CONFIG_FILE, IOFLAG_READ, IStorage::TYPE_ALL); + if(File) + { + io_close(File); + pConsole->ExecuteFile(CONFIG_FILE); + } + else // fallback + { + pConsole->ExecuteFile("settings.cfg"); + } + + // execute autoexec file + File = pStorage->OpenFile(AUTOEXEC_CLIENT_FILE, IOFLAG_READ, IStorage::TYPE_ALL); + if(File) + { + io_close(File); + pConsole->ExecuteFile(AUTOEXEC_CLIENT_FILE); + } + else // fallback + { + pConsole->ExecuteFile(AUTOEXEC_FILE); + } + + if(g_Config.m_ClConfigVersion < 1) + { + if(g_Config.m_ClAntiPing == 0) + { + g_Config.m_ClAntiPingPlayers = 1; + g_Config.m_ClAntiPingGrenade = 1; + g_Config.m_ClAntiPingWeapons = 1; + } + } + g_Config.m_ClConfigVersion = 1; + + // parse the command line arguments + if(argc > 1) // ignore_convention + pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + + pClient->Engine()->InitLogfile(); + +#if defined(CONF_FAMILY_UNIX) + FifoConsole *fifoConsole = new FifoConsole(pConsole, g_Config.m_ClInputFifo, CFGFLAG_CLIENT); +#endif + +#if defined(CONF_FAMILY_WINDOWS) + if(!g_Config.m_ClShowConsole) + FreeConsole(); +#endif + + // run the client + dbg_msg("client", "starting..."); + pClient->Run(); + +#if defined(CONF_FAMILY_UNIX) + delete fifoConsole; +#endif + + // write down the config and quit + pConfig->Save(); + + return 0; +} + +// DDRace + +const char* CClient::GetCurrentMap() +{ + return m_aCurrentMap; +} + +int CClient::GetCurrentMapCrc() +{ + return m_CurrentMapCrc; +} + +const char* CClient::RaceRecordStart(const char *pFilename) +{ + char aFilename[128]; + str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", m_aCurrentMap, pFilename); + + if(State() != STATE_ONLINE) + dbg_msg("demorec/record", "client is not online"); + else + m_DemoRecorder[RECORDER_RACE].Start(Storage(), m_pConsole, aFilename, GameClient()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "client"); + + return m_aCurrentMap; +} + +void CClient::RaceRecordStop() +{ + if(m_DemoRecorder[RECORDER_RACE].IsRecording()) + m_DemoRecorder[RECORDER_RACE].Stop(); +} + +bool CClient::RaceRecordIsRecording() +{ + return m_DemoRecorder[RECORDER_RACE].IsRecording(); +} + +void CClient::RequestDDNetSrvList() +{ + // request ddnet server list + // generate new token + for (int i = 0; i < 4; i++) + m_aDDNetSrvListToken[i] = rand()&0xff; + m_DDNetSrvListTokenSet = true; + + char aData[sizeof(VERSIONSRV_GETDDNETLIST)+4]; + mem_copy(aData, VERSIONSRV_GETDDNETLIST, sizeof(VERSIONSRV_GETDDNETLIST)); + mem_copy(aData+sizeof(VERSIONSRV_GETDDNETLIST), m_aDDNetSrvListToken, 4); // add token + + CNetChunk Packet; + mem_zero(&Packet, sizeof(Packet)); + Packet.m_ClientID = -1; + Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; + Packet.m_pData = aData; + Packet.m_DataSize = sizeof(VERSIONSRV_GETDDNETLIST)+4; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + m_NetClient[g_Config.m_ClDummy].Send(&Packet); +} diff --git a/src/engine/client/client.h b/src/engine/client/client.h new file mode 100644 index 0000000..77be762 --- /dev/null +++ b/src/engine/client/client.h @@ -0,0 +1,373 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_CLIENT_H +#define ENGINE_CLIENT_CLIENT_H + +class CGraph +{ +public: + enum + { + // restrictions: Must be power of two + MAX_VALUES=128, + }; + + float m_Min, m_Max; + float m_aValues[MAX_VALUES]; + float m_aColors[MAX_VALUES][3]; + int m_Index; + + void Init(float Min, float Max); + + void ScaleMax(); + void ScaleMin(); + + void Add(float v, float r, float g, float b); + void Render(IGraphics *pGraphics, int Font, float x, float y, float w, float h, const char *pDescription); +}; + + +class CSmoothTime +{ + int64 m_Snap; + int64 m_Current; + int64 m_Target; + + CGraph m_Graph; + + int m_SpikeCounter; + + float m_aAdjustSpeed[2]; // 0 = down, 1 = up +public: + void Init(int64 Target); + void SetAdjustSpeed(int Direction, float Value); + + int64 Get(int64 Now); + + void UpdateInt(int64 Target); + void Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection); +}; + + +class CClient : public IClient, public CDemoPlayer::IListner +{ + // needed interfaces + IEngine *m_pEngine; + IEditor *m_pEditor; + IEngineInput *m_pInput; + IEngineGraphics *m_pGraphics; + IEngineSound *m_pSound; + IGameClient *m_pGameClient; + IEngineMap *m_pMap; + IConsole *m_pConsole; + IStorage *m_pStorage; + IFetcher *m_pFetcher; + IUpdater *m_pUpdater; + IEngineMasterServer *m_pMasterServer; + + enum + { + NUM_SNAPSHOT_TYPES=2, + PREDICTION_MARGIN=1000/50/2, // magic network prediction value + }; + + class CNetClient m_NetClient[3]; + class CDemoPlayer m_DemoPlayer; + class CDemoRecorder m_DemoRecorder[RECORDER_MAX]; + class CDemoEditor m_DemoEditor; + class CServerBrowser m_ServerBrowser; + class CFetcher m_Fetcher; + class CUpdater m_Updater; + class CFriends m_Friends; + class CFriends m_Foes; + class CMapChecker m_MapChecker; + + char m_aServerAddressStr[256]; + + unsigned m_SnapshotParts; + int64 m_LocalStartTime; + + int m_DebugFont; + + int64 m_LastRenderTime; + float m_RenderFrameTimeLow; + float m_RenderFrameTimeHigh; + int m_RenderFrames; + + NETADDR m_ServerAddress; + int m_WindowMustRefocus; + int m_SnapCrcErrors; + bool m_AutoScreenshotRecycle; + bool m_AutoStatScreenshotRecycle; + bool m_EditorActive; + bool m_SoundInitFailed; + bool m_ResortServerBrowser; + + int m_AckGameTick[2]; + int m_CurrentRecvTick[2]; + int m_RconAuthed[2]; + char m_RconPassword[32]; + int m_UseTempRconCommands; + + // version-checking + char m_aVersionStr[10]; + + // pinging + int64 m_PingStartTime; + + // + char m_aCurrentMap[256]; + unsigned m_CurrentMapCrc; + + bool m_TimeoutCodeSent[2]; + + // + char m_aCmdConnect[256]; + + // map download + CFetchTask *m_pMapdownloadTask; + char m_aMapdownloadFilename[256]; + char m_aMapdownloadName[256]; + IOHANDLE m_MapdownloadFile; + int m_MapdownloadChunk; + int m_MapdownloadCrc; + int m_MapdownloadAmount; + int m_MapdownloadTotalsize; + + // time + CSmoothTime m_GameTime[2]; + CSmoothTime m_PredictedTime; + + // input + struct // TODO: handle input better + { + int m_aData[MAX_INPUT_SIZE]; // the input data + int m_Tick; // the tick that the input is for + int64 m_PredictedTime; // prediction latency when we sent this input + int64 m_Time; + } m_aInputs[2][200]; + + int m_CurrentInput[2]; + bool m_LastDummy; + bool m_LastDummy2; + CNetObj_PlayerInput HammerInput; + + // graphs + CGraph m_InputtimeMarginGraph; + CGraph m_GametimeMarginGraph; + CGraph m_FpsGraph; + + // the game snapshots are modifiable by the game + class CSnapshotStorage m_SnapshotStorage[2]; + CSnapshotStorage::CHolder *m_aSnapshots[2][NUM_SNAPSHOT_TYPES]; + + int m_ReceivedSnapshots[2]; + char m_aSnapshotIncomingData[CSnapshot::MAX_SIZE]; + + class CSnapshotStorage::CHolder m_aDemorecSnapshotHolders[NUM_SNAPSHOT_TYPES]; + char *m_aDemorecSnapshotData[NUM_SNAPSHOT_TYPES][2][CSnapshot::MAX_SIZE]; + + class CSnapshotDelta m_SnapshotDelta; + + // + class CServerInfo m_CurrentServerInfo; + int64 m_CurrentServerInfoRequestTime; // >= 0 should request, == -1 got info + + // version info + struct CVersionInfo + { + enum + { + STATE_INIT=0, + STATE_START, + STATE_READY, + }; + + int m_State; + class CHostLookup m_VersionServeraddr; + } m_VersionInfo; + + volatile int m_GfxState; + static void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); } + void GraphicsThread(); + vec3 GetColorV3(int v); + + char m_aDDNetSrvListToken[4]; + bool m_DDNetSrvListTokenSet; + +public: + IEngine *Engine() { return m_pEngine; } + IEngineGraphics *Graphics() { return m_pGraphics; } + IEngineInput *Input() { return m_pInput; } + IEngineSound *Sound() { return m_pSound; } + IGameClient *GameClient() { return m_pGameClient; } + IEngineMasterServer *MasterServer() { return m_pMasterServer; } + IStorage *Storage() { return m_pStorage; } + IFetcher *Fetcher() { return m_pFetcher; } + IUpdater *Updater() { return m_pUpdater; } + + CClient(); + + // ----- send functions ----- + virtual int SendMsg(CMsgPacker *pMsg, int Flags); + virtual int SendMsgExY(CMsgPacker *pMsg, int Flags, bool System=true, int NetClient=1); + + int SendMsgEx(CMsgPacker *pMsg, int Flags, bool System=true); + void SendInfo(); + void SendEnterGame(); + void SendReady(); + void SendMapRequest(); + + virtual bool RconAuthed() { return m_RconAuthed[g_Config.m_ClDummy] != 0; } + virtual bool UseTempRconCommands() { return m_UseTempRconCommands != 0; } + void RconAuth(const char *pName, const char *pPassword); + virtual void Rcon(const char *pCmd); + + virtual bool ConnectionProblems(); + + virtual bool SoundInitFailed() { return m_SoundInitFailed; } + + virtual int GetDebugFont() { return m_DebugFont; } + + void DirectInput(int *pInput, int Size); + void SendInput(); + + // TODO: OPT: do this alot smarter! + virtual int *GetInput(int Tick); + virtual bool InputExists(int Tick); + + const char *LatestVersion(); + void VersionUpdate(); + void CheckVersionUpdate(); + + // ------ state handling ----- + void SetState(int s); + + // called when the map is loaded and we should init for a new round + void OnEnterGame(); + virtual void EnterGame(); + + virtual void Connect(const char *pAddress); + void DisconnectWithReason(const char *pReason); + virtual void Disconnect(); + + virtual void DummyDisconnect(const char *pReason); + virtual void DummyConnect(); + virtual bool DummyConnected(); + virtual bool DummyConnecting(); + void DummyInfo(); + int m_DummyConnected; + int m_LastDummyConnectTime; + int m_Fire; + + virtual void GetServerInfo(CServerInfo *pServerInfo); + void ServerInfoRequest(); + + int LoadData(); + + // --- + + void *SnapGetItem(int SnapID, int Index, CSnapItem *pItem); + void SnapInvalidateItem(int SnapID, int Index); + void *SnapFindItem(int SnapID, int Type, int ID); + int SnapNumItems(int SnapID); + void SnapSetStaticsize(int ItemType, int Size); + + void Render(); + void DebugRender(); + + virtual void Restart(); + virtual void Quit(); + + virtual const char *ErrorString(); + + const char *LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc); + const char *LoadMapSearch(const char *pMapName, int WantedCrc); + + static int PlayerScoreNameComp(const void *a, const void *b); + + void ProcessConnlessPacket(CNetChunk *pPacket); + void ProcessServerPacket(CNetChunk *pPacket); + void ProcessServerPacketDummy(CNetChunk *pPacket); + + void ResetMapDownload(); + void FinishMapDownload(); + + virtual CFetchTask *MapDownloadTask() { return m_pMapdownloadTask; } + virtual const char *MapDownloadName() { return m_aMapdownloadName; } + virtual int MapDownloadAmount() { return !m_pMapdownloadTask ? m_MapdownloadAmount : (int)m_pMapdownloadTask->Current(); } + virtual int MapDownloadTotalsize() { return !m_pMapdownloadTask ? m_MapdownloadTotalsize : (int)m_pMapdownloadTask->Size(); } + + void PumpNetwork(); + + virtual void OnDemoPlayerSnapshot(void *pData, int Size); + virtual void OnDemoPlayerMessage(void *pData, int Size); + + void Update(); + + void RegisterInterfaces(); + void InitInterfaces(); + + void Run(); + + bool CtrlShiftKey(int Key, bool &Last); + + static void Con_Connect(IConsole::IResult *pResult, void *pUserData); + static void Con_Disconnect(IConsole::IResult *pResult, void *pUserData); + + static void Con_DummyConnect(IConsole::IResult *pResult, void *pUserData); + static void Con_DummyDisconnect(IConsole::IResult *pResult, void *pUserData); + + static void Con_Quit(IConsole::IResult *pResult, void *pUserData); + static void Con_DemoPlay(IConsole::IResult *pResult, void *pUserData); + static void Con_Minimize(IConsole::IResult *pResult, void *pUserData); + static void Con_Ping(IConsole::IResult *pResult, void *pUserData); + static void Con_Screenshot(IConsole::IResult *pResult, void *pUserData); + static void Con_Rcon(IConsole::IResult *pResult, void *pUserData); + static void Con_RconAuth(IConsole::IResult *pResult, void *pUserData); + static void Con_AddFavorite(IConsole::IResult *pResult, void *pUserData); + static void Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData); + static void Con_Play(IConsole::IResult *pResult, void *pUserData); + static void Con_Record(IConsole::IResult *pResult, void *pUserData); + static void Con_StopRecord(IConsole::IResult *pResult, void *pUserData); + static void Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData); + static void ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + + static void Con_DemoSlice(IConsole::IResult *pResult, void *pUserData); + static void Con_DemoSliceBegin(IConsole::IResult *pResult, void *pUserData); + static void Con_DemoSliceEnd(IConsole::IResult *pResult, void *pUserData); + + void RegisterCommands(); + + const char *DemoPlayer_Play(const char *pFilename, int StorageType); + void DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder); + void DemoRecorder_HandleAutoStart(); + void DemoRecorder_Stop(int Recorder); + void DemoRecorder_AddDemoMarker(int Recorder); + class IDemoRecorder *DemoRecorder(int Recorder); + + void AutoScreenshot_Start(); + void AutoStatScreenshot_Start(); + void AutoScreenshot_Cleanup(); + void AutoStatScreenshot_Cleanup(); + + void ServerBrowserUpdate(); + + // DDRace + + virtual const char* GetCurrentMap(); + virtual int GetCurrentMapCrc(); + virtual const char* RaceRecordStart(const char *pFilename); + virtual void RaceRecordStop(); + virtual bool RaceRecordIsRecording(); + + virtual void DemoSliceBegin(); + virtual void DemoSliceEnd(); + virtual void DemoSlice(const char *pDstPath); + + void RequestDDNetSrvList(); + bool EditorHasUnsavedData() { return m_pEditor->HasUnsavedData(); } + + virtual IFriends* Foes() {return &m_Foes; } +}; +#endif diff --git a/src/engine/client/fetcher.cpp b/src/engine/client/fetcher.cpp new file mode 100644 index 0000000..769b7f1 --- /dev/null +++ b/src/engine/client/fetcher.cpp @@ -0,0 +1,174 @@ +#include <base/system.h> +#include <engine/storage.h> +#include <engine/shared/config.h> +#include "fetcher.h" + +CFetchTask::CFetchTask(bool canTimeout) +{ + m_pNext = NULL; + m_CanTimeout = canTimeout; +} + +CFetcher::CFetcher() +{ + m_pStorage = NULL; + m_pHandle = NULL; + m_Lock = lock_create(); + m_pFirst = NULL; + m_pLast = NULL; +} + +bool CFetcher::Init() +{ + m_pStorage = Kernel()->RequestInterface<IStorage>(); + if(!curl_global_init(CURL_GLOBAL_DEFAULT) && (m_pHandle = curl_easy_init())) + return true; + return false; +} + +CFetcher::~CFetcher() +{ + if(m_pHandle) + curl_easy_cleanup(m_pHandle); + curl_global_cleanup(); +} + +void CFetcher::QueueAdd(CFetchTask *pTask, const char *pUrl, const char *pDest, int StorageType, void *pUser, COMPFUNC pfnCompCb, PROGFUNC pfnProgCb) +{ + str_copy(pTask->m_pUrl, pUrl, sizeof(pTask->m_pUrl)); + str_copy(pTask->m_pDest, pDest, sizeof(pTask->m_pDest)); + pTask->m_StorageType = StorageType; + pTask->m_pfnProgressCallback = pfnProgCb; + pTask->m_pfnCompCallback = pfnCompCb; + pTask->m_pUser = pUser; + pTask->m_Size = pTask->m_Progress = 0; + pTask->m_Abort = false; + + lock_wait(m_Lock); + if(!m_pThHandle) + { + m_pThHandle = thread_init(&FetcherThread, this); + thread_detach(m_pThHandle); + } + + if(!m_pFirst) + { + m_pFirst = pTask; + m_pLast = m_pFirst; + } + else + { + m_pLast->m_pNext = pTask; + m_pLast = pTask; + } + pTask->m_State = CFetchTask::STATE_QUEUED; + lock_unlock(m_Lock); +} + +void CFetcher::Escape(char *pBuf, size_t size, const char *pStr) +{ + char *pEsc = curl_easy_escape(0, pStr, 0); + str_copy(pBuf, pEsc, size); + curl_free(pEsc); +} + +void CFetcher::FetcherThread(void *pUser) +{ + CFetcher *pFetcher = (CFetcher *)pUser; + dbg_msg("fetcher", "Thread started..."); + while(1) + { + lock_wait(pFetcher->m_Lock); + CFetchTask *pTask = pFetcher->m_pFirst; + if(pTask) + pFetcher->m_pFirst = pTask->m_pNext; + lock_unlock(pFetcher->m_Lock); + if(pTask) + { + dbg_msg("fetcher", "Task got %s:%s", pTask->m_pUrl, pTask->m_pDest); + pFetcher->FetchFile(pTask); + if(pTask->m_pfnCompCallback) + pTask->m_pfnCompCallback(pTask, pTask->m_pUser); + } + else + thread_sleep(10); + } +} + +void CFetcher::FetchFile(CFetchTask *pTask) +{ + char aPath[512]; + if(pTask->m_StorageType == -2) + m_pStorage->GetBinaryPath(pTask->m_pDest, aPath, sizeof(aPath)); + else + m_pStorage->GetCompletePath(pTask->m_StorageType, pTask->m_pDest, aPath, sizeof(aPath)); + IOHANDLE File = io_open(aPath, IOFLAG_WRITE); + + if(!File){ + dbg_msg("fetcher", "I/O Error cannot open file: %s", pTask->m_pDest); + pTask->m_State = CFetchTask::STATE_ERROR; + return; + } + + char aCAFile[512]; + m_pStorage->GetBinaryPath("data/ca-ddnet.pem", aCAFile, sizeof aCAFile); + + char aErr[CURL_ERROR_SIZE]; + curl_easy_setopt(m_pHandle, CURLOPT_ERRORBUFFER, aErr); + + //curl_easy_setopt(m_pHandle, CURLOPT_VERBOSE, 1L); + if(pTask->m_CanTimeout) + { + curl_easy_setopt(m_pHandle, CURLOPT_CONNECTTIMEOUT_MS, (long)g_Config.m_ClHTTPConnectTimeoutMs); + curl_easy_setopt(m_pHandle, CURLOPT_LOW_SPEED_LIMIT, (long)g_Config.m_ClHTTPLowSpeedLimit); + curl_easy_setopt(m_pHandle, CURLOPT_LOW_SPEED_TIME, (long)g_Config.m_ClHTTPLowSpeedTime); + } + else + { + curl_easy_setopt(m_pHandle, CURLOPT_CONNECTTIMEOUT_MS, 0); + curl_easy_setopt(m_pHandle, CURLOPT_LOW_SPEED_LIMIT, 0); + curl_easy_setopt(m_pHandle, CURLOPT_LOW_SPEED_TIME, 0); + } + curl_easy_setopt(m_pHandle, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(m_pHandle, CURLOPT_MAXREDIRS, 4L); + curl_easy_setopt(m_pHandle, CURLOPT_FAILONERROR, 1L); + curl_easy_setopt(m_pHandle, CURLOPT_CAINFO, aCAFile); + curl_easy_setopt(m_pHandle, CURLOPT_URL, pTask->m_pUrl); + curl_easy_setopt(m_pHandle, CURLOPT_WRITEDATA, File); + curl_easy_setopt(m_pHandle, CURLOPT_WRITEFUNCTION, &CFetcher::WriteToFile); + curl_easy_setopt(m_pHandle, CURLOPT_NOPROGRESS, 0); + curl_easy_setopt(m_pHandle, CURLOPT_PROGRESSDATA, pTask); + curl_easy_setopt(m_pHandle, CURLOPT_PROGRESSFUNCTION, &CFetcher::ProgressCallback); + + dbg_msg("fetcher", "Downloading %s", pTask->m_pDest); + pTask->m_State = CFetchTask::STATE_RUNNING; + int ret = curl_easy_perform(m_pHandle); + io_close(File); + if(ret != CURLE_OK) + { + dbg_msg("fetcher", "Task failed. libcurl error: %s", aErr); + pTask->m_State = (ret == CURLE_ABORTED_BY_CALLBACK) ? CFetchTask::STATE_ABORTED : CFetchTask::STATE_ERROR; + } + else + { + dbg_msg("fetcher", "Task done %s", pTask->m_pDest); + pTask->m_State = CFetchTask::STATE_DONE; + } +} + +void CFetcher::WriteToFile(char *pData, size_t size, size_t nmemb, void *pFile) +{ + io_write((IOHANDLE)pFile, pData, size*nmemb); +} + +int CFetcher::ProgressCallback(void *pUser, double DlTotal, double DlCurr, double UlTotal, double UlCurr) +{ + CFetchTask *pTask = (CFetchTask *)pUser; + //dbg_msg("fetcher", "DlCurr:%f, DlTotal:%f", DlCurr, DlTotal); + pTask->m_Current = DlCurr; + pTask->m_Size = DlTotal; + pTask->m_Progress = (100 * DlCurr) / (DlTotal ? DlTotal : 1); + if(pTask->m_pfnProgressCallback) + pTask->m_pfnProgressCallback(pTask, pTask->m_pUser); + return pTask->m_Abort ? -1 : 0; +} diff --git a/src/engine/client/fetcher.h b/src/engine/client/fetcher.h new file mode 100644 index 0000000..61ccb2f --- /dev/null +++ b/src/engine/client/fetcher.h @@ -0,0 +1,33 @@ +#ifndef ENGINE_CLIENT_FETCHER_H +#define ENGINE_CLIENT_FETCHER_H + +#define WIN32_LEAN_AND_MEAN +#include "curl/curl.h" +#include "curl/easy.h" +#include <engine/fetcher.h> + +class CFetcher : public IFetcher +{ +private: + CURL *m_pHandle; + + void *m_pThHandle; + + LOCK m_Lock; + CFetchTask *m_pFirst; + CFetchTask *m_pLast; + class IStorage *m_pStorage; +public: + CFetcher(); + virtual bool Init(); + ~CFetcher(); + + virtual void QueueAdd(CFetchTask *pTask, const char *pUrl, const char *pDest, int StorageType = -2, void *pUser = 0, COMPFUNC pfnCompCb = 0, PROGFUNC pfnProgCb = 0); + virtual void Escape(char *pBud, size_t size, const char *pStr); + static void FetcherThread(void *pUser); + void FetchFile(CFetchTask *pTask); + static void WriteToFile(char *pData, size_t size, size_t nmemb, void *pFile); + static int ProgressCallback(void *pUser, double DlTotal, double DlCurr, double UlTotal, double UlCurr); +}; + +#endif diff --git a/src/engine/client/friends.cpp b/src/engine/client/friends.cpp new file mode 100644 index 0000000..939a277 --- /dev/null +++ b/src/engine/client/friends.cpp @@ -0,0 +1,194 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/config.h> +#include <engine/console.h> +#include <engine/shared/config.h> + +#include "friends.h" + +CFriends::CFriends() +{ + mem_zero(m_aFriends, sizeof(m_aFriends)); + m_NumFriends = 0; + m_Foes = false; +} + +void CFriends::ConAddFriend(IConsole::IResult *pResult, void *pUserData) +{ + CFriends *pSelf = (CFriends *)pUserData; + pSelf->AddFriend(pResult->GetString(0), pResult->GetString(1)); +} + +void CFriends::ConRemoveFriend(IConsole::IResult *pResult, void *pUserData) +{ + CFriends *pSelf = (CFriends *)pUserData; + pSelf->RemoveFriend(pResult->GetString(0), pResult->GetString(1)); +} + +void CFriends::ConFriends(IConsole::IResult *pResult, void *pUserData) +{ + CFriends *pSelf = (CFriends *)pUserData; + pSelf->Friends(); +} + +void CFriends::Init(bool Foes) +{ + m_Foes = Foes; + + IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); + if(pConfig) + pConfig->RegisterCallback(ConfigSaveCallback, this); + + IConsole *pConsole = Kernel()->RequestInterface<IConsole>(); + if(pConsole) + { + if(Foes) + { + pConsole->Register("add_foe", "s[name] ?s[clan]", CFGFLAG_CLIENT, ConAddFriend, this, "Add a foe"); + pConsole->Register("remove_foe", "s[name] ?s[clan]", CFGFLAG_CLIENT, ConRemoveFriend, this, "Remove a foe"); + pConsole->Register("foes", "", CFGFLAG_CLIENT, ConFriends, this, "List foes"); + } + else + { + pConsole->Register("add_friend", "s[name] ?s[clan]", CFGFLAG_CLIENT, ConAddFriend, this, "Add a friend"); + pConsole->Register("remove_friend", "s[name] ?s[clan]", CFGFLAG_CLIENT, ConRemoveFriend, this, "Remove a friend"); + pConsole->Register("friends", "", CFGFLAG_CLIENT, ConFriends, this, "List friends"); + } + } +} + +const CFriendInfo *CFriends::GetFriend(int Index) const +{ + return &m_aFriends[max(0, Index%m_NumFriends)]; +} + +int CFriends::GetFriendState(const char *pName, const char *pClan) const +{ + int Result = FRIEND_NO; + unsigned NameHash = str_quickhash(pName); + unsigned ClanHash = str_quickhash(pClan); + for(int i = 0; i < m_NumFriends; ++i) + { + if((g_Config.m_ClFriendsIgnoreClan && m_aFriends[i].m_aName[0]) || m_aFriends[i].m_ClanHash == ClanHash) + { + if(m_aFriends[i].m_aName[0] == 0) + Result = FRIEND_CLAN; + else if(m_aFriends[i].m_NameHash == NameHash) + { + Result = FRIEND_PLAYER; + break; + } + } + } + return Result; +} + +bool CFriends::IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const +{ + unsigned NameHash = str_quickhash(pName); + unsigned ClanHash = str_quickhash(pClan); + for(int i = 0; i < m_NumFriends; ++i) + { + if(((g_Config.m_ClFriendsIgnoreClan && m_aFriends[i].m_aName[0]) || m_aFriends[i].m_ClanHash == ClanHash) && + ((!PlayersOnly && m_aFriends[i].m_aName[0] == 0) || m_aFriends[i].m_NameHash == NameHash)) + return true; + } + return false; +} + +void CFriends::AddFriend(const char *pName, const char *pClan) +{ + if(m_NumFriends == MAX_FRIENDS || (pName[0] == 0 && pClan[0] == 0)) + return; + + // make sure we don't have the friend already + unsigned NameHash = str_quickhash(pName); + unsigned ClanHash = str_quickhash(pClan); + for(int i = 0; i < m_NumFriends; ++i) + { + if(m_aFriends[i].m_NameHash == NameHash && ((g_Config.m_ClFriendsIgnoreClan && m_aFriends[i].m_aName[0]) || m_aFriends[i].m_ClanHash == ClanHash)) + return; + } + + str_copy(m_aFriends[m_NumFriends].m_aName, pName, sizeof(m_aFriends[m_NumFriends].m_aName)); + str_copy(m_aFriends[m_NumFriends].m_aClan, pClan, sizeof(m_aFriends[m_NumFriends].m_aClan)); + m_aFriends[m_NumFriends].m_NameHash = NameHash; + m_aFriends[m_NumFriends].m_ClanHash = ClanHash; + ++m_NumFriends; +} + +void CFriends::RemoveFriend(const char *pName, const char *pClan) +{ + unsigned NameHash = str_quickhash(pName); + unsigned ClanHash = str_quickhash(pClan); + for(int i = 0; i < m_NumFriends; ++i) + { + if(m_aFriends[i].m_NameHash == NameHash && ((g_Config.m_ClFriendsIgnoreClan && m_aFriends[i].m_aName[0]) || m_aFriends[i].m_ClanHash == ClanHash)) + { + RemoveFriend(i); + return; + } + } +} + +void CFriends::RemoveFriend(int Index) +{ + if(Index >= 0 && Index < m_NumFriends) + { + mem_move(&m_aFriends[Index], &m_aFriends[Index+1], sizeof(CFriendInfo)*(m_NumFriends-(Index+1))); + --m_NumFriends; + } +} + +void CFriends::Friends() +{ + char aBuf[128]; + IConsole *pConsole = Kernel()->RequestInterface<IConsole>(); + if(pConsole) + { + for(int i = 0; i < m_NumFriends; ++i) + { + str_format(aBuf, sizeof(aBuf), "Name: %s, Clan: %s", m_aFriends[i].m_aName, m_aFriends[i].m_aClan); + pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_Foes?"foes":"friends", aBuf, true); + } + } +} + +void CFriends::ConfigSaveCallback(IConfig *pConfig, void *pUserData) +{ + CFriends *pSelf = (CFriends *)pUserData; + char aBuf[128]; + const char *pEnd = aBuf+sizeof(aBuf)-4; + for(int i = 0; i < pSelf->m_NumFriends; ++i) + { + str_copy(aBuf, pSelf->m_Foes ? "add_foe " : "add_friend ", sizeof(aBuf)); + + const char *pSrc = pSelf->m_aFriends[i].m_aName; + char *pDst = aBuf+str_length(aBuf); + *pDst++ = '"'; + while(*pSrc && pDst < pEnd) + { + if(*pSrc == '"' || *pSrc == '\\') // escape \ and " + *pDst++ = '\\'; + *pDst++ = *pSrc++; + } + *pDst++ = '"'; + *pDst++ = ' '; + + pSrc = pSelf->m_aFriends[i].m_aClan; + *pDst++ = '"'; + while(*pSrc && pDst < pEnd) + { + if(*pSrc == '"' || *pSrc == '\\') // escape \ and " + *pDst++ = '\\'; + *pDst++ = *pSrc++; + } + *pDst++ = '"'; + *pDst++ = 0; + + pConfig->WriteLine(aBuf); + } +} diff --git a/src/engine/client/friends.h b/src/engine/client/friends.h new file mode 100644 index 0000000..4ddc043 --- /dev/null +++ b/src/engine/client/friends.h @@ -0,0 +1,36 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_FRIENDS_H +#define ENGINE_CLIENT_FRIENDS_H + +#include <engine/friends.h> + +class CFriends : public IFriends +{ + CFriendInfo m_aFriends[MAX_FRIENDS]; + int m_Foes; + int m_NumFriends; + + static void ConAddFriend(IConsole::IResult *pResult, void *pUserData); + static void ConRemoveFriend(IConsole::IResult *pResult, void *pUserData); + static void ConFriends(IConsole::IResult *pResult, void *pUserData); + + static void ConfigSaveCallback(IConfig *pConfig, void *pUserData); + +public: + CFriends(); + + void Init(bool Foes = false); + + int NumFriends() const { return m_NumFriends; } + const CFriendInfo *GetFriend(int Index) const; + int GetFriendState(const char *pName, const char *pClan) const; + bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const; + + void AddFriend(const char *pName, const char *pClan); + void RemoveFriend(const char *pName, const char *pClan); + void RemoveFriend(int Index); + void Friends(); +}; + +#endif diff --git a/src/engine/client/graphics.cpp b/src/engine/client/graphics.cpp new file mode 100644 index 0000000..3627b45 --- /dev/null +++ b/src/engine/client/graphics.cpp @@ -0,0 +1,1203 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/detect.h> +#include <base/math.h> +#include <base/tl/threading.h> + +#if defined(CONF_FAMILY_WINDOWS) + // For FlashWindowEx, FLASHWINFO, FLASHW_TRAY + #define _WIN32_WINNT 0x0501 + #define WINVER 0x0501 +#endif + +#include "SDL.h" +#include "SDL_syswm.h" +#if defined(__ANDROID__) + #define GL_GLEXT_PROTOTYPES + #include <GLES/gl.h> + #include <GLES/glext.h> + #include <GL/glu.h> + #define glOrtho glOrthof +#else + #include "SDL_opengl.h" +#endif + +#if defined(SDL_VIDEO_DRIVER_X11) + #include <X11/Xutil.h> + #include <X11/Xlib.h> +#endif + +#include <base/system.h> +#include <engine/external/pnglite/pnglite.h> + +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/storage.h> +#include <engine/keys.h> +#include <engine/console.h> + +#include <math.h> // cosf, sinf + +#include "graphics.h" + + +#if defined(CONF_PLATFORM_MACOSX) + + class semaphore + { + SDL_sem *sem; + public: + semaphore() { sem = SDL_CreateSemaphore(0); } + ~semaphore() { SDL_DestroySemaphore(sem); } + void wait() { SDL_SemWait(sem); } + void signal() { SDL_SemPost(sem); } + }; +#endif + + +static CVideoMode g_aFakeModes[] = { + {320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8}, + {720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8}, + {1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8}, + {1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8}, + {1280,1024,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8}, + {1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,1000,8,8,8}, + {1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8}, + {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}, + {1280,768,5,6,5}, {1280,800,5,6,5}, {1280,960,5,6,5}, + {1280,1024,5,6,5}, {1368,768,5,6,5}, {1400,1050,5,6,5}, + {1440,900,5,6,5}, {1440,1050,5,6,5}, {1600,1000,5,6,5}, + {1600,1200,5,6,5}, {1680,1050,5,6,5}, {1792,1344,5,6,5}, + {1800,1440,5,6,5}, {1856,1392,5,6,5}, {1920,1080,5,6,5}, + {1920,1200,5,6,5}, {1920,1440,5,6,5}, {1920,2400,5,6,5}, + {2048,1536,5,6,5} +}; + +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); + + glVertexPointer(3, GL_FLOAT, + sizeof(CVertex), + (char*)m_aVertices); + glTexCoordPointer(2, GL_FLOAT, + sizeof(CVertex), + (char*)m_aVertices + sizeof(float)*3); + glColorPointer(4, GL_FLOAT, + sizeof(CVertex), + (char*)m_aVertices + sizeof(float)*5); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + + if(m_RenderEnable) + { + if(m_Drawing == DRAWING_QUADS) + { +#if defined(__ANDROID__) + for( unsigned i = 0, j = m_NumVertices; i < j; i += 4 ) + glDrawArrays(GL_TRIANGLE_FAN, i, 4); +#else + if(g_Config.m_GfxQuadAsTriangle) + glDrawArrays(GL_TRIANGLES, 0, m_NumVertices); + else + glDrawArrays(GL_QUADS, 0, m_NumVertices); +#endif + } + else if(m_Drawing == DRAWING_LINES) + glDrawArrays(GL_LINES, 0, m_NumVertices); + } + + // Reset pointer + m_NumVertices = 0; +} + +void CGraphics_OpenGL::AddVertices(int Count) +{ + m_NumVertices += Count; + if((m_NumVertices + Count) >= MAX_VERTICES) + Flush(); +} + +void CGraphics_OpenGL::Rotate(const CPoint &rCenter, CVertex *pPoints, int NumPoints) +{ + float c = cosf(m_Rotation); + float s = sinf(m_Rotation); + float x, y; + int i; + + for(i = 0; i < NumPoints; i++) + { + x = pPoints[i].m_Pos.x - rCenter.x; + y = pPoints[i].m_Pos.y - rCenter.y; + pPoints[i].m_Pos.x = x * c - y * s + rCenter.x; + pPoints[i].m_Pos.y = x * s + y * c + rCenter.y; + } +} + +unsigned char CGraphics_OpenGL::Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp) +{ + int Value = 0; + for(int x = 0; x < ScaleW; x++) + for(int y = 0; y < ScaleH; y++) + Value += pData[((v+y)*w+(u+x))*Bpp+Offset]; + return Value/(ScaleW*ScaleH); +} + +unsigned char *CGraphics_OpenGL::Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData) +{ + unsigned char *pTmpData; + int ScaleW = Width/NewWidth; + int ScaleH = Height/NewHeight; + + int Bpp = 3; + if(Format == CImageInfo::FORMAT_RGBA) + Bpp = 4; + + pTmpData = (unsigned char *)mem_alloc(NewWidth*NewHeight*Bpp, 1); + + int c = 0; + for(int y = 0; y < NewHeight; y++) + for(int x = 0; x < NewWidth; x++, c++) + { + pTmpData[c*Bpp] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 0, ScaleW, ScaleH, Bpp); + pTmpData[c*Bpp+1] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 1, ScaleW, ScaleH, Bpp); + pTmpData[c*Bpp+2] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 2, ScaleW, ScaleH, Bpp); + if(Bpp == 4) + pTmpData[c*Bpp+3] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 3, ScaleW, ScaleH, Bpp); + } + + return pTmpData; +} + +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; +} + +void CGraphics_OpenGL::ClipEnable(int x, int y, int w, int h) +{ + if(x < 0) + w += x; + if(y < 0) + h += y; + + x = clamp(x, 0, ScreenWidth()); + y = clamp(y, 0, ScreenHeight()); + w = clamp(w, 0, ScreenWidth()-x); + h = clamp(h, 0, ScreenHeight()-y); + + glScissor(x, ScreenHeight()-(y+h), w, h); + glEnable(GL_SCISSOR_TEST); +} + +void CGraphics_OpenGL::ClipDisable() +{ + //if(no_gfx) return; + glDisable(GL_SCISSOR_TEST); +} + +void CGraphics_OpenGL::BlendNone() +{ + glDisable(GL_BLEND); +} + +void CGraphics_OpenGL::BlendNormal() +{ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +} + +void CGraphics_OpenGL::BlendAdditive() +{ + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); +} + +void CGraphics_OpenGL::WrapNormal() +{ + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); +} + +void CGraphics_OpenGL::WrapClamp() +{ + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +} + +int CGraphics_OpenGL::MemoryUsage() const +{ + return m_TextureMemoryUsage; +} + +void CGraphics_OpenGL::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) +{ + m_ScreenX0 = TopLeftX; + m_ScreenY0 = TopLeftY; + m_ScreenX1 = BottomRightX; + m_ScreenY1 = BottomRightY; + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(TopLeftX, BottomRightX, BottomRightY, TopLeftY, 1.0f, 10.f); +} + +void CGraphics_OpenGL::GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) +{ + *pTopLeftX = m_ScreenX0; + *pTopLeftY = m_ScreenY0; + *pBottomRightX = m_ScreenX1; + *pBottomRightY = m_ScreenY1; +} + +void CGraphics_OpenGL::LinesBegin() +{ + dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice"); + m_Drawing = DRAWING_LINES; + SetColor(1,1,1,1); +} + +void CGraphics_OpenGL::LinesEnd() +{ + dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesEnd without begin"); + Flush(); + m_Drawing = 0; +} + +void CGraphics_OpenGL::LinesDraw(const CLineItem *pArray, int Num) +{ + dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesDraw without begin"); + + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 2*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 2*i + 1].m_Color = m_aColor[1]; + } + + AddVertices(2*Num); +} + +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; + m_FirstFreeTexture = Index; + return 0; +} + +int CGraphics_OpenGL::LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData) +{ + int Oglformat = GL_RGBA; + if(Format == CImageInfo::FORMAT_RGB) + Oglformat = GL_RGB; + else if(Format == CImageInfo::FORMAT_ALPHA) + Oglformat = GL_ALPHA; + + glBindTexture(GL_TEXTURE_2D, m_aTextures[TextureID].m_Tex); + glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pData); + return 0; +} + +int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) +{ + int Mipmap = 1; + unsigned char *pTexData = (unsigned char *)pData; + unsigned char *pTmpData = 0; + 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) && (Format == CImageInfo::FORMAT_RGBA || Format == CImageInfo::FORMAT_RGB)) + { + if(Width > GL_MAX_TEXTURE_SIZE || Height > GL_MAX_TEXTURE_SIZE) + { + int NewWidth = min(Width, GL_MAX_TEXTURE_SIZE); + int NewHeight = min(Height, GL_MAX_TEXTURE_SIZE); + pTmpData = Rescale(Width, Height, NewWidth, NewHeight, Format, pTexData); + pTexData = pTmpData; + Width = NewWidth; + Height = NewHeight; + } + else if(Width > 16 && Height > 16 && g_Config.m_GfxTextureQuality == 0) + { + pTmpData = Rescale(Width, Height, Width/2, Height/2, Format, pTexData); + pTexData = pTmpData; + Width /= 2; + Height /= 2; + } + } + + Oglformat = GL_RGBA; + if(Format == CImageInfo::FORMAT_RGB) + Oglformat = GL_RGB; + else if(Format == CImageInfo::FORMAT_ALPHA) + Oglformat = GL_ALPHA; + + // upload texture +#if defined(__ANDROID__) + StoreOglformat = Oglformat; +#else + if(g_Config.m_GfxTextureCompression) + { + StoreOglformat = GL_COMPRESSED_RGBA_ARB; + if(StoreFormat == CImageInfo::FORMAT_RGB) + StoreOglformat = GL_COMPRESSED_RGB_ARB; + else if(StoreFormat == CImageInfo::FORMAT_ALPHA) + StoreOglformat = GL_COMPRESSED_ALPHA_ARB; + } + else + { + StoreOglformat = GL_RGBA; + if(StoreFormat == CImageInfo::FORMAT_RGB) + StoreOglformat = GL_RGB; + else if(StoreFormat == CImageInfo::FORMAT_ALPHA) + StoreOglformat = GL_ALPHA; + } +#endif + + glGenTextures(1, &m_aTextures[Tex].m_Tex); + glBindTexture(GL_TEXTURE_2D, m_aTextures[Tex].m_Tex); + + if(Flags&TEXLOAD_NOMIPMAPS) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, Width, Height, 0, Oglformat, GL_UNSIGNED_BYTE, pData); + } + else + { + 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; + if(StoreFormat == CImageInfo::FORMAT_RGB) + PixelSize = 3; + else if(StoreFormat == CImageInfo::FORMAT_ALPHA) + PixelSize = 1; + + m_aTextures[Tex].m_MemSize = Width*Height*PixelSize; + if(Mipmap) + { + while(Width > 2 && Height > 2) + { + Width>>=1; + Height>>=1; + m_aTextures[Tex].m_MemSize += Width*Height*PixelSize; + } + } + } + + m_TextureMemoryUsage += m_aTextures[Tex].m_MemSize; + mem_free(pTmpData); + return Tex; +} + +// simple uncompressed RGBA loaders +int CGraphics_OpenGL::LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) +{ + int l = str_length(pFilename); + int ID; + CImageInfo Img; + + if(l < 3) + return -1; + if(LoadPNG(&Img, pFilename, StorageType)) + { + if (StoreFormat == CImageInfo::FORMAT_AUTO) + StoreFormat = Img.m_Format; + + ID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags); + mem_free(Img.m_pData); + if(ID != m_InvalidTexture && g_Config.m_Debug) + dbg_msg("graphics/texture", "loaded %s", pFilename); + return ID; + } + + return m_InvalidTexture; +} + +int CGraphics_OpenGL::LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) +{ + char aCompleteFilename[512]; + unsigned char *pBuffer; + png_t Png; // ignore_convention + + // open file for reading + png_init(0,0); // ignore_convention + + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename)); + if(File) + io_close(File); + else + { + 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) + { + dbg_msg("game/png", "failed to open file. filename='%s'", aCompleteFilename); + if(Error != PNG_FILE_ERROR) + 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 + pImg->m_Format = CImageInfo::FORMAT_RGB; + else if(Png.color_type == PNG_TRUECOLOR_ALPHA) // ignore_convention + pImg->m_Format = CImageInfo::FORMAT_RGBA; + pImg->m_pData = pBuffer; + return 1; +} + +void CGraphics_OpenGL::ScreenshotDirect(const char *pFilename) +{ + // fetch image data + int y; + int w = m_ScreenWidth; + int h = m_ScreenHeight; + unsigned char *pPixelData = (unsigned char *)mem_alloc(w*(h+1)*3, 1); + unsigned char *pTempRow = pPixelData+w*h*3; + GLint Alignment; + glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment); + 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++) + { + mem_copy(pTempRow, pPixelData+y*w*3, w*3); + 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)); + if(File) + io_close(File); + + // save png + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "saved screenshot to '%s'", aWholePath); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + png_open_file_write(&Png, aWholePath); // ignore_convention + png_set_data(&Png, w, h, 8, PNG_TRUECOLOR, (unsigned char *)pPixelData); // ignore_convention + png_close_file(&Png); // ignore_convention + } + + // clean up + mem_free(pPixelData); +} + +void CGraphics_OpenGL::TextureSet(int TextureID) +{ + dbg_assert(m_Drawing == 0, "called Graphics()->TextureSet within begin"); + if(TextureID == -1) + { + glDisable(GL_TEXTURE_2D); + } + else + { + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, m_aTextures[TextureID].m_Tex); + } +} + +void CGraphics_OpenGL::Clear(float r, float g, float b) +{ + glClearColor(r,g,b,0.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +void CGraphics_OpenGL::QuadsBegin() +{ + dbg_assert(m_Drawing == 0, "called Graphics()->QuadsBegin twice"); + m_Drawing = DRAWING_QUADS; + + QuadsSetSubset(0,0,1,1); + QuadsSetRotation(0); + SetColor(1,1,1,1); +} + +void CGraphics_OpenGL::QuadsEnd() +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsEnd without begin"); + Flush(); + m_Drawing = 0; +} + +void CGraphics_OpenGL::QuadsSetRotation(float Angle) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetRotation without begin"); + m_Rotation = Angle; +} + +void CGraphics_OpenGL::SetColorVertex(const CColorVertex *pArray, int Num) +{ + dbg_assert(m_Drawing != 0, "called Graphics()->SetColorVertex without begin"); + + for(int i = 0; i < Num; ++i) + { + m_aColor[pArray[i].m_Index].r = pArray[i].m_R; + m_aColor[pArray[i].m_Index].g = pArray[i].m_G; + m_aColor[pArray[i].m_Index].b = pArray[i].m_B; + m_aColor[pArray[i].m_Index].a = pArray[i].m_A; + } +} + +void CGraphics_OpenGL::SetColor(float r, float g, float b, float a) +{ + dbg_assert(m_Drawing != 0, "called Graphics()->SetColor without begin"); + CColorVertex Array[4] = { + CColorVertex(0, r, g, b, a), + CColorVertex(1, r, g, b, a), + CColorVertex(2, r, g, b, a), + CColorVertex(3, r, g, b, a)}; + SetColorVertex(Array, 4); +} + +void CGraphics_OpenGL::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetSubset without begin"); + + m_aTexture[0].u = TlU; m_aTexture[1].u = BrU; + m_aTexture[0].v = TlV; m_aTexture[1].v = TlV; + + m_aTexture[3].u = TlU; m_aTexture[2].u = BrU; + m_aTexture[3].v = BrV; m_aTexture[2].v = BrV; +} + +void CGraphics_OpenGL::QuadsSetSubsetFree( + float x0, float y0, float x1, float y1, + float x2, float y2, float x3, float y3) +{ + m_aTexture[0].u = x0; m_aTexture[0].v = y0; + m_aTexture[1].u = x1; m_aTexture[1].v = y1; + m_aTexture[2].u = x2; m_aTexture[2].v = y2; + m_aTexture[3].u = x3; m_aTexture[3].v = y3; +} + +void CGraphics_OpenGL::QuadsDraw(CQuadItem *pArray, int Num) +{ + for(int i = 0; i < Num; ++i) + { + pArray[i].m_X -= pArray[i].m_Width/2; + pArray[i].m_Y -= pArray[i].m_Height/2; + } + + QuadsDrawTL(pArray, Num); +} + +void CGraphics_OpenGL::QuadsDrawTL(const CQuadItem *pArray, int Num) +{ + CPoint Center; + Center.z = 0; + + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawTL without begin"); + + if(g_Config.m_GfxQuadAsTriangle) + { + for(int i = 0; i < Num; ++i) + { + // first triangle + m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 6*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 2].m_Color = m_aColor[2]; + + // second triangle + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i + 3].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 4].m_Color = m_aColor[2]; + + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 5].m_Color = m_aColor[3]; + + if(m_Rotation != 0) + { + Center.x = pArray[i].m_X + pArray[i].m_Width/2; + Center.y = pArray[i].m_Y + pArray[i].m_Height/2; + + Rotate(Center, &m_aVertices[m_NumVertices + 6*i], 6); + } + } + + AddVertices(3*2*Num); + } + else + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[2]; + + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[3]; + + if(m_Rotation != 0) + { + Center.x = pArray[i].m_X + pArray[i].m_Width/2; + Center.y = pArray[i].m_Y + pArray[i].m_Height/2; + + Rotate(Center, &m_aVertices[m_NumVertices + 4*i], 4); + } + } + + AddVertices(4*Num); + } +} + +void CGraphics_OpenGL::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawFreeform without begin"); + + if(g_Config.m_GfxQuadAsTriangle) + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 6*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 2].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i + 3].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 4].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y2; + m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 5].m_Color = m_aColor[2]; + } + + AddVertices(3*2*Num); + } + else + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2; + 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); + } +} + +void CGraphics_OpenGL::QuadsText(float x, float y, float Size, const char *pText) +{ + float StartX = x; + + while(*pText) + { + char c = *pText; + pText++; + + if(c == '\n') + { + x = StartX; + y += Size; + } + else + { + QuadsSetSubset( + (c%16)/16.0f, + (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; + } + } +} + +int 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; + + // init textures + m_FirstFreeTexture = 0; + for(int i = 0; i < MAX_TEXTURES; i++) + m_aTextures[i].m_Next = i+1; + m_aTextures[MAX_TEXTURES-1].m_Next = -1; + + // set some default settings + glEnable(GL_BLEND); + glDisable(GL_CULL_FACE); + 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, + }; + + m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); + + return 0; +} + +int CGraphics_SDL::TryInit() +{ + const SDL_VideoInfo *pInfo = SDL_GetVideoInfo(); + SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows + + // use current resolution as default +#ifndef __ANDROID__ + if(g_Config.m_GfxScreenWidth == 0 || g_Config.m_GfxScreenHeight == 0) +#endif + { + g_Config.m_GfxScreenWidth = pInfo->current_w; + g_Config.m_GfxScreenHeight = pInfo->current_h; + } + + m_ScreenWidth = g_Config.m_GfxScreenWidth; + m_ScreenHeight = g_Config.m_GfxScreenHeight; + + // set flags + int Flags = SDL_OPENGL; + if(g_Config.m_DbgResizable) + Flags |= SDL_RESIZABLE; + + if(pInfo->hw_available) // ignore_convention + Flags |= SDL_HWSURFACE; + else + Flags |= SDL_SWSURFACE; + + if(pInfo->blit_hw) // ignore_convention + Flags |= SDL_HWACCEL; + + if(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen) + { + dbg_msg("gfx", "both borderless and fullscreen activated, disabling borderless"); + g_Config.m_GfxBorderless = 0; + } + + if(g_Config.m_GfxBorderless) + Flags |= SDL_NOFRAME; + else if(g_Config.m_GfxFullscreen) + Flags |= SDL_FULLSCREEN; + + // set gl attributes + if(g_Config.m_GfxFsaaSamples) + { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, g_Config.m_GfxFsaaSamples); + } + else + { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); + } + + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, g_Config.m_GfxVsync); + + // set caption + SDL_WM_SetCaption("DDNet Client", "DDNet Client"); + + // create window + m_pScreenSurface = SDL_SetVideoMode(m_ScreenWidth, m_ScreenHeight, 0, Flags); + if(m_pScreenSurface == NULL) + { + dbg_msg("gfx", "unable to set video mode: %s", SDL_GetError()); + return -1; + } + + return 0; +} + + +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 + dbg_msg("gfx", "disabling FSAA and trying again"); + + if(TryInit() == 0) + return 0; + } + + // try lowering the resolution + if(g_Config.m_GfxScreenWidth != 640 || g_Config.m_GfxScreenHeight != 480) + { + dbg_msg("gfx", "setting resolution to 640x480 and trying again"); + g_Config.m_GfxScreenWidth = 640; + g_Config.m_GfxScreenHeight = 480; + + if(TryInit() == 0) + return 0; + } + + dbg_msg("gfx", "out of ideas. failed to init graphics"); + + return -1; +} + + +CGraphics_SDL::CGraphics_SDL() +{ + m_pScreenSurface = 0; +} + +int 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 -1; + } + } + + 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=center"); // ignore_convention + #endif + + if(InitWindow() != 0) + return -1; + + SDL_ShowCursor(0); + + CGraphics_OpenGL::Init(); + + MapScreen(0,0,g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight); + return 0; +} + +void CGraphics_SDL::Shutdown() +{ + // TODO: SDL, is this correct? + SDL_Quit(); +} + +void CGraphics_SDL::Minimize() +{ + SDL_WM_IconifyWindow(); +} + +void CGraphics_SDL::Maximize() +{ + // TODO: SDL +} + +int CGraphics_SDL::WindowActive() +{ + return SDL_GetAppState()&SDL_APPINPUTFOCUS; +} + +int CGraphics_SDL::WindowOpen() +{ + return SDL_GetAppState()&SDL_APPACTIVE; +} + +void CGraphics_SDL::NotifyWindow() +{ + // get window handle + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if(!SDL_GetWMInfo(&info)) + { + dbg_msg("gfx", "unable to obtain window handle"); + return; + } + + #if defined(CONF_FAMILY_WINDOWS) + FLASHWINFO desc; + desc.cbSize = sizeof(desc); + desc.hwnd = info.window; + desc.dwFlags = FLASHW_TRAY; + desc.uCount = 3; // flash 3 times + desc.dwTimeout = 0; + + FlashWindowEx(&desc); + #elif defined(SDL_VIDEO_DRIVER_X11) && !defined(CONF_PLATFORM_MACOSX) + Display *dpy = info.info.x11.display; + Window win; + if(m_pScreenSurface->flags & SDL_FULLSCREEN) + win = info.info.x11.fswindow; + else + win = info.info.x11.wmwindow; + + // Old hints + XWMHints *wmhints; + wmhints = XAllocWMHints(); + wmhints->flags = XUrgencyHint; + XSetWMHints(dpy, win, wmhints); + XFree(wmhints); + + // More modern way of notifying + static Atom demandsAttention = XInternAtom(dpy, "_NET_WM_STATE_DEMANDS_ATTENTION", true); + static Atom wmState = XInternAtom(dpy, "_NET_WM_STATE", true); + XChangeProperty(dpy, win, wmState, XA_ATOM, 32, PropModeReplace, + (unsigned char *) &demandsAttention, 1); + #endif +} + +void CGraphics_SDL::TakeScreenshot(const char *pFilename) +{ + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate); + m_DoScreenshot = true; +} + +void CGraphics_SDL::TakeCustomScreenshot(const char *pFilename) +{ + str_copy(m_aScreenshotName, pFilename, sizeof(m_aScreenshotName)); + m_DoScreenshot = true; +} + + +void CGraphics_SDL::Swap() +{ + if(m_DoScreenshot) + { + if(WindowActive()) + ScreenshotDirect(m_aScreenshotName); + m_DoScreenshot = false; + } + + SDL_GL_SwapBuffers(); + + if(g_Config.m_GfxFinish) + glFinish(); +} + + +int CGraphics_SDL::GetVideoModes(CVideoMode *pModes, int MaxModes) +{ + int NumModes = sizeof(g_aFakeModes)/sizeof(CVideoMode); + SDL_Rect **ppModes; + + if(g_Config.m_GfxDisplayAllModes) + { + int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode); + mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes)); + if(MaxModes < Count) + 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) + { + // no modes + NumModes = 0; + } + else if(ppModes == (SDL_Rect**)-1) + { + // all modes + } + else + { + NumModes = 0; + for(int i = 0; ppModes[i]; ++i) + { + if(NumModes == MaxModes) + break; + pModes[NumModes].m_Width = ppModes[i]->w; + pModes[NumModes].m_Height = ppModes[i]->h; + pModes[NumModes].m_Red = 8; + pModes[NumModes].m_Green = 8; + pModes[NumModes].m_Blue = 8; + NumModes++; + } + } + + return NumModes; +} + +// syncronization +void CGraphics_SDL::InsertSignal(semaphore *pSemaphore) +{ + pSemaphore->signal(); +} + +bool CGraphics_SDL::IsIdle() +{ + return true; +} + +void CGraphics_SDL::WaitForIdle() +{ +} + +extern IEngineGraphics *CreateEngineGraphics() { return new CGraphics_SDL(); } diff --git a/src/engine/client/graphics.h b/src/engine/client/graphics.h new file mode 100644 index 0000000..9fefcd2 --- /dev/null +++ b/src/engine/client/graphics.h @@ -0,0 +1,159 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_GRAPHICS_H +#define ENGINE_CLIENT_GRAPHICS_H + +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; + typedef struct { float r, g, b, a; } CColor; + + typedef struct + { + CPoint m_Pos; + CTexCoord m_Tex; + CColor m_Color; + } CVertex; + + enum + { + MAX_VERTICES = 32*1024, + MAX_TEXTURES = 1024*4, + + DRAWING_QUADS=1, + DRAWING_LINES=2 + }; + + CVertex m_aVertices[MAX_VERTICES]; + int m_NumVertices; + + CColor m_aColor[4]; + CTexCoord m_aTexture[4]; + + bool m_RenderEnable; + + float m_Rotation; + int m_Drawing; + bool m_DoScreenshot; + char m_aScreenshotName[128]; + + float m_ScreenX0; + float m_ScreenY0; + float m_ScreenX1; + float m_ScreenY1; + + int m_InvalidTexture; + + struct CTexture + { + GLuint m_Tex; + int m_MemSize; + int m_Flags; + int m_Next; + }; + + CTexture m_aTextures[MAX_TEXTURES]; + int m_FirstFreeTexture; + int m_TextureMemoryUsage; + + void Flush(); + void AddVertices(int Count); + void Rotate(const CPoint &rCenter, CVertex *pPoints, int NumPoints); + + static unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp); + static unsigned char *Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData); +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 void WrapNormal(); + virtual void WrapClamp(); + + 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); + virtual int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData); + + // simple uncompressed RGBA loaders + virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags); + virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType); + + void ScreenshotDirect(const char *pFilename); + + virtual void TextureSet(int TextureID); + + virtual void Clear(float r, float g, float b); + + virtual void QuadsBegin(); + virtual void QuadsEnd(); + virtual void QuadsSetRotation(float Angle); + + virtual void SetColorVertex(const CColorVertex *pArray, int Num); + virtual void SetColor(float r, float g, float b, float a); + + virtual void QuadsSetSubset(float TlU, float TlV, float BrU, float BrV); + virtual void QuadsSetSubsetFree( + float x0, float y0, float x1, float y1, + float x2, float y2, float x3, float y3); + + virtual void QuadsDraw(CQuadItem *pArray, int Num); + 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, const char *pText); + + virtual int Init(); +}; + +class CGraphics_SDL : public CGraphics_OpenGL +{ + SDL_Surface *m_pScreenSurface; + + int TryInit(); + int InitWindow(); +public: + CGraphics_SDL(); + + virtual int Init(); + virtual void Shutdown(); + + virtual void Minimize(); + virtual void Maximize(); + + virtual int WindowActive(); + virtual int WindowOpen(); + + virtual void NotifyWindow(); + + virtual void TakeScreenshot(const char *pFilename); + virtual void TakeCustomScreenshot(const char *pFilename); + virtual void Swap(); + + virtual int GetVideoModes(CVideoMode *pModes, int MaxModes); + + // syncronization + virtual void InsertSignal(semaphore *pSemaphore); + virtual bool IsIdle(); + virtual void WaitForIdle(); +}; + +#endif diff --git a/src/engine/client/graphics_threaded.cpp b/src/engine/client/graphics_threaded.cpp new file mode 100644 index 0000000..7f733d4 --- /dev/null +++ b/src/engine/client/graphics_threaded.cpp @@ -0,0 +1,993 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/detect.h> +#include <base/math.h> +#include <base/tl/threading.h> + +#if defined(CONF_FAMILY_UNIX) +#include <pthread.h> +#endif + +#include <base/system.h> +#include <engine/external/pnglite/pnglite.h> + +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/storage.h> +#include <engine/keys.h> +#include <engine/console.h> + +#include <math.h> // cosf, sinf + +#include "graphics_threaded.h" + +static CVideoMode g_aFakeModes[] = { + {320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8}, + {720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8}, + {1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8}, + {1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8}, + {1280,1024,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8}, + {1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,1000,8,8,8}, + {1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8}, + {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}, + {1280,768,5,6,5}, {1280,800,5,6,5}, {1280,960,5,6,5}, + {1280,1024,5,6,5}, {1368,768,5,6,5}, {1400,1050,5,6,5}, + {1440,900,5,6,5}, {1440,1050,5,6,5}, {1600,1000,5,6,5}, + {1600,1200,5,6,5}, {1680,1050,5,6,5}, {1792,1344,5,6,5}, + {1800,1440,5,6,5}, {1856,1392,5,6,5}, {1920,1080,5,6,5}, + {1920,1200,5,6,5}, {1920,1440,5,6,5}, {1920,2400,5,6,5}, + {2048,1536,5,6,5} +}; + +void CGraphics_Threaded::FlushVertices() +{ + if(m_NumVertices == 0) + return; + + int NumVerts = m_NumVertices; + m_NumVertices = 0; + + CCommandBuffer::SCommand_Render Cmd; + Cmd.m_State = m_State; + + if(m_Drawing == DRAWING_QUADS) + { + if(g_Config.m_GfxQuadAsTriangle) + { + Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_TRIANGLES; + Cmd.m_PrimCount = NumVerts/3; + } + else + { + Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_QUADS; + Cmd.m_PrimCount = NumVerts/4; + } + } + else if(m_Drawing == DRAWING_LINES) + { + Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_LINES; + Cmd.m_PrimCount = NumVerts/2; + } + else + return; + + Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); + if(Cmd.m_pVertices == 0x0) + { + // kick command buffer and try again + KickCommandBuffer(); + + Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); + if(Cmd.m_pVertices == 0x0) + { + dbg_msg("graphics", "failed to allocate data for vertices"); + return; + } + } + + // check if we have enough free memory in the commandbuffer + if(!m_pCommandBuffer->AddCommand(Cmd)) + { + // kick command buffer and try again + KickCommandBuffer(); + + Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); + if(Cmd.m_pVertices == 0x0) + { + dbg_msg("graphics", "failed to allocate data for vertices"); + return; + } + + if(!m_pCommandBuffer->AddCommand(Cmd)) + { + dbg_msg("graphics", "failed to allocate memory for render command"); + return; + } + } + + mem_copy(Cmd.m_pVertices, m_aVertices, sizeof(CCommandBuffer::SVertex)*NumVerts); +} + +void CGraphics_Threaded::AddVertices(int Count) +{ + m_NumVertices += Count; + if((m_NumVertices + Count) >= MAX_VERTICES) + FlushVertices(); +} + +void CGraphics_Threaded::Rotate(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints, int NumPoints) +{ + float c = cosf(m_Rotation); + float s = sinf(m_Rotation); + float x, y; + int i; + + for(i = 0; i < NumPoints; i++) + { + x = pPoints[i].m_Pos.x - rCenter.x; + y = pPoints[i].m_Pos.y - rCenter.y; + pPoints[i].m_Pos.x = x * c - y * s + rCenter.x; + pPoints[i].m_Pos.y = x * s + y * c + rCenter.y; + } +} + +CGraphics_Threaded::CGraphics_Threaded() +{ + m_State.m_ScreenTL.x = 0; + m_State.m_ScreenTL.y = 0; + m_State.m_ScreenBR.x = 0; + m_State.m_ScreenBR.y = 0; + m_State.m_ClipEnable = false; + m_State.m_ClipX = 0; + m_State.m_ClipY = 0; + m_State.m_ClipW = 0; + m_State.m_ClipH = 0; + m_State.m_Texture = -1; + m_State.m_BlendMode = CCommandBuffer::BLEND_NONE; + m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT; + + m_CurrentCommandBuffer = 0; + m_pCommandBuffer = 0x0; + m_apCommandBuffers[0] = 0x0; + m_apCommandBuffers[1] = 0x0; + + m_NumVertices = 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; +} + +void CGraphics_Threaded::ClipEnable(int x, int y, int w, int h) +{ + if(x < 0) + w += x; + if(y < 0) + h += y; + + x = clamp(x, 0, ScreenWidth()); + y = clamp(y, 0, ScreenHeight()); + w = clamp(w, 0, ScreenWidth()-x); + h = clamp(h, 0, ScreenHeight()-y); + + m_State.m_ClipEnable = true; + m_State.m_ClipX = x; + m_State.m_ClipY = ScreenHeight()-(y+h); + m_State.m_ClipW = w; + m_State.m_ClipH = h; +} + +void CGraphics_Threaded::ClipDisable() +{ + m_State.m_ClipEnable = false; +} + +void CGraphics_Threaded::BlendNone() +{ + m_State.m_BlendMode = CCommandBuffer::BLEND_NONE; +} + +void CGraphics_Threaded::BlendNormal() +{ + m_State.m_BlendMode = CCommandBuffer::BLEND_ALPHA; +} + +void CGraphics_Threaded::BlendAdditive() +{ + m_State.m_BlendMode = CCommandBuffer::BLEND_ADDITIVE; +} + +void CGraphics_Threaded::WrapNormal() +{ + m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT; +} + +void CGraphics_Threaded::WrapClamp() +{ + m_State.m_WrapMode = CCommandBuffer::WRAP_CLAMP; +} + +int CGraphics_Threaded::MemoryUsage() const +{ + return m_pBackend->MemoryUsage(); +} + +void CGraphics_Threaded::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) +{ + m_State.m_ScreenTL.x = TopLeftX; + m_State.m_ScreenTL.y = TopLeftY; + m_State.m_ScreenBR.x = BottomRightX; + m_State.m_ScreenBR.y = BottomRightY; +} + +void CGraphics_Threaded::GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) +{ + *pTopLeftX = m_State.m_ScreenTL.x; + *pTopLeftY = m_State.m_ScreenTL.y; + *pBottomRightX = m_State.m_ScreenBR.x; + *pBottomRightY = m_State.m_ScreenBR.y; +} + +void CGraphics_Threaded::LinesBegin() +{ + dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice"); + m_Drawing = DRAWING_LINES; + SetColor(1,1,1,1); +} + +void CGraphics_Threaded::LinesEnd() +{ + dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesEnd without begin"); + FlushVertices(); + m_Drawing = 0; +} + +void CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num) +{ + dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesDraw without begin"); + + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 2*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 2*i + 1].m_Color = m_aColor[1]; + } + + AddVertices(2*Num); +} + +int CGraphics_Threaded::UnloadTexture(int Index) +{ + if(Index == m_InvalidTexture) + return 0; + + if(Index < 0) + return 0; + + CCommandBuffer::SCommand_Texture_Destroy Cmd; + Cmd.m_Slot = Index; + m_pCommandBuffer->AddCommand(Cmd); + + m_aTextureIndices[Index] = m_FirstFreeTexture; + m_FirstFreeTexture = Index; + return 0; +} + +static int ImageFormatToTexFormat(int Format) +{ + if(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB; + if(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA; + if(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA; + return CCommandBuffer::TEXFORMAT_RGBA; +} + +static int ImageFormatToPixelSize(int Format) +{ + switch(Format) + { + case CImageInfo::FORMAT_RGB: return 3; + case CImageInfo::FORMAT_ALPHA: return 1; + default: return 4; + } +} + + +int CGraphics_Threaded::LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData) +{ + CCommandBuffer::SCommand_Texture_Update Cmd; + Cmd.m_Slot = TextureID; + Cmd.m_X = x; + Cmd.m_Y = y; + Cmd.m_Width = Width; + Cmd.m_Height = Height; + Cmd.m_Format = ImageFormatToTexFormat(Format); + + // calculate memory usage + int MemSize = Width*Height*ImageFormatToPixelSize(Format); + + // copy texture data + void *pTmpData = mem_alloc(MemSize, sizeof(void*)); + mem_copy(pTmpData, pData, MemSize); + Cmd.m_pData = pTmpData; + + // + m_pCommandBuffer->AddCommand(Cmd); + return 0; +} + +int CGraphics_Threaded::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) +{ + // don't waste memory on texture if we are stress testing + if(g_Config.m_DbgStress) + return m_InvalidTexture; + + // grab texture + int Tex = m_FirstFreeTexture; + m_FirstFreeTexture = m_aTextureIndices[Tex]; + m_aTextureIndices[Tex] = -1; + + CCommandBuffer::SCommand_Texture_Create Cmd; + Cmd.m_Slot = Tex; + Cmd.m_Width = Width; + Cmd.m_Height = Height; + Cmd.m_PixelSize = ImageFormatToPixelSize(Format); + Cmd.m_Format = ImageFormatToTexFormat(Format); + Cmd.m_StoreFormat = ImageFormatToTexFormat(StoreFormat); + + // flags + Cmd.m_Flags = 0; + if(Flags&IGraphics::TEXLOAD_NOMIPMAPS) + Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS; + if(g_Config.m_GfxTextureCompression) + Cmd.m_Flags |= CCommandBuffer::TEXFLAG_COMPRESSED; + if(g_Config.m_GfxTextureQuality || Flags&TEXLOAD_NORESAMPLE) + Cmd.m_Flags |= CCommandBuffer::TEXFLAG_QUALITY; + + // copy texture data + int MemSize = Width*Height*Cmd.m_PixelSize; + void *pTmpData = mem_alloc(MemSize, sizeof(void*)); + mem_copy(pTmpData, pData, MemSize); + Cmd.m_pData = pTmpData; + + // + m_pCommandBuffer->AddCommand(Cmd); + + return Tex; +} + +// simple uncompressed RGBA loaders +int CGraphics_Threaded::LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) +{ + int l = str_length(pFilename); + int ID; + CImageInfo Img; + + if(l < 3) + return -1; + if(LoadPNG(&Img, pFilename, StorageType)) + { + if (StoreFormat == CImageInfo::FORMAT_AUTO) + StoreFormat = Img.m_Format; + + ID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags); + mem_free(Img.m_pData); + if(ID != m_InvalidTexture && g_Config.m_Debug) + dbg_msg("graphics/texture", "loaded %s", pFilename); + return ID; + } + + return m_InvalidTexture; +} + +int CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) +{ + char aCompleteFilename[512]; + unsigned char *pBuffer; + png_t Png; // ignore_convention + + // open file for reading + png_init(0,0); // ignore_convention + + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename)); + if(File) + io_close(File); + else + { + 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) + { + dbg_msg("game/png", "failed to open file. filename='%s'", aCompleteFilename); + if(Error != PNG_FILE_ERROR) + 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 + pImg->m_Format = CImageInfo::FORMAT_RGB; + else if(Png.color_type == PNG_TRUECOLOR_ALPHA) // ignore_convention + pImg->m_Format = CImageInfo::FORMAT_RGBA; + pImg->m_pData = pBuffer; + return 1; +} + +void CGraphics_Threaded::KickCommandBuffer() +{ + m_pBackend->RunBuffer(m_pCommandBuffer); + + // swap buffer + m_CurrentCommandBuffer ^= 1; + m_pCommandBuffer = m_apCommandBuffers[m_CurrentCommandBuffer]; + m_pCommandBuffer->Reset(); +} + +void CGraphics_Threaded::ScreenshotDirect() +{ + // add swap command + CImageInfo Image; + mem_zero(&Image, sizeof(Image)); + + CCommandBuffer::SCommand_Screenshot Cmd; + Cmd.m_pImage = &Image; + m_pCommandBuffer->AddCommand(Cmd); + + // kick the buffer and wait for the result + KickCommandBuffer(); + WaitForIdle(); + + if(Image.m_pData) + { + // find filename + char aWholePath[1024]; + png_t Png; // ignore_convention + + IOHANDLE File = m_pStorage->OpenFile(m_aScreenshotName, 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); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); + png_open_file_write(&Png, aWholePath); // ignore_convention + png_set_data(&Png, Image.m_Width, Image.m_Height, 8, PNG_TRUECOLOR, (unsigned char *)Image.m_pData); // ignore_convention + png_close_file(&Png); // ignore_convention + + mem_free(Image.m_pData); + } +} + +void CGraphics_Threaded::TextureSet(int TextureID) +{ + dbg_assert(m_Drawing == 0, "called Graphics()->TextureSet within begin"); + m_State.m_Texture = TextureID; +} + +void CGraphics_Threaded::Clear(float r, float g, float b) +{ + CCommandBuffer::SCommand_Clear Cmd; + Cmd.m_Color.r = r; + Cmd.m_Color.g = g; + Cmd.m_Color.b = b; + Cmd.m_Color.a = 0; + m_pCommandBuffer->AddCommand(Cmd); +} + +void CGraphics_Threaded::QuadsBegin() +{ + dbg_assert(m_Drawing == 0, "called Graphics()->QuadsBegin twice"); + m_Drawing = DRAWING_QUADS; + + QuadsSetSubset(0,0,1,1); + QuadsSetRotation(0); + SetColor(1,1,1,1); +} + +void CGraphics_Threaded::QuadsEnd() +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsEnd without begin"); + FlushVertices(); + m_Drawing = 0; +} + +void CGraphics_Threaded::QuadsSetRotation(float Angle) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetRotation without begin"); + m_Rotation = Angle; +} + +void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num) +{ + dbg_assert(m_Drawing != 0, "called Graphics()->SetColorVertex without begin"); + + for(int i = 0; i < Num; ++i) + { + m_aColor[pArray[i].m_Index].r = pArray[i].m_R; + m_aColor[pArray[i].m_Index].g = pArray[i].m_G; + m_aColor[pArray[i].m_Index].b = pArray[i].m_B; + m_aColor[pArray[i].m_Index].a = pArray[i].m_A; + } +} + +void CGraphics_Threaded::SetColor(float r, float g, float b, float a) +{ + dbg_assert(m_Drawing != 0, "called Graphics()->SetColor without begin"); + CColorVertex Array[4] = { + CColorVertex(0, r, g, b, a), + CColorVertex(1, r, g, b, a), + CColorVertex(2, r, g, b, a), + CColorVertex(3, r, g, b, a)}; + SetColorVertex(Array, 4); +} + +void CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetSubset without begin"); + + m_aTexture[0].u = TlU; m_aTexture[1].u = BrU; + m_aTexture[0].v = TlV; m_aTexture[1].v = TlV; + + m_aTexture[3].u = TlU; m_aTexture[2].u = BrU; + m_aTexture[3].v = BrV; m_aTexture[2].v = BrV; +} + +void CGraphics_Threaded::QuadsSetSubsetFree( + float x0, float y0, float x1, float y1, + float x2, float y2, float x3, float y3) +{ + m_aTexture[0].u = x0; m_aTexture[0].v = y0; + m_aTexture[1].u = x1; m_aTexture[1].v = y1; + m_aTexture[2].u = x2; m_aTexture[2].v = y2; + m_aTexture[3].u = x3; m_aTexture[3].v = y3; +} + +void CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num) +{ + for(int i = 0; i < Num; ++i) + { + pArray[i].m_X -= pArray[i].m_Width/2; + pArray[i].m_Y -= pArray[i].m_Height/2; + } + + QuadsDrawTL(pArray, Num); +} + +void CGraphics_Threaded::QuadsDrawTL(const CQuadItem *pArray, int Num) +{ + CCommandBuffer::SPoint Center; + Center.z = 0; + + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawTL without begin"); + + if(g_Config.m_GfxQuadAsTriangle) + { + for(int i = 0; i < Num; ++i) + { + // first triangle + m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 6*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 2].m_Color = m_aColor[2]; + + // second triangle + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i + 3].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 4].m_Color = m_aColor[2]; + + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 5].m_Color = m_aColor[3]; + + if(m_Rotation != 0) + { + Center.x = pArray[i].m_X + pArray[i].m_Width/2; + Center.y = pArray[i].m_Y + pArray[i].m_Height/2; + + Rotate(Center, &m_aVertices[m_NumVertices + 6*i], 6); + } + } + + AddVertices(3*2*Num); + } + else + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y; + m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[2]; + + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X; + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; + m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[3]; + + if(m_Rotation != 0) + { + Center.x = pArray[i].m_X + pArray[i].m_Width/2; + Center.y = pArray[i].m_Y + pArray[i].m_Height/2; + + Rotate(Center, &m_aVertices[m_NumVertices + 4*i], 4); + } + } + + AddVertices(4*Num); + } +} + +void CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) +{ + dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawFreeform without begin"); + + if(g_Config.m_GfxQuadAsTriangle) + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 6*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 2].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 6*i + 3].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 6*i + 4].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y2; + m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[2]; + m_aVertices[m_NumVertices + 6*i + 5].m_Color = m_aColor[2]; + } + + AddVertices(3*2*Num); + } + else + { + for(int i = 0; i < Num; ++i) + { + m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0; + m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0; + m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; + m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; + + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1; + m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1; + m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; + m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; + + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3; + m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3; + m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3]; + m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[3]; + + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2; + m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2; + 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); + } +} + +void CGraphics_Threaded::QuadsText(float x, float y, float Size, const char *pText) +{ + float StartX = x; + + while(*pText) + { + char c = *pText; + pText++; + + if(c == '\n') + { + x = StartX; + y += Size; + } + else + { + QuadsSetSubset( + (c%16)/16.0f, + (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; + } + } +} + +int CGraphics_Threaded::IssueInit() +{ + int Flags = 0; + if(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen) + { + dbg_msg("gfx", "both borderless and fullscreen activated, disabling borderless"); + g_Config.m_GfxBorderless = 0; + } + + if(g_Config.m_GfxBorderless) Flags |= IGraphicsBackend::INITFLAG_BORDERLESS; + else if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN; + if(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC; + if(g_Config.m_DbgResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE; + + return m_pBackend->Init("DDNet Client", &g_Config.m_GfxScreenWidth, &g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags); +} + +int CGraphics_Threaded::InitWindow() +{ + if(IssueInit() == 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 + dbg_msg("gfx", "disabling FSAA and trying again"); + + if(IssueInit() == 0) + return 0; + } + + // try lowering the resolution + if(g_Config.m_GfxScreenWidth != 640 || g_Config.m_GfxScreenHeight != 480) + { + dbg_msg("gfx", "setting resolution to 640x480 and trying again"); + g_Config.m_GfxScreenWidth = 640; + g_Config.m_GfxScreenHeight = 480; + + if(IssueInit() == 0) + return 0; + } + + dbg_msg("gfx", "out of ideas. failed to init graphics"); + + return -1; +} + +int CGraphics_Threaded::Init() +{ + // fetch pointers + 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; + + // init textures + m_FirstFreeTexture = 0; + for(int i = 0; i < MAX_TEXTURES-1; i++) + m_aTextureIndices[i] = i+1; + m_aTextureIndices[MAX_TEXTURES-1] = -1; + + m_pBackend = CreateGraphicsBackend(); + if(InitWindow() != 0) + return -1; + + // fetch final resolusion + m_ScreenWidth = g_Config.m_GfxScreenWidth; + m_ScreenHeight = g_Config.m_GfxScreenHeight; + + // create command buffers + for(int i = 0; i < NUM_CMDBUFFERS; i++) + m_apCommandBuffers[i] = new CCommandBuffer(256*1024, 2*1024*1024); + m_pCommandBuffer = m_apCommandBuffers[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, + }; + + m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); + return 0; +} + +void CGraphics_Threaded::Shutdown() +{ + // shutdown the backend + m_pBackend->Shutdown(); + delete m_pBackend; + m_pBackend = 0x0; + + // delete the command buffers + for(int i = 0; i < NUM_CMDBUFFERS; i++) + delete m_apCommandBuffers[i]; +} + +void CGraphics_Threaded::Minimize() +{ + m_pBackend->Minimize(); +} + +void CGraphics_Threaded::Maximize() +{ + // TODO: SDL + m_pBackend->Maximize(); +} + +int CGraphics_Threaded::WindowActive() +{ + return m_pBackend->WindowActive(); +} + +int CGraphics_Threaded::WindowOpen() +{ + return m_pBackend->WindowOpen(); +} + +void CGraphics_Threaded::NotifyWindow() +{ + return m_pBackend->NotifyWindow(); +} + +void CGraphics_Threaded::TakeScreenshot(const char *pFilename) +{ + // TODO: screenshot support + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate); + m_DoScreenshot = true; +} + +void CGraphics_Threaded::TakeCustomScreenshot(const char *pFilename) +{ + str_copy(m_aScreenshotName, pFilename, sizeof(m_aScreenshotName)); + m_DoScreenshot = true; +} + +void CGraphics_Threaded::Swap() +{ + // TODO: screenshot support + if(m_DoScreenshot) + { + if(WindowActive()) + ScreenshotDirect(); + m_DoScreenshot = false; + } + + // add swap command + CCommandBuffer::SCommand_Swap Cmd; + Cmd.m_Finish = g_Config.m_GfxFinish; + m_pCommandBuffer->AddCommand(Cmd); + + // kick the command buffer + KickCommandBuffer(); +} + +// syncronization +void CGraphics_Threaded::InsertSignal(semaphore *pSemaphore) +{ + CCommandBuffer::SCommand_Signal Cmd; + Cmd.m_pSemaphore = pSemaphore; + m_pCommandBuffer->AddCommand(Cmd); +} + +bool CGraphics_Threaded::IsIdle() +{ + return m_pBackend->IsIdle(); +} + +void CGraphics_Threaded::WaitForIdle() +{ + m_pBackend->WaitForIdle(); +} + +int CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes) +{ + if(g_Config.m_GfxDisplayAllModes) + { + int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode); + mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes)); + if(MaxModes < Count) + Count = MaxModes; + return Count; + } + + // add videomodes command + CImageInfo Image; + mem_zero(&Image, sizeof(Image)); + + int NumModes = 0; + CCommandBuffer::SCommand_VideoModes Cmd; + Cmd.m_pModes = pModes; + Cmd.m_MaxModes = MaxModes; + Cmd.m_pNumModes = &NumModes; + m_pCommandBuffer->AddCommand(Cmd); + + // kick the buffer and wait for the result and return it + KickCommandBuffer(); + WaitForIdle(); + return NumModes; +} + +extern IEngineGraphics *CreateEngineGraphicsThreaded() { return new CGraphics_Threaded(); } diff --git a/src/engine/client/graphics_threaded.h b/src/engine/client/graphics_threaded.h new file mode 100644 index 0000000..50ca5cc --- /dev/null +++ b/src/engine/client/graphics_threaded.h @@ -0,0 +1,449 @@ +#pragma once + +#include <engine/graphics.h> + +class CCommandBuffer +{ + class CBuffer + { + unsigned char *m_pData; + unsigned m_Size; + unsigned m_Used; + public: + CBuffer(unsigned BufferSize) + { + m_Size = BufferSize; + m_pData = new unsigned char[m_Size]; + m_Used = 0; + } + + ~CBuffer() + { + delete [] m_pData; + m_pData = 0x0; + m_Used = 0; + m_Size = 0; + } + + void Reset() + { + m_Used = 0; + } + + void *Alloc(unsigned Requested) + { + if(Requested + m_Used > m_Size) + return 0; + void *pPtr = &m_pData[m_Used]; + m_Used += Requested; + return pPtr; + } + + unsigned char *DataPtr() { return m_pData; } + unsigned DataSize() { return m_Size; } + unsigned DataUsed() { return m_Used; } + }; + +public: + CBuffer m_CmdBuffer; + CBuffer m_DataBuffer; + + enum + { + MAX_TEXTURES=1024*4, + }; + + enum + { + // commadn groups + CMDGROUP_CORE = 0, // commands that everyone has to implement + CMDGROUP_PLATFORM_OPENGL = 10000, // commands specific to a platform + CMDGROUP_PLATFORM_SDL = 20000, + + // + CMD_NOP = CMDGROUP_CORE, + + // + CMD_RUNBUFFER, + + // syncronization + CMD_SIGNAL, + + // texture commands + CMD_TEXTURE_CREATE, + CMD_TEXTURE_DESTROY, + CMD_TEXTURE_UPDATE, + + // rendering + CMD_CLEAR, + CMD_RENDER, + + // swap + CMD_SWAP, + + // misc + CMD_SCREENSHOT, + CMD_VIDEOMODES, + + }; + + enum + { + TEXFORMAT_INVALID = 0, + TEXFORMAT_RGB, + TEXFORMAT_RGBA, + TEXFORMAT_ALPHA, + + TEXFLAG_NOMIPMAPS = 1, + TEXFLAG_COMPRESSED = 2, + TEXFLAG_QUALITY = 4, + }; + + enum + { + // + PRIMTYPE_INVALID = 0, + PRIMTYPE_LINES, + PRIMTYPE_QUADS, + PRIMTYPE_TRIANGLES, + }; + + enum + { + BLEND_NONE = 0, + BLEND_ALPHA, + BLEND_ADDITIVE, + }; + + enum + { + WRAP_REPEAT = 0, + WRAP_CLAMP, + }; + + struct SPoint { float x, y, z; }; + struct STexCoord { float u, v; }; + struct SColor { float r, g, b, a; }; + + struct SVertex + { + SPoint m_Pos; + STexCoord m_Tex; + SColor m_Color; + }; + + struct SCommand + { + public: + SCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {} + unsigned m_Cmd; + unsigned m_Size; + }; + + struct SState + { + int m_BlendMode; + int m_WrapMode; + int m_Texture; + SPoint m_ScreenTL; + SPoint m_ScreenBR; + + // clip + bool m_ClipEnable; + int m_ClipX; + int m_ClipY; + int m_ClipW; + int m_ClipH; + }; + + struct SCommand_Clear : public SCommand + { + SCommand_Clear() : SCommand(CMD_CLEAR) {} + SColor m_Color; + }; + + struct SCommand_Signal : public SCommand + { + SCommand_Signal() : SCommand(CMD_SIGNAL) {} + semaphore *m_pSemaphore; + }; + + struct SCommand_RunBuffer : public SCommand + { + SCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {} + CCommandBuffer *m_pOtherBuffer; + }; + + struct SCommand_Render : public SCommand + { + SCommand_Render() : SCommand(CMD_RENDER) {} + SState m_State; + unsigned m_PrimType; + unsigned m_PrimCount; + SVertex *m_pVertices; // you should use the command buffer data to allocate vertices for this command + }; + + struct SCommand_Screenshot : public SCommand + { + SCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {} + CImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well + }; + + struct SCommand_VideoModes : public SCommand + { + SCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {} + + CVideoMode *m_pModes; // processor will fill this in + int m_MaxModes; // maximum of modes the processor can write to the m_pModes + int *m_pNumModes; // processor will write to this pointer + }; + + struct SCommand_Swap : public SCommand + { + SCommand_Swap() : SCommand(CMD_SWAP) {} + + int m_Finish; + }; + + struct SCommand_Texture_Create : public SCommand + { + SCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {} + + // texture information + int m_Slot; + + int m_Width; + int m_Height; + int m_PixelSize; + int m_Format; + int m_StoreFormat; + int m_Flags; + void *m_pData; // will be freed by the command processor + }; + + struct SCommand_Texture_Update : public SCommand + { + SCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {} + + // texture information + int m_Slot; + + int m_X; + int m_Y; + int m_Width; + int m_Height; + int m_Format; + void *m_pData; // will be freed by the command processor + }; + + + struct SCommand_Texture_Destroy : public SCommand + { + SCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {} + + // texture information + int m_Slot; + }; + + // + CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize) + : m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize) + { + } + + void *AllocData(unsigned WantedSize) + { + return m_DataBuffer.Alloc(WantedSize); + } + + template<class T> + bool AddCommand(const T &Command) + { + // make sure that we don't do something stupid like ->AddCommand(&Cmd); + (void)static_cast<const SCommand *>(&Command); + + // allocate and copy the command into the buffer + SCommand *pCmd = (SCommand *)m_CmdBuffer.Alloc(sizeof(Command)); + if(!pCmd) + return false; + mem_copy(pCmd, &Command, sizeof(Command)); + pCmd->m_Size = sizeof(Command); + return true; + } + + SCommand *GetCommand(unsigned *pIndex) + { + if(*pIndex >= m_CmdBuffer.DataUsed()) + return NULL; + + SCommand *pCommand = (SCommand *)&m_CmdBuffer.DataPtr()[*pIndex]; + *pIndex += pCommand->m_Size; + return pCommand; + } + + void Reset() + { + m_CmdBuffer.Reset(); + m_DataBuffer.Reset(); + } +}; + +// interface for the graphics backend +// all these functions are called on the main thread +class IGraphicsBackend +{ +public: + enum + { + INITFLAG_FULLSCREEN = 1, + INITFLAG_VSYNC = 2, + INITFLAG_RESIZABLE = 4, + INITFLAG_BORDERLESS = 8, + }; + + virtual ~IGraphicsBackend() {} + + virtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags) = 0; + virtual int Shutdown() = 0; + + virtual int MemoryUsage() const = 0; + + virtual void Minimize() = 0; + virtual void Maximize() = 0; + virtual int WindowActive() = 0; + virtual int WindowOpen() = 0; + virtual void NotifyWindow() = 0; + + virtual void RunBuffer(CCommandBuffer *pBuffer) = 0; + virtual bool IsIdle() const = 0; + virtual void WaitForIdle() = 0; +}; + +class CGraphics_Threaded : public IEngineGraphics +{ + enum + { + NUM_CMDBUFFERS = 2, + + MAX_VERTICES = 32*1024, + MAX_TEXTURES = 1024*4, + + DRAWING_QUADS=1, + DRAWING_LINES=2 + }; + + CCommandBuffer::SState m_State; + IGraphicsBackend *m_pBackend; + + CCommandBuffer *m_apCommandBuffers[NUM_CMDBUFFERS]; + CCommandBuffer *m_pCommandBuffer; + unsigned m_CurrentCommandBuffer; + + // + class IStorage *m_pStorage; + class IConsole *m_pConsole; + + CCommandBuffer::SVertex m_aVertices[MAX_VERTICES]; + int m_NumVertices; + + CCommandBuffer::SColor m_aColor[4]; + CCommandBuffer::STexCoord m_aTexture[4]; + + bool m_RenderEnable; + + float m_Rotation; + int m_Drawing; + bool m_DoScreenshot; + char m_aScreenshotName[128]; + + int m_InvalidTexture; + + int m_aTextureIndices[MAX_TEXTURES]; + int m_FirstFreeTexture; + int m_TextureMemoryUsage; + + void FlushVertices(); + void AddVertices(int Count); + void Rotate(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints, int NumPoints); + + void KickCommandBuffer(); + + int IssueInit(); + int InitWindow(); +public: + CGraphics_Threaded(); + + virtual void ClipEnable(int x, int y, int w, int h); + virtual void ClipDisable(); + + virtual void BlendNone(); + virtual void BlendNormal(); + virtual void BlendAdditive(); + + virtual void WrapNormal(); + virtual void WrapClamp(); + + 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); + virtual int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData); + + // simple uncompressed RGBA loaders + virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags); + virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType); + + void ScreenshotDirect(); + + virtual void TextureSet(int TextureID); + + virtual void Clear(float r, float g, float b); + + virtual void QuadsBegin(); + virtual void QuadsEnd(); + virtual void QuadsSetRotation(float Angle); + + virtual void SetColorVertex(const CColorVertex *pArray, int Num); + virtual void SetColor(float r, float g, float b, float a); + + virtual void QuadsSetSubset(float TlU, float TlV, float BrU, float BrV); + virtual void QuadsSetSubsetFree( + float x0, float y0, float x1, float y1, + float x2, float y2, float x3, float y3); + + virtual void QuadsDraw(CQuadItem *pArray, int Num); + 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, const char *pText); + + virtual void Minimize(); + virtual void Maximize(); + + virtual int WindowActive(); + virtual int WindowOpen(); + + virtual void NotifyWindow(); + + virtual int Init(); + virtual void Shutdown(); + + virtual void TakeScreenshot(const char *pFilename); + virtual void TakeCustomScreenshot(const char *pFilename); + virtual void Swap(); + + virtual int GetVideoModes(CVideoMode *pModes, int MaxModes); + + // syncronization + virtual void InsertSignal(semaphore *pSemaphore); + virtual bool IsIdle(); + virtual void WaitForIdle(); +}; + +extern IGraphicsBackend *CreateGraphicsBackend(); diff --git a/src/engine/client/input.cpp b/src/engine/client/input.cpp new file mode 100644 index 0000000..d27407c --- /dev/null +++ b/src/engine/client/input.cpp @@ -0,0 +1,238 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "SDL.h" + +#include <base/system.h> +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/input.h> +#include <engine/keys.h> + +#include "input.h" + +//print >>f, "int inp_key_code(const char *key_name) { int i; if (!strcmp(key_name, \"-?-\")) return -1; else for (i = 0; i < 512; i++) if (!strcmp(key_strings[i], key_name)) return i; return -1; }" + +// this header is protected so you don't include it from anywere +#define KEYS_INCLUDE +#include "keynames.h" +#undef KEYS_INCLUDE + +void CInput::AddEvent(int Unicode, int Key, int Flags) +{ + if(m_NumEvents != INPUT_BUFFER_SIZE) + { + m_aInputEvents[m_NumEvents].m_Unicode = Unicode; + m_aInputEvents[m_NumEvents].m_Key = Key; + m_aInputEvents[m_NumEvents].m_Flags = Flags; + m_NumEvents++; + } +} + +CInput::CInput() +{ + mem_zero(m_aInputCount, sizeof(m_aInputCount)); + mem_zero(m_aInputState, sizeof(m_aInputState)); + + m_InputCurrent = 0; + m_InputGrabbed = 0; + m_InputDispatched = false; + + m_LastRelease = 0; + m_ReleaseDelta = -1; + + m_NumEvents = 0; + + m_VideoRestartNeeded = 0; +} + +void CInput::Init() +{ + m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); + SDL_EnableUNICODE(1); + SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); +} + +void CInput::MouseRelative(float *x, float *y) +{ +#if defined(__ANDROID__) // No relative mouse on Android + int nx = 0, ny = 0; + SDL_GetMouseState(&nx, &ny); + *x = nx; + *y = ny; +#else + int nx = 0, ny = 0; + float Sens = ((g_Config.m_ClDyncam && g_Config.m_ClDyncamMousesens) ? g_Config.m_ClDyncamMousesens : g_Config.m_InpMousesens) / 100.0f; + + if(g_Config.m_InpGrab) + SDL_GetRelativeMouseState(&nx, &ny); + else + { + if(m_InputGrabbed) + { + SDL_GetMouseState(&nx,&ny); + SDL_WarpMouse(Graphics()->ScreenWidth()/2,Graphics()->ScreenHeight()/2); + nx -= Graphics()->ScreenWidth()/2; ny -= Graphics()->ScreenHeight()/2; + } + } + + *x = nx*Sens; + *y = ny*Sens; +#endif +} + +void CInput::MouseModeAbsolute() +{ + SDL_ShowCursor(1); + m_InputGrabbed = 0; + if(g_Config.m_InpGrab) + SDL_WM_GrabInput(SDL_GRAB_OFF); +} + +void CInput::MouseModeRelative() +{ + SDL_ShowCursor(0); + m_InputGrabbed = 1; + if(g_Config.m_InpGrab) + SDL_WM_GrabInput(SDL_GRAB_ON); +} + +int CInput::MouseDoubleClick() +{ + if(m_ReleaseDelta >= 0 && m_ReleaseDelta < (time_freq() / 3)) + { + m_LastRelease = 0; + m_ReleaseDelta = -1; + return 1; + } + return 0; +} + +void CInput::ClearKeyStates() +{ + mem_zero(m_aInputState, sizeof(m_aInputState)); + mem_zero(m_aInputCount, sizeof(m_aInputCount)); +} + +int CInput::KeyState(int Key) +{ + return m_aInputState[m_InputCurrent][Key]; +} + +int CInput::Update() +{ + if(m_InputGrabbed && !Graphics()->WindowActive()) + MouseModeAbsolute(); + + /*if(!input_grabbed && Graphics()->WindowActive()) + Input()->MouseModeRelative();*/ + + if(m_InputDispatched) + { + // clear and begin count on the other one + m_InputCurrent^=1; + mem_zero(&m_aInputCount[m_InputCurrent], sizeof(m_aInputCount[m_InputCurrent])); + mem_zero(&m_aInputState[m_InputCurrent], sizeof(m_aInputState[m_InputCurrent])); + m_InputDispatched = false; + } + + { + int i; + Uint8 *pState = SDL_GetKeyState(&i); + if(i >= KEY_LAST) + i = KEY_LAST-1; + mem_copy(m_aInputState[m_InputCurrent], pState, i); + } + + // these states must always be updated manually because they are not in the GetKeyState from SDL + int i = SDL_GetMouseState(NULL, NULL); + if(i&SDL_BUTTON(1)) m_aInputState[m_InputCurrent][KEY_MOUSE_1] = 1; // 1 is left + if(i&SDL_BUTTON(3)) m_aInputState[m_InputCurrent][KEY_MOUSE_2] = 1; // 3 is right + if(i&SDL_BUTTON(2)) m_aInputState[m_InputCurrent][KEY_MOUSE_3] = 1; // 2 is middle + if(i&SDL_BUTTON(4)) m_aInputState[m_InputCurrent][KEY_MOUSE_4] = 1; + if(i&SDL_BUTTON(5)) m_aInputState[m_InputCurrent][KEY_MOUSE_5] = 1; + if(i&SDL_BUTTON(6)) m_aInputState[m_InputCurrent][KEY_MOUSE_6] = 1; + if(i&SDL_BUTTON(7)) m_aInputState[m_InputCurrent][KEY_MOUSE_7] = 1; + if(i&SDL_BUTTON(8)) m_aInputState[m_InputCurrent][KEY_MOUSE_8] = 1; + if(i&SDL_BUTTON(9)) m_aInputState[m_InputCurrent][KEY_MOUSE_9] = 1; + + { + SDL_Event Event; + + while(SDL_PollEvent(&Event)) + { + int Key = -1; + int Action = IInput::FLAG_PRESS; + switch (Event.type) + { + // handle keys + case SDL_KEYDOWN: + // 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 + break; + case SDL_KEYUP: + Action = IInput::FLAG_RELEASE; + Key = Event.key.keysym.sym; // ignore_convention + break; + + // handle mouse buttons + case SDL_MOUSEBUTTONUP: + Action = IInput::FLAG_RELEASE; + + if(Event.button.button == 1) // ignore_convention + { + m_ReleaseDelta = time_get() - m_LastRelease; + m_LastRelease = time_get(); + } + + // fall through + case SDL_MOUSEBUTTONDOWN: + if(Event.button.button == SDL_BUTTON_LEFT) Key = KEY_MOUSE_1; // ignore_convention + if(Event.button.button == SDL_BUTTON_RIGHT) Key = KEY_MOUSE_2; // ignore_convention + if(Event.button.button == SDL_BUTTON_MIDDLE) Key = KEY_MOUSE_3; // ignore_convention + if(Event.button.button == SDL_BUTTON_WHEELUP) Key = KEY_MOUSE_WHEEL_UP; // ignore_convention + if(Event.button.button == SDL_BUTTON_WHEELDOWN) Key = KEY_MOUSE_WHEEL_DOWN; // ignore_convention + if(Event.button.button == 6) Key = KEY_MOUSE_6; // ignore_convention + if(Event.button.button == 7) Key = KEY_MOUSE_7; // ignore_convention + if(Event.button.button == 8) Key = KEY_MOUSE_8; // ignore_convention + if(Event.button.button == 9) Key = KEY_MOUSE_9; // ignore_convention + break; + + // other messages + case SDL_QUIT: + return 1; + +#if defined(__ANDROID__) + case SDL_VIDEORESIZE: + m_VideoRestartNeeded = 1; + break; +#endif + } + + // + if(Key != -1) + { + m_aInputCount[m_InputCurrent][Key].m_Presses++; + if(Action == IInput::FLAG_PRESS) + m_aInputState[m_InputCurrent][Key] = 1; + AddEvent(0, Key, Action); + } + + } + } + + return 0; +} + +int CInput::VideoRestartNeeded() +{ + if( m_VideoRestartNeeded ) + { + m_VideoRestartNeeded = 0; + return 1; + } + return 0; +} + +IEngineInput *CreateEngineInput() { return new CInput; } diff --git a/src/engine/client/input.h b/src/engine/client/input.h new file mode 100644 index 0000000..528c1e4 --- /dev/null +++ b/src/engine/client/input.h @@ -0,0 +1,41 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_INPUT_H +#define ENGINE_CLIENT_INPUT_H + +class CInput : public IEngineInput +{ + IEngineGraphics *m_pGraphics; + + int m_InputGrabbed; + + int64 m_LastRelease; + int64 m_ReleaseDelta; + + int m_VideoRestartNeeded; + + void AddEvent(int Unicode, int Key, int Flags); + + IEngineGraphics *Graphics() { return m_pGraphics; } + +public: + CInput(); + + virtual void Init(); + + virtual void MouseRelative(float *x, float *y); + virtual void MouseModeAbsolute(); + virtual void MouseModeRelative(); + virtual int MouseDoubleClick(); + + void ClearKeyStates(); + int KeyState(int Key); + + int ButtonPressed(int Button) { return m_aInputState[m_InputCurrent][Button]; } + + virtual int Update(); + + virtual int VideoRestartNeeded(); +}; + +#endif diff --git a/src/engine/client/keynames.h b/src/engine/client/keynames.h new file mode 100644 index 0000000..14129bd --- /dev/null +++ b/src/engine/client/keynames.h @@ -0,0 +1,525 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +/* AUTO GENERATED! DO NOT EDIT MANUALLY! */ + +#ifndef KEYS_INCLUDE +#error do not include this header! +#endif + +#include <string.h> + +const char g_aaKeyStrings[512][16] = +{ + "first", + "&1", + "&2", + "&3", + "&4", + "&5", + "&6", + "&7", + "backspace", + "tab", + "&10", + "&11", + "clear", + "return", + "&14", + "&15", + "&16", + "&17", + "&18", + "pause", + "&20", + "&21", + "&22", + "&23", + "&24", + "&25", + "&26", + "escape", + "&28", + "&29", + "&30", + "&31", + "space", + "exclaim", + "quotedbl", + "hash", + "dollar", + "&37", + "ampersand", + "quote", + "leftparen", + "rightparen", + "asterisk", + "plus", + "comma", + "minus", + "period", + "slash", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "colon", + "semicolon", + "less", + "equals", + "greater", + "question", + "at", + "&65", + "&66", + "&67", + "&68", + "&69", + "&70", + "&71", + "&72", + "&73", + "&74", + "&75", + "&76", + "&77", + "&78", + "&79", + "&80", + "&81", + "&82", + "&83", + "&84", + "&85", + "&86", + "&87", + "&88", + "&89", + "&90", + "leftbracket", + "backslash", + "rightbracket", + "caret", + "underscore", + "backquote", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "&123", + "&124", + "&125", + "&126", + "delete", + "&128", + "&129", + "&130", + "&131", + "&132", + "&133", + "&134", + "&135", + "&136", + "&137", + "&138", + "&139", + "&140", + "&141", + "&142", + "&143", + "&144", + "&145", + "&146", + "&147", + "&148", + "&149", + "&150", + "&151", + "&152", + "&153", + "&154", + "&155", + "&156", + "&157", + "&158", + "&159", + "world_0", + "world_1", + "world_2", + "world_3", + "world_4", + "world_5", + "world_6", + "world_7", + "world_8", + "world_9", + "world_10", + "world_11", + "world_12", + "world_13", + "world_14", + "world_15", + "world_16", + "world_17", + "world_18", + "world_19", + "world_20", + "world_21", + "world_22", + "world_23", + "world_24", + "world_25", + "world_26", + "world_27", + "world_28", + "world_29", + "world_30", + "world_31", + "world_32", + "world_33", + "world_34", + "world_35", + "world_36", + "world_37", + "world_38", + "world_39", + "world_40", + "world_41", + "world_42", + "world_43", + "world_44", + "world_45", + "world_46", + "world_47", + "world_48", + "world_49", + "world_50", + "world_51", + "world_52", + "world_53", + "world_54", + "world_55", + "world_56", + "world_57", + "world_58", + "world_59", + "world_60", + "world_61", + "world_62", + "world_63", + "world_64", + "world_65", + "world_66", + "world_67", + "world_68", + "world_69", + "world_70", + "world_71", + "world_72", + "world_73", + "world_74", + "world_75", + "world_76", + "world_77", + "world_78", + "world_79", + "world_80", + "world_81", + "world_82", + "world_83", + "world_84", + "world_85", + "world_86", + "world_87", + "world_88", + "world_89", + "world_90", + "world_91", + "world_92", + "world_93", + "world_94", + "world_95", + "kp0", + "kp1", + "kp2", + "kp3", + "kp4", + "kp5", + "kp6", + "kp7", + "kp8", + "kp9", + "kp_period", + "kp_divide", + "kp_multiply", + "kp_minus", + "kp_plus", + "kp_enter", + "kp_equals", + "up", + "down", + "right", + "left", + "insert", + "home", + "end", + "pageup", + "pagedown", + "f1", + "f2", + "f3", + "f4", + "f5", + "f6", + "f7", + "f8", + "f9", + "f10", + "f11", + "f12", + "f13", + "f14", + "f15", + "&297", + "&298", + "&299", + "numlock", + "capslock", + "scrollock", + "rshift", + "lshift", + "rctrl", + "lctrl", + "ralt", + "lalt", + "rmeta", + "lmeta", + "lsuper", + "rsuper", + "mode", + "compose", + "help", + "print", + "sysreq", + "break", + "menu", + "power", + "euro", + "undo", + "mouse1", + "mouse2", + "mouse3", + "mouse4", + "mouse5", + "mouse6", + "mouse7", + "mouse8", + "mousewheelup", + "mousewheeldown", + "mouse9", + "&334", + "&335", + "&336", + "&337", + "&338", + "&339", + "&340", + "&341", + "&342", + "&343", + "&344", + "&345", + "&346", + "&347", + "&348", + "&349", + "&350", + "&351", + "&352", + "&353", + "&354", + "&355", + "&356", + "&357", + "&358", + "&359", + "&360", + "&361", + "&362", + "&363", + "&364", + "&365", + "&366", + "&367", + "&368", + "&369", + "&370", + "&371", + "&372", + "&373", + "&374", + "&375", + "&376", + "&377", + "&378", + "&379", + "&380", + "&381", + "&382", + "&383", + "&384", + "&385", + "&386", + "&387", + "&388", + "&389", + "&390", + "&391", + "&392", + "&393", + "&394", + "&395", + "&396", + "&397", + "&398", + "&399", + "&400", + "&401", + "&402", + "&403", + "&404", + "&405", + "&406", + "&407", + "&408", + "&409", + "&410", + "&411", + "&412", + "&413", + "&414", + "&415", + "&416", + "&417", + "&418", + "&419", + "&420", + "&421", + "&422", + "&423", + "&424", + "&425", + "&426", + "&427", + "&428", + "&429", + "&430", + "&431", + "&432", + "&433", + "&434", + "&435", + "&436", + "&437", + "&438", + "&439", + "&440", + "&441", + "&442", + "&443", + "&444", + "&445", + "&446", + "&447", + "&448", + "&449", + "&450", + "&451", + "&452", + "&453", + "&454", + "&455", + "&456", + "&457", + "&458", + "&459", + "&460", + "&461", + "&462", + "&463", + "&464", + "&465", + "&466", + "&467", + "&468", + "&469", + "&470", + "&471", + "&472", + "&473", + "&474", + "&475", + "&476", + "&477", + "&478", + "&479", + "&480", + "&481", + "&482", + "&483", + "&484", + "&485", + "&486", + "&487", + "&488", + "&489", + "&490", + "&491", + "&492", + "&493", + "&494", + "&495", + "&496", + "&497", + "&498", + "&499", + "&500", + "&501", + "&502", + "&503", + "&504", + "&505", + "&506", + "&507", + "&508", + "&509", + "&510", + "&511", +}; diff --git a/src/engine/client/serverbrowser.cpp b/src/engine/client/serverbrowser.cpp new file mode 100644 index 0000000..cd4fef2 --- /dev/null +++ b/src/engine/client/serverbrowser.cpp @@ -0,0 +1,1100 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <algorithm> // sort TODO: remove this + +#include <base/math.h> +#include <base/system.h> + +#include <engine/shared/config.h> +#include <engine/shared/memheap.h> +#include <engine/shared/network.h> +#include <engine/shared/protocol.h> + +#include <engine/config.h> +#include <engine/console.h> +#include <engine/friends.h> +#include <engine/masterserver.h> +#include <engine/storage.h> + +#include <mastersrv/mastersrv.h> + +#include <engine/external/json-parser/json.h> + +#include "serverbrowser.h" +class SortWrap +{ + typedef bool (CServerBrowser::*SortFunc)(int, int) const; + SortFunc m_pfnSort; + CServerBrowser *m_pThis; +public: + SortWrap(CServerBrowser *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {} + bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); } +}; + +CServerBrowser::CServerBrowser() +{ + m_pMasterServer = 0; + m_ppServerlist = 0; + m_pSortedServerlist = 0; + + m_NumFavoriteServers = 0; + + mem_zero(m_aServerlistIp, sizeof(m_aServerlistIp)); + + m_pFirstReqServer = 0; // request list + m_pLastReqServer = 0; + m_NumRequests = 0; + + m_NeedRefresh = 0; + + m_NumSortedServers = 0; + m_NumSortedServersCapacity = 0; + m_NumServers = 0; + m_NumServerCapacity = 0; + + m_Sorthash = 0; + m_aFilterString[0] = 0; + m_aFilterGametypeString[0] = 0; + + // the token is to keep server refresh separated from each other + m_CurrentToken = 1; + + m_ServerlistType = 0; + m_BroadcastTime = 0; +} + +void CServerBrowser::SetBaseInfo(class CNetClient *pClient, const char *pNetVersion) +{ + m_pNetClient = pClient; + str_copy(m_aNetVersion, pNetVersion, sizeof(m_aNetVersion)); + m_pMasterServer = Kernel()->RequestInterface<IMasterServer>(); + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_pFriends = Kernel()->RequestInterface<IFriends>(); + IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); + if(pConfig) + pConfig->RegisterCallback(ConfigSaveCallback, this); +} + +const CServerInfo *CServerBrowser::SortedGet(int Index) const +{ + if(Index < 0 || Index >= m_NumSortedServers) + return 0; + return &m_ppServerlist[m_pSortedServerlist[Index]]->m_Info; +} + + +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 : + a->m_GotInfo ? true : false; +} + +bool CServerBrowser::SortCompareMap(int Index1, int Index2) const +{ + CServerEntry *a = m_ppServerlist[Index1]; + CServerEntry *b = m_ppServerlist[Index2]; + return str_comp(a->m_Info.m_aMap, b->m_Info.m_aMap) < 0; +} + +bool CServerBrowser::SortComparePing(int Index1, int Index2) const +{ + CServerEntry *a = m_ppServerlist[Index1]; + CServerEntry *b = m_ppServerlist[Index2]; + return a->m_Info.m_Latency < b->m_Info.m_Latency; +} + +bool CServerBrowser::SortCompareGametype(int Index1, int Index2) const +{ + CServerEntry *a = m_ppServerlist[Index1]; + CServerEntry *b = m_ppServerlist[Index2]; + return str_comp(a->m_Info.m_aGameType, b->m_Info.m_aGameType) < 0; +} + +bool CServerBrowser::SortCompareNumPlayers(int Index1, int Index2) const +{ + CServerEntry *a = m_ppServerlist[Index1]; + CServerEntry *b = m_ppServerlist[Index2]; + return a->m_Info.m_NumPlayers < b->m_Info.m_NumPlayers; +} + +bool CServerBrowser::SortCompareNumClients(int Index1, int Index2) const +{ + CServerEntry *a = m_ppServerlist[Index1]; + CServerEntry *b = m_ppServerlist[Index2]; + return a->m_Info.m_NumClients < b->m_Info.m_NumClients; +} + +void CServerBrowser::Filter() +{ + int i = 0, p = 0; + m_NumSortedServers = 0; + + // allocate the sorted list + if(m_NumSortedServersCapacity < m_NumServers) + { + if(m_pSortedServerlist) + mem_free(m_pSortedServerlist); + m_NumSortedServersCapacity = m_NumServers; + m_pSortedServerlist = (int *)mem_alloc(m_NumSortedServersCapacity*sizeof(int), 1); + } + + // filter the servers + for(i = 0; i < m_NumServers; i++) + { + int Filtered = 0; + + if(g_Config.m_BrFilterEmpty && ((g_Config.m_BrFilterSpectators && m_ppServerlist[i]->m_Info.m_NumPlayers == 0) || m_ppServerlist[i]->m_Info.m_NumClients == 0)) + Filtered = 1; + else if(g_Config.m_BrFilterFull && ((g_Config.m_BrFilterSpectators && m_ppServerlist[i]->m_Info.m_NumPlayers == m_ppServerlist[i]->m_Info.m_MaxPlayers) || + m_ppServerlist[i]->m_Info.m_NumClients == m_ppServerlist[i]->m_Info.m_MaxClients)) + Filtered = 1; + else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags&SERVER_FLAG_PASSWORD) + Filtered = 1; + else if(g_Config.m_BrFilterPure && + (str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "DM") != 0 && + str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "TDM") != 0 && + str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "CTF") != 0)) + { + Filtered = 1; + } + else if(g_Config.m_BrFilterPureMap && + !(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm1") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm2") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm6") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm7") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm8") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm9") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf1") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf2") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf3") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf4") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf5") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf6") == 0 || + str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf7") == 0) + ) + { + Filtered = 1; + } + else if(g_Config.m_BrFilterPing < m_ppServerlist[i]->m_Info.m_Latency) + Filtered = 1; + else if(g_Config.m_BrFilterCompatversion && str_comp_num(m_ppServerlist[i]->m_Info.m_aVersion, m_aNetVersion, 3) != 0) + Filtered = 1; + else if(g_Config.m_BrFilterServerAddress[0] && !str_find_nocase(m_ppServerlist[i]->m_Info.m_aAddress, g_Config.m_BrFilterServerAddress)) + Filtered = 1; + else if(g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && str_comp_nocase(m_ppServerlist[i]->m_Info.m_aGameType, g_Config.m_BrFilterGametype)) + Filtered = 1; + else if(!g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && !str_find_nocase(m_ppServerlist[i]->m_Info.m_aGameType, g_Config.m_BrFilterGametype)) + Filtered = 1; + else + { + if(g_Config.m_BrFilterCountry) + { + Filtered = 1; + // match against player country + for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++) + { + if(m_ppServerlist[i]->m_Info.m_aClients[p].m_Country == g_Config.m_BrFilterCountryIndex) + { + Filtered = 0; + break; + } + } + } + + if(!Filtered && g_Config.m_BrFilterString[0] != 0) + { + int MatchFound = 0; + + m_ppServerlist[i]->m_Info.m_QuickSearchHit = 0; + + // match against server name + if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrFilterString)) + { + MatchFound = 1; + m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME; + } + + // match against players + for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++) + { + if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, g_Config.m_BrFilterString) || + str_find_nocase(m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan, g_Config.m_BrFilterString)) + { + MatchFound = 1; + m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYER; + break; + } + } + + // match against map + if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrFilterString)) + { + MatchFound = 1; + m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME; + } + + if(!MatchFound) + Filtered = 1; + } + + if(!Filtered && g_Config.m_BrExcludeString[0] != 0) + { + int MatchFound = 0; + + // match against server name + if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrExcludeString)) + { + MatchFound = 1; + } + + // match against map + if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrExcludeString)) + { + MatchFound = 1; + } + + if(MatchFound) + Filtered = 1; + } + } + + if(Filtered == 0) + { + // check for friend + m_ppServerlist[i]->m_Info.m_FriendState = IFriends::FRIEND_NO; + for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++) + { + m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState = m_pFriends->GetFriendState(m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, + m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan); + m_ppServerlist[i]->m_Info.m_FriendState = max(m_ppServerlist[i]->m_Info.m_FriendState, m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState); + } + + if(!g_Config.m_BrFilterFriends || m_ppServerlist[i]->m_Info.m_FriendState != IFriends::FRIEND_NO) + m_pSortedServerlist[m_NumSortedServers++] = i; + } + } +} + +int CServerBrowser::SortHash() const +{ + int i = g_Config.m_BrSort&0xf; + i |= g_Config.m_BrFilterEmpty<<4; + i |= g_Config.m_BrFilterFull<<5; + i |= g_Config.m_BrFilterSpectators<<6; + i |= g_Config.m_BrFilterFriends<<7; + i |= g_Config.m_BrFilterPw<<8; + i |= g_Config.m_BrSortOrder<<9; + i |= g_Config.m_BrFilterCompatversion<<10; + i |= g_Config.m_BrFilterPure<<11; + i |= g_Config.m_BrFilterPureMap<<12; + i |= g_Config.m_BrFilterGametypeStrict<<13; + i |= g_Config.m_BrFilterCountry<<14; + i |= g_Config.m_BrFilterPing<<15; + return i; +} + +void CServerBrowser::Sort() +{ + int i; + + // create filtered list + Filter(); + + // sort + if(g_Config.m_BrSort == IServerBrowser::SORT_NAME) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName)); + else if(g_Config.m_BrSort == IServerBrowser::SORT_PING) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing)); + else if(g_Config.m_BrSort == IServerBrowser::SORT_MAP) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap)); + else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, + g_Config.m_BrFilterSpectators ? &CServerBrowser::SortCompareNumPlayers : &CServerBrowser::SortCompareNumClients)); + else if(g_Config.m_BrSort == IServerBrowser::SORT_GAMETYPE) + std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype)); + + // set indexes + for(i = 0; i < m_NumSortedServers; i++) + m_ppServerlist[m_pSortedServerlist[i]]->m_Info.m_SortedIndex = i; + + str_copy(m_aFilterGametypeString, g_Config.m_BrFilterGametype, sizeof(m_aFilterGametypeString)); + str_copy(m_aFilterString, g_Config.m_BrFilterString, sizeof(m_aFilterString)); + m_Sorthash = SortHash(); +} + +void CServerBrowser::RemoveRequest(CServerEntry *pEntry) +{ + if(pEntry->m_pPrevReq || pEntry->m_pNextReq || m_pFirstReqServer == pEntry) + { + if(pEntry->m_pPrevReq) + pEntry->m_pPrevReq->m_pNextReq = pEntry->m_pNextReq; + else + m_pFirstReqServer = pEntry->m_pNextReq; + + if(pEntry->m_pNextReq) + pEntry->m_pNextReq->m_pPrevReq = pEntry->m_pPrevReq; + else + m_pLastReqServer = pEntry->m_pPrevReq; + + pEntry->m_pPrevReq = 0; + pEntry->m_pNextReq = 0; + m_NumRequests--; + } +} + +CServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr) +{ + CServerEntry *pEntry = m_aServerlistIp[Addr.ip[0]]; + + for(; pEntry; pEntry = pEntry->m_pNextIp) + { + if(net_addr_comp(&pEntry->m_Addr, &Addr) == 0) + return pEntry; + } + return (CServerEntry*)0; +} + +void CServerBrowser::QueueRequest(CServerEntry *pEntry) +{ + // add it to the list of servers that we should request info from + pEntry->m_pPrevReq = m_pLastReqServer; + if(m_pLastReqServer) + m_pLastReqServer->m_pNextReq = pEntry; + else + m_pFirstReqServer = pEntry; + m_pLastReqServer = pEntry; + pEntry->m_pNextReq = 0; + m_NumRequests++; +} + +void CServerBrowser::SetInfo(CServerEntry *pEntry, const CServerInfo &Info) +{ + int Fav = pEntry->m_Info.m_Favorite; + pEntry->m_Info = Info; + pEntry->m_Info.m_Favorite = Fav; + pEntry->m_Info.m_NetAddr = pEntry->m_Addr; + + // all these are just for nice compability + if(pEntry->m_Info.m_aGameType[0] == '0' && pEntry->m_Info.m_aGameType[1] == 0) + str_copy(pEntry->m_Info.m_aGameType, "DM", sizeof(pEntry->m_Info.m_aGameType)); + else if(pEntry->m_Info.m_aGameType[0] == '1' && pEntry->m_Info.m_aGameType[1] == 0) + str_copy(pEntry->m_Info.m_aGameType, "TDM", sizeof(pEntry->m_Info.m_aGameType)); + else if(pEntry->m_Info.m_aGameType[0] == '2' && pEntry->m_Info.m_aGameType[1] == 0) + str_copy(pEntry->m_Info.m_aGameType, "CTF", sizeof(pEntry->m_Info.m_aGameType)); + + /*if(!request) + { + pEntry->m_Info.latency = (time_get()-pEntry->request_time)*1000/time_freq(); + RemoveRequest(pEntry); + }*/ + + pEntry->m_GotInfo = 1; +} + +CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr) +{ + int Hash = Addr.ip[0]; + CServerEntry *pEntry = 0; + int i; + + // create new pEntry + pEntry = (CServerEntry *)m_ServerlistHeap.Allocate(sizeof(CServerEntry)); + mem_zero(pEntry, sizeof(CServerEntry)); + + // set the info + pEntry->m_Addr = Addr; + pEntry->m_Info.m_NetAddr = Addr; + + pEntry->m_Info.m_Latency = 999; + net_addr_str(&Addr, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aAddress), true); + str_copy(pEntry->m_Info.m_aName, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aName)); + + // check if it's a favorite + for(i = 0; i < m_NumFavoriteServers; i++) + { + if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0) + pEntry->m_Info.m_Favorite = 1; + } + + // add to the hash list + pEntry->m_pNextIp = m_aServerlistIp[Hash]; + m_aServerlistIp[Hash] = pEntry; + + if(m_NumServers == m_NumServerCapacity) + { + CServerEntry **ppNewlist; + m_NumServerCapacity += 100; + ppNewlist = (CServerEntry **)mem_alloc(m_NumServerCapacity*sizeof(CServerEntry*), 1); + mem_copy(ppNewlist, m_ppServerlist, m_NumServers*sizeof(CServerEntry*)); + mem_free(m_ppServerlist); + m_ppServerlist = ppNewlist; + } + + // add to list + m_ppServerlist[m_NumServers] = pEntry; + pEntry->m_Info.m_ServerIndex = m_NumServers; + m_NumServers++; + + return pEntry; +} + +void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo) +{ + static int temp = 0; + CServerEntry *pEntry = 0; + if(Type == IServerBrowser::SET_MASTER_ADD) + { + if(m_ServerlistType != IServerBrowser::TYPE_INTERNET) + return; + m_LastPacketTick = 0; + ++temp; + if(!Find(Addr)) + { + pEntry = Add(Addr); + QueueRequest(pEntry); + } + } + else if(Type == IServerBrowser::SET_FAV_ADD) + { + if(m_ServerlistType != IServerBrowser::TYPE_FAVORITES) + return; + + if(!Find(Addr)) + { + pEntry = Add(Addr); + QueueRequest(pEntry); + } + } + else if(Type == IServerBrowser::SET_DDNET_ADD) + { + if(m_ServerlistType != IServerBrowser::TYPE_DDNET) + return; + + if(!Find(Addr)) + { + pEntry = Add(Addr); + QueueRequest(pEntry); + } + } + else if(Type == IServerBrowser::SET_TOKEN) + { + if(Token != m_CurrentToken) + return; + + pEntry = Find(Addr); + if(!pEntry) + pEntry = Add(Addr); + if(pEntry) + { + SetInfo(pEntry, *pInfo); + if (m_ServerlistType == IServerBrowser::TYPE_LAN) + pEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-m_BroadcastTime)*1000/time_freq()), 999); + else if (pEntry->m_RequestTime > 0) + { + pEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-pEntry->m_RequestTime)*1000/time_freq()), 999); + pEntry->m_RequestTime = -1; // Request has been answered + } + RemoveRequest(pEntry); + } + } + + Sort(); +} + +void CServerBrowser::Refresh(int Type) +{ + // clear out everything + m_ServerlistHeap.Reset(); + m_NumServers = 0; + m_NumSortedServers = 0; + mem_zero(m_aServerlistIp, sizeof(m_aServerlistIp)); + m_pFirstReqServer = 0; + m_pLastReqServer = 0; + m_NumRequests = 0; + m_CurrentMaxRequests = g_Config.m_BrMaxRequests; + // next token + m_CurrentToken = (m_CurrentToken+1)&0xff; + + // + m_ServerlistType = Type; + + if(Type == IServerBrowser::TYPE_LAN) + { + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; + CNetChunk Packet; + int i; + + mem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)); + Buffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken; + + /* do the broadcast version */ + Packet.m_ClientID = -1; + mem_zero(&Packet, sizeof(Packet)); + Packet.m_Address.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(Buffer); + Packet.m_pData = Buffer; + m_BroadcastTime = time_get(); + + for(i = 8303; i <= 8310; i++) + { + Packet.m_Address.port = i; + m_pNetClient->Send(&Packet); + } + + if(g_Config.m_Debug) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", "broadcasting for servers"); + } + else if(Type == IServerBrowser::TYPE_INTERNET) + m_NeedRefresh = 1; + else if(Type == IServerBrowser::TYPE_FAVORITES) + { + for(int i = 0; i < m_NumFavoriteServers; i++) + Set(m_aFavoriteServers[i], IServerBrowser::SET_FAV_ADD, -1, 0); + } + else if(Type == IServerBrowser::TYPE_DDNET) + { + LoadDDNet(); + + // remove unknown elements of exclude list + DDNetCountryFilterClean(); + DDNetTypeFilterClean(); + + for(int i = 0; i < m_NumDDNetCountries; i++) + { + CDDNetCountry *pCntr = &m_aDDNetCountries[i]; + + // check for filter + if(DDNetFiltered(g_Config.m_BrFilterExcludeCountries, pCntr->m_aName)) + continue; + + for(int g = 0; g < pCntr->m_NumServers; g++) + { + if(!DDNetFiltered(g_Config.m_BrFilterExcludeTypes, pCntr->m_aTypes[g])) + Set(pCntr->m_aServers[g], IServerBrowser::SET_DDNET_ADD, -1, 0); + } + } + } +} + +void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const +{ + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; + CNetChunk Packet; + + if(g_Config.m_Debug) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf),"requesting server info from %s", aAddrStr); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); + } + + mem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)); + Buffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken; + + Packet.m_ClientID = -1; + Packet.m_Address = Addr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(Buffer); + Packet.m_pData = Buffer; + + m_pNetClient->Send(&Packet); + + if(pEntry) + pEntry->m_RequestTime = time_get(); +} + +void CServerBrowser::RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) const +{ + unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO64)+1]; + CNetChunk Packet; + + if(g_Config.m_Debug) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf),"requesting server info 64 from %s", aAddrStr); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); + } + + mem_copy(Buffer, SERVERBROWSE_GETINFO64, sizeof(SERVERBROWSE_GETINFO64)); + Buffer[sizeof(SERVERBROWSE_GETINFO64)] = m_CurrentToken; + + Packet.m_ClientID = -1; + Packet.m_Address = Addr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(Buffer); + Packet.m_pData = Buffer; + + m_pNetClient->Send(&Packet); + + if(pEntry) + pEntry->m_RequestTime = time_get(); +} + +void CServerBrowser::Request(const NETADDR &Addr) const +{ + // Call both because we can't know what kind the server is + RequestImpl64(Addr, 0); + RequestImpl(Addr, 0); +} + + +void CServerBrowser::Update(bool ForceResort) +{ + int64 Timeout = time_freq(); + int64 Now = time_get(); + int Count; + CServerEntry *pEntry, *pNext; + + // do server list requests + if(m_NeedRefresh && !m_pMasterServer->IsRefreshing()) + { + NETADDR Addr; + CNetChunk Packet; + int i = 0; + + m_NeedRefresh = 0; + m_MasterServerCount = -1; + mem_zero(&Packet, sizeof(Packet)); + Packet.m_ClientID = -1; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_GETCOUNT); + Packet.m_pData = SERVERBROWSE_GETCOUNT; + + for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + + Addr = m_pMasterServer->GetAddr(i); + m_pMasterServer->SetCount(i, -1); + Packet.m_Address = Addr; + m_pNetClient->Send(&Packet); + if(g_Config.m_Debug) + { + dbg_msg("client_srvbrowse", "Count-Request sent to %d", i); + } + } + } + + //Check if all server counts arrived + if(m_MasterServerCount == -1) + { + m_MasterServerCount = 0; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + int Count = m_pMasterServer->GetCount(i); + if(Count == -1) + { + /* ignore Server + m_MasterServerCount = -1; + return; + // we don't have the required server information + */ + } + else + m_MasterServerCount += Count; + } + //request Server-List + NETADDR Addr; + CNetChunk Packet; + mem_zero(&Packet, sizeof(Packet)); + Packet.m_ClientID = -1; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_GETLIST); + Packet.m_pData = SERVERBROWSE_GETLIST; + + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + + Addr = m_pMasterServer->GetAddr(i); + Packet.m_Address = Addr; + m_pNetClient->Send(&Packet); + } + if(g_Config.m_Debug) + { + dbg_msg("client_srvbrowse", "ServerCount: %d, requesting server list", m_MasterServerCount); + } + m_LastPacketTick = 0; + } + else if(m_MasterServerCount > -1) + { + m_MasterServerCount = 0; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + continue; + int Count = m_pMasterServer->GetCount(i); + if(Count == -1) + { + /* ignore Server + m_MasterServerCount = -1; + return; + // we don't have the required server information + */ + } + else + m_MasterServerCount += Count; + } + //if(g_Config.m_Debug) + //{ + // dbg_msg("client_srvbrowse", "ServerCount2: %d", m_MasterServerCount); + //} + } + if(m_MasterServerCount > m_NumRequests + m_LastPacketTick) + { + ++m_LastPacketTick; + return; //wait for more packets + } + pEntry = m_pFirstReqServer; + Count = 0; + while(1) + { + if(!pEntry) // no more entries + break; + if(pEntry->m_RequestTime && pEntry->m_RequestTime+Timeout < Now) + { + pEntry = pEntry->m_pNextReq; + continue; + } + // no more then 10 concurrent requests + if(Count == m_CurrentMaxRequests) + break; + + if(pEntry->m_RequestTime == 0) + { + if (pEntry->m_Is64) + RequestImpl64(pEntry->m_Addr, pEntry); + else + RequestImpl(pEntry->m_Addr, pEntry); + } + + Count++; + pEntry = pEntry->m_pNextReq; + } + + if(m_pFirstReqServer && Count == 0 && m_CurrentMaxRequests > 1) //NO More current Server Requests + { + //reset old ones + pEntry = m_pFirstReqServer; + while(1) + { + if(!pEntry) // no more entries + break; + pEntry->m_RequestTime = 0; + pEntry = pEntry->m_pNextReq; + } + + //update max-requests + m_CurrentMaxRequests = m_CurrentMaxRequests/2; + if(m_CurrentMaxRequests < 1) + m_CurrentMaxRequests = 1; + } + else if(Count == 0 && m_CurrentMaxRequests == 1) //we reached the limit, just release all left requests. IF a server sends us a packet, a new request will be added automatically, so we can delete all + { + pEntry = m_pFirstReqServer; + while(1) + { + if(!pEntry) // no more entries + break; + pNext = pEntry->m_pNextReq; + RemoveRequest(pEntry); //release request + pEntry = pNext; + } + } + + // check if we need to resort + if(m_Sorthash != SortHash() || ForceResort) + Sort(); +} + + +bool CServerBrowser::IsFavorite(const NETADDR &Addr) const +{ + // search for the address + int i; + for(i = 0; i < m_NumFavoriteServers; i++) + { + if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0) + return true; + } + return false; +} + +void CServerBrowser::AddFavorite(const NETADDR &Addr) +{ + CServerEntry *pEntry; + + if(m_NumFavoriteServers == MAX_FAVORITES) + return; + + // make sure that we don't already have the server in our list + for(int i = 0; i < m_NumFavoriteServers; i++) + { + if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0) + return; + } + + // add the server to the list + m_aFavoriteServers[m_NumFavoriteServers++] = Addr; + pEntry = Find(Addr); + if(pEntry) + pEntry->m_Info.m_Favorite = 1; + + if(g_Config.m_Debug) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "added fav, %s", aAddrStr); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); + } +} + +void CServerBrowser::RemoveFavorite(const NETADDR &Addr) +{ + int i; + CServerEntry *pEntry; + + for(i = 0; i < m_NumFavoriteServers; i++) + { + if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0) + { + mem_move(&m_aFavoriteServers[i], &m_aFavoriteServers[i+1], sizeof(NETADDR)*(m_NumFavoriteServers-(i+1))); + m_NumFavoriteServers--; + + pEntry = Find(Addr); + if(pEntry) + pEntry->m_Info.m_Favorite = 0; + + return; + } + } +} + +void CServerBrowser::LoadDDNet() +{ + // reset servers / countries + m_NumDDNetCountries = 0; + m_NumDDNetTypes = 0; + + // load ddnet server list + IStorage *pStorage = Kernel()->RequestInterface<IStorage>(); + IOHANDLE File = pStorage->OpenFile("ddnet-servers.json", IOFLAG_READ, IStorage::TYPE_ALL); + + if(File) + { + char aBuf[4096*4]; + mem_zero(aBuf, sizeof(aBuf)); + + io_read(File, aBuf, sizeof(aBuf)); + io_close(File); + + + // parse JSON + json_value *pCountries = json_parse(aBuf); + + if (pCountries && pCountries->type == json_array) + { + for (int i = 0; i < json_array_length(pCountries) && m_NumDDNetCountries < MAX_DDNET_COUNTRIES; i++) + { + // pSrv - { name, flagId, servers } + const json_value *pSrv = json_array_get(pCountries, i); + const json_value *pTypes = json_object_get(pSrv, "servers"); + const json_value *pName = json_object_get(pSrv, "name"); + const json_value *pFlagID = json_object_get(pSrv, "flagId"); + + if (pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer) + { + dbg_msg("client_srvbrowse", "Invalid attributes"); + continue; + } + + // build structure + CDDNetCountry *pCntr = &m_aDDNetCountries[m_NumDDNetCountries]; + + pCntr->Reset(); + + str_copy(pCntr->m_aName, json_string_get(pName), sizeof(pCntr->m_aName)); + pCntr->m_FlagID = json_int_get(pFlagID); + + // add country + for (unsigned int t = 0; t < pTypes->u.object.length; t++) + { + const char *pType = pTypes->u.object.values[t].name; + const json_value *pAddrs = pTypes->u.object.values[t].value; + + // add type + if(json_array_length(pAddrs) > 0 && m_NumDDNetTypes < MAX_DDNET_TYPES) + { + int pos; + for(pos = 0; pos < m_NumDDNetTypes; pos++) + { + if(!str_comp(m_aDDNetTypes[pos], pType)) + break; + } + if(pos == m_NumDDNetTypes) + { + str_copy(m_aDDNetTypes[m_NumDDNetTypes], pType, sizeof(m_aDDNetTypes[m_NumDDNetTypes])); + m_NumDDNetTypes++; + } + } + + // add addresses + for (int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++) + { + const json_value *pAddr = json_array_get(pAddrs, g); + const char* pStr = json_string_get(pAddr); + net_addr_from_str(&pCntr->m_aServers[pCntr->m_NumServers], pStr); + str_copy(pCntr->m_aTypes[pCntr->m_NumServers], pType, sizeof(pCntr->m_aTypes[pCntr->m_NumServers])); + } + } + + m_NumDDNetCountries++; + } + } + + if (pCountries) + json_value_free(pCountries); + } +} + +bool CServerBrowser::IsRefreshing() const +{ + return m_pFirstReqServer != 0; +} + +bool CServerBrowser::IsRefreshingMasters() const +{ + return m_pMasterServer->IsRefreshing(); +} + + +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; +} + + +void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData) +{ + CServerBrowser *pSelf = (CServerBrowser *)pUserData; + + char aAddrStr[128]; + char aBuffer[256]; + for(int i = 0; i < pSelf->m_NumFavoriteServers; i++) + { + net_addr_str(&pSelf->m_aFavoriteServers[i], aAddrStr, sizeof(aAddrStr), true); + str_format(aBuffer, sizeof(aBuffer), "add_favorite %s", aAddrStr); + pConfig->WriteLine(aBuffer); + } +} + +void CServerBrowser::DDNetFilterAdd(char *pFilter, const char *pName) +{ + if (DDNetFiltered(pFilter, pName)) + return; + + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), ",%s", pName); + str_append(pFilter, aBuf, 128); +} + +void CServerBrowser::DDNetFilterRem(char *pFilter, const char *pName) +{ + if (!DDNetFiltered(pFilter, pName)) + return; + + // rewrite exclude/filter list + char aBuf[128]; + char *p; + + str_copy(aBuf, pFilter, sizeof(aBuf)); + pFilter[0] = '\0'; + + p = strtok(aBuf, ","); + + while(p) + { + if(str_comp_nocase(pName, p) != 0) + { + char aBuf2[128]; + str_format(aBuf2, sizeof(aBuf2), ",%s", p); + str_append(pFilter, aBuf2, 128); + } + + p = strtok(NULL, ","); + } +} + +bool CServerBrowser::DDNetFiltered(char *pFilter, const char *pName) +{ + char aBuf[128]; + char *p; + + str_copy(aBuf, pFilter, sizeof(aBuf)); + + p = strtok(aBuf, ","); + + while(p) + { + if(str_comp_nocase(pName, p) == 0) + return true; // country excluded + + p = strtok(NULL, ","); + } + + return false; // contry not excluded +} + +void CServerBrowser::DDNetCountryFilterClean() +{ + char aNewList[128]; + + for(int i = 0; i < m_NumDDNetCountries; i++) + { + const char *pName = m_aDDNetCountries[i].m_aName; + if(DDNetFiltered(g_Config.m_BrFilterExcludeCountries, pName)) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), ",%s", pName); + str_append(aNewList, aBuf, sizeof(aNewList)); + } + } + + str_copy(g_Config.m_BrFilterExcludeCountries, aNewList, sizeof(g_Config.m_BrFilterExcludeCountries)); +} + +void CServerBrowser::DDNetTypeFilterClean() +{ + char aNewList[128]; + + for(int i = 0; i < m_NumDDNetTypes; i++) + { + const char *pName = m_aDDNetTypes[i]; + if(DDNetFiltered(g_Config.m_BrFilterExcludeTypes, pName)) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), ",%s", pName); + str_append(aNewList, aBuf, sizeof(aNewList)); + } + } + + str_copy(g_Config.m_BrFilterExcludeTypes, aNewList, sizeof(g_Config.m_BrFilterExcludeTypes)); +} diff --git a/src/engine/client/serverbrowser.h b/src/engine/client/serverbrowser.h new file mode 100644 index 0000000..fbd9fa7 --- /dev/null +++ b/src/engine/client/serverbrowser.h @@ -0,0 +1,174 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_SERVERBROWSER_H +#define ENGINE_CLIENT_SERVERBROWSER_H + +#include <engine/serverbrowser.h> + +class CServerBrowser : public IServerBrowser +{ +public: + class CServerEntry + { + public: + NETADDR m_Addr; + int64 m_RequestTime; + bool m_Is64; + int m_GotInfo; + CServerInfo m_Info; + + CServerEntry *m_pNextIp; // ip hashed list + + CServerEntry *m_pPrevReq; // request list + CServerEntry *m_pNextReq; + }; + + class CDDNetCountry + { + public: + enum + { + MAX_SERVERS = 1024 + }; + + char m_aName[256]; + int m_FlagID; + NETADDR m_aServers[MAX_SERVERS]; + char m_aTypes[MAX_SERVERS][32]; + int m_NumServers; + + void Reset() { m_NumServers = 0; m_FlagID = -1; m_aName[0] = '\0'; }; + /*void Add(NETADDR Addr, char* pType) { + if (m_NumServers < MAX_SERVERS) + { + m_aServers[m_NumServers] = Addr; + str_copy(m_aTypes[m_NumServers], pType, sizeof(m_aTypes[0])); + m_NumServers++; + } + };*/ + }; + + enum + { + MAX_FAVORITES=2048, + MAX_DDNET_COUNTRIES=16, + MAX_DDNET_TYPES=32, + }; + + CServerBrowser(); + + // interface functions + void Refresh(int Type); + bool IsRefreshing() const; + bool IsRefreshingMasters() const; + int LoadingProgression() const; + + int NumServers() const { return m_NumServers; } + + int NumSortedServers() const { return m_NumSortedServers; } + const CServerInfo *SortedGet(int Index) const; + + bool IsFavorite(const NETADDR &Addr) const; + void AddFavorite(const NETADDR &Addr); + void RemoveFavorite(const NETADDR &Addr); + + void LoadDDNet(); + int NumDDNetCountries() { return m_NumDDNetCountries; }; + int GetDDNetCountryFlag(int Index) { return m_aDDNetCountries[Index].m_FlagID; }; + const char *GetDDNetCountryName(int Index) { return m_aDDNetCountries[Index].m_aName; }; + + int NumDDNetTypes() { return m_NumDDNetTypes; }; + const char *GetDDNetType(int Index) { return m_aDDNetTypes[Index]; }; + + void DDNetFilterAdd(char *pFilter, const char *pName); + void DDNetFilterRem(char *pFilter, const char *pName); + bool DDNetFiltered(char *pFilter, const char *pName); + void DDNetCountryFilterClean(); + void DDNetTypeFilterClean(); + + // + void Update(bool ForceResort); + void Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo); + void Request(const NETADDR &Addr) const; + + void SetBaseInfo(class CNetClient *pClient, const char *pNetVersion); + + void RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) const; + void QueueRequest(CServerEntry *pEntry); + CServerEntry *Find(const NETADDR &Addr); + int GetCurrentType() { return m_ServerlistType; }; + +private: + CNetClient *m_pNetClient; + IMasterServer *m_pMasterServer; + class IConsole *m_pConsole; + class IFriends *m_pFriends; + char m_aNetVersion[128]; + + CHeap m_ServerlistHeap; + CServerEntry **m_ppServerlist; + int *m_pSortedServerlist; + + NETADDR m_aFavoriteServers[MAX_FAVORITES]; + int m_NumFavoriteServers; + + CDDNetCountry m_aDDNetCountries[MAX_DDNET_COUNTRIES]; + int m_NumDDNetCountries; + + char m_aDDNetTypes[MAX_DDNET_TYPES][32]; + int m_NumDDNetTypes; + + CServerEntry *m_aServerlistIp[256]; // ip hash list + + CServerEntry *m_pFirstReqServer; // request list + CServerEntry *m_pLastReqServer; + int m_NumRequests; + int m_MasterServerCount; + + //used instead of g_Config.br_max_requests to get more servers + int m_CurrentMaxRequests; + + int m_LastPacketTick; + + int m_NeedRefresh; + + int m_NumSortedServers; + int m_NumSortedServersCapacity; + int m_NumServers; + int m_NumServerCapacity; + + int m_Sorthash; + char m_aFilterString[64]; + char m_aFilterGametypeString[128]; + + // the token is to keep server refresh separated from each other + int m_CurrentToken; + + int m_ServerlistType; + int64 m_BroadcastTime; + + // sorting criterions + bool SortCompareName(int Index1, int Index2) const; + bool SortCompareMap(int Index1, int Index2) const; + bool SortComparePing(int Index1, int Index2) const; + bool SortCompareGametype(int Index1, int Index2) const; + bool SortCompareNumPlayers(int Index1, int Index2) const; + bool SortCompareNumClients(int Index1, int Index2) const; + + // + void Filter(); + void Sort(); + int SortHash() const; + + CServerEntry *Add(const NETADDR &Addr); + + void RemoveRequest(CServerEntry *pEntry); + + void RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const; + + void SetInfo(CServerEntry *pEntry, const CServerInfo &Info); + + static void ConfigSaveCallback(IConfig *pConfig, void *pUserData); +}; + +#endif diff --git a/src/engine/client/sound.cpp b/src/engine/client/sound.cpp new file mode 100644 index 0000000..230007d --- /dev/null +++ b/src/engine/client/sound.cpp @@ -0,0 +1,929 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/graphics.h> +#include <engine/storage.h> + +#include <engine/shared/config.h> + +#include "SDL.h" + +#include "sound.h" + +extern "C" { // wavpack + #include <engine/external/wavpack/wavpack.h> + #include <opusfile.h> +} +#include <math.h> + +enum +{ + NUM_SAMPLES = 512, + NUM_VOICES = 256, + NUM_CHANNELS = 16, +}; + +struct CSample +{ + short *m_pData; + int m_NumFrames; + int m_Rate; + int m_Channels; + int m_LoopStart; + int m_LoopEnd; + int m_PausedAt; +}; + +struct CChannel +{ + int m_Vol; + int m_Pan; +}; + +struct CVoice +{ + CSample *m_pSample; + CChannel *m_pChannel; + int m_Age; // increases when reused + int m_Tick; + int m_Vol; // 0 - 255 + int m_Flags; + int m_X, m_Y; + float m_Falloff; // [0.0, 1.0] + + int m_Shape; + union + { + ISound::CVoiceShapeCircle m_Circle; + ISound::CVoiceShapeRectangle m_Rectangle; + }; +}; + +static CSample m_aSamples[NUM_SAMPLES] = { {0} }; +static CVoice m_aVoices[NUM_VOICES] = { {0} }; +static CChannel m_aChannels[NUM_CHANNELS] = { {255, 0} }; + +static LOCK m_SoundLock = 0; + +static int m_CenterX = 0; +static int m_CenterY = 0; + +static int m_MixingRate = 48000; +static volatile int m_SoundVolume = 100; + +static int m_NextVoice = 0; +static int *m_pMixBuffer = 0; // buffer only used by the thread callback function +static unsigned m_MaxFrames = 0; + +static const void *ms_pWVBuffer = 0x0; +static int ms_WVBufferPosition = 0; +static int ms_WVBufferSize = 0; + +const int DefaultDistance = 1500; + +// TODO: there should be a faster way todo this +static short Int2Short(int i) +{ + if(i > 0x7fff) + return 0x7fff; + else if(i < -0x7fff) + return -0x7fff; + return i; +} + +static int IntAbs(int i) +{ + if(i<0) + return -i; + return i; +} + +static void Mix(short *pFinalOut, unsigned Frames) +{ + int MasterVol; + mem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int)); + Frames = min(Frames, m_MaxFrames); + + // aquire lock while we are mixing + lock_wait(m_SoundLock); + + MasterVol = m_SoundVolume; + + for(unsigned i = 0; i < NUM_VOICES; i++) + { + if(m_aVoices[i].m_pSample) + { + // mix voice + CVoice *v = &m_aVoices[i]; + int *pOut = m_pMixBuffer; + + int Step = v->m_pSample->m_Channels; // setup input sources + short *pInL = &v->m_pSample->m_pData[v->m_Tick*Step]; + short *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1]; + + unsigned End = v->m_pSample->m_NumFrames-v->m_Tick; + + int Rvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f)); + int Lvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f)); + + // make sure that we don't go outside the sound data + if(Frames < End) + End = Frames; + + // check if we have a mono sound + if(v->m_pSample->m_Channels == 1) + pInR = pInL; + + // volume calculation + if(v->m_Flags&ISound::FLAG_POS && v->m_pChannel->m_Pan) + { + // TODO: we should respect the channel panning value + int dx = v->m_X - m_CenterX; + int dy = v->m_Y - m_CenterY; + // + int p = IntAbs(dx); + float FalloffX = 0.0f; + float FalloffY = 0.0f; + + int RangeX = 0; // for panning + bool InVoiceField = false; + + switch(v->m_Shape) + { + case ISound::SHAPE_CIRCLE: + { + float r = v->m_Circle.m_Radius; + RangeX = r; + + int Dist = (int)sqrtf((float)dx*dx+dy*dy); // nasty float + if(Dist < r) + { + InVoiceField = true; + + // falloff + int FalloffDistance = r*v->m_Falloff; + if(Dist > FalloffDistance) + FalloffX = FalloffY = (r-Dist)/(r-FalloffDistance); + else + FalloffX = FalloffY = 1.0f; + } + else + InVoiceField = false; + + break; + } + + case ISound::SHAPE_RECTANGLE: + { + RangeX = v->m_Rectangle.m_Width/2.0f; + + int abs_dx = abs(dx); + int abs_dy = abs(dy); + + int w = v->m_Rectangle.m_Width/2.0f; + int h = v->m_Rectangle.m_Height/2.0f; + + if(abs_dx < w && abs_dy < h) + { + InVoiceField = true; + + // falloff + int fx = v->m_Falloff * w; + int fy = v->m_Falloff * h; + + FalloffX = abs_dx > fx ? (float)(w-abs_dx)/(w-fx) : 1.0f; + FalloffY = abs_dy > fy ? (float)(h-abs_dy)/(h-fy) : 1.0f; + } + else + InVoiceField = false; + + break; + } + }; + + if(InVoiceField) + { + // panning + if(!(v->m_Flags&ISound::FLAG_NO_PANNING)) + { + if(dx > 0) + Lvol = ((RangeX-p)*Lvol)/RangeX; + else + Rvol = ((RangeX-p)*Rvol)/RangeX; + } + + { + Lvol *= FalloffX; + Rvol *= FalloffY; + } + } + else + { + Lvol = 0; + Rvol = 0; + } + } + + // process all frames + for(unsigned s = 0; s < End; s++) + { + *pOut++ += (*pInL)*Lvol; + *pOut++ += (*pInR)*Rvol; + pInL += Step; + pInR += Step; + v->m_Tick++; + } + + // free voice if not used any more + if(v->m_Tick == v->m_pSample->m_NumFrames) + { + if(v->m_Flags&ISound::FLAG_LOOP) + v->m_Tick = 0; + else + { + v->m_pSample = 0; + v->m_Age++; + } + } + } + } + + + // release the lock + lock_unlock(m_SoundLock); + + { + // clamp accumulated values + // TODO: this seams slow + for(unsigned i = 0; i < Frames; i++) + { + int j = i<<1; + int vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8; + int vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8; + + pFinalOut[j] = Int2Short(vl); + pFinalOut[j+1] = Int2Short(vr); + } + } + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(pFinalOut, sizeof(short), Frames * 2); +#endif +} + +static void SdlCallback(void *pUnused, Uint8 *pStream, int Len) +{ + (void)pUnused; + Mix((short *)pStream, Len/2/2); +} + + +int CSound::Init() +{ + m_SoundEnabled = 0; + m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + + SDL_AudioSpec Format, FormatOut; + + m_SoundLock = lock_create(); + + if(!g_Config.m_SndEnable) + return 0; + + if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) + { + dbg_msg("gfx", "unable to init SDL audio: %s", SDL_GetError()); + return -1; + } + + m_MixingRate = g_Config.m_SndRate; + + // Set 16-bit stereo audio at 22Khz + Format.freq = g_Config.m_SndRate; // ignore_convention + Format.format = AUDIO_S16; // ignore_convention + Format.channels = 2; // ignore_convention + Format.samples = g_Config.m_SndBufferSize; // ignore_convention + Format.callback = SdlCallback; // ignore_convention + Format.userdata = NULL; // ignore_convention + + // Open the audio device and start playing sound! + if(SDL_OpenAudio(&Format, &FormatOut) < 0) + { + dbg_msg("client/sound", "unable to open audio: %s", SDL_GetError()); + return -1; + } + else + dbg_msg("client/sound", "sound init successful"); + + m_MaxFrames = FormatOut.samples*2; + m_pMixBuffer = (int *)mem_alloc(m_MaxFrames*2*sizeof(int), 1); + + SDL_PauseAudio(0); + + m_SoundEnabled = 1; + Update(); // update the volume + return 0; +} + +int CSound::Update() +{ + // update volume + int WantedVolume = g_Config.m_SndVolume; + + if(!m_pGraphics->WindowActive() && g_Config.m_SndNonactiveMute) + WantedVolume = 0; + + if(WantedVolume != m_SoundVolume) + { + lock_wait(m_SoundLock); + m_SoundVolume = WantedVolume; + lock_unlock(m_SoundLock); + } + + return 0; +} + +int CSound::Shutdown() +{ + SDL_CloseAudio(); + SDL_QuitSubSystem(SDL_INIT_AUDIO); + lock_destroy(m_SoundLock); + if(m_pMixBuffer) + { + mem_free(m_pMixBuffer); + m_pMixBuffer = 0; + } + return 0; +} + +int CSound::AllocID() +{ + // TODO: linear search, get rid of it + for(unsigned SampleID = 0; SampleID < NUM_SAMPLES; SampleID++) + { + if(m_aSamples[SampleID].m_pData == 0x0) + return SampleID; + } + + return -1; +} + +void CSound::RateConvert(int SampleID) +{ + CSample *pSample = &m_aSamples[SampleID]; + int NumFrames = 0; + short *pNewData = 0; + + // make sure that we need to convert this sound + if(!pSample->m_pData || pSample->m_Rate == m_MixingRate) + return; + + // allocate new data + NumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate); + pNewData = (short *)mem_alloc(NumFrames*pSample->m_Channels*sizeof(short), 1); + + for(int i = 0; i < NumFrames; i++) + { + // resample TODO: this should be done better, like linear atleast + float a = i/(float)NumFrames; + int f = (int)(a*pSample->m_NumFrames); + if(f >= pSample->m_NumFrames) + f = pSample->m_NumFrames-1; + + // set new data + if(pSample->m_Channels == 1) + pNewData[i] = pSample->m_pData[f]; + else if(pSample->m_Channels == 2) + { + pNewData[i*2] = pSample->m_pData[f*2]; + pNewData[i*2+1] = pSample->m_pData[f*2+1]; + } + } + + // free old data and apply new + mem_free(pSample->m_pData); + pSample->m_pData = pNewData; + pSample->m_NumFrames = NumFrames; + pSample->m_Rate = m_MixingRate; +} + +int CSound::ReadData(void *pBuffer, int Size) +{ + int ChunkSize = min(Size, ms_WVBufferSize - ms_WVBufferPosition); + mem_copy(pBuffer, (const char *)ms_pWVBuffer + ms_WVBufferPosition, ChunkSize); + ms_WVBufferPosition += ChunkSize; + return ChunkSize; +} + +int CSound::DecodeOpus(int SampleID, const void *pData, unsigned DataSize) +{ + if(SampleID == -1 || SampleID >= NUM_SAMPLES) + return -1; + + CSample *pSample = &m_aSamples[SampleID]; + + OggOpusFile *OpusFile = op_open_memory((const unsigned char *) pData, DataSize, NULL); + if (OpusFile) + { + int NumChannels = op_channel_count(OpusFile, -1); + int NumSamples = op_pcm_total(OpusFile, -1); // per channel! + + pSample->m_Channels = NumChannels; + + if(pSample->m_Channels > 2) + { + dbg_msg("sound/opus", "file is not mono or stereo."); + return -1; + } + + pSample->m_pData = (short *)mem_alloc(NumSamples * sizeof(short) * NumChannels, 1); + + int Read; + int Pos = 0; + while (Pos < NumSamples) + { + Read = op_read(OpusFile, pSample->m_pData + Pos*NumChannels, NumSamples*NumChannels, NULL); + Pos += Read; + } + + pSample->m_NumFrames = NumSamples; // ? + pSample->m_Rate = 48000; + pSample->m_LoopStart = -1; + pSample->m_LoopEnd = -1; + pSample->m_PausedAt = 0; + } + else + { + dbg_msg("sound/opus", "failed to decode sample"); + return -1; + } + + return SampleID; +} + +int CSound::DecodeWV(int SampleID, const void *pData, unsigned DataSize) +{ + if(SampleID == -1 || SampleID >= NUM_SAMPLES) + return -1; + + CSample *pSample = &m_aSamples[SampleID]; + char aError[100]; + WavpackContext *pContext; + + ms_pWVBuffer = pData; + ms_WVBufferSize = DataSize; + ms_WVBufferPosition = 0; + + pContext = WavpackOpenFileInput(ReadData, aError); + if (pContext) + { + int NumSamples = WavpackGetNumSamples(pContext); + int BitsPerSample = WavpackGetBitsPerSample(pContext); + unsigned int SampleRate = WavpackGetSampleRate(pContext); + int NumChannels = WavpackGetNumChannels(pContext); + int *pSrc; + short *pDst; + int i; + + pSample->m_Channels = NumChannels; + pSample->m_Rate = SampleRate; + + if(pSample->m_Channels > 2) + { + dbg_msg("sound/wv", "file is not mono or stereo."); + return -1; + } + + if(BitsPerSample != 16) + { + dbg_msg("sound/wv", "bps is %d, not 16", BitsPerSample); + return -1; + } + + int *pBuffer = (int *)mem_alloc(4*NumSamples*NumChannels, 1); + WavpackUnpackSamples(pContext, pBuffer, NumSamples); // TODO: check return value + pSrc = pBuffer; + + pSample->m_pData = (short *)mem_alloc(2*NumSamples*NumChannels, 1); + pDst = pSample->m_pData; + + for (i = 0; i < NumSamples*NumChannels; i++) + *pDst++ = (short)*pSrc++; + + mem_free(pBuffer); + + pSample->m_NumFrames = NumSamples; + pSample->m_LoopStart = -1; + pSample->m_LoopEnd = -1; + pSample->m_PausedAt = 0; + } + else + { + dbg_msg("sound/wv", "failed to decode sample (%s)", aError); + return -1; + } + + return SampleID; +} + +int CSound::LoadOpus(const char *pFilename) +{ + // don't waste memory on sound when we are stress testing + if(g_Config.m_DbgStress) + return -1; + + // no need to load sound when we are running with no sound + if(!m_SoundEnabled) + return -1; + + if(!m_pStorage) + return -1; + + ms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); + if(!ms_File) + { + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFilename); + return -1; + } + + int SampleID = AllocID(); + if(SampleID < 0) + return -1; + + // read the whole file into memory + int DataSize = io_length(ms_File); + + if(DataSize <= 0) + { + io_close(ms_File); + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFilename); + return -1; + } + + char *pData = new char[DataSize]; + io_read(ms_File, pData, DataSize); + + SampleID = DecodeOpus(SampleID, pData, DataSize); + + delete[] pData; + io_close(ms_File); + ms_File = NULL; + + if(g_Config.m_Debug) + dbg_msg("sound/opus", "loaded %s", pFilename); + + RateConvert(SampleID); + return SampleID; +} + + +int CSound::LoadWV(const char *pFilename) +{ + // don't waste memory on sound when we are stress testing + if(g_Config.m_DbgStress) + return -1; + + // no need to load sound when we are running with no sound + if(!m_SoundEnabled) + return -1; + + if(!m_pStorage) + return -1; + + ms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); + if(!ms_File) + { + dbg_msg("sound/wv", "failed to open file. filename='%s'", pFilename); + return -1; + } + + int SampleID = AllocID(); + if(SampleID < 0) + return -1; + + // read the whole file into memory + int DataSize = io_length(ms_File); + + if(DataSize <= 0) + { + io_close(ms_File); + dbg_msg("sound/wv", "failed to open file. filename='%s'", pFilename); + return -1; + } + + char *pData = new char[DataSize]; + io_read(ms_File, pData, DataSize); + + SampleID = DecodeWV(SampleID, pData, DataSize); + + delete[] pData; + io_close(ms_File); + ms_File = NULL; + + if(g_Config.m_Debug) + dbg_msg("sound/wv", "loaded %s", pFilename); + + RateConvert(SampleID); + return SampleID; +} + +int CSound::LoadOpusFromMem(const void *pData, unsigned DataSize, bool FromEditor = false) +{ + // don't waste memory on sound when we are stress testing + if(g_Config.m_DbgStress) + return -1; + + // no need to load sound when we are running with no sound + if(!m_SoundEnabled && !FromEditor) + return -1; + + if(!pData) + return -1; + + int SampleID = AllocID(); + if(SampleID < 0) + return -1; + + SampleID = DecodeOpus(SampleID, pData, DataSize); + + RateConvert(SampleID); + return SampleID; +} + +int CSound::LoadWVFromMem(const void *pData, unsigned DataSize, bool FromEditor = false) +{ + // don't waste memory on sound when we are stress testing + if(g_Config.m_DbgStress) + return -1; + + // no need to load sound when we are running with no sound + if(!m_SoundEnabled && !FromEditor) + return -1; + + if(!pData) + return -1; + + int SampleID = AllocID(); + if(SampleID < 0) + return -1; + + SampleID = DecodeWV(SampleID, pData, DataSize); + + RateConvert(SampleID); + return SampleID; +} + +void CSound::UnloadSample(int SampleID) +{ + if(SampleID == -1 || SampleID >= NUM_SAMPLES) + return; + + Stop(SampleID); + mem_free(m_aSamples[SampleID].m_pData); + + m_aSamples[SampleID].m_pData = 0x0; +} + +float CSound::GetSampleDuration(int SampleID) +{ + if(SampleID == -1 || SampleID >= NUM_SAMPLES) + return 0.0f; + + return (m_aSamples[SampleID].m_NumFrames/m_aSamples[SampleID].m_Rate); +} + +void CSound::SetListenerPos(float x, float y) +{ + m_CenterX = (int)x; + m_CenterY = (int)y; +} + +void CSound::SetVoiceVolume(CVoiceHandle Voice, float Volume) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + Volume = clamp(Volume, 0.0f, 1.0f); + m_aVoices[VoiceID].m_Vol = (int)(Volume*255.0f); +} + +void CSound::SetVoiceFalloff(CVoiceHandle Voice, float Falloff) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + Falloff = clamp(Falloff, 0.0f, 1.0f); + m_aVoices[VoiceID].m_Falloff = Falloff; +} + +void CSound::SetVoiceLocation(CVoiceHandle Voice, float x, float y) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + m_aVoices[VoiceID].m_X = x; + m_aVoices[VoiceID].m_Y = y; +} + +void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float offset) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + lock_wait(m_SoundLock); + { + if(m_aVoices[VoiceID].m_pSample) + { + int Tick = 0; + bool IsLooping = m_aVoices[VoiceID].m_Flags&ISound::FLAG_LOOP; + uint64_t TickOffset = m_aVoices[VoiceID].m_pSample->m_Rate * offset; + if(m_aVoices[VoiceID].m_pSample->m_NumFrames > 0 && IsLooping) + Tick = TickOffset % m_aVoices[VoiceID].m_pSample->m_NumFrames; + else + Tick = clamp(TickOffset, (uint64_t)0, (uint64_t)m_aVoices[VoiceID].m_pSample->m_NumFrames); + + // at least 200msec off, else depend on buffer size + float Threshold = max(0.2f * m_aVoices[VoiceID].m_pSample->m_Rate, (float)m_MaxFrames); + if(abs(m_aVoices[VoiceID].m_Tick-Tick) > Threshold) + { + // take care of looping (modulo!) + if( !(IsLooping && (min(m_aVoices[VoiceID].m_Tick, Tick) + m_aVoices[VoiceID].m_pSample->m_NumFrames - max(m_aVoices[VoiceID].m_Tick, Tick)) <= Threshold)) + { + m_aVoices[VoiceID].m_Tick = Tick; + } + } + } + } + lock_unlock(m_SoundLock); +} + +void CSound::SetVoiceCircle(CVoiceHandle Voice, float Radius) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + m_aVoices[VoiceID].m_Shape = ISound::SHAPE_CIRCLE; + m_aVoices[VoiceID].m_Circle.m_Radius = max(0.0f, Radius); +} + +void CSound::SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + m_aVoices[VoiceID].m_Shape = ISound::SHAPE_RECTANGLE; + m_aVoices[VoiceID].m_Rectangle.m_Width = max(0.0f, Width); + m_aVoices[VoiceID].m_Rectangle.m_Height = max(0.0f, Height); +} + +void CSound::SetChannel(int ChannelID, float Vol, float Pan) +{ + m_aChannels[ChannelID].m_Vol = (int)(Vol*255.0f); + m_aChannels[ChannelID].m_Pan = (int)(Pan*255.0f); // TODO: this is only on and off right now +} + +ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float x, float y) +{ + int VoiceID = -1; + int Age = -1; + int i; + + lock_wait(m_SoundLock); + + // search for voice + for(i = 0; i < NUM_VOICES; i++) + { + int id = (m_NextVoice + i) % NUM_VOICES; + if(!m_aVoices[id].m_pSample) + { + VoiceID = id; + m_NextVoice = id+1; + break; + } + } + + // voice found, use it + if(VoiceID != -1) + { + m_aVoices[VoiceID].m_pSample = &m_aSamples[SampleID]; + m_aVoices[VoiceID].m_pChannel = &m_aChannels[ChannelID]; + if(Flags & FLAG_LOOP) + m_aVoices[VoiceID].m_Tick = m_aSamples[SampleID].m_PausedAt; + else + m_aVoices[VoiceID].m_Tick = 0; + m_aVoices[VoiceID].m_Vol = 255; + m_aVoices[VoiceID].m_Flags = Flags; + m_aVoices[VoiceID].m_X = (int)x; + m_aVoices[VoiceID].m_Y = (int)y; + m_aVoices[VoiceID].m_Falloff = 0.0f; + m_aVoices[VoiceID].m_Shape = ISound::SHAPE_CIRCLE; + m_aVoices[VoiceID].m_Circle.m_Radius = DefaultDistance; + Age = m_aVoices[VoiceID].m_Age; + } + + lock_unlock(m_SoundLock); + return CreateVoiceHandle(VoiceID, Age); +} + +ISound::CVoiceHandle CSound::PlayAt(int ChannelID, int SampleID, int Flags, float x, float y) +{ + return Play(ChannelID, SampleID, Flags|ISound::FLAG_POS, x, y); +} + +ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags) +{ + return Play(ChannelID, SampleID, Flags, 0, 0); +} + +void CSound::Stop(int SampleID) +{ + // TODO: a nice fade out + lock_wait(m_SoundLock); + CSample *pSample = &m_aSamples[SampleID]; + for(int i = 0; i < NUM_VOICES; i++) + { + if(m_aVoices[i].m_pSample == pSample) + { + if(m_aVoices[i].m_Flags & FLAG_LOOP) + m_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick; + else + m_aVoices[i].m_pSample->m_PausedAt = 0; + m_aVoices[i].m_pSample = 0; + } + } + lock_unlock(m_SoundLock); +} + +void CSound::StopAll() +{ + // TODO: a nice fade out + lock_wait(m_SoundLock); + for(int i = 0; i < NUM_VOICES; i++) + { + if(m_aVoices[i].m_pSample) + { + if(m_aVoices[i].m_Flags & FLAG_LOOP) + m_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick; + else + m_aVoices[i].m_pSample->m_PausedAt = 0; + } + m_aVoices[i].m_pSample = 0; + } + lock_unlock(m_SoundLock); +} + +void CSound::StopVoice(CVoiceHandle Voice) +{ + if(!Voice.IsValid()) + return; + + int VoiceID = Voice.Id(); + + if(m_aVoices[VoiceID].m_Age != Voice.Age()) + return; + + lock_wait(m_SoundLock); + { + m_aVoices[VoiceID].m_pSample = 0; + m_aVoices[VoiceID].m_Age++; + } + lock_unlock(m_SoundLock); +} + + +IOHANDLE CSound::ms_File = 0; + +IEngineSound *CreateEngineSound() { return new CSound; } diff --git a/src/engine/client/sound.h b/src/engine/client/sound.h new file mode 100644 index 0000000..09fb972 --- /dev/null +++ b/src/engine/client/sound.h @@ -0,0 +1,59 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CLIENT_SOUND_H +#define ENGINE_CLIENT_SOUND_H + +#include <engine/sound.h> + +class CSound : public IEngineSound +{ + int m_SoundEnabled; + +public: + IEngineGraphics *m_pGraphics; + IStorage *m_pStorage; + + virtual int Init(); + + int Update(); + int Shutdown(); + int AllocID(); + + static void RateConvert(int SampleID); + + // TODO: Refactor: clean this mess up + static IOHANDLE ms_File; + static int ReadData(void *pBuffer, int Size); + static int DecodeWV(int SampleID, const void *pData, unsigned DataSize); + static int DecodeOpus(int SampleID, const void *pData, unsigned DataSize); + + virtual bool IsSoundEnabled() { return m_SoundEnabled != 0; } + + virtual int LoadWV(const char *pFilename); + virtual int LoadWVFromMem(const void *pData, unsigned DataSize, bool FromEditor); + virtual int LoadOpus(const char *pFilename); + virtual int LoadOpusFromMem(const void *pData, unsigned DataSize, bool FromEditor); + virtual void UnloadSample(int SampleID); + + virtual float GetSampleDuration(int SampleID); // in s + + virtual void SetListenerPos(float x, float y); + virtual void SetChannel(int ChannelID, float Vol, float Pan); + + virtual void SetVoiceVolume(CVoiceHandle Voice, float Volume); + virtual void SetVoiceFalloff(CVoiceHandle Voice, float Falloff); + virtual void SetVoiceLocation(CVoiceHandle Voice, float x, float y); + virtual void SetVoiceTimeOffset(CVoiceHandle Voice, float offset); // in s + + virtual void SetVoiceCircle(CVoiceHandle Voice, float Radius); + virtual void SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height); + + CVoiceHandle Play(int ChannelID, int SampleID, int Flags, float x, float y); + virtual CVoiceHandle PlayAt(int ChannelID, int SampleID, int Flags, float x, float y); + virtual CVoiceHandle Play(int ChannelID, int SampleID, int Flags); + virtual void Stop(int SampleID); + virtual void StopAll(); + virtual void StopVoice(CVoiceHandle Voice); +}; + +#endif diff --git a/src/engine/client/text.cpp b/src/engine/client/text.cpp new file mode 100644 index 0000000..39ed536 --- /dev/null +++ b/src/engine/client/text.cpp @@ -0,0 +1,737 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <base/math.h> +#include <engine/graphics.h> +#include <engine/textrender.h> + +#ifdef CONF_FAMILY_WINDOWS + #include <windows.h> +#endif + +// ft2 texture +#include <ft2build.h> +#include FT_FREETYPE_H + +// TODO: Refactor: clean this up +enum +{ + MAX_CHARACTERS = 64, +}; + + +static int aFontSizes[] = {8,9,10,11,12,13,14,15,16,17,18,19,20,36,64}; +#define NUM_FONT_SIZES (sizeof(aFontSizes)/sizeof(int)) + +struct CFontChar +{ + int m_ID; + + // these values are scaled to the pFont size + // width * font_size == real_size + float m_Width; + float m_Height; + float m_OffsetX; + float m_OffsetY; + float m_AdvanceX; + + float m_aUvs[4]; + int64 m_TouchTime; +}; + +struct CFontSizeData +{ + int m_FontSize; + FT_Face *m_pFace; + + int 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; +}; + +class CFont +{ +public: + char m_aFilename[512]; + FT_Face m_FtFace; + CFontSizeData m_aSizes[NUM_FONT_SIZES]; +}; + + +class CTextRender : public IEngineTextRender +{ + IGraphics *m_pGraphics; + IGraphics *Graphics() { return m_pGraphics; } + + int WordLength(const char *pText) + { + int s = 1; + while(1) + { + if(*pText == 0) + return s-1; + if(*pText == '\n' || *pText == '\t' || *pText == ' ') + return s; + pText++; + s++; + } + } + + float m_TextR; + float m_TextG; + float m_TextB; + float m_TextA; + + float m_TextOutlineR; + 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++) + { + 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 sy = -1; sy <= 1; sy++) + for(int sx = -1; sx <= 1; sx++) + { + int GetX = x+sx; + int GetY = y+sy; + if (GetX >= 0 && GetY >= 0 && GetX < w && GetY < h) + { + int Index = GetY*w+GetX; + if(pIn[Index] > c) + c = pIn[Index]; + } + } + + pOut[y*w+x] = c; + } + } + + void InitTexture(CFontSizeData *pSizeData, int CharWidth, int CharHeight, int Xchars, int Ychars) + { + static int FontMemoryUsage = 0; + int Width = CharWidth*Xchars; + int Height = CharHeight*Ychars; + void *pMem = mem_alloc(Width*Height, 1); + mem_zero(pMem, Width*Height); + + for(int i = 0; i < 2; i++) + { + if(pSizeData->m_aTextures[i] != 0) + { + Graphics()->UnloadTexture(pSizeData->m_aTextures[i]); + FontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight; + pSizeData->m_aTextures[i] = 0; + } + + pSizeData->m_aTextures[i] = Graphics()->LoadTextureRaw(Width, Height, CImageInfo::FORMAT_ALPHA, pMem, CImageInfo::FORMAT_ALPHA, IGraphics::TEXLOAD_NOMIPMAPS); + FontMemoryUsage += Width*Height; + } + + pSizeData->m_NumXChars = Xchars; + pSizeData->m_NumYChars = Ychars; + pSizeData->m_TextureWidth = Width; + pSizeData->m_TextureHeight = Height; + pSizeData->m_CurrentCharacter = 0; + + dbg_msg("text", "pFont memory usage: %d", FontMemoryUsage); + + mem_free(pMem); + } + + int AdjustOutlineThicknessToFontSize(int OutlineThickness, int FontSize) + { + if(FontSize > 36) + OutlineThickness *= 4; + else if(FontSize >= 18) + OutlineThickness *= 2; + return OutlineThickness; + } + + void IncreaseTextureSize(CFontSizeData *pSizeData) + { + if(pSizeData->m_TextureWidth < pSizeData->m_TextureHeight) + pSizeData->m_NumXChars <<= 1; + else + pSizeData->m_NumYChars <<= 1; + 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); + } + + CFontSizeData *GetSize(CFont *pFont, int Pixelsize) + { + int Index = GetFontSizeIndex(Pixelsize); + if(pFont->m_aSizes[Index].m_FontSize != aFontSizes[Index]) + InitIndex(pFont, Index); + return &pFont->m_aSizes[Index]; + } + + + void UploadGlyph(CFontSizeData *pSizeData, int Texnum, int SlotID, int Chr, const void *pData) + { + int x = (SlotID%pSizeData->m_NumXChars) * (pSizeData->m_TextureWidth/pSizeData->m_NumXChars); + int y = (SlotID/pSizeData->m_NumXChars) * (pSizeData->m_TextureHeight/pSizeData->m_NumYChars); + + Graphics()->LoadTextureRawSub(pSizeData->m_aTextures[Texnum], x, y, + pSizeData->m_TextureWidth/pSizeData->m_NumXChars, + pSizeData->m_TextureHeight/pSizeData->m_NumYChars, + CImageInfo::FORMAT_ALPHA, pData); + /* + glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[Texnum]); + glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, + pSizeData->m_TextureWidth/pSizeData->m_NumXChars, + pSizeData->m_TextureHeight/pSizeData->m_NumYChars, + m_FontTextureFormat, GL_UNSIGNED_BYTE, pData);*/ + } + + // 32k of data used for rendering glyphs + unsigned char ms_aGlyphData[(1024/8) * (1024/8)]; + unsigned char ms_aGlyphDataOutlined[(1024/8) * (1024/8)]; + + int GetSlot(CFontSizeData *pSizeData) + { + int CharCount = pSizeData->m_NumXChars*pSizeData->m_NumYChars; + if(pSizeData->m_CurrentCharacter < CharCount) + { + int i = pSizeData->m_CurrentCharacter; + pSizeData->m_CurrentCharacter++; + return i; + } + + // kick out the oldest + // TODO: remove this linear search + { + int Oldest = 0; + for(int i = 1; i < CharCount; i++) + { + 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() && + (pSizeData->m_NumXChars < MAX_CHARACTERS || pSizeData->m_NumYChars < MAX_CHARACTERS)) + { + IncreaseTextureSize(pSizeData); + return GetSlot(pSizeData); + } + + return Oldest; + } + } + + int RenderGlyph(CFont *pFont, CFontSizeData *pSizeData, int Chr) + { + FT_Bitmap *pBitmap; + int SlotID = 0; + int SlotW = pSizeData->m_TextureWidth / pSizeData->m_NumXChars; + int SlotH = pSizeData->m_TextureHeight / pSizeData->m_NumYChars; + int SlotSize = SlotW*SlotH; + int x = 1; + int y = 1; + unsigned int px, py; + + FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize); + + if(FT_Load_Char(pFont->m_FtFace, Chr, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP)) + { + dbg_msg("pFont", "error loading glyph %d", Chr); + return -1; + } + + 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; + y += OutlineThickness; + + // prepare glyph data + mem_zero(ms_aGlyphData, SlotSize); + + if(pBitmap->pixel_mode == FT_PIXEL_MODE_GRAY) // ignore_convention + { + for(py = 0; py < pBitmap->rows; py++) // ignore_convention + for(px = 0; px < pBitmap->width; px++) // ignore_convention + ms_aGlyphData[(py+y)*SlotW+px+x] = pBitmap->buffer[py*pBitmap->pitch+px]; // ignore_convention + } + else if(pBitmap->pixel_mode == FT_PIXEL_MODE_MONO) // 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 + ms_aGlyphData[(py+y)*SlotW+px+x] = 255; + } + } + + if(0) for(py = 0; (int)py < SlotW; py++) + for(px = 0; (int)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); + UploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphDataOutlined); + } + else + { + for(int i = OutlineThickness; i > 0; i-=2) + { + Grow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH); + Grow(ms_aGlyphDataOutlined, ms_aGlyphData, SlotW, SlotH); + } + UploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphData); + } + + // set char info + { + CFontChar *pFontchr = &pSizeData->m_aCharacters[SlotID]; + float Scale = 1.0f/pSizeData->m_FontSize; + float Uscale = 1.0f/pSizeData->m_TextureWidth; + 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; + for(i = 0; i < pSizeData->m_CurrentCharacter; i++) + { + if(pSizeData->m_aCharacters[i].m_ID == Chr) + { + pFontchr = &pSizeData->m_aCharacters[i]; + break; + } + } + + // check if we need to render the character + if(!pFontchr) + { + int Index = RenderGlyph(pFont, pSizeData, Chr); + 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; + } + + // must only be called from the rendering function as the pFont must be set to the correct size + void RenderSetup(CFont *pFont, int size) + { + FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, size); + } + + float Kerning(CFont *pFont, int Left, int Right) + { + FT_Vector Kerning = {0,0}; + FT_Get_Kerning(pFont->m_FtFace, Left, Right, FT_KERNING_DEFAULT, &Kerning); + return (Kerning.x>>6); + } + + +public: + CTextRender() + { + m_pGraphics = 0; + + m_TextR = 1.0f; + m_TextG = 1.0f; + m_TextB = 1.0f; + m_TextA = 1.0f; + m_TextOutlineR = 0.0f; + m_TextOutlineG = 0.0f; + m_TextOutlineB = 0.0f; + m_TextOutlineA = 0.3f; + + m_pDefaultFont = 0; + + // 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); + return NULL; + } + + 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; + }; + + virtual void DestroyFont(CFont *pFont) + { + mem_free(pFont); + } + + virtual void SetDefaultFont(CFont *pFont) + { + 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)); + pCursor->m_FontSize = FontSize; + pCursor->m_StartX = x; + pCursor->m_StartY = y; + pCursor->m_X = x; + pCursor->m_Y = y; + pCursor->m_LineCount = 1; + pCursor->m_LineWidth = -1; + 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; + SetCursor(&Cursor, x, y, Size, TEXTFLAG_RENDER); + Cursor.m_LineWidth = MaxWidth; + TextEx(&Cursor, pText, -1); + } + + virtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length) + { + CTextCursor Cursor; + SetCursor(&Cursor, 0, 0, Size, 0); + TextEx(&Cursor, pText, Length); + return Cursor.m_X; + } + + virtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) + { + CTextCursor Cursor; + SetCursor(&Cursor, 0, 0, Size, 0); + Cursor.m_LineWidth = LineWidth; + TextEx(&Cursor, pText, -1); + return Cursor.m_LineCount; + } + + virtual void TextColor(float r, float g, float b, float a) + { + m_TextR = r; + m_TextG = g; + m_TextB = b; + m_TextA = a; + } + + virtual void TextOutlineColor(float r, float g, float b, float a) + { + m_TextOutlineR = r; + m_TextOutlineG = g; + 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; + float FakeToScreenX, FakeToScreenY; + int ActualX, ActualY; + + int ActualSize; + int i; + int GotNewLine = 0; + float DrawX = 0.0f, DrawY = 0.0f; + int LineCount = 0; + float CursorX, CursorY; + + float Size = pCursor->m_FontSize; + + // 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); + ActualY = (int)(pCursor->m_Y * FakeToScreenY); + + CursorX = ActualX / FakeToScreenX; + CursorY = ActualY / FakeToScreenY; + + // same with size + ActualSize = (int)(Size * FakeToScreenY); + Size = ActualSize / FakeToScreenY; + + // fetch pFont data + if(!pFont) + pFont = m_pDefaultFont; + + if(!pFont) + return; + + pSizeData = GetSize(pFont, ActualSize); + RenderSetup(pFont, ActualSize); + + float Scale = 1/pSizeData->m_FontSize; + + // set length + if(Length < 0) + Length = str_length(pText); + + // if we don't want to render, we can just skip the first outline pass + i = 1; + if(pCursor->m_Flags&TEXTFLAG_RENDER) + i = 0; + + for(;i < 2; i++) + { + const char *pCurrent = (char *)pText; + const char *pEnd = pCurrent+Length; + DrawX = CursorX; + DrawY = CursorY; + LineCount = pCursor->m_LineCount; + + if(pCursor->m_Flags&TEXTFLAG_RENDER) + { + // TODO: Make this better + if (i == 0) + Graphics()->TextureSet(pSizeData->m_aTextures[1]); + else + Graphics()->TextureSet(pSizeData->m_aTextures[0]); + + Graphics()->QuadsBegin(); + if (i == 0) + Graphics()->SetColor(m_TextOutlineR, m_TextOutlineG, m_TextOutlineB, m_TextOutlineA*m_TextA); + else + Graphics()->SetColor(m_TextR, m_TextG, m_TextB, m_TextA); + } + + while(pCurrent < pEnd && (pCursor->m_MaxLines < 1 || LineCount <= pCursor->m_MaxLines)) + { + int NewLine = 0; + const char *pBatchEnd = pEnd; + if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END)) + { + int Wlen = min(WordLength((char *)pCurrent), (int)(pEnd-pCurrent)); + CTextCursor Compare = *pCursor; + Compare.m_X = DrawX; + Compare.m_Y = DrawY; + Compare.m_Flags &= ~TEXTFLAG_RENDER; + Compare.m_LineWidth = -1; + TextEx(&Compare, pCurrent, Wlen); + + if(Compare.m_X-DrawX > pCursor->m_LineWidth) + { + // word can't be fitted in one line, cut it + CTextCursor Cutter = *pCursor; + Cutter.m_CharCount = 0; + Cutter.m_X = DrawX; + 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; + } + else if(Compare.m_X-pCursor->m_StartX > pCursor->m_LineWidth) + { + NewLine = 1; + Wlen = 0; + } + + pBatchEnd = pCurrent + Wlen; + } + + const char *pTmp = pCurrent; + int NextCharacter = str_utf8_decode(&pTmp); + while(pCurrent < pBatchEnd) + { + int Character = NextCharacter; + pCurrent = pTmp; + NextCharacter = str_utf8_decode(&pTmp); + + if(Character == '\n') + { + DrawX = pCursor->m_StartX; + DrawY += Size; + DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign + DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; + ++LineCount; + if(pCursor->m_MaxLines > 0 && LineCount > pCursor->m_MaxLines) + break; + continue; + } + + CFontChar *pChr = GetChar(pFont, pSizeData, Character); + if(pChr) + { + float Advance = pChr->m_AdvanceX + Kerning(pFont, Character, NextCharacter)*Scale; + if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && DrawX+Advance*Size-pCursor->m_StartX > pCursor->m_LineWidth) + { + // we hit the end of the line, no more to render or count + pCurrent = pEnd; + break; + } + + if(pCursor->m_Flags&TEXTFLAG_RENDER) + { + Graphics()->QuadsSetSubset(pChr->m_aUvs[0], pChr->m_aUvs[1], pChr->m_aUvs[2], pChr->m_aUvs[3]); + IGraphics::CQuadItem QuadItem(DrawX+pChr->m_OffsetX*Size, DrawY+pChr->m_OffsetY*Size, pChr->m_Width*Size, pChr->m_Height*Size); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + + DrawX += Advance*Size; + pCursor->m_CharCount++; + } + } + + if(NewLine) + { + DrawX = pCursor->m_StartX; + DrawY += Size; + GotNewLine = 1; + DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign + DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; + ++LineCount; + } + } + + if(pCursor->m_Flags&TEXTFLAG_RENDER) + Graphics()->QuadsEnd(); + } + + pCursor->m_X = DrawX; + pCursor->m_LineCount = LineCount; + + if(GotNewLine) + pCursor->m_Y = DrawY; + } + +}; + +IEngineTextRender *CreateEngineTextRender() { return new CTextRender; } diff --git a/src/engine/client/updater.cpp b/src/engine/client/updater.cpp new file mode 100644 index 0000000..a1518c2 --- /dev/null +++ b/src/engine/client/updater.cpp @@ -0,0 +1,253 @@ +#include "updater.h" +#include <base/system.h> +#include <engine/fetcher.h> +#include <engine/storage.h> +#include <engine/client.h> +#include <engine/external/json-parser/json.h> +#include <game/version.h> + +#include <stdlib.h> // system + +using std::string; +using std::vector; + +CUpdater::CUpdater() +{ + m_pClient = NULL; + m_pStorage = NULL; + m_pFetcher = NULL; + m_State = CLEAN; + m_Percent = 0; +} + +void CUpdater::Init() +{ + m_pClient = Kernel()->RequestInterface<IClient>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + m_pFetcher = Kernel()->RequestInterface<IFetcher>(); + #if defined(CONF_FAMILY_WINDOWS) + m_IsWinXP = os_compare_version(5, 1) <= 0; + #else + m_IsWinXP = false; + #endif +} + +void CUpdater::ProgressCallback(CFetchTask *pTask, void *pUser) +{ + CUpdater *pUpdate = (CUpdater *)pUser; + str_copy(pUpdate->m_Status, pTask->Dest(), sizeof(pUpdate->m_Status)); + pUpdate->m_Percent = pTask->Progress(); +} + +void CUpdater::CompletionCallback(CFetchTask *pTask, void *pUser) +{ + CUpdater *pUpdate = (CUpdater *)pUser; + if(!str_comp(pTask->Dest(), "update.json")) + { + if(pTask->State() == CFetchTask::STATE_DONE) + pUpdate->m_State = GOT_MANIFEST; + else if(pTask->State() == CFetchTask::STATE_ERROR) + pUpdate->m_State = FAIL; + } + else if(!str_comp(pTask->Dest(), pUpdate->m_aLastFile)) + { + if(pTask->State() == CFetchTask::STATE_DONE) + { + if(pUpdate->m_ClientUpdate) + pUpdate->ReplaceClient(); + if(pUpdate->m_ServerUpdate) + pUpdate->ReplaceServer(); + if(pUpdate->m_pClient->State() == IClient::STATE_ONLINE || pUpdate->m_pClient->EditorHasUnsavedData()) + pUpdate->m_State = NEED_RESTART; + else{ + if(!pUpdate->m_IsWinXP) + pUpdate->m_pClient->Restart(); + else + pUpdate->WinXpRestart(); + } + } + else if(pTask->State() == CFetchTask::STATE_ERROR) + pUpdate->m_State = FAIL; + } + delete pTask; +} + +void CUpdater::FetchFile(const char *pFile, const char *pDestPath) +{ + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "https://%s/%s", g_Config.m_ClDDNetUpdateServer, pFile); + if(!pDestPath) + pDestPath = pFile; + CFetchTask *Task = new CFetchTask(false); + m_pFetcher->QueueAdd(Task, aBuf, pDestPath, -2, this, &CUpdater::CompletionCallback, &CUpdater::ProgressCallback); +} + +void CUpdater::Update() +{ + switch(m_State) + { + case GOT_MANIFEST: + PerformUpdate(); + default: + return; + } +} + +void CUpdater::AddNewFile(const char *pFile) +{ + //Check if already on the download list + for(vector<string>::iterator it = m_AddedFiles.begin(); it < m_AddedFiles.end(); ++it) + { + if(!str_comp(it->c_str(), pFile)) + return; + } + m_AddedFiles.push_back(string(pFile)); +} + +void CUpdater::AddRemovedFile(const char *pFile) +{ + //First remove from to be downloaded list + for(vector<string>::iterator it = m_AddedFiles.begin(); it < m_AddedFiles.end(); ++it) + { + if(!str_comp(it->c_str(), pFile)){ + m_AddedFiles.erase(it); + break; + } + } + m_RemovedFiles.push_back(string(pFile)); +} + +void CUpdater::ReplaceClient() +{ + dbg_msg("updater", "Replacing " PLAT_CLIENT_EXEC); + + //Replace running executable by renaming twice... + if(!m_IsWinXP) + { + m_pStorage->RemoveBinaryFile("DDNet.old"); + m_pStorage->RenameBinaryFile(PLAT_CLIENT_EXEC, "DDNet.old"); + m_pStorage->RenameBinaryFile("DDNet.tmp", PLAT_CLIENT_EXEC); + } + #if !defined(CONF_FAMILY_WINDOWS) + char aPath[512]; + m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, aPath, sizeof aPath); + char aBuf[512]; + str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); + if (system(aBuf)) + dbg_msg("updater", "Error setting client executable bit"); + #endif +} + +void CUpdater::ReplaceServer() +{ + dbg_msg("updater", "Replacing " PLAT_SERVER_EXEC); + + //Replace running executable by renaming twice... + m_pStorage->RemoveBinaryFile("DDNet-Server.old"); + m_pStorage->RenameBinaryFile(PLAT_SERVER_EXEC, "DDNet-Server.old"); + m_pStorage->RenameBinaryFile("DDNet-Server.tmp", PLAT_SERVER_EXEC); + #if !defined(CONF_FAMILY_WINDOWS) + char aPath[512]; + m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, aPath, sizeof aPath); + char aBuf[512]; + str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath); + if (system(aBuf)) + dbg_msg("updater", "Error setting server executable bit"); + #endif +} + +void CUpdater::ParseUpdate() +{ + char aPath[512]; + IOHANDLE File = m_pStorage->OpenFile(m_pStorage->GetBinaryPath("update.json", aPath, sizeof aPath), IOFLAG_READ, IStorage::TYPE_ALL); + if(File) + { + char aBuf[4096*4]; + mem_zero(aBuf, sizeof (aBuf)); + io_read(File, aBuf, sizeof(aBuf)); + io_close(File); + + json_value *pVersions = json_parse(aBuf); + + if(pVersions && pVersions->type == json_array) + { + for(int i = 0; i < json_array_length(pVersions); i++) + { + const json_value *pTemp; + const json_value *pCurrent = json_array_get(pVersions, i); + if(str_comp(json_string_get(json_object_get(pCurrent, "version")), GAME_RELEASE_VERSION)) + { + if(json_boolean_get(json_object_get(pCurrent, "client"))) + m_ClientUpdate = true; + if(json_boolean_get(json_object_get(pCurrent, "server"))) + m_ServerUpdate = true; + if((pTemp = json_object_get(pCurrent, "download"))->type == json_array) + { + for(int j = 0; j < json_array_length(pTemp); j++) + AddNewFile(json_string_get(json_array_get(pTemp, j))); + } + if((pTemp = json_object_get(pCurrent, "remove"))->type == json_array) + { + for(int j = 0; j < json_array_length(pTemp); j++) + AddRemovedFile(json_string_get(json_array_get(pTemp, j))); + } + } + else + break; + } + } + } +} + +void CUpdater::InitiateUpdate() +{ + m_State = GETTING_MANIFEST; + FetchFile("update.json"); +} + +void CUpdater::PerformUpdate() +{ + m_State = PARSING_UPDATE; + dbg_msg("updater", "Parsing update.json"); + ParseUpdate(); + m_State = DOWNLOADING; + + const char *aLastFile; + if(m_ClientUpdate) + aLastFile = "DDNet.tmp"; + else if(!m_AddedFiles.empty()) + aLastFile= m_AddedFiles.front().c_str(); + else + aLastFile = ""; + + str_copy(m_aLastFile, aLastFile, sizeof(m_aLastFile)); + + while(!m_AddedFiles.empty()) + { + FetchFile(m_AddedFiles.back().c_str()); + m_AddedFiles.pop_back(); + } + while(!m_RemovedFiles.empty()) + { + m_pStorage->RemoveBinaryFile(m_RemovedFiles.back().c_str()); + m_RemovedFiles.pop_back(); + } + if(m_ServerUpdate) + FetchFile(PLAT_SERVER_DOWN, "DDNet-Server.tmp"); + if(m_ClientUpdate) + FetchFile(PLAT_CLIENT_DOWN, "DDNet.tmp"); +} + +void CUpdater::WinXpRestart() +{ + char aBuf[512]; + IOHANDLE bhFile = io_open(m_pStorage->GetBinaryPath("du.bat", aBuf, sizeof aBuf), IOFLAG_WRITE); + if(!bhFile) + return; + char bBuf[512]; + str_format(bBuf, sizeof(bBuf), ":_R\r\ndel \"DDNet.exe\"\r\nif exist \"DDNet.exe\" goto _R\r\nrename \"DDNet.tmp\" \"DDNet.exe\"\r\n:_T\r\nif not exist \"DDNet.exe\" goto _T\r\nstart DDNet.exe\r\ndel \"du.bat\"\r\n"); + io_write(bhFile, bBuf, str_length(bBuf)); + io_close(bhFile); + shell_execute(aBuf); + m_pClient->Quit(); +} diff --git a/src/engine/client/updater.h b/src/engine/client/updater.h new file mode 100644 index 0000000..7748aff --- /dev/null +++ b/src/engine/client/updater.h @@ -0,0 +1,79 @@ +#ifndef ENGINE_CLIENT_UPDATER_H +#define ENGINE_CLIENT_UPDATER_H + +#include <engine/updater.h> +#include <engine/fetcher.h> +#include <vector> +#include <string> + +#define CLIENT_EXEC "DDNet" +#define SERVER_EXEC "DDNet-Server" + +#if defined(CONF_FAMILY_WINDOWS) + #define PLAT_EXT ".exe" + #define PLAT_NAME CONF_PLATFORM_STRING +#elif defined(CONF_FAMILY_UNIX) + #define PLAT_EXT "" + #if defined(CONF_ARCH_IA32) + #define PLAT_NAME CONF_PLATFORM_STRING "-x86" + #elif defined(CONF_ARCH_AMD64) + #define PLAT_NAME CONF_PLATFORM_STRING "-x86_64" + #else + #define PLAT_NAME CONF_PLATFORM_STRING "-unsupported" + #endif +#else + #define PLAT_EXT "" + #define PLAT_NAME "unsupported-unsupported" +#endif + +#define PLAT_CLIENT_DOWN CLIENT_EXEC "-" PLAT_NAME PLAT_EXT +#define PLAT_SERVER_DOWN SERVER_EXEC "-" PLAT_NAME PLAT_EXT + +#define PLAT_CLIENT_EXEC CLIENT_EXEC PLAT_EXT +#define PLAT_SERVER_EXEC SERVER_EXEC PLAT_EXT + +class CUpdater : public IUpdater +{ + class IClient *m_pClient; + class IStorage *m_pStorage; + class IFetcher *m_pFetcher; + + bool m_IsWinXP; + + int m_State; + char m_Status[256]; + int m_Percent; + char m_aLastFile[256]; + + bool m_ClientUpdate; + bool m_ServerUpdate; + + std::vector<std::string> m_AddedFiles; + std::vector<std::string> m_RemovedFiles; + + void AddNewFile(const char *pFile); + void AddRemovedFile(const char *pFile); + void FetchFile(const char *pFile, const char *pDestPath = 0); + + void ParseUpdate(); + void PerformUpdate(); + + void ReplaceClient(); + void ReplaceServer(); + +public: + CUpdater(); + static void ProgressCallback(CFetchTask *pTask, void *pUser); + static void CompletionCallback(CFetchTask *pTask, void *pUser); + + int GetCurrentState() { return m_State; }; + char *GetCurrentFile() { return m_Status; }; + int GetCurrentPercent() { return m_Percent; }; + + virtual void InitiateUpdate(); + void Init(); + virtual void Update(); + void WinXpRestart(); +}; + +#endif diff --git a/src/engine/config.h b/src/engine/config.h new file mode 100644 index 0000000..76860e2 --- /dev/null +++ b/src/engine/config.h @@ -0,0 +1,25 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CONFIG_H +#define ENGINE_CONFIG_H + +#include "kernel.h" + +class IConfig : public IInterface +{ + MACRO_INTERFACE("config", 0) +public: + typedef void (*SAVECALLBACKFUNC)(IConfig *pConfig, void *pUserData); + + virtual void Init() = 0; + virtual void Reset() = 0; + virtual void Save() = 0; + + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) = 0; + + virtual void WriteLine(const char *pLine) = 0; +}; + +extern IConfig *CreateConfig(); + +#endif diff --git a/src/engine/console.h b/src/engine/console.h new file mode 100644 index 0000000..e1d7ac0 --- /dev/null +++ b/src/engine/console.h @@ -0,0 +1,111 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_CONSOLE_H +#define ENGINE_CONSOLE_H + +#include "kernel.h" + +class IConsole : public IInterface +{ + MACRO_INTERFACE("console", 0) +public: + + // TODO: rework/cleanup + enum + { + OUTPUT_LEVEL_STANDARD=0, + OUTPUT_LEVEL_ADDINFO, + OUTPUT_LEVEL_DEBUG, + + ACCESS_LEVEL_ADMIN=0, + ACCESS_LEVEL_MOD, + ACCESS_LEVEL_HELPER, + ACCESS_LEVEL_USER, + + TEMPCMD_NAME_LENGTH=32, + TEMPCMD_HELP_LENGTH=96, + TEMPCMD_PARAMS_LENGTH=96, + + MAX_PRINT_CB=4, + + CLIENT_ID_GAME=-2, + CLIENT_ID_NO_GAME=-3, + }; + + // TODO: rework this interface to reduce the amount of virtual calls + class IResult + { + protected: + unsigned m_NumArgs; + 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; } + int m_ClientID; + + // DDRace + + virtual int GetVictim() = 0; + }; + + class CCommandInfo + { + protected: + int m_AccessLevel; + public: + CCommandInfo() { m_AccessLevel = ACCESS_LEVEL_ADMIN; } + virtual ~CCommandInfo() {} + const char *m_pName; + const char *m_pHelp; + const char *m_pParams; + + virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const = 0; + + int GetAccessLevel() const { return m_AccessLevel; } + }; + + typedef void (*FPrintCallback)(const char *pStr, void *pUser, bool Highlighted); + typedef void (*FPossibleCallback)(const char *pCmd, void *pUser); + typedef void (*FCommandCallback)(IResult *pResult, void *pUserData); + typedef void (*FChainCommandCallback)(IResult *pResult, void *pUserData, FCommandCallback pfnCallback, void *pCallbackUserData); + + virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int Flagmask) const = 0; + virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp) = 0; + virtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) = 0; + virtual void ParseArguments(int NumArgs, const char **ppArguments) = 0; + + virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) = 0; + virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) = 0; + virtual void DeregisterTemp(const char *pName) = 0; + virtual void DeregisterTempAll() = 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, int ClientID = -1) = 0; + virtual void ExecuteLineFlag(const char *Sptr, int FlasgMask, int ClientID = -1) = 0; + virtual void ExecuteLineStroked(int Stroke, const char *pStr, int ClientID = -1) = 0; + virtual void ExecuteFile(const char *pFilename, int ClientID = -1) = 0; + + virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) = 0; + virtual void SetPrintOutputLevel(int Index, int OutputLevel) = 0; + virtual void Print(int Level, const char *pFrom, const char *pStr, bool Highlighted = false) = 0; + + virtual void SetAccessLevel(int AccessLevel) = 0; + + virtual void ResetServerGameSettings() = 0; + + // DDRace + + bool m_Cheated; + virtual void SetFlagMask(int FlagMask) = 0; +}; + +extern IConsole *CreateConsole(int FlagMask); + +#endif // FILE_ENGINE_CONSOLE_H diff --git a/src/engine/demo.h b/src/engine/demo.h new file mode 100644 index 0000000..3957268 --- /dev/null +++ b/src/engine/demo.h @@ -0,0 +1,87 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_DEMO_H +#define ENGINE_DEMO_H + +#include "kernel.h" + +enum +{ + MAX_TIMELINE_MARKERS=64 +}; + +struct CDemoHeader +{ + unsigned char m_aMarker[7]; + unsigned char m_Version; + char m_aNetversion[64]; + char m_aMapName[64]; + unsigned char m_aMapSize[4]; + unsigned char m_aMapCrc[4]; + char m_aType[8]; + char m_aLength[4]; + char m_aTimestamp[20]; +}; + +struct CTimelineMarkers +{ + char m_aNumTimelineMarkers[4]; + char m_aTimelineMarkers[MAX_TIMELINE_MARKERS][4]; +}; + +class IDemoPlayer : public IInterface +{ + MACRO_INTERFACE("demoplayer", 0) +public: + class CInfo + { + public: + bool m_Paused; + float m_Speed; + + int m_FirstTick; + int m_CurrentTick; + int m_LastTick; + + int m_NumTimelineMarkers; + int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; + }; + + enum + { + DEMOTYPE_INVALID=0, + DEMOTYPE_CLIENT, + DEMOTYPE_SERVER, + }; + + ~IDemoPlayer() {} + virtual void SetSpeed(float Speed) = 0; + virtual int SetPos(float Percent) = 0; + virtual void Pause() = 0; + virtual void Unpause() = 0; + virtual bool IsPlaying() const = 0; + virtual const CInfo *BaseInfo() const = 0; + virtual void GetDemoName(char *pBuffer, int BufferSize) const = 0; + virtual bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const = 0; + virtual int GetDemoType() const = 0; +}; + +class IDemoRecorder : public IInterface +{ + MACRO_INTERFACE("demorecorder", 0) +public: + ~IDemoRecorder() {} + virtual bool IsRecording() const = 0; + virtual int Stop(bool Finalize = false) = 0; + virtual int Length() const = 0; +}; + +class IDemoEditor : public IInterface +{ + MACRO_INTERFACE("demoeditor", 0) +public: + + virtual void Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick) = 0; +}; + +#endif diff --git a/src/engine/docs/client_time.txt b/src/engine/docs/client_time.txt new file mode 100644 index 0000000..0d4dd53 --- /dev/null +++ b/src/engine/docs/client_time.txt @@ -0,0 +1,11 @@ +Title: Time on the client + +tick, intratick +predtick, predintratick + + prevtick tick predtick + 4 8 14 + |---------------------|---------------------| + 0 <- intratick -> 1 + 0 <- ticktime(in s)-> X + 0 <- predintratick?-> 1 diff --git a/src/engine/docs/prediction.txt b/src/engine/docs/prediction.txt new file mode 100644 index 0000000..e740b1e --- /dev/null +++ b/src/engine/docs/prediction.txt @@ -0,0 +1,19 @@ +Title: Prediction + +The engine calls <modc_predict> when reprediction is required. This happens usally when new data has arrived from the server. <modc_predict> should to prediction from the current snapshot and current snapshot tick (<client_tick> + 1) upto and including the tick returned by <client_predtick>. + +Predicted input sent to the server can be retrived by calling <client_get_input> with the corresponding tick that you want the input for. Here is a simple example of how it might look. + +> void modc_predict() +> { +> int tick; +> prediction_reset(); +> +> for(tick = client_tick()+1; tick <= client_predtick(); tick++) +> { +> MY_INPUT *input = (MY_INPUT *)client_get_input(); +> if(input) +> prediction_apply_input(input); +> prediction_tick(); +> } +> } diff --git a/src/engine/docs/server_op.txt b/src/engine/docs/server_op.txt new file mode 100644 index 0000000..c0a054c --- /dev/null +++ b/src/engine/docs/server_op.txt @@ -0,0 +1,39 @@ +Title: Server Operation + +Section: Init + +Section: Running + +Here is an graph over how the server operates on each refresh. + +(start code) +load map +init mod + +while running + if map change then + load new map + shutdown mod <mods_shutdown> + reset clients to init state + init mod <mods_init> + end if + + if new tick then + call <mods_tick> + for each client do + create snapshot <mods_snap> + send snapshot + end for + end + + process new network messages +end while + +unload map +(end) + + + +Section: Reinit + +Section: Shutdown diff --git a/src/engine/docs/snapshots.txt b/src/engine/docs/snapshots.txt new file mode 100644 index 0000000..b1845b8 --- /dev/null +++ b/src/engine/docs/snapshots.txt @@ -0,0 +1,57 @@ +Title: Snapshots + +Section: Overview + +Topic: Definitions + +- *Snapshot*. A is a serialized game state from which a client can render the game from. They are sent from the server at a regular interval and is created specificly for each client in order to reduce bandwidth. +- *Delta Snapshot*. A set of data that can be applied to a snapshot in order to create a new snapshot with the updated game state. + +Topic: Structure + +A snapshot contains a series of items. Each item have a type, id and data. + +- *Type*. Type of item. Could be projectile or character for example. +- *Id*. A unique id so the client can identify the item between two snapshots. +- *Data*. A series of 32-bit integers that contains the per item type specific data. + +Section: Server Side + +Topic: Creating + +Items can be added when <mods_snap> is called using the <snap_new_item> function to insert an item to the snapshot. The server can not inspect the snapshot that is in progress of being created. + +Section: Client Side + +Topic: Inspection +<modc_newsnapshot> is called when a new snapshot has arrived for processing. <snap_num_items>, <snap_get_item> and <snap_find_item> can be used to inspect the current and previous snapshot. This can be done anywhere while the client is running and not just in the <modc_newsnapshot> function. The client can also call <snap_invalidate_item> if an item contains improper information that could harm the operation of the client. This should however be done in <modc_newsnapshot> to assure that no bad data propagates into the rest of the client. + +Topic: Rendering +DOCTODO + +Section: In depth + +Topic: Compression + +After a snapshot have been created, compression is applyed to reduce the bandwidth. There are several steps taken inorder to reduce the size of the size of the snapshot. + +- *Delta*. The server looks in a clients backlog of snapshots to find a previous acked snapshot. It then compares the two snapshots and creates a delta snapshot containing the changes from the previous acked snapshot to the new one. +- *Variable Integers*. The delta snapshot which is only consisting of 32-bit integers is then encoded into variable integers similar to UTF-8. Each byte has a bit that tells the decoder that it needs one more byte to decode the 32-bit integer. The first byte also contains a bit for telling the sign of the integer. + +> ESDDDDDD EDDDDDDD EDDDDDDD EDDDDDDD + +> E = extend +> S = sign +> D = data bit + +- *Huffman*. The last step is to compress the buffer with a huffman encoder. It uses a static tree that is weighted towards 0 because it's where most of the data will be because of the delta compression. + +Topic: Interval + +The interval for how often a client recives a snapshot changes during the course of the connection. There are three different snapshot rates. + +- *Init*. 5 snapshots per second. Used when a client is connecting and used until the client has acknowlaged a snapshot. This mechanism is used because the first snapshot because no delta compression can be done. + +- *Full*. Snapshot for every tick or every even tick depending on server configuration. This is used during normal gameplay and everything is running smooth. + +- *Recovery*. 1 snapshot each second. A client enters recovery rate when it havn't acknowlaged a snapshot over 1 second. This is to let the client to beable to recover if it has a slow connection. diff --git a/src/engine/editor.h b/src/engine/editor.h new file mode 100644 index 0000000..1cafea0 --- /dev/null +++ b/src/engine/editor.h @@ -0,0 +1,19 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_EDITOR_H +#define ENGINE_EDITOR_H +#include "kernel.h" + +class IEditor : public IInterface +{ + MACRO_INTERFACE("editor", 0) +public: + + virtual ~IEditor() {} + virtual void Init() = 0; + virtual void UpdateAndRender() = 0; + virtual bool HasUnsavedData() = 0; +}; + +extern IEditor *CreateEditor(); +#endif diff --git a/src/engine/engine.h b/src/engine/engine.h new file mode 100644 index 0000000..f4b6864 --- /dev/null +++ b/src/engine/engine.h @@ -0,0 +1,34 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_ENGINE_H +#define ENGINE_ENGINE_H + +#include "kernel.h" +#include <engine/shared/jobs.h> + +class CHostLookup +{ +public: + CJob m_Job; + char m_aHostname[128]; + int m_Nettype; + NETADDR m_Addr; +}; + +class IEngine : public IInterface +{ + MACRO_INTERFACE("engine", 0) + +protected: + class CJobPool m_JobPool; + +public: + virtual void Init() = 0; + virtual void InitLogfile() = 0; + virtual void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) = 0; + virtual void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) = 0; +}; + +extern IEngine *CreateEngine(const char *pAppname); + +#endif diff --git a/src/engine/external/important.txt b/src/engine/external/important.txt new file mode 100644 index 0000000..305ccad --- /dev/null +++ b/src/engine/external/important.txt @@ -0,0 +1,5 @@ +The source code under this directory are external libraries +with their own licences. The source you find here is stripped +of unnessesary information. Please visit their websites for +more information and official releases. + diff --git a/src/engine/external/json-parser/json.c b/src/engine/external/json-parser/json.c new file mode 100644 index 0000000..6637c2d --- /dev/null +++ b/src/engine/external/json-parser/json.c @@ -0,0 +1,866 @@ + +/* vim: set et ts=3 sw=3 ft=c: + * + * Copyright (C) 2012 James McLaughlin et al. All rights reserved. + * https://github.com/udp/json-parser + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "json.h" + +#ifdef _MSC_VER + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif +#endif + +#ifdef __cplusplus + const struct _json_value json_value_none; /* zero-d by ctor */ +#else + const struct _json_value json_value_none = { 0 }; +#endif + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <ctype.h> +#include <math.h> + +typedef unsigned short json_uchar; + +static unsigned char hex_value (json_char c) +{ + if (c >= 'A' && c <= 'F') + return (c - 'A') + 10; + + if (c >= 'a' && c <= 'f') + return (c - 'a') + 10; + + if (c >= '0' && c <= '9') + return c - '0'; + + return 0xFF; +} + +typedef struct +{ + json_settings settings; + int first_pass; + + unsigned long used_memory; + + unsigned int uint_max; + unsigned long ulong_max; + +} json_state; + +static void * json_alloc (json_state * state, unsigned long size, int zero) +{ + void * mem; + + if ((state->ulong_max - state->used_memory) < size) + return 0; + + if (state->settings.max_memory + && (state->used_memory += size) > state->settings.max_memory) + { + return 0; + } + + if (! (mem = zero ? calloc (size, 1) : malloc (size))) + return 0; + + return mem; +} + +static int new_value + (json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type) +{ + json_value * value; + int values_size; + + if (!state->first_pass) + { + value = *top = *alloc; + *alloc = (*alloc)->_reserved.next_alloc; + + if (!*root) + *root = value; + + switch (value->type) + { + case json_array: + + if (! (value->u.array.values = (json_value **) json_alloc + (state, value->u.array.length * sizeof (json_value *), 0)) ) + { + return 0; + } + + value->u.array.length = 0; + break; + + case json_object: + + values_size = sizeof (*value->u.object.values) * value->u.object.length; + + if (! ((*(void **) &value->u.object.values) = json_alloc + (state, values_size + ((unsigned long) value->u.object.values), 0)) ) + { + return 0; + } + + value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size; + + value->u.object.length = 0; + break; + + case json_string: + + if (! (value->u.string.ptr = (json_char *) json_alloc + (state, (value->u.string.length + 1) * sizeof (json_char), 0)) ) + { + return 0; + } + + value->u.string.length = 0; + break; + + default: + break; + }; + + return 1; + } + + value = (json_value *) json_alloc (state, sizeof (json_value), 1); + + if (!value) + return 0; + + if (!*root) + *root = value; + + value->type = type; + value->parent = *top; + + if (*alloc) + (*alloc)->_reserved.next_alloc = value; + + *alloc = *top = value; + + return 1; +} + +#define e_off \ + ((int) (i - cur_line_begin)) + +#define whitespace \ + case '\n': ++ cur_line; cur_line_begin = i; \ + case ' ': case '\t': case '\r' + +#define string_add(b) \ + do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0); + +const static long + flag_next = 1, flag_reproc = 2, flag_need_comma = 4, flag_seek_value = 8, + flag_escaped = 16, flag_string = 32, flag_need_colon = 64, flag_done = 128, + flag_num_negative = 256, flag_num_zero = 512, flag_num_e = 1024, + flag_num_e_got_sign = 2048, flag_num_e_negative = 4096; + +json_value * json_parse_ex (json_settings * settings, const json_char * json, char * error_buf) +{ + json_char error [128]; + unsigned int cur_line; + const json_char * cur_line_begin, * i; + json_value * top, * root, * alloc = 0; + json_state state; + long flags; + long num_digits, num_fraction, num_e; + + error[0] = '\0'; + num_digits = num_fraction = num_e = 0; + + memset (&state, 0, sizeof (json_state)); + memcpy (&state.settings, settings, sizeof (json_settings)); + + memset (&state.uint_max, 0xFF, sizeof (state.uint_max)); + memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max)); + + state.uint_max -= 8; /* limit of how much can be added before next check */ + state.ulong_max -= 8; + + for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass) + { + json_uchar uchar; + unsigned char uc_b1, uc_b2, uc_b3, uc_b4; + json_char * string; + unsigned int string_length; + + top = root = 0; + flags = flag_seek_value; + string_length = 0; + string = 0; + + cur_line = 1; + cur_line_begin = json; + + for (i = json ;; ++ i) + { + json_char b = *i; + + if (flags & flag_done) + { + if (!b) + break; + + switch (b) + { + whitespace: + continue; + + default: + sprintf (error, "%d:%d: Trailing garbage: `%c`", cur_line, e_off, b); + goto e_failed; + }; + } + + if (flags & flag_string) + { + if (!b) + { sprintf (error, "Unexpected EOF in string (at %d:%d)", cur_line, e_off); + goto e_failed; + } + + if (string_length > state.uint_max) + goto e_overflow; + + if (flags & flag_escaped) + { + flags &= ~ flag_escaped; + + switch (b) + { + case 'b': string_add ('\b'); break; + case 'f': string_add ('\f'); break; + case 'n': string_add ('\n'); break; + case 'r': string_add ('\r'); break; + case 't': string_add ('\t'); break; + case 'u': + + if ((uc_b1 = hex_value (*++ i)) == 0xFF || (uc_b2 = hex_value (*++ i)) == 0xFF + || (uc_b3 = hex_value (*++ i)) == 0xFF || (uc_b4 = hex_value (*++ i)) == 0xFF) + { + sprintf (error, "Invalid character value `%c` (at %d:%d)", b, cur_line, e_off); + goto e_failed; + } + + uc_b1 = uc_b1 * 16 + uc_b2; + uc_b2 = uc_b3 * 16 + uc_b4; + + uchar = ((json_char) uc_b1) * 256 + uc_b2; + + if (sizeof (json_char) >= sizeof (json_uchar) || (uc_b1 == 0 && uc_b2 <= 0x7F)) + { + string_add ((json_char) uchar); + break; + } + + if (uchar <= 0x7FF) + { + if (state.first_pass) + string_length += 2; + else + { string [string_length ++] = 0xC0 | ((uc_b2 & 0xC0) >> 6) | ((uc_b1 & 0x7) << 2); + string [string_length ++] = 0x80 | (uc_b2 & 0x3F); + } + + break; + } + + if (state.first_pass) + string_length += 3; + else + { string [string_length ++] = 0xE0 | ((uc_b1 & 0xF0) >> 4); + string [string_length ++] = 0x80 | ((uc_b1 & 0xF) << 2) | ((uc_b2 & 0xC0) >> 6); + string [string_length ++] = 0x80 | (uc_b2 & 0x3F); + } + + break; + + default: + string_add (b); + }; + + continue; + } + + if (b == '\\') + { + flags |= flag_escaped; + continue; + } + + if (b == '"') + { + if (!state.first_pass) + string [string_length] = 0; + + flags &= ~ flag_string; + string = 0; + + switch (top->type) + { + case json_string: + + top->u.string.length = string_length; + flags |= flag_next; + + break; + + case json_object: + + if (state.first_pass) + (*(json_char **) &top->u.object.values) += string_length + 1; + else + { + top->u.object.values [top->u.object.length].name + = (json_char *) top->_reserved.object_mem; + + (*(json_char **) &top->_reserved.object_mem) += string_length + 1; + } + + flags |= flag_seek_value | flag_need_colon; + continue; + + default: + break; + }; + } + else + { + string_add (b); + continue; + } + } + + if (flags & flag_seek_value) + { + switch (b) + { + whitespace: + continue; + + case ']': + + if (top->type == json_array) + flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next; + else if (!state.settings.settings & json_relaxed_commas) + { sprintf (error, "%d:%d: Unexpected ]", cur_line, e_off); + goto e_failed; + } + + break; + + default: + + if (flags & flag_need_comma) + { + if (b == ',') + { flags &= ~ flag_need_comma; + continue; + } + else + { sprintf (error, "%d:%d: Expected , before %c", cur_line, e_off, b); + goto e_failed; + } + } + + if (flags & flag_need_colon) + { + if (b == ':') + { flags &= ~ flag_need_colon; + continue; + } + else + { sprintf (error, "%d:%d: Expected : before %c", cur_line, e_off, b); + goto e_failed; + } + } + + flags &= ~ flag_seek_value; + + switch (b) + { + case '{': + + if (!new_value (&state, &top, &root, &alloc, json_object)) + goto e_alloc_failure; + + continue; + + case '[': + + if (!new_value (&state, &top, &root, &alloc, json_array)) + goto e_alloc_failure; + + flags |= flag_seek_value; + continue; + + case '"': + + if (!new_value (&state, &top, &root, &alloc, json_string)) + goto e_alloc_failure; + + flags |= flag_string; + + string = top->u.string.ptr; + string_length = 0; + + continue; + + case 't': + + if (*(++ i) != 'r' || *(++ i) != 'u' || *(++ i) != 'e') + goto e_unknown_value; + + if (!new_value (&state, &top, &root, &alloc, json_boolean)) + goto e_alloc_failure; + + top->u.boolean = 1; + + flags |= flag_next; + break; + + case 'f': + + if (*(++ i) != 'a' || *(++ i) != 'l' || *(++ i) != 's' || *(++ i) != 'e') + goto e_unknown_value; + + if (!new_value (&state, &top, &root, &alloc, json_boolean)) + goto e_alloc_failure; + + flags |= flag_next; + break; + + case 'n': + + if (*(++ i) != 'u' || *(++ i) != 'l' || *(++ i) != 'l') + goto e_unknown_value; + + if (!new_value (&state, &top, &root, &alloc, json_null)) + goto e_alloc_failure; + + flags |= flag_next; + break; + + default: + + if (isdigit (b) || b == '-') + { + if (!new_value (&state, &top, &root, &alloc, json_integer)) + goto e_alloc_failure; + + if (!state.first_pass) + { + while (isdigit (b) || b == '+' || b == '-' + || b == 'e' || b == 'E' || b == '.') + { + b = *++ i; + } + + flags |= flag_next | flag_reproc; + break; + } + + flags &= ~ (flag_num_negative | flag_num_e | + flag_num_e_got_sign | flag_num_e_negative | + flag_num_zero); + + num_digits = 0; + num_fraction = 0; + num_e = 0; + + if (b != '-') + { + flags |= flag_reproc; + break; + } + + flags |= flag_num_negative; + continue; + } + else + { sprintf (error, "%d:%d: Unexpected %c when seeking value", cur_line, e_off, b); + goto e_failed; + } + }; + }; + } + else + { + switch (top->type) + { + case json_object: + + switch (b) + { + whitespace: + continue; + + case '"': + + if (flags & flag_need_comma && (!state.settings.settings & json_relaxed_commas)) + { + sprintf (error, "%d:%d: Expected , before \"", cur_line, e_off); + goto e_failed; + } + + flags |= flag_string; + + string = (json_char *) top->_reserved.object_mem; + string_length = 0; + + break; + + case '}': + + flags = (flags & ~ flag_need_comma) | flag_next; + break; + + case ',': + + if (flags & flag_need_comma) + { + flags &= ~ flag_need_comma; + break; + } + + default: + + sprintf (error, "%d:%d: Unexpected `%c` in object", cur_line, e_off, b); + goto e_failed; + }; + + break; + + case json_integer: + case json_double: + + if (isdigit (b)) + { + ++ num_digits; + + if (top->type == json_integer || flags & flag_num_e) + { + if (! (flags & flag_num_e)) + { + if (flags & flag_num_zero) + { sprintf (error, "%d:%d: Unexpected `0` before `%c`", cur_line, e_off, b); + goto e_failed; + } + + if (num_digits == 1 && b == '0') + flags |= flag_num_zero; + } + else + { + flags |= flag_num_e_got_sign; + num_e = (num_e * 10) + (b - '0'); + continue; + } + + top->u.integer = (top->u.integer * 10) + (b - '0'); + continue; + } + + num_fraction = (num_fraction * 10) + (b - '0'); + continue; + } + + if (b == '+' || b == '-') + { + if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign)) + { + flags |= flag_num_e_got_sign; + + if (b == '-') + flags |= flag_num_e_negative; + + continue; + } + } + else if (b == '.' && top->type == json_integer) + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit before `.`", cur_line, e_off); + goto e_failed; + } + + top->type = json_double; + top->u.dbl = top->u.integer; + + num_digits = 0; + continue; + } + + if (! (flags & flag_num_e)) + { + if (top->type == json_double) + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit after `.`", cur_line, e_off); + goto e_failed; + } + + top->u.dbl += ((double) num_fraction) / (pow (10.0, num_digits)); + } + + if (b == 'e' || b == 'E') + { + flags |= flag_num_e; + + if (top->type == json_integer) + { + top->type = json_double; + top->u.dbl = top->u.integer; + } + + num_digits = 0; + flags &= ~ flag_num_zero; + + continue; + } + } + else + { + if (!num_digits) + { sprintf (error, "%d:%d: Expected digit after `e`", cur_line, e_off); + goto e_failed; + } + + top->u.dbl *= pow (10.0, flags & flag_num_e_negative ? - num_e : num_e); + } + + if (flags & flag_num_negative) + { + if (top->type == json_integer) + top->u.integer = - top->u.integer; + else + top->u.dbl = - top->u.dbl; + } + + flags |= flag_next | flag_reproc; + break; + + default: + break; + }; + } + + if (flags & flag_reproc) + { + flags &= ~ flag_reproc; + -- i; + } + + if (flags & flag_next) + { + flags = (flags & ~ flag_next) | flag_need_comma; + + if (!top->parent) + { + /* root value done */ + + flags |= flag_done; + continue; + } + + if (top->parent->type == json_array) + flags |= flag_seek_value; + + if (!state.first_pass) + { + json_value * parent = top->parent; + + switch (parent->type) + { + case json_object: + + parent->u.object.values + [parent->u.object.length].value = top; + + break; + + case json_array: + + parent->u.array.values + [parent->u.array.length] = top; + + break; + + default: + break; + }; + } + + if ( (++ top->parent->u.array.length) > state.uint_max) + goto e_overflow; + + top = top->parent; + + continue; + } + } + + alloc = root; + } + + return root; + +e_unknown_value: + + sprintf (error, "%d:%d: Unknown value", cur_line, e_off); + goto e_failed; + +e_alloc_failure: + + strcpy (error, "Memory allocation failure"); + goto e_failed; + +e_overflow: + + sprintf (error, "%d:%d: Too long (caught overflow)", cur_line, e_off); + goto e_failed; + +e_failed: + + if (error_buf) + { + if (*error) + strcpy (error_buf, error); + else + strcpy (error_buf, "Unknown error"); + } + + if (state.first_pass) + alloc = root; + + while (alloc) + { + top = alloc->_reserved.next_alloc; + free (alloc); + alloc = top; + } + + if (!state.first_pass) + json_value_free (root); + + return 0; +} + +json_value * json_parse (const json_char * json) +{ + json_settings settings; + memset (&settings, 0, sizeof (json_settings)); + + return json_parse_ex (&settings, json, 0); +} + +void json_value_free (json_value * value) +{ + json_value * cur_value; + + if (!value) + return; + + value->parent = 0; + + while (value) + { + switch (value->type) + { + case json_array: + + if (!value->u.array.length) + { + free (value->u.array.values); + break; + } + + value = value->u.array.values [-- value->u.array.length]; + continue; + + case json_object: + + if (!value->u.object.length) + { + free (value->u.object.values); + break; + } + + value = value->u.object.values [-- value->u.object.length].value; + continue; + + case json_string: + + free (value->u.string.ptr); + break; + + default: + break; + }; + + cur_value = value; + value = value->parent; + free (cur_value); + } +} +const struct _json_value *json_object_get (const json_value * object, const char * index) +{ + unsigned int i; + + if (object->type != json_object) + return &json_value_none; + + for (i = 0; i < object->u.object.length; ++ i) + if (!strcmp (object->u.object.values [i].name, index)) + return object->u.object.values [i].value; + + return &json_value_none; +} + +const struct _json_value *json_array_get (const json_value * array, int index) +{ + if (array->type != json_array || index >= (int)array->u.array.length) + return &json_value_none; + + return array->u.array.values[index]; +} + +int json_array_length (const json_value * array) { return array->u.array.length; } +const char * json_string_get (const json_value * string) { return string->u.string.ptr; } +int json_int_get (const json_value * integer) { return integer->u.integer; } +int json_boolean_get(const json_value * boolean) { return boolean->u.boolean != 0; } diff --git a/src/engine/external/json-parser/json.h b/src/engine/external/json-parser/json.h new file mode 100644 index 0000000..1a862bd --- /dev/null +++ b/src/engine/external/json-parser/json.h @@ -0,0 +1,205 @@ + +/* vim: set et ts=3 sw=3 ft=c: + * + * Copyright (C) 2012 James McLaughlin et al. All rights reserved. + * https://github.com/udp/json-parser + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifndef _JSON_H +#define _JSON_H + +#ifdef _MSC_VER + #define inline __inline +#endif + +#include <string.h> + +#ifndef json_char + #define json_char char +#endif + +#ifdef __cplusplus + + #include <string.h> + + extern "C" + { + +#endif + +typedef struct +{ + unsigned long max_memory; + int settings; + +} json_settings; + +#define json_relaxed_commas 1 + +typedef enum +{ + json_none, + json_object, + json_array, + json_integer, + json_double, + json_string, + json_boolean, + json_null + +} json_type; + +extern const struct _json_value json_value_none; + +typedef struct _json_value +{ + struct _json_value * parent; + + json_type type; + + union + { + int boolean; + long integer; + double dbl; + + struct + { + unsigned int length; + json_char * ptr; /* null terminated */ + + } string; + + struct + { + unsigned int length; + + struct + { + json_char * name; + struct _json_value * value; + + } * values; + + } object; + + struct + { + unsigned int length; + struct _json_value ** values; + + } array; + + } u; + + union + { + struct _json_value * next_alloc; + void * object_mem; + + } _reserved; + + + /* Some C++ operator sugar */ + + #ifdef __cplusplus + + public: + + inline _json_value () + { memset (this, 0, sizeof (_json_value)); + } + + inline const struct _json_value &operator [] (int index) const + { + if (type != json_array || index < 0 + || ((unsigned int) index) >= u.array.length) + { + return json_value_none; + } + + return *u.array.values [index]; + } + + inline const struct _json_value &operator [] (const char * index) const + { + if (type != json_object) + return json_value_none; + + for (unsigned int i = 0; i < u.object.length; ++ i) + if (!strcmp (u.object.values [i].name, index)) + return *u.object.values [i].value; + + return json_value_none; + } + + inline operator const char * () const + { + switch (type) + { + case json_string: + return u.string.ptr; + + default: + return ""; + }; + } + + inline operator long () const + { return u.integer; + } + + inline operator bool () const + { return u.boolean != 0; + } + + #endif + +} json_value; + +json_value * json_parse + (const json_char * json); + +json_value * json_parse_ex + (json_settings * settings, const json_char * json, char * error); + +void json_value_free (json_value *); + +const struct _json_value *json_object_get (const json_value * object, const char * index); + +const struct _json_value *json_array_get (const json_value * array, int index); + +int json_array_length (const json_value * array); +const char * json_string_get (const json_value * string); +int json_int_get (const json_value * integer); +int json_boolean_get(const json_value * boolean); + +#ifdef __cplusplus + } /* extern "C" */ +#endif + +#endif + diff --git a/src/engine/external/libwebsockets/LICENSE b/src/engine/external/libwebsockets/LICENSE new file mode 100644 index 0000000..7c89865 --- /dev/null +++ b/src/engine/external/libwebsockets/LICENSE @@ -0,0 +1,526 @@ +Libwebsockets and included programs are provided under the terms of the GNU +Library General Public License (LGPL) 2.1, with the following exceptions: + +1) Static linking of programs with the libwebsockets library does not +constitute a derivative work and does not require the author to provide +source code for the program, use the shared libwebsockets libraries, or +link their program against a user-supplied version of libwebsockets. + +If you link the program to a modified version of libwebsockets, then the +changes to libwebsockets must be provided under the terms of the LGPL in +sections 1, 2, and 4. + +2) You do not have to provide a copy of the libwebsockets license with +programs that are linked to the libwebsockets library, nor do you have to +identify the libwebsockets license in your program or documentation as +required by section 6 of the LGPL. + +However, programs must still identify their use of libwebsockets. The +following example statement can be included in user documentation to +satisfy this requirement: + +"[program] is based in part on the work of the libwebsockets project +(http://libwebsockets.org)" + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/engine/external/libwebsockets/alloc.c b/src/engine/external/libwebsockets/alloc.c new file mode 100644 index 0000000..3bc5260 --- /dev/null +++ b/src/engine/external/libwebsockets/alloc.c @@ -0,0 +1,30 @@ +#include "private-libwebsockets.h" + +static void *_realloc(void *ptr, size_t size) +{ + if (size) + return realloc(ptr, size); + else if (ptr) + free(ptr); + return NULL; +} + +void *(*_lws_realloc)(void *ptr, size_t size) = _realloc; + +void *lws_realloc(void *ptr, size_t size) +{ + return _lws_realloc(ptr, size); +} + +void *lws_zalloc(size_t size) +{ + void *ptr = _lws_realloc(NULL, size); + if (ptr) + memset(ptr, 0, size); + return ptr; +} + +void lws_set_allocator(void *(*cb)(void *ptr, size_t size)) +{ + _lws_realloc = cb; +} diff --git a/src/engine/external/libwebsockets/base64-decode.c b/src/engine/external/libwebsockets/base64-decode.c new file mode 100644 index 0000000..92501b0 --- /dev/null +++ b/src/engine/external/libwebsockets/base64-decode.c @@ -0,0 +1,185 @@ +/* + * This code originally came from here + * + * http://base64.sourceforge.net/b64.c + * + * with the following license: + * + * LICENCE: Copyright (c) 2001 Bob Trower, Trantor Standard Systems Inc. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the + * Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall + * be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY + * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR + * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS + * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * VERSION HISTORY: + * Bob Trower 08/04/01 -- Create Version 0.00.00B + * + * I cleaned it up quite a bit to match the (linux kernel) style of the rest + * of libwebsockets; this version is under LGPL2 like the rest of libwebsockets + * since he explictly allows sublicensing, but I give the URL above so you can + * get the original with Bob's super-liberal terms directly if you prefer. + */ + + +#include <stdio.h> +#include <string.h> +#include "private-libwebsockets.h" + +static const char encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char decode[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW" + "$$$$$$XYZ[\\]^_`abcdefghijklmnopq"; + +LWS_VISIBLE int +lws_b64_encode_string(const char *in, int in_len, char *out, int out_size) +{ + unsigned char triple[3]; + int i; + int len; + int line = 0; + int done = 0; + + while (in_len) { + len = 0; + for (i = 0; i < 3; i++) { + if (in_len) { + triple[i] = *in++; + len++; + in_len--; + } else + triple[i] = 0; + } + + if (done + 4 >= out_size) + return -1; + + *out++ = encode[triple[0] >> 2]; + *out++ = encode[((triple[0] & 0x03) << 4) | + ((triple[1] & 0xf0) >> 4)]; + *out++ = (len > 1 ? encode[((triple[1] & 0x0f) << 2) | + ((triple[2] & 0xc0) >> 6)] : '='); + *out++ = (len > 2 ? encode[triple[2] & 0x3f] : '='); + + done += 4; + line += 4; + } + + if (done + 1 >= out_size) + return -1; + + *out++ = '\0'; + + return done; +} + +/* + * returns length of decoded string in out, or -1 if out was too small + * according to out_size + */ + +LWS_VISIBLE int +lws_b64_decode_string(const char *in, char *out, int out_size) +{ + int len; + int i; + int done = 0; + unsigned char v; + unsigned char quad[4]; + + while (*in) { + + len = 0; + for (i = 0; i < 4 && *in; i++) { + + v = 0; + while (*in && !v) { + + v = *in++; + v = (v < 43 || v > 122) ? 0 : decode[v - 43]; + if (v) + v = (v == '$') ? 0 : v - 61; + if (*in) { + len++; + if (v) + quad[i] = v - 1; + } else + quad[i] = 0; + } + } + + if (out_size < (done + len - 1)) + /* out buffer is too small */ + return -1; + + if (len >= 2) + *out++ = quad[0] << 2 | quad[1] >> 4; + if (len >= 3) + *out++ = quad[1] << 4 | quad[2] >> 2; + if (len >= 4) + *out++ = ((quad[2] << 6) & 0xc0) | quad[3]; + + done += len - 1; + } + + if (done + 1 >= out_size) + return -1; + + *out++ = '\0'; + + return done; +} + +int +lws_b64_selftest(void) +{ + char buf[64]; + int n; + int test; + static const char * const plaintext[] = { + "sanity check base 64" + }; + static const char * const coded[] = { + "c2FuaXR5IGNoZWNrIGJhc2UgNjQ=" + }; + + for (test = 0; test < sizeof plaintext / sizeof(plaintext[0]); test++) { + + buf[sizeof(buf) - 1] = '\0'; + n = lws_b64_encode_string(plaintext[test], + strlen(plaintext[test]), buf, sizeof buf); + if (n != strlen(coded[test]) || strcmp(buf, coded[test])) { + lwsl_err("Failed lws_b64 encode selftest " + "%d result '%s' %d\n", test, buf, n); + return -1; + } + + buf[sizeof(buf) - 1] = '\0'; + n = lws_b64_decode_string(coded[test], buf, sizeof buf); + if (n != strlen(plaintext[test]) || + strcmp(buf, plaintext[test])) { + lwsl_err("Failed lws_b64 decode selftest " + "%d result '%s' %d\n", test, buf, n); + return -1; + } + } + + return 0; +} diff --git a/src/engine/external/libwebsockets/config.h b/src/engine/external/libwebsockets/config.h new file mode 100644 index 0000000..617c897 --- /dev/null +++ b/src/engine/external/libwebsockets/config.h @@ -0,0 +1,174 @@ +/* config.h.in. Generated from configure.ac by autoheader. */ + +#ifndef WIN32 +/* #undef _DEBUG */ +#endif + +/* Define to 1 to use CyaSSL as a replacement for OpenSSL. + * LWS_OPENSSL_SUPPORT needs to be set also for this to work. */ +/* #undef USE_CYASSL */ + +/* The Libwebsocket version */ +#define LWS_LIBRARY_VERSION "1.3" + +/* The current git commit hash that we're building from */ +#define LWS_BUILD_HASH "080e6dd" + +/* Build with OpenSSL support */ +/* #undef LWS_OPENSSL_SUPPORT */ + +/* The client should load and trust CA root certs it finds in the OS */ +/* #undef LWS_SSL_CLIENT_USE_OS_CA_CERTS */ + +/* Sets the path where the client certs should be installed. */ +#define LWS_OPENSSL_CLIENT_CERTS "../share" + +/* Turn off websocket extensions */ +/* #undef LWS_NO_EXTENSIONS */ + +/* Enable libev io loop */ +/* #undef LWS_USE_LIBEV */ + +/* Build with support for ipv6 */ +/* #undef LWS_USE_IPV6 */ + +/* Build with support for HTTP2 */ +/* #undef LWS_USE_HTTP2 */ + +/* Turn on latency measuring code */ +/* #undef LWS_LATENCY */ + +/* Don't build the daemonizeation api */ +#define LWS_NO_DAEMONIZE + +/* Build without server support */ +/* #undef LWS_NO_SERVER */ + +/* Build without client support */ +#define LWS_NO_CLIENT + +/* If we should compile with MinGW support */ +/* #undef LWS_MINGW_SUPPORT */ + +/* Use the BSD getifaddrs that comes with libwebsocket, for uclibc support */ +/* #undef LWS_BUILTIN_GETIFADDRS */ + +/* Define to 1 if you have the `bzero' function. */ +#define HAVE_BZERO + +/* Define to 1 if you have the <dlfcn.h> header file. */ +#define HAVE_DLFCN_H + +/* Define to 1 if you have the <fcntl.h> header file. */ +#define HAVE_FCNTL_H + +/* Define to 1 if you have the `fork' function. */ +#define HAVE_FORK + +/* Define to 1 if you have the `getenv’ function. */ +#define HAVE_GETENV + +/* Define to 1 if you have the <in6addr.h> header file. */ +/* #undef HAVE_IN6ADDR_H */ + +/* Define to 1 if you have the <inttypes.h> header file. */ +#define HAVE_INTTYPES_H + +/* Define to 1 if you have the `ssl' library (-lssl). */ +/* #undef HAVE_LIBSSL */ + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#define HAVE_MALLOC + +/* Define to 1 if you have the <memory.h> header file. */ +#define HAVE_MEMORY_H + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET + +/* Define to 1 if you have the <netinet/in.h> header file. */ +#define HAVE_NETINET_IN_H + +/* Define to 1 if your system has a GNU libc compatible `realloc' function, + and to 0 otherwise. */ +#define HAVE_REALLOC + +/* Define to 1 if you have the `socket' function. */ +#define HAVE_SOCKET + +/* Define to 1 if you have the <stdint.h> header file. */ +#define HAVE_STDINT_H + +/* Define to 1 if you have the <stdlib.h> header file. */ +#define HAVE_STDLIB_H + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR + +/* Define to 1 if you have the <strings.h> header file. */ +#define HAVE_STRINGS_H + +/* Define to 1 if you have the <string.h> header file. */ +#define HAVE_STRING_H + +/* Define to 1 if you have the <sys/prctl.h> header file. */ +/* #undef HAVE_SYS_PRCTL_H */ + +/* Define to 1 if you have the <sys/socket.h> header file. */ +#define HAVE_SYS_SOCKET_H + +/* Define to 1 if you have the <sys/stat.h> header file. */ +#define HAVE_SYS_STAT_H + +/* Define to 1 if you have the <sys/types.h> header file. */ +#define HAVE_SYS_TYPES_H + +/* Define to 1 if you have the <unistd.h> header file. */ +#define HAVE_UNISTD_H + +/* Define to 1 if you have the `vfork' function. */ +#define HAVE_VFORK + +/* Define to 1 if you have the <vfork.h> header file. */ +/* #undef HAVE_VFORK_H */ + +/* Define to 1 if `fork' works. */ +#define HAVE_WORKING_FORK + +/* Define to 1 if `vfork' works. */ +#define HAVE_WORKING_VFORK + +/* Define to 1 if you have the <zlib.h> header file. */ +#define HAVE_ZLIB_H + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#undef LT_OBJDIR // We're not using libtool + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS + +/* Version number of package */ +#define VERSION + +/* Define to rpl_malloc if the replacement function should be used. */ +/* #undef malloc */ + +/* Define to `int' if <sys/types.h> does not define. */ +/* #undef pid_t */ + +/* Define to rpl_realloc if the replacement function should be used. */ +/* #undef realloc */ + +/* Define to `unsigned int' if <sys/types.h> does not define. */ +/* #undef size_t */ + +/* Define to 1 if we have getifaddrs */ +#define HAVE_GETIFADDRS + +/* Define as `fork' if `vfork' does not work. */ +/* #undef vfork */ + +/* Define if the inline keyword doesn't exist. */ +/* #undef inline */ diff --git a/src/engine/external/libwebsockets/context.c b/src/engine/external/libwebsockets/context.c new file mode 100644 index 0000000..2ea9c60 --- /dev/null +++ b/src/engine/external/libwebsockets/context.c @@ -0,0 +1,337 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +#ifndef LWS_BUILD_HASH +#define LWS_BUILD_HASH "unknown-build-hash" +#endif + +static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH; + +/** + * lws_get_library_version: get version and git hash library built from + * + * returns a const char * to a string like "1.1 178d78c" + * representing the library version followed by the git head hash it + * was built from + */ + +LWS_VISIBLE const char * +lws_get_library_version(void) +{ + return library_version; +} + +/** + * libwebsocket_create_context() - Create the websocket handler + * @info: pointer to struct with parameters + * + * This function creates the listening socket (if serving) and takes care + * of all initialization in one step. + * + * After initialization, it returns a struct libwebsocket_context * that + * represents this server. After calling, user code needs to take care + * of calling libwebsocket_service() with the context pointer to get the + * server's sockets serviced. This must be done in the same process + * context as the initialization call. + * + * The protocol callback functions are called for a handful of events + * including http requests coming in, websocket connections becoming + * established, and data arriving; it's also called periodically to allow + * async transmission. + * + * HTTP requests are sent always to the FIRST protocol in @protocol, since + * at that time websocket protocol has not been negotiated. Other + * protocols after the first one never see any HTTP callack activity. + * + * The server created is a simple http server by default; part of the + * websocket standard is upgrading this http connection to a websocket one. + * + * This allows the same server to provide files like scripts and favicon / + * images or whatever over http and dynamic data over websockets all in + * one place; they're all handled in the user callback. + */ + +LWS_VISIBLE struct libwebsocket_context * +libwebsocket_create_context(struct lws_context_creation_info *info) +{ + struct libwebsocket_context *context = NULL; + char *p; + + int pid_daemon = get_daemonize_pid(); + + lwsl_notice("Initial logging level %d\n", log_level); + lwsl_notice("Library version: %s\n", library_version); +#ifdef LWS_USE_IPV6 + if (!(info->options & LWS_SERVER_OPTION_DISABLE_IPV6)) + lwsl_notice("IPV6 compiled in and enabled\n"); + else + lwsl_notice("IPV6 compiled in but disabled\n"); +#else + lwsl_notice("IPV6 not compiled in\n"); +#endif + lws_feature_status_libev(info); + lwsl_info(" LWS_MAX_HEADER_LEN: %u\n", LWS_MAX_HEADER_LEN); + lwsl_info(" LWS_MAX_PROTOCOLS: %u\n", LWS_MAX_PROTOCOLS); + + lwsl_info(" SPEC_LATEST_SUPPORTED: %u\n", SPEC_LATEST_SUPPORTED); + lwsl_info(" AWAITING_TIMEOUT: %u\n", AWAITING_TIMEOUT); + lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH); + lwsl_info(" LWS_MAX_ZLIB_CONN_BUFFER: %u\n", LWS_MAX_ZLIB_CONN_BUFFER); + + if (lws_plat_context_early_init()) + return NULL; + + context = lws_zalloc(sizeof(struct libwebsocket_context)); + if (!context) { + lwsl_err("No memory for websocket context\n"); + return NULL; + } + + if (pid_daemon) { + context->started_with_parent = pid_daemon; + lwsl_notice(" Started with daemon pid %d\n", pid_daemon); + } + + context->listen_service_extraseen = 0; + context->protocols = info->protocols; + context->token_limits = info->token_limits; + context->listen_port = info->port; + context->http_proxy_port = 0; + context->http_proxy_address[0] = '\0'; + context->options = info->options; + context->iface = info->iface; + context->ka_time = info->ka_time; + context->ka_interval = info->ka_interval; + context->ka_probes = info->ka_probes; + + /* to reduce this allocation, */ + context->max_fds = getdtablesize(); + lwsl_notice(" static allocation: %u + (%u x %u fds) = %u bytes\n", + sizeof(struct libwebsocket_context), + sizeof(struct libwebsocket_pollfd) + + sizeof(struct libwebsocket *), + context->max_fds, + sizeof(struct libwebsocket_context) + + ((sizeof(struct libwebsocket_pollfd) + + sizeof(struct libwebsocket *)) * + context->max_fds)); + + context->fds = lws_zalloc(sizeof(struct libwebsocket_pollfd) * + context->max_fds); + if (context->fds == NULL) { + lwsl_err("Unable to allocate fds array for %d connections\n", + context->max_fds); + lws_free(context); + return NULL; + } + + context->lws_lookup = lws_zalloc(sizeof(struct libwebsocket *) * context->max_fds); + if (context->lws_lookup == NULL) { + lwsl_err( + "Unable to allocate lws_lookup array for %d connections\n", + context->max_fds); + lws_free(context->fds); + lws_free(context); + return NULL; + } + + if (lws_plat_init_fd_tables(context)) { + lws_free(context->lws_lookup); + lws_free(context->fds); + lws_free(context); + return NULL; + } + + lws_context_init_extensions(info, context); + + context->user_space = info->user; + + strcpy(context->canonical_hostname, "unknown"); + + lws_server_get_canonical_hostname(context, info); + + /* split the proxy ads:port if given */ + + if (info->http_proxy_address) { + strncpy(context->http_proxy_address, info->http_proxy_address, + sizeof(context->http_proxy_address) - 1); + context->http_proxy_address[ + sizeof(context->http_proxy_address) - 1] = '\0'; + context->http_proxy_port = info->http_proxy_port; + } else { +#ifdef HAVE_GETENV + p = getenv("http_proxy"); + if (p) { + strncpy(context->http_proxy_address, p, + sizeof(context->http_proxy_address) - 1); + context->http_proxy_address[ + sizeof(context->http_proxy_address) - 1] = '\0'; + + p = strchr(context->http_proxy_address, ':'); + if (p == NULL) { + lwsl_err("http_proxy needs to be ads:port\n"); + goto bail; + } + *p = '\0'; + context->http_proxy_port = atoi(p + 1); + } +#endif + } + + if (context->http_proxy_address[0]) + lwsl_notice(" Proxy %s:%u\n", + context->http_proxy_address, + context->http_proxy_port); + + lwsl_notice( + " per-conn mem: %u + %u headers + protocol rx buf\n", + sizeof(struct libwebsocket), + sizeof(struct allocated_headers)); + + if (lws_context_init_server_ssl(info, context)) + goto bail; + + if (lws_context_init_client_ssl(info, context)) + goto bail; + + if (lws_context_init_server(info, context)) + goto bail; + + /* + * drop any root privs for this process + * to listen on port < 1023 we would have needed root, but now we are + * listening, we don't want the power for anything else + */ + lws_plat_drop_app_privileges(info); + + /* initialize supported protocols */ + + for (context->count_protocols = 0; + info->protocols[context->count_protocols].callback; + context->count_protocols++) { + + lwsl_parser(" Protocol: %s\n", + info->protocols[context->count_protocols].name); + + info->protocols[context->count_protocols].owning_server = + context; + info->protocols[context->count_protocols].protocol_index = + context->count_protocols; + + /* + * inform all the protocols that they are doing their one-time + * initialization if they want to + */ + info->protocols[context->count_protocols].callback(context, + NULL, LWS_CALLBACK_PROTOCOL_INIT, NULL, NULL, 0); + } + + /* + * give all extensions a chance to create any per-context + * allocations they need + */ + + if (info->port != CONTEXT_PORT_NO_LISTEN) { + if (lws_ext_callback_for_each_extension_type(context, NULL, + LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT, + NULL, 0) < 0) + goto bail; + } else + if (lws_ext_callback_for_each_extension_type(context, NULL, + LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT, + NULL, 0) < 0) + goto bail; + + return context; + +bail: + libwebsocket_context_destroy(context); + return NULL; +} + +/** + * libwebsocket_context_destroy() - Destroy the websocket context + * @context: Websocket context + * + * This function closes any active connections and then frees the + * context. After calling this, any further use of the context is + * undefined. + */ +LWS_VISIBLE void +libwebsocket_context_destroy(struct libwebsocket_context *context) +{ + int n; + struct libwebsocket_protocols *protocol = context->protocols; + + lwsl_notice("%s\n", __func__); + +#ifdef LWS_LATENCY + if (context->worst_latency_info[0]) + lwsl_notice("Worst latency: %s\n", context->worst_latency_info); +#endif + + for (n = 0; n < context->fds_count; n++) { + struct libwebsocket *wsi = + context->lws_lookup[context->fds[n].fd]; + if (!wsi) + continue; + libwebsocket_close_and_free_session(context, + wsi, LWS_CLOSE_STATUS_NOSTATUS /* no protocol close */); + n--; + } + + /* + * give all extensions a chance to clean up any per-context + * allocations they might have made + */ + if (context->listen_port != CONTEXT_PORT_NO_LISTEN) { + if (lws_ext_callback_for_each_extension_type(context, NULL, + LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT, NULL, 0) < 0) + return; + } else + if (lws_ext_callback_for_each_extension_type(context, NULL, + LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT, NULL, 0) < 0) + return; + + /* + * inform all the protocols that they are done and will have no more + * callbacks + */ + + while (protocol->callback) { + protocol->callback(context, NULL, LWS_CALLBACK_PROTOCOL_DESTROY, + NULL, NULL, 0); + protocol++; + } + + lws_plat_context_early_destroy(context); + + lws_ssl_context_destroy(context); + + lws_free(context->fds); + lws_free(context->lws_lookup); + + lws_plat_context_late_destroy(context); + + lws_free(context); +} diff --git a/src/engine/external/libwebsockets/extension-deflate-frame.c b/src/engine/external/libwebsockets/extension-deflate-frame.c new file mode 100644 index 0000000..13b2b8d --- /dev/null +++ b/src/engine/external/libwebsockets/extension-deflate-frame.c @@ -0,0 +1,288 @@ +#include "private-libwebsockets.h" +#include "extension-deflate-frame.h" +#include <stdio.h> +#include <string.h> +#include <assert.h> + +#define LWS_ZLIB_WINDOW_BITS 15 +#define LWS_ZLIB_MEMLEVEL 8 + +int lws_extension_callback_deflate_frame( + struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len) +{ + struct lws_ext_deflate_frame_conn *conn = + (struct lws_ext_deflate_frame_conn *)user; + struct lws_tokens *eff_buf = (struct lws_tokens *)in; + size_t current_payload, remaining_payload, total_payload; + int n; + size_t len_so_far; + + switch (reason) { + + /* + * for deflate-frame, both client and server sides act the same + */ + + case LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: + case LWS_EXT_CALLBACK_CONSTRUCT: + conn->zs_in.zalloc = conn->zs_out.zalloc = Z_NULL; + conn->zs_in.zfree = conn->zs_out.zfree = Z_NULL; + conn->zs_in.opaque = conn->zs_out.opaque = Z_NULL; + n = inflateInit2(&conn->zs_in, -LWS_ZLIB_WINDOW_BITS); + if (n != Z_OK) { + lwsl_ext("deflateInit returned %d\n", n); + return 1; + } + n = deflateInit2(&conn->zs_out, + (context->listen_port ? + DEFLATE_FRAME_COMPRESSION_LEVEL_SERVER : + DEFLATE_FRAME_COMPRESSION_LEVEL_CLIENT), + Z_DEFLATED, + -LWS_ZLIB_WINDOW_BITS, LWS_ZLIB_MEMLEVEL, + Z_DEFAULT_STRATEGY); + if (n != Z_OK) { + lwsl_ext("deflateInit2 returned %d\n", n); + return 1; + } + conn->buf_pre_used = 0; + conn->buf_pre_length = 0; + conn->buf_in_length = sizeof(conn->buf_in); + conn->buf_out_length = sizeof(conn->buf_out); + conn->compressed_out = 0; + conn->buf_pre = NULL; + conn->buf_in = lws_malloc(LWS_SEND_BUFFER_PRE_PADDING + + conn->buf_in_length + + LWS_SEND_BUFFER_POST_PADDING); + if (!conn->buf_in) + goto bail; + conn->buf_out = lws_malloc(LWS_SEND_BUFFER_PRE_PADDING + + conn->buf_out_length + + LWS_SEND_BUFFER_POST_PADDING); + if (!conn->buf_out) + goto bail; + lwsl_ext("zlibs constructed\n"); + break; +bail: + lwsl_err("Out of mem\n"); + (void)inflateEnd(&conn->zs_in); + (void)deflateEnd(&conn->zs_out); + return -1; + + case LWS_EXT_CALLBACK_DESTROY: + lws_free(conn->buf_pre); + lws_free(conn->buf_in); + lws_free(conn->buf_out); + conn->buf_pre_used = 0; + conn->buf_pre_length = 0; + conn->buf_in_length = 0; + conn->buf_out_length = 0; + conn->compressed_out = 0; + (void)inflateEnd(&conn->zs_in); + (void)deflateEnd(&conn->zs_out); + lwsl_ext("zlibs destructed\n"); + break; + + case LWS_EXT_CALLBACK_PAYLOAD_RX: + if (!(wsi->u.ws.rsv & 0x40)) + return 0; + + /* + * inflate the incoming payload + */ + current_payload = eff_buf->token_len; + + remaining_payload = wsi->u.ws.rx_packet_length; + if (remaining_payload) { + total_payload = conn->buf_pre_used + + current_payload + + remaining_payload; + + if (conn->buf_pre_length < total_payload) { + conn->buf_pre_length = total_payload; + lws_free(conn->buf_pre); + conn->buf_pre = lws_malloc(total_payload + 4); + if (!conn->buf_pre) { + lwsl_err("Out of memory\n"); + return -1; + } + } + + memcpy(conn->buf_pre + conn->buf_pre_used, + eff_buf->token, current_payload); + conn->buf_pre_used += current_payload; + + eff_buf->token = NULL; + eff_buf->token_len = 0; + + return 0; + } + if (conn->buf_pre_used) { + total_payload = conn->buf_pre_used + + current_payload; + + memcpy(conn->buf_pre + conn->buf_pre_used, + eff_buf->token, current_payload); + conn->buf_pre_used = 0; + + conn->zs_in.next_in = conn->buf_pre; + } else { + total_payload = current_payload; + + conn->zs_in.next_in = (unsigned char *)eff_buf->token; + } + + conn->zs_in.next_in[total_payload + 0] = 0; + conn->zs_in.next_in[total_payload + 1] = 0; + conn->zs_in.next_in[total_payload + 2] = 0xff; + conn->zs_in.next_in[total_payload + 3] = 0xff; + + conn->zs_in.avail_in = total_payload + 4; + + conn->zs_in.next_out = + conn->buf_in + LWS_SEND_BUFFER_PRE_PADDING; + conn->zs_in.avail_out = conn->buf_in_length; + + while (1) { + n = inflate(&conn->zs_in, Z_SYNC_FLUSH); + switch (n) { + case Z_NEED_DICT: + case Z_STREAM_ERROR: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + /* + * screwed.. close the connection... + * we will get a destroy callback to take care + * of closing nicely + */ + lwsl_info("zlib error inflate %d: %s\n", + n, conn->zs_in.msg); + return -1; + } + + if (conn->zs_in.avail_out) + break; + + len_so_far = conn->zs_in.next_out - + (conn->buf_in + LWS_SEND_BUFFER_PRE_PADDING); + + conn->buf_in_length *= 2; + if (conn->buf_in_length > LWS_MAX_ZLIB_CONN_BUFFER) { + lwsl_ext("zlib in buffer hit limit %u\n", + LWS_MAX_ZLIB_CONN_BUFFER); + return -1; + } + conn->buf_in = lws_realloc(conn->buf_in, + LWS_SEND_BUFFER_PRE_PADDING + + conn->buf_in_length + + LWS_SEND_BUFFER_POST_PADDING); + if (!conn->buf_in) { + lwsl_err("Out of memory\n"); + return -1; + } + lwsl_debug( + "deflate-frame ext RX did realloc to %ld\n", + conn->buf_in_length); + conn->zs_in.next_out = conn->buf_in + + LWS_SEND_BUFFER_PRE_PADDING + len_so_far; + conn->zs_in.avail_out = + conn->buf_in_length - len_so_far; + } + + /* rewrite the buffer pointers and length */ + eff_buf->token = + (char *)(conn->buf_in + LWS_SEND_BUFFER_PRE_PADDING); + eff_buf->token_len = (int)(conn->zs_in.next_out - + (conn->buf_in + LWS_SEND_BUFFER_PRE_PADDING)); + + return 0; + + case LWS_EXT_CALLBACK_PAYLOAD_TX: + /* + * deflate the outgoing payload + */ + current_payload = eff_buf->token_len; + + conn->zs_out.next_in = (unsigned char *)eff_buf->token; + conn->zs_out.avail_in = current_payload; + + conn->zs_out.next_out = + conn->buf_out + LWS_SEND_BUFFER_PRE_PADDING; + conn->zs_out.avail_out = conn->buf_out_length; + + while (1) { + n = deflate(&conn->zs_out, Z_SYNC_FLUSH); + if (n == Z_STREAM_ERROR) { + /* + * screwed.. close the connection... we will + * get a destroy callback to take care of + * closing nicely + */ + lwsl_ext("zlib error deflate\n"); + + return -1; + } + + if (conn->zs_out.avail_out) + break; + + len_so_far = (conn->zs_out.next_out - + (conn->buf_out + + LWS_SEND_BUFFER_PRE_PADDING)); + conn->buf_out_length *= 2; + if (conn->buf_out_length > LWS_MAX_ZLIB_CONN_BUFFER) { + lwsl_ext("zlib out hit limit %u\n", + LWS_MAX_ZLIB_CONN_BUFFER); + return -1; + } + conn->buf_out = lws_realloc(conn->buf_out, + LWS_SEND_BUFFER_PRE_PADDING + + conn->buf_out_length + + LWS_SEND_BUFFER_POST_PADDING); + if (!conn->buf_out) { + lwsl_err("Out of memory\n"); + return -1; + } + lwsl_debug( + "deflate-frame ext TX did realloc to %ld\n", + conn->buf_in_length); + + conn->zs_out.next_out = (conn->buf_out + + LWS_SEND_BUFFER_PRE_PADDING + len_so_far); + conn->zs_out.avail_out = + (conn->buf_out_length - len_so_far); + } + + conn->compressed_out = 1; + + /* rewrite the buffer pointers and length */ + eff_buf->token = (char *)(conn->buf_out + + LWS_SEND_BUFFER_PRE_PADDING); + eff_buf->token_len = (int)(conn->zs_out.next_out - + (conn->buf_out + LWS_SEND_BUFFER_PRE_PADDING)) - 4; + + return 0; + + case LWS_EXT_CALLBACK_PACKET_TX_PRESEND: + if (conn->compressed_out) { + conn->compressed_out = 0; + *((unsigned char *)eff_buf->token) |= 0x40; + } + break; + + case LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION: + /* Avoid x-webkit-deflate-frame extension on client */ + if (!strcmp((char *)in, "x-webkit-deflate-frame")) + return 1; + break; + + default: + break; + } + + return 0; +} + diff --git a/src/engine/external/libwebsockets/extension-deflate-frame.h b/src/engine/external/libwebsockets/extension-deflate-frame.h new file mode 100644 index 0000000..00a4447 --- /dev/null +++ b/src/engine/external/libwebsockets/extension-deflate-frame.h @@ -0,0 +1,25 @@ + +#include <zlib.h> + +#define DEFLATE_FRAME_COMPRESSION_LEVEL_SERVER 1 +#define DEFLATE_FRAME_COMPRESSION_LEVEL_CLIENT Z_DEFAULT_COMPRESSION + +struct lws_ext_deflate_frame_conn { + z_stream zs_in; + z_stream zs_out; + size_t buf_pre_used; + size_t buf_pre_length; + size_t buf_in_length; + size_t buf_out_length; + int compressed_out; + unsigned char *buf_pre; + unsigned char *buf_in; + unsigned char *buf_out; +}; + +extern int lws_extension_callback_deflate_frame( + struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len); diff --git a/src/engine/external/libwebsockets/extension-deflate-stream.c b/src/engine/external/libwebsockets/extension-deflate-stream.c new file mode 100644 index 0000000..addaa2c --- /dev/null +++ b/src/engine/external/libwebsockets/extension-deflate-stream.c @@ -0,0 +1,166 @@ +#include "private-libwebsockets.h" +#include "extension-deflate-stream.h" +#include <stdio.h> +#include <string.h> +#include <assert.h> + +#define LWS_ZLIB_WINDOW_BITS 15 +#define LWS_ZLIB_MEMLEVEL 8 + +int lws_extension_callback_deflate_stream( + struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len) +{ + struct lws_ext_deflate_stream_conn *conn = + (struct lws_ext_deflate_stream_conn *)user; + int n; + struct lws_tokens *eff_buf = (struct lws_tokens *)in; + + switch (reason) { + + /* + * for deflate-stream, both client and server sides act the same + */ + + case LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: + case LWS_EXT_CALLBACK_CONSTRUCT: + conn->zs_in.zalloc = conn->zs_out.zalloc = Z_NULL; + conn->zs_in.zfree = conn->zs_out.zfree = Z_NULL; + conn->zs_in.opaque = conn->zs_out.opaque = Z_NULL; + n = inflateInit2(&conn->zs_in, -LWS_ZLIB_WINDOW_BITS); + if (n != Z_OK) { + lwsl_err("deflateInit returned %d\n", n); + return 1; + } + n = deflateInit2(&conn->zs_out, + DEFLATE_STREAM_COMPRESSION_LEVEL, Z_DEFLATED, + -LWS_ZLIB_WINDOW_BITS, LWS_ZLIB_MEMLEVEL, + Z_DEFAULT_STRATEGY); + if (n != Z_OK) { + lwsl_err("deflateInit returned %d\n", n); + return 1; + } + lwsl_ext("zlibs constructed\n"); + conn->remaining_in = 0; + break; + + case LWS_EXT_CALLBACK_DESTROY: + (void)inflateEnd(&conn->zs_in); + (void)deflateEnd(&conn->zs_out); + lwsl_ext("zlibs destructed\n"); + break; + + case LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: + + /* + * inflate the incoming compressed data + * Notice, length may be 0 and pointer NULL + * in the case we are flushing with nothing new coming in + */ + if (conn->remaining_in) { + conn->zs_in.next_in = conn->buf_in; + conn->zs_in.avail_in = conn->remaining_in; + conn->remaining_in = 0; + } else { + conn->zs_in.next_in = (unsigned char *)eff_buf->token; + conn->zs_in.avail_in = eff_buf->token_len; + } + + conn->zs_in.next_out = conn->buf_out; + conn->zs_in.avail_out = sizeof(conn->buf_out); + + n = inflate(&conn->zs_in, Z_SYNC_FLUSH); + switch (n) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: + /* + * screwed.. close the connection... we will get a + * destroy callback to take care of closing nicely + */ + lwsl_err("zlib error inflate %d\n", n); + return -1; + } + + /* rewrite the buffer pointers and length */ + + eff_buf->token = (char *)conn->buf_out; + eff_buf->token_len = + sizeof(conn->buf_out) - conn->zs_in.avail_out; + + /* copy avail data if not consumed */ + if (conn->zs_in.avail_in > 0) { + conn->remaining_in = conn->zs_in.avail_in; + memcpy(conn->buf_in, conn->zs_in.next_in, + conn->zs_in.avail_in); + return 1; + } + + /* + * if we filled the output buffer, signal that we likely have + * more and need to be called again + */ + + if (eff_buf->token_len == sizeof(conn->buf_out)) + return 1; + + /* we don't need calling again until new input data comes */ + + return 0; + + case LWS_EXT_CALLBACK_FLUSH_PENDING_TX: + case LWS_EXT_CALLBACK_PACKET_TX_PRESEND: + + /* + * deflate the outgoing compressed data + */ + + conn->zs_out.next_in = (unsigned char *)eff_buf->token; + conn->zs_out.avail_in = eff_buf->token_len; + + conn->zs_out.next_out = conn->buf_out; + conn->zs_out.avail_out = sizeof(conn->buf_out); + + n = Z_PARTIAL_FLUSH; + if (reason == LWS_EXT_CALLBACK_FLUSH_PENDING_TX) + n = Z_FULL_FLUSH; + + n = deflate(&conn->zs_out, n); + if (n == Z_STREAM_ERROR) { + /* + * screwed.. close the connection... we will get a + * destroy callback to take care of closing nicely + */ + lwsl_ext("zlib error deflate\n"); + + return -1; + } + + /* rewrite the buffer pointers and length */ + + eff_buf->token = (char *)conn->buf_out; + eff_buf->token_len = + sizeof(conn->buf_out) - conn->zs_out.avail_out; + + /* + * if we filled the output buffer, signal that we likely have + * more and need to be called again... even in deflate case + * we might sometimes need to spill more than came in + */ + + if (eff_buf->token_len == sizeof(conn->buf_out)) + return 1; + + /* we don't need calling again until new input data comes */ + + return 0; + + default: + break; + } + + return 0; +} diff --git a/src/engine/external/libwebsockets/extension-deflate-stream.h b/src/engine/external/libwebsockets/extension-deflate-stream.h new file mode 100644 index 0000000..fcadc07 --- /dev/null +++ b/src/engine/external/libwebsockets/extension-deflate-stream.h @@ -0,0 +1,20 @@ + +#include <zlib.h> + +#define DEFLATE_STREAM_CHUNK 128 +#define DEFLATE_STREAM_COMPRESSION_LEVEL 1 + +struct lws_ext_deflate_stream_conn { + z_stream zs_in; + z_stream zs_out; + int remaining_in; + unsigned char buf_in[LWS_MAX_SOCKET_IO_BUF]; + unsigned char buf_out[LWS_MAX_SOCKET_IO_BUF]; +}; + +extern int lws_extension_callback_deflate_stream( + struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len); diff --git a/src/engine/external/libwebsockets/extension.c b/src/engine/external/libwebsockets/extension.c new file mode 100644 index 0000000..b7a5792 --- /dev/null +++ b/src/engine/external/libwebsockets/extension.c @@ -0,0 +1,208 @@ +#include "private-libwebsockets.h" + +#include "extension-deflate-frame.h" +#include "extension-deflate-stream.h" + +struct libwebsocket_extension libwebsocket_internal_extensions[] = { +#ifdef LWS_EXT_DEFLATE_STREAM + { + "deflate-stream", + lws_extension_callback_deflate_stream, + sizeof(struct lws_ext_deflate_stream_conn) + }, +#else + { + "x-webkit-deflate-frame", + lws_extension_callback_deflate_frame, + sizeof(struct lws_ext_deflate_frame_conn) + }, + { + "deflate-frame", + lws_extension_callback_deflate_frame, + sizeof(struct lws_ext_deflate_frame_conn) + }, +#endif + { /* terminator */ + NULL, NULL, 0 + } +}; + +LWS_VISIBLE void +lws_context_init_extensions(struct lws_context_creation_info *info, + struct libwebsocket_context *context) +{ + context->extensions = info->extensions; + lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE); +} + +LWS_VISIBLE struct libwebsocket_extension *libwebsocket_get_internal_extensions() +{ + return libwebsocket_internal_extensions; +} + + +/* 0 = nobody had nonzero return, 1 = somebody had positive return, -1 = fail */ + +int lws_ext_callback_for_each_active(struct libwebsocket *wsi, int reason, + void *arg, int len) +{ + int n, m, handled = 0; + + for (n = 0; n < wsi->count_active_extensions; n++) { + m = wsi->active_extensions[n]->callback( + wsi->protocol->owning_server, + wsi->active_extensions[n], wsi, + reason, + wsi->active_extensions_user[n], + arg, len); + if (m < 0) { + lwsl_ext( + "Extension '%s' failed to handle callback %d!\n", + wsi->active_extensions[n]->name, reason); + return -1; + } + if (m > handled) + handled = m; + } + + return handled; +} + +int lws_ext_callback_for_each_extension_type( + struct libwebsocket_context *context, struct libwebsocket *wsi, + int reason, void *arg, int len) +{ + int n = 0, m, handled = 0; + struct libwebsocket_extension *ext = context->extensions; + + while (ext && ext->callback && !handled) { + m = ext->callback(context, ext, wsi, reason, + (void *)(long)n, arg, len); + if (m < 0) { + lwsl_ext( + "Extension '%s' failed to handle callback %d!\n", + wsi->active_extensions[n]->name, reason); + return -1; + } + if (m) + handled = 1; + + ext++; + n++; + } + + return 0; +} + +int +lws_issue_raw_ext_access(struct libwebsocket *wsi, + unsigned char *buf, size_t len) +{ + int ret; + struct lws_tokens eff_buf; + int m; + int n = 0; + + eff_buf.token = (char *)buf; + eff_buf.token_len = len; + + /* + * while we have original buf to spill ourselves, or extensions report + * more in their pipeline + */ + + ret = 1; + while (ret == 1) { + + /* default to nobody has more to spill */ + + ret = 0; + + /* show every extension the new incoming data */ + m = lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PACKET_TX_PRESEND, &eff_buf, 0); + if (m < 0) + return -1; + if (m) /* handled */ + ret = 1; + + if ((char *)buf != eff_buf.token) + /* + * extension recreated it: + * need to buffer this if not all sent + */ + wsi->u.ws.clean_buffer = 0; + + /* assuming they left us something to send, send it */ + + if (eff_buf.token_len) { + n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, + eff_buf.token_len); + if (n < 0) { + lwsl_info("closing from ext access\n"); + return -1; + } + + /* always either sent it all or privately buffered */ + if (wsi->u.ws.clean_buffer) + len = n; + } + + lwsl_parser("written %d bytes to client\n", n); + + /* no extension has more to spill? Then we can go */ + + if (!ret) + break; + + /* we used up what we had */ + + eff_buf.token = NULL; + eff_buf.token_len = 0; + + /* + * Did that leave the pipe choked? + * Or we had to hold on to some of it? + */ + + if (!lws_send_pipe_choked(wsi) && !wsi->truncated_send_len) + /* no we could add more, lets's do that */ + continue; + + lwsl_debug("choked\n"); + + /* + * Yes, he's choked. Don't spill the rest now get a callback + * when he is ready to send and take care of it there + */ + libwebsocket_callback_on_writable( + wsi->protocol->owning_server, wsi); + wsi->extension_data_pending = 1; + ret = 0; + } + + return len; +} + +int +lws_any_extension_handled(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons r, + void *v, size_t len) +{ + int n; + int handled = 0; + + /* maybe an extension will take care of it for us */ + + for (n = 0; n < wsi->count_active_extensions && !handled; n++) { + if (!wsi->active_extensions[n]->callback) + continue; + + handled |= wsi->active_extensions[n]->callback(context, + wsi->active_extensions[n], wsi, + r, wsi->active_extensions_user[n], v, len); + } + + return handled; +} diff --git a/src/engine/external/libwebsockets/getifaddrs.h b/src/engine/external/libwebsockets/getifaddrs.h new file mode 100644 index 0000000..da69b50 --- /dev/null +++ b/src/engine/external/libwebsockets/getifaddrs.h @@ -0,0 +1,76 @@ +#if HAVE_GETIFADDRS +#include <sys/types.h> +#include <ifaddrs.h> +#else +#ifdef __cplusplus +extern "C" { +#endif +/* + * Copyright (c) 2000 Kungliga Tekniska H�gskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* $KTH: ifaddrs.hin,v 1.3 2000/12/11 00:01:13 assar Exp $ */ + +#ifndef ifaddrs_h_7467027A95AD4B5C8DDD40FE7D973791 +#define ifaddrs_h_7467027A95AD4B5C8DDD40FE7D973791 + +/* + * the interface is defined in terms of the fields below, and this is + * sometimes #define'd, so there seems to be no simple way of solving + * this and this seemed the best. */ + +#undef ifa_dstaddr + +struct ifaddrs { + struct ifaddrs *ifa_next; + char *ifa_name; + unsigned int ifa_flags; + struct sockaddr *ifa_addr; + struct sockaddr *ifa_netmask; + struct sockaddr *ifa_dstaddr; + void *ifa_data; +}; + +#ifndef ifa_broadaddr +#define ifa_broadaddr ifa_dstaddr +#endif + +int getifaddrs(struct ifaddrs **); + +void freeifaddrs(struct ifaddrs *); + +#endif /* __ifaddrs_h__ */ + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/engine/external/libwebsockets/handshake.c b/src/engine/external/libwebsockets/handshake.c new file mode 100644 index 0000000..856297d --- /dev/null +++ b/src/engine/external/libwebsockets/handshake.c @@ -0,0 +1,232 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +/* + * -04 of the protocol (actually the 80th version) has a radically different + * handshake. The 04 spec gives the following idea + * + * The handshake from the client looks as follows: + * + * GET /chat HTTP/1.1 + * Host: server.example.com + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== + * Sec-WebSocket-Origin: http://example.com + * Sec-WebSocket-Protocol: chat, superchat + * Sec-WebSocket-Version: 4 + * + * The handshake from the server looks as follows: + * + * HTTP/1.1 101 Switching Protocols + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= + * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== + * Sec-WebSocket-Protocol: chat + */ + +#ifndef min +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif +/* + * We have to take care about parsing because the headers may be split + * into multiple fragments. They may contain unknown headers with arbitrary + * argument lengths. So, we parse using a single-character at a time state + * machine that is completely independent of packet size. + */ + +LWS_VISIBLE int +libwebsocket_read(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char *buf, size_t len) +{ + size_t n; + int body_chunk_len; + unsigned char *last_char; + + switch (wsi->state) { +#ifdef LWS_USE_HTTP2 + case WSI_STATE_HTTP2_AWAIT_CLIENT_PREFACE: + case WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS: + case WSI_STATE_HTTP2_ESTABLISHED: + n = 0; + while (n < len) { + /* + * we were accepting input but now we stopped doing so + */ + if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) { + lws_rxflow_cache(wsi, buf, n, len); + + return 1; + } + + /* account for what we're using in rxflow buffer */ + if (wsi->rxflow_buffer) + wsi->rxflow_pos++; + if (lws_http2_parser(context, wsi, buf[n++])) + goto bail; + } + break; +#endif +http_new: + case WSI_STATE_HTTP: + wsi->hdr_parsing_completed = 0; + /* fallthru */ + case WSI_STATE_HTTP_ISSUING_FILE: + wsi->state = WSI_STATE_HTTP_HEADERS; + wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; + wsi->u.hdr.lextable_pos = 0; + /* fallthru */ + case WSI_STATE_HTTP_HEADERS: + lwsl_parser("issuing %d bytes to parser\n", (int)len); + + if (lws_handshake_client(wsi, &buf, len)) + goto bail; + + last_char = buf; + if (lws_handshake_server(context, wsi, &buf, len)) + /* Handshake indicates this session is done. */ + goto bail; + + /* It's possible that we've exhausted our data already, but + * lws_handshake_server doesn't update len for us. Figure out how + * much was read, so that we can proceed appropriately: */ + len -= (buf - last_char); + + if (!wsi->hdr_parsing_completed) + /* More header content on the way */ + goto read_ok; + + switch (wsi->state) { + case WSI_STATE_HTTP: + case WSI_STATE_HTTP_HEADERS: + goto http_complete; + case WSI_STATE_HTTP_ISSUING_FILE: + goto read_ok; + case WSI_STATE_HTTP_BODY: + wsi->u.http.content_remain = wsi->u.http.content_length; + goto http_postbody; + default: + break; + } + break; + + case WSI_STATE_HTTP_BODY: +http_postbody: + while (len && wsi->u.http.content_remain) { + /* Copy as much as possible, up to the limit of: + * what we have in the read buffer (len) + * remaining portion of the POST body (content_remain) + */ + body_chunk_len = min(wsi->u.http.content_remain,len); + wsi->u.http.content_remain -= body_chunk_len; + len -= body_chunk_len; + + if (wsi->protocol->callback) { + n = wsi->protocol->callback( + wsi->protocol->owning_server, wsi, + LWS_CALLBACK_HTTP_BODY, wsi->user_space, + buf, body_chunk_len); + if (n) + goto bail; + } + buf += body_chunk_len; + + if (!wsi->u.http.content_remain) { + /* he sent the content in time */ + libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + if (wsi->protocol->callback) { + n = wsi->protocol->callback( + wsi->protocol->owning_server, wsi, + LWS_CALLBACK_HTTP_BODY_COMPLETION, + wsi->user_space, NULL, 0); + if (n) + goto bail; + } + goto http_complete; + } else + libwebsocket_set_timeout(wsi, + PENDING_TIMEOUT_HTTP_CONTENT, + AWAITING_TIMEOUT); + } + break; + + case WSI_STATE_ESTABLISHED: + case WSI_STATE_AWAITING_CLOSE_ACK: + if (lws_handshake_client(wsi, &buf, len)) + goto bail; + switch (wsi->mode) { + case LWS_CONNMODE_WS_SERVING: + + if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0) { + lwsl_info("interpret_incoming_packet has bailed\n"); + goto bail; + } + break; + } + break; + default: + lwsl_err("libwebsocket_read: Unhandled state\n"); + break; + } + +read_ok: + /* Nothing more to do for now. */ + lwsl_debug("libwebsocket_read: read_ok\n"); + + return 0; + +http_complete: + lwsl_debug("libwebsocket_read: http_complete\n"); + + /* Did the client want to keep the HTTP connection going? */ + + if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE) { + lwsl_debug("libwebsocket_read: keep-alive\n"); + wsi->state = WSI_STATE_HTTP; + wsi->mode = LWS_CONNMODE_HTTP_SERVING; + + /* He asked for it to stay alive indefinitely */ + libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + + if (lws_allocate_header_table(wsi)) + goto bail; + + /* If we're (re)starting on headers, need other implied init */ + wsi->u.hdr.ues = URIES_IDLE; + + /* If we have more data, loop back around: */ + if (len) + goto http_new; + + return 0; + } + +bail: + lwsl_debug("closing connection at libwebsocket_read bail:\n"); + + libwebsocket_close_and_free_session(context, wsi, + LWS_CLOSE_STATUS_NOSTATUS); + + return -1; +} diff --git a/src/engine/external/libwebsockets/huftable.h b/src/engine/external/libwebsockets/huftable.h new file mode 100644 index 0000000..385a83b --- /dev/null +++ b/src/engine/external/libwebsockets/huftable.h @@ -0,0 +1,530 @@ +static unsigned char lextable[] = { +/* pos 0000: 0 */ /* 0 */ 0x42 /* (to 0x0084 state 98) */, + /* 1 */ 0x01 /* (to 0x0002 state 1) */, +/* pos 0002: 1 */ /* 0 */ 0x5C /* (to 0x00BA state 151) */, + /* 1 */ 0x01 /* (to 0x0004 state 2) */, +/* pos 0004: 2 */ /* 0 */ 0x66 /* (to 0x00D0 state 173) */, + /* 1 */ 0x01 /* (to 0x0006 state 3) */, +/* pos 0006: 3 */ /* 0 */ 0x74 /* (to 0x00EE state 204) */, + /* 1 */ 0x01 /* (to 0x0008 state 4) */, +/* pos 0008: 4 */ /* 0 */ 0x8C /* (to 0x0120 state 263) */, + /* 1 */ 0x01 /* (to 0x000A state 5) */, +/* pos 000a: 5 */ /* 0 */ 0x46 /* (to 0x0096 state 113) */, + /* 1 */ 0x01 /* (to 0x000C state 6) */, +/* pos 000c: 6 */ /* 0 */ 0x75 /* (to 0x00F6 state 211) */, + /* 1 */ 0x01 /* (to 0x000E state 7) */, +/* pos 000e: 7 */ /* 0 */ 0x40 /* (to 0x008E state 104) */, + /* 1 */ 0x01 /* (to 0x0010 state 8) */, +/* pos 0010: 8 */ /* 0 */ 0x45 /* (to 0x009A state 116) */, + /* 1 */ 0x01 /* (to 0x0012 state 9) */, +/* pos 0012: 9 */ /* 0 */ 0x40 /* (to 0x0092 state 108) */, + /* 1 */ 0x01 /* (to 0x0014 state 10) */, +/* pos 0014: 10 */ /* 0 */ 0x01 /* (to 0x0016 state 11) */, + /* 1 */ 0x03 /* (to 0x001A state 14) */, +/* pos 0016: 11 */ /* 0 */ 0x01 /* (to 0x0018 state 12) */, + /* 1 */ 0x5B /* (to 0x00CC state 166) */, +/* pos 0018: 12 */ /* terminal 0 */ 0x00, + /* terminal 36 */ 0x24, +/* pos 001a: 14 */ /* 0 */ 0x72 /* (to 0x00FE state 220) */, + /* 1 */ 0x01 /* (to 0x001C state 15) */, +/* pos 001c: 15 */ /* 0 */ 0x72 /* (to 0x0100 state 222) */, + /* 1 */ 0x01 /* (to 0x001E state 16) */, +/* pos 001e: 16 */ /* 0 */ 0x53 /* (to 0x00C4 state 158) */, + /* 1 */ 0x01 /* (to 0x0020 state 17) */, +/* pos 0020: 17 */ /* terminal 123 */ 0x7B, + /* 1 */ 0x01 /* (to 0x0022 state 18) */, +/* pos 0022: 18 */ /* 0 */ 0x6B /* (to 0x00F8 state 216) */, + /* 1 */ 0x01 /* (to 0x0024 state 19) */, +/* pos 0024: 19 */ /* 0 */ 0x84 /* (to 0x012C state 279) */, + /* 1 */ 0x01 /* (to 0x0026 state 20) */, +/* pos 0026: 20 */ /* 0 */ 0x01 /* (to 0x0028 state 21) */, + /* 1 */ 0x06 /* (to 0x0032 state 27) */, +/* pos 0028: 21 */ /* 0 */ 0xB3 /* (to 0x018E state 377) */, + /* 1 */ 0x01 /* (to 0x002A state 22) */, +/* pos 002a: 22 */ /* 0 */ 0xC3 /* (to 0x01B0 state 414) */, + /* 1 */ 0x01 /* (to 0x002C state 23) */, +/* pos 002c: 23 */ /* 0 */ 0x01 /* (to 0x002E state 24) */, + /* 1 */ 0x8C /* (to 0x0144 state 301) */, +/* pos 002e: 24 */ /* 0 */ 0x01 /* (to 0x0030 state 25) */, + /* 1 */ 0x8A /* (to 0x0142 state 298) */, +/* pos 0030: 25 */ /* terminal 1 */ 0x01, + /* terminal 135 */ 0x87, +/* pos 0032: 27 */ /* 0 */ 0x8E /* (to 0x014E state 314) */, + /* 1 */ 0x01 /* (to 0x0034 state 28) */, +/* pos 0034: 28 */ /* 0 */ 0x0F /* (to 0x0052 state 50) */, + /* 1 */ 0x01 /* (to 0x0036 state 29) */, +/* pos 0036: 29 */ /* 0 */ 0xA4 /* (to 0x017E state 362) */, + /* 1 */ 0x01 /* (to 0x0038 state 30) */, +/* pos 0038: 30 */ /* 0 */ 0xB7 /* (to 0x01A6 state 403) */, + /* 1 */ 0x01 /* (to 0x003A state 31) */, +/* pos 003a: 31 */ /* 0 */ 0xC8 /* (to 0x01CA state 440) */, + /* 1 */ 0x01 /* (to 0x003C state 32) */, +/* pos 003c: 32 */ /* 0 */ 0x01 /* (to 0x003E state 33) */, + /* 1 */ 0x0F /* (to 0x005A state 55) */, +/* pos 003e: 33 */ /* 0 */ 0x01 /* (to 0x0040 state 34) */, + /* 1 */ 0x07 /* (to 0x004C state 46) */, +/* pos 0040: 34 */ /* 0 */ 0x01 /* (to 0x0042 state 35) */, + /* 1 */ 0x03 /* (to 0x0046 state 39) */, +/* pos 0042: 35 */ /* terminal 254 */ 0xFE, + /* 1 */ 0x01 /* (to 0x0044 state 36) */, +/* pos 0044: 36 */ /* terminal 2 */ 0x02, + /* terminal 3 */ 0x03, +/* pos 0046: 39 */ /* 0 */ 0x01 /* (to 0x0048 state 40) */, + /* 1 */ 0x02 /* (to 0x004A state 43) */, +/* pos 0048: 40 */ /* terminal 4 */ 0x04, + /* terminal 5 */ 0x05, +/* pos 004a: 43 */ /* terminal 6 */ 0x06, + /* terminal 7 */ 0x07, +/* pos 004c: 46 */ /* 0 */ 0x01 /* (to 0x004E state 47) */, + /* 1 */ 0x0E /* (to 0x0068 state 67) */, +/* pos 004e: 47 */ /* 0 */ 0x01 /* (to 0x0050 state 48) */, + /* 1 */ 0x0C /* (to 0x0066 state 63) */, +/* pos 0050: 48 */ /* terminal 8 */ 0x08, + /* terminal 11 */ 0x0B, +/* pos 0052: 50 */ /* 0 */ 0xA7 /* (to 0x01A0 state 396) */, + /* 1 */ 0x01 /* (to 0x0054 state 51) */, +/* pos 0054: 51 */ /* 0 */ 0x01 /* (to 0x0056 state 52) */, + /* 1 */ 0x7B /* (to 0x014A state 309) */, +/* pos 0056: 52 */ /* terminal 239 */ 0xEF, + /* 1 */ 0x01 /* (to 0x0058 state 53) */, +/* pos 0058: 53 */ /* terminal 9 */ 0x09, + /* terminal 142 */ 0x8E, +/* pos 005a: 55 */ /* 0 */ 0x0A /* (to 0x006E state 74) */, + /* 1 */ 0x01 /* (to 0x005C state 56) */, +/* pos 005c: 56 */ /* 0 */ 0x11 /* (to 0x007E state 91) */, + /* 1 */ 0x01 /* (to 0x005E state 57) */, +/* pos 005e: 57 */ /* 0 */ 0x64 /* (to 0x0126 state 274) */, + /* 1 */ 0x01 /* (to 0x0060 state 58) */, +/* pos 0060: 58 */ /* terminal 249 */ 0xF9, + /* 1 */ 0x01 /* (to 0x0062 state 59) */, +/* pos 0062: 59 */ /* 0 */ 0x01 /* (to 0x0064 state 60) */, + /* 1 */ 0x0A /* (to 0x0076 state 81) */, +/* pos 0064: 60 */ /* terminal 10 */ 0x0A, + /* terminal 13 */ 0x0D, +/* pos 0066: 63 */ /* terminal 12 */ 0x0C, + /* terminal 14 */ 0x0E, +/* pos 0068: 67 */ /* 0 */ 0x01 /* (to 0x006A state 68) */, + /* 1 */ 0x02 /* (to 0x006C state 71) */, +/* pos 006a: 68 */ /* terminal 15 */ 0x0F, + /* terminal 16 */ 0x10, +/* pos 006c: 71 */ /* terminal 17 */ 0x11, + /* terminal 18 */ 0x12, +/* pos 006e: 74 */ /* 0 */ 0x01 /* (to 0x0070 state 75) */, + /* 1 */ 0x05 /* (to 0x0078 state 84) */, +/* pos 0070: 75 */ /* 0 */ 0x01 /* (to 0x0072 state 76) */, + /* 1 */ 0x02 /* (to 0x0074 state 79) */, +/* pos 0072: 76 */ /* terminal 19 */ 0x13, + /* terminal 20 */ 0x14, +/* pos 0074: 79 */ /* terminal 21 */ 0x15, + /* terminal 23 */ 0x17, +/* pos 0076: 81 */ /* terminal 22 */ 0x16, + /* terminal 256 */ 0x00, +/* pos 0078: 84 */ /* 0 */ 0x01 /* (to 0x007A state 85) */, + /* 1 */ 0x02 /* (to 0x007C state 88) */, +/* pos 007a: 85 */ /* terminal 24 */ 0x18, + /* terminal 25 */ 0x19, +/* pos 007c: 88 */ /* terminal 26 */ 0x1A, + /* terminal 27 */ 0x1B, +/* pos 007e: 91 */ /* 0 */ 0x01 /* (to 0x0080 state 92) */, + /* 1 */ 0x02 /* (to 0x0082 state 95) */, +/* pos 0080: 92 */ /* terminal 28 */ 0x1C, + /* terminal 29 */ 0x1D, +/* pos 0082: 95 */ /* terminal 30 */ 0x1E, + /* terminal 31 */ 0x1F, +/* pos 0084: 98 */ /* 0 */ 0x13 /* (to 0x00AA state 133) */, + /* 1 */ 0x01 /* (to 0x0086 state 99) */, +/* pos 0086: 99 */ /* 0 */ 0x01 /* (to 0x0088 state 100) */, + /* 1 */ 0x0F /* (to 0x00A4 state 129) */, +/* pos 0088: 100 */ /* 0 */ 0x4B /* (to 0x011E state 258) */, + /* 1 */ 0x01 /* (to 0x008A state 101) */, +/* pos 008a: 101 */ /* 0 */ 0x01 /* (to 0x008C state 102) */, + /* 1 */ 0x0C /* (to 0x00A2 state 126) */, +/* pos 008c: 102 */ /* terminal 32 */ 0x20, + /* terminal 37 */ 0x25, +/* pos 008e: 104 */ /* 0 */ 0x01 /* (to 0x0090 state 105) */, + /* 1 */ 0x08 /* (to 0x009E state 119) */, +/* pos 0090: 105 */ /* terminal 33 */ 0x21, + /* terminal 34 */ 0x22, +/* pos 0092: 108 */ /* terminal 124 */ 0x7C, + /* 1 */ 0x01 /* (to 0x0094 state 109) */, +/* pos 0094: 109 */ /* terminal 35 */ 0x23, + /* terminal 62 */ 0x3E, +/* pos 0096: 113 */ /* 0 */ 0x01 /* (to 0x0098 state 114) */, + /* 1 */ 0x05 /* (to 0x00A0 state 124) */, +/* pos 0098: 114 */ /* terminal 38 */ 0x26, + /* terminal 42 */ 0x2A, +/* pos 009a: 116 */ /* terminal 63 */ 0x3F, + /* 1 */ 0x01 /* (to 0x009C state 117) */, +/* pos 009c: 117 */ /* terminal 39 */ 0x27, + /* terminal 43 */ 0x2B, +/* pos 009e: 119 */ /* terminal 40 */ 0x28, + /* terminal 41 */ 0x29, +/* pos 00a0: 124 */ /* terminal 44 */ 0x2C, + /* terminal 59 */ 0x3B, +/* pos 00a2: 126 */ /* terminal 45 */ 0x2D, + /* terminal 46 */ 0x2E, +/* pos 00a4: 129 */ /* 0 */ 0x01 /* (to 0x00A6 state 130) */, + /* 1 */ 0x08 /* (to 0x00B4 state 144) */, +/* pos 00a6: 130 */ /* 0 */ 0x01 /* (to 0x00A8 state 131) */, + /* 1 */ 0x06 /* (to 0x00B2 state 141) */, +/* pos 00a8: 131 */ /* terminal 47 */ 0x2F, + /* terminal 51 */ 0x33, +/* pos 00aa: 133 */ /* 0 */ 0x01 /* (to 0x00AC state 134) */, + /* 1 */ 0x2D /* (to 0x0104 state 229) */, +/* pos 00ac: 134 */ /* 0 */ 0x01 /* (to 0x00AE state 135) */, + /* 1 */ 0x02 /* (to 0x00B0 state 138) */, +/* pos 00ae: 135 */ /* terminal 48 */ 0x30, + /* terminal 49 */ 0x31, +/* pos 00b0: 138 */ /* terminal 50 */ 0x32, + /* terminal 97 */ 0x61, +/* pos 00b2: 141 */ /* terminal 52 */ 0x34, + /* terminal 53 */ 0x35, +/* pos 00b4: 144 */ /* 0 */ 0x01 /* (to 0x00B6 state 145) */, + /* 1 */ 0x02 /* (to 0x00B8 state 148) */, +/* pos 00b6: 145 */ /* terminal 54 */ 0x36, + /* terminal 55 */ 0x37, +/* pos 00b8: 148 */ /* terminal 56 */ 0x38, + /* terminal 57 */ 0x39, +/* pos 00ba: 151 */ /* 0 */ 0x06 /* (to 0x00C6 state 160) */, + /* 1 */ 0x01 /* (to 0x00BC state 152) */, +/* pos 00bc: 152 */ /* 0 */ 0x2C /* (to 0x0114 state 246) */, + /* 1 */ 0x01 /* (to 0x00BE state 153) */, +/* pos 00be: 153 */ /* 0 */ 0x2F /* (to 0x011C state 256) */, + /* 1 */ 0x01 /* (to 0x00C0 state 154) */, +/* pos 00c0: 154 */ /* 0 */ 0x01 /* (to 0x00C2 state 155) */, + /* 1 */ 0x07 /* (to 0x00CE state 170) */, +/* pos 00c2: 155 */ /* terminal 58 */ 0x3A, + /* terminal 66 */ 0x42, +/* pos 00c4: 158 */ /* terminal 60 */ 0x3C, + /* terminal 96 */ 0x60, +/* pos 00c6: 160 */ /* 0 */ 0x01 /* (to 0x00C8 state 161) */, + /* 1 */ 0x21 /* (to 0x0108 state 232) */, +/* pos 00c8: 161 */ /* 0 */ 0x01 /* (to 0x00CA state 162) */, + /* 1 */ 0x1D /* (to 0x0102 state 224) */, +/* pos 00ca: 162 */ /* terminal 61 */ 0x3D, + /* terminal 65 */ 0x41, +/* pos 00cc: 166 */ /* terminal 64 */ 0x40, + /* terminal 91 */ 0x5B, +/* pos 00ce: 170 */ /* terminal 67 */ 0x43, + /* terminal 68 */ 0x44, +/* pos 00d0: 173 */ /* 0 */ 0x01 /* (to 0x00D2 state 174) */, + /* 1 */ 0x08 /* (to 0x00E0 state 189) */, +/* pos 00d2: 174 */ /* 0 */ 0x01 /* (to 0x00D4 state 175) */, + /* 1 */ 0x04 /* (to 0x00DA state 182) */, +/* pos 00d4: 175 */ /* 0 */ 0x01 /* (to 0x00D6 state 176) */, + /* 1 */ 0x02 /* (to 0x00D8 state 179) */, +/* pos 00d6: 176 */ /* terminal 69 */ 0x45, + /* terminal 70 */ 0x46, +/* pos 00d8: 179 */ /* terminal 71 */ 0x47, + /* terminal 72 */ 0x48, +/* pos 00da: 182 */ /* 0 */ 0x01 /* (to 0x00DC state 183) */, + /* 1 */ 0x02 /* (to 0x00DE state 186) */, +/* pos 00dc: 183 */ /* terminal 73 */ 0x49, + /* terminal 74 */ 0x4A, +/* pos 00de: 186 */ /* terminal 75 */ 0x4B, + /* terminal 76 */ 0x4C, +/* pos 00e0: 189 */ /* 0 */ 0x01 /* (to 0x00E2 state 190) */, + /* 1 */ 0x04 /* (to 0x00E8 state 197) */, +/* pos 00e2: 190 */ /* 0 */ 0x01 /* (to 0x00E4 state 191) */, + /* 1 */ 0x02 /* (to 0x00E6 state 194) */, +/* pos 00e4: 191 */ /* terminal 77 */ 0x4D, + /* terminal 78 */ 0x4E, +/* pos 00e6: 194 */ /* terminal 79 */ 0x4F, + /* terminal 80 */ 0x50, +/* pos 00e8: 197 */ /* 0 */ 0x01 /* (to 0x00EA state 198) */, + /* 1 */ 0x02 /* (to 0x00EC state 201) */, +/* pos 00ea: 198 */ /* terminal 81 */ 0x51, + /* terminal 82 */ 0x52, +/* pos 00ec: 201 */ /* terminal 83 */ 0x53, + /* terminal 84 */ 0x54, +/* pos 00ee: 204 */ /* 0 */ 0x01 /* (to 0x00F0 state 205) */, + /* 1 */ 0x11 /* (to 0x0110 state 242) */, +/* pos 00f0: 205 */ /* 0 */ 0x01 /* (to 0x00F2 state 206) */, + /* 1 */ 0x02 /* (to 0x00F4 state 209) */, +/* pos 00f2: 206 */ /* terminal 85 */ 0x55, + /* terminal 86 */ 0x56, +/* pos 00f4: 209 */ /* terminal 87 */ 0x57, + /* terminal 89 */ 0x59, +/* pos 00f6: 211 */ /* terminal 88 */ 0x58, + /* terminal 90 */ 0x5A, +/* pos 00f8: 216 */ /* 0 */ 0x01 /* (to 0x00FA state 217) */, + /* 1 */ 0x1F /* (to 0x0136 state 286) */, +/* pos 00fa: 217 */ /* 0 */ 0x01 /* (to 0x00FC state 218) */, + /* 1 */ 0x17 /* (to 0x0128 state 276) */, +/* pos 00fc: 218 */ /* terminal 92 */ 0x5C, + /* terminal 195 */ 0xC3, +/* pos 00fe: 220 */ /* terminal 93 */ 0x5D, + /* terminal 126 */ 0x7E, +/* pos 0100: 222 */ /* terminal 94 */ 0x5E, + /* terminal 125 */ 0x7D, +/* pos 0102: 224 */ /* terminal 95 */ 0x5F, + /* terminal 98 */ 0x62, +/* pos 0104: 229 */ /* 0 */ 0x01 /* (to 0x0106 state 230) */, + /* 1 */ 0x05 /* (to 0x010E state 240) */, +/* pos 0106: 230 */ /* terminal 99 */ 0x63, + /* terminal 101 */ 0x65, +/* pos 0108: 232 */ /* 0 */ 0x01 /* (to 0x010A state 233) */, + /* 1 */ 0x02 /* (to 0x010C state 237) */, +/* pos 010a: 233 */ /* terminal 100 */ 0x64, + /* terminal 102 */ 0x66, +/* pos 010c: 237 */ /* terminal 103 */ 0x67, + /* terminal 104 */ 0x68, +/* pos 010e: 240 */ /* terminal 105 */ 0x69, + /* terminal 111 */ 0x6F, +/* pos 0110: 242 */ /* 0 */ 0x01 /* (to 0x0112 state 243) */, + /* 1 */ 0x05 /* (to 0x011A state 254) */, +/* pos 0112: 243 */ /* terminal 106 */ 0x6A, + /* terminal 107 */ 0x6B, +/* pos 0114: 246 */ /* 0 */ 0x01 /* (to 0x0116 state 247) */, + /* 1 */ 0x02 /* (to 0x0118 state 250) */, +/* pos 0116: 247 */ /* terminal 108 */ 0x6C, + /* terminal 109 */ 0x6D, +/* pos 0118: 250 */ /* terminal 110 */ 0x6E, + /* terminal 112 */ 0x70, +/* pos 011a: 254 */ /* terminal 113 */ 0x71, + /* terminal 118 */ 0x76, +/* pos 011c: 256 */ /* terminal 114 */ 0x72, + /* terminal 117 */ 0x75, +/* pos 011e: 258 */ /* terminal 115 */ 0x73, + /* terminal 116 */ 0x74, +/* pos 0120: 263 */ /* 0 */ 0x01 /* (to 0x0122 state 264) */, + /* 1 */ 0x02 /* (to 0x0124 state 267) */, +/* pos 0122: 264 */ /* terminal 119 */ 0x77, + /* terminal 120 */ 0x78, +/* pos 0124: 267 */ /* terminal 121 */ 0x79, + /* terminal 122 */ 0x7A, +/* pos 0126: 274 */ /* terminal 127 */ 0x7F, + /* terminal 220 */ 0xDC, +/* pos 0128: 276 */ /* terminal 208 */ 0xD0, + /* 1 */ 0x01 /* (to 0x012A state 277) */, +/* pos 012a: 277 */ /* terminal 128 */ 0x80, + /* terminal 130 */ 0x82, +/* pos 012c: 279 */ /* 0 */ 0x2E /* (to 0x0188 state 372) */, + /* 1 */ 0x01 /* (to 0x012E state 280) */, +/* pos 012e: 280 */ /* 0 */ 0x01 /* (to 0x0130 state 281) */, + /* 1 */ 0x1B /* (to 0x0164 state 332) */, +/* pos 0130: 281 */ /* 0 */ 0x01 /* (to 0x0132 state 282) */, + /* 1 */ 0x06 /* (to 0x013C state 291) */, +/* pos 0132: 282 */ /* terminal 230 */ 0xE6, + /* 1 */ 0x01 /* (to 0x0134 state 283) */, +/* pos 0134: 283 */ /* terminal 129 */ 0x81, + /* terminal 132 */ 0x84, +/* pos 0136: 286 */ /* 0 */ 0x01 /* (to 0x0138 state 287) */, + /* 1 */ 0x14 /* (to 0x015E state 328) */, +/* pos 0138: 287 */ /* 0 */ 0x01 /* (to 0x013A state 288) */, + /* 1 */ 0x30 /* (to 0x0198 state 388) */, +/* pos 013a: 288 */ /* terminal 131 */ 0x83, + /* terminal 162 */ 0xA2, +/* pos 013c: 291 */ /* 0 */ 0x01 /* (to 0x013E state 292) */, + /* 1 */ 0x02 /* (to 0x0140 state 296) */, +/* pos 013e: 292 */ /* terminal 133 */ 0x85, + /* terminal 134 */ 0x86, +/* pos 0140: 296 */ /* terminal 136 */ 0x88, + /* terminal 146 */ 0x92, +/* pos 0142: 298 */ /* terminal 137 */ 0x89, + /* terminal 138 */ 0x8A, +/* pos 0144: 301 */ /* 0 */ 0x01 /* (to 0x0146 state 302) */, + /* 1 */ 0x02 /* (to 0x0148 state 305) */, +/* pos 0146: 302 */ /* terminal 139 */ 0x8B, + /* terminal 140 */ 0x8C, +/* pos 0148: 305 */ /* terminal 141 */ 0x8D, + /* terminal 143 */ 0x8F, +/* pos 014a: 309 */ /* 0 */ 0x01 /* (to 0x014C state 310) */, + /* 1 */ 0x06 /* (to 0x0156 state 319) */, +/* pos 014c: 310 */ /* terminal 144 */ 0x90, + /* terminal 145 */ 0x91, +/* pos 014e: 314 */ /* 0 */ 0x01 /* (to 0x0150 state 315) */, + /* 1 */ 0x12 /* (to 0x0172 state 350) */, +/* pos 0150: 315 */ /* 0 */ 0x01 /* (to 0x0152 state 316) */, + /* 1 */ 0x05 /* (to 0x015A state 325) */, +/* pos 0152: 316 */ /* 0 */ 0x01 /* (to 0x0154 state 317) */, + /* 1 */ 0x03 /* (to 0x0158 state 322) */, +/* pos 0154: 317 */ /* terminal 147 */ 0x93, + /* terminal 149 */ 0x95, +/* pos 0156: 319 */ /* terminal 148 */ 0x94, + /* terminal 159 */ 0x9F, +/* pos 0158: 322 */ /* terminal 150 */ 0x96, + /* terminal 151 */ 0x97, +/* pos 015a: 325 */ /* 0 */ 0x01 /* (to 0x015C state 326) */, + /* 1 */ 0x08 /* (to 0x016A state 338) */, +/* pos 015c: 326 */ /* terminal 152 */ 0x98, + /* terminal 155 */ 0x9B, +/* pos 015e: 328 */ /* 0 */ 0x42 /* (to 0x01E2 state 465) */, + /* 1 */ 0x01 /* (to 0x0160 state 329) */, +/* pos 0160: 329 */ /* 0 */ 0x01 /* (to 0x0162 state 330) */, + /* 1 */ 0x0C /* (to 0x0178 state 355) */, +/* pos 0162: 330 */ /* terminal 153 */ 0x99, + /* terminal 161 */ 0xA1, +/* pos 0164: 332 */ /* 0 */ 0x01 /* (to 0x0166 state 333) */, + /* 1 */ 0x05 /* (to 0x016E state 347) */, +/* pos 0166: 333 */ /* 0 */ 0x01 /* (to 0x0168 state 334) */, + /* 1 */ 0x03 /* (to 0x016C state 342) */, +/* pos 0168: 334 */ /* terminal 154 */ 0x9A, + /* terminal 156 */ 0x9C, +/* pos 016a: 338 */ /* terminal 157 */ 0x9D, + /* terminal 158 */ 0x9E, +/* pos 016c: 342 */ /* terminal 160 */ 0xA0, + /* terminal 163 */ 0xA3, +/* pos 016e: 347 */ /* 0 */ 0x01 /* (to 0x0170 state 348) */, + /* 1 */ 0x07 /* (to 0x017C state 360) */, +/* pos 0170: 348 */ /* terminal 164 */ 0xA4, + /* terminal 169 */ 0xA9, +/* pos 0172: 350 */ /* 0 */ 0x01 /* (to 0x0174 state 351) */, + /* 1 */ 0x09 /* (to 0x0184 state 369) */, +/* pos 0174: 351 */ /* 0 */ 0x01 /* (to 0x0176 state 352) */, + /* 1 */ 0x03 /* (to 0x017A state 357) */, +/* pos 0176: 352 */ /* terminal 165 */ 0xA5, + /* terminal 166 */ 0xA6, +/* pos 0178: 355 */ /* terminal 167 */ 0xA7, + /* terminal 172 */ 0xAC, +/* pos 017a: 357 */ /* terminal 168 */ 0xA8, + /* terminal 174 */ 0xAE, +/* pos 017c: 360 */ /* terminal 170 */ 0xAA, + /* terminal 173 */ 0xAD, +/* pos 017e: 362 */ /* 0 */ 0x01 /* (to 0x0180 state 363) */, + /* 1 */ 0x1B /* (to 0x01B4 state 417) */, +/* pos 0180: 363 */ /* 0 */ 0x01 /* (to 0x0182 state 364) */, + /* 1 */ 0x2A /* (to 0x01D4 state 449) */, +/* pos 0182: 364 */ /* terminal 171 */ 0xAB, + /* terminal 206 */ 0xCE, +/* pos 0184: 369 */ /* 0 */ 0x01 /* (to 0x0186 state 370) */, + /* 1 */ 0x09 /* (to 0x0196 state 385) */, +/* pos 0186: 370 */ /* terminal 175 */ 0xAF, + /* terminal 180 */ 0xB4, +/* pos 0188: 372 */ /* 0 */ 0x01 /* (to 0x018A state 373) */, + /* 1 */ 0x27 /* (to 0x01D6 state 451) */, +/* pos 018a: 373 */ /* 0 */ 0x01 /* (to 0x018C state 374) */, + /* 1 */ 0x05 /* (to 0x0194 state 381) */, +/* pos 018c: 374 */ /* terminal 176 */ 0xB0, + /* terminal 177 */ 0xB1, +/* pos 018e: 377 */ /* 0 */ 0x01 /* (to 0x0190 state 378) */, + /* 1 */ 0x07 /* (to 0x019C state 393) */, +/* pos 0190: 378 */ /* 0 */ 0x01 /* (to 0x0192 state 379) */, + /* 1 */ 0x05 /* (to 0x019A state 390) */, +/* pos 0192: 379 */ /* terminal 178 */ 0xB2, + /* terminal 181 */ 0xB5, +/* pos 0194: 381 */ /* terminal 179 */ 0xB3, + /* terminal 209 */ 0xD1, +/* pos 0196: 385 */ /* terminal 182 */ 0xB6, + /* terminal 183 */ 0xB7, +/* pos 0198: 388 */ /* terminal 184 */ 0xB8, + /* terminal 194 */ 0xC2, +/* pos 019a: 390 */ /* terminal 185 */ 0xB9, + /* terminal 186 */ 0xBA, +/* pos 019c: 393 */ /* 0 */ 0x01 /* (to 0x019E state 394) */, + /* 1 */ 0x04 /* (to 0x01A4 state 400) */, +/* pos 019e: 394 */ /* terminal 187 */ 0xBB, + /* terminal 189 */ 0xBD, +/* pos 01a0: 396 */ /* 0 */ 0x01 /* (to 0x01A2 state 397) */, + /* 1 */ 0x07 /* (to 0x01AE state 412) */, +/* pos 01a2: 397 */ /* terminal 188 */ 0xBC, + /* terminal 191 */ 0xBF, +/* pos 01a4: 400 */ /* terminal 190 */ 0xBE, + /* terminal 196 */ 0xC4, +/* pos 01a6: 403 */ /* 0 */ 0x01 /* (to 0x01A8 state 404) */, + /* 1 */ 0x0D /* (to 0x01C0 state 427) */, +/* pos 01a8: 404 */ /* 0 */ 0x01 /* (to 0x01AA state 405) */, + /* 1 */ 0x0A /* (to 0x01BC state 424) */, +/* pos 01aa: 405 */ /* 0 */ 0x01 /* (to 0x01AC state 406) */, + /* 1 */ 0x08 /* (to 0x01BA state 421) */, +/* pos 01ac: 406 */ /* terminal 192 */ 0xC0, + /* terminal 193 */ 0xC1, +/* pos 01ae: 412 */ /* terminal 197 */ 0xC5, + /* terminal 231 */ 0xE7, +/* pos 01b0: 414 */ /* 0 */ 0x01 /* (to 0x01B2 state 415) */, + /* 1 */ 0x1B /* (to 0x01E6 state 475) */, +/* pos 01b2: 415 */ /* terminal 198 */ 0xC6, + /* terminal 228 */ 0xE4, +/* pos 01b4: 417 */ /* 0 */ 0x1B /* (to 0x01EA state 481) */, + /* 1 */ 0x01 /* (to 0x01B6 state 418) */, +/* pos 01b6: 418 */ /* 0 */ 0x01 /* (to 0x01B8 state 419) */, + /* 1 */ 0x19 /* (to 0x01E8 state 478) */, +/* pos 01b8: 419 */ /* terminal 199 */ 0xC7, + /* terminal 207 */ 0xCF, +/* pos 01ba: 421 */ /* terminal 200 */ 0xC8, + /* terminal 201 */ 0xC9, +/* pos 01bc: 424 */ /* 0 */ 0x01 /* (to 0x01BE state 425) */, + /* 1 */ 0x06 /* (to 0x01C8 state 438) */, +/* pos 01be: 425 */ /* terminal 202 */ 0xCA, + /* terminal 205 */ 0xCD, +/* pos 01c0: 427 */ /* 0 */ 0x0D /* (to 0x01DA state 455) */, + /* 1 */ 0x01 /* (to 0x01C2 state 428) */, +/* pos 01c2: 428 */ /* 0 */ 0x17 /* (to 0x01F0 state 490) */, + /* 1 */ 0x01 /* (to 0x01C4 state 429) */, +/* pos 01c4: 429 */ /* terminal 255 */ 0xFF, + /* 1 */ 0x01 /* (to 0x01C6 state 430) */, +/* pos 01c6: 430 */ /* terminal 203 */ 0xCB, + /* terminal 204 */ 0xCC, +/* pos 01c8: 438 */ /* terminal 210 */ 0xD2, + /* terminal 213 */ 0xD5, +/* pos 01ca: 440 */ /* 0 */ 0x01 /* (to 0x01CC state 441) */, + /* 1 */ 0x14 /* (to 0x01F2 state 494) */, +/* pos 01cc: 441 */ /* 0 */ 0x01 /* (to 0x01CE state 442) */, + /* 1 */ 0x09 /* (to 0x01DE state 461) */, +/* pos 01ce: 442 */ /* 0 */ 0x01 /* (to 0x01D0 state 443) */, + /* 1 */ 0x02 /* (to 0x01D2 state 447) */, +/* pos 01d0: 443 */ /* terminal 211 */ 0xD3, + /* terminal 212 */ 0xD4, +/* pos 01d2: 447 */ /* terminal 214 */ 0xD6, + /* terminal 221 */ 0xDD, +/* pos 01d4: 449 */ /* terminal 215 */ 0xD7, + /* terminal 225 */ 0xE1, +/* pos 01d6: 451 */ /* 0 */ 0x01 /* (to 0x01D8 state 452) */, + /* 1 */ 0x07 /* (to 0x01E4 state 469) */, +/* pos 01d8: 452 */ /* terminal 216 */ 0xD8, + /* terminal 217 */ 0xD9, +/* pos 01da: 455 */ /* 0 */ 0x01 /* (to 0x01DC state 456) */, + /* 1 */ 0x09 /* (to 0x01EC state 484) */, +/* pos 01dc: 456 */ /* terminal 218 */ 0xDA, + /* terminal 219 */ 0xDB, +/* pos 01de: 461 */ /* 0 */ 0x01 /* (to 0x01E0 state 462) */, + /* 1 */ 0x08 /* (to 0x01EE state 488) */, +/* pos 01e0: 462 */ /* terminal 222 */ 0xDE, + /* terminal 223 */ 0xDF, +/* pos 01e2: 465 */ /* terminal 224 */ 0xE0, + /* terminal 226 */ 0xE2, +/* pos 01e4: 469 */ /* terminal 227 */ 0xE3, + /* terminal 229 */ 0xE5, +/* pos 01e6: 475 */ /* terminal 232 */ 0xE8, + /* terminal 233 */ 0xE9, +/* pos 01e8: 478 */ /* terminal 234 */ 0xEA, + /* terminal 235 */ 0xEB, +/* pos 01ea: 481 */ /* terminal 236 */ 0xEC, + /* terminal 237 */ 0xED, +/* pos 01ec: 484 */ /* terminal 238 */ 0xEE, + /* terminal 240 */ 0xF0, +/* pos 01ee: 488 */ /* terminal 241 */ 0xF1, + /* terminal 244 */ 0xF4, +/* pos 01f0: 490 */ /* terminal 242 */ 0xF2, + /* terminal 243 */ 0xF3, +/* pos 01f2: 494 */ /* 0 */ 0x01 /* (to 0x01F4 state 495) */, + /* 1 */ 0x04 /* (to 0x01FA state 503) */, +/* pos 01f4: 495 */ /* 0 */ 0x01 /* (to 0x01F6 state 496) */, + /* 1 */ 0x02 /* (to 0x01F8 state 499) */, +/* pos 01f6: 496 */ /* terminal 245 */ 0xF5, + /* terminal 246 */ 0xF6, +/* pos 01f8: 499 */ /* terminal 247 */ 0xF7, + /* terminal 248 */ 0xF8, +/* pos 01fa: 503 */ /* 0 */ 0x01 /* (to 0x01FC state 504) */, + /* 1 */ 0x02 /* (to 0x01FE state 507) */, +/* pos 01fc: 504 */ /* terminal 250 */ 0xFA, + /* terminal 251 */ 0xFB, +/* pos 01fe: 507 */ /* terminal 252 */ 0xFC, + /* terminal 253 */ 0xFD, +/* total size 512 bytes, biggest jump 200/256, fails=0 */ +}; + + static unsigned char lextable_terms[] = { + + 0x00, 0x00, 0x00, 0x03, 0x01, 0x00, 0x03, 0x00, + 0x34, 0x0f, 0x43, 0x03, 0xf1, 0x3c, 0xfc, 0x3c, + 0x0f, 0x30, 0x37, 0xf7, 0x0f, 0xc3, 0xcf, 0x03, + 0x3c, 0xfc, 0xc0, 0xf3, 0xf0, 0x3c, 0xfc, 0xf0, + 0xcf, 0xfc, 0xcc, 0xff, 0xfc, 0x0d, 0x34, 0xcc, + 0xcf, 0x33, 0xf0, 0x33, 0x0c, 0x3f, 0xc3, 0x3f, + 0xcc, 0x30, 0xfc, 0xcf, 0x3c, 0xf0, 0x0c, 0xcf, + 0xd0, 0x03, 0x3f, 0x33, 0xff, 0xff, 0xc3, 0xf3, +}; + +/* state that points to 0x100 for disambiguation with 0x0 */ +#define HUFTABLE_0x100_PREV 118 diff --git a/src/engine/external/libwebsockets/lextable-strings.h b/src/engine/external/libwebsockets/lextable-strings.h new file mode 100644 index 0000000..c0f1f2e --- /dev/null +++ b/src/engine/external/libwebsockets/lextable-strings.h @@ -0,0 +1,86 @@ +/* set of parsable strings -- ALL LOWER CASE */ + +static const char *set[] = { + "get ", + "post ", + "options ", + "host:", + "connection:", + "upgrade:", + "origin:", + "sec-websocket-draft:", + "\x0d\x0a", + + "sec-websocket-extensions:", + "sec-websocket-key1:", + "sec-websocket-key2:", + "sec-websocket-protocol:", + + "sec-websocket-accept:", + "sec-websocket-nonce:", + "http/1.1 ", + "http2-settings:", + + "accept:", + "access-control-request-headers:", + "if-modified-since:", + "if-none-match:", + "accept-encoding:", + "accept-language:", + "pragma:", + "cache-control:", + "authorization:", + "cookie:", + "content-length:", + "content-type:", + "date:", + "range:", + "referer:", + "sec-websocket-key:", + "sec-websocket-version:", + "sec-websocket-origin:", + + ":authority:", + ":method:", + ":path:", + ":scheme:", + ":status:", + + "accept-charset:", + "accept-ranges:", + "access-control-allow-origin:", + "age:", + "allow:", + "content-disposition:", + "content-encoding:", + "content-language:", + "content-location:", + "content-range:", + "etag:", + "expect:", + "expires:", + "from:", + "if-match:", + "if-range:", + "if-unmodified-since:", + "last-modified:", + "link:", + "location:", + "max-forwards:", + "proxy-authenticate:", + "proxy-authorization:", + "refresh:", + "retry-after:", + "server:", + "set-cookie:", + "strict-transport-security:", + "transfer-encoding:", + "user-agent:", + "vary:", + "via:", + "www-authenticate:", + "proxy ", + + "", /* not matchable */ + +}; diff --git a/src/engine/external/libwebsockets/lextable.h b/src/engine/external/libwebsockets/lextable.h new file mode 100644 index 0000000..80d318e --- /dev/null +++ b/src/engine/external/libwebsockets/lextable.h @@ -0,0 +1,745 @@ +/* pos 0000: 0 */ 0x67 /* 'g' */, 0x3D, 0x00 /* (to 0x003D state 1) */, + 0x70 /* 'p' */, 0x3F, 0x00 /* (to 0x0042 state 5) */, + 0x6F /* 'o' */, 0x48, 0x00 /* (to 0x004E state 10) */, + 0x68 /* 'h' */, 0x54, 0x00 /* (to 0x005D state 18) */, + 0x63 /* 'c' */, 0x5D, 0x00 /* (to 0x0069 state 23) */, + 0x75 /* 'u' */, 0x78, 0x00 /* (to 0x0087 state 34) */, + 0x73 /* 's' */, 0x8B, 0x00 /* (to 0x009D state 48) */, + 0x0D /* '.' */, 0xC4, 0x00 /* (to 0x00D9 state 68) */, + 0x61 /* 'a' */, 0x16, 0x01 /* (to 0x012E state 129) */, + 0x69 /* 'i' */, 0x55, 0x01 /* (to 0x0170 state 163) */, + 0x64 /* 'd' */, 0xFE, 0x01 /* (to 0x021C state 265) */, + 0x72 /* 'r' */, 0x01, 0x02 /* (to 0x0222 state 270) */, + 0x3A /* ':' */, 0x32, 0x02 /* (to 0x0256 state 299) */, + 0x65 /* 'e' */, 0xC3, 0x02 /* (to 0x02EA state 414) */, + 0x66 /* 'f' */, 0xDF, 0x02 /* (to 0x0309 state 430) */, + 0x6C /* 'l' */, 0x01, 0x03 /* (to 0x032E state 463) */, + 0x6D /* 'm' */, 0x24, 0x03 /* (to 0x0354 state 489) */, + 0x74 /* 't' */, 0x93, 0x03 /* (to 0x03C6 state 583) */, + 0x76 /* 'v' */, 0xAE, 0x03 /* (to 0x03E4 state 611) */, + 0x77 /* 'w' */, 0xBB, 0x03 /* (to 0x03F4 state 619) */, + 0x08, /* fail */ +/* pos 003d: 1 */ 0xE5 /* 'e' -> */, +/* pos 003e: 2 */ 0xF4 /* 't' -> */, +/* pos 003f: 3 */ 0xA0 /* ' ' -> */, +/* pos 0040: 4 */ 0x00, 0x00 /* - terminal marker 0 - */, +/* pos 0042: 5 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x0049 state 6) */, + 0x72 /* 'r' */, 0x7D, 0x01 /* (to 0x01C2 state 211) */, + 0x08, /* fail */ +/* pos 0049: 6 */ 0xF3 /* 's' -> */, +/* pos 004a: 7 */ 0xF4 /* 't' -> */, +/* pos 004b: 8 */ 0xA0 /* ' ' -> */, +/* pos 004c: 9 */ 0x00, 0x01 /* - terminal marker 1 - */, +/* pos 004e: 10 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x0055 state 11) */, + 0x72 /* 'r' */, 0x45, 0x00 /* (to 0x0096 state 42) */, + 0x08, /* fail */ +/* pos 0055: 11 */ 0xF4 /* 't' -> */, +/* pos 0056: 12 */ 0xE9 /* 'i' -> */, +/* pos 0057: 13 */ 0xEF /* 'o' -> */, +/* pos 0058: 14 */ 0xEE /* 'n' -> */, +/* pos 0059: 15 */ 0xF3 /* 's' -> */, +/* pos 005a: 16 */ 0xA0 /* ' ' -> */, +/* pos 005b: 17 */ 0x00, 0x02 /* - terminal marker 2 - */, +/* pos 005d: 18 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x0064 state 19) */, + 0x74 /* 't' */, 0xB3, 0x00 /* (to 0x0113 state 110) */, + 0x08, /* fail */ +/* pos 0064: 19 */ 0xF3 /* 's' -> */, +/* pos 0065: 20 */ 0xF4 /* 't' -> */, +/* pos 0066: 21 */ 0xBA /* ':' -> */, +/* pos 0067: 22 */ 0x00, 0x03 /* - terminal marker 3 - */, +/* pos 0069: 23 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x0070 state 24) */, + 0x61 /* 'a' */, 0x63, 0x01 /* (to 0x01CF state 217) */, + 0x08, /* fail */ +/* pos 0070: 24 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x0077 state 25) */, + 0x6F /* 'o' */, 0x78, 0x01 /* (to 0x01EB state 243) */, + 0x08, /* fail */ +/* pos 0077: 25 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x007E state 26) */, + 0x74 /* 't' */, 0x77, 0x01 /* (to 0x01F1 state 248) */, + 0x08, /* fail */ +/* pos 007e: 26 */ 0xE5 /* 'e' -> */, +/* pos 007f: 27 */ 0xE3 /* 'c' -> */, +/* pos 0080: 28 */ 0xF4 /* 't' -> */, +/* pos 0081: 29 */ 0xE9 /* 'i' -> */, +/* pos 0082: 30 */ 0xEF /* 'o' -> */, +/* pos 0083: 31 */ 0xEE /* 'n' -> */, +/* pos 0084: 32 */ 0xBA /* ':' -> */, +/* pos 0085: 33 */ 0x00, 0x04 /* - terminal marker 4 - */, +/* pos 0087: 34 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x008E state 35) */, + 0x73 /* 's' */, 0x4F, 0x03 /* (to 0x03D9 state 601) */, + 0x08, /* fail */ +/* pos 008e: 35 */ 0xE7 /* 'g' -> */, +/* pos 008f: 36 */ 0xF2 /* 'r' -> */, +/* pos 0090: 37 */ 0xE1 /* 'a' -> */, +/* pos 0091: 38 */ 0xE4 /* 'd' -> */, +/* pos 0092: 39 */ 0xE5 /* 'e' -> */, +/* pos 0093: 40 */ 0xBA /* ':' -> */, +/* pos 0094: 41 */ 0x00, 0x05 /* - terminal marker 5 - */, +/* pos 0096: 42 */ 0xE9 /* 'i' -> */, +/* pos 0097: 43 */ 0xE7 /* 'g' -> */, +/* pos 0098: 44 */ 0xE9 /* 'i' -> */, +/* pos 0099: 45 */ 0xEE /* 'n' -> */, +/* pos 009a: 46 */ 0xBA /* ':' -> */, +/* pos 009b: 47 */ 0x00, 0x06 /* - terminal marker 6 - */, +/* pos 009d: 48 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x00A4 state 49) */, + 0x74 /* 't' */, 0x0C, 0x03 /* (to 0x03AC state 558) */, + 0x08, /* fail */ +/* pos 00a4: 49 */ 0x63 /* 'c' */, 0x0A, 0x00 /* (to 0x00AE state 50) */, + 0x72 /* 'r' */, 0xF5, 0x02 /* (to 0x039C state 544) */, + 0x74 /* 't' */, 0xF8, 0x02 /* (to 0x03A2 state 549) */, + 0x08, /* fail */ +/* pos 00ae: 50 */ 0xAD /* '-' -> */, +/* pos 00af: 51 */ 0xF7 /* 'w' -> */, +/* pos 00b0: 52 */ 0xE5 /* 'e' -> */, +/* pos 00b1: 53 */ 0xE2 /* 'b' -> */, +/* pos 00b2: 54 */ 0xF3 /* 's' -> */, +/* pos 00b3: 55 */ 0xEF /* 'o' -> */, +/* pos 00b4: 56 */ 0xE3 /* 'c' -> */, +/* pos 00b5: 57 */ 0xEB /* 'k' -> */, +/* pos 00b6: 58 */ 0xE5 /* 'e' -> */, +/* pos 00b7: 59 */ 0xF4 /* 't' -> */, +/* pos 00b8: 60 */ 0xAD /* '-' -> */, +/* pos 00b9: 61 */ 0x64 /* 'd' */, 0x19, 0x00 /* (to 0x00D2 state 62) */, + 0x65 /* 'e' */, 0x20, 0x00 /* (to 0x00DC state 70) */, + 0x6B /* 'k' */, 0x29, 0x00 /* (to 0x00E8 state 81) */, + 0x70 /* 'p' */, 0x38, 0x00 /* (to 0x00FA state 88) */, + 0x61 /* 'a' */, 0x3F, 0x00 /* (to 0x0104 state 97) */, + 0x6E /* 'n' */, 0x44, 0x00 /* (to 0x010C state 104) */, + 0x76 /* 'v' */, 0x7A, 0x01 /* (to 0x0245 state 284) */, + 0x6F /* 'o' */, 0x80, 0x01 /* (to 0x024E state 292) */, + 0x08, /* fail */ +/* pos 00d2: 62 */ 0xF2 /* 'r' -> */, +/* pos 00d3: 63 */ 0xE1 /* 'a' -> */, +/* pos 00d4: 64 */ 0xE6 /* 'f' -> */, +/* pos 00d5: 65 */ 0xF4 /* 't' -> */, +/* pos 00d6: 66 */ 0xBA /* ':' -> */, +/* pos 00d7: 67 */ 0x00, 0x07 /* - terminal marker 7 - */, +/* pos 00d9: 68 */ 0x8A /* '.' -> */, +/* pos 00da: 69 */ 0x00, 0x08 /* - terminal marker 8 - */, +/* pos 00dc: 70 */ 0xF8 /* 'x' -> */, +/* pos 00dd: 71 */ 0xF4 /* 't' -> */, +/* pos 00de: 72 */ 0xE5 /* 'e' -> */, +/* pos 00df: 73 */ 0xEE /* 'n' -> */, +/* pos 00e0: 74 */ 0xF3 /* 's' -> */, +/* pos 00e1: 75 */ 0xE9 /* 'i' -> */, +/* pos 00e2: 76 */ 0xEF /* 'o' -> */, +/* pos 00e3: 77 */ 0xEE /* 'n' -> */, +/* pos 00e4: 78 */ 0xF3 /* 's' -> */, +/* pos 00e5: 79 */ 0xBA /* ':' -> */, +/* pos 00e6: 80 */ 0x00, 0x09 /* - terminal marker 9 - */, +/* pos 00e8: 81 */ 0xE5 /* 'e' -> */, +/* pos 00e9: 82 */ 0xF9 /* 'y' -> */, +/* pos 00ea: 83 */ 0x31 /* '1' */, 0x0A, 0x00 /* (to 0x00F4 state 84) */, + 0x32 /* '2' */, 0x0A, 0x00 /* (to 0x00F7 state 86) */, + 0x3A /* ':' */, 0x53, 0x01 /* (to 0x0243 state 283) */, + 0x08, /* fail */ +/* pos 00f4: 84 */ 0xBA /* ':' -> */, +/* pos 00f5: 85 */ 0x00, 0x0A /* - terminal marker 10 - */, +/* pos 00f7: 86 */ 0xBA /* ':' -> */, +/* pos 00f8: 87 */ 0x00, 0x0B /* - terminal marker 11 - */, +/* pos 00fa: 88 */ 0xF2 /* 'r' -> */, +/* pos 00fb: 89 */ 0xEF /* 'o' -> */, +/* pos 00fc: 90 */ 0xF4 /* 't' -> */, +/* pos 00fd: 91 */ 0xEF /* 'o' -> */, +/* pos 00fe: 92 */ 0xE3 /* 'c' -> */, +/* pos 00ff: 93 */ 0xEF /* 'o' -> */, +/* pos 0100: 94 */ 0xEC /* 'l' -> */, +/* pos 0101: 95 */ 0xBA /* ':' -> */, +/* pos 0102: 96 */ 0x00, 0x0C /* - terminal marker 12 - */, +/* pos 0104: 97 */ 0xE3 /* 'c' -> */, +/* pos 0105: 98 */ 0xE3 /* 'c' -> */, +/* pos 0106: 99 */ 0xE5 /* 'e' -> */, +/* pos 0107: 100 */ 0xF0 /* 'p' -> */, +/* pos 0108: 101 */ 0xF4 /* 't' -> */, +/* pos 0109: 102 */ 0xBA /* ':' -> */, +/* pos 010a: 103 */ 0x00, 0x0D /* - terminal marker 13 - */, +/* pos 010c: 104 */ 0xEF /* 'o' -> */, +/* pos 010d: 105 */ 0xEE /* 'n' -> */, +/* pos 010e: 106 */ 0xE3 /* 'c' -> */, +/* pos 010f: 107 */ 0xE5 /* 'e' -> */, +/* pos 0110: 108 */ 0xBA /* ':' -> */, +/* pos 0111: 109 */ 0x00, 0x0E /* - terminal marker 14 - */, +/* pos 0113: 110 */ 0xF4 /* 't' -> */, +/* pos 0114: 111 */ 0xF0 /* 'p' -> */, +/* pos 0115: 112 */ 0x2F /* '/' */, 0x07, 0x00 /* (to 0x011C state 113) */, + 0x32 /* '2' */, 0x0A, 0x00 /* (to 0x0122 state 118) */, + 0x08, /* fail */ +/* pos 011c: 113 */ 0xB1 /* '1' -> */, +/* pos 011d: 114 */ 0xAE /* '.' -> */, +/* pos 011e: 115 */ 0xB1 /* '1' -> */, +/* pos 011f: 116 */ 0xA0 /* ' ' -> */, +/* pos 0120: 117 */ 0x00, 0x0F /* - terminal marker 15 - */, +/* pos 0122: 118 */ 0xAD /* '-' -> */, +/* pos 0123: 119 */ 0xF3 /* 's' -> */, +/* pos 0124: 120 */ 0xE5 /* 'e' -> */, +/* pos 0125: 121 */ 0xF4 /* 't' -> */, +/* pos 0126: 122 */ 0xF4 /* 't' -> */, +/* pos 0127: 123 */ 0xE9 /* 'i' -> */, +/* pos 0128: 124 */ 0xEE /* 'n' -> */, +/* pos 0129: 125 */ 0xE7 /* 'g' -> */, +/* pos 012a: 126 */ 0xF3 /* 's' -> */, +/* pos 012b: 127 */ 0xBA /* ':' -> */, +/* pos 012c: 128 */ 0x00, 0x10 /* - terminal marker 16 - */, +/* pos 012e: 129 */ 0x63 /* 'c' */, 0x0D, 0x00 /* (to 0x013B state 130) */, + 0x75 /* 'u' */, 0xAC, 0x00 /* (to 0x01DD state 230) */, + 0x67 /* 'g' */, 0x7C, 0x01 /* (to 0x02B0 state 363) */, + 0x6C /* 'l' */, 0x7D, 0x01 /* (to 0x02B4 state 366) */, + 0x08, /* fail */ +/* pos 013b: 130 */ 0xE3 /* 'c' -> */, +/* pos 013c: 131 */ 0xE5 /* 'e' -> */, +/* pos 013d: 132 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x0144 state 133) */, + 0x73 /* 's' */, 0x0E, 0x00 /* (to 0x014E state 136) */, + 0x08, /* fail */ +/* pos 0144: 133 */ 0xF4 /* 't' -> */, +/* pos 0145: 134 */ 0x3A /* ':' */, 0x07, 0x00 /* (to 0x014C state 135) */, + 0x2D /* '-' */, 0x59, 0x00 /* (to 0x01A1 state 192) */, + 0x08, /* fail */ +/* pos 014c: 135 */ 0x00, 0x11 /* - terminal marker 17 - */, +/* pos 014e: 136 */ 0xF3 /* 's' -> */, +/* pos 014f: 137 */ 0xAD /* '-' -> */, +/* pos 0150: 138 */ 0xE3 /* 'c' -> */, +/* pos 0151: 139 */ 0xEF /* 'o' -> */, +/* pos 0152: 140 */ 0xEE /* 'n' -> */, +/* pos 0153: 141 */ 0xF4 /* 't' -> */, +/* pos 0154: 142 */ 0xF2 /* 'r' -> */, +/* pos 0155: 143 */ 0xEF /* 'o' -> */, +/* pos 0156: 144 */ 0xEC /* 'l' -> */, +/* pos 0157: 145 */ 0xAD /* '-' -> */, +/* pos 0158: 146 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x015F state 147) */, + 0x61 /* 'a' */, 0x47, 0x01 /* (to 0x02A2 state 350) */, + 0x08, /* fail */ +/* pos 015f: 147 */ 0xE5 /* 'e' -> */, +/* pos 0160: 148 */ 0xF1 /* 'q' -> */, +/* pos 0161: 149 */ 0xF5 /* 'u' -> */, +/* pos 0162: 150 */ 0xE5 /* 'e' -> */, +/* pos 0163: 151 */ 0xF3 /* 's' -> */, +/* pos 0164: 152 */ 0xF4 /* 't' -> */, +/* pos 0165: 153 */ 0xAD /* '-' -> */, +/* pos 0166: 154 */ 0xE8 /* 'h' -> */, +/* pos 0167: 155 */ 0xE5 /* 'e' -> */, +/* pos 0168: 156 */ 0xE1 /* 'a' -> */, +/* pos 0169: 157 */ 0xE4 /* 'd' -> */, +/* pos 016a: 158 */ 0xE5 /* 'e' -> */, +/* pos 016b: 159 */ 0xF2 /* 'r' -> */, +/* pos 016c: 160 */ 0xF3 /* 's' -> */, +/* pos 016d: 161 */ 0xBA /* ':' -> */, +/* pos 016e: 162 */ 0x00, 0x12 /* - terminal marker 18 - */, +/* pos 0170: 163 */ 0xE6 /* 'f' -> */, +/* pos 0171: 164 */ 0xAD /* '-' -> */, +/* pos 0172: 165 */ 0x6D /* 'm' */, 0x0D, 0x00 /* (to 0x017F state 166) */, + 0x6E /* 'n' */, 0x20, 0x00 /* (to 0x0195 state 181) */, + 0x72 /* 'r' */, 0x9D, 0x01 /* (to 0x0315 state 440) */, + 0x75 /* 'u' */, 0xA1, 0x01 /* (to 0x031C state 446) */, + 0x08, /* fail */ +/* pos 017f: 166 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x0186 state 167) */, + 0x61 /* 'a' */, 0x8D, 0x01 /* (to 0x030F state 435) */, + 0x08, /* fail */ +/* pos 0186: 167 */ 0xE4 /* 'd' -> */, +/* pos 0187: 168 */ 0xE9 /* 'i' -> */, +/* pos 0188: 169 */ 0xE6 /* 'f' -> */, +/* pos 0189: 170 */ 0xE9 /* 'i' -> */, +/* pos 018a: 171 */ 0xE5 /* 'e' -> */, +/* pos 018b: 172 */ 0xE4 /* 'd' -> */, +/* pos 018c: 173 */ 0xAD /* '-' -> */, +/* pos 018d: 174 */ 0xF3 /* 's' -> */, +/* pos 018e: 175 */ 0xE9 /* 'i' -> */, +/* pos 018f: 176 */ 0xEE /* 'n' -> */, +/* pos 0190: 177 */ 0xE3 /* 'c' -> */, +/* pos 0191: 178 */ 0xE5 /* 'e' -> */, +/* pos 0192: 179 */ 0xBA /* ':' -> */, +/* pos 0193: 180 */ 0x00, 0x13 /* - terminal marker 19 - */, +/* pos 0195: 181 */ 0xEF /* 'o' -> */, +/* pos 0196: 182 */ 0xEE /* 'n' -> */, +/* pos 0197: 183 */ 0xE5 /* 'e' -> */, +/* pos 0198: 184 */ 0xAD /* '-' -> */, +/* pos 0199: 185 */ 0xED /* 'm' -> */, +/* pos 019a: 186 */ 0xE1 /* 'a' -> */, +/* pos 019b: 187 */ 0xF4 /* 't' -> */, +/* pos 019c: 188 */ 0xE3 /* 'c' -> */, +/* pos 019d: 189 */ 0xE8 /* 'h' -> */, +/* pos 019e: 190 */ 0xBA /* ':' -> */, +/* pos 019f: 191 */ 0x00, 0x14 /* - terminal marker 20 - */, +/* pos 01a1: 192 */ 0x65 /* 'e' */, 0x0D, 0x00 /* (to 0x01AE state 193) */, + 0x6C /* 'l' */, 0x14, 0x00 /* (to 0x01B8 state 202) */, + 0x63 /* 'c' */, 0xEA, 0x00 /* (to 0x0291 state 335) */, + 0x72 /* 'r' */, 0xF0, 0x00 /* (to 0x029A state 343) */, + 0x08, /* fail */ +/* pos 01ae: 193 */ 0xEE /* 'n' -> */, +/* pos 01af: 194 */ 0xE3 /* 'c' -> */, +/* pos 01b0: 195 */ 0xEF /* 'o' -> */, +/* pos 01b1: 196 */ 0xE4 /* 'd' -> */, +/* pos 01b2: 197 */ 0xE9 /* 'i' -> */, +/* pos 01b3: 198 */ 0xEE /* 'n' -> */, +/* pos 01b4: 199 */ 0xE7 /* 'g' -> */, +/* pos 01b5: 200 */ 0xBA /* ':' -> */, +/* pos 01b6: 201 */ 0x00, 0x15 /* - terminal marker 21 - */, +/* pos 01b8: 202 */ 0xE1 /* 'a' -> */, +/* pos 01b9: 203 */ 0xEE /* 'n' -> */, +/* pos 01ba: 204 */ 0xE7 /* 'g' -> */, +/* pos 01bb: 205 */ 0xF5 /* 'u' -> */, +/* pos 01bc: 206 */ 0xE1 /* 'a' -> */, +/* pos 01bd: 207 */ 0xE7 /* 'g' -> */, +/* pos 01be: 208 */ 0xE5 /* 'e' -> */, +/* pos 01bf: 209 */ 0xBA /* ':' -> */, +/* pos 01c0: 210 */ 0x00, 0x16 /* - terminal marker 22 - */, +/* pos 01c2: 211 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x01C9 state 212) */, + 0x6F /* 'o' */, 0x9D, 0x01 /* (to 0x0362 state 502) */, + 0x08, /* fail */ +/* pos 01c9: 212 */ 0xE7 /* 'g' -> */, +/* pos 01ca: 213 */ 0xED /* 'm' -> */, +/* pos 01cb: 214 */ 0xE1 /* 'a' -> */, +/* pos 01cc: 215 */ 0xBA /* ':' -> */, +/* pos 01cd: 216 */ 0x00, 0x17 /* - terminal marker 23 - */, +/* pos 01cf: 217 */ 0xE3 /* 'c' -> */, +/* pos 01d0: 218 */ 0xE8 /* 'h' -> */, +/* pos 01d1: 219 */ 0xE5 /* 'e' -> */, +/* pos 01d2: 220 */ 0xAD /* '-' -> */, +/* pos 01d3: 221 */ 0xE3 /* 'c' -> */, +/* pos 01d4: 222 */ 0xEF /* 'o' -> */, +/* pos 01d5: 223 */ 0xEE /* 'n' -> */, +/* pos 01d6: 224 */ 0xF4 /* 't' -> */, +/* pos 01d7: 225 */ 0xF2 /* 'r' -> */, +/* pos 01d8: 226 */ 0xEF /* 'o' -> */, +/* pos 01d9: 227 */ 0xEC /* 'l' -> */, +/* pos 01da: 228 */ 0xBA /* ':' -> */, +/* pos 01db: 229 */ 0x00, 0x18 /* - terminal marker 24 - */, +/* pos 01dd: 230 */ 0xF4 /* 't' -> */, +/* pos 01de: 231 */ 0xE8 /* 'h' -> */, +/* pos 01df: 232 */ 0xEF /* 'o' -> */, +/* pos 01e0: 233 */ 0xF2 /* 'r' -> */, +/* pos 01e1: 234 */ 0xE9 /* 'i' -> */, +/* pos 01e2: 235 */ 0xFA /* 'z' -> */, +/* pos 01e3: 236 */ 0xE1 /* 'a' -> */, +/* pos 01e4: 237 */ 0xF4 /* 't' -> */, +/* pos 01e5: 238 */ 0xE9 /* 'i' -> */, +/* pos 01e6: 239 */ 0xEF /* 'o' -> */, +/* pos 01e7: 240 */ 0xEE /* 'n' -> */, +/* pos 01e8: 241 */ 0xBA /* ':' -> */, +/* pos 01e9: 242 */ 0x00, 0x19 /* - terminal marker 25 - */, +/* pos 01eb: 243 */ 0xEB /* 'k' -> */, +/* pos 01ec: 244 */ 0xE9 /* 'i' -> */, +/* pos 01ed: 245 */ 0xE5 /* 'e' -> */, +/* pos 01ee: 246 */ 0xBA /* ':' -> */, +/* pos 01ef: 247 */ 0x00, 0x1A /* - terminal marker 26 - */, +/* pos 01f1: 248 */ 0xE5 /* 'e' -> */, +/* pos 01f2: 249 */ 0xEE /* 'n' -> */, +/* pos 01f3: 250 */ 0xF4 /* 't' -> */, +/* pos 01f4: 251 */ 0xAD /* '-' -> */, +/* pos 01f5: 252 */ 0x6C /* 'l' */, 0x10, 0x00 /* (to 0x0205 state 253) */, + 0x74 /* 't' */, 0x1E, 0x00 /* (to 0x0216 state 260) */, + 0x64 /* 'd' */, 0xBF, 0x00 /* (to 0x02BA state 371) */, + 0x65 /* 'e' */, 0xC9, 0x00 /* (to 0x02C7 state 383) */, + 0x72 /* 'r' */, 0xE2, 0x00 /* (to 0x02E3 state 408) */, + 0x08, /* fail */ +/* pos 0205: 253 */ 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x020F state 254) */, + 0x61 /* 'a' */, 0xC9, 0x00 /* (to 0x02D1 state 392) */, + 0x6F /* 'o' */, 0xCF, 0x00 /* (to 0x02DA state 400) */, + 0x08, /* fail */ +/* pos 020f: 254 */ 0xEE /* 'n' -> */, +/* pos 0210: 255 */ 0xE7 /* 'g' -> */, +/* pos 0211: 256 */ 0xF4 /* 't' -> */, +/* pos 0212: 257 */ 0xE8 /* 'h' -> */, +/* pos 0213: 258 */ 0xBA /* ':' -> */, +/* pos 0214: 259 */ 0x00, 0x1B /* - terminal marker 27 - */, +/* pos 0216: 260 */ 0xF9 /* 'y' -> */, +/* pos 0217: 261 */ 0xF0 /* 'p' -> */, +/* pos 0218: 262 */ 0xE5 /* 'e' -> */, +/* pos 0219: 263 */ 0xBA /* ':' -> */, +/* pos 021a: 264 */ 0x00, 0x1C /* - terminal marker 28 - */, +/* pos 021c: 265 */ 0xE1 /* 'a' -> */, +/* pos 021d: 266 */ 0xF4 /* 't' -> */, +/* pos 021e: 267 */ 0xE5 /* 'e' -> */, +/* pos 021f: 268 */ 0xBA /* ':' -> */, +/* pos 0220: 269 */ 0x00, 0x1D /* - terminal marker 29 - */, +/* pos 0222: 270 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x0229 state 271) */, + 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x022F state 276) */, + 0x08, /* fail */ +/* pos 0229: 271 */ 0xEE /* 'n' -> */, +/* pos 022a: 272 */ 0xE7 /* 'g' -> */, +/* pos 022b: 273 */ 0xE5 /* 'e' -> */, +/* pos 022c: 274 */ 0xBA /* ':' -> */, +/* pos 022d: 275 */ 0x00, 0x1E /* - terminal marker 30 - */, +/* pos 022f: 276 */ 0x66 /* 'f' */, 0x07, 0x00 /* (to 0x0236 state 277) */, + 0x74 /* 't' */, 0x5F, 0x01 /* (to 0x0391 state 534) */, + 0x08, /* fail */ +/* pos 0236: 277 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x023D state 278) */, + 0x72 /* 'r' */, 0x52, 0x01 /* (to 0x038B state 529) */, + 0x08, /* fail */ +/* pos 023d: 278 */ 0xF2 /* 'r' -> */, +/* pos 023e: 279 */ 0xE5 /* 'e' -> */, +/* pos 023f: 280 */ 0xF2 /* 'r' -> */, +/* pos 0240: 281 */ 0xBA /* ':' -> */, +/* pos 0241: 282 */ 0x00, 0x1F /* - terminal marker 31 - */, +/* pos 0243: 283 */ 0x00, 0x20 /* - terminal marker 32 - */, +/* pos 0245: 284 */ 0xE5 /* 'e' -> */, +/* pos 0246: 285 */ 0xF2 /* 'r' -> */, +/* pos 0247: 286 */ 0xF3 /* 's' -> */, +/* pos 0248: 287 */ 0xE9 /* 'i' -> */, +/* pos 0249: 288 */ 0xEF /* 'o' -> */, +/* pos 024a: 289 */ 0xEE /* 'n' -> */, +/* pos 024b: 290 */ 0xBA /* ':' -> */, +/* pos 024c: 291 */ 0x00, 0x21 /* - terminal marker 33 - */, +/* pos 024e: 292 */ 0xF2 /* 'r' -> */, +/* pos 024f: 293 */ 0xE9 /* 'i' -> */, +/* pos 0250: 294 */ 0xE7 /* 'g' -> */, +/* pos 0251: 295 */ 0xE9 /* 'i' -> */, +/* pos 0252: 296 */ 0xEE /* 'n' -> */, +/* pos 0253: 297 */ 0xBA /* ':' -> */, +/* pos 0254: 298 */ 0x00, 0x22 /* - terminal marker 34 - */, +/* pos 0256: 299 */ 0x61 /* 'a' */, 0x0D, 0x00 /* (to 0x0263 state 300) */, + 0x6D /* 'm' */, 0x15, 0x00 /* (to 0x026E state 310) */, + 0x70 /* 'p' */, 0x1A, 0x00 /* (to 0x0276 state 317) */, + 0x73 /* 's' */, 0x1D, 0x00 /* (to 0x027C state 322) */, + 0x08, /* fail */ +/* pos 0263: 300 */ 0xF5 /* 'u' -> */, +/* pos 0264: 301 */ 0xF4 /* 't' -> */, +/* pos 0265: 302 */ 0xE8 /* 'h' -> */, +/* pos 0266: 303 */ 0xEF /* 'o' -> */, +/* pos 0267: 304 */ 0xF2 /* 'r' -> */, +/* pos 0268: 305 */ 0xE9 /* 'i' -> */, +/* pos 0269: 306 */ 0xF4 /* 't' -> */, +/* pos 026a: 307 */ 0xF9 /* 'y' -> */, +/* pos 026b: 308 */ 0xBA /* ':' -> */, +/* pos 026c: 309 */ 0x00, 0x23 /* - terminal marker 35 - */, +/* pos 026e: 310 */ 0xE5 /* 'e' -> */, +/* pos 026f: 311 */ 0xF4 /* 't' -> */, +/* pos 0270: 312 */ 0xE8 /* 'h' -> */, +/* pos 0271: 313 */ 0xEF /* 'o' -> */, +/* pos 0272: 314 */ 0xE4 /* 'd' -> */, +/* pos 0273: 315 */ 0xBA /* ':' -> */, +/* pos 0274: 316 */ 0x00, 0x24 /* - terminal marker 36 - */, +/* pos 0276: 317 */ 0xE1 /* 'a' -> */, +/* pos 0277: 318 */ 0xF4 /* 't' -> */, +/* pos 0278: 319 */ 0xE8 /* 'h' -> */, +/* pos 0279: 320 */ 0xBA /* ':' -> */, +/* pos 027a: 321 */ 0x00, 0x25 /* - terminal marker 37 - */, +/* pos 027c: 322 */ 0x63 /* 'c' */, 0x07, 0x00 /* (to 0x0283 state 323) */, + 0x74 /* 't' */, 0x0B, 0x00 /* (to 0x028A state 329) */, + 0x08, /* fail */ +/* pos 0283: 323 */ 0xE8 /* 'h' -> */, +/* pos 0284: 324 */ 0xE5 /* 'e' -> */, +/* pos 0285: 325 */ 0xED /* 'm' -> */, +/* pos 0286: 326 */ 0xE5 /* 'e' -> */, +/* pos 0287: 327 */ 0xBA /* ':' -> */, +/* pos 0288: 328 */ 0x00, 0x26 /* - terminal marker 38 - */, +/* pos 028a: 329 */ 0xE1 /* 'a' -> */, +/* pos 028b: 330 */ 0xF4 /* 't' -> */, +/* pos 028c: 331 */ 0xF5 /* 'u' -> */, +/* pos 028d: 332 */ 0xF3 /* 's' -> */, +/* pos 028e: 333 */ 0xBA /* ':' -> */, +/* pos 028f: 334 */ 0x00, 0x27 /* - terminal marker 39 - */, +/* pos 0291: 335 */ 0xE8 /* 'h' -> */, +/* pos 0292: 336 */ 0xE1 /* 'a' -> */, +/* pos 0293: 337 */ 0xF2 /* 'r' -> */, +/* pos 0294: 338 */ 0xF3 /* 's' -> */, +/* pos 0295: 339 */ 0xE5 /* 'e' -> */, +/* pos 0296: 340 */ 0xF4 /* 't' -> */, +/* pos 0297: 341 */ 0xBA /* ':' -> */, +/* pos 0298: 342 */ 0x00, 0x28 /* - terminal marker 40 - */, +/* pos 029a: 343 */ 0xE1 /* 'a' -> */, +/* pos 029b: 344 */ 0xEE /* 'n' -> */, +/* pos 029c: 345 */ 0xE7 /* 'g' -> */, +/* pos 029d: 346 */ 0xE5 /* 'e' -> */, +/* pos 029e: 347 */ 0xF3 /* 's' -> */, +/* pos 029f: 348 */ 0xBA /* ':' -> */, +/* pos 02a0: 349 */ 0x00, 0x29 /* - terminal marker 41 - */, +/* pos 02a2: 350 */ 0xEC /* 'l' -> */, +/* pos 02a3: 351 */ 0xEC /* 'l' -> */, +/* pos 02a4: 352 */ 0xEF /* 'o' -> */, +/* pos 02a5: 353 */ 0xF7 /* 'w' -> */, +/* pos 02a6: 354 */ 0xAD /* '-' -> */, +/* pos 02a7: 355 */ 0xEF /* 'o' -> */, +/* pos 02a8: 356 */ 0xF2 /* 'r' -> */, +/* pos 02a9: 357 */ 0xE9 /* 'i' -> */, +/* pos 02aa: 358 */ 0xE7 /* 'g' -> */, +/* pos 02ab: 359 */ 0xE9 /* 'i' -> */, +/* pos 02ac: 360 */ 0xEE /* 'n' -> */, +/* pos 02ad: 361 */ 0xBA /* ':' -> */, +/* pos 02ae: 362 */ 0x00, 0x2A /* - terminal marker 42 - */, +/* pos 02b0: 363 */ 0xE5 /* 'e' -> */, +/* pos 02b1: 364 */ 0xBA /* ':' -> */, +/* pos 02b2: 365 */ 0x00, 0x2B /* - terminal marker 43 - */, +/* pos 02b4: 366 */ 0xEC /* 'l' -> */, +/* pos 02b5: 367 */ 0xEF /* 'o' -> */, +/* pos 02b6: 368 */ 0xF7 /* 'w' -> */, +/* pos 02b7: 369 */ 0xBA /* ':' -> */, +/* pos 02b8: 370 */ 0x00, 0x2C /* - terminal marker 44 - */, +/* pos 02ba: 371 */ 0xE9 /* 'i' -> */, +/* pos 02bb: 372 */ 0xF3 /* 's' -> */, +/* pos 02bc: 373 */ 0xF0 /* 'p' -> */, +/* pos 02bd: 374 */ 0xEF /* 'o' -> */, +/* pos 02be: 375 */ 0xF3 /* 's' -> */, +/* pos 02bf: 376 */ 0xE9 /* 'i' -> */, +/* pos 02c0: 377 */ 0xF4 /* 't' -> */, +/* pos 02c1: 378 */ 0xE9 /* 'i' -> */, +/* pos 02c2: 379 */ 0xEF /* 'o' -> */, +/* pos 02c3: 380 */ 0xEE /* 'n' -> */, +/* pos 02c4: 381 */ 0xBA /* ':' -> */, +/* pos 02c5: 382 */ 0x00, 0x2D /* - terminal marker 45 - */, +/* pos 02c7: 383 */ 0xEE /* 'n' -> */, +/* pos 02c8: 384 */ 0xE3 /* 'c' -> */, +/* pos 02c9: 385 */ 0xEF /* 'o' -> */, +/* pos 02ca: 386 */ 0xE4 /* 'd' -> */, +/* pos 02cb: 387 */ 0xE9 /* 'i' -> */, +/* pos 02cc: 388 */ 0xEE /* 'n' -> */, +/* pos 02cd: 389 */ 0xE7 /* 'g' -> */, +/* pos 02ce: 390 */ 0xBA /* ':' -> */, +/* pos 02cf: 391 */ 0x00, 0x2E /* - terminal marker 46 - */, +/* pos 02d1: 392 */ 0xEE /* 'n' -> */, +/* pos 02d2: 393 */ 0xE7 /* 'g' -> */, +/* pos 02d3: 394 */ 0xF5 /* 'u' -> */, +/* pos 02d4: 395 */ 0xE1 /* 'a' -> */, +/* pos 02d5: 396 */ 0xE7 /* 'g' -> */, +/* pos 02d6: 397 */ 0xE5 /* 'e' -> */, +/* pos 02d7: 398 */ 0xBA /* ':' -> */, +/* pos 02d8: 399 */ 0x00, 0x2F /* - terminal marker 47 - */, +/* pos 02da: 400 */ 0xE3 /* 'c' -> */, +/* pos 02db: 401 */ 0xE1 /* 'a' -> */, +/* pos 02dc: 402 */ 0xF4 /* 't' -> */, +/* pos 02dd: 403 */ 0xE9 /* 'i' -> */, +/* pos 02de: 404 */ 0xEF /* 'o' -> */, +/* pos 02df: 405 */ 0xEE /* 'n' -> */, +/* pos 02e0: 406 */ 0xBA /* ':' -> */, +/* pos 02e1: 407 */ 0x00, 0x30 /* - terminal marker 48 - */, +/* pos 02e3: 408 */ 0xE1 /* 'a' -> */, +/* pos 02e4: 409 */ 0xEE /* 'n' -> */, +/* pos 02e5: 410 */ 0xE7 /* 'g' -> */, +/* pos 02e6: 411 */ 0xE5 /* 'e' -> */, +/* pos 02e7: 412 */ 0xBA /* ':' -> */, +/* pos 02e8: 413 */ 0x00, 0x31 /* - terminal marker 49 - */, +/* pos 02ea: 414 */ 0x74 /* 't' */, 0x07, 0x00 /* (to 0x02F1 state 415) */, + 0x78 /* 'x' */, 0x09, 0x00 /* (to 0x02F6 state 419) */, + 0x08, /* fail */ +/* pos 02f1: 415 */ 0xE1 /* 'a' -> */, +/* pos 02f2: 416 */ 0xE7 /* 'g' -> */, +/* pos 02f3: 417 */ 0xBA /* ':' -> */, +/* pos 02f4: 418 */ 0x00, 0x32 /* - terminal marker 50 - */, +/* pos 02f6: 419 */ 0xF0 /* 'p' -> */, +/* pos 02f7: 420 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x02FE state 421) */, + 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x0303 state 425) */, + 0x08, /* fail */ +/* pos 02fe: 421 */ 0xE3 /* 'c' -> */, +/* pos 02ff: 422 */ 0xF4 /* 't' -> */, +/* pos 0300: 423 */ 0xBA /* ':' -> */, +/* pos 0301: 424 */ 0x00, 0x33 /* - terminal marker 51 - */, +/* pos 0303: 425 */ 0xF2 /* 'r' -> */, +/* pos 0304: 426 */ 0xE5 /* 'e' -> */, +/* pos 0305: 427 */ 0xF3 /* 's' -> */, +/* pos 0306: 428 */ 0xBA /* ':' -> */, +/* pos 0307: 429 */ 0x00, 0x34 /* - terminal marker 52 - */, +/* pos 0309: 430 */ 0xF2 /* 'r' -> */, +/* pos 030a: 431 */ 0xEF /* 'o' -> */, +/* pos 030b: 432 */ 0xED /* 'm' -> */, +/* pos 030c: 433 */ 0xBA /* ':' -> */, +/* pos 030d: 434 */ 0x00, 0x35 /* - terminal marker 53 - */, +/* pos 030f: 435 */ 0xF4 /* 't' -> */, +/* pos 0310: 436 */ 0xE3 /* 'c' -> */, +/* pos 0311: 437 */ 0xE8 /* 'h' -> */, +/* pos 0312: 438 */ 0xBA /* ':' -> */, +/* pos 0313: 439 */ 0x00, 0x36 /* - terminal marker 54 - */, +/* pos 0315: 440 */ 0xE1 /* 'a' -> */, +/* pos 0316: 441 */ 0xEE /* 'n' -> */, +/* pos 0317: 442 */ 0xE7 /* 'g' -> */, +/* pos 0318: 443 */ 0xE5 /* 'e' -> */, +/* pos 0319: 444 */ 0xBA /* ':' -> */, +/* pos 031a: 445 */ 0x00, 0x37 /* - terminal marker 55 - */, +/* pos 031c: 446 */ 0xEE /* 'n' -> */, +/* pos 031d: 447 */ 0xED /* 'm' -> */, +/* pos 031e: 448 */ 0xEF /* 'o' -> */, +/* pos 031f: 449 */ 0xE4 /* 'd' -> */, +/* pos 0320: 450 */ 0xE9 /* 'i' -> */, +/* pos 0321: 451 */ 0xE6 /* 'f' -> */, +/* pos 0322: 452 */ 0xE9 /* 'i' -> */, +/* pos 0323: 453 */ 0xE5 /* 'e' -> */, +/* pos 0324: 454 */ 0xE4 /* 'd' -> */, +/* pos 0325: 455 */ 0xAD /* '-' -> */, +/* pos 0326: 456 */ 0xF3 /* 's' -> */, +/* pos 0327: 457 */ 0xE9 /* 'i' -> */, +/* pos 0328: 458 */ 0xEE /* 'n' -> */, +/* pos 0329: 459 */ 0xE3 /* 'c' -> */, +/* pos 032a: 460 */ 0xE5 /* 'e' -> */, +/* pos 032b: 461 */ 0xBA /* ':' -> */, +/* pos 032c: 462 */ 0x00, 0x38 /* - terminal marker 56 - */, +/* pos 032e: 463 */ 0x61 /* 'a' */, 0x0A, 0x00 /* (to 0x0338 state 464) */, + 0x69 /* 'i' */, 0x15, 0x00 /* (to 0x0346 state 477) */, + 0x6F /* 'o' */, 0x17, 0x00 /* (to 0x034B state 481) */, + 0x08, /* fail */ +/* pos 0338: 464 */ 0xF3 /* 's' -> */, +/* pos 0339: 465 */ 0xF4 /* 't' -> */, +/* pos 033a: 466 */ 0xAD /* '-' -> */, +/* pos 033b: 467 */ 0xED /* 'm' -> */, +/* pos 033c: 468 */ 0xEF /* 'o' -> */, +/* pos 033d: 469 */ 0xE4 /* 'd' -> */, +/* pos 033e: 470 */ 0xE9 /* 'i' -> */, +/* pos 033f: 471 */ 0xE6 /* 'f' -> */, +/* pos 0340: 472 */ 0xE9 /* 'i' -> */, +/* pos 0341: 473 */ 0xE5 /* 'e' -> */, +/* pos 0342: 474 */ 0xE4 /* 'd' -> */, +/* pos 0343: 475 */ 0xBA /* ':' -> */, +/* pos 0344: 476 */ 0x00, 0x39 /* - terminal marker 57 - */, +/* pos 0346: 477 */ 0xEE /* 'n' -> */, +/* pos 0347: 478 */ 0xEB /* 'k' -> */, +/* pos 0348: 479 */ 0xBA /* ':' -> */, +/* pos 0349: 480 */ 0x00, 0x3A /* - terminal marker 58 - */, +/* pos 034b: 481 */ 0xE3 /* 'c' -> */, +/* pos 034c: 482 */ 0xE1 /* 'a' -> */, +/* pos 034d: 483 */ 0xF4 /* 't' -> */, +/* pos 034e: 484 */ 0xE9 /* 'i' -> */, +/* pos 034f: 485 */ 0xEF /* 'o' -> */, +/* pos 0350: 486 */ 0xEE /* 'n' -> */, +/* pos 0351: 487 */ 0xBA /* ':' -> */, +/* pos 0352: 488 */ 0x00, 0x3B /* - terminal marker 59 - */, +/* pos 0354: 489 */ 0xE1 /* 'a' -> */, +/* pos 0355: 490 */ 0xF8 /* 'x' -> */, +/* pos 0356: 491 */ 0xAD /* '-' -> */, +/* pos 0357: 492 */ 0xE6 /* 'f' -> */, +/* pos 0358: 493 */ 0xEF /* 'o' -> */, +/* pos 0359: 494 */ 0xF2 /* 'r' -> */, +/* pos 035a: 495 */ 0xF7 /* 'w' -> */, +/* pos 035b: 496 */ 0xE1 /* 'a' -> */, +/* pos 035c: 497 */ 0xF2 /* 'r' -> */, +/* pos 035d: 498 */ 0xE4 /* 'd' -> */, +/* pos 035e: 499 */ 0xF3 /* 's' -> */, +/* pos 035f: 500 */ 0xBA /* ':' -> */, +/* pos 0360: 501 */ 0x00, 0x3C /* - terminal marker 60 - */, +/* pos 0362: 502 */ 0xF8 /* 'x' -> */, +/* pos 0363: 503 */ 0xF9 /* 'y' -> */, +/* pos 0364: 504 */ 0x2D /* '-' */, 0x07, 0x00 /* (to 0x036B state 505) */, + 0x20 /* ' ' */, 0x9F, 0x00 /* (to 0x0406 state 636) */, + 0x08, /* fail */ +/* pos 036b: 505 */ 0xE1 /* 'a' -> */, +/* pos 036c: 506 */ 0xF5 /* 'u' -> */, +/* pos 036d: 507 */ 0xF4 /* 't' -> */, +/* pos 036e: 508 */ 0xE8 /* 'h' -> */, +/* pos 036f: 509 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x0376 state 510) */, + 0x6F /* 'o' */, 0x0E, 0x00 /* (to 0x0380 state 519) */, + 0x08, /* fail */ +/* pos 0376: 510 */ 0xEE /* 'n' -> */, +/* pos 0377: 511 */ 0xF4 /* 't' -> */, +/* pos 0378: 512 */ 0xE9 /* 'i' -> */, +/* pos 0379: 513 */ 0xE3 /* 'c' -> */, +/* pos 037a: 514 */ 0xE1 /* 'a' -> */, +/* pos 037b: 515 */ 0xF4 /* 't' -> */, +/* pos 037c: 516 */ 0xE5 /* 'e' -> */, +/* pos 037d: 517 */ 0xBA /* ':' -> */, +/* pos 037e: 518 */ 0x00, 0x3D /* - terminal marker 61 - */, +/* pos 0380: 519 */ 0xF2 /* 'r' -> */, +/* pos 0381: 520 */ 0xE9 /* 'i' -> */, +/* pos 0382: 521 */ 0xFA /* 'z' -> */, +/* pos 0383: 522 */ 0xE1 /* 'a' -> */, +/* pos 0384: 523 */ 0xF4 /* 't' -> */, +/* pos 0385: 524 */ 0xE9 /* 'i' -> */, +/* pos 0386: 525 */ 0xEF /* 'o' -> */, +/* pos 0387: 526 */ 0xEE /* 'n' -> */, +/* pos 0388: 527 */ 0xBA /* ':' -> */, +/* pos 0389: 528 */ 0x00, 0x3E /* - terminal marker 62 - */, +/* pos 038b: 529 */ 0xE5 /* 'e' -> */, +/* pos 038c: 530 */ 0xF3 /* 's' -> */, +/* pos 038d: 531 */ 0xE8 /* 'h' -> */, +/* pos 038e: 532 */ 0xBA /* ':' -> */, +/* pos 038f: 533 */ 0x00, 0x3F /* - terminal marker 63 - */, +/* pos 0391: 534 */ 0xF2 /* 'r' -> */, +/* pos 0392: 535 */ 0xF9 /* 'y' -> */, +/* pos 0393: 536 */ 0xAD /* '-' -> */, +/* pos 0394: 537 */ 0xE1 /* 'a' -> */, +/* pos 0395: 538 */ 0xE6 /* 'f' -> */, +/* pos 0396: 539 */ 0xF4 /* 't' -> */, +/* pos 0397: 540 */ 0xE5 /* 'e' -> */, +/* pos 0398: 541 */ 0xF2 /* 'r' -> */, +/* pos 0399: 542 */ 0xBA /* ':' -> */, +/* pos 039a: 543 */ 0x00, 0x40 /* - terminal marker 64 - */, +/* pos 039c: 544 */ 0xF6 /* 'v' -> */, +/* pos 039d: 545 */ 0xE5 /* 'e' -> */, +/* pos 039e: 546 */ 0xF2 /* 'r' -> */, +/* pos 039f: 547 */ 0xBA /* ':' -> */, +/* pos 03a0: 548 */ 0x00, 0x41 /* - terminal marker 65 - */, +/* pos 03a2: 549 */ 0xAD /* '-' -> */, +/* pos 03a3: 550 */ 0xE3 /* 'c' -> */, +/* pos 03a4: 551 */ 0xEF /* 'o' -> */, +/* pos 03a5: 552 */ 0xEF /* 'o' -> */, +/* pos 03a6: 553 */ 0xEB /* 'k' -> */, +/* pos 03a7: 554 */ 0xE9 /* 'i' -> */, +/* pos 03a8: 555 */ 0xE5 /* 'e' -> */, +/* pos 03a9: 556 */ 0xBA /* ':' -> */, +/* pos 03aa: 557 */ 0x00, 0x42 /* - terminal marker 66 - */, +/* pos 03ac: 558 */ 0xF2 /* 'r' -> */, +/* pos 03ad: 559 */ 0xE9 /* 'i' -> */, +/* pos 03ae: 560 */ 0xE3 /* 'c' -> */, +/* pos 03af: 561 */ 0xF4 /* 't' -> */, +/* pos 03b0: 562 */ 0xAD /* '-' -> */, +/* pos 03b1: 563 */ 0xF4 /* 't' -> */, +/* pos 03b2: 564 */ 0xF2 /* 'r' -> */, +/* pos 03b3: 565 */ 0xE1 /* 'a' -> */, +/* pos 03b4: 566 */ 0xEE /* 'n' -> */, +/* pos 03b5: 567 */ 0xF3 /* 's' -> */, +/* pos 03b6: 568 */ 0xF0 /* 'p' -> */, +/* pos 03b7: 569 */ 0xEF /* 'o' -> */, +/* pos 03b8: 570 */ 0xF2 /* 'r' -> */, +/* pos 03b9: 571 */ 0xF4 /* 't' -> */, +/* pos 03ba: 572 */ 0xAD /* '-' -> */, +/* pos 03bb: 573 */ 0xF3 /* 's' -> */, +/* pos 03bc: 574 */ 0xE5 /* 'e' -> */, +/* pos 03bd: 575 */ 0xE3 /* 'c' -> */, +/* pos 03be: 576 */ 0xF5 /* 'u' -> */, +/* pos 03bf: 577 */ 0xF2 /* 'r' -> */, +/* pos 03c0: 578 */ 0xE9 /* 'i' -> */, +/* pos 03c1: 579 */ 0xF4 /* 't' -> */, +/* pos 03c2: 580 */ 0xF9 /* 'y' -> */, +/* pos 03c3: 581 */ 0xBA /* ':' -> */, +/* pos 03c4: 582 */ 0x00, 0x43 /* - terminal marker 67 - */, +/* pos 03c6: 583 */ 0xF2 /* 'r' -> */, +/* pos 03c7: 584 */ 0xE1 /* 'a' -> */, +/* pos 03c8: 585 */ 0xEE /* 'n' -> */, +/* pos 03c9: 586 */ 0xF3 /* 's' -> */, +/* pos 03ca: 587 */ 0xE6 /* 'f' -> */, +/* pos 03cb: 588 */ 0xE5 /* 'e' -> */, +/* pos 03cc: 589 */ 0xF2 /* 'r' -> */, +/* pos 03cd: 590 */ 0xAD /* '-' -> */, +/* pos 03ce: 591 */ 0xE5 /* 'e' -> */, +/* pos 03cf: 592 */ 0xEE /* 'n' -> */, +/* pos 03d0: 593 */ 0xE3 /* 'c' -> */, +/* pos 03d1: 594 */ 0xEF /* 'o' -> */, +/* pos 03d2: 595 */ 0xE4 /* 'd' -> */, +/* pos 03d3: 596 */ 0xE9 /* 'i' -> */, +/* pos 03d4: 597 */ 0xEE /* 'n' -> */, +/* pos 03d5: 598 */ 0xE7 /* 'g' -> */, +/* pos 03d6: 599 */ 0xBA /* ':' -> */, +/* pos 03d7: 600 */ 0x00, 0x44 /* - terminal marker 68 - */, +/* pos 03d9: 601 */ 0xE5 /* 'e' -> */, +/* pos 03da: 602 */ 0xF2 /* 'r' -> */, +/* pos 03db: 603 */ 0xAD /* '-' -> */, +/* pos 03dc: 604 */ 0xE1 /* 'a' -> */, +/* pos 03dd: 605 */ 0xE7 /* 'g' -> */, +/* pos 03de: 606 */ 0xE5 /* 'e' -> */, +/* pos 03df: 607 */ 0xEE /* 'n' -> */, +/* pos 03e0: 608 */ 0xF4 /* 't' -> */, +/* pos 03e1: 609 */ 0xBA /* ':' -> */, +/* pos 03e2: 610 */ 0x00, 0x45 /* - terminal marker 69 - */, +/* pos 03e4: 611 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x03EB state 612) */, + 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x03F0 state 616) */, + 0x08, /* fail */ +/* pos 03eb: 612 */ 0xF2 /* 'r' -> */, +/* pos 03ec: 613 */ 0xF9 /* 'y' -> */, +/* pos 03ed: 614 */ 0xBA /* ':' -> */, +/* pos 03ee: 615 */ 0x00, 0x46 /* - terminal marker 70 - */, +/* pos 03f0: 616 */ 0xE1 /* 'a' -> */, +/* pos 03f1: 617 */ 0xBA /* ':' -> */, +/* pos 03f2: 618 */ 0x00, 0x47 /* - terminal marker 71 - */, +/* pos 03f4: 619 */ 0xF7 /* 'w' -> */, +/* pos 03f5: 620 */ 0xF7 /* 'w' -> */, +/* pos 03f6: 621 */ 0xAD /* '-' -> */, +/* pos 03f7: 622 */ 0xE1 /* 'a' -> */, +/* pos 03f8: 623 */ 0xF5 /* 'u' -> */, +/* pos 03f9: 624 */ 0xF4 /* 't' -> */, +/* pos 03fa: 625 */ 0xE8 /* 'h' -> */, +/* pos 03fb: 626 */ 0xE5 /* 'e' -> */, +/* pos 03fc: 627 */ 0xEE /* 'n' -> */, +/* pos 03fd: 628 */ 0xF4 /* 't' -> */, +/* pos 03fe: 629 */ 0xE9 /* 'i' -> */, +/* pos 03ff: 630 */ 0xE3 /* 'c' -> */, +/* pos 0400: 631 */ 0xE1 /* 'a' -> */, +/* pos 0401: 632 */ 0xF4 /* 't' -> */, +/* pos 0402: 633 */ 0xE5 /* 'e' -> */, +/* pos 0403: 634 */ 0xBA /* ':' -> */, +/* pos 0404: 635 */ 0x00, 0x48 /* - terminal marker 72 - */, +/* pos 0406: 636 */ 0x00, 0x49 /* - terminal marker 73 - */, +/* total size 1032 bytes */ diff --git a/src/engine/external/libwebsockets/libwebsockets.c b/src/engine/external/libwebsockets/libwebsockets.c new file mode 100644 index 0000000..b9be442 --- /dev/null +++ b/src/engine/external/libwebsockets/libwebsockets.c @@ -0,0 +1,850 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE; +static void (*lwsl_emit)(int level, const char *line) = lwsl_emit_stderr; + +static const char * const log_level_names[] = { + "ERR", + "WARN", + "NOTICE", + "INFO", + "DEBUG", + "PARSER", + "HEADER", + "EXTENSION", + "CLIENT", + "LATENCY", +}; + + +void +libwebsocket_close_and_free_session(struct libwebsocket_context *context, + struct libwebsocket *wsi, enum lws_close_status reason) +{ + int n, m, ret; + int old_state; + unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 + + LWS_SEND_BUFFER_POST_PADDING]; + struct lws_tokens eff_buf; + + if (!wsi) + return; + + old_state = wsi->state; + + if (wsi->socket_is_permanently_unusable) + goto just_kill_connection; + + switch (old_state) { + case WSI_STATE_DEAD_SOCKET: + return; + + /* we tried the polite way... */ + case WSI_STATE_AWAITING_CLOSE_ACK: + goto just_kill_connection; + + case WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE: + if (wsi->truncated_send_len) { + libwebsocket_callback_on_writable(context, wsi); + return; + } + lwsl_info("wsi %p completed WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi); + goto just_kill_connection; + default: + if (wsi->truncated_send_len) { + lwsl_info("wsi %p entering WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi); + wsi->state = WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE; + return; + } + break; + } + + wsi->u.ws.close_reason = reason; + + if (wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT || + wsi->mode == LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE) { + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); + + lws_free_header_table(wsi); + goto just_kill_connection; + } + + if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) { + if (wsi->u.http.fd != LWS_INVALID_FILE) { + lwsl_debug("closing http file\n"); + compatible_file_close(wsi->u.http.fd); + wsi->u.http.fd = LWS_INVALID_FILE; + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0); + } + } + + /* + * are his extensions okay with him closing? Eg he might be a mux + * parent and just his ch1 aspect is closing? + */ + + if (lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) { + lwsl_ext("extension vetoed close\n"); + return; + } + + /* + * flush any tx pending from extensions, since we may send close packet + * if there are problems with send, just nuke the connection + */ + + do { + ret = 0; + eff_buf.token = NULL; + eff_buf.token_len = 0; + + /* show every extension the new incoming data */ + + m = lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_FLUSH_PENDING_TX, &eff_buf, 0); + if (m < 0) { + lwsl_ext("Extension reports fatal error\n"); + goto just_kill_connection; + } + if (m) + /* + * at least one extension told us he has more + * to spill, so we will go around again after + */ + ret = 1; + + /* assuming they left us something to send, send it */ + + if (eff_buf.token_len) + if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token, + eff_buf.token_len) != eff_buf.token_len) { + lwsl_debug("close: ext spill failed\n"); + goto just_kill_connection; + } + } while (ret); + + /* + * signal we are closing, libwebsocket_write will + * add any necessary version-specific stuff. If the write fails, + * no worries we are closing anyway. If we didn't initiate this + * close, then our state has been changed to + * WSI_STATE_RETURNED_CLOSE_ALREADY and we will skip this. + * + * Likewise if it's a second call to close this connection after we + * sent the close indication to the peer already, we are in state + * WSI_STATE_AWAITING_CLOSE_ACK and will skip doing this a second time. + */ + + if (old_state == WSI_STATE_ESTABLISHED && + reason != LWS_CLOSE_STATUS_NOSTATUS) { + + lwsl_debug("sending close indication...\n"); + + /* make valgrind happy */ + memset(buf, 0, sizeof(buf)); + n = libwebsocket_write(wsi, + &buf[LWS_SEND_BUFFER_PRE_PADDING + 2], + 0, LWS_WRITE_CLOSE); + if (n >= 0) { + /* + * we have sent a nice protocol level indication we + * now wish to close, we should not send anything more + */ + + wsi->state = WSI_STATE_AWAITING_CLOSE_ACK; + + /* + * ...and we should wait for a reply for a bit + * out of politeness + */ + + libwebsocket_set_timeout(wsi, + PENDING_TIMEOUT_CLOSE_ACK, 1); + + lwsl_debug("sent close indication, awaiting ack\n"); + + return; + } + + lwsl_info("close: sending close packet failed, hanging up\n"); + + /* else, the send failed and we should just hang up */ + } + +just_kill_connection: + + lwsl_debug("close: just_kill_connection\n"); + + /* + * we won't be servicing or receiving anything further from this guy + * delete socket from the internal poll list if still present + */ + + remove_wsi_socket_from_fds(context, wsi); + + wsi->state = WSI_STATE_DEAD_SOCKET; + + lws_free2(wsi->rxflow_buffer); + + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING && wsi->u.hdr.ah) { + lws_free2(wsi->u.hdr.ah); + } + + if ((old_state == WSI_STATE_ESTABLISHED || + wsi->mode == LWS_CONNMODE_WS_SERVING || + wsi->mode == LWS_CONNMODE_WS_CLIENT)) { + + lws_free2(wsi->u.ws.rx_user_buffer); + + if (wsi->truncated_send_malloc) { + /* not going to be completed... nuke it */ + lws_free2(wsi->truncated_send_malloc); + wsi->truncated_send_len = 0; + } + if (wsi->u.ws.ping_payload_buf) { + lws_free2(wsi->u.ws.ping_payload_buf); + wsi->u.ws.ping_payload_alloc = 0; + wsi->u.ws.ping_payload_len = 0; + } + } + + /* tell the user it's all over for this guy */ + + if (wsi->protocol && wsi->protocol->callback && + ((old_state == WSI_STATE_ESTABLISHED) || + (old_state == WSI_STATE_RETURNED_CLOSE_ALREADY) || + (old_state == WSI_STATE_AWAITING_CLOSE_ACK) || + (old_state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE))) { + lwsl_debug("calling back CLOSED\n"); + wsi->protocol->callback(context, wsi, LWS_CALLBACK_CLOSED, + wsi->user_space, NULL, 0); + } else if (wsi->mode == LWS_CONNMODE_HTTP_SERVING_ACCEPTED) { + lwsl_debug("calling back CLOSED_HTTP\n"); + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0 ); + } else + lwsl_debug("not calling back closed\n"); + + /* deallocate any active extension contexts */ + + if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_DESTROY, NULL, 0) < 0) + lwsl_warn("extension destruction failed\n"); +#ifndef LWS_NO_EXTENSIONS + for (n = 0; n < wsi->count_active_extensions; n++) + lws_free(wsi->active_extensions_user[n]); +#endif + /* + * inform all extensions in case they tracked this guy out of band + * even though not active on him specifically + */ + if (lws_ext_callback_for_each_extension_type(context, wsi, + LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0) + lwsl_warn("ext destroy wsi failed\n"); + +/* lwsl_info("closing fd=%d\n", wsi->sock); */ + + if (!lws_ssl_close(wsi) && wsi->sock >= 0) { + n = shutdown(wsi->sock, SHUT_RDWR); + if (n) + lwsl_debug("closing: shutdown ret %d\n", LWS_ERRNO); + + n = compatible_close(wsi->sock); + if (n) + lwsl_debug("closing: close ret %d\n", LWS_ERRNO); + } + + /* outermost destroy notification for wsi (user_space still intact) */ + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_WSI_DESTROY, wsi->user_space, NULL, 0); + + if (wsi->protocol && wsi->protocol->per_session_data_size && + wsi->user_space && !wsi->user_space_externally_allocated) + lws_free(wsi->user_space); + + /* As a precaution, free the header table in case it lingered: */ + lws_free_header_table(wsi); + lws_free(wsi); +} + +/** + * libwebsockets_get_peer_addresses() - Get client address information + * @context: Libwebsockets context + * @wsi: Local struct libwebsocket associated with + * @fd: Connection socket descriptor + * @name: Buffer to take client address name + * @name_len: Length of client address name buffer + * @rip: Buffer to take client address IP dotted quad + * @rip_len: Length of client address IP buffer + * + * This function fills in @name and @rip with the name and IP of + * the client connected with socket descriptor @fd. Names may be + * truncated if there is not enough room. If either cannot be + * determined, they will be returned as valid zero-length strings. + */ + +LWS_VISIBLE void +libwebsockets_get_peer_addresses(struct libwebsocket_context *context, + struct libwebsocket *wsi, int fd, char *name, int name_len, + char *rip, int rip_len) +{ + socklen_t len; +#ifdef LWS_USE_IPV6 + struct sockaddr_in6 sin6; +#endif + struct sockaddr_in sin4; + struct hostent *host; + struct hostent *host1; + char ip[128]; + unsigned char *p; + int n; +#ifdef AF_LOCAL + struct sockaddr_un *un; +#endif + int ret = -1; + + rip[0] = '\0'; + name[0] = '\0'; + + lws_latency_pre(context, wsi); + +#ifdef LWS_USE_IPV6 + if (LWS_IPV6_ENABLED(context)) { + + len = sizeof(sin6); + if (getpeername(fd, (struct sockaddr *) &sin6, &len) < 0) { + lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO)); + goto bail; + } + + if (!lws_plat_inet_ntop(AF_INET6, &sin6.sin6_addr, rip, rip_len)) { + lwsl_err("inet_ntop", strerror(LWS_ERRNO)); + goto bail; + } + + // Strip off the IPv4 to IPv6 header if one exists + if (strncmp(rip, "::ffff:", 7) == 0) + memmove(rip, rip + 7, strlen(rip) - 6); + + getnameinfo((struct sockaddr *)&sin6, + sizeof(struct sockaddr_in6), name, + name_len, NULL, 0, 0); + + } else +#endif + { + len = sizeof(sin4); + if (getpeername(fd, (struct sockaddr *) &sin4, &len) < 0) { + lwsl_warn("getpeername: %s\n", strerror(LWS_ERRNO)); + goto bail; + } + host = gethostbyaddr((char *) &sin4.sin_addr, + sizeof(sin4.sin_addr), AF_INET); + if (host == NULL) { + lwsl_warn("gethostbyaddr: %s\n", strerror(LWS_ERRNO)); + goto bail; + } + + strncpy(name, host->h_name, name_len); + name[name_len - 1] = '\0'; + + host1 = gethostbyname(host->h_name); + if (host1 == NULL) + goto bail; + p = (unsigned char *)host1; + n = 0; + while (p != NULL) { + p = (unsigned char *)host1->h_addr_list[n++]; + if (p == NULL) + continue; + if ((host1->h_addrtype != AF_INET) +#ifdef AF_LOCAL + && (host1->h_addrtype != AF_LOCAL) +#endif + ) + continue; + + if (host1->h_addrtype == AF_INET) + sprintf(ip, "%u.%u.%u.%u", + p[0], p[1], p[2], p[3]); +#ifdef AF_LOCAL + else { + un = (struct sockaddr_un *)p; + strncpy(ip, un->sun_path, sizeof(ip) - 1); + ip[sizeof(ip) - 1] = '\0'; + } +#endif + p = NULL; + strncpy(rip, ip, rip_len); + rip[rip_len - 1] = '\0'; + } + } + + ret = 0; +bail: + lws_latency(context, wsi, "libwebsockets_get_peer_addresses", ret, 1); +} + + + +/** + * libwebsocket_context_user() - get the user data associated with the context + * @context: Websocket context + * + * This returns the optional user allocation that can be attached to + * the context the sockets live in at context_create time. It's a way + * to let all sockets serviced in the same context share data without + * using globals statics in the user code. + */ +LWS_EXTERN void * +libwebsocket_context_user(struct libwebsocket_context *context) +{ + return context->user_space; +} + + +/** + * libwebsocket_callback_all_protocol() - Callback all connections using + * the given protocol with the given reason + * + * @protocol: Protocol whose connections will get callbacks + * @reason: Callback reason index + */ + +LWS_VISIBLE int +libwebsocket_callback_all_protocol( + const struct libwebsocket_protocols *protocol, int reason) +{ + struct libwebsocket_context *context = protocol->owning_server; + int n; + struct libwebsocket *wsi; + + for (n = 0; n < context->fds_count; n++) { + wsi = context->lws_lookup[context->fds[n].fd]; + if (!wsi) + continue; + if (wsi->protocol == protocol) + protocol->callback(context, wsi, + reason, wsi->user_space, NULL, 0); + } + + return 0; +} + +/** + * libwebsocket_set_timeout() - marks the wsi as subject to a timeout + * + * You will not need this unless you are doing something special + * + * @wsi: Websocket connection instance + * @reason: timeout reason + * @secs: how many seconds + */ + +LWS_VISIBLE void +libwebsocket_set_timeout(struct libwebsocket *wsi, + enum pending_timeout reason, int secs) +{ + time_t now; + + time(&now); + + wsi->pending_timeout_limit = now + secs; + wsi->pending_timeout = reason; +} + + +/** + * libwebsocket_get_socket_fd() - returns the socket file descriptor + * + * You will not need this unless you are doing something special + * + * @wsi: Websocket connection instance + */ + +LWS_VISIBLE int +libwebsocket_get_socket_fd(struct libwebsocket *wsi) +{ + return wsi->sock; +} + +#ifdef LWS_LATENCY +void +lws_latency(struct libwebsocket_context *context, struct libwebsocket *wsi, + const char *action, int ret, int completed) +{ + unsigned long long u; + char buf[256]; + + u = time_in_microseconds(); + + if (!action) { + wsi->latency_start = u; + if (!wsi->action_start) + wsi->action_start = u; + return; + } + if (completed) { + if (wsi->action_start == wsi->latency_start) + sprintf(buf, + "Completion first try lat %lluus: %p: ret %d: %s\n", + u - wsi->latency_start, + (void *)wsi, ret, action); + else + sprintf(buf, + "Completion %lluus: lat %lluus: %p: ret %d: %s\n", + u - wsi->action_start, + u - wsi->latency_start, + (void *)wsi, ret, action); + wsi->action_start = 0; + } else + sprintf(buf, "lat %lluus: %p: ret %d: %s\n", + u - wsi->latency_start, (void *)wsi, ret, action); + + if (u - wsi->latency_start > context->worst_latency) { + context->worst_latency = u - wsi->latency_start; + strcpy(context->worst_latency_info, buf); + } + lwsl_latency("%s", buf); +} +#endif + + + +/** + * libwebsocket_rx_flow_control() - Enable and disable socket servicing for + * received packets. + * + * If the output side of a server process becomes choked, this allows flow + * control for the input side. + * + * @wsi: Websocket connection instance to get callback for + * @enable: 0 = disable read servicing for this connection, 1 = enable + */ + +LWS_VISIBLE int +libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable) +{ + if (enable == (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) + return 0; + + lwsl_info("libwebsocket_rx_flow_control(0x%p, %d)\n", wsi, enable); + wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !!enable; + + return 0; +} + +/** + * libwebsocket_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive + * + * When the user server code realizes it can accept more input, it can + * call this to have the RX flow restriction removed from all connections using + * the given protocol. + * + * @protocol: all connections using this protocol will be allowed to receive + */ + +LWS_VISIBLE void +libwebsocket_rx_flow_allow_all_protocol( + const struct libwebsocket_protocols *protocol) +{ + struct libwebsocket_context *context = protocol->owning_server; + int n; + struct libwebsocket *wsi; + + for (n = 0; n < context->fds_count; n++) { + wsi = context->lws_lookup[context->fds[n].fd]; + if (!wsi) + continue; + if (wsi->protocol == protocol) + libwebsocket_rx_flow_control(wsi, LWS_RXFLOW_ALLOW); + } +} + + +/** + * libwebsocket_canonical_hostname() - returns this host's hostname + * + * This is typically used by client code to fill in the host parameter + * when making a client connection. You can only call it after the context + * has been created. + * + * @context: Websocket context + */ +LWS_VISIBLE extern const char * +libwebsocket_canonical_hostname(struct libwebsocket_context *context) +{ + return (const char *)context->canonical_hostname; +} + +int user_callback_handle_rxflow(callback_function callback_function, + struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_callback_reasons reason, void *user, + void *in, size_t len) +{ + int n; + + n = callback_function(context, wsi, reason, user, in, len); + if (!n) + n = _libwebsocket_rx_flow_control(wsi); + + return n; +} + + +/** + * libwebsocket_set_proxy() - Setups proxy to libwebsocket_context. + * @context: pointer to struct libwebsocket_context you want set proxy to + * @proxy: pointer to c string containing proxy in format address:port + * + * Returns 0 if proxy string was parsed and proxy was setup. + * Returns -1 if @proxy is NULL or has incorrect format. + * + * This is only required if your OS does not provide the http_proxy + * environment variable (eg, OSX) + * + * IMPORTANT! You should call this function right after creation of the + * libwebsocket_context and before call to connect. If you call this + * function after connect behavior is undefined. + * This function will override proxy settings made on libwebsocket_context + * creation with genenv() call. + */ + +LWS_VISIBLE int +libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy) +{ + char *p; + + if (!proxy) + return -1; + + strncpy(context->http_proxy_address, proxy, + sizeof(context->http_proxy_address) - 1); + context->http_proxy_address[ + sizeof(context->http_proxy_address) - 1] = '\0'; + + p = strchr(context->http_proxy_address, ':'); + if (!p) { + lwsl_err("http_proxy needs to be ads:port\n"); + + return -1; + } + *p = '\0'; + context->http_proxy_port = atoi(p + 1); + + lwsl_notice(" Proxy %s:%u\n", context->http_proxy_address, + context->http_proxy_port); + + return 0; +} + +/** + * libwebsockets_get_protocol() - Returns a protocol pointer from a websocket + * connection. + * @wsi: pointer to struct websocket you want to know the protocol of + * + * + * Some apis can act on all live connections of a given protocol, + * this is how you can get a pointer to the active protocol if needed. + */ + +LWS_VISIBLE const struct libwebsocket_protocols * +libwebsockets_get_protocol(struct libwebsocket *wsi) +{ + return wsi->protocol; +} + +LWS_VISIBLE int +libwebsocket_is_final_fragment(struct libwebsocket *wsi) +{ + return wsi->u.ws.final; +} + +LWS_VISIBLE unsigned char +libwebsocket_get_reserved_bits(struct libwebsocket *wsi) +{ + return wsi->u.ws.rsv; +} + +int +libwebsocket_ensure_user_space(struct libwebsocket *wsi) +{ + lwsl_info("%s: %p protocol %p\n", __func__, wsi, wsi->protocol); + if (!wsi->protocol) + return 1; + + /* allocate the per-connection user memory (if any) */ + + if (wsi->protocol->per_session_data_size && !wsi->user_space) { + wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size); + if (wsi->user_space == NULL) { + lwsl_err("Out of memory for conn user space\n"); + return 1; + } + } else + lwsl_info("%s: %p protocol pss %u, user_space=%d\n", __func__, wsi, wsi->protocol->per_session_data_size, wsi->user_space); + return 0; +} + +LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line) +{ + char buf[300]; + unsigned long long now; + int n; + + buf[0] = '\0'; + for (n = 0; n < LLL_COUNT; n++) + if (level == (1 << n)) { + now = time_in_microseconds() / 100; + sprintf(buf, "[%lu:%04d] %s: ", (unsigned long) now / 10000, + (int)(now % 10000), log_level_names[n]); + break; + } + + fprintf(stderr, "%s%s", buf, line); +} + + +LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl) +{ + char buf[256]; + + if (!(log_level & filter)) + return; + + vsnprintf(buf, sizeof(buf), format, vl); + buf[sizeof(buf) - 1] = '\0'; + + lwsl_emit(filter, buf); +} + +LWS_VISIBLE void _lws_log(int filter, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + _lws_logv(filter, format, ap); + va_end(ap); +} + +/** + * lws_set_log_level() - Set the logging bitfield + * @level: OR together the LLL_ debug contexts you want output from + * @log_emit_function: NULL to leave it as it is, or a user-supplied + * function to perform log string emission instead of + * the default stderr one. + * + * log level defaults to "err", "warn" and "notice" contexts enabled and + * emission on stderr. + */ + +LWS_VISIBLE void lws_set_log_level(int level, void (*log_emit_function)(int level, + const char *line)) +{ + log_level = level; + if (log_emit_function) + lwsl_emit = log_emit_function; +} + +/** + * lws_use_ssl() - Find out if connection is using SSL + * @wsi: websocket connection to check + * + * Returns 0 if the connection is not using SSL, 1 if using SSL and + * using verified cert, and 2 if using SSL but the cert was not + * checked (appears for client wsi told to skip check on connection) + */ +LWS_VISIBLE int +lws_is_ssl(struct libwebsocket *wsi) +{ +#ifdef LWS_OPENSSL_SUPPORT + return wsi->use_ssl; +#else + return 0; +#endif +} + +/** + * lws_partial_buffered() - find out if lws buffered the last write + * @wsi: websocket connection to check + * + * Returns 1 if you cannot use libwebsocket_write because the last + * write on this connection is still buffered, and can't be cleared without + * returning to the service loop and waiting for the connection to be + * writeable again. + * + * If you will try to do >1 libwebsocket_write call inside a single + * WRITEABLE callback, you must check this after every write and bail if + * set, ask for a new writeable callback and continue writing from there. + * + * This is never set at the start of a writeable callback, but any write + * may set it. + */ + +LWS_VISIBLE int +lws_partial_buffered(struct libwebsocket *wsi) +{ + return !!wsi->truncated_send_len; +} + +void lws_set_protocol_write_pending(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum lws_pending_protocol_send pend) +{ + lwsl_info("setting pps %d\n", pend); + + if (wsi->pps) + lwsl_err("pps overwrite\n"); + wsi->pps = pend; + libwebsocket_rx_flow_control(wsi, 0); + libwebsocket_callback_on_writable(context, wsi); +} + +LWS_VISIBLE size_t +lws_get_peer_write_allowance(struct libwebsocket *wsi) +{ +#ifdef LWS_USE_HTTP2 + /* only if we are using HTTP2 on this connection */ + if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) + return -1; + /* user is only interested in how much he can send, or that he can't */ + if (wsi->u.http2.tx_credit <= 0) + return 0; + + return wsi->u.http2.tx_credit; +#else + return -1; +#endif +} + +LWS_VISIBLE void +lws_union_transition(struct libwebsocket *wsi, enum connection_mode mode) +{ + memset(&wsi->u, 0, sizeof(wsi->u)); + wsi->mode = mode; +} diff --git a/src/engine/external/libwebsockets/libwebsockets.h b/src/engine/external/libwebsockets/libwebsockets.h new file mode 100644 index 0000000..3c717ff --- /dev/null +++ b/src/engine/external/libwebsockets/libwebsockets.h @@ -0,0 +1,1371 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C +#define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C + +#ifdef __cplusplus +#include <cstddef> +#include <cstdarg> +extern "C" { +#endif + +#ifdef CMAKE_BUILD +#include "lws_config.h" +#endif + +#if defined(WIN32) || defined(_WIN32) + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <winsock2.h> +#include <ws2tcpip.h> +#include <stddef.h> +#include <stdint.h> +#include <basetsd.h> + +#define strcasecmp stricmp +#define getdtablesize() 30000 + +#define LWS_VISIBLE + +#ifdef LWS_DLL +#ifdef LWS_INTERNAL +#define LWS_EXTERN extern __declspec(dllexport) +#else +#define LWS_EXTERN extern __declspec(dllimport) +#endif +#else +#define LWS_EXTERN +#endif + +#else // NOT WIN32 + +#include <poll.h> +#include <unistd.h> + +#if defined(__GNUC__) +#define LWS_VISIBLE __attribute__((visibility("default"))) +#else +#define LWS_VISIBLE +#endif + +#endif + +#ifdef LWS_USE_LIBEV +#include <ev.h> +#endif /* LWS_USE_LIBEV */ + +#include <assert.h> + +#ifndef LWS_EXTERN +#define LWS_EXTERN extern +#endif + +#ifdef _WIN32 +#define random rand +#else +#include <sys/time.h> +#include <unistd.h> +#endif + +#ifdef LWS_OPENSSL_SUPPORT +#ifdef USE_CYASSL +#include <cyassl/openssl/ssl.h> +#else +#include <openssl/ssl.h> +#endif /* not USE_CYASSL */ +#endif + +#define CONTEXT_PORT_NO_LISTEN -1 +#define MAX_MUX_RECURSION 2 + +enum lws_log_levels { + LLL_ERR = 1 << 0, + LLL_WARN = 1 << 1, + LLL_NOTICE = 1 << 2, + LLL_INFO = 1 << 3, + LLL_DEBUG = 1 << 4, + LLL_PARSER = 1 << 5, + LLL_HEADER = 1 << 6, + LLL_EXT = 1 << 7, + LLL_CLIENT = 1 << 8, + LLL_LATENCY = 1 << 9, + + LLL_COUNT = 10 /* set to count of valid flags */ +}; + +LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...); +LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl); + +/* notice, warn and log are always compiled in */ +#define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__) +#define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__) +#define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__) +/* + * weaker logging can be deselected at configure time using --disable-debug + * that gets rid of the overhead of checking while keeping _warn and _err + * active + */ +#ifdef _DEBUG + +#define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__) +#define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__) +#define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__) +#define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__) +#define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__) +#define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__) +#define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__) +LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len); + +#else /* no debug */ + +#define lwsl_info(...) +#define lwsl_debug(...) +#define lwsl_parser(...) +#define lwsl_header(...) +#define lwsl_ext(...) +#define lwsl_client(...) +#define lwsl_latency(...) +#define lwsl_hexdump(a, b) + +#endif + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) + +/* api change list for user code to test against */ + +#define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG + +/* the struct libwebsocket_protocols has the id field present */ +#define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD + +/* you can call lws_get_peer_write_allowance */ +#define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE + +/* extra parameter introduced in 917f43ab821 */ +#define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN + +enum libwebsocket_context_options { + LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = 2, + LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = 4, + LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = 8, + LWS_SERVER_OPTION_LIBEV = 16, + LWS_SERVER_OPTION_DISABLE_IPV6 = 32, + LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = 64, +}; + +enum libwebsocket_callback_reasons { + LWS_CALLBACK_ESTABLISHED, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, + LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, + LWS_CALLBACK_CLIENT_ESTABLISHED, + LWS_CALLBACK_CLOSED, + LWS_CALLBACK_CLOSED_HTTP, + LWS_CALLBACK_RECEIVE, + LWS_CALLBACK_CLIENT_RECEIVE, + LWS_CALLBACK_CLIENT_RECEIVE_PONG, + LWS_CALLBACK_CLIENT_WRITEABLE, + LWS_CALLBACK_SERVER_WRITEABLE, + LWS_CALLBACK_HTTP, + LWS_CALLBACK_HTTP_BODY, + LWS_CALLBACK_HTTP_BODY_COMPLETION, + LWS_CALLBACK_HTTP_FILE_COMPLETION, + LWS_CALLBACK_HTTP_WRITEABLE, + LWS_CALLBACK_FILTER_NETWORK_CONNECTION, + LWS_CALLBACK_FILTER_HTTP_CONNECTION, + LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, + LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS, + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, + LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION, + LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER, + LWS_CALLBACK_CONFIRM_EXTENSION_OKAY, + LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED, + LWS_CALLBACK_PROTOCOL_INIT, + LWS_CALLBACK_PROTOCOL_DESTROY, + LWS_CALLBACK_WSI_CREATE, /* always protocol[0] */ + LWS_CALLBACK_WSI_DESTROY, /* always protocol[0] */ + LWS_CALLBACK_GET_THREAD_ID, + + /* external poll() management support */ + LWS_CALLBACK_ADD_POLL_FD, + LWS_CALLBACK_DEL_POLL_FD, + LWS_CALLBACK_CHANGE_MODE_POLL_FD, + LWS_CALLBACK_LOCK_POLL, + LWS_CALLBACK_UNLOCK_POLL, + + LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY, + + LWS_CALLBACK_USER = 1000, /* user code can use any including / above */ +}; + +// argument structure for all external poll related calls +// passed in via 'in' +struct libwebsocket_pollargs { + int fd; // applicable file descriptor + int events; // the new event mask + int prev_events; // the previous event mask +}; + +#ifdef _WIN32 +struct libwebsocket_pollfd { + SOCKET fd; + SHORT events; + SHORT revents; +}; +#else +#define libwebsocket_pollfd pollfd +#endif + +enum libwebsocket_extension_callback_reasons { + LWS_EXT_CALLBACK_SERVER_CONTEXT_CONSTRUCT, + LWS_EXT_CALLBACK_CLIENT_CONTEXT_CONSTRUCT, + LWS_EXT_CALLBACK_SERVER_CONTEXT_DESTRUCT, + LWS_EXT_CALLBACK_CLIENT_CONTEXT_DESTRUCT, + LWS_EXT_CALLBACK_CONSTRUCT, + LWS_EXT_CALLBACK_CLIENT_CONSTRUCT, + LWS_EXT_CALLBACK_CHECK_OK_TO_REALLY_CLOSE, + LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION, + LWS_EXT_CALLBACK_DESTROY, + LWS_EXT_CALLBACK_DESTROY_ANY_WSI_CLOSING, + LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, + LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, + LWS_EXT_CALLBACK_PACKET_TX_PRESEND, + LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, + LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX, + LWS_EXT_CALLBACK_FLUSH_PENDING_TX, + LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX, + LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION, + LWS_EXT_CALLBACK_1HZ, + LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE, + LWS_EXT_CALLBACK_IS_WRITEABLE, + LWS_EXT_CALLBACK_PAYLOAD_TX, + LWS_EXT_CALLBACK_PAYLOAD_RX, +}; + +enum libwebsocket_write_protocol { + LWS_WRITE_TEXT, + LWS_WRITE_BINARY, + LWS_WRITE_CONTINUATION, + LWS_WRITE_HTTP, + + /* special 04+ opcodes */ + + LWS_WRITE_CLOSE, + LWS_WRITE_PING, + LWS_WRITE_PONG, + + /* Same as write_http but we know this write ends the transaction */ + LWS_WRITE_HTTP_FINAL, + + /* HTTP2 */ + + LWS_WRITE_HTTP_HEADERS, + + /* flags */ + + LWS_WRITE_NO_FIN = 0x40, + /* + * client packet payload goes out on wire unmunged + * only useful for security tests since normal servers cannot + * decode the content if used + */ + LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80 +}; + +/* + * you need these to look at headers that have been parsed if using the + * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum + * list below is absent, .token = NULL and token_len = 0. Otherwise .token + * points to .token_len chars containing that header content. + */ + +struct lws_tokens { + char *token; + int token_len; +}; + +/* + * don't forget to update test server header dump accordingly + * + * these have to be kept in sync with lextable.h / minilex.c + */ + +enum lws_token_indexes { + WSI_TOKEN_GET_URI, + WSI_TOKEN_POST_URI, + WSI_TOKEN_OPTIONS_URI, + WSI_TOKEN_HOST, + WSI_TOKEN_CONNECTION, + WSI_TOKEN_UPGRADE, + WSI_TOKEN_ORIGIN, + WSI_TOKEN_DRAFT, + WSI_TOKEN_CHALLENGE, + WSI_TOKEN_EXTENSIONS, + WSI_TOKEN_KEY1, + WSI_TOKEN_KEY2, + WSI_TOKEN_PROTOCOL, + WSI_TOKEN_ACCEPT, + WSI_TOKEN_NONCE, + WSI_TOKEN_HTTP, + WSI_TOKEN_HTTP2_SETTINGS, + WSI_TOKEN_HTTP_ACCEPT, + WSI_TOKEN_HTTP_AC_REQUEST_HEADERS, + WSI_TOKEN_HTTP_IF_MODIFIED_SINCE, + WSI_TOKEN_HTTP_IF_NONE_MATCH, + WSI_TOKEN_HTTP_ACCEPT_ENCODING, + WSI_TOKEN_HTTP_ACCEPT_LANGUAGE, + WSI_TOKEN_HTTP_PRAGMA, + WSI_TOKEN_HTTP_CACHE_CONTROL, + WSI_TOKEN_HTTP_AUTHORIZATION, + WSI_TOKEN_HTTP_COOKIE, + WSI_TOKEN_HTTP_CONTENT_LENGTH, + WSI_TOKEN_HTTP_CONTENT_TYPE, + WSI_TOKEN_HTTP_DATE, + WSI_TOKEN_HTTP_RANGE, + WSI_TOKEN_HTTP_REFERER, + WSI_TOKEN_KEY, + WSI_TOKEN_VERSION, + WSI_TOKEN_SWORIGIN, + + WSI_TOKEN_HTTP_COLON_AUTHORITY, + WSI_TOKEN_HTTP_COLON_METHOD, + WSI_TOKEN_HTTP_COLON_PATH, + WSI_TOKEN_HTTP_COLON_SCHEME, + WSI_TOKEN_HTTP_COLON_STATUS, + + WSI_TOKEN_HTTP_ACCEPT_CHARSET, + WSI_TOKEN_HTTP_ACCEPT_RANGES, + WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN, + WSI_TOKEN_HTTP_AGE, + WSI_TOKEN_HTTP_ALLOW, + WSI_TOKEN_HTTP_CONTENT_DISPOSITION, + WSI_TOKEN_HTTP_CONTENT_ENCODING, + WSI_TOKEN_HTTP_CONTENT_LANGUAGE, + WSI_TOKEN_HTTP_CONTENT_LOCATION, + WSI_TOKEN_HTTP_CONTENT_RANGE, + WSI_TOKEN_HTTP_ETAG, + WSI_TOKEN_HTTP_EXPECT, + WSI_TOKEN_HTTP_EXPIRES, + WSI_TOKEN_HTTP_FROM, + WSI_TOKEN_HTTP_IF_MATCH, + WSI_TOKEN_HTTP_IF_RANGE, + WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE, + WSI_TOKEN_HTTP_LAST_MODIFIED, + WSI_TOKEN_HTTP_LINK, + WSI_TOKEN_HTTP_LOCATION, + WSI_TOKEN_HTTP_MAX_FORWARDS, + WSI_TOKEN_HTTP_PROXY_AUTHENTICATE, + WSI_TOKEN_HTTP_PROXY_AUTHORIZATION, + WSI_TOKEN_HTTP_REFRESH, + WSI_TOKEN_HTTP_RETRY_AFTER, + WSI_TOKEN_HTTP_SERVER, + WSI_TOKEN_HTTP_SET_COOKIE, + WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY, + WSI_TOKEN_HTTP_TRANSFER_ENCODING, + WSI_TOKEN_HTTP_USER_AGENT, + WSI_TOKEN_HTTP_VARY, + WSI_TOKEN_HTTP_VIA, + WSI_TOKEN_HTTP_WWW_AUTHENTICATE, + WSI_TOKEN_PROXY, + + WSI_TOKEN_HTTP_URI_ARGS, + + /* use token storage to stash these */ + + _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, + _WSI_TOKEN_CLIENT_PEER_ADDRESS, + _WSI_TOKEN_CLIENT_URI, + _WSI_TOKEN_CLIENT_HOST, + _WSI_TOKEN_CLIENT_ORIGIN, + + /* always last real token index*/ + WSI_TOKEN_COUNT, + /* parser state additions */ + WSI_TOKEN_NAME_PART, + WSI_TOKEN_SKIPPING, + WSI_TOKEN_SKIPPING_SAW_CR, + WSI_PARSING_COMPLETE, + WSI_INIT_TOKEN_MUXURL, +}; + +struct lws_token_limits { + unsigned short token_limit[WSI_TOKEN_COUNT]; +}; + +/* + * From RFC 6455 + 1000 + + 1000 indicates a normal closure, meaning that the purpose for + which the connection was established has been fulfilled. + + 1001 + + 1001 indicates that an endpoint is "going away", such as a server + going down or a browser having navigated away from a page. + + 1002 + + 1002 indicates that an endpoint is terminating the connection due + to a protocol error. + + 1003 + + 1003 indicates that an endpoint is terminating the connection + because it has received a type of data it cannot accept (e.g., an + endpoint that understands only text data MAY send this if it + receives a binary message). + + 1004 + + Reserved. The specific meaning might be defined in the future. + + 1005 + + 1005 is a reserved value and MUST NOT be set as a status code in a + Close control frame by an endpoint. It is designated for use in + applications expecting a status code to indicate that no status + code was actually present. + + 1006 + + 1006 is a reserved value and MUST NOT be set as a status code in a + Close control frame by an endpoint. It is designated for use in + applications expecting a status code to indicate that the + connection was closed abnormally, e.g., without sending or + receiving a Close control frame. + + 1007 + + 1007 indicates that an endpoint is terminating the connection + because it has received data within a message that was not + consistent with the type of the message (e.g., non-UTF-8 [RFC3629] + data within a text message). + + 1008 + + 1008 indicates that an endpoint is terminating the connection + because it has received a message that violates its policy. This + is a generic status code that can be returned when there is no + other more suitable status code (e.g., 1003 or 1009) or if there + is a need to hide specific details about the policy. + + 1009 + + 1009 indicates that an endpoint is terminating the connection + because it has received a message that is too big for it to + process. + + 1010 + + 1010 indicates that an endpoint (client) is terminating the + connection because it has expected the server to negotiate one or + more extension, but the server didn't return them in the response + message of the WebSocket handshake. The list of extensions that + are needed SHOULD appear in the /reason/ part of the Close frame. + Note that this status code is not used by the server, because it + can fail the WebSocket handshake instead. + + 1011 + + 1011 indicates that a server is terminating the connection because + it encountered an unexpected condition that prevented it from + fulfilling the request. + + 1015 + + 1015 is a reserved value and MUST NOT be set as a status code in a + Close control frame by an endpoint. It is designated for use in + applications expecting a status code to indicate that the + connection was closed due to a failure to perform a TLS handshake + (e.g., the server certificate can't be verified). +*/ + +enum lws_close_status { + LWS_CLOSE_STATUS_NOSTATUS = 0, + LWS_CLOSE_STATUS_NORMAL = 1000, + LWS_CLOSE_STATUS_GOINGAWAY = 1001, + LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002, + LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003, + LWS_CLOSE_STATUS_RESERVED = 1004, + LWS_CLOSE_STATUS_NO_STATUS = 1005, + LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006, + LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007, + LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008, + LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009, + LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010, + LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011, + LWS_CLOSE_STATUS_TLS_FAILURE = 1015, +}; + +enum http_status { + HTTP_STATUS_OK = 200, + HTTP_STATUS_NO_CONTENT = 204, + + HTTP_STATUS_BAD_REQUEST = 400, + HTTP_STATUS_UNAUTHORIZED, + HTTP_STATUS_PAYMENT_REQUIRED, + HTTP_STATUS_FORBIDDEN, + HTTP_STATUS_NOT_FOUND, + HTTP_STATUS_METHOD_NOT_ALLOWED, + HTTP_STATUS_NOT_ACCEPTABLE, + HTTP_STATUS_PROXY_AUTH_REQUIRED, + HTTP_STATUS_REQUEST_TIMEOUT, + HTTP_STATUS_CONFLICT, + HTTP_STATUS_GONE, + HTTP_STATUS_LENGTH_REQUIRED, + HTTP_STATUS_PRECONDITION_FAILED, + HTTP_STATUS_REQ_ENTITY_TOO_LARGE, + HTTP_STATUS_REQ_URI_TOO_LONG, + HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, + HTTP_STATUS_EXPECTATION_FAILED, + + HTTP_STATUS_INTERNAL_SERVER_ERROR = 500, + HTTP_STATUS_NOT_IMPLEMENTED, + HTTP_STATUS_BAD_GATEWAY, + HTTP_STATUS_SERVICE_UNAVAILABLE, + HTTP_STATUS_GATEWAY_TIMEOUT, + HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED, +}; + +struct libwebsocket; +struct libwebsocket_context; +/* needed even with extensions disabled for create context */ +struct libwebsocket_extension; + +/** + * callback_function() - User server actions + * @context: Websockets context + * @wsi: Opaque websocket instance pointer + * @reason: The reason for the call + * @user: Pointer to per-session user data allocated by library + * @in: Pointer used for some callback reasons + * @len: Length set for some callback reasons + * + * This callback is the way the user controls what is served. All the + * protocol detail is hidden and handled by the library. + * + * For each connection / session there is user data allocated that is + * pointed to by "user". You set the size of this user data area when + * the library is initialized with libwebsocket_create_server. + * + * You get an opportunity to initialize user data when called back with + * LWS_CALLBACK_ESTABLISHED reason. + * + * LWS_CALLBACK_ESTABLISHED: after the server completes a handshake with + * an incoming client + * + * LWS_CALLBACK_CLIENT_CONNECTION_ERROR: the request client connection has + * been unable to complete a handshake with the remote server + * + * LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH: this is the last chance for the + * client user code to examine the http headers + * and decide to reject the connection. If the + * content in the headers is interesting to the + * client (url, etc) it needs to copy it out at + * this point since it will be destroyed before + * the CLIENT_ESTABLISHED call + * + * LWS_CALLBACK_CLIENT_ESTABLISHED: after your client connection completed + * a handshake with the remote server + * + * LWS_CALLBACK_CLOSED: when the websocket session ends + * + * LWS_CALLBACK_CLOSED_HTTP: when a HTTP (non-websocket) session ends + * + * LWS_CALLBACK_RECEIVE: data has appeared for this server endpoint from a + * remote client, it can be found at *in and is + * len bytes long + * + * LWS_CALLBACK_CLIENT_RECEIVE_PONG: if you elected to see PONG packets, + * they appear with this callback reason. PONG + * packets only exist in 04+ protocol + * + * LWS_CALLBACK_CLIENT_RECEIVE: data has appeared from the server for the + * client connection, it can be found at *in and + * is len bytes long + * + * LWS_CALLBACK_HTTP: an http request has come from a client that is not + * asking to upgrade the connection to a websocket + * one. This is a chance to serve http content, + * for example, to send a script to the client + * which will then open the websockets connection. + * @in points to the URI path requested and + * libwebsockets_serve_http_file() makes it very + * simple to send back a file to the client. + * Normally after sending the file you are done + * with the http connection, since the rest of the + * activity will come by websockets from the script + * that was delivered by http, so you will want to + * return 1; to close and free up the connection. + * That's important because it uses a slot in the + * total number of client connections allowed set + * by MAX_CLIENTS. + * + * LWS_CALLBACK_HTTP_BODY: the next @len bytes data from the http + * request body HTTP connection is now available in @in. + * + * LWS_CALLBACK_HTTP_BODY_COMPLETION: the expected amount of http request + * body has been delivered + * + * LWS_CALLBACK_HTTP_WRITEABLE: you can write more down the http protocol + * link now. + * + * LWS_CALLBACK_HTTP_FILE_COMPLETION: a file requested to be send down + * http link has completed. + * + * LWS_CALLBACK_CLIENT_WRITEABLE: + * LWS_CALLBACK_SERVER_WRITEABLE: If you call + * libwebsocket_callback_on_writable() on a connection, you will + * get one of these callbacks coming when the connection socket + * is able to accept another write packet without blocking. + * If it already was able to take another packet without blocking, + * you'll get this callback at the next call to the service loop + * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE + * and servers get LWS_CALLBACK_SERVER_WRITEABLE. + * + * LWS_CALLBACK_FILTER_NETWORK_CONNECTION: called when a client connects to + * the server at network level; the connection is accepted but then + * passed to this callback to decide whether to hang up immediately + * or not, based on the client IP. @in contains the connection + * socket's descriptor. Since the client connection information is + * not available yet, @wsi still pointing to the main server socket. + * Return non-zero to terminate the connection before sending or + * receiving anything. Because this happens immediately after the + * network connection from the client, there's no websocket protocol + * selected yet so this callback is issued only to protocol 0. + * + * LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED: A new client just had + * been connected, accepted, and instantiated into the pool. This + * callback allows setting any relevant property to it. Because this + * happens immediately after the instantiation of a new client, + * there's no websocket protocol selected yet so this callback is + * issued only to protocol 0. Only @wsi is defined, pointing to the + * new client, and the return value is ignored. + * + * LWS_CALLBACK_FILTER_HTTP_CONNECTION: called when the request has + * been received and parsed from the client, but the response is + * not sent yet. Return non-zero to disallow the connection. + * @user is a pointer to the connection user space allocation, + * @in is the URI, eg, "/" + * In your handler you can use the public APIs + * lws_hdr_total_length() / lws_hdr_copy() to access all of the + * headers using the header enums lws_token_indexes from + * libwebsockets.h to check for and read the supported header + * presence and content before deciding to allow the http + * connection to proceed or to kill the connection. + * + * LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: called when the handshake has + * been received and parsed from the client, but the response is + * not sent yet. Return non-zero to disallow the connection. + * @user is a pointer to the connection user space allocation, + * @in is the requested protocol name + * In your handler you can use the public APIs + * lws_hdr_total_length() / lws_hdr_copy() to access all of the + * headers using the header enums lws_token_indexes from + * libwebsockets.h to check for and read the supported header + * presence and content before deciding to allow the handshake + * to proceed or to kill the connection. + * + * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS: if configured for + * including OpenSSL support, this callback allows your user code + * to perform extra SSL_CTX_load_verify_locations() or similar + * calls to direct OpenSSL where to find certificates the client + * can use to confirm the remote server identity. @user is the + * OpenSSL SSL_CTX* + * + * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS: if configured for + * including OpenSSL support, this callback allows your user code + * to load extra certifcates into the server which allow it to + * verify the validity of certificates returned by clients. @user + * is the server's OpenSSL SSL_CTX* + * + * LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY: if configured for + * including OpenSSL support but no private key file has been specified + * (ssl_private_key_filepath is NULL), this callback is called to + * allow the user to set the private key directly via libopenssl + * and perform further operations if required; this might be useful + * in situations where the private key is not directly accessible by + * the OS, for example if it is stored on a smartcard + * @user is the server's OpenSSL SSL_CTX* + * + * LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION: if the + * libwebsockets context was created with the option + * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this + * callback is generated during OpenSSL verification of the cert + * sent from the client. It is sent to protocol[0] callback as + * no protocol has been negotiated on the connection yet. + * Notice that the libwebsockets context and wsi are both NULL + * during this callback. See + * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html + * to understand more detail about the OpenSSL callback that + * generates this libwebsockets callback and the meanings of the + * arguments passed. In this callback, @user is the x509_ctx, + * @in is the ssl pointer and @len is preverify_ok + * Notice that this callback maintains libwebsocket return + * conventions, return 0 to mean the cert is OK or 1 to fail it. + * This also means that if you don't handle this callback then + * the default callback action of returning 0 allows the client + * certificates. + * + * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER: this callback happens + * when a client handshake is being compiled. @user is NULL, + * @in is a char **, it's pointing to a char * which holds the + * next location in the header buffer where you can add + * headers, and @len is the remaining space in the header buffer, + * which is typically some hundreds of bytes. So, to add a canned + * cookie, your handler code might look similar to: + * + * char **p = (char **)in; + * + * if (len < 100) + * return 1; + * + * *p += sprintf(*p, "Cookie: a=b\x0d\x0a"); + * + * return 0; + * + * Notice if you add anything, you just have to take care about + * the CRLF on the line you added. Obviously this callback is + * optional, if you don't handle it everything is fine. + * + * Notice the callback is coming to protocols[0] all the time, + * because there is no specific protocol handshook yet. + * + * LWS_CALLBACK_CONFIRM_EXTENSION_OKAY: When the server handshake code + * sees that it does support a requested extension, before + * accepting the extension by additing to the list sent back to + * the client it gives this callback just to check that it's okay + * to use that extension. It calls back to the requested protocol + * and with @in being the extension name, @len is 0 and @user is + * valid. Note though at this time the ESTABLISHED callback hasn't + * happened yet so if you initialize @user content there, @user + * content during this callback might not be useful for anything. + * Notice this callback comes to protocols[0]. + * + * LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED: When a client + * connection is being prepared to start a handshake to a server, + * each supported extension is checked with protocols[0] callback + * with this reason, giving the user code a chance to suppress the + * claim to support that extension by returning non-zero. If + * unhandled, by default 0 will be returned and the extension + * support included in the header to the server. Notice this + * callback comes to protocols[0]. + * + * LWS_CALLBACK_PROTOCOL_INIT: One-time call per protocol so it can + * do initial setup / allocations etc + * + * LWS_CALLBACK_PROTOCOL_DESTROY: One-time call per protocol indicating + * this protocol won't get used at all after this callback, the + * context is getting destroyed. Take the opportunity to + * deallocate everything that was allocated by the protocol. + * + * LWS_CALLBACK_WSI_CREATE: outermost (earliest) wsi create notification + * + * LWS_CALLBACK_WSI_DESTROY: outermost (latest) wsi destroy notification + * + * The next five reasons are optional and only need taking care of if you + * will be integrating libwebsockets sockets into an external polling + * array. + * + * For these calls, @in points to a struct libwebsocket_pollargs that + * contains @fd, @events and @prev_events members + * + * LWS_CALLBACK_ADD_POLL_FD: libwebsocket deals with its poll() loop + * internally, but in the case you are integrating with another + * server you will need to have libwebsocket sockets share a + * polling array with the other server. This and the other + * POLL_FD related callbacks let you put your specialized + * poll array interface code in the callback for protocol 0, the + * first protocol you support, usually the HTTP protocol in the + * serving case. + * This callback happens when a socket needs to be + * added to the polling loop: @in points to a struct + * libwebsocket_pollargs; the @fd member of the struct is the file + * descriptor, and @events contains the active events. + * + * If you are using the internal polling loop (the "service" + * callback), you can just ignore these callbacks. + * + * LWS_CALLBACK_DEL_POLL_FD: This callback happens when a socket descriptor + * needs to be removed from an external polling array. @in is + * again the struct libwebsocket_pollargs containing the @fd member + * to be removed. If you are using the internal polling + * loop, you can just ignore it. + * + * LWS_CALLBACK_CHANGE_MODE_POLL_FD: This callback happens when + * libwebsockets wants to modify the events for a connectiion. + * @in is the struct libwebsocket_pollargs with the @fd to change. + * The new event mask is in @events member and the old mask is in + * the @prev_events member. + * If you are using the internal polling loop, you can just ignore + * it. + * + * LWS_CALLBACK_LOCK_POLL: + * LWS_CALLBACK_UNLOCK_POLL: These allow the external poll changes driven + * by libwebsockets to participate in an external thread locking + * scheme around the changes, so the whole thing is threadsafe. + */ +LWS_VISIBLE LWS_EXTERN int callback(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_callback_reasons reason, void *user, + void *in, size_t len); + +typedef int (callback_function)(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_callback_reasons reason, void *user, + void *in, size_t len); + +#ifndef LWS_NO_EXTENSIONS +/** + * extension_callback_function() - Hooks to allow extensions to operate + * @context: Websockets context + * @ext: This extension + * @wsi: Opaque websocket instance pointer + * @reason: The reason for the call + * @user: Pointer to per-session user data allocated by library + * @in: Pointer used for some callback reasons + * @len: Length set for some callback reasons + * + * Each extension that is active on a particular connection receives + * callbacks during the connection lifetime to allow the extension to + * operate on websocket data and manage itself. + * + * Libwebsockets takes care of allocating and freeing "user" memory for + * each active extension on each connection. That is what is pointed to + * by the @user parameter. + * + * LWS_EXT_CALLBACK_CONSTRUCT: called when the server has decided to + * select this extension from the list provided by the client, + * just before the server will send back the handshake accepting + * the connection with this extension active. This gives the + * extension a chance to initialize its connection context found + * in @user. + * + * LWS_EXT_CALLBACK_CLIENT_CONSTRUCT: same as LWS_EXT_CALLBACK_CONSTRUCT + * but called when client is instantiating this extension. Some + * extensions will work the same on client and server side and then + * you can just merge handlers for both CONSTRUCTS. + * + * LWS_EXT_CALLBACK_DESTROY: called when the connection the extension was + * being used on is about to be closed and deallocated. It's the + * last chance for the extension to deallocate anything it has + * allocated in the user data (pointed to by @user) before the + * user data is deleted. This same callback is used whether you + * are in client or server instantiation context. + * + * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE: when this extension was active on + * a connection, and a packet of data arrived at the connection, + * it is passed to this callback to give the extension a chance to + * change the data, eg, decompress it. @user is pointing to the + * extension's private connection context data, @in is pointing + * to an lws_tokens struct, it consists of a char * pointer called + * token, and an int called token_len. At entry, these are + * set to point to the received buffer and set to the content + * length. If the extension will grow the content, it should use + * a new buffer allocated in its private user context data and + * set the pointed-to lws_tokens members to point to its buffer. + * + * LWS_EXT_CALLBACK_PACKET_TX_PRESEND: this works the same way as + * LWS_EXT_CALLBACK_PACKET_RX_PREPARSE above, except it gives the + * extension a chance to change websocket data just before it will + * be sent out. Using the same lws_token pointer scheme in @in, + * the extension can change the buffer and the length to be + * transmitted how it likes. Again if it wants to grow the + * buffer safely, it should copy the data into its own buffer and + * set the lws_tokens token pointer to it. + */ +LWS_VISIBLE LWS_EXTERN int extension_callback(struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len); + +typedef int (extension_callback_function)(struct libwebsocket_context *context, + struct libwebsocket_extension *ext, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons reason, + void *user, void *in, size_t len); +#endif + +/** + * struct libwebsocket_protocols - List of protocols and handlers server + * supports. + * @name: Protocol name that must match the one given in the client + * Javascript new WebSocket(url, 'protocol') name. + * @callback: The service callback used for this protocol. It allows the + * service action for an entire protocol to be encapsulated in + * the protocol-specific callback + * @per_session_data_size: Each new connection using this protocol gets + * this much memory allocated on connection establishment and + * freed on connection takedown. A pointer to this per-connection + * allocation is passed into the callback in the 'user' parameter + * @rx_buffer_size: if you want atomic frames delivered to the callback, you + * should set this to the size of the biggest legal frame that + * you support. If the frame size is exceeded, there is no + * error, but the buffer will spill to the user callback when + * full, which you can detect by using + * libwebsockets_remaining_packet_payload(). Notice that you + * just talk about frame size here, the LWS_SEND_BUFFER_PRE_PADDING + * and post-padding are automatically also allocated on top. + * @id: ignored by lws, but useful to contain user information bound + * to the selected protocol. For example if this protocol was + * called "myprotocol-v2", you might set id to 2, and the user + * code that acts differently according to the version can do so by + * switch (wsi->protocol->id), user code might use some bits as + * capability flags based on selected protocol version, etc. + * @user: User provided context data at the protocol level. + * Accessible via libwebsockets_get_protocol(wsi)->user + * This should not be confused with wsi->user, it is not the same. + * The library completely ignores any value in here. + * @owning_server: the server init call fills in this opaque pointer when + * registering this protocol with the server. + * @protocol_index: which protocol we are starting from zero + * + * This structure represents one protocol supported by the server. An + * array of these structures is passed to libwebsocket_create_server() + * allows as many protocols as you like to be handled by one server. + * + * The first protocol given has its callback used for user callbacks when + * there is no agreed protocol name, that's true during HTTP part of the + * connection and true if the client did not send a Protocol: header. + */ + +struct libwebsocket_protocols { + const char *name; + callback_function *callback; + size_t per_session_data_size; + size_t rx_buffer_size; + unsigned int id; + void *user; + + /* + * below are filled in on server init and can be left uninitialized, + * no need for user to use them directly either + */ + + struct libwebsocket_context *owning_server; + int protocol_index; +}; + +#ifndef LWS_NO_EXTENSIONS +/** + * struct libwebsocket_extension - An extension we know how to cope with + * + * @name: Formal extension name, eg, "deflate-stream" + * @callback: Service callback + * @per_session_data_size: Libwebsockets will auto-malloc this much + * memory for the use of the extension, a pointer + * to it comes in the @user callback parameter + * @per_context_private_data: Optional storage for this extension that + * is per-context, so it can track stuff across + * all sessions, etc, if it wants + */ + +struct libwebsocket_extension { + const char *name; + extension_callback_function *callback; + size_t per_session_data_size; + void *per_context_private_data; +}; +#endif + +/** + * struct lws_context_creation_info: parameters to create context with + * + * @port: Port to listen on... you can use CONTEXT_PORT_NO_LISTEN to + * suppress listening on any port, that's what you want if you are + * not running a websocket server at all but just using it as a + * client + * @iface: NULL to bind the listen socket to all interfaces, or the + * interface name, eg, "eth2" + * @protocols: Array of structures listing supported protocols and a protocol- + * specific callback for each one. The list is ended with an + * entry that has a NULL callback pointer. + * It's not const because we write the owning_server member + * @extensions: NULL or array of libwebsocket_extension structs listing the + * extensions this context supports. If you configured with + * --without-extensions, you should give NULL here. + * @token_limits: NULL or struct lws_token_limits pointer which is initialized + * with a token length limit for each possible WSI_TOKEN_*** + * @ssl_cert_filepath: If libwebsockets was compiled to use ssl, and you want + * to listen using SSL, set to the filepath to fetch the + * server cert from, otherwise NULL for unencrypted + * @ssl_private_key_filepath: filepath to private key if wanting SSL mode; + * if this is set to NULL but sll_cert_filepath is set, the + * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called to allow + * setting of the private key directly via openSSL library calls + * @ssl_ca_filepath: CA certificate filepath or NULL + * @ssl_cipher_list: List of valid ciphers to use (eg, + * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL" + * or you can leave it as NULL to get "DEFAULT" + * @gid: group id to change to after setting listen socket, or -1. + * @uid: user id to change to after setting listen socket, or -1. + * @options: 0, or LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK + * @user: optional user pointer that can be recovered via the context + * pointer using libwebsocket_context_user + * @ka_time: 0 for no keepalive, otherwise apply this keepalive timeout to + * all libwebsocket sockets, client or server + * @ka_probes: if ka_time was nonzero, after the timeout expires how many + * times to try to get a response from the peer before giving up + * and killing the connection + * @ka_interval: if ka_time was nonzero, how long to wait before each ka_probes + * attempt + * @provided_client_ssl_ctx: If non-null, swap out libwebsockets ssl + * implementation for the one provided by provided_ssl_ctx. + * Libwebsockets no longer is responsible for freeing the context + * if this option is selected. + */ + +struct lws_context_creation_info { + int port; + const char *iface; + struct libwebsocket_protocols *protocols; + struct libwebsocket_extension *extensions; + struct lws_token_limits *token_limits; + const char *ssl_private_key_password; + const char *ssl_cert_filepath; + const char *ssl_private_key_filepath; + const char *ssl_ca_filepath; + const char *ssl_cipher_list; + const char *http_proxy_address; + unsigned int http_proxy_port; + int gid; + int uid; + unsigned int options; + void *user; + int ka_time; + int ka_probes; + int ka_interval; +#ifdef LWS_OPENSSL_SUPPORT + SSL_CTX *provided_client_ssl_ctx; +#else /* maintain structure layout either way */ + void *provided_client_ssl_ctx; +#endif +}; + +LWS_VISIBLE LWS_EXTERN +void lws_set_log_level(int level, + void (*log_emit_function)(int level, const char *line)); + +LWS_VISIBLE LWS_EXTERN void +lwsl_emit_syslog(int level, const char *line); + +LWS_VISIBLE LWS_EXTERN struct libwebsocket_context * +libwebsocket_create_context(struct lws_context_creation_info *info); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_set_proxy(struct libwebsocket_context *context, const char *proxy); + +LWS_VISIBLE LWS_EXTERN void +libwebsocket_context_destroy(struct libwebsocket_context *context); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_service(struct libwebsocket_context *context, int timeout_ms); + +LWS_VISIBLE LWS_EXTERN void +libwebsocket_cancel_service(struct libwebsocket_context *context); + +LWS_VISIBLE LWS_EXTERN const unsigned char * +lws_token_to_string(enum lws_token_indexes token); + +LWS_VISIBLE LWS_EXTERN int +lws_add_http_header_by_name(struct libwebsocket_context *context, + struct libwebsocket *wsi, + const unsigned char *name, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end); +LWS_VISIBLE LWS_EXTERN int +lws_finalize_http_header(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned char **p, + unsigned char *end); +LWS_VISIBLE LWS_EXTERN int +lws_add_http_header_by_token(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum lws_token_indexes token, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end); +LWS_VISIBLE LWS_EXTERN int lws_add_http_header_content_length(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned long content_length, + unsigned char **p, + unsigned char *end); +LWS_VISIBLE LWS_EXTERN int +lws_add_http_header_status(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned int code, + unsigned char **p, + unsigned char *end); + +LWS_EXTERN int lws_http_transaction_completed(struct libwebsocket *wsi); + +#ifdef LWS_USE_LIBEV +LWS_VISIBLE LWS_EXTERN int +libwebsocket_initloop( + struct libwebsocket_context *context, struct ev_loop *loop); + +LWS_VISIBLE void +libwebsocket_sigint_cb( + struct ev_loop *loop, struct ev_signal *watcher, int revents); +#endif /* LWS_USE_LIBEV */ + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_service_fd(struct libwebsocket_context *context, + struct libwebsocket_pollfd *pollfd); + +LWS_VISIBLE LWS_EXTERN void * +libwebsocket_context_user(struct libwebsocket_context *context); + +enum pending_timeout { + NO_PENDING_TIMEOUT = 0, + PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE, + PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE, + PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, + PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, + PENDING_TIMEOUT_AWAITING_PING, + PENDING_TIMEOUT_CLOSE_ACK, + PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE, + PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, + PENDING_TIMEOUT_SSL_ACCEPT, + PENDING_TIMEOUT_HTTP_CONTENT, + PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND, +}; + +LWS_VISIBLE LWS_EXTERN void +libwebsocket_set_timeout(struct libwebsocket *wsi, + enum pending_timeout reason, int secs); + +/* + * IMPORTANT NOTICE! + * + * When sending with websocket protocol (LWS_WRITE_TEXT or LWS_WRITE_BINARY) + * the send buffer has to have LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE + * buf, and LWS_SEND_BUFFER_POST_PADDING bytes valid AFTER (buf + len). + * + * This allows us to add protocol info before and after the data, and send as + * one packet on the network without payload copying, for maximum efficiency. + * + * So for example you need this kind of code to use libwebsocket_write with a + * 128-byte payload + * + * char buf[LWS_SEND_BUFFER_PRE_PADDING + 128 + LWS_SEND_BUFFER_POST_PADDING]; + * + * // fill your part of the buffer... for example here it's all zeros + * memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, 128); + * + * libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 128, + * LWS_WRITE_TEXT); + * + * When sending LWS_WRITE_HTTP, there is no protocol addition and you can just + * use the whole buffer without taking care of the above. + */ + +/* + * this is the frame nonce plus two header plus 8 length + * there's an additional two for mux extension per mux nesting level + * 2 byte prepend on close will already fit because control frames cannot use + * the big length style + */ + +#define LWS_SEND_BUFFER_PRE_PADDING (4 + 10 + (2 * MAX_MUX_RECURSION)) +#define LWS_SEND_BUFFER_POST_PADDING 4 + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, size_t len, + enum libwebsocket_write_protocol protocol); + +/* helper for case where buffer may be const */ +#define libwebsocket_write_http(wsi, buf, len) \ + libwebsocket_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP) + +LWS_VISIBLE LWS_EXTERN int +libwebsockets_serve_http_file(struct libwebsocket_context *context, + struct libwebsocket *wsi, const char *file, + const char *content_type, const char *other_headers, + int other_headers_len); +LWS_VISIBLE LWS_EXTERN int +libwebsockets_serve_http_file_fragment(struct libwebsocket_context *context, + struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int libwebsockets_return_http_status( + struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned int code, + const char *html_body); + +LWS_VISIBLE LWS_EXTERN const struct libwebsocket_protocols * +libwebsockets_get_protocol(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_callback_on_writable(struct libwebsocket_context *context, + struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_callback_on_writable_all_protocol( + const struct libwebsocket_protocols *protocol); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_callback_all_protocol( + const struct libwebsocket_protocols *protocol, int reason); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_get_socket_fd(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_is_final_fragment(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN unsigned char +libwebsocket_get_reserved_bits(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_rx_flow_control(struct libwebsocket *wsi, int enable); + +LWS_VISIBLE LWS_EXTERN void +libwebsocket_rx_flow_allow_all_protocol( + const struct libwebsocket_protocols *protocol); + +LWS_VISIBLE LWS_EXTERN size_t +libwebsockets_remaining_packet_payload(struct libwebsocket *wsi); + +/* + * if the protocol does not have any guidence, returns -1. Currently only + * http2 connections get send window information from this API. But your code + * should use it so it can work properly with any protocol. + * + * If nonzero return is the amount of payload data the peer or intermediary has + * reported it has buffer space for. That has NO relationship with the amount + * of buffer space your OS can accept on this connection for a write action. + * + * This number represents the maximum you could send to the peer or intermediary + * on this connection right now without it complaining. + * + * lws manages accounting for send window updates and payload writes + * automatically, so this number reflects the situation at the peer or + * intermediary dynamically. + */ +LWS_VISIBLE LWS_EXTERN size_t +lws_get_peer_write_allowance(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN struct libwebsocket * +libwebsocket_client_connect(struct libwebsocket_context *clients, + const char *address, + int port, + int ssl_connection, + const char *path, + const char *host, + const char *origin, + const char *protocol, + int ietf_version_or_minus_one); + +LWS_VISIBLE LWS_EXTERN struct libwebsocket * +libwebsocket_client_connect_extended(struct libwebsocket_context *clients, + const char *address, + int port, + int ssl_connection, + const char *path, + const char *host, + const char *origin, + const char *protocol, + int ietf_version_or_minus_one, + void *userdata); + +LWS_VISIBLE LWS_EXTERN const char * +libwebsocket_canonical_hostname(struct libwebsocket_context *context); + + +LWS_VISIBLE LWS_EXTERN void +libwebsockets_get_peer_addresses(struct libwebsocket_context *context, + struct libwebsocket *wsi, int fd, char *name, int name_len, + char *rip, int rip_len); + +LWS_VISIBLE LWS_EXTERN int +libwebsockets_get_random(struct libwebsocket_context *context, + void *buf, int len); + +LWS_VISIBLE LWS_EXTERN int +lws_daemonize(const char *_lock_path); + +LWS_VISIBLE LWS_EXTERN int +lws_send_pipe_choked(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +lws_partial_buffered(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +lws_frame_is_binary(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN int +lws_is_ssl(struct libwebsocket *wsi); + +LWS_VISIBLE LWS_EXTERN unsigned char * +libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md); + +LWS_VISIBLE LWS_EXTERN int +lws_b64_encode_string(const char *in, int in_len, char *out, int out_size); + +LWS_VISIBLE LWS_EXTERN int +lws_b64_decode_string(const char *in, char *out, int out_size); + +LWS_VISIBLE LWS_EXTERN const char * +lws_get_library_version(void); + +/* access to headers... only valid while headers valid */ + +LWS_VISIBLE LWS_EXTERN int +lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h); + +LWS_VISIBLE LWS_EXTERN int +lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len, + enum lws_token_indexes h); + +/* + * Note: this is not normally needed as a user api. It's provided in case it is + * useful when integrating with other app poll loop service code. + */ + +LWS_VISIBLE LWS_EXTERN int +libwebsocket_read(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned char *buf, size_t len); + +#ifndef LWS_NO_EXTENSIONS +LWS_VISIBLE LWS_EXTERN struct libwebsocket_extension *libwebsocket_get_internal_extensions(); +#endif + +/* + * custom allocator support + */ +LWS_VISIBLE LWS_EXTERN void +lws_set_allocator(void *(*realloc)(void *ptr, size_t size)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/engine/external/libwebsockets/lws-plat-unix.c b/src/engine/external/libwebsockets/lws-plat-unix.c new file mode 100644 index 0000000..9af4bdf --- /dev/null +++ b/src/engine/external/libwebsockets/lws-plat-unix.c @@ -0,0 +1,442 @@ +#include "private-libwebsockets.h" + +/* + * included from libwebsockets.c for unix builds + */ + +unsigned long long time_in_microseconds(void) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + return (tv.tv_sec * 1000000) + tv.tv_usec; +} + +LWS_VISIBLE int libwebsockets_get_random(struct libwebsocket_context *context, + void *buf, int len) +{ + return read(context->fd_random, (char *)buf, len); +} + +LWS_VISIBLE int lws_send_pipe_choked(struct libwebsocket *wsi) +{ + struct libwebsocket_pollfd fds; + + /* treat the fact we got a truncated send pending as if we're choked */ + if (wsi->truncated_send_len) + return 1; + + fds.fd = wsi->sock; + fds.events = POLLOUT; + fds.revents = 0; + + if (poll(&fds, 1, 0) != 1) + return 1; + + if ((fds.revents & POLLOUT) == 0) + return 1; + + /* okay to send another packet without blocking */ + + return 0; +} + +LWS_VISIBLE int +lws_poll_listen_fd(struct libwebsocket_pollfd *fd) +{ + return poll(fd, 1, 0); +} + +/* + * This is just used to interrupt poll waiting + * we don't have to do anything with it. + */ +static void lws_sigusr2(int sig) +{ +} + +/** + * libwebsocket_cancel_service() - Cancel servicing of pending websocket activity + * @context: Websocket context + * + * This function let a call to libwebsocket_service() waiting for a timeout + * immediately return. + */ +LWS_VISIBLE void +libwebsocket_cancel_service(struct libwebsocket_context *context) +{ + char buf = 0; + + if (write(context->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1) + lwsl_err("Cannot write to dummy pipe"); +} + +LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line) +{ + int syslog_level = LOG_DEBUG; + + switch (level) { + case LLL_ERR: + syslog_level = LOG_ERR; + break; + case LLL_WARN: + syslog_level = LOG_WARNING; + break; + case LLL_NOTICE: + syslog_level = LOG_NOTICE; + break; + case LLL_INFO: + syslog_level = LOG_INFO; + break; + } + syslog(syslog_level, "%s", line); +} + +LWS_VISIBLE int +lws_plat_service(struct libwebsocket_context *context, int timeout_ms) +{ + int n; + int m; + char buf; + + /* stay dead once we are dead */ + + if (!context) + return 1; + + lws_libev_run(context); + + context->service_tid = context->protocols[0].callback(context, NULL, + LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0); + +#ifdef LWS_OPENSSL_SUPPORT + /* if we know we have non-network pending data, do not wait in poll */ + if (context->ssl_flag_buffered_reads) + timeout_ms = 0; +#endif + n = poll(context->fds, context->fds_count, timeout_ms); + context->service_tid = 0; + +#ifdef LWS_OPENSSL_SUPPORT + if (!context->ssl_flag_buffered_reads && n == 0) { +#else + if (n == 0) /* poll timeout */ { +#endif + libwebsocket_service_fd(context, NULL); + return 0; + } + +#ifdef LWS_OPENSSL_SUPPORT + /* any more will have to set it fresh this time around */ + context->ssl_flag_buffered_reads = 0; +#endif + + if (n < 0) { + if (LWS_ERRNO != LWS_EINTR) + return -1; + return 0; + } + + /* any socket with events to service? */ + + for (n = 0; n < context->fds_count; n++) { +#ifdef LWS_OPENSSL_SUPPORT + struct libwebsocket *wsi; + + wsi = context->lws_lookup[context->fds[n].fd]; + if (wsi == NULL) + continue; + /* + * if he's not flowcontrolled, make sure we service ssl + * pending read data + */ + if (wsi->ssl && wsi->buffered_reads_pending) { + lwsl_debug("wsi %p: forcing POLLIN\n", wsi); + context->fds[n].revents |= context->fds[n].events & POLLIN; + if (context->fds[n].revents & POLLIN) + wsi->buffered_reads_pending = 0; + else + /* somebody left with pending SSL read data */ + context->ssl_flag_buffered_reads = 1; + } +#endif + if (!context->fds[n].revents) + continue; + + if (context->fds[n].fd == context->dummy_pipe_fds[0]) { + if (read(context->fds[n].fd, &buf, 1) != 1) + lwsl_err("Cannot read from dummy pipe."); + continue; + } + + m = libwebsocket_service_fd(context, &context->fds[n]); + if (m < 0) + return -1; + /* if something closed, retry this slot */ + if (m) + n--; + } + + return 0; +} + +LWS_VISIBLE int +lws_plat_set_socket_options(struct libwebsocket_context *context, int fd) +{ + int optval = 1; + socklen_t optlen = sizeof(optval); + +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__OpenBSD__) + struct protoent *tcp_proto; +#endif + + if (context->ka_time) { + /* enable keepalive on this socket */ + optval = 1; + if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, + (const void *)&optval, optlen) < 0) + return 1; + +#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ + defined(__CYGWIN__) || defined(__OpenBSD__) + + /* + * didn't find a way to set these per-socket, need to + * tune kernel systemwide values + */ +#else + /* set the keepalive conditions we want on it too */ + optval = context->ka_time; + if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, + (const void *)&optval, optlen) < 0) + return 1; + + optval = context->ka_interval; + if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, + (const void *)&optval, optlen) < 0) + return 1; + + optval = context->ka_probes; + if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, + (const void *)&optval, optlen) < 0) + return 1; +#endif + } + + /* Disable Nagle */ + optval = 1; +#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && \ + !defined(__OpenBSD__) + if (setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0) + return 1; +#else + tcp_proto = getprotobyname("TCP"); + if (setsockopt(fd, tcp_proto->p_proto, TCP_NODELAY, &optval, optlen) < 0) + return 1; +#endif + + /* We are nonblocking... */ + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) + return 1; + + return 0; +} + +LWS_VISIBLE void +lws_plat_drop_app_privileges(struct lws_context_creation_info *info) +{ + if (info->gid != -1) + if (setgid(info->gid)) + lwsl_warn("setgid: %s\n", strerror(LWS_ERRNO)); + if (info->uid != -1) + if (setuid(info->uid)) + lwsl_warn("setuid: %s\n", strerror(LWS_ERRNO)); +} + +LWS_VISIBLE int +lws_plat_init_fd_tables(struct libwebsocket_context *context) +{ + if (lws_libev_init_fd_table(context)) + /* libev handled it instead */ + return 0; + + if (pipe(context->dummy_pipe_fds)) { + lwsl_err("Unable to create pipe\n"); + return 1; + } + + /* use the read end of pipe as first item */ + context->fds[0].fd = context->dummy_pipe_fds[0]; + context->fds[0].events = LWS_POLLIN; + context->fds[0].revents = 0; + context->fds_count = 1; + + context->fd_random = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY); + if (context->fd_random < 0) { + lwsl_err("Unable to open random device %s %d\n", + SYSTEM_RANDOM_FILEPATH, context->fd_random); + return 1; + } + + return 0; +} + +static void sigpipe_handler(int x) +{ +} + + +LWS_VISIBLE int +lws_plat_context_early_init(void) +{ + sigset_t mask; + + signal(SIGUSR2, lws_sigusr2); + sigemptyset(&mask); + sigaddset(&mask, SIGUSR2); + + sigprocmask(SIG_BLOCK, &mask, NULL); + + signal(SIGPIPE, sigpipe_handler); + + return 0; +} + +LWS_VISIBLE void +lws_plat_context_early_destroy(struct libwebsocket_context *context) +{ +} + +LWS_VISIBLE void +lws_plat_context_late_destroy(struct libwebsocket_context *context) +{ + close(context->dummy_pipe_fds[0]); + close(context->dummy_pipe_fds[1]); + close(context->fd_random); +} + +/* cast a struct sockaddr_in6 * into addr for ipv6 */ + +LWS_VISIBLE int +interface_to_sa(struct libwebsocket_context *context, + const char *ifname, struct sockaddr_in *addr, size_t addrlen) +{ + int rc = -1; + + struct ifaddrs *ifr; + struct ifaddrs *ifc; +#ifdef LWS_USE_IPV6 + struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr; +#endif + + getifaddrs(&ifr); + for (ifc = ifr; ifc != NULL && rc; ifc = ifc->ifa_next) { + if (!ifc->ifa_addr) + continue; + + lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname); + + if (strcmp(ifc->ifa_name, ifname)) + continue; + + switch (ifc->ifa_addr->sa_family) { + case AF_INET: +#ifdef LWS_USE_IPV6 + if (LWS_IPV6_ENABLED(context)) { + /* map IPv4 to IPv6 */ + bzero((char *)&addr6->sin6_addr, + sizeof(struct in6_addr)); + addr6->sin6_addr.s6_addr[10] = 0xff; + addr6->sin6_addr.s6_addr[11] = 0xff; + memcpy(&addr6->sin6_addr.s6_addr[12], + &((struct sockaddr_in *)ifc->ifa_addr)->sin_addr, + sizeof(struct in_addr)); + } else +#endif + memcpy(addr, + (struct sockaddr_in *)ifc->ifa_addr, + sizeof(struct sockaddr_in)); + break; +#ifdef LWS_USE_IPV6 + case AF_INET6: + memcpy(&addr6->sin6_addr, + &((struct sockaddr_in6 *)ifc->ifa_addr)->sin6_addr, + sizeof(struct in6_addr)); + break; +#endif + default: + continue; + } + rc = 0; + } + + freeifaddrs(ifr); + + if (rc == -1) { + /* check if bind to IP adddress */ +#ifdef LWS_USE_IPV6 + if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1) + rc = 0; + else +#endif + if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1) + rc = 0; + } + + return rc; +} + +LWS_VISIBLE void +lws_plat_insert_socket_into_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ + lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_READ); + context->fds[context->fds_count++].revents = 0; +} + +LWS_VISIBLE void +lws_plat_delete_socket_from_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi, int m) +{ +} + +LWS_VISIBLE void +lws_plat_service_periodic(struct libwebsocket_context *context) +{ + /* if our parent went down, don't linger around */ + if (context->started_with_parent && + kill(context->started_with_parent, 0) < 0) + kill(getpid(), SIGTERM); +} + +LWS_VISIBLE int +lws_plat_change_pollfd(struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pfd) +{ + return 0; +} + +LWS_VISIBLE int +lws_plat_open_file(const char* filename, unsigned long* filelen) +{ + struct stat stat_buf; + int ret = open(filename, O_RDONLY); + + if (ret < 0) + return LWS_INVALID_FILE; + + if (fstat(ret, &stat_buf) < 0) { + close(ret); + return LWS_INVALID_FILE; + } + *filelen = stat_buf.st_size; + return ret; +} + +#ifdef LWS_USE_IPV6 +LWS_VISIBLE const char * +lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt) +{ + return inet_ntop(af, src, dst, cnt); +} +#endif diff --git a/src/engine/external/libwebsockets/output.c b/src/engine/external/libwebsockets/output.c new file mode 100644 index 0000000..b914f28 --- /dev/null +++ b/src/engine/external/libwebsockets/output.c @@ -0,0 +1,606 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +static int +libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi) +{ + int n; + + /* fetch the per-frame nonce */ + + n = libwebsockets_get_random(wsi->protocol->owning_server, + wsi->u.ws.frame_masking_nonce_04, 4); + if (n != 4) { + lwsl_parser("Unable to read from random device %s %d\n", + SYSTEM_RANDOM_FILEPATH, n); + return 1; + } + + /* start masking from first byte of masking key buffer */ + wsi->u.ws.frame_mask_index = 0; + + return 0; +} + +#ifdef _DEBUG + +LWS_VISIBLE void lwsl_hexdump(void *vbuf, size_t len) +{ + int n; + int m; + int start; + unsigned char *buf = (unsigned char *)vbuf; + char line[80]; + char *p; + + lwsl_parser("\n"); + + for (n = 0; n < len;) { + start = n; + p = line; + + p += sprintf(p, "%04X: ", start); + + for (m = 0; m < 16 && n < len; m++) + p += sprintf(p, "%02X ", buf[n++]); + while (m++ < 16) + p += sprintf(p, " "); + + p += sprintf(p, " "); + + for (m = 0; m < 16 && (start + m) < len; m++) { + if (buf[start + m] >= ' ' && buf[start + m] < 127) + *p++ = buf[start + m]; + else + *p++ = '.'; + } + while (m++ < 16) + *p++ = ' '; + + *p++ = '\n'; + *p = '\0'; + lwsl_debug("%s", line); + } + lwsl_debug("\n"); +} + +#endif + +/* + * notice this returns number of bytes consumed, or -1 + */ + +int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len) +{ + struct libwebsocket_context *context = wsi->protocol->owning_server; + int n; + size_t real_len = len; + int m; + + if (!len) + return 0; + /* just ignore sends after we cleared the truncation buffer */ + if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE && + !wsi->truncated_send_len) + return len; + + if (wsi->truncated_send_len && (buf < wsi->truncated_send_malloc || + buf > (wsi->truncated_send_malloc + + wsi->truncated_send_len + + wsi->truncated_send_offset))) { + lwsl_err("****** %x Sending new, pending truncated ...\n", wsi); + assert(0); + } + + m = lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PACKET_TX_DO_SEND, &buf, len); + if (m < 0) + return -1; + if (m) /* handled */ { + n = m; + goto handle_truncated_send; + } + if (wsi->sock < 0) + lwsl_warn("** error invalid sock but expected to send\n"); + + /* + * nope, send it on the socket directly + */ + lws_latency_pre(context, wsi); + n = lws_ssl_capable_write(wsi, buf, len); + lws_latency(context, wsi, "send lws_issue_raw", n, n == len); + + switch (n) { + case LWS_SSL_CAPABLE_ERROR: + /* we're going to close, let close know sends aren't possible */ + wsi->socket_is_permanently_unusable = 1; + return -1; + case LWS_SSL_CAPABLE_MORE_SERVICE: + /* nothing got sent, not fatal, retry the whole thing later */ + n = 0; + break; + } + +handle_truncated_send: + /* + * we were already handling a truncated send? + */ + if (wsi->truncated_send_len) { + lwsl_info("***** %x partial send moved on by %d (vs %d)\n", + wsi, n, real_len); + wsi->truncated_send_offset += n; + wsi->truncated_send_len -= n; + + if (!wsi->truncated_send_len) { + lwsl_info("***** %x partial send completed\n", wsi); + /* done with it, but don't free it */ + n = real_len; + if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) { + lwsl_info("***** %x signalling to close now\n", wsi); + return -1; /* retry closing now */ + } + } + /* always callback on writeable */ + libwebsocket_callback_on_writable( + wsi->protocol->owning_server, wsi); + + return n; + } + + if (n == real_len) + /* what we just sent went out cleanly */ + return n; + + if (n && wsi->u.ws.clean_buffer) + /* + * This buffer unaffected by extension rewriting. + * It means the user code is expected to deal with + * partial sends. (lws knows the header was already + * sent, so on next send will just resume sending + * payload) + */ + return n; + + /* + * Newly truncated send. Buffer the remainder (it will get + * first priority next time the socket is writable) + */ + lwsl_info("***** %x new partial sent %d from %d total\n", + wsi, n, real_len); + + /* + * - if we still have a suitable malloc lying around, use it + * - or, if too small, reallocate it + * - or, if no buffer, create it + */ + if (!wsi->truncated_send_malloc || + real_len - n > wsi->truncated_send_allocation) { + lws_free(wsi->truncated_send_malloc); + + wsi->truncated_send_allocation = real_len - n; + wsi->truncated_send_malloc = lws_malloc(real_len - n); + if (!wsi->truncated_send_malloc) { + lwsl_err("truncated send: unable to malloc %d\n", + real_len - n); + return -1; + } + } + wsi->truncated_send_offset = 0; + wsi->truncated_send_len = real_len - n; + memcpy(wsi->truncated_send_malloc, buf + n, real_len - n); + + /* since something buffered, force it to get another chance to send */ + libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi); + + return real_len; +} + +/** + * libwebsocket_write() - Apply protocol then write data to client + * @wsi: Websocket instance (available from user callback) + * @buf: The data to send. For data being sent on a websocket + * connection (ie, not default http), this buffer MUST have + * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer + * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid + * in the buffer after (buf + len). This is so the protocol + * header and trailer data can be added in-situ. + * @len: Count of the data bytes in the payload starting from buf + * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one + * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate + * data on a websockets connection. Remember to allow the extra + * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT + * are used. + * + * This function provides the way to issue data back to the client + * for both http and websocket protocols. + * + * In the case of sending using websocket protocol, be sure to allocate + * valid storage before and after buf as explained above. This scheme + * allows maximum efficiency of sending data and protocol in a single + * packet while not burdening the user code with any protocol knowledge. + * + * Return may be -1 for a fatal error needing connection close, or a + * positive number reflecting the amount of bytes actually sent. This + * can be less than the requested number of bytes due to OS memory + * pressure at any given time. + */ + +LWS_VISIBLE int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf, + size_t len, enum libwebsocket_write_protocol protocol) +{ + int n; + int pre = 0; + int post = 0; + int masked7 = wsi->mode == LWS_CONNMODE_WS_CLIENT; + unsigned char *dropmask = NULL; + unsigned char is_masked_bit = 0; + size_t orig_len = len; + struct lws_tokens eff_buf; + + if (len == 0 && protocol != LWS_WRITE_CLOSE && + protocol != LWS_WRITE_PING && protocol != LWS_WRITE_PONG) { + lwsl_warn("zero length libwebsocket_write attempt\n"); + return 0; + } + + if (protocol == LWS_WRITE_HTTP || + protocol == LWS_WRITE_HTTP_FINAL || + protocol == LWS_WRITE_HTTP_HEADERS) + goto send_raw; + + /* websocket protocol, either binary or text */ + + if (wsi->state != WSI_STATE_ESTABLISHED) + return -1; + + /* if we are continuing a frame that already had its header done */ + + if (wsi->u.ws.inside_frame) + goto do_more_inside_frame; + + wsi->u.ws.clean_buffer = 1; + + /* + * give a chance to the extensions to modify payload + * pre-TX mangling is not allowed to truncate + */ + eff_buf.token = (char *)buf; + eff_buf.token_len = len; + + switch (protocol) { + case LWS_WRITE_PING: + case LWS_WRITE_PONG: + case LWS_WRITE_CLOSE: + break; + default: + if (lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PAYLOAD_TX, &eff_buf, 0) < 0) + return -1; + } + + /* + * an extension did something we need to keep... for example, if + * compression extension, it has already updated its state according + * to this being issued + */ + if ((char *)buf != eff_buf.token) + /* + * extension recreated it: + * need to buffer this if not all sent + */ + wsi->u.ws.clean_buffer = 0; + + buf = (unsigned char *)eff_buf.token; + len = eff_buf.token_len; + + switch (wsi->ietf_spec_revision) { + case 13: + + if (masked7) { + pre += 4; + dropmask = &buf[0 - pre]; + is_masked_bit = 0x80; + } + + switch (protocol & 0xf) { + case LWS_WRITE_TEXT: + n = LWS_WS_OPCODE_07__TEXT_FRAME; + break; + case LWS_WRITE_BINARY: + n = LWS_WS_OPCODE_07__BINARY_FRAME; + break; + case LWS_WRITE_CONTINUATION: + n = LWS_WS_OPCODE_07__CONTINUATION; + break; + + case LWS_WRITE_CLOSE: + n = LWS_WS_OPCODE_07__CLOSE; + + /* + * 06+ has a 2-byte status code in network order + * we can do this because we demand post-buf + */ + + if (wsi->u.ws.close_reason) { + /* reason codes count as data bytes */ + buf -= 2; + buf[0] = wsi->u.ws.close_reason >> 8; + buf[1] = wsi->u.ws.close_reason; + len += 2; + } + break; + case LWS_WRITE_PING: + n = LWS_WS_OPCODE_07__PING; + break; + case LWS_WRITE_PONG: + n = LWS_WS_OPCODE_07__PONG; + break; + default: + lwsl_warn("lws_write: unknown write opc / protocol\n"); + return -1; + } + + if (!(protocol & LWS_WRITE_NO_FIN)) + n |= 1 << 7; + + if (len < 126) { + pre += 2; + buf[-pre] = n; + buf[-pre + 1] = len | is_masked_bit; + } else { + if (len < 65536) { + pre += 4; + buf[-pre] = n; + buf[-pre + 1] = 126 | is_masked_bit; + buf[-pre + 2] = len >> 8; + buf[-pre + 3] = len; + } else { + pre += 10; + buf[-pre] = n; + buf[-pre + 1] = 127 | is_masked_bit; +#if defined __LP64__ + buf[-pre + 2] = (len >> 56) & 0x7f; + buf[-pre + 3] = len >> 48; + buf[-pre + 4] = len >> 40; + buf[-pre + 5] = len >> 32; +#else + buf[-pre + 2] = 0; + buf[-pre + 3] = 0; + buf[-pre + 4] = 0; + buf[-pre + 5] = 0; +#endif + buf[-pre + 6] = len >> 24; + buf[-pre + 7] = len >> 16; + buf[-pre + 8] = len >> 8; + buf[-pre + 9] = len; + } + } + break; + } + +do_more_inside_frame: + + /* + * Deal with masking if we are in client -> server direction and + * the protocol demands it + */ + + if (wsi->mode == LWS_CONNMODE_WS_CLIENT) { + + if (!wsi->u.ws.inside_frame) + if (libwebsocket_0405_frame_mask_generate(wsi)) { + lwsl_err("frame mask generation failed\n"); + return -1; + } + + /* + * in v7, just mask the payload + */ + if (dropmask) { /* never set if already inside frame */ + for (n = 4; n < (int)len + 4; n++) + dropmask[n] = dropmask[n] ^ + wsi->u.ws.frame_masking_nonce_04[ + (wsi->u.ws.frame_mask_index++) & 3]; + + /* copy the frame nonce into place */ + memcpy(dropmask, wsi->u.ws.frame_masking_nonce_04, 4); + } + } + +send_raw: + switch (protocol) { + case LWS_WRITE_CLOSE: +/* lwsl_hexdump(&buf[-pre], len + post); */ + case LWS_WRITE_HTTP: + case LWS_WRITE_HTTP_FINAL: + case LWS_WRITE_HTTP_HEADERS: + case LWS_WRITE_PONG: + case LWS_WRITE_PING: +#ifdef LWS_USE_HTTP2 + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) { + unsigned char flags = 0; + + n = LWS_HTTP2_FRAME_TYPE_DATA; + if (protocol == LWS_WRITE_HTTP_HEADERS) { + n = LWS_HTTP2_FRAME_TYPE_HEADERS; + flags = LWS_HTTP2_FLAG_END_HEADERS; + if (wsi->u.http2.send_END_STREAM) + flags |= LWS_HTTP2_FLAG_END_STREAM; + } + + if ((protocol == LWS_WRITE_HTTP || protocol == LWS_WRITE_HTTP_FINAL) && wsi->u.http.content_length) { + wsi->u.http.content_remain -= len; + lwsl_info("%s: content_remain = %lu\n", __func__, wsi->u.http.content_remain); + if (!wsi->u.http.content_remain) { + lwsl_info("%s: selecting final write mode\n", __func__); + protocol = LWS_WRITE_HTTP_FINAL; + } + } + + if (protocol == LWS_WRITE_HTTP_FINAL && wsi->u.http2.END_STREAM) { + lwsl_info("%s: setting END_STREAM\n", __func__); + flags |= LWS_HTTP2_FLAG_END_STREAM; + } + + return lws_http2_frame_write(wsi, n, flags, wsi->u.http2.my_stream_id, len, buf); + } +#endif + return lws_issue_raw(wsi, (unsigned char *)buf - pre, + len + pre + post); + default: + break; + } + + wsi->u.ws.inside_frame = 1; + + /* + * give any active extensions a chance to munge the buffer + * before send. We pass in a pointer to an lws_tokens struct + * prepared with the default buffer and content length that's in + * there. Rather than rewrite the default buffer, extensions + * that expect to grow the buffer can adapt .token to + * point to their own per-connection buffer in the extension + * user allocation. By default with no extensions or no + * extension callback handling, just the normal input buffer is + * used then so it is efficient. + * + * callback returns 1 in case it wants to spill more buffers + * + * This takes care of holding the buffer if send is incomplete, ie, + * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with + * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead + * return to the user code how much OF THE USER BUFFER was consumed. + */ + + n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre + post); + if (n <= 0) + return n; + + if (n == len + pre + post) { + /* everything in the buffer was handled (or rebuffered...) */ + wsi->u.ws.inside_frame = 0; + return orig_len; + } + + /* + * it is how many bytes of user buffer got sent... may be < orig_len + * in which case callback when writable has already been arranged + * and user code can call libwebsocket_write() again with the rest + * later. + */ + + return n - (pre + post); +} + +LWS_VISIBLE int libwebsockets_serve_http_file_fragment( + struct libwebsocket_context *context, struct libwebsocket *wsi) +{ + int n; + int m; + + while (!lws_send_pipe_choked(wsi)) { + + if (wsi->truncated_send_len) { + if (lws_issue_raw(wsi, wsi->truncated_send_malloc + + wsi->truncated_send_offset, + wsi->truncated_send_len) < 0) { + lwsl_info("closing from libwebsockets_serve_http_file_fragment\n"); + return -1; + } + continue; + } + + if (wsi->u.http.filepos == wsi->u.http.filelen) + goto all_sent; + + compatible_file_read(n, wsi->u.http.fd, context->service_buffer, + sizeof(context->service_buffer)); + if (n < 0) + return -1; /* caller will close */ + if (n) { + wsi->u.http.filepos += n; + m = libwebsocket_write(wsi, context->service_buffer, n, + wsi->u.http.filepos == wsi->u.http.filelen ? LWS_WRITE_HTTP_FINAL : LWS_WRITE_HTTP); + if (m < 0) + return -1; + + if (m != n) + /* adjust for what was not sent */ + if (compatible_file_seek_cur(wsi->u.http.fd, m - n) < 0) + return -1; + } +all_sent: + if (!wsi->truncated_send_len && + wsi->u.http.filepos == wsi->u.http.filelen) { + wsi->state = WSI_STATE_HTTP; + + if (wsi->protocol->callback) + /* ignore callback returned value */ + user_callback_handle_rxflow( + wsi->protocol->callback, context, wsi, + LWS_CALLBACK_HTTP_FILE_COMPLETION, + wsi->user_space, NULL, 0); + return 1; /* >0 indicates completed */ + } + } + + lwsl_info("choked before able to send whole file (post)\n"); + libwebsocket_callback_on_writable(context, wsi); + + return 0; /* indicates further processing must be done */ +} + +LWS_VISIBLE int +lws_ssl_capable_read_no_ssl(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char *buf, int len) +{ + int n; + + n = recv(wsi->sock, buf, len, 0); + if (n >= 0) + return n; + + lwsl_warn("error on reading from skt\n"); + return LWS_SSL_CAPABLE_ERROR; +} + +LWS_VISIBLE int +lws_ssl_capable_write_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len) +{ + int n; + + n = send(wsi->sock, buf, len, 0); + if (n >= 0) + return n; + + if (LWS_ERRNO == LWS_EAGAIN || + LWS_ERRNO == LWS_EWOULDBLOCK || + LWS_ERRNO == LWS_EINTR) { + if (LWS_ERRNO == LWS_EWOULDBLOCK) + lws_set_blocking_send(wsi); + + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + lwsl_debug("ERROR writing len %d to skt %d\n", len, n); + return LWS_SSL_CAPABLE_ERROR; +} diff --git a/src/engine/external/libwebsockets/parsers.c b/src/engine/external/libwebsockets/parsers.c new file mode 100644 index 0000000..2b4a900 --- /dev/null +++ b/src/engine/external/libwebsockets/parsers.c @@ -0,0 +1,1015 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +unsigned char lextable[] = { + #include "lextable.h" +}; + +#define FAIL_CHAR 0x08 + +int lextable_decode(int pos, char c) +{ + + c = tolower(c); + + while (1) { + if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */ + if ((lextable[pos] & 0x7f) != c) + return -1; + /* fall thru */ + pos++; + if (lextable[pos] == FAIL_CHAR) + return -1; + return pos; + } + + if (lextable[pos] == FAIL_CHAR) + return -1; + + /* b7 = 0, end or 3-byte */ + if (lextable[pos] < FAIL_CHAR) /* terminal marker */ + return pos; + + if (lextable[pos] == c) /* goto */ + return pos + (lextable[pos + 1]) + + (lextable[pos + 2] << 8); + /* fall thru goto */ + pos += 3; + /* continue */ + } +} + +int lws_allocate_header_table(struct libwebsocket *wsi) +{ + /* Be sure to free any existing header data to avoid mem leak: */ + lws_free_header_table(wsi); + wsi->u.hdr.ah = lws_malloc(sizeof(*wsi->u.hdr.ah)); + if (wsi->u.hdr.ah == NULL) { + lwsl_err("Out of memory\n"); + return -1; + } + memset(wsi->u.hdr.ah->frag_index, 0, sizeof(wsi->u.hdr.ah->frag_index)); + wsi->u.hdr.ah->next_frag_index = 0; + wsi->u.hdr.ah->pos = 0; + + return 0; +} + +int lws_free_header_table(struct libwebsocket *wsi) +{ + lws_free2(wsi->u.hdr.ah); + wsi->u.hdr.ah = NULL; + return 0; +}; + +LWS_VISIBLE int lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h) +{ + int n; + int len = 0; + + n = wsi->u.hdr.ah->frag_index[h]; + if (!n) + return 0; + do { + len += wsi->u.hdr.ah->frags[n].len; + n = wsi->u.hdr.ah->frags[n].next_frag_index; + } while (n); + + return len; +} + +LWS_VISIBLE int lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len, + enum lws_token_indexes h) +{ + int toklen = lws_hdr_total_length(wsi, h); + int n; + + if (toklen >= len) + return -1; + + n = wsi->u.hdr.ah->frag_index[h]; + if (!n) + return 0; + + do { + strcpy(dest, + &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]); + dest += wsi->u.hdr.ah->frags[n].len; + n = wsi->u.hdr.ah->frags[n].next_frag_index; + } while (n); + + return toklen; +} + +char *lws_hdr_simple_ptr(struct libwebsocket *wsi, enum lws_token_indexes h) +{ + int n; + + n = wsi->u.hdr.ah->frag_index[h]; + if (!n) + return NULL; + + return &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]; +} + +int lws_hdr_simple_create(struct libwebsocket *wsi, + enum lws_token_indexes h, const char *s) +{ + wsi->u.hdr.ah->next_frag_index++; + if (wsi->u.hdr.ah->next_frag_index == + sizeof(wsi->u.hdr.ah->frags) / sizeof(wsi->u.hdr.ah->frags[0])) { + lwsl_warn("More hdr frags than we can deal with, dropping\n"); + return -1; + } + + wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->next_frag_index; + + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].offset = + wsi->u.hdr.ah->pos; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len = 0; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].next_frag_index = + 0; + + do { + if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) { + lwsl_err("Ran out of header data space\n"); + return -1; + } + wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s; + if (*s) + wsi->u.hdr.ah->frags[ + wsi->u.hdr.ah->next_frag_index].len++; + } while (*s++); + + return 0; +} + +static char char_to_hex(const char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + + return -1; +} + +static int issue_char(struct libwebsocket *wsi, unsigned char c) +{ + if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) { + lwsl_warn("excessive header content\n"); + return -1; + } + + if( wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len >= + wsi->u.hdr.current_token_limit) { + lwsl_warn("header %i exceeds limit\n", wsi->u.hdr.parser_state); + return 1; + }; + + wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c; + if (c) + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len++; + + return 0; +} + +int libwebsocket_parse( + struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char c) +{ + int n; + + switch (wsi->u.hdr.parser_state) { + default: + + lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c); + + /* collect into malloc'd buffers */ + /* optional initial space swallow */ + if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->frag_index[ + wsi->u.hdr.parser_state]].len && c == ' ') + break; + + if ((wsi->u.hdr.parser_state != WSI_TOKEN_GET_URI) && + (wsi->u.hdr.parser_state != WSI_TOKEN_POST_URI) && + (wsi->u.hdr.parser_state != WSI_TOKEN_OPTIONS_URI)) + goto check_eol; + + /* special URI processing... end at space */ + + if (c == ' ') { + /* enforce starting with / */ + if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len) + if (issue_char(wsi, '/') < 0) + return -1; + + /* begin parsing HTTP version: */ + if (issue_char(wsi, '\0') < 0) + return -1; + wsi->u.hdr.parser_state = WSI_TOKEN_HTTP; + goto start_fragment; + } + + /* special URI processing... convert %xx */ + + switch (wsi->u.hdr.ues) { + case URIES_IDLE: + if (c == '%') { + wsi->u.hdr.ues = URIES_SEEN_PERCENT; + goto swallow; + } + break; + case URIES_SEEN_PERCENT: + if (char_to_hex(c) < 0) { + /* regurgitate */ + if (issue_char(wsi, '%') < 0) + return -1; + wsi->u.hdr.ues = URIES_IDLE; + /* continue on to assess c */ + break; + } + wsi->u.hdr.esc_stash = c; + wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1; + goto swallow; + + case URIES_SEEN_PERCENT_H1: + if (char_to_hex(c) < 0) { + /* regurgitate */ + issue_char(wsi, '%'); + wsi->u.hdr.ues = URIES_IDLE; + /* regurgitate + assess */ + if (libwebsocket_parse(context, wsi, wsi->u.hdr.esc_stash) < 0) + return -1; + /* continue on to assess c */ + break; + } + c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) | + char_to_hex(c); + wsi->u.hdr.ues = URIES_IDLE; + break; + } + + /* + * special URI processing... + * convert /.. or /... or /../ etc to / + * convert /./ to / + * convert // or /// etc to / + * leave /.dir or whatever alone + */ + + switch (wsi->u.hdr.ups) { + case URIPS_IDLE: + /* issue the first / always */ + if (c == '/') + wsi->u.hdr.ups = URIPS_SEEN_SLASH; + break; + case URIPS_SEEN_SLASH: + /* swallow subsequent slashes */ + if (c == '/') + goto swallow; + /* track and swallow the first . after / */ + if (c == '.') { + wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT; + goto swallow; + } + wsi->u.hdr.ups = URIPS_IDLE; + break; + case URIPS_SEEN_SLASH_DOT: + /* swallow second . */ + if (c == '.') { + /* + * back up one dir level if possible + * safe against header fragmentation because + * the method URI can only be in 1 fragment + */ + if (wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len > 2) { + wsi->u.hdr.ah->pos--; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len--; + do { + wsi->u.hdr.ah->pos--; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len--; + } while (wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len > 1 && + wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos] != '/'); + } + wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT; + goto swallow; + } + /* change /./ to / */ + if (c == '/') { + wsi->u.hdr.ups = URIPS_SEEN_SLASH; + goto swallow; + } + /* it was like /.dir ... regurgitate the . */ + wsi->u.hdr.ups = URIPS_IDLE; + issue_char(wsi, '.'); + break; + + case URIPS_SEEN_SLASH_DOT_DOT: + /* swallow prior .. chars and any subsequent . */ + if (c == '.') + goto swallow; + /* last issued was /, so another / == // */ + if (c == '/') + goto swallow; + /* last we issued was / so SEEN_SLASH */ + wsi->u.hdr.ups = URIPS_SEEN_SLASH; + break; + case URIPS_ARGUMENTS: + /* leave them alone */ + break; + } + + if (c == '?') { /* start of URI arguments */ + /* seal off uri header */ + wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0'; + + /* move to using WSI_TOKEN_HTTP_URI_ARGS */ + wsi->u.hdr.ah->next_frag_index++; + wsi->u.hdr.ah->frags[ + wsi->u.hdr.ah->next_frag_index].offset = + wsi->u.hdr.ah->pos; + wsi->u.hdr.ah->frags[ + wsi->u.hdr.ah->next_frag_index].len = 0; + wsi->u.hdr.ah->frags[ + wsi->u.hdr.ah->next_frag_index].next_frag_index = 0; + + wsi->u.hdr.ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = + wsi->u.hdr.ah->next_frag_index; + + /* defeat normal uri path processing */ + wsi->u.hdr.ups = URIPS_ARGUMENTS; + goto swallow; + } + +check_eol: + + /* bail at EOL */ + if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE && + c == '\x0d') { + c = '\0'; + wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR; + lwsl_parser("*\n"); + } + + n = issue_char(wsi, c); + if (n < 0) + return -1; + if (n > 0) + wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; + +swallow: + /* per-protocol end of headers management */ + + if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE) + goto set_parsing_complete; + break; + + /* collecting and checking a name part */ + case WSI_TOKEN_NAME_PART: + lwsl_parser("WSI_TOKEN_NAME_PART '%c'\n", c); + + wsi->u.hdr.lextable_pos = + lextable_decode(wsi->u.hdr.lextable_pos, c); + + if (wsi->u.hdr.lextable_pos < 0) { + /* this is not a header we know about */ + if (wsi->u.hdr.ah->frag_index[WSI_TOKEN_GET_URI] || + wsi->u.hdr.ah->frag_index[WSI_TOKEN_POST_URI] || + wsi->u.hdr.ah->frag_index[WSI_TOKEN_OPTIONS_URI] || + wsi->u.hdr.ah->frag_index[WSI_TOKEN_HTTP]) { + /* + * already had the method, no idea what + * this crap is, ignore + */ + wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; + break; + } + /* + * hm it's an unknown http method in fact, + * treat as dangerous + */ + + lwsl_info("Unknown method - dropping\n"); + return -1; + } + if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) { + + /* terminal state */ + + n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) | + lextable[wsi->u.hdr.lextable_pos + 1]; + + lwsl_parser("known hdr %d\n", n); + if (n == WSI_TOKEN_GET_URI && + wsi->u.hdr.ah->frag_index[WSI_TOKEN_GET_URI]) { + lwsl_warn("Duplicated GET\n"); + return -1; + } + if (n == WSI_TOKEN_POST_URI && + wsi->u.hdr.ah->frag_index[WSI_TOKEN_POST_URI]) { + lwsl_warn("Duplicated POST\n"); + return -1; + } + if (n == WSI_TOKEN_OPTIONS_URI && + wsi->u.hdr.ah->frag_index[WSI_TOKEN_OPTIONS_URI]) { + lwsl_warn("Duplicated OPTIONS\n"); + return -1; + } + + /* + * WSORIGIN is protocol equiv to ORIGIN, + * JWebSocket likes to send it, map to ORIGIN + */ + if (n == WSI_TOKEN_SWORIGIN) + n = WSI_TOKEN_ORIGIN; + + wsi->u.hdr.parser_state = (enum lws_token_indexes) + (WSI_TOKEN_GET_URI + n); + + if (context->token_limits) + wsi->u.hdr.current_token_limit = + context->token_limits->token_limit[wsi->u.hdr.parser_state]; + else + wsi->u.hdr.current_token_limit = sizeof(wsi->u.hdr.ah->data); + + if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE) + goto set_parsing_complete; + + goto start_fragment; + } + break; + +start_fragment: + wsi->u.hdr.ah->next_frag_index++; + if (wsi->u.hdr.ah->next_frag_index == + sizeof(wsi->u.hdr.ah->frags) / + sizeof(wsi->u.hdr.ah->frags[0])) { + lwsl_warn("More hdr frags than we can deal with\n"); + return -1; + } + + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].offset = + wsi->u.hdr.ah->pos; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len = 0; + wsi->u.hdr.ah->frags[ + wsi->u.hdr.ah->next_frag_index].next_frag_index = 0; + + n = wsi->u.hdr.ah->frag_index[wsi->u.hdr.parser_state]; + if (!n) { /* first fragment */ + wsi->u.hdr.ah->frag_index[wsi->u.hdr.parser_state] = + wsi->u.hdr.ah->next_frag_index; + break; + } + /* continuation */ + while (wsi->u.hdr.ah->frags[n].next_frag_index) + n = wsi->u.hdr.ah->frags[n].next_frag_index; + wsi->u.hdr.ah->frags[n].next_frag_index = + wsi->u.hdr.ah->next_frag_index; + + if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) { + lwsl_warn("excessive header content\n"); + return -1; + } + + wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = ' '; + wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len++; + break; + + /* skipping arg part of a name we didn't recognize */ + case WSI_TOKEN_SKIPPING: + lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c); + + if (c == '\x0d') + wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR; + break; + + case WSI_TOKEN_SKIPPING_SAW_CR: + lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c); + if (c == '\x0a') { + wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; + wsi->u.hdr.lextable_pos = 0; + } else + wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; + break; + /* we're done, ignore anything else */ + + case WSI_PARSING_COMPLETE: + lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c); + break; + } + + return 0; + +set_parsing_complete: + + if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) { + if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION)) + wsi->ietf_spec_revision = + atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION)); + + lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision); + } + wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE; + wsi->hdr_parsing_completed = 1; + + return 0; +} + + +/** + * lws_frame_is_binary: true if the current frame was sent in binary mode + * + * @wsi: the connection we are inquiring about + * + * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if + * it's interested to see if the frame it's dealing with was sent in binary + * mode. + */ + +LWS_VISIBLE int lws_frame_is_binary(struct libwebsocket *wsi) +{ + return wsi->u.ws.frame_is_binary; +} + +int +libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c) +{ + int n; + struct lws_tokens eff_buf; + int ret = 0; + + switch (wsi->lws_rx_parse_state) { + case LWS_RXPS_NEW: + + switch (wsi->ietf_spec_revision) { + case 13: + /* + * no prepended frame key any more + */ + wsi->u.ws.all_zero_nonce = 1; + goto handle_first; + + default: + lwsl_warn("lws_rx_sm: unknown spec version %d\n", + wsi->ietf_spec_revision); + break; + } + break; + case LWS_RXPS_04_MASK_NONCE_1: + wsi->u.ws.frame_masking_nonce_04[1] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2; + break; + case LWS_RXPS_04_MASK_NONCE_2: + wsi->u.ws.frame_masking_nonce_04[2] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3; + break; + case LWS_RXPS_04_MASK_NONCE_3: + wsi->u.ws.frame_masking_nonce_04[3] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + + /* + * start from the zero'th byte in the XOR key buffer since + * this is the start of a frame with a new key + */ + + wsi->u.ws.frame_mask_index = 0; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1; + break; + + /* + * 04 logical framing from the spec (all this is masked when incoming + * and has to be unmasked) + * + * We ignore the possibility of extension data because we don't + * negotiate any extensions at the moment. + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-------+-+-------------+-------------------------------+ + * |F|R|R|R| opcode|R| Payload len | Extended payload length | + * |I|S|S|S| (4) |S| (7) | (16/63) | + * |N|V|V|V| |V| | (if payload len==126/127) | + * | |1|2|3| |4| | | + * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + * | Extended payload length continued, if payload len == 127 | + * + - - - - - - - - - - - - - - - +-------------------------------+ + * | | Extension data | + * +-------------------------------+ - - - - - - - - - - - - - - - + + * : : + * +---------------------------------------------------------------+ + * : Application data : + * +---------------------------------------------------------------+ + * + * We pass payload through to userland as soon as we get it, ignoring + * FIN. It's up to userland to buffer it up if it wants to see a + * whole unfragmented block of the original size (which may be up to + * 2^63 long!) + */ + + case LWS_RXPS_04_FRAME_HDR_1: +handle_first: + + wsi->u.ws.opcode = c & 0xf; + wsi->u.ws.rsv = c & 0x70; + wsi->u.ws.final = !!((c >> 7) & 1); + + switch (wsi->u.ws.opcode) { + case LWS_WS_OPCODE_07__TEXT_FRAME: + case LWS_WS_OPCODE_07__BINARY_FRAME: + wsi->u.ws.frame_is_binary = + wsi->u.ws.opcode == LWS_WS_OPCODE_07__BINARY_FRAME; + break; + } + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN: + + wsi->u.ws.this_frame_masked = !!(c & 0x80); + + switch (c & 0x7f) { + case 126: + /* control frames are not allowed to have big lengths */ + if (wsi->u.ws.opcode & 8) + goto illegal_ctl_length; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2; + break; + case 127: + /* control frames are not allowed to have big lengths */ + if (wsi->u.ws.opcode & 8) + goto illegal_ctl_length; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8; + break; + default: + wsi->u.ws.rx_packet_length = c & 0x7f; + if (wsi->u.ws.this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else + if (wsi->u.ws.rx_packet_length) + wsi->lws_rx_parse_state = + LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + else { + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } + break; + } + break; + + case LWS_RXPS_04_FRAME_HDR_LEN16_2: + wsi->u.ws.rx_packet_length = c << 8; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN16_1: + wsi->u.ws.rx_packet_length |= c; + if (wsi->u.ws.this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else + wsi->lws_rx_parse_state = + LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_8: + if (c & 0x80) { + lwsl_warn("b63 of length must be zero\n"); + /* kill the connection */ + return -1; + } +#if defined __LP64__ + wsi->u.ws.rx_packet_length = ((size_t)c) << 56; +#else + wsi->u.ws.rx_packet_length = 0; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_7: +#if defined __LP64__ + wsi->u.ws.rx_packet_length |= ((size_t)c) << 48; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_6: +#if defined __LP64__ + wsi->u.ws.rx_packet_length |= ((size_t)c) << 40; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_5: +#if defined __LP64__ + wsi->u.ws.rx_packet_length |= ((size_t)c) << 32; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_4: + wsi->u.ws.rx_packet_length |= ((size_t)c) << 24; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_3: + wsi->u.ws.rx_packet_length |= ((size_t)c) << 16; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_2: + wsi->u.ws.rx_packet_length |= ((size_t)c) << 8; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_1: + wsi->u.ws.rx_packet_length |= ((size_t)c); + if (wsi->u.ws.this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else + wsi->lws_rx_parse_state = + LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_1: + wsi->u.ws.frame_masking_nonce_04[0] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_2: + wsi->u.ws.frame_masking_nonce_04[1] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_3: + wsi->u.ws.frame_masking_nonce_04[2] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_4: + wsi->u.ws.frame_masking_nonce_04[3] = c; + if (c) + wsi->u.ws.all_zero_nonce = 0; + wsi->lws_rx_parse_state = + LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + wsi->u.ws.frame_mask_index = 0; + if (wsi->u.ws.rx_packet_length == 0) { + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } + break; + + + case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED: + + if (!wsi->u.ws.rx_user_buffer) { + lwsl_err("NULL user buffer...\n"); + return 1; + } + + if (wsi->u.ws.all_zero_nonce) + wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING + + (wsi->u.ws.rx_user_buffer_head++)] = c; + else + wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING + + (wsi->u.ws.rx_user_buffer_head++)] = + c ^ wsi->u.ws.frame_masking_nonce_04[ + (wsi->u.ws.frame_mask_index++) & 3]; + + if (--wsi->u.ws.rx_packet_length == 0) { + /* spill because we have the whole frame */ + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } + + /* + * if there's no protocol max frame size given, we are + * supposed to default to LWS_MAX_SOCKET_IO_BUF + */ + + if (!wsi->protocol->rx_buffer_size && + wsi->u.ws.rx_user_buffer_head != + LWS_MAX_SOCKET_IO_BUF) + break; + else + if (wsi->protocol->rx_buffer_size && + wsi->u.ws.rx_user_buffer_head != + wsi->protocol->rx_buffer_size) + break; + + /* spill because we filled our rx buffer */ +spill: + /* + * is this frame a control packet we should take care of at this + * layer? If so service it and hide it from the user callback + */ + + lwsl_parser("spill on %s\n", wsi->protocol->name); + + switch (wsi->u.ws.opcode) { + case LWS_WS_OPCODE_07__CLOSE: + /* is this an acknowledgement of our close? */ + if (wsi->state == WSI_STATE_AWAITING_CLOSE_ACK) { + /* + * fine he has told us he is closing too, let's + * finish our close + */ + lwsl_parser("seen client close ack\n"); + return -1; + } + lwsl_parser("server sees client close packet\n"); + /* parrot the close packet payload back */ + n = libwebsocket_write(wsi, (unsigned char *) + &wsi->u.ws.rx_user_buffer[ + LWS_SEND_BUFFER_PRE_PADDING], + wsi->u.ws.rx_user_buffer_head, + LWS_WRITE_CLOSE); + if (n < 0) + lwsl_info("write of close ack failed %d\n", n); + wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY; + /* close the connection */ + return -1; + + case LWS_WS_OPCODE_07__PING: + lwsl_info("received %d byte ping, sending pong\n", + wsi->u.ws.rx_user_buffer_head); + + if (wsi->u.ws.ping_payload_len) { + /* + * there is already a pending ping payload + * we should just log and drop + */ + lwsl_parser("DROP PING since one pending\n"); + goto ping_drop; + } + + /* control packets can only be < 128 bytes long */ + if (wsi->u.ws.ping_payload_len > 128 - 4) { + lwsl_parser("DROP PING payload too large\n"); + goto ping_drop; + } + + /* if existing buffer is too small, drop it */ + if (wsi->u.ws.ping_payload_buf && + wsi->u.ws.ping_payload_alloc < wsi->u.ws.rx_user_buffer_head) { + lws_free2(wsi->u.ws.ping_payload_buf); + } + + /* if no buffer, allocate it */ + if (!wsi->u.ws.ping_payload_buf) { + wsi->u.ws.ping_payload_buf = lws_malloc(wsi->u.ws.rx_user_buffer_head + + LWS_SEND_BUFFER_PRE_PADDING); + wsi->u.ws.ping_payload_alloc = wsi->u.ws.rx_user_buffer_head; + } + + /* stash the pong payload */ + memcpy(wsi->u.ws.ping_payload_buf + LWS_SEND_BUFFER_PRE_PADDING, + &wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING], + wsi->u.ws.rx_user_buffer_head); + + wsi->u.ws.ping_payload_len = wsi->u.ws.rx_user_buffer_head; + + /* get it sent as soon as possible */ + libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi); +ping_drop: + wsi->u.ws.rx_user_buffer_head = 0; + return 0; + + case LWS_WS_OPCODE_07__PONG: + /* ... then just drop it */ + wsi->u.ws.rx_user_buffer_head = 0; + return 0; + + case LWS_WS_OPCODE_07__TEXT_FRAME: + case LWS_WS_OPCODE_07__BINARY_FRAME: + case LWS_WS_OPCODE_07__CONTINUATION: + break; + + default: + lwsl_parser("passing opc %x up to exts\n", + wsi->u.ws.opcode); + /* + * It's something special we can't understand here. + * Pass the payload up to the extension's parsing + * state machine. + */ + + eff_buf.token = &wsi->u.ws.rx_user_buffer[ + LWS_SEND_BUFFER_PRE_PADDING]; + eff_buf.token_len = wsi->u.ws.rx_user_buffer_head; + + if (lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX, + &eff_buf, 0) <= 0) /* not handle or fail */ + lwsl_ext("ext opc opcode 0x%x unknown\n", + wsi->u.ws.opcode); + + wsi->u.ws.rx_user_buffer_head = 0; + return 0; + } + + /* + * No it's real payload, pass it up to the user callback. + * It's nicely buffered with the pre-padding taken care of + * so it can be sent straight out again using libwebsocket_write + */ + + eff_buf.token = &wsi->u.ws.rx_user_buffer[ + LWS_SEND_BUFFER_PRE_PADDING]; + eff_buf.token_len = wsi->u.ws.rx_user_buffer_head; + + if (lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PAYLOAD_RX, &eff_buf, 0) < 0) + return -1; + + if (eff_buf.token_len > 0) { + eff_buf.token[eff_buf.token_len] = '\0'; + + if (wsi->protocol->callback) + ret = user_callback_handle_rxflow( + wsi->protocol->callback, + wsi->protocol->owning_server, + wsi, LWS_CALLBACK_RECEIVE, + wsi->user_space, + eff_buf.token, + eff_buf.token_len); + else + lwsl_err("No callback on payload spill!\n"); + } + + wsi->u.ws.rx_user_buffer_head = 0; + break; + } + + return ret; + +illegal_ctl_length: + + lwsl_warn("Control frame with xtended length is illegal\n"); + /* kill the connection */ + return -1; +} + + +/** + * libwebsockets_remaining_packet_payload() - Bytes to come before "overall" + * rx packet is complete + * @wsi: Websocket instance (available from user callback) + * + * This function is intended to be called from the callback if the + * user code is interested in "complete packets" from the client. + * libwebsockets just passes through payload as it comes and issues a buffer + * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE + * callback handler can use this API to find out if the buffer it has just + * been given is the last piece of a "complete packet" from the client -- + * when that is the case libwebsockets_remaining_packet_payload() will return + * 0. + * + * Many protocols won't care becuse their packets are always small. + */ + +LWS_VISIBLE size_t +libwebsockets_remaining_packet_payload(struct libwebsocket *wsi) +{ + return wsi->u.ws.rx_packet_length; +} diff --git a/src/engine/external/libwebsockets/pollfd.c b/src/engine/external/libwebsockets/pollfd.c new file mode 100644 index 0000000..b09127e --- /dev/null +++ b/src/engine/external/libwebsockets/pollfd.c @@ -0,0 +1,293 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +int +insert_wsi_socket_into_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ + struct libwebsocket_pollargs pa = { wsi->sock, LWS_POLLIN, 0 }; + + if (context->fds_count >= context->max_fds) { + lwsl_err("Too many fds (%d)\n", context->max_fds); + return 1; + } + + if (wsi->sock >= context->max_fds) { + lwsl_err("Socket fd %d is too high (%d)\n", + wsi->sock, context->max_fds); + return 1; + } + + assert(wsi); + assert(wsi->sock >= 0); + + lwsl_info("insert_wsi_socket_into_fds: wsi=%p, sock=%d, fds pos=%d\n", + wsi, wsi->sock, context->fds_count); + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_LOCK_POLL, + wsi->user_space, (void *) &pa, 0); + + context->lws_lookup[wsi->sock] = wsi; + wsi->position_in_fds_table = context->fds_count; + context->fds[context->fds_count].fd = wsi->sock; + context->fds[context->fds_count].events = LWS_POLLIN; + + lws_plat_insert_socket_into_fds(context, wsi); + + /* external POLL support via protocol 0 */ + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_ADD_POLL_FD, + wsi->user_space, (void *) &pa, 0); + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_UNLOCK_POLL, + wsi->user_space, (void *)&pa, 0); + + return 0; +} + +int +remove_wsi_socket_from_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ + int m; + struct libwebsocket_pollargs pa = { wsi->sock, 0, 0 }; + + lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); + + if (!--context->fds_count) { + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_LOCK_POLL, + wsi->user_space, (void *) &pa, 0); + goto do_ext; + } + + if (wsi->sock > context->max_fds) { + lwsl_err("Socket fd %d too high (%d)\n", + wsi->sock, context->max_fds); + return 1; + } + + lwsl_info("%s: wsi=%p, sock=%d, fds pos=%d\n", __func__, + wsi, wsi->sock, wsi->position_in_fds_table); + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_LOCK_POLL, + wsi->user_space, (void *)&pa, 0); + + m = wsi->position_in_fds_table; /* replace the contents for this */ + + /* have the last guy take up the vacant slot */ + context->fds[m] = context->fds[context->fds_count]; + + lws_plat_delete_socket_from_fds(context, wsi, m); + + /* + * end guy's fds_lookup entry remains unchanged + * (still same fd pointing to same wsi) + */ + /* end guy's "position in fds table" changed */ + context->lws_lookup[context->fds[context->fds_count].fd]-> + position_in_fds_table = m; + /* deletion guy's lws_lookup entry needs nuking */ + context->lws_lookup[wsi->sock] = NULL; + /* removed wsi has no position any more */ + wsi->position_in_fds_table = -1; + +do_ext: + /* remove also from external POLL support via protocol 0 */ + if (wsi->sock) { + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_DEL_POLL_FD, wsi->user_space, + (void *) &pa, 0); + } + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_UNLOCK_POLL, + wsi->user_space, (void *) &pa, 0); + return 0; +} + +int +lws_change_pollfd(struct libwebsocket *wsi, int _and, int _or) +{ + struct libwebsocket_context *context; + int tid; + int sampled_tid; + struct libwebsocket_pollfd *pfd; + struct libwebsocket_pollargs pa; + + if (!wsi || !wsi->protocol || wsi->position_in_fds_table < 0) + return 1; + + context = wsi->protocol->owning_server; + if (!context) + return 1; + + pfd = &context->fds[wsi->position_in_fds_table]; + pa.fd = wsi->sock; + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 0); + + pa.prev_events = pfd->events; + pa.events = pfd->events = (pfd->events & ~_and) | _or; + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_CHANGE_MODE_POLL_FD, + wsi->user_space, (void *) &pa, 0); + + /* + * if we changed something in this pollfd... + * ... and we're running in a different thread context + * than the service thread... + * ... and the service thread is waiting ... + * then cancel it to force a restart with our changed events + */ + if (pa.prev_events != pa.events) { + + if (lws_plat_change_pollfd(context, wsi, pfd)) { + lwsl_info("%s failed\n", __func__); + return 1; + } + + sampled_tid = context->service_tid; + if (sampled_tid) { + tid = context->protocols[0].callback(context, NULL, + LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0); + if (tid != sampled_tid) + libwebsocket_cancel_service(context); + } + } + + context->protocols[0].callback(context, wsi, + LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0); + + return 0; +} + + +/** + * libwebsocket_callback_on_writable() - Request a callback when this socket + * becomes able to be written to without + * blocking + * + * @context: libwebsockets context + * @wsi: Websocket connection instance to get callback for + */ + +LWS_VISIBLE int +libwebsocket_callback_on_writable(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ +#ifdef LWS_USE_HTTP2 + struct libwebsocket *network_wsi, *wsi2; + int already; + + lwsl_info("%s: %p\n", __func__, wsi); + + if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) + goto network_sock; + + if (wsi->u.http2.requested_POLLOUT) { + lwsl_info("already pending writable\n"); + return 1; + } + + if (wsi->u.http2.tx_credit <= 0) { + /* + * other side is not able to cope with us sending + * anything so no matter if we have POLLOUT on our side. + * + * Delay waiting for our POLLOUT until peer indicates he has + * space for more using tx window command in http2 layer + */ + lwsl_info("%s: %p: waiting_tx_credit (%d)\n", __func__, wsi, wsi->u.http2.tx_credit); + wsi->u.http2.waiting_tx_credit = 1; + return 0; + } + + network_wsi = lws_http2_get_network_wsi(wsi); + already = network_wsi->u.http2.requested_POLLOUT; + + /* mark everybody above him as requesting pollout */ + + wsi2 = wsi; + while (wsi2) { + wsi2->u.http2.requested_POLLOUT = 1; + lwsl_info("mark %p pending writable\n", wsi2); + wsi2 = wsi2->u.http2.parent_wsi; + } + + /* for network action, act only on the network wsi */ + + wsi = network_wsi; + if (already) + return 1; +network_sock: +#endif + + if (lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_REQUEST_ON_WRITEABLE, NULL, 0)) + return 1; + + if (wsi->position_in_fds_table < 0) { + lwsl_err("%s: failed to find socket %d\n", __func__, wsi->sock); + return -1; + } + + if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) + return -1; + + lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE); + + return 1; +} + +/** + * libwebsocket_callback_on_writable_all_protocol() - Request a callback for + * all connections using the given protocol when it + * becomes possible to write to each socket without + * blocking in turn. + * + * @protocol: Protocol whose connections will get callbacks + */ + +LWS_VISIBLE int +libwebsocket_callback_on_writable_all_protocol( + const struct libwebsocket_protocols *protocol) +{ + struct libwebsocket_context *context = protocol->owning_server; + int n; + struct libwebsocket *wsi; + + for (n = 0; n < context->fds_count; n++) { + wsi = context->lws_lookup[context->fds[n].fd]; + if (!wsi) + continue; + if (wsi->protocol == protocol) + libwebsocket_callback_on_writable(context, wsi); + } + + return 0; +} diff --git a/src/engine/external/libwebsockets/private-libwebsockets.h b/src/engine/external/libwebsockets/private-libwebsockets.h new file mode 100644 index 0000000..de43ec4 --- /dev/null +++ b/src/engine/external/libwebsockets/private-libwebsockets.h @@ -0,0 +1,1211 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +/* System introspection configs */ +#ifdef CMAKE_BUILD +#include "lws_config.h" +#else +#if defined(WIN32) || defined(_WIN32) +#define inline __inline +#else /* not WIN32 */ +#include "config.h" + +#endif /* not WIN32 */ +#endif /* not CMAKE */ + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <ctype.h> +#include <limits.h> +#include <stdarg.h> + +#ifdef HAVE_SYS_STAT_H +#include <sys/stat.h> +#endif + +#if defined(WIN32) || defined(_WIN32) +#define LWS_NO_DAEMONIZE +#define LWS_ERRNO WSAGetLastError() +#define LWS_EAGAIN WSAEWOULDBLOCK +#define LWS_EALREADY WSAEALREADY +#define LWS_EINPROGRESS WSAEINPROGRESS +#define LWS_EINTR WSAEINTR +#define LWS_EISCONN WSAEISCONN +#define LWS_EWOULDBLOCK WSAEWOULDBLOCK +#define LWS_POLLHUP (FD_CLOSE) +#define LWS_POLLIN (FD_READ | FD_ACCEPT) +#define LWS_POLLOUT (FD_WRITE) +#define MSG_NOSIGNAL 0 +#define SHUT_RDWR SD_BOTH +#define SOL_TCP IPPROTO_TCP + +#define compatible_close(fd) closesocket(fd) +#define compatible_file_close(fd) CloseHandle(fd) +#define compatible_file_seek_cur(fd, offset) SetFilePointer(fd, offset, NULL, FILE_CURRENT) +#define compatible_file_read(amount, fd, buf, len) {\ + DWORD _amount; \ + if (!ReadFile(fd, buf, len, &_amount, NULL)) \ + amount = -1; \ + else \ + amount = _amount; \ + } +#define lws_set_blocking_send(wsi) wsi->sock_send_blocking = TRUE +#include <winsock2.h> +#include <windows.h> +#include <tchar.h> +#ifdef HAVE_IN6ADDR_H +#include <in6addr.h> +#endif +#include <mstcpip.h> + +#ifndef __func__ +#define __func__ __FUNCTION__ +#endif + +#ifdef _WIN32_WCE +#define vsnprintf _vsnprintf +#endif + +#define LWS_INVALID_FILE INVALID_HANDLE_VALUE +#else /* not windows --> */ +#include <errno.h> +#include <fcntl.h> +#include <netdb.h> +#include <signal.h> +#include <strings.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/socket.h> +#ifdef LWS_BUILTIN_GETIFADDRS + #include <getifaddrs.h> +#else + #include <ifaddrs.h> +#endif +#if defined (__ANDROID__) +#include <syslog.h> +#else +#include <sys/syslog.h> +#endif +#include <sys/un.h> +#include <sys/socket.h> +#include <netdb.h> +#ifndef LWS_NO_FORK +#ifdef HAVE_SYS_PRCTL_H +#include <sys/prctl.h> +#endif +#endif +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <arpa/inet.h> +#include <poll.h> +#ifdef LWS_USE_LIBEV +#include <ev.h> +#endif /* LWS_USE_LIBEV */ + +#include <sys/mman.h> +#include <sys/time.h> + +#define LWS_ERRNO errno +#define LWS_EAGAIN EAGAIN +#define LWS_EALREADY EALREADY +#define LWS_EINPROGRESS EINPROGRESS +#define LWS_EINTR EINTR +#define LWS_EISCONN EISCONN +#define LWS_EWOULDBLOCK EWOULDBLOCK +#define LWS_INVALID_FILE -1 +#define LWS_POLLHUP (POLLHUP|POLLERR) +#define LWS_POLLIN (POLLIN) +#define LWS_POLLOUT (POLLOUT) +#define compatible_close(fd) close(fd) +#define compatible_file_close(fd) close(fd) +#define compatible_file_seek_cur(fd, offset) lseek(fd, offset, SEEK_CUR) +#define compatible_file_read(amount, fd, buf, len) \ + amount = read(fd, buf, len); +#define lws_set_blocking_send(wsi) +#endif + +#ifndef HAVE_BZERO +#ifndef bzero +#define bzero(b, len) (memset((b), '\0', (len)), (void) 0) +#endif +#endif + +#ifndef HAVE_STRERROR +#define strerror(x) "" +#endif + +#ifdef LWS_OPENSSL_SUPPORT +#ifdef USE_CYASSL +#include <cyassl/openssl/ssl.h> +#include <cyassl/error-ssl.h> +#else +#include <openssl/ssl.h> +#include <openssl/evp.h> +#include <openssl/err.h> +#include <openssl/md5.h> +#include <openssl/sha.h> +#endif /* not USE_CYASSL */ +#endif + +#include "libwebsockets.h" + +#if defined(WIN32) || defined(_WIN32) + +#ifndef BIG_ENDIAN +#define BIG_ENDIAN 4321 /* to show byte order (taken from gcc) */ +#endif +#ifndef LITTLE_ENDIAN +#define LITTLE_ENDIAN 1234 +#endif +#ifndef BYTE_ORDER +#define BYTE_ORDER LITTLE_ENDIAN +#endif +typedef unsigned __int64 u_int64_t; + +#undef __P +#ifndef __P +#if __STDC__ +#define __P(protos) protos +#else +#define __P(protos) () +#endif +#endif + +#else + +#include <sys/stat.h> +#include <sys/cdefs.h> +#include <sys/time.h> + +#if defined(__APPLE__) +#include <machine/endian.h> +#elif defined(__FreeBSD__) +#include <sys/endian.h> +#elif defined(__linux__) +#include <endian.h> +#endif + +#include <stddef.h> + +#ifndef container_of +#define container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M))) +#endif + +#if defined(__QNX__) + #include <gulliver.h> + #if defined(__LITTLEENDIAN__) + #define BYTE_ORDER __LITTLEENDIAN__ + #define LITTLE_ENDIAN __LITTLEENDIAN__ + #define BIG_ENDIAN 4321 /* to show byte order (taken from gcc); for suppres warning that BIG_ENDIAN is not defined. */ + #endif + #if defined(__BIGENDIAN__) + #define BYTE_ORDER __BIGENDIAN__ + #define LITTLE_ENDIAN 1234 /* to show byte order (taken from gcc); for suppres warning that LITTLE_ENDIAN is not defined. */ + #define BIG_ENDIAN __BIGENDIAN__ + #endif +#endif + +#if !defined(BYTE_ORDER) +# define BYTE_ORDER __BYTE_ORDER +#endif +#if !defined(LITTLE_ENDIAN) +# define LITTLE_ENDIAN __LITTLE_ENDIAN +#endif +#if !defined(BIG_ENDIAN) +# define BIG_ENDIAN __BIG_ENDIAN +#endif + +#endif + +/* + * Mac OSX as well as iOS do not define the MSG_NOSIGNAL flag, + * but happily have something equivalent in the SO_NOSIGPIPE flag. + */ +#ifdef __APPLE__ +#define MSG_NOSIGNAL SO_NOSIGPIPE +#endif + +#ifndef LWS_MAX_HEADER_LEN +#define LWS_MAX_HEADER_LEN 1024 +#endif +#ifndef LWS_MAX_PROTOCOLS +#define LWS_MAX_PROTOCOLS 5 +#endif +#ifndef LWS_MAX_EXTENSIONS_ACTIVE +#define LWS_MAX_EXTENSIONS_ACTIVE 3 +#endif +#ifndef SPEC_LATEST_SUPPORTED +#define SPEC_LATEST_SUPPORTED 13 +#endif +#ifndef AWAITING_TIMEOUT +#define AWAITING_TIMEOUT 5 +#endif +#ifndef CIPHERS_LIST_STRING +#define CIPHERS_LIST_STRING "DEFAULT" +#endif +#ifndef LWS_SOMAXCONN +#define LWS_SOMAXCONN SOMAXCONN +#endif + +#define MAX_WEBSOCKET_04_KEY_LEN 128 +#define LWS_MAX_SOCKET_IO_BUF 4096 + +#ifndef SYSTEM_RANDOM_FILEPATH +#define SYSTEM_RANDOM_FILEPATH "/dev/urandom" +#endif +#ifndef LWS_MAX_ZLIB_CONN_BUFFER +#define LWS_MAX_ZLIB_CONN_BUFFER (64 * 1024) +#endif + +/* + * if not in a connection storm, check for incoming + * connections this many normal connection services + */ +#define LWS_LISTEN_SERVICE_MODULO 10 + +enum lws_websocket_opcodes_07 { + LWS_WS_OPCODE_07__CONTINUATION = 0, + LWS_WS_OPCODE_07__TEXT_FRAME = 1, + LWS_WS_OPCODE_07__BINARY_FRAME = 2, + + LWS_WS_OPCODE_07__NOSPEC__MUX = 7, + + /* control extensions 8+ */ + + LWS_WS_OPCODE_07__CLOSE = 8, + LWS_WS_OPCODE_07__PING = 9, + LWS_WS_OPCODE_07__PONG = 0xa, +}; + + +enum lws_connection_states { + WSI_STATE_HTTP, + WSI_STATE_HTTP_ISSUING_FILE, + WSI_STATE_HTTP_HEADERS, + WSI_STATE_HTTP_BODY, + WSI_STATE_DEAD_SOCKET, + WSI_STATE_ESTABLISHED, + WSI_STATE_CLIENT_UNCONNECTED, + WSI_STATE_RETURNED_CLOSE_ALREADY, + WSI_STATE_AWAITING_CLOSE_ACK, + WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE, + + WSI_STATE_HTTP2_AWAIT_CLIENT_PREFACE, + WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS, + WSI_STATE_HTTP2_ESTABLISHED, +}; + +enum http_version { + HTTP_VERSION_1_0, + HTTP_VERSION_1_1, +}; + +enum http_connection_type { + HTTP_CONNECTION_CLOSE, + HTTP_CONNECTION_KEEP_ALIVE +}; + +enum lws_pending_protocol_send { + LWS_PPS_NONE, + LWS_PPS_HTTP2_MY_SETTINGS, + LWS_PPS_HTTP2_ACK_SETTINGS, + LWS_PPS_HTTP2_PONG, +}; + +enum lws_rx_parse_state { + LWS_RXPS_NEW, + + LWS_RXPS_04_MASK_NONCE_1, + LWS_RXPS_04_MASK_NONCE_2, + LWS_RXPS_04_MASK_NONCE_3, + + LWS_RXPS_04_FRAME_HDR_1, + LWS_RXPS_04_FRAME_HDR_LEN, + LWS_RXPS_04_FRAME_HDR_LEN16_2, + LWS_RXPS_04_FRAME_HDR_LEN16_1, + LWS_RXPS_04_FRAME_HDR_LEN64_8, + LWS_RXPS_04_FRAME_HDR_LEN64_7, + LWS_RXPS_04_FRAME_HDR_LEN64_6, + LWS_RXPS_04_FRAME_HDR_LEN64_5, + LWS_RXPS_04_FRAME_HDR_LEN64_4, + LWS_RXPS_04_FRAME_HDR_LEN64_3, + LWS_RXPS_04_FRAME_HDR_LEN64_2, + LWS_RXPS_04_FRAME_HDR_LEN64_1, + + LWS_RXPS_07_COLLECT_FRAME_KEY_1, + LWS_RXPS_07_COLLECT_FRAME_KEY_2, + LWS_RXPS_07_COLLECT_FRAME_KEY_3, + LWS_RXPS_07_COLLECT_FRAME_KEY_4, + + LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED +}; + + +enum connection_mode { + LWS_CONNMODE_HTTP_SERVING, + LWS_CONNMODE_HTTP_SERVING_ACCEPTED, /* actual HTTP service going on */ + LWS_CONNMODE_PRE_WS_SERVING_ACCEPT, + + LWS_CONNMODE_WS_SERVING, + LWS_CONNMODE_WS_CLIENT, + + LWS_CONNMODE_HTTP2_SERVING, + + /* transient, ssl delay hiding */ + LWS_CONNMODE_SSL_ACK_PENDING, + + /* transient modes */ + LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT, + LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY, + LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE, + LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE2, + LWS_CONNMODE_WS_CLIENT_WAITING_SSL, + LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY, + LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT, + LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD, + + /* special internal types */ + LWS_CONNMODE_SERVER_LISTENER, +}; + +enum { + LWS_RXFLOW_ALLOW = (1 << 0), + LWS_RXFLOW_PENDING_CHANGE = (1 << 1), +}; + +struct libwebsocket_protocols; +struct libwebsocket; + +#ifdef LWS_USE_LIBEV +struct lws_io_watcher { + struct ev_io watcher; + struct libwebsocket_context* context; +}; + +struct lws_signal_watcher { + struct ev_signal watcher; + struct libwebsocket_context* context; +}; +#endif /* LWS_USE_LIBEV */ + +struct libwebsocket_context { +#ifdef _WIN32 + WSAEVENT *events; +#endif + struct libwebsocket_pollfd *fds; + struct libwebsocket **lws_lookup; /* fd to wsi */ + int fds_count; +#ifdef LWS_USE_LIBEV + struct ev_loop* io_loop; + struct lws_io_watcher w_accept; + struct lws_signal_watcher w_sigint; +#endif /* LWS_USE_LIBEV */ + int max_fds; + int listen_port; + const char *iface; + char http_proxy_address[128]; + char canonical_hostname[128]; + unsigned int http_proxy_port; + unsigned int options; + time_t last_timeout_check_s; + + /* + * usable by anything in the service code, but only if the scope + * does not last longer than the service action (since next service + * of any socket can likewise use it and overwrite) + */ + unsigned char service_buffer[LWS_MAX_SOCKET_IO_BUF]; + + int started_with_parent; + + int fd_random; + int listen_service_modulo; + int listen_service_count; + int listen_service_fd; + int listen_service_extraseen; + + /* + * set to the Thread ID that's doing the service loop just before entry + * to poll indicates service thread likely idling in poll() + * volatile because other threads may check it as part of processing + * for pollfd event change. + */ + volatile int service_tid; +#ifndef _WIN32 + int dummy_pipe_fds[2]; +#endif + + int ka_time; + int ka_probes; + int ka_interval; + +#ifdef LWS_LATENCY + unsigned long worst_latency; + char worst_latency_info[256]; +#endif + +#ifdef LWS_OPENSSL_SUPPORT + int use_ssl; + int allow_non_ssl_on_ssl_port; + unsigned int user_supplied_ssl_ctx:1; + SSL_CTX *ssl_ctx; + SSL_CTX *ssl_client_ctx; + unsigned int ssl_flag_buffered_reads:1; +#endif + struct libwebsocket_protocols *protocols; + int count_protocols; +#ifndef LWS_NO_EXTENSIONS + struct libwebsocket_extension *extensions; +#endif + struct lws_token_limits *token_limits; + void *user_space; +}; + +enum { + LWS_EV_READ = (1 << 0), + LWS_EV_WRITE = (1 << 1), + LWS_EV_START = (1 << 2), + LWS_EV_STOP = (1 << 3), +}; + +#ifdef LWS_USE_LIBEV +#define LWS_LIBEV_ENABLED(context) (context->options & LWS_SERVER_OPTION_LIBEV) +LWS_EXTERN void lws_feature_status_libev(struct lws_context_creation_info *info); +LWS_EXTERN void +lws_libev_accept(struct libwebsocket_context *context, + struct libwebsocket *new_wsi, int accept_fd); +LWS_EXTERN void +lws_libev_io(struct libwebsocket_context *context, + struct libwebsocket *wsi, int flags); +LWS_EXTERN int +lws_libev_init_fd_table(struct libwebsocket_context *context); +LWS_EXTERN void +lws_libev_run(struct libwebsocket_context *context); +#else +#define LWS_LIBEV_ENABLED(context) (0) +#define lws_feature_status_libev(_a) \ + lwsl_notice("libev support not compiled in\n") +#define lws_libev_accept(_a, _b, _c) ((void) 0) +#define lws_libev_io(_a, _b, _c) ((void) 0) +#define lws_libev_init_fd_table(_a) (0) +#define lws_libev_run(_a) ((void) 0) +#endif + +#ifdef LWS_USE_IPV6 +#define LWS_IPV6_ENABLED(context) (!(context->options & LWS_SERVER_OPTION_DISABLE_IPV6)) +#else +#define LWS_IPV6_ENABLED(context) (0) +#endif + +enum uri_path_states { + URIPS_IDLE, + URIPS_SEEN_SLASH, + URIPS_SEEN_SLASH_DOT, + URIPS_SEEN_SLASH_DOT_DOT, + URIPS_ARGUMENTS, +}; + +enum uri_esc_states { + URIES_IDLE, + URIES_SEEN_PERCENT, + URIES_SEEN_PERCENT_H1, +}; + +/* + * This is totally opaque to code using the library. It's exported as a + * forward-reference pointer-only declaration; the user can use the pointer with + * other APIs to get information out of it. + */ + +struct lws_fragments { + unsigned short offset; + unsigned short len; + unsigned char next_frag_index; +}; + +/* notice that these union members: + * + * hdr + * http + * http2 + * + * all have a pointer to allocated_headers struct as their first member. + * + * It means for allocated_headers access, the three union paths can all be + * used interchangably to access the same data + */ + +struct allocated_headers { + unsigned short next_frag_index; + unsigned short pos; + unsigned char frag_index[WSI_TOKEN_COUNT]; + struct lws_fragments frags[WSI_TOKEN_COUNT * 2]; + char data[LWS_MAX_HEADER_LEN]; +#ifndef LWS_NO_CLIENT + char initial_handshake_hash_base64[30]; + unsigned short c_port; +#endif +}; + +struct _lws_http_mode_related { + /* MUST be first in struct */ + struct allocated_headers *ah; /* mirroring _lws_header_related */ +#if defined(WIN32) || defined(_WIN32) + HANDLE fd; +#else + int fd; +#endif + unsigned long filepos; + unsigned long filelen; + + enum http_version request_version; + enum http_connection_type connection_type; + int content_length; + int content_remain; +}; + + +#ifdef LWS_USE_HTTP2 + +enum lws_http2_settings { + LWS_HTTP2_SETTINGS__HEADER_TABLE_SIZE = 1, + LWS_HTTP2_SETTINGS__ENABLE_PUSH, + LWS_HTTP2_SETTINGS__MAX_CONCURRENT_STREAMS, + LWS_HTTP2_SETTINGS__INITIAL_WINDOW_SIZE, + LWS_HTTP2_SETTINGS__MAX_FRAME_SIZE, + LWS_HTTP2_SETTINGS__MAX_HEADER_LIST_SIZE, + + LWS_HTTP2_SETTINGS__COUNT /* always last */ +}; + +enum lws_http2_wellknown_frame_types { + LWS_HTTP2_FRAME_TYPE_DATA, + LWS_HTTP2_FRAME_TYPE_HEADERS, + LWS_HTTP2_FRAME_TYPE_PRIORITY, + LWS_HTTP2_FRAME_TYPE_RST_STREAM, + LWS_HTTP2_FRAME_TYPE_SETTINGS, + LWS_HTTP2_FRAME_TYPE_PUSH_PROMISE, + LWS_HTTP2_FRAME_TYPE_PING, + LWS_HTTP2_FRAME_TYPE_GOAWAY, + LWS_HTTP2_FRAME_TYPE_WINDOW_UPDATE, + LWS_HTTP2_FRAME_TYPE_CONTINUATION, + + LWS_HTTP2_FRAME_TYPE_COUNT /* always last */ +}; + +enum lws_http2_flags { + LWS_HTTP2_FLAG_END_STREAM = 1, + LWS_HTTP2_FLAG_END_HEADERS = 4, + LWS_HTTP2_FLAG_PADDED = 8, + LWS_HTTP2_FLAG_PRIORITY = 0x20, + + LWS_HTTP2_FLAG_SETTINGS_ACK = 1, +}; + +#define LWS_HTTP2_STREAM_ID_MASTER 0 +#define LWS_HTTP2_FRAME_HEADER_LENGTH 9 +#define LWS_HTTP2_SETTINGS_LENGTH 6 + +struct http2_settings { + unsigned int setting[LWS_HTTP2_SETTINGS__COUNT]; +}; + +enum http2_hpack_state { + + /* optional before first header block */ + HPKS_OPT_PADDING, + HKPS_OPT_E_DEPENDENCY, + HKPS_OPT_WEIGHT, + + /* header block */ + HPKS_TYPE, + + HPKS_IDX_EXT, + + HPKS_HLEN, + HPKS_HLEN_EXT, + + HPKS_DATA, + + /* optional after last header block */ + HKPS_OPT_DISCARD_PADDING, +}; + +enum http2_hpack_type { + HPKT_INDEXED_HDR_7, + HPKT_INDEXED_HDR_6_VALUE_INCR, + HPKT_LITERAL_HDR_VALUE_INCR, + HPKT_INDEXED_HDR_4_VALUE, + HPKT_LITERAL_HDR_VALUE, + HPKT_SIZE_5 +}; + +struct hpack_dt_entry { + int token; /* additions that don't map to a token are ignored */ + int arg_offset; + int arg_len; +}; + +struct hpack_dynamic_table { + struct hpack_dt_entry *entries; + char *args; + int pos; + int next; + int num_entries; + int args_length; +}; + +struct _lws_http2_related { + /* + * having this first lets us also re-use all HTTP union code + * and in turn, http_mode_related has allocated headers in right + * place so we can use the header apis on the wsi directly still + */ + struct _lws_http_mode_related http; /* MUST BE FIRST IN STRUCT */ + + struct http2_settings my_settings; + struct http2_settings peer_settings; + + struct libwebsocket *parent_wsi; + struct libwebsocket *next_child_wsi; + + struct hpack_dynamic_table *hpack_dyn_table; + + unsigned int count; + + /* frame */ + unsigned int length; + unsigned int stream_id; + struct libwebsocket *stream_wsi; + unsigned char type; + unsigned char flags; + unsigned char frame_state; + unsigned char padding; + + unsigned char ping_payload[8]; + + unsigned short round_robin_POLLOUT; + unsigned short count_POLLOUT_children; + + unsigned int END_STREAM:1; + unsigned int END_HEADERS:1; + unsigned int send_END_STREAM:1; + unsigned int GOING_AWAY; + unsigned int requested_POLLOUT:1; + unsigned int waiting_tx_credit:1; + + /* hpack */ + enum http2_hpack_state hpack; + enum http2_hpack_type hpack_type; + unsigned int header_index; + unsigned int hpack_len; + unsigned short hpack_pos; + unsigned char hpack_m; + unsigned int hpack_e_dep; + unsigned int huff:1; + unsigned int value:1; + + /* negative credit is mandated by the spec */ + int tx_credit; + unsigned int my_stream_id; + unsigned int child_count; + int my_priority; + unsigned char initialized; + unsigned char one_setting[LWS_HTTP2_SETTINGS_LENGTH]; +}; + +#define HTTP2_IS_TOPLEVEL_WSI(wsi) (!wsi->u.http2.parent_wsi) + +#endif + +struct _lws_header_related { + /* MUST be first in struct */ + struct allocated_headers *ah; + short lextable_pos; + unsigned short current_token_limit; + unsigned char parser_state; /* enum lws_token_indexes */ + enum uri_path_states ups; + enum uri_esc_states ues; + char esc_stash; +}; + +struct _lws_websocket_related { + char *rx_user_buffer; + int rx_user_buffer_head; + unsigned char frame_masking_nonce_04[4]; + unsigned char frame_mask_index; + size_t rx_packet_length; + unsigned char opcode; + unsigned int final:1; + unsigned char rsv; + unsigned int frame_is_binary:1; + unsigned int all_zero_nonce:1; + short close_reason; /* enum lws_close_status */ + + unsigned int this_frame_masked:1; + unsigned int inside_frame:1; /* next write will be more of frame */ + unsigned int clean_buffer:1; /* buffer not rewritten by extension */ + + unsigned char *ping_payload_buf; /* non-NULL if malloc'd */ + unsigned int ping_payload_alloc; /* length malloc'd */ + unsigned int ping_payload_len; /* nonzero if PONG pending */ +}; + +struct libwebsocket { + + /* lifetime members */ + +#ifdef LWS_USE_LIBEV + struct lws_io_watcher w_read; + struct lws_io_watcher w_write; +#endif /* LWS_USE_LIBEV */ + const struct libwebsocket_protocols *protocol; +#ifndef LWS_NO_EXTENSIONS + struct libwebsocket_extension * + active_extensions[LWS_MAX_EXTENSIONS_ACTIVE]; + void *active_extensions_user[LWS_MAX_EXTENSIONS_ACTIVE]; + unsigned char count_active_extensions; + unsigned int extension_data_pending:1; +#endif + unsigned char ietf_spec_revision; + enum lws_pending_protocol_send pps; + + char mode; /* enum connection_mode */ + char state; /* enum lws_connection_states */ + char lws_rx_parse_state; /* enum lws_rx_parse_state */ + char rx_frame_type; /* enum libwebsocket_write_protocol */ + + unsigned int hdr_parsing_completed:1; + unsigned int user_space_externally_allocated:1; + unsigned int socket_is_permanently_unusable:1; + + char pending_timeout; /* enum pending_timeout */ + time_t pending_timeout_limit; + + int sock; + int position_in_fds_table; +#ifdef LWS_LATENCY + unsigned long action_start; + unsigned long latency_start; +#endif + /* rxflow handling */ + unsigned char *rxflow_buffer; + int rxflow_len; + int rxflow_pos; + unsigned int rxflow_change_to:2; + + /* truncated send handling */ + unsigned char *truncated_send_malloc; /* non-NULL means buffering in progress */ + unsigned int truncated_send_allocation; /* size of malloc */ + unsigned int truncated_send_offset; /* where we are in terms of spilling */ + unsigned int truncated_send_len; /* how much is buffered */ + + void *user_space; + + /* members with mutually exclusive lifetimes are unionized */ + + union u { + struct _lws_http_mode_related http; +#ifdef LWS_USE_HTTP2 + struct _lws_http2_related http2; +#endif + struct _lws_header_related hdr; + struct _lws_websocket_related ws; + } u; + +#ifdef LWS_OPENSSL_SUPPORT + SSL *ssl; + BIO *client_bio; + unsigned int use_ssl:2; + unsigned int buffered_reads_pending:1; + unsigned int upgraded:1; +#endif + +#ifdef _WIN32 + BOOL sock_send_blocking; +#endif +}; + +LWS_EXTERN int log_level; + +LWS_EXTERN void +libwebsocket_close_and_free_session(struct libwebsocket_context *context, + struct libwebsocket *wsi, enum lws_close_status); + +LWS_EXTERN int +remove_wsi_socket_from_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi); +LWS_EXTERN int +lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len); + +#ifndef LWS_LATENCY +static inline void lws_latency(struct libwebsocket_context *context, + struct libwebsocket *wsi, const char *action, + int ret, int completion) { do { } while (0); } +static inline void lws_latency_pre(struct libwebsocket_context *context, + struct libwebsocket *wsi) { do { } while (0); } +#else +#define lws_latency_pre(_context, _wsi) lws_latency(_context, _wsi, NULL, 0, 0) +extern void +lws_latency(struct libwebsocket_context *context, + struct libwebsocket *wsi, const char *action, + int ret, int completion); +#endif + +LWS_EXTERN void lws_set_protocol_write_pending(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum lws_pending_protocol_send pend); +LWS_EXTERN int +libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c); + +LWS_EXTERN int +libwebsocket_parse(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char c); + +LWS_EXTERN int +lws_http_action(struct libwebsocket_context *context, struct libwebsocket *wsi); + +LWS_EXTERN int +lws_b64_selftest(void); + +LWS_EXTERN struct libwebsocket * +wsi_from_fd(struct libwebsocket_context *context, int fd); + +LWS_EXTERN int +insert_wsi_socket_into_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi); + +LWS_EXTERN int +lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len); + + +LWS_EXTERN int +libwebsocket_service_timeout_check(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned int sec); + +LWS_EXTERN struct libwebsocket * +libwebsocket_client_connect_2(struct libwebsocket_context *context, + struct libwebsocket *wsi); + +LWS_EXTERN struct libwebsocket * +libwebsocket_create_new_server_wsi(struct libwebsocket_context *context); + +LWS_EXTERN char * +libwebsockets_generate_client_handshake(struct libwebsocket_context *context, + struct libwebsocket *wsi, char *pkt); + +LWS_EXTERN int +lws_handle_POLLOUT_event(struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd); + +/* + * EXTENSIONS + */ + +#ifndef LWS_NO_EXTENSIONS +LWS_VISIBLE void +lws_context_init_extensions(struct lws_context_creation_info *info, + struct libwebsocket_context *context); +LWS_EXTERN int +lws_any_extension_handled(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_extension_callback_reasons r, + void *v, size_t len); + +LWS_EXTERN int +lws_ext_callback_for_each_active(struct libwebsocket *wsi, int reason, + void *buf, int len); +LWS_EXTERN int +lws_ext_callback_for_each_extension_type( + struct libwebsocket_context *context, struct libwebsocket *wsi, + int reason, void *arg, int len); +#else +#define lws_any_extension_handled(_a, _b, _c, _d, _e) (0) +#define lws_ext_callback_for_each_active(_a, _b, _c, _d) (0) +#define lws_ext_callback_for_each_extension_type(_a, _b, _c, _d, _e) (0) +#define lws_issue_raw_ext_access lws_issue_raw +#define lws_context_init_extensions(_a, _b) +#endif + +LWS_EXTERN int +lws_client_interpret_server_handshake(struct libwebsocket_context *context, + struct libwebsocket *wsi); + +LWS_EXTERN int +libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c); + +LWS_EXTERN int +lws_issue_raw_ext_access(struct libwebsocket *wsi, + unsigned char *buf, size_t len); + +LWS_EXTERN int +_libwebsocket_rx_flow_control(struct libwebsocket *wsi); + +LWS_EXTERN void +lws_union_transition(struct libwebsocket *wsi, enum connection_mode mode); + +LWS_EXTERN int +user_callback_handle_rxflow(callback_function, + struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum libwebsocket_callback_reasons reason, void *user, + void *in, size_t len); +#ifdef LWS_USE_HTTP2 +LWS_EXTERN struct libwebsocket *lws_http2_get_network_wsi(struct libwebsocket *wsi); +struct libwebsocket * lws_http2_get_nth_child(struct libwebsocket *wsi, int n); +LWS_EXTERN int +lws_http2_interpret_settings_payload(struct http2_settings *settings, unsigned char *buf, int len); +LWS_EXTERN void lws_http2_init(struct http2_settings *settings); +LWS_EXTERN int +lws_http2_parser(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char c); +LWS_EXTERN int lws_http2_do_pps_send(struct libwebsocket_context *context, struct libwebsocket *wsi); +LWS_EXTERN int lws_http2_frame_write(struct libwebsocket *wsi, int type, int flags, unsigned int sid, unsigned int len, unsigned char *buf); +LWS_EXTERN struct libwebsocket * +lws_http2_wsi_from_id(struct libwebsocket *wsi, unsigned int sid); +LWS_EXTERN int lws_hpack_interpret(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned char c); +LWS_EXTERN int +lws_add_http2_header_by_name(struct libwebsocket_context *context, + struct libwebsocket *wsi, + const unsigned char *name, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end); +LWS_EXTERN int +lws_add_http2_header_by_token(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum lws_token_indexes token, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end); +LWS_EXTERN int +lws_add_http2_header_status(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned int code, + unsigned char **p, + unsigned char *end); +LWS_EXTERN +void lws_http2_configure_if_upgraded(struct libwebsocket *wsi); +#else +#define lws_http2_configure_if_upgraded(x) +#endif + +LWS_EXTERN int +lws_plat_set_socket_options(struct libwebsocket_context *context, int fd); + +LWS_EXTERN int +lws_allocate_header_table(struct libwebsocket *wsi); + +LWS_EXTERN int +lws_free_header_table(struct libwebsocket *wsi); + +LWS_EXTERN char * +lws_hdr_simple_ptr(struct libwebsocket *wsi, enum lws_token_indexes h); + +LWS_EXTERN int +lws_hdr_simple_create(struct libwebsocket *wsi, + enum lws_token_indexes h, const char *s); + +LWS_EXTERN int +libwebsocket_ensure_user_space(struct libwebsocket *wsi); + +LWS_EXTERN int +lws_change_pollfd(struct libwebsocket *wsi, int _and, int _or); + +#ifndef LWS_NO_SERVER +int lws_context_init_server(struct lws_context_creation_info *info, + struct libwebsocket_context *context); +LWS_EXTERN int handshake_0405(struct libwebsocket_context *context, + struct libwebsocket *wsi); +LWS_EXTERN int +libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi, + unsigned char *buf, size_t len); +LWS_EXTERN void +lws_server_get_canonical_hostname(struct libwebsocket_context *context, + struct lws_context_creation_info *info); +#else +#define lws_context_init_server(_a, _b) (0) +#define libwebsocket_interpret_incoming_packet(_a, _b, _c) (0) +#define lws_server_get_canonical_hostname(_a, _b) +#endif + +#ifndef LWS_NO_DAEMONIZE +LWS_EXTERN int get_daemonize_pid(); +#else +#define get_daemonize_pid() (0) +#endif + +LWS_EXTERN int interface_to_sa(struct libwebsocket_context *context, + const char *ifname, struct sockaddr_in *addr, size_t addrlen); + +LWS_EXTERN void lwsl_emit_stderr(int level, const char *line); + +#ifdef _WIN32 +LWS_EXTERN HANDLE lws_plat_open_file(const char* filename, unsigned long* filelen); +#else +LWS_EXTERN int lws_plat_open_file(const char* filename, unsigned long* filelen); +#endif + +enum lws_ssl_capable_status { + LWS_SSL_CAPABLE_ERROR = -1, + LWS_SSL_CAPABLE_MORE_SERVICE = -2, +}; + +#ifndef LWS_OPENSSL_SUPPORT +#define LWS_SSL_ENABLED(context) (0) +#define lws_context_init_server_ssl(_a, _b) (0) +#define lws_ssl_destroy(_a) +#define lws_context_init_http2_ssl(_a) +#define lws_ssl_capable_read lws_ssl_capable_read_no_ssl +#define lws_ssl_capable_write lws_ssl_capable_write_no_ssl +#define lws_server_socket_service_ssl(_a, _b, _c, _d, _e) (0) +#define lws_ssl_close(_a) (0) +#define lws_ssl_context_destroy(_a) +#else +#define LWS_SSL_ENABLED(context) (context->use_ssl) +LWS_EXTERN int openssl_websocket_private_data_index; +LWS_EXTERN int +lws_ssl_capable_read(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char *buf, int len); + +LWS_EXTERN int +lws_ssl_capable_write(struct libwebsocket *wsi, unsigned char *buf, int len); +LWS_EXTERN int +lws_server_socket_service_ssl(struct libwebsocket_context *context, + struct libwebsocket **wsi, struct libwebsocket *new_wsi, + int accept_fd, struct libwebsocket_pollfd *pollfd); +LWS_EXTERN int +lws_ssl_close(struct libwebsocket *wsi); +LWS_EXTERN void +lws_ssl_context_destroy(struct libwebsocket_context *context); +#ifndef LWS_NO_SERVER +LWS_EXTERN int +lws_context_init_server_ssl(struct lws_context_creation_info *info, + struct libwebsocket_context *context); +#else +#define lws_context_init_server_ssl(_a, _b) (0) +#endif +LWS_EXTERN void +lws_ssl_destroy(struct libwebsocket_context *context); + +/* HTTP2-related */ + +#ifdef LWS_USE_HTTP2 +LWS_EXTERN void +lws_context_init_http2_ssl(struct libwebsocket_context *context); +#else +#define lws_context_init_http2_ssl(_a) +#endif +#endif + +LWS_EXTERN int +lws_ssl_capable_read_no_ssl(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char *buf, int len); + +LWS_EXTERN int +lws_ssl_capable_write_no_ssl(struct libwebsocket *wsi, unsigned char *buf, int len); + +#ifndef LWS_NO_CLIENT + LWS_EXTERN int lws_client_socket_service( + struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd); +#ifdef LWS_OPENSSL_SUPPORT + LWS_EXTERN int lws_context_init_client_ssl(struct lws_context_creation_info *info, + struct libwebsocket_context *context); +#else + #define lws_context_init_client_ssl(_a, _b) (0) +#endif + LWS_EXTERN int lws_handshake_client(struct libwebsocket *wsi, unsigned char **buf, size_t len); + LWS_EXTERN void + libwebsockets_decode_ssl_error(void); +#else +#define lws_context_init_client_ssl(_a, _b) (0) +#define lws_handshake_client(_a, _b, _c) (0) +#endif +#ifndef LWS_NO_SERVER + LWS_EXTERN int lws_server_socket_service( + struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd); + LWS_EXTERN int _libwebsocket_rx_flow_control(struct libwebsocket *wsi); + LWS_EXTERN int lws_handshake_server(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char **buf, size_t len); +#else +#define lws_server_socket_service(_a, _b, _c) (0) +#define _libwebsocket_rx_flow_control(_a) (0) +#define lws_handshake_server(_a, _b, _c, _d) (0) +#endif + +/* + * custom allocator + */ +LWS_EXTERN void* +lws_realloc(void *ptr, size_t size); + +LWS_EXTERN void* +lws_zalloc(size_t size); + +#define lws_malloc(S) lws_realloc(NULL, S) +#define lws_free(P) lws_realloc(P, 0) +#define lws_free2(P) do { lws_realloc(P, 0); (P) = NULL; } while(0) + +/* + * lws_plat_ + */ +LWS_EXTERN void +lws_plat_delete_socket_from_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi, int m); +LWS_EXTERN void +lws_plat_insert_socket_into_fds(struct libwebsocket_context *context, + struct libwebsocket *wsi); +LWS_EXTERN void +lws_plat_service_periodic(struct libwebsocket_context *context); + +LWS_EXTERN int +lws_plat_change_pollfd(struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pfd); +LWS_EXTERN int +lws_plat_context_early_init(void); +LWS_EXTERN void +lws_plat_context_early_destroy(struct libwebsocket_context *context); +LWS_EXTERN void +lws_plat_context_late_destroy(struct libwebsocket_context *context); +LWS_EXTERN int +lws_poll_listen_fd(struct libwebsocket_pollfd *fd); +LWS_EXTERN int +lws_plat_service(struct libwebsocket_context *context, int timeout_ms); +LWS_EXTERN int +lws_plat_init_fd_tables(struct libwebsocket_context *context); +LWS_EXTERN void +lws_plat_drop_app_privileges(struct lws_context_creation_info *info); +LWS_EXTERN unsigned long long +time_in_microseconds(void); +LWS_EXTERN const char * +lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt); diff --git a/src/engine/external/libwebsockets/server-handshake.c b/src/engine/external/libwebsockets/server-handshake.c new file mode 100644 index 0000000..b4641d1 --- /dev/null +++ b/src/engine/external/libwebsockets/server-handshake.c @@ -0,0 +1,274 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); } +#ifndef LWS_NO_EXTENSIONS +LWS_VISIBLE int +lws_extension_server_handshake(struct libwebsocket_context *context, + struct libwebsocket *wsi, char **p) +{ + int n; + char *c; + char ext_name[128]; + struct libwebsocket_extension *ext; + int ext_count = 0; + int more = 1; + + /* + * Figure out which extensions the client has that we want to + * enable on this connection, and give him back the list + */ + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) + return 0; + + /* + * break down the list of client extensions + * and go through them + */ + + if (lws_hdr_copy(wsi, (char *)context->service_buffer, + sizeof(context->service_buffer), + WSI_TOKEN_EXTENSIONS) < 0) + return 1; + + c = (char *)context->service_buffer; + lwsl_parser("WSI_TOKEN_EXTENSIONS = '%s'\n", c); + wsi->count_active_extensions = 0; + n = 0; + while (more) { + + if (*c && (*c != ',' && *c != ' ' && *c != '\t')) { + ext_name[n] = *c++; + if (n < sizeof(ext_name) - 1) + n++; + continue; + } + ext_name[n] = '\0'; + if (!*c) + more = 0; + else { + c++; + if (!n) + continue; + } + + /* check a client's extension against our support */ + + ext = wsi->protocol->owning_server->extensions; + + while (ext && ext->callback) { + + if (strcmp(ext_name, ext->name)) { + ext++; + continue; + } + + /* + * oh, we do support this one he + * asked for... but let's ask user + * code if it's OK to apply it on this + * particular connection + protocol + */ + + n = wsi->protocol->owning_server-> + protocols[0].callback( + wsi->protocol->owning_server, + wsi, + LWS_CALLBACK_CONFIRM_EXTENSION_OKAY, + wsi->user_space, ext_name, 0); + + /* + * zero return from callback means + * go ahead and allow the extension, + * it's what we get if the callback is + * unhandled + */ + + if (n) { + ext++; + continue; + } + + /* apply it */ + + if (ext_count) + *(*p)++ = ','; + else + LWS_CPYAPP(*p, + "\x0d\x0aSec-WebSocket-Extensions: "); + *p += sprintf(*p, "%s", ext_name); + ext_count++; + + /* instantiate the extension on this conn */ + + wsi->active_extensions_user[ + wsi->count_active_extensions] = + lws_zalloc(ext->per_session_data_size); + if (wsi->active_extensions_user[ + wsi->count_active_extensions] == NULL) { + lwsl_err("Out of mem\n"); + return 1; + } + + wsi->active_extensions[ + wsi->count_active_extensions] = ext; + + /* allow him to construct his context */ + + ext->callback(wsi->protocol->owning_server, + ext, wsi, + LWS_EXT_CALLBACK_CONSTRUCT, + wsi->active_extensions_user[ + wsi->count_active_extensions], NULL, 0); + + wsi->count_active_extensions++; + lwsl_parser("count_active_extensions <- %d\n", + wsi->count_active_extensions); + + ext++; + } + + n = 0; + } + + return 0; +} +#endif +int +handshake_0405(struct libwebsocket_context *context, struct libwebsocket *wsi) +{ + unsigned char hash[20]; + int n; + char *response; + char *p; + int accept_len; + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST) || + !lws_hdr_total_length(wsi, WSI_TOKEN_KEY)) { + lwsl_parser("handshake_04 missing pieces\n"); + /* completed header processing, but missing some bits */ + goto bail; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_KEY) >= + MAX_WEBSOCKET_04_KEY_LEN) { + lwsl_warn("Client key too long %d\n", MAX_WEBSOCKET_04_KEY_LEN); + goto bail; + } + + /* + * since key length is restricted above (currently 128), cannot + * overflow + */ + n = sprintf((char *)context->service_buffer, + "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + lws_hdr_simple_ptr(wsi, WSI_TOKEN_KEY)); + + libwebsockets_SHA1(context->service_buffer, n, hash); + + accept_len = lws_b64_encode_string((char *)hash, 20, + (char *)context->service_buffer, + sizeof(context->service_buffer)); + if (accept_len < 0) { + lwsl_warn("Base64 encoded hash too long\n"); + goto bail; + } + + /* allocate the per-connection user memory (if any) */ + if (libwebsocket_ensure_user_space(wsi)) + goto bail; + + /* create the response packet */ + + /* make a buffer big enough for everything */ + + response = (char *)context->service_buffer + MAX_WEBSOCKET_04_KEY_LEN + LWS_SEND_BUFFER_PRE_PADDING; + p = response; + LWS_CPYAPP(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a" + "Upgrade: WebSocket\x0d\x0a" + "Connection: Upgrade\x0d\x0a" + "Sec-WebSocket-Accept: "); + strcpy(p, (char *)context->service_buffer); + p += accept_len; + + if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL)) { + LWS_CPYAPP(p, "\x0d\x0aSec-WebSocket-Protocol: "); + n = lws_hdr_copy(wsi, p, 128, WSI_TOKEN_PROTOCOL); + if (n < 0) + goto bail; + p += n; + } + +#ifndef LWS_NO_EXTENSIONS + /* + * Figure out which extensions the client has that we want to + * enable on this connection, and give him back the list + */ + if (lws_extension_server_handshake(context, wsi, &p)) + goto bail; +#endif + /* end of response packet */ + + LWS_CPYAPP(p, "\x0d\x0a\x0d\x0a"); + + if (!lws_any_extension_handled(context, wsi, + LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX, + response, p - response)) { + + /* okay send the handshake response accepting the connection */ + + lwsl_parser("issuing resp pkt %d len\n", (int)(p - response)); +#ifdef DEBUG + fwrite(response, 1, p - response, stderr); +#endif + n = libwebsocket_write(wsi, (unsigned char *)response, + p - response, LWS_WRITE_HTTP_HEADERS); + if (n != (p - response)) { + lwsl_debug("handshake_0405: ERROR writing to socket\n"); + goto bail; + } + + } + + /* alright clean up and set ourselves into established state */ + + wsi->state = WSI_STATE_ESTABLISHED; + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + + /* notify user code that we're ready to roll */ + + if (wsi->protocol->callback) + wsi->protocol->callback(wsi->protocol->owning_server, + wsi, LWS_CALLBACK_ESTABLISHED, + wsi->user_space, NULL, 0); + + return 0; + + +bail: + /* free up his parsing allocations */ + lws_free_header_table(wsi); + return -1; +} + diff --git a/src/engine/external/libwebsockets/server.c b/src/engine/external/libwebsockets/server.c new file mode 100644 index 0000000..ed5c47b --- /dev/null +++ b/src/engine/external/libwebsockets/server.c @@ -0,0 +1,1162 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + + +#include "private-libwebsockets.h" + +int lws_context_init_server(struct lws_context_creation_info *info, + struct libwebsocket_context *context) +{ + int n; + int sockfd; + struct sockaddr_in sin; + socklen_t len = sizeof(sin); + int opt = 1; + struct libwebsocket *wsi; +#ifdef LWS_USE_IPV6 + struct sockaddr_in6 serv_addr6; +#endif + struct sockaddr_in serv_addr4; + struct sockaddr *v; + + /* set up our external listening socket we serve on */ + + if (info->port == CONTEXT_PORT_NO_LISTEN) + return 0; + +#ifdef LWS_USE_IPV6 + if (LWS_IPV6_ENABLED(context)) + sockfd = socket(AF_INET6, SOCK_STREAM, 0); + else +#endif + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + if (sockfd < 0) { + lwsl_err("ERROR opening socket\n"); + return 1; + } + + /* + * allow us to restart even if old sockets in TIME_WAIT + */ + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, + (const void *)&opt, sizeof(opt)) < 0) { + compatible_close(sockfd); + return 1; + } + + lws_plat_set_socket_options(context, sockfd); + +#ifdef LWS_USE_IPV6 + if (LWS_IPV6_ENABLED(context)) { + v = (struct sockaddr *)&serv_addr6; + n = sizeof(struct sockaddr_in6); + bzero((char *) &serv_addr6, sizeof(serv_addr6)); + serv_addr6.sin6_addr = in6addr_any; + serv_addr6.sin6_family = AF_INET6; + serv_addr6.sin6_port = htons(info->port); + } else +#endif + { + v = (struct sockaddr *)&serv_addr4; + n = sizeof(serv_addr4); + bzero((char *) &serv_addr4, sizeof(serv_addr4)); + serv_addr4.sin_addr.s_addr = INADDR_ANY; + serv_addr4.sin_family = AF_INET; + + if (info->iface) { + if (interface_to_sa(context, info->iface, + (struct sockaddr_in *)v, n) < 0) { + lwsl_err("Unable to find interface %s\n", + info->iface); + compatible_close(sockfd); + return 1; + } + } + + serv_addr4.sin_port = htons(info->port); + } /* ipv4 */ + + n = bind(sockfd, v, n); + if (n < 0) { + lwsl_err("ERROR on binding to port %d (%d %d)\n", + info->port, n, LWS_ERRNO); + compatible_close(sockfd); + return 1; + } + + if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1) + lwsl_warn("getsockname: %s\n", strerror(LWS_ERRNO)); + else + info->port = ntohs(sin.sin_port); + + context->listen_port = info->port; + + wsi = lws_zalloc(sizeof(struct libwebsocket)); + if (wsi == NULL) { + lwsl_err("Out of mem\n"); + compatible_close(sockfd); + return 1; + } + wsi->sock = sockfd; + wsi->mode = LWS_CONNMODE_SERVER_LISTENER; + + insert_wsi_socket_into_fds(context, wsi); + + context->listen_service_modulo = LWS_LISTEN_SERVICE_MODULO; + context->listen_service_count = 0; + context->listen_service_fd = sockfd; + + listen(sockfd, LWS_SOMAXCONN); + lwsl_notice(" Listening on port %d\n", info->port); + + return 0; +} + +int +_libwebsocket_rx_flow_control(struct libwebsocket *wsi) +{ + struct libwebsocket_context *context = wsi->protocol->owning_server; + + /* there is no pending change */ + if (!(wsi->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE)) + return 0; + + /* stuff is still buffered, not ready to really accept new input */ + if (wsi->rxflow_buffer) { + /* get ourselves called back to deal with stashed buffer */ + libwebsocket_callback_on_writable(context, wsi); + return 0; + } + + /* pending is cleared, we can change rxflow state */ + + wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE; + + lwsl_info("rxflow: wsi %p change_to %d\n", wsi, + wsi->rxflow_change_to & LWS_RXFLOW_ALLOW); + + /* adjust the pollfd for this wsi */ + + if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) { + if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { + lwsl_info("%s: fail\n", __func__); + return -1; + } + } else + if (lws_change_pollfd(wsi, LWS_POLLIN, 0)) + return -1; + + return 0; +} + +int lws_http_action(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ + char *uri_ptr = NULL; + int uri_len = 0; + enum http_version request_version; + enum http_connection_type connection_type; + int http_version_len; + char content_length_str[32]; + char http_version_str[10]; + char http_conn_str[20]; + int n; + + /* it's not websocket.... shall we accept it as http? */ + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) && + !lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) && +#ifdef LWS_USE_HTTP2 + !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH) && +#endif + !lws_hdr_total_length(wsi, WSI_TOKEN_OPTIONS_URI)) { + lwsl_warn("Missing URI in HTTP request\n"); + goto bail_nuke_ah; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) && + lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) { + lwsl_warn("GET and POST methods?\n"); + goto bail_nuke_ah; + } + + if (libwebsocket_ensure_user_space(wsi)) + goto bail_nuke_ah; + +#ifdef LWS_USE_HTTP2 + if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH)) { + uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_PATH); + uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH); + lwsl_info("HTTP2 request for '%s'\n", uri_ptr); + goto got_uri; + } +#endif + if (lws_hdr_total_length(wsi, WSI_TOKEN_OPTIONS_URI)) { + uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_OPTIONS_URI); + uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_OPTIONS_URI); + lwsl_info("HTTP OPTIONS request for '%s'\n", uri_ptr); + goto got_uri; + } + if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) { + uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_POST_URI); + uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI); + lwsl_info("HTTP POST request for '%s'\n", uri_ptr); + goto got_uri; + } + if (lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) { + uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI); + uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI); + lwsl_info("HTTP GET request for '%s'\n", uri_ptr); + } + +got_uri: + /* HTTP header had a content length? */ + + wsi->u.http.content_length = 0; + if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) + wsi->u.http.content_length = 100 * 1024 * 1024; + + if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) { + lws_hdr_copy(wsi, content_length_str, + sizeof(content_length_str) - 1, + WSI_TOKEN_HTTP_CONTENT_LENGTH); + wsi->u.http.content_length = atoi(content_length_str); + } + + /* http_version? Default to 1.0, override with token: */ + request_version = HTTP_VERSION_1_0; + + /* Works for single digit HTTP versions. : */ + http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP); + if (http_version_len > 7) { + lws_hdr_copy(wsi, http_version_str, + sizeof(http_version_str) - 1, WSI_TOKEN_HTTP); + if (http_version_str[5] == '1' && http_version_str[7] == '1') + request_version = HTTP_VERSION_1_1; + } + wsi->u.http.request_version = request_version; + + /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */ + if (request_version == HTTP_VERSION_1_1) + connection_type = HTTP_CONNECTION_KEEP_ALIVE; + else + connection_type = HTTP_CONNECTION_CLOSE; + + /* Override default if http "Connection:" header: */ + if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) { + lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1, + WSI_TOKEN_CONNECTION); + http_conn_str[sizeof(http_conn_str) - 1] = '\0'; + if (!strcasecmp(http_conn_str, "keep-alive")) + connection_type = HTTP_CONNECTION_KEEP_ALIVE; + else + if (strcasecmp(http_conn_str, "close")) + connection_type = HTTP_CONNECTION_CLOSE; + } + wsi->u.http.connection_type = connection_type; + + n = 0; + if (wsi->protocol->callback) + n = wsi->protocol->callback(context, wsi, + LWS_CALLBACK_FILTER_HTTP_CONNECTION, + wsi->user_space, uri_ptr, uri_len); + + if (!n) { + /* + * if there is content supposed to be coming, + * put a timeout on it having arrived + */ + libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, + AWAITING_TIMEOUT); + + if (wsi->protocol->callback) + n = wsi->protocol->callback(context, wsi, + LWS_CALLBACK_HTTP, + wsi->user_space, uri_ptr, uri_len); + } + + /* now drop the header info we kept a pointer to */ + lws_free2(wsi->u.http.ah); + + if (n) { + lwsl_info("LWS_CALLBACK_HTTP closing\n"); + return 1; /* struct ah ptr already nuked */ } + + /* + * If we're not issuing a file, check for content_length or + * HTTP keep-alive. No keep-alive header allocation for + * ISSUING_FILE, as this uses HTTP/1.0. + * + * In any case, return 0 and let libwebsocket_read decide how to + * proceed based on state + */ + if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE) + /* Prepare to read body if we have a content length: */ + if (wsi->u.http.content_length > 0) + wsi->state = WSI_STATE_HTTP_BODY; + + return 0; + +bail_nuke_ah: + /* drop the header info */ + lws_free2(wsi->u.hdr.ah); + + return 1; +} + + +int lws_handshake_server(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned char **buf, size_t len) +{ + struct allocated_headers *ah; + int protocol_len; + char protocol_list[128]; + char protocol_name[32]; + char *p; + int n, hit; + + /* LWS_CONNMODE_WS_SERVING */ + + while (len--) { + if (libwebsocket_parse(context, wsi, *(*buf)++)) { + lwsl_info("libwebsocket_parse failed\n"); + goto bail_nuke_ah; + } + + if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE) + continue; + + lwsl_parser("libwebsocket_parse sees parsing complete\n"); + + wsi->mode = LWS_CONNMODE_PRE_WS_SERVING_ACCEPT; + libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + + /* is this websocket protocol or normal http 1.0? */ + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE) || + !lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) { + + ah = wsi->u.hdr.ah; + + lws_union_transition(wsi, LWS_CONNMODE_HTTP_SERVING_ACCEPTED); + wsi->state = WSI_STATE_HTTP; + wsi->u.http.fd = LWS_INVALID_FILE; + + /* expose it at the same offset as u.hdr */ + wsi->u.http.ah = ah; + + n = lws_http_action(context, wsi); + + return n; + } + + if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), + "websocket")) + goto upgrade_ws; +#ifdef LWS_USE_HTTP2 + if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), + "h2c-14")) + goto upgrade_h2c; +#endif + /* dunno what he wanted to upgrade to */ + goto bail_nuke_ah; + +#ifdef LWS_USE_HTTP2 +upgrade_h2c: + if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) { + lwsl_err("missing http2_settings\n"); + goto bail_nuke_ah; + } + + lwsl_err("h2c upgrade...\n"); + + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS); + /* convert the peer's HTTP-Settings */ + n = lws_b64_decode_string(p, protocol_list, sizeof(protocol_list)); + if (n < 0) { + lwsl_parser("HTTP2_SETTINGS too long\n"); + return 1; + } + + /* adopt the header info */ + + ah = wsi->u.hdr.ah; + + lws_union_transition(wsi, LWS_CONNMODE_HTTP2_SERVING); + + /* http2 union member has http union struct at start */ + wsi->u.http.ah = ah; + + lws_http2_init(&wsi->u.http2.peer_settings); + lws_http2_init(&wsi->u.http2.my_settings); + + /* HTTP2 union */ + + lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings, (unsigned char *)protocol_list, n); + + strcpy(protocol_list, + "HTTP/1.1 101 Switching Protocols\x0d\x0a" + "Connection: Upgrade\x0d\x0a" + "Upgrade: h2c\x0d\x0a\x0d\x0a"); + n = lws_issue_raw(wsi, (unsigned char *)protocol_list, + strlen(protocol_list)); + if (n != strlen(protocol_list)) { + lwsl_debug("http2 switch: ERROR writing to socket\n"); + return 1; + } + + wsi->state = WSI_STATE_HTTP2_AWAIT_CLIENT_PREFACE; + + return 0; +#endif + +upgrade_ws: + if (!wsi->protocol) + lwsl_err("NULL protocol at libwebsocket_read\n"); + + /* + * It's websocket + * + * Select the first protocol we support from the list + * the client sent us. + * + * Copy it to remove header fragmentation + */ + + if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1, + WSI_TOKEN_PROTOCOL) < 0) { + lwsl_err("protocol list too long"); + goto bail_nuke_ah; + } + + protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); + protocol_list[protocol_len] = '\0'; + p = protocol_list; + hit = 0; + + while (*p && !hit) { + n = 0; + while (n < sizeof(protocol_name) - 1 && *p && *p !=',') + protocol_name[n++] = *p++; + protocol_name[n] = '\0'; + if (*p) + p++; + + lwsl_info("checking %s\n", protocol_name); + + n = 0; + while (wsi->protocol && context->protocols[n].callback) { + if (!wsi->protocol->name) { + n++; + continue; + } + if (!strcmp(context->protocols[n].name, + protocol_name)) { + lwsl_info("prot match %d\n", n); + wsi->protocol = &context->protocols[n]; + hit = 1; + break; + } + + n++; + } + } + + /* we didn't find a protocol he wanted? */ + + if (!hit) { + if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL) == + NULL) { + /* + * some clients only have one protocol and + * do not sent the protocol list header... + * allow it and match to protocol 0 + */ + lwsl_info("defaulting to prot 0 handler\n"); + wsi->protocol = &context->protocols[0]; + } else { + lwsl_err("No protocol from list \"%s\" supported\n", + protocol_list); + goto bail_nuke_ah; + } + } + + /* allocate wsi->user storage */ + if (libwebsocket_ensure_user_space(wsi)) + goto bail_nuke_ah; + + /* + * Give the user code a chance to study the request and + * have the opportunity to deny it + */ + + if ((wsi->protocol->callback)(wsi->protocol->owning_server, wsi, + LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, + wsi->user_space, + lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) { + lwsl_warn("User code denied connection\n"); + goto bail_nuke_ah; + } + + + /* + * Perform the handshake according to the protocol version the + * client announced + */ + + switch (wsi->ietf_spec_revision) { + case 13: + lwsl_parser("lws_parse calling handshake_04\n"); + if (handshake_0405(context, wsi)) { + lwsl_info("hs0405 has failed the connection\n"); + goto bail_nuke_ah; + } + break; + + default: + lwsl_warn("Unknown client spec version %d\n", + wsi->ietf_spec_revision); + goto bail_nuke_ah; + } + + /* drop the header info -- no bail_nuke_ah after this */ + lws_free_header_table(wsi); + + lws_union_transition(wsi, LWS_CONNMODE_WS_SERVING); + + /* + * create the frame buffer for this connection according to the + * size mentioned in the protocol definition. If 0 there, use + * a big default for compatibility + */ + + n = wsi->protocol->rx_buffer_size; + if (!n) + n = LWS_MAX_SOCKET_IO_BUF; + n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING; + wsi->u.ws.rx_user_buffer = lws_malloc(n); + if (!wsi->u.ws.rx_user_buffer) { + lwsl_err("Out of Mem allocating rx buffer %d\n", n); + return 1; + } + lwsl_info("Allocating RX buffer %d\n", n); + + if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { + lwsl_warn("Failed to set SNDBUF to %d", n); + return 1; + } + + lwsl_parser("accepted v%02d connection\n", + wsi->ietf_spec_revision); + } /* while all chars are handled */ + + return 0; + +bail_nuke_ah: + /* drop the header info */ + lws_free_header_table(wsi); + return 1; +} + +struct libwebsocket * +libwebsocket_create_new_server_wsi(struct libwebsocket_context *context) +{ + struct libwebsocket *new_wsi; + + new_wsi = lws_zalloc(sizeof(struct libwebsocket)); + if (new_wsi == NULL) { + lwsl_err("Out of memory for new connection\n"); + return NULL; + } + + new_wsi->pending_timeout = NO_PENDING_TIMEOUT; + new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; + + /* intialize the instance struct */ + + new_wsi->state = WSI_STATE_HTTP; + new_wsi->mode = LWS_CONNMODE_HTTP_SERVING; + new_wsi->hdr_parsing_completed = 0; + + if (lws_allocate_header_table(new_wsi)) { + lws_free(new_wsi); + return NULL; + } + + /* + * these can only be set once the protocol is known + * we set an unestablished connection's protocol pointer + * to the start of the supported list, so it can look + * for matching ones during the handshake + */ + new_wsi->protocol = context->protocols; + new_wsi->user_space = NULL; + new_wsi->ietf_spec_revision = 0; + + /* + * outermost create notification for wsi + * no user_space because no protocol selection + */ + context->protocols[0].callback(context, new_wsi, + LWS_CALLBACK_WSI_CREATE, NULL, NULL, 0); + + return new_wsi; +} + +/** + * lws_http_transaction_completed() - wait for new http transaction or close + * @wsi: websocket connection + * + * Returns 1 if the HTTP connection must close now + * Returns 0 and resets connection to wait for new HTTP header / + * transaction if possible + */ + +LWS_VISIBLE +int lws_http_transaction_completed(struct libwebsocket *wsi) +{ + /* if we can't go back to accept new headers, drop the connection */ + if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) { + lwsl_info("%s: close connection\n", __func__); + return 1; + } + + /* otherwise set ourselves up ready to go again */ + wsi->state = WSI_STATE_HTTP; + + lwsl_info("%s: await new transaction\n", __func__); + + return 0; +} + +int lws_server_socket_service(struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd) +{ + struct libwebsocket *new_wsi = NULL; + int accept_fd = 0; + socklen_t clilen; + struct sockaddr_in cli_addr; + int n; + int len; + + switch (wsi->mode) { + + case LWS_CONNMODE_HTTP_SERVING: + case LWS_CONNMODE_HTTP_SERVING_ACCEPTED: + case LWS_CONNMODE_HTTP2_SERVING: + + /* handle http headers coming in */ + + /* pending truncated sends have uber priority */ + + if (wsi->truncated_send_len) { + if (pollfd->revents & LWS_POLLOUT) + if (lws_issue_raw(wsi, wsi->truncated_send_malloc + + wsi->truncated_send_offset, + wsi->truncated_send_len) < 0) { + lwsl_info("closing from socket service\n"); + return -1; + } + /* + * we can't afford to allow input processing send + * something new, so spin around he event loop until + * he doesn't have any partials + */ + break; + } + + /* any incoming data ready? */ + + if (pollfd->revents & LWS_POLLIN) { + len = lws_ssl_capable_read(context, wsi, + context->service_buffer, + sizeof(context->service_buffer)); + switch (len) { + case 0: + lwsl_info("lws_server_skt_srv: read 0 len\n"); + /* lwsl_info(" state=%d\n", wsi->state); */ + if (!wsi->hdr_parsing_completed) + lws_free_header_table(wsi); + /* fallthru */ + case LWS_SSL_CAPABLE_ERROR: + libwebsocket_close_and_free_session( + context, wsi, + LWS_CLOSE_STATUS_NOSTATUS); + return 0; + case LWS_SSL_CAPABLE_MORE_SERVICE: + goto try_pollout; + } + + /* just ignore incoming if waiting for close */ + if (wsi->state != WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) { + + /* hm this may want to send (via HTTP callback for example) */ + n = libwebsocket_read(context, wsi, + context->service_buffer, len); + if (n < 0) + /* we closed wsi */ + return 0; + + /* hum he may have used up the writability above */ + break; + } + } + +try_pollout: + /* this handles POLLOUT for http serving fragments */ + + if (!(pollfd->revents & LWS_POLLOUT)) + break; + + /* one shot */ + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) + goto fail; + + lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE); + + if (wsi->state != WSI_STATE_HTTP_ISSUING_FILE) { + n = user_callback_handle_rxflow( + wsi->protocol->callback, + wsi->protocol->owning_server, + wsi, LWS_CALLBACK_HTTP_WRITEABLE, + wsi->user_space, + NULL, + 0); + if (n < 0) + goto fail; + break; + } + + /* >0 == completion, <0 == error */ + n = libwebsockets_serve_http_file_fragment(context, wsi); + if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) + goto fail; + break; + + case LWS_CONNMODE_SERVER_LISTENER: + + /* pollin means a client has connected to us then */ + + if (!(pollfd->revents & LWS_POLLIN)) + break; + + /* listen socket got an unencrypted connection... */ + + clilen = sizeof(cli_addr); + lws_latency_pre(context, wsi); + accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr, + &clilen); + lws_latency(context, wsi, + "unencrypted accept LWS_CONNMODE_SERVER_LISTENER", + accept_fd, accept_fd >= 0); + if (accept_fd < 0) { + if (LWS_ERRNO == LWS_EAGAIN || LWS_ERRNO == LWS_EWOULDBLOCK) { + lwsl_debug("accept asks to try again\n"); + break; + } + lwsl_warn("ERROR on accept: %s\n", strerror(LWS_ERRNO)); + break; + } + + lws_plat_set_socket_options(context, accept_fd); + + /* + * look at who we connected to and give user code a chance + * to reject based on client IP. There's no protocol selected + * yet so we issue this to protocols[0] + */ + + if ((context->protocols[0].callback)(context, wsi, + LWS_CALLBACK_FILTER_NETWORK_CONNECTION, + NULL, (void *)(long)accept_fd, 0)) { + lwsl_debug("Callback denied network connection\n"); + compatible_close(accept_fd); + break; + } + + new_wsi = libwebsocket_create_new_server_wsi(context); + if (new_wsi == NULL) { + compatible_close(accept_fd); + break; + } + + new_wsi->sock = accept_fd; + + /* the transport is accepted... give him time to negotiate */ + libwebsocket_set_timeout(new_wsi, + PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, + AWAITING_TIMEOUT); + + /* + * A new connection was accepted. Give the user a chance to + * set properties of the newly created wsi. There's no protocol + * selected yet so we issue this to protocols[0] + */ + + (context->protocols[0].callback)(context, new_wsi, + LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0); + + lws_libev_accept(context, new_wsi, accept_fd); + + if (!LWS_SSL_ENABLED(context)) { + lwsl_debug("accepted new conn port %u on fd=%d\n", + ntohs(cli_addr.sin_port), accept_fd); + + insert_wsi_socket_into_fds(context, new_wsi); + } + break; + + default: + break; + } + + if (lws_server_socket_service_ssl(context, &wsi, new_wsi, + accept_fd, pollfd)) + goto fail; + + return 0; + +fail: + libwebsocket_close_and_free_session(context, wsi, + LWS_CLOSE_STATUS_NOSTATUS); + return 1; +} + +#include "lextable-strings.h" + +const unsigned char *lws_token_to_string(enum lws_token_indexes token) +{ + if ((unsigned int)token >= ARRAY_SIZE(set)) + return NULL; + + return (unsigned char *)set[token]; +} + +int lws_add_http_header_by_name(struct libwebsocket_context *context, + struct libwebsocket *wsi, + const unsigned char *name, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end) +{ +#ifdef LWS_USE_HTTP2 + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) + return lws_add_http2_header_by_name(context, wsi, name, value, length, p, end); +#endif + if (name) { + while (*p < end && *name) + *((*p)++) = *name++; + + if (*p == end) + return 1; + + *((*p)++) = ' '; + } + if (*p + length + 3 >= end) + return 1; + + memcpy(*p, value, length); + *p += length; + + *((*p)++) = '\x0d'; + *((*p)++) = '\x0a'; + + return 0; +} + +int lws_finalize_http_header(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned char **p, + unsigned char *end) +{ +#ifdef LWS_USE_HTTP2 + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) + return 0; +#endif + + if ((long)(end - *p) < 3) + return 1; + + *((*p)++) = '\x0d'; + *((*p)++) = '\x0a'; + + return 0; +} + +int lws_add_http_header_by_token(struct libwebsocket_context *context, + struct libwebsocket *wsi, + enum lws_token_indexes token, + const unsigned char *value, + int length, + unsigned char **p, + unsigned char *end) +{ + const unsigned char *name; +#ifdef LWS_USE_HTTP2 + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) + return lws_add_http2_header_by_token(context, wsi, token, value, length, p, end); +#endif + name = lws_token_to_string(token); + if (!name) + return 1; + + return lws_add_http_header_by_name(context, wsi, name, value, length, p, end); +} + +int lws_add_http_header_content_length(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned long content_length, + unsigned char **p, + unsigned char *end) +{ + char b[24]; + int n; + + n = sprintf(b, "%lu", content_length); + if (lws_add_http_header_by_token(context, wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, (unsigned char *)b, n, p, end)) + return 1; + wsi->u.http.content_length = content_length; + wsi->u.http.content_remain = content_length; + + return 0; +} + +static const char *err400[] = { + "Bad Request", + "Unauthorized", + "Payment Required", + "Forbidden", + "Not Found", + "Method Not Allowed", + "Not Acceptable", + "Proxy Auth Required", + "Request Timeout", + "Conflict", + "Gone", + "Length Required", + "Precondition Failed", + "Request Entity Too Large", + "Request URI too Long", + "Unsupported Media Type", + "Requested Range Not Satisfiable", + "Expectation Failed" +}; + +static const char *err500[] = { + "Internal Server Error", + "Not Implemented", + "Bad Gateway", + "Service Unavailable", + "Gateway Timeout", + "HTTP Version Not Supported" +}; + +int lws_add_http_header_status(struct libwebsocket_context *context, + struct libwebsocket *wsi, + unsigned int code, + unsigned char **p, + unsigned char *end) +{ + unsigned char code_and_desc[60]; + const char *description = ""; + int n; + +#ifdef LWS_USE_HTTP2 + if (wsi->mode == LWS_CONNMODE_HTTP2_SERVING) + return lws_add_http2_header_status(context, wsi, code, p, end); +#endif + if (code >= 400 && code < (400 + ARRAY_SIZE(err400))) + description = err400[code - 400]; + if (code >= 500 && code < (500 + ARRAY_SIZE(err500))) + description = err500[code - 500]; + + n = sprintf((char *)code_and_desc, "HTTP/1.0 %u %s", code, description); + + return lws_add_http_header_by_name(context, wsi, NULL, code_and_desc, n, p, end); +} + +/** + * libwebsockets_return_http_status() - Return simple http status + * @context: libwebsockets context + * @wsi: Websocket instance (available from user callback) + * @code: Status index, eg, 404 + * @html_body: User-readable HTML description < 1KB, or NULL + * + * Helper to report HTTP errors back to the client cleanly and + * consistently + */ +LWS_VISIBLE int libwebsockets_return_http_status( + struct libwebsocket_context *context, struct libwebsocket *wsi, + unsigned int code, const char *html_body) +{ + int n, m; + + unsigned char *p = context->service_buffer + LWS_SEND_BUFFER_PRE_PADDING; + unsigned char *start = p; + unsigned char *end = p + sizeof(context->service_buffer) - + LWS_SEND_BUFFER_PRE_PADDING; + + if (!html_body) + html_body = ""; + + if (lws_add_http_header_status(context, wsi, code, &p, end)) + return 1; + if (lws_add_http_header_by_token(context, wsi, WSI_TOKEN_HTTP_SERVER, (unsigned char *)"libwebsockets", 13, &p, end)) + return 1; + if (lws_add_http_header_by_token(context, wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)"text/html", 9, &p, end)) + return 1; + if (lws_finalize_http_header(context, wsi, &p, end)) + return 1; + + m = libwebsocket_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS); + if (m != (int)(p - start)) + return 1; + + n = sprintf((char *)start, "<html><body><h1>%u</h1>%s</body></html>", code, html_body); + m = libwebsocket_write(wsi, start, n, LWS_WRITE_HTTP); + + return m != n; +} + +/** + * libwebsockets_serve_http_file() - Send a file back to the client using http + * @context: libwebsockets context + * @wsi: Websocket instance (available from user callback) + * @file: The file to issue over http + * @content_type: The http content type, eg, text/html + * @other_headers: NULL or pointer to \0-terminated other header string + * + * This function is intended to be called from the callback in response + * to http requests from the client. It allows the callback to issue + * local files down the http link in a single step. + * + * Returning <0 indicates error and the wsi should be closed. Returning + * >0 indicates the file was completely sent and + * lws_http_transaction_completed() called on the wsi (and close if != 0) + * ==0 indicates the file transfer is started and needs more service later, + * the wsi should be left alone. + */ + +LWS_VISIBLE int libwebsockets_serve_http_file( + struct libwebsocket_context *context, + struct libwebsocket *wsi, const char *file, + const char *content_type, const char *other_headers, + int other_headers_len) +{ + unsigned char *response = context->service_buffer + LWS_SEND_BUFFER_PRE_PADDING; + unsigned char *p = response; + unsigned char *end = p + sizeof(context->service_buffer) - + LWS_SEND_BUFFER_PRE_PADDING; + int ret = 0; + + wsi->u.http.fd = lws_plat_open_file(file, &wsi->u.http.filelen); + + if (wsi->u.http.fd == LWS_INVALID_FILE) { + lwsl_err("Unable to open '%s'\n", file); + libwebsockets_return_http_status(context, wsi, + HTTP_STATUS_NOT_FOUND, NULL); + return -1; + } + + if (lws_add_http_header_status(context, wsi, 200, &p, end)) + return -1; + if (lws_add_http_header_by_token(context, wsi, WSI_TOKEN_HTTP_SERVER, (unsigned char *)"libwebsockets", 13, &p, end)) + return -1; + if (lws_add_http_header_by_token(context, wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)content_type, strlen(content_type), &p, end)) + return -1; + if (lws_add_http_header_content_length(context, wsi, wsi->u.http.filelen, &p, end)) + return -1; + + if (other_headers) { + if ((end - p) < other_headers_len) + return -1; + memcpy(p, other_headers, other_headers_len); + p += other_headers_len; + } + + if (lws_finalize_http_header(context, wsi, &p, end)) + return -1; + + ret = libwebsocket_write(wsi, response, + p - response, LWS_WRITE_HTTP_HEADERS); + if (ret != (p - response)) { + lwsl_err("_write returned %d from %d\n", ret, (p - response)); + return -1; + } + + wsi->u.http.filepos = 0; + wsi->state = WSI_STATE_HTTP_ISSUING_FILE; + + return libwebsockets_serve_http_file_fragment(context, wsi); +} + + +int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi, + unsigned char *buf, size_t len) +{ + size_t n = 0; + int m; + +#if 0 + lwsl_parser("received %d byte packet\n", (int)len); + lwsl_hexdump(buf, len); +#endif + + /* let the rx protocol state machine have as much as it needs */ + + while (n < len) { + /* + * we were accepting input but now we stopped doing so + */ + if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) { + lws_rxflow_cache(wsi, buf, n, len); + + return 1; + } + + /* account for what we're using in rxflow buffer */ + if (wsi->rxflow_buffer) + wsi->rxflow_pos++; + + /* process the byte */ + m = libwebsocket_rx_sm(wsi, buf[n++]); + if (m < 0) + return -1; + } + + return 0; +} + +LWS_VISIBLE void +lws_server_get_canonical_hostname(struct libwebsocket_context *context, + struct lws_context_creation_info *info) +{ + if (info->options & LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME) + return; + + /* find canonical hostname */ + gethostname((char *)context->canonical_hostname, + sizeof(context->canonical_hostname) - 1); + + lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname); +} diff --git a/src/engine/external/libwebsockets/service.c b/src/engine/external/libwebsockets/service.c new file mode 100644 index 0000000..f905a60 --- /dev/null +++ b/src/engine/external/libwebsockets/service.c @@ -0,0 +1,636 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "private-libwebsockets.h" + +static int +lws_calllback_as_writeable(struct libwebsocket_context *context, + struct libwebsocket *wsi) +{ + int n; + + switch (wsi->mode) { + case LWS_CONNMODE_WS_CLIENT: + n = LWS_CALLBACK_CLIENT_WRITEABLE; + break; + case LWS_CONNMODE_WS_SERVING: + n = LWS_CALLBACK_SERVER_WRITEABLE; + break; + default: + n = LWS_CALLBACK_HTTP_WRITEABLE; + break; + } + lwsl_info("%s: %p (user=%p)\n", __func__, wsi, wsi->user_space); + return user_callback_handle_rxflow(wsi->protocol->callback, context, + wsi, (enum libwebsocket_callback_reasons) n, + wsi->user_space, NULL, 0); +} + +int +lws_handle_POLLOUT_event(struct libwebsocket_context *context, + struct libwebsocket *wsi, struct libwebsocket_pollfd *pollfd) +{ + int n; + struct lws_tokens eff_buf; +#ifdef LWS_USE_HTTP2 + struct libwebsocket *wsi2; +#endif + int ret; + int m; + + /* pending truncated sends have uber priority */ + + if (wsi->truncated_send_len) { + if (lws_issue_raw(wsi, wsi->truncated_send_malloc + + wsi->truncated_send_offset, + wsi->truncated_send_len) < 0) { + lwsl_info("lws_handle_POLLOUT_event signalling to close\n"); + return -1; + } + /* leave POLLOUT active either way */ + return 0; + } else + if (wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) { + lwsl_info("***** %x signalling to close in POLLOUT handler\n", wsi); + return -1; /* retry closing now */ + } +#ifdef LWS_USE_HTTP2 + /* protocol packets are next */ + if (wsi->pps) { + lwsl_info("servicing pps %d\n", wsi->pps); + switch (wsi->pps) { + case LWS_PPS_HTTP2_MY_SETTINGS: + case LWS_PPS_HTTP2_ACK_SETTINGS: + lws_http2_do_pps_send(context, wsi); + break; + default: + break; + } + wsi->pps = LWS_PPS_NONE; + libwebsocket_rx_flow_control(wsi, 1); + + return 0; /* leave POLLOUT active */ + } +#endif + /* pending control packets have next priority */ + + if (wsi->state == WSI_STATE_ESTABLISHED && wsi->u.ws.ping_payload_len) { + n = libwebsocket_write(wsi, + &wsi->u.ws.ping_payload_buf[ + LWS_SEND_BUFFER_PRE_PADDING], + wsi->u.ws.ping_payload_len, + LWS_WRITE_PONG); + if (n < 0) + return -1; + /* well he is sent, mark him done */ + wsi->u.ws.ping_payload_len = 0; + /* leave POLLOUT active either way */ + return 0; + } + + /* if nothing critical, user can get the callback */ + + m = lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_IS_WRITEABLE, + NULL, 0); +#ifndef LWS_NO_EXTENSIONS + if (!wsi->extension_data_pending) + goto user_service; +#endif + /* + * check in on the active extensions, see if they + * had pending stuff to spill... they need to get the + * first look-in otherwise sequence will be disordered + * + * NULL, zero-length eff_buf means just spill pending + */ + + ret = 1; + while (ret == 1) { + + /* default to nobody has more to spill */ + + ret = 0; + eff_buf.token = NULL; + eff_buf.token_len = 0; + + /* give every extension a chance to spill */ + + m = lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PACKET_TX_PRESEND, + &eff_buf, 0); + if (m < 0) { + lwsl_err("ext reports fatal error\n"); + return -1; + } + if (m) + /* + * at least one extension told us he has more + * to spill, so we will go around again after + */ + ret = 1; + + /* assuming they gave us something to send, send it */ + + if (eff_buf.token_len) { + n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, + eff_buf.token_len); + if (n < 0) { + lwsl_info("closing from POLLOUT spill\n"); + return -1; + } + /* + * Keep amount spilled small to minimize chance of this + */ + if (n != eff_buf.token_len) { + lwsl_err("Unable to spill ext %d vs %s\n", + eff_buf.token_len, n); + return -1; + } + } else + continue; + + /* no extension has more to spill */ + + if (!ret) + continue; + + /* + * There's more to spill from an extension, but we just sent + * something... did that leave the pipe choked? + */ + + if (!lws_send_pipe_choked(wsi)) + /* no we could add more */ + continue; + + lwsl_info("choked in POLLOUT service\n"); + + /* + * Yes, he's choked. Leave the POLLOUT masked on so we will + * come back here when he is unchoked. Don't call the user + * callback to enforce ordering of spilling, he'll get called + * when we come back here and there's nothing more to spill. + */ + + return 0; + } +#ifndef LWS_NO_EXTENSIONS + wsi->extension_data_pending = 0; + +user_service: +#endif + /* one shot */ + + if (pollfd) { + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_info("failled at set pollfd\n"); + return 1; + } + + lws_libev_io(context, wsi, LWS_EV_STOP | LWS_EV_WRITE); + } + +#ifdef LWS_USE_HTTP2 + /* + * we are the 'network wsi' for potentially many muxed child wsi with + * no network connection of their own, who have to use us for all their + * network actions. So we use a round-robin scheme to share out the + * POLLOUT notifications to our children. + * + * But because any child could exhaust the socket's ability to take + * writes, we can only let one child get notified each time. + * + * In addition children may be closed / deleted / added between POLLOUT + * notifications, so we can't hold pointers + */ + + if (wsi->mode != LWS_CONNMODE_HTTP2_SERVING) { + lwsl_info("%s: non http2\n", __func__); + goto notify; + } + + wsi->u.http2.requested_POLLOUT = 0; + if (!wsi->u.http2.initialized) { + lwsl_info("pollout on uninitialized http2 conn\n"); + return 0; + } + + lwsl_info("%s: doing children\n", __func__); + + wsi2 = wsi; + do { + wsi2 = wsi2->u.http2.next_child_wsi; + lwsl_info("%s: child %p\n", __func__, wsi2); + if (!wsi2) + continue; + if (!wsi2->u.http2.requested_POLLOUT) + continue; + wsi2->u.http2.requested_POLLOUT = 0; + if (lws_calllback_as_writeable(context, wsi2)) { + lwsl_debug("Closing POLLOUT child\n"); + libwebsocket_close_and_free_session(context, wsi2, + LWS_CLOSE_STATUS_NOSTATUS); + } + wsi2 = wsi; + } while (wsi2 != NULL && !lws_send_pipe_choked(wsi)); + + lwsl_info("%s: completed\n", __func__); + + return 0; +notify: +#endif + return lws_calllback_as_writeable(context, wsi); +} + + + +int +libwebsocket_service_timeout_check(struct libwebsocket_context *context, + struct libwebsocket *wsi, unsigned int sec) +{ + /* + * if extensions want in on it (eg, we are a mux parent) + * give them a chance to service child timeouts + */ + if (lws_ext_callback_for_each_active(wsi, LWS_EXT_CALLBACK_1HZ, NULL, sec) < 0) + return 0; + + if (!wsi->pending_timeout) + return 0; + + /* + * if we went beyond the allowed time, kill the + * connection + */ + if (sec > wsi->pending_timeout_limit) { + lwsl_info("TIMEDOUT WAITING on %d\n", wsi->pending_timeout); + libwebsocket_close_and_free_session(context, + wsi, LWS_CLOSE_STATUS_NOSTATUS); + return 1; + } + + return 0; +} + +int lws_rxflow_cache(struct libwebsocket *wsi, unsigned char *buf, int n, int len) +{ + /* his RX is flowcontrolled, don't send remaining now */ + if (wsi->rxflow_buffer) { + /* rxflow while we were spilling prev rxflow */ + lwsl_info("stalling in existing rxflow buf\n"); + return 1; + } + + /* a new rxflow, buffer it and warn caller */ + lwsl_info("new rxflow input buffer len %d\n", len - n); + wsi->rxflow_buffer = lws_malloc(len - n); + wsi->rxflow_len = len - n; + wsi->rxflow_pos = 0; + memcpy(wsi->rxflow_buffer, buf + n, len - n); + + return 0; +} + +/** + * libwebsocket_service_fd() - Service polled socket with something waiting + * @context: Websocket context + * @pollfd: The pollfd entry describing the socket fd and which events + * happened. + * + * This function takes a pollfd that has POLLIN or POLLOUT activity and + * services it according to the state of the associated + * struct libwebsocket. + * + * The one call deals with all "service" that might happen on a socket + * including listen accepts, http files as well as websocket protocol. + * + * If a pollfd says it has something, you can just pass it to + * libwebsocket_serice_fd() whether it is a socket handled by lws or not. + * If it sees it is a lws socket, the traffic will be handled and + * pollfd->revents will be zeroed now. + * + * If the socket is foreign to lws, it leaves revents alone. So you can + * see if you should service yourself by checking the pollfd revents + * after letting lws try to service it. + */ + +LWS_VISIBLE int +libwebsocket_service_fd(struct libwebsocket_context *context, + struct libwebsocket_pollfd *pollfd) +{ + struct libwebsocket *wsi; + int n; + int m; + int listen_socket_fds_index = 0; + time_t now; + int timed_out = 0; + int our_fd = 0; + char draining_flow = 0; + int more; + struct lws_tokens eff_buf; + + if (context->listen_service_fd) + listen_socket_fds_index = context->lws_lookup[ + context->listen_service_fd]->position_in_fds_table; + + /* + * you can call us with pollfd = NULL to just allow the once-per-second + * global timeout checks; if less than a second since the last check + * it returns immediately then. + */ + + time(&now); + + /* TODO: if using libev, we should probably use timeout watchers... */ + if (context->last_timeout_check_s != now) { + context->last_timeout_check_s = now; + + lws_plat_service_periodic(context); + + /* global timeout check once per second */ + + if (pollfd) + our_fd = pollfd->fd; + + for (n = 0; n < context->fds_count; n++) { + m = context->fds[n].fd; + wsi = context->lws_lookup[m]; + if (!wsi) + continue; + + if (libwebsocket_service_timeout_check(context, wsi, now)) + /* he did time out... */ + if (m == our_fd) { + /* it was the guy we came to service! */ + timed_out = 1; + /* mark as handled */ + if (pollfd) + pollfd->revents = 0; + } + } + } + + /* the socket we came to service timed out, nothing to do */ + if (timed_out) + return 0; + + /* just here for timeout management? */ + if (pollfd == NULL) + return 0; + + /* no, here to service a socket descriptor */ + wsi = context->lws_lookup[pollfd->fd]; + if (wsi == NULL) + /* not lws connection ... leave revents alone and return */ + return 0; + + /* + * so that caller can tell we handled, past here we need to + * zero down pollfd->revents after handling + */ + + /* + * deal with listen service piggybacking + * every listen_service_modulo services of other fds, we + * sneak one in to service the listen socket if there's anything waiting + * + * To handle connection storms, as found in ab, if we previously saw a + * pending connection here, it causes us to check again next time. + */ + + if (context->listen_service_fd && pollfd != + &context->fds[listen_socket_fds_index]) { + context->listen_service_count++; + if (context->listen_service_extraseen || + context->listen_service_count == + context->listen_service_modulo) { + context->listen_service_count = 0; + m = 1; + if (context->listen_service_extraseen > 5) + m = 2; + while (m--) { + /* + * even with extpoll, we prepared this + * internal fds for listen + */ + n = lws_poll_listen_fd(&context->fds[listen_socket_fds_index]); + if (n > 0) { /* there's a conn waiting for us */ + libwebsocket_service_fd(context, + &context-> + fds[listen_socket_fds_index]); + context->listen_service_extraseen++; + } else { + if (context->listen_service_extraseen) + context-> + listen_service_extraseen--; + break; + } + } + } + + } + + /* handle session socket closed */ + + if ((!(pollfd->revents & LWS_POLLIN)) && + (pollfd->revents & LWS_POLLHUP)) { + + lwsl_debug("Session Socket %p (fd=%d) dead\n", + (void *)wsi, pollfd->fd); + + goto close_and_handled; + } + + /* okay, what we came here to do... */ + + switch (wsi->mode) { + case LWS_CONNMODE_HTTP_SERVING: + case LWS_CONNMODE_HTTP_SERVING_ACCEPTED: + case LWS_CONNMODE_SERVER_LISTENER: + case LWS_CONNMODE_SSL_ACK_PENDING: + n = lws_server_socket_service(context, wsi, pollfd); + if (n < 0) + goto close_and_handled; + goto handled; + + case LWS_CONNMODE_WS_SERVING: + case LWS_CONNMODE_WS_CLIENT: + case LWS_CONNMODE_HTTP2_SERVING: + + /* the guy requested a callback when it was OK to write */ + + if ((pollfd->revents & LWS_POLLOUT) && + (wsi->state == WSI_STATE_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED || wsi->state == WSI_STATE_HTTP2_ESTABLISHED_PRE_SETTINGS || + wsi->state == WSI_STATE_FLUSHING_STORED_SEND_BEFORE_CLOSE) && + lws_handle_POLLOUT_event(context, wsi, pollfd)) { + lwsl_info("libwebsocket_service_fd: closing\n"); + goto close_and_handled; + } + + if (wsi->rxflow_buffer && + (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) { + lwsl_info("draining rxflow\n"); + /* well, drain it */ + eff_buf.token = (char *)wsi->rxflow_buffer + + wsi->rxflow_pos; + eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos; + draining_flow = 1; + goto drain; + } + + /* any incoming data ready? */ + + if (!(pollfd->revents & LWS_POLLIN)) + break; + + eff_buf.token_len = lws_ssl_capable_read(context, wsi, + context->service_buffer, + sizeof(context->service_buffer)); + switch (eff_buf.token_len) { + case 0: + lwsl_info("service_fd: closing due to 0 length read\n"); + goto close_and_handled; + case LWS_SSL_CAPABLE_MORE_SERVICE: + lwsl_info("SSL Capable more service\n"); + n = 0; + goto handled; + case LWS_SSL_CAPABLE_ERROR: + lwsl_info("Closing when error\n"); + goto close_and_handled; + } + + /* + * give any active extensions a chance to munge the buffer + * before parse. We pass in a pointer to an lws_tokens struct + * prepared with the default buffer and content length that's in + * there. Rather than rewrite the default buffer, extensions + * that expect to grow the buffer can adapt .token to + * point to their own per-connection buffer in the extension + * user allocation. By default with no extensions or no + * extension callback handling, just the normal input buffer is + * used then so it is efficient. + */ + + eff_buf.token = (char *)context->service_buffer; +drain: + + do { + + more = 0; + + m = lws_ext_callback_for_each_active(wsi, + LWS_EXT_CALLBACK_PACKET_RX_PREPARSE, &eff_buf, 0); + if (m < 0) + goto close_and_handled; + if (m) + more = 1; + + /* service incoming data */ + + if (eff_buf.token_len) { + n = libwebsocket_read(context, wsi, + (unsigned char *)eff_buf.token, + eff_buf.token_len); + if (n < 0) { + /* we closed wsi */ + n = 0; + goto handled; + } + } + + eff_buf.token = NULL; + eff_buf.token_len = 0; + } while (more); + + if (draining_flow && wsi->rxflow_buffer && + wsi->rxflow_pos == wsi->rxflow_len) { + lwsl_info("flow buffer: drained\n"); + lws_free2(wsi->rxflow_buffer); + /* having drained the rxflow buffer, can rearm POLLIN */ +#ifdef LWS_NO_SERVER + n = +#endif + _libwebsocket_rx_flow_control(wsi); /* n ignored, needed for NO_SERVER case */ + } + + break; + + default: +#ifdef LWS_NO_CLIENT + break; +#else + n = lws_client_socket_service(context, wsi, pollfd); + goto handled; +#endif + } + + n = 0; + goto handled; + +close_and_handled: + lwsl_debug("Close and handled\n"); + libwebsocket_close_and_free_session(context, wsi, + LWS_CLOSE_STATUS_NOSTATUS); + n = 1; + +handled: + pollfd->revents = 0; + return n; +} + +/** + * libwebsocket_service() - Service any pending websocket activity + * @context: Websocket context + * @timeout_ms: Timeout for poll; 0 means return immediately if nothing needed + * service otherwise block and service immediately, returning + * after the timeout if nothing needed service. + * + * This function deals with any pending websocket traffic, for three + * kinds of event. It handles these events on both server and client + * types of connection the same. + * + * 1) Accept new connections to our context's server + * + * 2) Call the receive callback for incoming frame data received by + * server or client connections. + * + * You need to call this service function periodically to all the above + * functions to happen; if your application is single-threaded you can + * just call it in your main event loop. + * + * Alternatively you can fork a new process that asynchronously handles + * calling this service in a loop. In that case you are happy if this + * call blocks your thread until it needs to take care of something and + * would call it with a large nonzero timeout. Your loop then takes no + * CPU while there is nothing happening. + * + * If you are calling it in a single-threaded app, you don't want it to + * wait around blocking other things in your loop from happening, so you + * would call it with a timeout_ms of 0, so it returns immediately if + * nothing is pending, or as soon as it services whatever was pending. + */ + +LWS_VISIBLE int +libwebsocket_service(struct libwebsocket_context *context, int timeout_ms) +{ + return lws_plat_service(context, timeout_ms); +} + diff --git a/src/engine/external/libwebsockets/sha-1.c b/src/engine/external/libwebsockets/sha-1.c new file mode 100644 index 0000000..e68ee38 --- /dev/null +++ b/src/engine/external/libwebsockets/sha-1.c @@ -0,0 +1,301 @@ +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +/* + * FIPS pub 180-1: Secure Hash Algorithm (SHA-1) + * based on: http://csrc.nist.gov/fips/fip180-1.txt + * implemented by Jun-ichiro itojun Itoh <itojun@itojun.org> + */ + +#include "private-libwebsockets.h" + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +struct sha1_ctxt { + union { + unsigned char b8[20]; + unsigned int b32[5]; + } h; + union { + unsigned char b8[8]; + u_int64_t b64[1]; + } c; + union { + unsigned char b8[64]; + unsigned int b32[16]; + } m; + unsigned char count; +}; + +/* sanity check */ +#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN) || !defined(BIG_ENDIAN) +# define unsupported 1 +#elif BYTE_ORDER != BIG_ENDIAN +# if BYTE_ORDER != LITTLE_ENDIAN +# define unsupported 1 +# endif +#endif + +#ifndef unsupported + +/* constant table */ +static const unsigned int _K[] = + { 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 }; +#define K(t) _K[(t) / 20] + +#define F0(b, c, d) (((b) & (c)) | ((~(b)) & (d))) +#define F1(b, c, d) (((b) ^ (c)) ^ (d)) +#define F2(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d))) +#define F3(b, c, d) (((b) ^ (c)) ^ (d)) + +#define S(n, x) (((x) << (n)) | ((x) >> (32 - n))) + +#define H(n) (ctxt->h.b32[(n)]) +#define COUNT (ctxt->count) +#define BCOUNT (ctxt->c.b64[0] / 8) +#define W(n) (ctxt->m.b32[(n)]) + +#define PUTBYTE(x) { \ + ctxt->m.b8[(COUNT % 64)] = (x); \ + COUNT++; \ + COUNT %= 64; \ + ctxt->c.b64[0] += 8; \ + if (COUNT % 64 == 0) \ + sha1_step(ctxt); \ + } + +#define PUTPAD(x) { \ + ctxt->m.b8[(COUNT % 64)] = (x); \ + COUNT++; \ + COUNT %= 64; \ + if (COUNT % 64 == 0) \ + sha1_step(ctxt); \ + } + +static void sha1_step __P((struct sha1_ctxt *)); + +static void +sha1_step(struct sha1_ctxt *ctxt) +{ + unsigned int a, b, c, d, e, tmp; + size_t t, s; + +#if BYTE_ORDER == LITTLE_ENDIAN + struct sha1_ctxt tctxt; + + memcpy(&tctxt.m.b8[0], &ctxt->m.b8[0], 64); + ctxt->m.b8[0] = tctxt.m.b8[3]; ctxt->m.b8[1] = tctxt.m.b8[2]; + ctxt->m.b8[2] = tctxt.m.b8[1]; ctxt->m.b8[3] = tctxt.m.b8[0]; + ctxt->m.b8[4] = tctxt.m.b8[7]; ctxt->m.b8[5] = tctxt.m.b8[6]; + ctxt->m.b8[6] = tctxt.m.b8[5]; ctxt->m.b8[7] = tctxt.m.b8[4]; + ctxt->m.b8[8] = tctxt.m.b8[11]; ctxt->m.b8[9] = tctxt.m.b8[10]; + ctxt->m.b8[10] = tctxt.m.b8[9]; ctxt->m.b8[11] = tctxt.m.b8[8]; + ctxt->m.b8[12] = tctxt.m.b8[15]; ctxt->m.b8[13] = tctxt.m.b8[14]; + ctxt->m.b8[14] = tctxt.m.b8[13]; ctxt->m.b8[15] = tctxt.m.b8[12]; + ctxt->m.b8[16] = tctxt.m.b8[19]; ctxt->m.b8[17] = tctxt.m.b8[18]; + ctxt->m.b8[18] = tctxt.m.b8[17]; ctxt->m.b8[19] = tctxt.m.b8[16]; + ctxt->m.b8[20] = tctxt.m.b8[23]; ctxt->m.b8[21] = tctxt.m.b8[22]; + ctxt->m.b8[22] = tctxt.m.b8[21]; ctxt->m.b8[23] = tctxt.m.b8[20]; + ctxt->m.b8[24] = tctxt.m.b8[27]; ctxt->m.b8[25] = tctxt.m.b8[26]; + ctxt->m.b8[26] = tctxt.m.b8[25]; ctxt->m.b8[27] = tctxt.m.b8[24]; + ctxt->m.b8[28] = tctxt.m.b8[31]; ctxt->m.b8[29] = tctxt.m.b8[30]; + ctxt->m.b8[30] = tctxt.m.b8[29]; ctxt->m.b8[31] = tctxt.m.b8[28]; + ctxt->m.b8[32] = tctxt.m.b8[35]; ctxt->m.b8[33] = tctxt.m.b8[34]; + ctxt->m.b8[34] = tctxt.m.b8[33]; ctxt->m.b8[35] = tctxt.m.b8[32]; + ctxt->m.b8[36] = tctxt.m.b8[39]; ctxt->m.b8[37] = tctxt.m.b8[38]; + ctxt->m.b8[38] = tctxt.m.b8[37]; ctxt->m.b8[39] = tctxt.m.b8[36]; + ctxt->m.b8[40] = tctxt.m.b8[43]; ctxt->m.b8[41] = tctxt.m.b8[42]; + ctxt->m.b8[42] = tctxt.m.b8[41]; ctxt->m.b8[43] = tctxt.m.b8[40]; + ctxt->m.b8[44] = tctxt.m.b8[47]; ctxt->m.b8[45] = tctxt.m.b8[46]; + ctxt->m.b8[46] = tctxt.m.b8[45]; ctxt->m.b8[47] = tctxt.m.b8[44]; + ctxt->m.b8[48] = tctxt.m.b8[51]; ctxt->m.b8[49] = tctxt.m.b8[50]; + ctxt->m.b8[50] = tctxt.m.b8[49]; ctxt->m.b8[51] = tctxt.m.b8[48]; + ctxt->m.b8[52] = tctxt.m.b8[55]; ctxt->m.b8[53] = tctxt.m.b8[54]; + ctxt->m.b8[54] = tctxt.m.b8[53]; ctxt->m.b8[55] = tctxt.m.b8[52]; + ctxt->m.b8[56] = tctxt.m.b8[59]; ctxt->m.b8[57] = tctxt.m.b8[58]; + ctxt->m.b8[58] = tctxt.m.b8[57]; ctxt->m.b8[59] = tctxt.m.b8[56]; + ctxt->m.b8[60] = tctxt.m.b8[63]; ctxt->m.b8[61] = tctxt.m.b8[62]; + ctxt->m.b8[62] = tctxt.m.b8[61]; ctxt->m.b8[63] = tctxt.m.b8[60]; +#endif + + a = H(0); b = H(1); c = H(2); d = H(3); e = H(4); + + for (t = 0; t < 20; t++) { + s = t & 0x0f; + if (t >= 16) + W(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^ + W((s+2) & 0x0f) ^ W(s)); + + tmp = S(5, a) + F0(b, c, d) + e + W(s) + K(t); + e = d; d = c; c = S(30, b); b = a; a = tmp; + } + for (t = 20; t < 40; t++) { + s = t & 0x0f; + W(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^ + W((s+2) & 0x0f) ^ W(s)); + tmp = S(5, a) + F1(b, c, d) + e + W(s) + K(t); + e = d; d = c; c = S(30, b); b = a; a = tmp; + } + for (t = 40; t < 60; t++) { + s = t & 0x0f; + W(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^ + W((s+2) & 0x0f) ^ W(s)); + tmp = S(5, a) + F2(b, c, d) + e + W(s) + K(t); + e = d; d = c; c = S(30, b); b = a; a = tmp; + } + for (t = 60; t < 80; t++) { + s = t & 0x0f; + W(s) = S(1, W((s+13) & 0x0f) ^ W((s+8) & 0x0f) ^ + W((s+2) & 0x0f) ^ W(s)); + tmp = S(5, a) + F3(b, c, d) + e + W(s) + K(t); + e = d; d = c; c = S(30, b); b = a; a = tmp; + } + + H(0) = H(0) + a; + H(1) = H(1) + b; + H(2) = H(2) + c; + H(3) = H(3) + d; + H(4) = H(4) + e; + + bzero(&ctxt->m.b8[0], 64); +} + +/*------------------------------------------------------------*/ + +static void +sha1_init(struct sha1_ctxt *ctxt) +{ + bzero(ctxt, sizeof(struct sha1_ctxt)); + H(0) = 0x67452301; + H(1) = 0xefcdab89; + H(2) = 0x98badcfe; + H(3) = 0x10325476; + H(4) = 0xc3d2e1f0; +} + +void +sha1_pad(struct sha1_ctxt *ctxt) +{ + size_t padlen; /*pad length in bytes*/ + size_t padstart; + + PUTPAD(0x80); + + padstart = COUNT % 64; + padlen = 64 - padstart; + if (padlen < 8) { + bzero(&ctxt->m.b8[padstart], padlen); + COUNT += padlen; + COUNT %= 64; + sha1_step(ctxt); + padstart = COUNT % 64; /* should be 0 */ + padlen = 64 - padstart; /* should be 64 */ + } + bzero(&ctxt->m.b8[padstart], padlen - 8); + COUNT += (padlen - 8); + COUNT %= 64; +#if BYTE_ORDER == BIG_ENDIAN + PUTPAD(ctxt->c.b8[0]); PUTPAD(ctxt->c.b8[1]); + PUTPAD(ctxt->c.b8[2]); PUTPAD(ctxt->c.b8[3]); + PUTPAD(ctxt->c.b8[4]); PUTPAD(ctxt->c.b8[5]); + PUTPAD(ctxt->c.b8[6]); PUTPAD(ctxt->c.b8[7]); +#else + PUTPAD(ctxt->c.b8[7]); PUTPAD(ctxt->c.b8[6]); + PUTPAD(ctxt->c.b8[5]); PUTPAD(ctxt->c.b8[4]); + PUTPAD(ctxt->c.b8[3]); PUTPAD(ctxt->c.b8[2]); + PUTPAD(ctxt->c.b8[1]); PUTPAD(ctxt->c.b8[0]); +#endif +} + +void +sha1_loop(struct sha1_ctxt *ctxt, const unsigned char *input, size_t len) +{ + size_t gaplen; + size_t gapstart; + size_t off; + size_t copysiz; + + off = 0; + + while (off < len) { + gapstart = COUNT % 64; + gaplen = 64 - gapstart; + + copysiz = (gaplen < len - off) ? gaplen : len - off; + memcpy(&ctxt->m.b8[gapstart], &input[off], copysiz); + COUNT += copysiz; + COUNT %= 64; + ctxt->c.b64[0] += copysiz * 8; + if (COUNT % 64 == 0) + sha1_step(ctxt); + off += copysiz; + } +} + +void +sha1_result(struct sha1_ctxt *ctxt, void *digest0) +{ + unsigned char *digest; + + digest = (unsigned char *)digest0; + sha1_pad(ctxt); +#if BYTE_ORDER == BIG_ENDIAN + memcpy(digest, &ctxt->h.b8[0], 20); +#else + digest[0] = ctxt->h.b8[3]; digest[1] = ctxt->h.b8[2]; + digest[2] = ctxt->h.b8[1]; digest[3] = ctxt->h.b8[0]; + digest[4] = ctxt->h.b8[7]; digest[5] = ctxt->h.b8[6]; + digest[6] = ctxt->h.b8[5]; digest[7] = ctxt->h.b8[4]; + digest[8] = ctxt->h.b8[11]; digest[9] = ctxt->h.b8[10]; + digest[10] = ctxt->h.b8[9]; digest[11] = ctxt->h.b8[8]; + digest[12] = ctxt->h.b8[15]; digest[13] = ctxt->h.b8[14]; + digest[14] = ctxt->h.b8[13]; digest[15] = ctxt->h.b8[12]; + digest[16] = ctxt->h.b8[19]; digest[17] = ctxt->h.b8[18]; + digest[18] = ctxt->h.b8[17]; digest[19] = ctxt->h.b8[16]; +#endif +} + +/* + * This should look and work like the libcrypto implementation + */ + +LWS_VISIBLE unsigned char * +libwebsockets_SHA1(const unsigned char *d, size_t n, unsigned char *md) +{ + struct sha1_ctxt ctx; + + sha1_init(&ctx); + sha1_loop(&ctx, d, n); + sha1_result(&ctx, (void *)md); + + return md; +} + +#endif /*unsupported*/ diff --git a/src/engine/external/md5/md5.c b/src/engine/external/md5/md5.c new file mode 100644 index 0000000..c35d96c --- /dev/null +++ b/src/engine/external/md5/md5.c @@ -0,0 +1,381 @@ +/* + Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + L. Peter Deutsch + ghost@aladdin.com + + */ +/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */ +/* + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.c is L. Peter Deutsch + <ghost@aladdin.com>. Other authors are noted in the change history + that follows (in reverse chronological order): + + 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order + either statically or dynamically; added missing #include <string.h> + in library. + 2002-03-11 lpd Corrected argument list for main(), and added int return + type, in test program and T value program. + 2002-02-21 lpd Added missing #include <stdio.h> in test program. + 2000-07-03 lpd Patched to eliminate warnings about "constant is + unsigned in ANSI C, signed in traditional"; made test program + self-checking. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). + 1999-05-03 lpd Original version. + */ + +#include "md5.h" +#include <string.h> + +#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ +#ifdef ARCH_IS_BIG_ENDIAN +# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) +#else +# define BYTE_ORDER 0 +#endif + +#define T_MASK ((md5_word_t)~0) +#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) +#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) +#define T3 0x242070db +#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) +#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) +#define T6 0x4787c62a +#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) +#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) +#define T9 0x698098d8 +#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) +#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) +#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) +#define T13 0x6b901122 +#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) +#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) +#define T16 0x49b40821 +#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) +#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) +#define T19 0x265e5a51 +#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) +#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) +#define T22 0x02441453 +#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) +#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) +#define T25 0x21e1cde6 +#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) +#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) +#define T28 0x455a14ed +#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) +#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) +#define T31 0x676f02d9 +#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) +#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) +#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) +#define T35 0x6d9d6122 +#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) +#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) +#define T38 0x4bdecfa9 +#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) +#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) +#define T41 0x289b7ec6 +#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) +#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) +#define T44 0x04881d05 +#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) +#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) +#define T47 0x1fa27cf8 +#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) +#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) +#define T50 0x432aff97 +#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) +#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) +#define T53 0x655b59c3 +#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) +#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) +#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) +#define T57 0x6fa87e4f +#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) +#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) +#define T60 0x4e0811a1 +#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) +#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) +#define T63 0x2ad7d2bb +#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) + + +static void +md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) +{ + md5_word_t + a = pms->abcd[0], b = pms->abcd[1], + c = pms->abcd[2], d = pms->abcd[3]; + md5_word_t t; +#if BYTE_ORDER > 0 + /* Define storage only for big-endian CPUs. */ + md5_word_t X[16]; +#else + /* Define storage for little-endian or both types of CPUs. */ + md5_word_t xbuf[16]; + const md5_word_t *X; +#endif + + { +#if BYTE_ORDER == 0 + /* + * Determine dynamically whether this is a big-endian or + * little-endian machine, since we can use a more efficient + * algorithm on the latter. + */ + static const int w = 1; + + if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ +#endif +#if BYTE_ORDER <= 0 /* little-endian */ + { + /* + * On little-endian machines, we can process properly aligned + * data without copying it. + */ + if (!((data - (const md5_byte_t *)0) & 3)) { + /* data are properly aligned */ + X = (const md5_word_t *)data; + } else { + /* not aligned */ + memcpy(xbuf, data, 64); + X = xbuf; + } + } +#endif +#if BYTE_ORDER == 0 + else /* dynamic big-endian */ +#endif +#if BYTE_ORDER >= 0 /* big-endian */ + { + /* + * On big-endian machines, we must arrange the bytes in the + * right order. + */ + const md5_byte_t *xp = data; + int i; + +# if BYTE_ORDER == 0 + X = xbuf; /* (dynamic only) */ +# else +# define xbuf X /* (static only) */ +# endif + for (i = 0; i < 16; ++i, xp += 4) + xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); + } +#endif + } + +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + + /* Round 1. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ +#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + F(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 0, 7, T1); + SET(d, a, b, c, 1, 12, T2); + SET(c, d, a, b, 2, 17, T3); + SET(b, c, d, a, 3, 22, T4); + SET(a, b, c, d, 4, 7, T5); + SET(d, a, b, c, 5, 12, T6); + SET(c, d, a, b, 6, 17, T7); + SET(b, c, d, a, 7, 22, T8); + SET(a, b, c, d, 8, 7, T9); + SET(d, a, b, c, 9, 12, T10); + SET(c, d, a, b, 10, 17, T11); + SET(b, c, d, a, 11, 22, T12); + SET(a, b, c, d, 12, 7, T13); + SET(d, a, b, c, 13, 12, T14); + SET(c, d, a, b, 14, 17, T15); + SET(b, c, d, a, 15, 22, T16); +#undef SET + + /* Round 2. */ + /* Let [abcd k s i] denote the operation + a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ +#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + G(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 1, 5, T17); + SET(d, a, b, c, 6, 9, T18); + SET(c, d, a, b, 11, 14, T19); + SET(b, c, d, a, 0, 20, T20); + SET(a, b, c, d, 5, 5, T21); + SET(d, a, b, c, 10, 9, T22); + SET(c, d, a, b, 15, 14, T23); + SET(b, c, d, a, 4, 20, T24); + SET(a, b, c, d, 9, 5, T25); + SET(d, a, b, c, 14, 9, T26); + SET(c, d, a, b, 3, 14, T27); + SET(b, c, d, a, 8, 20, T28); + SET(a, b, c, d, 13, 5, T29); + SET(d, a, b, c, 2, 9, T30); + SET(c, d, a, b, 7, 14, T31); + SET(b, c, d, a, 12, 20, T32); +#undef SET + + /* Round 3. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + H(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 5, 4, T33); + SET(d, a, b, c, 8, 11, T34); + SET(c, d, a, b, 11, 16, T35); + SET(b, c, d, a, 14, 23, T36); + SET(a, b, c, d, 1, 4, T37); + SET(d, a, b, c, 4, 11, T38); + SET(c, d, a, b, 7, 16, T39); + SET(b, c, d, a, 10, 23, T40); + SET(a, b, c, d, 13, 4, T41); + SET(d, a, b, c, 0, 11, T42); + SET(c, d, a, b, 3, 16, T43); + SET(b, c, d, a, 6, 23, T44); + SET(a, b, c, d, 9, 4, T45); + SET(d, a, b, c, 12, 11, T46); + SET(c, d, a, b, 15, 16, T47); + SET(b, c, d, a, 2, 23, T48); +#undef SET + + /* Round 4. */ + /* Let [abcd k s t] denote the operation + a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ +#define I(x, y, z) ((y) ^ ((x) | ~(z))) +#define SET(a, b, c, d, k, s, Ti)\ + t = a + I(b,c,d) + X[k] + Ti;\ + a = ROTATE_LEFT(t, s) + b + /* Do the following 16 operations. */ + SET(a, b, c, d, 0, 6, T49); + SET(d, a, b, c, 7, 10, T50); + SET(c, d, a, b, 14, 15, T51); + SET(b, c, d, a, 5, 21, T52); + SET(a, b, c, d, 12, 6, T53); + SET(d, a, b, c, 3, 10, T54); + SET(c, d, a, b, 10, 15, T55); + SET(b, c, d, a, 1, 21, T56); + SET(a, b, c, d, 8, 6, T57); + SET(d, a, b, c, 15, 10, T58); + SET(c, d, a, b, 6, 15, T59); + SET(b, c, d, a, 13, 21, T60); + SET(a, b, c, d, 4, 6, T61); + SET(d, a, b, c, 11, 10, T62); + SET(c, d, a, b, 2, 15, T63); + SET(b, c, d, a, 9, 21, T64); +#undef SET + + /* Then perform the following additions. (That is increment each + of the four registers by the value it had before this block + was started.) */ + pms->abcd[0] += a; + pms->abcd[1] += b; + pms->abcd[2] += c; + pms->abcd[3] += d; +} + +void +md5_init(md5_state_t *pms) +{ + pms->count[0] = pms->count[1] = 0; + pms->abcd[0] = 0x67452301; + pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; + pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; + pms->abcd[3] = 0x10325476; +} + +void +md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) +{ + const md5_byte_t *p = data; + int left = nbytes; + int offset = (pms->count[0] >> 3) & 63; + md5_word_t nbits = (md5_word_t)(nbytes << 3); + + if (nbytes <= 0) + return; + + /* Update the message length. */ + pms->count[1] += nbytes >> 29; + pms->count[0] += nbits; + if (pms->count[0] < nbits) + pms->count[1]++; + + /* Process an initial partial block. */ + if (offset) { + int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); + + memcpy(pms->buf + offset, p, copy); + if (offset + copy < 64) + return; + p += copy; + left -= copy; + md5_process(pms, pms->buf); + } + + /* Process full blocks. */ + for (; left >= 64; p += 64, left -= 64) + md5_process(pms, p); + + /* Process a final partial block. */ + if (left) + memcpy(pms->buf, p, left); +} + +void +md5_finish(md5_state_t *pms, md5_byte_t digest[16]) +{ + static const md5_byte_t pad[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + md5_byte_t data[8]; + int i; + + /* Save the length before padding. */ + for (i = 0; i < 8; ++i) + data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); + /* Pad to 56 bytes mod 64. */ + md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); + /* Append the length. */ + md5_append(pms, data, 8); + for (i = 0; i < 16; ++i) + digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); +} diff --git a/src/engine/external/md5/md5.h b/src/engine/external/md5/md5.h new file mode 100644 index 0000000..698c995 --- /dev/null +++ b/src/engine/external/md5/md5.h @@ -0,0 +1,91 @@ +/* + Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + L. Peter Deutsch + ghost@aladdin.com + + */ +/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */ +/* + Independent implementation of MD5 (RFC 1321). + + This code implements the MD5 Algorithm defined in RFC 1321, whose + text is available at + http://www.ietf.org/rfc/rfc1321.txt + The code is derived from the text of the RFC, including the test suite + (section A.5) but excluding the rest of Appendix A. It does not include + any code or documentation that is identified in the RFC as being + copyrighted. + + The original and principal author of md5.h is L. Peter Deutsch + <ghost@aladdin.com>. Other authors are noted in the change history + that follows (in reverse chronological order): + + 2002-04-13 lpd Removed support for non-ANSI compilers; removed + references to Ghostscript; clarified derivation from RFC 1321; + now handles byte order either statically or dynamically. + 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. + 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); + added conditionalization for C++ compilation from Martin + Purschke <purschke@bnl.gov>. + 1999-05-03 lpd Original version. + */ + +#ifndef md5_INCLUDED +# define md5_INCLUDED + +/* + * This package supports both compile-time and run-time determination of CPU + * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be + * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is + * defined as non-zero, the code will be compiled to run only on big-endian + * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to + * run on either big- or little-endian CPUs, but will run slightly less + * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. + */ + +typedef unsigned char md5_byte_t; /* 8-bit byte */ +typedef unsigned int md5_word_t; /* 32-bit word */ + +/* Define the state of the MD5 Algorithm. */ +typedef struct md5_state_s { + md5_word_t count[2]; /* message length in bits, lsw first */ + md5_word_t abcd[4]; /* digest buffer */ + md5_byte_t buf[64]; /* accumulate block */ +} md5_state_t; + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Initialize the algorithm. */ +void md5_init(md5_state_t *pms); + +/* Append a string to the message. */ +void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); + +/* Finish the message and return the digest. */ +void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); + +#ifdef __cplusplus +} /* end extern "C" */ +#endif + +#endif /* md5_INCLUDED */ diff --git a/src/engine/external/pnglite/VERSION b/src/engine/external/pnglite/VERSION new file mode 100644 index 0000000..44a7df2 --- /dev/null +++ b/src/engine/external/pnglite/VERSION @@ -0,0 +1 @@ +0.1.17 \ No newline at end of file diff --git a/src/engine/external/pnglite/pnglite.c b/src/engine/external/pnglite/pnglite.c new file mode 100644 index 0000000..3de4a8d --- /dev/null +++ b/src/engine/external/pnglite/pnglite.c @@ -0,0 +1,877 @@ +/* pnglite.c - pnglite library + For conditions of distribution and use, see copyright notice in pnglite.h +*/ +#define DO_CRC_CHECKS 1 +#define USE_ZLIB 1 + +#if USE_ZLIB +#include <zlib.h> +#else +#include "zlite.h" +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "pnglite.h" + + + +static png_alloc_t png_alloc; +static png_free_t png_free; + +static size_t file_read(png_t* png, void* out, size_t size, size_t numel) +{ + size_t result; + if(png->read_fun) + { + result = png->read_fun(out, size, numel, png->user_pointer); + } + else + { + if(!out) + { + result = fseek(png->user_pointer, (long)(size*numel), SEEK_CUR); + } + else + { + result = fread(out, size, numel, png->user_pointer); + } + } + + return result; +} + +static size_t file_write(png_t* png, void* p, size_t size, size_t numel) +{ + size_t result; + + if(png->write_fun) + { + result = png->write_fun(p, size, numel, png->user_pointer); + } + else + { + result = fwrite(p, size, numel, png->user_pointer); + } + + return result; +} + +static int file_read_ul(png_t* png, unsigned *out) +{ + unsigned char buf[4]; + + if(file_read(png, buf, 1, 4) != 4) + return PNG_FILE_ERROR; + + *out = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; + + return PNG_NO_ERROR; +} + +static int file_write_ul(png_t* png, unsigned in) +{ + unsigned char buf[4]; + + buf[0] = (in>>24) & 0xff; + buf[1] = (in>>16) & 0xff; + buf[2] = (in>>8) & 0xff; + buf[3] = (in) & 0xff; + + if(file_write(png, buf, 1, 4) != 4) + return PNG_FILE_ERROR; + + return PNG_NO_ERROR; +} + + +static unsigned get_ul(unsigned char* buf) +{ + unsigned result; + unsigned char foo[4]; + + memcpy(foo, buf, 4); + + result = (foo[0]<<24) | (foo[1]<<16) | (foo[2]<<8) | foo[3]; + + return result; +} + +static unsigned set_ul(unsigned char* buf, unsigned in) +{ + buf[0] = (in>>24) & 0xff; + buf[1] = (in>>16) & 0xff; + buf[2] = (in>>8) & 0xff; + buf[3] = (in) & 0xff; + + return PNG_NO_ERROR; +} + +int png_init(png_alloc_t pngalloc, png_free_t pngfree) +{ + if(pngalloc) + png_alloc = pngalloc; + else + png_alloc = (png_alloc_t)&malloc; + + if(pngfree) + png_free = pngfree; + else + png_free = &free; + + return PNG_NO_ERROR; +} + +static int png_get_bpp(png_t* png) +{ + int bpp; + + switch(png->color_type) + { + case PNG_GREYSCALE: + bpp = 1; break; + case PNG_TRUECOLOR: + bpp = 3; break; + case PNG_INDEXED: + bpp = 1; break; + case PNG_GREYSCALE_ALPHA: + bpp = 2; break; + case PNG_TRUECOLOR_ALPHA: + bpp = 4; break; + default: + return PNG_FILE_ERROR; + } + + bpp *= png->depth/8; + + return bpp; +} + +static int png_read_ihdr(png_t* png) +{ + unsigned length; +#if DO_CRC_CHECKS + unsigned orig_crc; + unsigned calc_crc; +#endif + unsigned char ihdr[13+4]; /* length should be 13, make room for type (IHDR) */ + + file_read_ul(png, &length); + + if(length != 13) + { + printf("%d\n", length); + return PNG_CRC_ERROR; + } + + if(file_read(png, ihdr, 1, 13+4) != 13+4) + return PNG_EOF_ERROR; +#if DO_CRC_CHECKS + file_read_ul(png, &orig_crc); + + calc_crc = crc32(0L, 0, 0); + calc_crc = crc32(calc_crc, ihdr, 13+4); + + if(orig_crc != calc_crc) + return PNG_CRC_ERROR; +#else + file_read_ul(png); +#endif + + png->width = get_ul(ihdr+4); + png->height = get_ul(ihdr+8); + png->depth = ihdr[12]; + png->color_type = ihdr[13]; + png->compression_method = ihdr[14]; + png->filter_method = ihdr[15]; + png->interlace_method = ihdr[16]; + + if(png->color_type == PNG_INDEXED) + return PNG_NOT_SUPPORTED; + + if(png->depth != 8 && png->depth != 16) + return PNG_NOT_SUPPORTED; + + if(png->interlace_method) + return PNG_NOT_SUPPORTED; + + return PNG_NO_ERROR; +} + +static int png_write_ihdr(png_t* png) +{ + unsigned char ihdr[13+4]; + unsigned char *p = ihdr; + unsigned crc; + + file_write(png, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 1, 8); + + file_write_ul(png, 13); + + *p = 'I'; p++; + *p = 'H'; p++; + *p = 'D'; p++; + *p = 'R'; p++; + set_ul(p, png->width); p+=4; + set_ul(p, png->height); p+=4; + *p = png->depth; p++; + *p = png->color_type; p++; + *p = 0; p++; + *p = 0; p++; + *p = 0; p++; + + file_write(png, ihdr, 1, 13+4); + + crc = crc32(0L, 0, 0); + crc = crc32(crc, ihdr, 13+4); + + file_write_ul(png, crc); + + return PNG_NO_ERROR; +} + +void png_print_info(png_t* png) +{ + printf("PNG INFO:\n"); + printf("\twidth:\t\t%d\n", png->width); + printf("\theight:\t\t%d\n", png->height); + printf("\tdepth:\t\t%d\n", png->depth); + printf("\tcolor:\t\t"); + + switch(png->color_type) + { + case PNG_GREYSCALE: printf("greyscale\n"); break; + case PNG_TRUECOLOR: printf("truecolor\n"); break; + case PNG_INDEXED: printf("palette\n"); break; + case PNG_GREYSCALE_ALPHA: printf("greyscale with alpha\n"); break; + case PNG_TRUECOLOR_ALPHA: printf("truecolor with alpha\n"); break; + default: printf("unknown, this is not good\n"); break; + } + + printf("\tcompression:\t%s\n", png->compression_method?"unknown, this is not good":"inflate/deflate"); + printf("\tfilter:\t\t%s\n", png->filter_method?"unknown, this is not good":"adaptive"); + printf("\tinterlace:\t%s\n", png->interlace_method?"interlace":"no interlace"); +} + +int png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer) +{ + char header[8]; + int result; + + png->read_fun = read_fun; + png->write_fun = 0; + png->user_pointer = user_pointer; + + if(!read_fun && !user_pointer) + return PNG_WRONG_ARGUMENTS; + + if(file_read(png, header, 1, 8) != 8) + return PNG_EOF_ERROR; + + if(memcmp(header, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8) != 0) + return PNG_HEADER_ERROR; + + result = png_read_ihdr(png); + + png->bpp = (unsigned char)png_get_bpp(png); + + return result; +} + +int png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer) +{ + png->write_fun = write_fun; + png->read_fun = 0; + png->user_pointer = user_pointer; + + if(!write_fun && !user_pointer) + return PNG_WRONG_ARGUMENTS; + + return PNG_NO_ERROR; +} + +int png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer) +{ + return png_open_read(png, read_fun, user_pointer); +} + +int png_open_file_read(png_t *png, const char* filename) +{ + FILE* fp = fopen(filename, "rb"); + + if(!fp) + return PNG_FILE_ERROR; + + return png_open_read(png, 0, fp); +} + +int png_open_file_write(png_t *png, const char* filename) +{ + FILE* fp = fopen(filename, "wb"); + + if(!fp) + return PNG_FILE_ERROR; + + return png_open_write(png, 0, fp); +} + +int png_open_file(png_t *png, const char* filename) +{ + return png_open_file_read(png, filename); +} + +int png_close_file(png_t* png) +{ + fclose(png->user_pointer); + + return PNG_NO_ERROR; +} + +static int png_init_deflate(png_t* png, unsigned char* data, int datalen) +{ + z_stream *stream; + png->zs = png_alloc(sizeof(z_stream)); + + stream = png->zs; + + if(!stream) + return PNG_MEMORY_ERROR; + + memset(stream, 0, sizeof(z_stream)); + + if(deflateInit(stream, Z_DEFAULT_COMPRESSION) != Z_OK) + return PNG_ZLIB_ERROR; + + stream->next_in = data; + stream->avail_in = datalen; + + return PNG_NO_ERROR; +} + +static int png_init_inflate(png_t* png) +{ +#if USE_ZLIB + z_stream *stream; + png->zs = png_alloc(sizeof(z_stream)); +#else + zl_stream *stream; + png->zs = png_alloc(sizeof(zl_stream)); +#endif + + stream = png->zs; + + if(!stream) + return PNG_MEMORY_ERROR; + + + +#if USE_ZLIB + memset(stream, 0, sizeof(z_stream)); + if(inflateInit(stream) != Z_OK) + return PNG_ZLIB_ERROR; +#else + memset(stream, 0, sizeof(zl_stream)); + if(z_inflateInit(stream) != Z_OK) + return PNG_ZLIB_ERROR; +#endif + + stream->next_out = png->png_data; + stream->avail_out = png->png_datalen; + + return PNG_NO_ERROR; +} + +static int png_end_deflate(png_t* png) +{ + z_stream *stream = png->zs; + + if(!stream) + return PNG_MEMORY_ERROR; + + deflateEnd(stream); + + png_free(png->zs); + + return PNG_NO_ERROR; +} + +static int png_end_inflate(png_t* png) +{ +#if USE_ZLIB + z_stream *stream = png->zs; +#else + zl_stream *stream = png->zs; +#endif + + if(!stream) + return PNG_MEMORY_ERROR; + +#if USE_ZLIB + if(inflateEnd(stream) != Z_OK) +#else + if(z_inflateEnd(stream) != Z_OK) +#endif + { + printf("ZLIB says: %s\n", stream->msg); + return PNG_ZLIB_ERROR; + } + + png_free(png->zs); + + return PNG_NO_ERROR; +} + +static int png_inflate(png_t* png, char* data, int len) +{ + int result; +#if USE_ZLIB + z_stream *stream = png->zs; +#else + zl_stream *stream = png->zs; +#endif + + if(!stream) + return PNG_MEMORY_ERROR; + + stream->next_in = (unsigned char*)data; + stream->avail_in = len; + +#if USE_ZLIB + result = inflate(stream, Z_SYNC_FLUSH); +#else + result = z_inflate(stream); +#endif + + if(result != Z_STREAM_END && result != Z_OK) + { + printf("%s\n", stream->msg); + return PNG_ZLIB_ERROR; + } + + if(stream->avail_in != 0) + return PNG_ZLIB_ERROR; + + return PNG_NO_ERROR; +} + +static int png_deflate(png_t* png, char* outdata, int outlen, int *outwritten) +{ + int result; + + z_stream *stream = png->zs; + + + if(!stream) + return PNG_MEMORY_ERROR; + + stream->next_out = (unsigned char*)outdata; + stream->avail_out = outlen; + + result = deflate(stream, Z_SYNC_FLUSH); + + *outwritten = outlen - stream->avail_out; + + if(result != Z_STREAM_END && result != Z_OK) + { + printf("%s\n", stream->msg); + return PNG_ZLIB_ERROR; + } + + return result; +} + +static int png_write_idats(png_t* png, unsigned char* data) +{ + unsigned char *chunk; + unsigned long written; + unsigned long crc; + unsigned size = png->width * png->height * png->bpp + png->height; + + (void)png_init_deflate; + (void)png_end_deflate; + (void)png_deflate; + + chunk = png_alloc(size+8); + memcpy(chunk, "IDAT", 4); + + written = size; + compress(chunk+4, &written, data, size); + + crc = crc32(0L, Z_NULL, 0); + crc = crc32(crc, chunk, written+4); + set_ul(chunk+written+4, crc); + file_write_ul(png, written); + file_write(png, chunk, 1, written+8); + png_free(chunk); + + file_write_ul(png, 0); + file_write(png, "IEND", 1, 4); + crc = crc32(0L, (const unsigned char *)"IEND", 4); + file_write_ul(png, crc); + + return PNG_NO_ERROR; +} + +static int png_read_idat(png_t* png, unsigned firstlen) +{ + unsigned type = 0; + char *chunk; + int result; + unsigned length = firstlen; + unsigned old_len = length; + +#if DO_CRC_CHECKS + unsigned orig_crc; + unsigned calc_crc; +#endif + + chunk = png_alloc(firstlen); + + result = png_init_inflate(png); + + if(result != PNG_NO_ERROR) + { + png_end_inflate(png); + png_free(chunk); + return result; + } + + do + { + if(file_read(png, chunk, 1, length) != length) + { + png_end_inflate(png); + png_free(chunk); + return PNG_FILE_ERROR; + } + +#if DO_CRC_CHECKS + calc_crc = crc32(0L, Z_NULL, 0); + calc_crc = crc32(calc_crc, (unsigned char*)"IDAT", 4); + calc_crc = crc32(calc_crc, (unsigned char*)chunk, length); + + file_read_ul(png, &orig_crc); + + if(orig_crc != calc_crc) + { + result = PNG_CRC_ERROR; + break; + } +#else + file_read_ul(png); +#endif + + result = png_inflate(png, chunk, length); + + if(result != PNG_NO_ERROR) break; + + file_read_ul(png, &length); + + if(length > old_len) + { + png_free(chunk); + chunk = png_alloc(length); + old_len = length; + } + + if(file_read(png, &type, 1, 4) != 4) + { + result = PNG_FILE_ERROR; + break; + } + + }while(type == *(unsigned int*)"IDAT"); + + if(type == *(unsigned int*)"IEND") + result = PNG_DONE; + + png_free(chunk); + png_end_inflate(png); + + return result; +} + +static int png_process_chunk(png_t* png) +{ + int result = PNG_NO_ERROR; + unsigned type; + unsigned length; + + file_read_ul(png, &length); + + if(file_read(png, &type, 1, 4) != 4) + return PNG_FILE_ERROR; + + if(type == *(unsigned int*)"IDAT") /* if we found an idat, all other idats should be followed with no other chunks in between */ + { + png->png_datalen = png->width * png->height * png->bpp + png->height; + png->png_data = png_alloc(png->png_datalen); + + if(!png->png_data) + return PNG_MEMORY_ERROR; + + return png_read_idat(png, length); + } + else if(type == *(unsigned int*)"IEND") + { + return PNG_DONE; + } + else + { + file_read(png, 0, 1, length + 4); /* unknown chunk */ + } + + return result; +} + +static void png_filter_sub(int stride, unsigned char* in, unsigned char* out, int len) +{ + int i; + unsigned char a = 0; + + for(i = 0; i < len; i++) + { + if(i >= stride) + a = out[i - stride]; + + out[i] = in[i] + a; + } +} + +static void png_filter_up(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) +{ + int i; + + if(prev_line) + { + for(i = 0; i < len; i++) + out[i] = in[i] + prev_line[i]; + } + else + memcpy(out, in, len); +} + +static void png_filter_average(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) +{ + int i; + unsigned char a = 0; + unsigned char b = 0; + unsigned int sum = 0; + + for(i = 0; i < len; i++) + { + if(prev_line) + b = prev_line[i]; + + if(i >= stride) + a = out[i - stride]; + + sum = a; + sum += b; + + out[i] = (char)(in[i] + sum/2); + } +} + +static unsigned char png_paeth(unsigned char a, unsigned char b, unsigned char c) +{ + int p = (int)a + b - c; + int pa = abs(p - a); + int pb = abs(p - b); + int pc = abs(p - c); + + int pr; + + if(pa <= pb && pa <= pc) + pr = a; + else if(pb <= pc) + pr = b; + else + pr = c; + + return (char)pr; +} + +static void png_filter_paeth(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) +{ + int i; + unsigned char a; + unsigned char b; + unsigned char c; + + for(i = 0; i < len; i++) + { + if(prev_line && i >= stride) + { + a = out[i - stride]; + b = prev_line[i]; + c = prev_line[i - stride]; + } + else + { + if(prev_line) + b = prev_line[i]; + else + b = 0; + + if(i >= stride) + a = out[i - stride]; + else + a = 0; + + c = 0; + } + + out[i] = in[i] + png_paeth(a, b, c); + } +} + +static int png_filter(png_t* png, unsigned char* data) +{ + + + return PNG_NO_ERROR; +} + +static int png_unfilter(png_t* png, unsigned char* data) +{ + unsigned i; + unsigned pos = 0; + unsigned outpos = 0; + unsigned char *filtered = png->png_data; + + int stride = png->bpp; + + while(pos < png->png_datalen) + { + unsigned char filter = filtered[pos]; + + pos++; + + if(png->depth == 16) + { + for(i = 0; i < png->width * stride; i+=2) + { + *(short*)(filtered+pos+i) = (filtered[pos+i] << 8) | filtered[pos+i+1]; + } + } + + switch(filter) + { + case 0: /* none */ + memcpy(data+outpos, filtered+pos, png->width * stride); + break; + case 1: /* sub */ + png_filter_sub(stride, filtered+pos, data+outpos, png->width * stride); + break; + case 2: /* up */ + if(outpos) + png_filter_up(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); + else + png_filter_up(stride, filtered+pos, data+outpos, 0, png->width*stride); + break; + case 3: /* average */ + if(outpos) + png_filter_average(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); + else + png_filter_average(stride, filtered+pos, data+outpos, 0, png->width*stride); + break; + case 4: /* paeth */ + if(outpos) + png_filter_paeth(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); + else + png_filter_paeth(stride, filtered+pos, data+outpos, 0, png->width*stride); + break; + default: + return PNG_UNKNOWN_FILTER; + } + + outpos += png->width * stride; + pos += png->width * stride; + } + + return PNG_NO_ERROR; +} + +int png_get_data(png_t* png, unsigned char* data) +{ + int result = PNG_NO_ERROR; + + while(result == PNG_NO_ERROR) + { + result = png_process_chunk(png); + } + + if(result != PNG_DONE) + { + png_free(png->png_data); + return result; + } + + result = png_unfilter(png, data); + + png_free(png->png_data); + + return result; +} + +int png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data) +{ + int i; + unsigned char *filtered; + png->width = width; + png->height = height; + png->depth = depth; + png->color_type = color; + png->bpp = png_get_bpp(png); + + filtered = png_alloc(width * height * png->bpp + height); + + for(i = 0; i < png->height; i++) + { + filtered[i*png->width*png->bpp+i] = 0; + memcpy(&filtered[i*png->width*png->bpp+i+1], data + i * png->width*png->bpp, png->width*png->bpp); + } + + png_filter(png, filtered); + png_write_ihdr(png); + png_write_idats(png, filtered); + + png_free(filtered); + return PNG_NO_ERROR; +} + + +char* png_error_string(int error) +{ + switch(error) + { + case PNG_NO_ERROR: + return "No error"; + case PNG_FILE_ERROR: + return "Unknown file error."; + case PNG_HEADER_ERROR: + return "No PNG header found. Are you sure this is a PNG?"; + case PNG_IO_ERROR: + return "Failure while reading file."; + case PNG_EOF_ERROR: + return "Reached end of file."; + case PNG_CRC_ERROR: + return "CRC or chunk length error."; + case PNG_MEMORY_ERROR: + return "Could not allocate memory."; + case PNG_ZLIB_ERROR: + return "zlib reported an error."; + case PNG_UNKNOWN_FILTER: + return "Unknown filter method used in scanline."; + case PNG_DONE: + return "PNG done"; + case PNG_NOT_SUPPORTED: + return "The PNG is unsupported by pnglite, too bad for you!"; + case PNG_WRONG_ARGUMENTS: + return "Wrong combination of arguments passed to png_open. You must use either a read_function or supply a file pointer to use."; + default: + return "Unknown error."; + }; +} diff --git a/src/engine/external/pnglite/pnglite.h b/src/engine/external/pnglite/pnglite.h new file mode 100644 index 0000000..578d369 --- /dev/null +++ b/src/engine/external/pnglite/pnglite.h @@ -0,0 +1,227 @@ +/* pnglite.h - Interface for pnglite library + Copyright (c) 2007 Daniel Karling + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. + + Daniel Karling + daniel.karling@gmail.com + */ + + +#ifndef _PNGLITE_H_ +#define _PNGLITE_H_ + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + Enumerations for pnglite. + Negative numbers are error codes and 0 and up are okay responses. +*/ + +enum +{ + PNG_DONE = 1, + PNG_NO_ERROR = 0, + PNG_FILE_ERROR = -1, + PNG_HEADER_ERROR = -2, + PNG_IO_ERROR = -3, + PNG_EOF_ERROR = -4, + PNG_CRC_ERROR = -5, + PNG_MEMORY_ERROR = -6, + PNG_ZLIB_ERROR = -7, + PNG_UNKNOWN_FILTER = -8, + PNG_NOT_SUPPORTED = -9, + PNG_WRONG_ARGUMENTS = -10 +}; + +/* + The five different kinds of color storage in PNG files. +*/ + +enum +{ + PNG_GREYSCALE = 0, + PNG_TRUECOLOR = 2, + PNG_INDEXED = 3, + PNG_GREYSCALE_ALPHA = 4, + PNG_TRUECOLOR_ALPHA = 6 +}; + +/* + Typedefs for callbacks. +*/ + +typedef unsigned (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer); +typedef unsigned (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer); +typedef void (*png_free_t)(void* p); +typedef void * (*png_alloc_t)(unsigned long s); + +typedef struct +{ + void* zs; /* pointer to z_stream */ + png_read_callback_t read_fun; + png_write_callback_t write_fun; + void* user_pointer; + + unsigned char* png_data; + unsigned png_datalen; + + unsigned width; + unsigned height; + unsigned char depth; + unsigned char color_type; + unsigned char compression_method; + unsigned char filter_method; + unsigned char interlace_method; + unsigned char bpp; +}png_t; + +/* + Function: png_init + + This function initializes pnglite. The parameters can be used to set your own memory allocation routines following these formats: + + > void* (*custom_alloc)(unsigned long s) + > void (*custom_free)(void* p) + Parameters: + pngalloc - Pointer to custom allocation routine. If 0 is passed, malloc from libc will be used. + pngfree - Pointer to custom free routine. If 0 is passed, free from libc will be used. + + Returns: + Always returns PNG_NO_ERROR. +*/ + +int png_init(png_alloc_t pngalloc, png_free_t pngfree); + +/* + Function: png_open_file + + This function is used to open a png file with the internal file IO system. This function should be used instead of + png_open if no custom read function is used. + + Parameters: + png - Empty png_t struct. + filename - Filename of the file to be opened. + + Returns: + PNG_NO_ERROR on success, otherwise an error code. +*/ + +int png_open_file(png_t *png, const char* filename); + +int png_open_file_read(png_t *png, const char* filename); +int png_open_file_write(png_t *png, const char* filename); + +/* + Function: png_open + + This function reads or writes a png from/to the specified callback. The callbacks should be of the format: + + > unsigned long (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer); + > unsigned long (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer). + + Only one callback has to be specified. The read callback in case of PNG reading, otherwise the write callback. + + Writing: + The callback will be called like fwrite. + + Reading: + The callback will be called each time pnglite needs more data. The callback should read as much data as requested, + or return 0. This should always be possible if the PNG is sane. If the output-buffer is a null-pointer the callback + should only skip ahead the specified number of elements. If the callback is a null-pointer the user_pointer will be + treated as a file pointer (use png_open_file instead). + + Parameters: + png - png_t struct + read_fun - Callback function for reading. + user_pointer - User pointer to be passed to read_fun. + + Returns: + PNG_NO_ERROR on success, otherwise an error code. +*/ + +int png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer); + +int png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer); +int png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer); + +/* + Function: png_print_info + + This function prints some info about the opened png file to stdout. + + Parameters: + png - png struct to get info from. +*/ + +void png_print_info(png_t* png); + +/* + Function: png_error_string + + This function translates an error code to a human readable string. + + Parameters: + error - Error code. + + Returns: + Pointer to string. +*/ + +char* png_error_string(int error); + +/* + Function: png_get_data + + This function decodes the opened png file and stores the result in data. data should be big enough to hold the decoded png. Required size will be: + + > width*height*(bytes per pixel) + + Parameters: + data - Where to store result. + + Returns: + PNG_NO_ERROR on success, otherwise an error code. +*/ + +int png_get_data(png_t* png, unsigned char* data); + +int png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data); + +/* + Function: png_close_file + + Closes an open png file pointer. Should only be used when the png has been opened with png_open_file. + + Parameters: + png - png to close. + + Returns: + PNG_NO_ERROR +*/ + +int png_close_file(png_t* png); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/engine/external/wavpack/VERSION b/src/engine/external/wavpack/VERSION new file mode 100644 index 0000000..4e21c89 --- /dev/null +++ b/src/engine/external/wavpack/VERSION @@ -0,0 +1 @@ +4.40 \ No newline at end of file diff --git a/src/engine/external/wavpack/arm.S b/src/engine/external/wavpack/arm.S new file mode 100644 index 0000000..4f29989 --- /dev/null +++ b/src/engine/external/wavpack/arm.S @@ -0,0 +1,461 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +/* This is an assembly optimized version of the following WavPack function: + * + * void decorr_stereo_pass_cont (struct decorr_pass *dpp, + * long *buffer, long sample_count); + * + * It performs a single pass of stereo decorrelation on the provided buffer. + * Note that this version of the function requires that the 8 previous stereo + * samples are visible and correct. In other words, it ignores the "samples_*" + * fields in the decorr_pass structure and gets the history data directly + * from the buffer. It does, however, return the appropriate history samples + * to the decorr_pass structure before returning. + * + * This is written to work on a ARM7TDMI processor. This version only uses the + * 32-bit multiply-accumulate instruction and so will overflow with 24-bit + * WavPack files. + */ + .text + .align + .global decorr_stereo_pass_cont_arm + +/* + * on entry: + * + * r0 = struct decorr_pass *dpp + * r1 = long *buffer + * r2 = long sample_count + */ + +decorr_stereo_pass_cont_arm: + + stmfd sp!, {r4 - r8, r10, r11, lr} + mov r5, r0 @ r5 = dpp + mov r11, #512 @ r11 = 512 for rounding + ldrsh r6, [r0, #2] @ r6 = dpp->delta + ldrsh r4, [r0, #4] @ r4 = dpp->weight_A + ldrsh r0, [r0, #6] @ r0 = dpp->weight_B + cmp r2, #0 @ exit if no samples to process + beq common_exit + + add r7, r1, r2, asl #3 @ r7 = buffer ending position + ldrsh r2, [r5, #0] @ r2 = dpp->term + cmp r2, #0 + bmi minus_term + + ldr lr, [r1, #-16] @ load 2 sample history from buffer + ldr r10, [r1, #-12] @ for terms 2, 17, and 18 + ldr r8, [r1, #-8] + ldr r3, [r1, #-4] + cmp r2, #17 + beq term_17_loop + cmp r2, #18 + beq term_18_loop + cmp r2, #2 + beq term_2_loop + b term_default_loop @ else handle default (1-8, except 2) + +minus_term: + mov r10, #1024 @ r10 = -1024 for weight clipping + rsb r10, r10, #0 @ (only used for negative terms) + cmn r2, #1 + beq term_minus_1 + cmn r2, #2 + beq term_minus_2 + cmn r2, #3 + beq term_minus_3 + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = 17 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample + * r3 = previous right sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = current decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_17_loop: + rsbs ip, lr, r8, asl #1 @ decorr value = (2 * prev) - 2nd prev + mov lr, r8 @ previous becomes 2nd previous + ldr r2, [r1], #4 @ get sample & update pointer + mla r8, ip, r4, r11 @ mult decorr value by weight, round, + add r8, r2, r8, asr #10 @ shift, and add to new sample + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L325 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L325: rsbs ip, r10, r3, asl #1 @ do same thing for right channel + mov r10, r3 + ldr r2, [r1], #4 + mla r3, ip, r0, r11 + add r3, r2, r3, asr #10 + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L329 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L329: cmp r7, r1 @ loop back if more samples to do + bhi term_17_loop + b store_1718 @ common exit for terms 17 & 18 + +/* + ****************************************************************************** + * Loop to handle term = 18 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample + * r3 = previous right sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_18_loop: + sub ip, r8, lr @ decorr value = + mov lr, r8 @ ((3 * prev) - 2nd prev) >> 1 + adds ip, r8, ip, asr #1 + ldr r2, [r1], #4 @ get sample & update pointer + mla r8, ip, r4, r11 @ mult decorr value by weight, round, + add r8, r2, r8, asr #10 @ shift, and add to new sample + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L337 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L337: sub ip, r3, r10 @ do same thing for right channel + mov r10, r3 + adds ip, r3, ip, asr #1 + ldr r2, [r1], #4 + mla r3, ip, r0, r11 + add r3, r2, r3, asr #10 + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L341 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L341: cmp r7, r1 @ loop back if more samples to do + bhi term_18_loop + +/* common exit for terms 17 & 18 */ + +store_1718: + str r3, [r5, #40] @ store sample history into struct + str r8, [r5, #8] + str r10, [r5, #44] + str lr, [r5, #12] + b common_exit @ and return + +/* + ****************************************************************************** + * Loop to handle term = 2 condition + * (note that this case can be handled by the default term handler (1-8), but + * this special case is faster because it doesn't have to read memory twice) + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample + * r3 = previous right sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_2_loop: + movs ip, lr @ get decorrelation value & test + mov lr, r8 @ previous becomes 2nd previous + ldr r2, [r1], #4 @ get sample & update pointer + mla r8, ip, r4, r11 @ mult decorr value by weight, round, + add r8, r2, r8, asr #10 @ shift, and add to new sample + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L225 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L225: movs ip, r10 @ do same thing for right channel + mov r10, r3 + ldr r2, [r1], #4 + mla r3, ip, r0, r11 + add r3, r2, r3, asr #10 + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L229 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L229: cmp r7, r1 @ loop back if more samples to do + bhi term_2_loop + b default_term_exit @ this exit updates all dpp->samples + +/* + ****************************************************************************** + * Loop to handle default term condition + * + * r0 = dpp->weight_B r8 = result accumulator + * r1 = bptr r9 = + * r2 = dpp->term r10 = + * r3 = decorrelation value r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = + * r7 = eptr pc = + ******************************************************************************* + */ + +term_default_loop: + ldr ip, [r1] @ get original sample + ldr r3, [r1, -r2, asl #3] @ get decorrelation value based on term + mla r8, r3, r4, r11 @ mult decorr value by weight, round, + add r8, ip, r8, asr #10 @ shift and add to new sample + str r8, [r1], #4 @ store update sample + cmp r3, #0 + cmpne ip, #0 + beq .L350 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L350: ldr ip, [r1] @ do the same thing for right channel + ldr r3, [r1, -r2, asl #3] + mla r8, r3, r0, r11 + add r8, ip, r8, asr #10 + str r8, [r1], #4 + cmp r3, #0 + cmpne ip, #0 + beq .L354 + teq ip, r3 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L354: cmp r7, r1 @ loop back if more samples to do + bhi term_default_loop + +/* + * This exit is used by terms 1-8 to store the previous 8 samples into the decorr + * structure (even if they are not all used for the given term) + */ + +default_term_exit: + ldrsh r3, [r5, #0] + sub ip, r3, #1 + mov lr, #7 + +.L358: and r3, ip, #7 + add r3, r5, r3, asl #2 + ldr r2, [r1, #-4] + str r2, [r3, #40] + ldr r2, [r1, #-8]! + str r2, [r3, #8] + sub ip, ip, #1 + sub lr, lr, #1 + cmn lr, #1 + bne .L358 + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -1 condition + * + * r0 = dpp->weight_B r8 = + * r1 = bptr r9 = + * r2 = intermediate result r10 = -1024 (for clipping) + * r3 = previous right sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = updated left sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_1: + ldr r3, [r1, #-4] + +term_minus_1_loop: + ldr ip, [r1] @ for left channel the decorrelation value + mla r2, r3, r4, r11 @ is the previous right sample (in r3) + add lr, ip, r2, asr #10 + str lr, [r1], #8 + cmp r3, #0 + cmpne ip, #0 + beq .L361 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #1024 + movgt r4, #1024 + cmp r4, r10 + movlt r4, r10 + +.L361: ldr r2, [r1, #-4] @ for right channel the decorrelation value + mla r3, lr, r0, r11 @ is the just updated right sample (in lr) + add r3, r2, r3, asr #10 + str r3, [r1, #-4] + cmp lr, #0 + cmpne r2, #0 + beq .L369 + teq r2, lr + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #1024 @ then clip weight to +/-1024 + movgt r0, #1024 + cmp r0, r10 + movlt r0, r10 + +.L369: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_1_loop + + str r3, [r5, #8] @ else store right sample and exit + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -2 condition + * (note that the channels are processed in the reverse order here) + * + * r0 = dpp->weight_B r8 = + * r1 = bptr r9 = + * r2 = intermediate result r10 = -1024 (for clipping) + * r3 = previous left sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = updated right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_2: + ldr r3, [r1, #-8] + +term_minus_2_loop: + ldr ip, [r1, #4] @ for right channel the decorrelation value + mla r2, r3, r0, r11 @ is the previous left sample (in r3) + add lr, ip, r2, asr #10 + str lr, [r1, #4] + cmp r3, #0 + cmpne ip, #0 + beq .L380 + teq ip, r3 @ update weight based on signs + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #1024 @ then clip weight to +/-1024 + movgt r0, #1024 + cmp r0, r10 + movlt r0, r10 + +.L380: ldr r2, [r1, #0] @ for left channel the decorrelation value + mla r3, lr, r4, r11 @ is the just updated left sample (in lr) + add r3, r2, r3, asr #10 + str r3, [r1], #8 + cmp lr, #0 + cmpne r2, #0 + beq .L388 + teq r2, lr + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #1024 + movgt r4, #1024 + cmp r4, r10 + movlt r4, r10 + +.L388: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_2_loop + + str r3, [r5, #40] @ else store left channel and exit + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -3 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current left sample r10 = -1024 (for clipping) + * r3 = previous right sample r11 = 512 (for rounding) + * r4 = dpp->weight_A ip = intermediate result + * r5 = dpp sp = + * r6 = dpp->delta lr = + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_3: + ldr r3, [r1, #-4] @ load previous samples + ldr r8, [r1, #-8] + +term_minus_3_loop: + ldr ip, [r1] + mla r2, r3, r4, r11 + add r2, ip, r2, asr #10 + str r2, [r1], #4 + cmp r3, #0 + cmpne ip, #0 + beq .L399 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #1024 @ then clip weight to +/-1024 + movgt r4, #1024 + cmp r4, r10 + movlt r4, r10 + +.L399: movs ip, r8 @ ip = previous left we use now + mov r8, r2 @ r8 = current left we use next time + ldr r2, [r1], #4 + mla r3, ip, r0, r11 + add r3, r2, r3, asr #10 + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L407 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #1024 + movgt r0, #1024 + cmp r0, r10 + movlt r0, r10 + +.L407: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_3_loop + + str r3, [r5, #8] @ else store previous samples & exit + str r8, [r5, #40] + +/* + * Before finally exiting we must store weights back for next time + */ + +common_exit: + strh r4, [r5, #4] + strh r0, [r5, #6] + ldmfd sp!, {r4 - r8, r10, r11, pc} + diff --git a/src/engine/external/wavpack/arml.S b/src/engine/external/wavpack/arml.S new file mode 100644 index 0000000..7da0051 --- /dev/null +++ b/src/engine/external/wavpack/arml.S @@ -0,0 +1,491 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +/* This is an assembly optimized version of the following WavPack function: + * + * void decorr_stereo_pass_cont (struct decorr_pass *dpp, + * long *buffer, long sample_count); + * + * It performs a single pass of stereo decorrelation on the provided buffer. + * Note that this version of the function requires that the 8 previous stereo + * samples are visible and correct. In other words, it ignores the "samples_*" + * fields in the decorr_pass structure and gets the history data directly + * from the buffer. It does, however, return the appropriate history samples + * to the decorr_pass structure before returning. + * + * This is written to work on a ARM7TDMI processor. This version uses the + * 64-bit multiply-accumulate instruction and so can be used with all + * WavPack files. However, for optimum performance with 16-bit WavPack + * files, there is a faster version that only uses the 32-bit MLA + * instruction. + */ + + .text + .align + .global decorr_stereo_pass_cont_arml + +/* + * on entry: + * + * r0 = struct decorr_pass *dpp + * r1 = long *buffer + * r2 = long sample_count + */ + +decorr_stereo_pass_cont_arml: + + stmfd sp!, {r4 - r8, r10, r11, lr} + mov r5, r0 @ r5 = dpp + mov r11, #512 @ r11 = 512 for rounding + ldrsh r6, [r0, #2] @ r6 = dpp->delta + ldrsh r4, [r0, #4] @ r4 = dpp->weight_A + ldrsh r0, [r0, #6] @ r0 = dpp->weight_B + cmp r2, #0 @ exit if no samples to process + beq common_exit + + mov r0, r0, asl #18 @ for 64-bit math we use weights << 18 + mov r4, r4, asl #18 + mov r6, r6, asl #18 + add r7, r1, r2, asl #3 @ r7 = buffer ending position + ldrsh r2, [r5, #0] @ r2 = dpp->term + cmp r2, #0 + blt minus_term + + ldr lr, [r1, #-16] @ load 2 sample history from buffer + ldr r10, [r1, #-12] @ for terms 2, 17, and 18 + ldr r8, [r1, #-8] + ldr r3, [r1, #-4] + + cmp r2, #18 + beq term_18_loop + mov lr, lr, asl #4 + mov r10, r10, asl #4 + cmp r2, #2 + beq term_2_loop + cmp r2, #17 + beq term_17_loop + b term_default_loop + +minus_term: + mov r10, #(1024 << 18) @ r10 = -1024 << 18 for weight clipping + rsb r10, r10, #0 @ (only used for negative terms) + cmn r2, #1 + beq term_minus_1 + cmn r2, #2 + beq term_minus_2 + cmn r2, #3 + beq term_minus_3 + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = 17 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample << 4 + * r3 = previous right sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = current decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample << 4 + * r7 = eptr pc = + ******************************************************************************* + */ + +term_17_loop: + rsbs ip, lr, r8, asl #5 @ decorr value = (2 * prev) - 2nd prev + mov lr, r8, asl #4 @ previous becomes 2nd previous + ldr r2, [r1], #4 @ get sample & update pointer + mov r11, #0x80000000 + mov r8, r2 + smlalne r11, r8, r4, ip + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L325 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L325: rsbs ip, r10, r3, asl #5 @ do same thing for right channel + mov r10, r3, asl #4 + ldr r2, [r1], #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r0, ip + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L329 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L329: cmp r7, r1 @ loop back if more samples to do + bhi term_17_loop + mov lr, lr, asr #4 + mov r10, r10, asr #4 + b store_1718 @ common exit for terms 17 & 18 + +/* + ****************************************************************************** + * Loop to handle term = 18 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample + * r3 = previous right sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_18_loop: + rsb ip, lr, r8 @ decorr value = + mov lr, r8 @ ((3 * prev) - 2nd prev) >> 1 + add ip, lr, ip, asr #1 + movs ip, ip, asl #4 + ldr r2, [r1], #4 @ get sample & update pointer + mov r11, #0x80000000 + mov r8, r2 + smlalne r11, r8, r4, ip + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L337 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L337: rsb ip, r10, r3 @ do same thing for right channel + mov r10, r3 + add ip, r10, ip, asr #1 + movs ip, ip, asl #4 + ldr r2, [r1], #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r0, ip + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L341 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L341: cmp r7, r1 @ loop back if more samples to do + bhi term_18_loop + +/* common exit for terms 17 & 18 */ + +store_1718: + str r3, [r5, #40] @ store sample history into struct + str r8, [r5, #8] + str r10, [r5, #44] + str lr, [r5, #12] + b common_exit @ and return + +/* + ****************************************************************************** + * Loop to handle term = 2 condition + * (note that this case can be handled by the default term handler (1-8), but + * this special case is faster because it doesn't have to read memory twice) + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current sample r10 = second previous left sample << 4 + * r3 = previous right sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = decorrelation value + * r5 = dpp sp = + * r6 = dpp->delta lr = second previous right sample << 4 + * r7 = eptr pc = + ******************************************************************************* + */ + +term_2_loop: + movs ip, lr @ get decorrelation value & test + ldr r2, [r1], #4 @ get sample & update pointer + mov lr, r8, asl #4 @ previous becomes 2nd previous + mov r11, #0x80000000 + mov r8, r2 + smlalne r11, r8, r4, ip + strne r8, [r1, #-4] @ if change possible, store sample back + cmpne r2, #0 + beq .L225 + teq ip, r2 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L225: movs ip, r10 @ do same thing for right channel + ldr r2, [r1], #4 + mov r10, r3, asl #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r0, ip + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L229 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L229: cmp r7, r1 @ loop back if more samples to do + bhi term_2_loop + + b default_term_exit @ this exit updates all dpp->samples + +/* + ****************************************************************************** + * Loop to handle default term condition + * + * r0 = dpp->weight_B r8 = result accumulator + * r1 = bptr r9 = + * r2 = dpp->term r10 = + * r3 = decorrelation value r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = + * r7 = eptr pc = + ******************************************************************************* + */ + +term_default_loop: + ldr r3, [r1, -r2, asl #3] @ get decorrelation value based on term + ldr ip, [r1], #4 @ get original sample and bump ptr + movs r3, r3, asl #4 + mov r11, #0x80000000 + mov r8, ip + smlalne r11, r8, r4, r3 + strne r8, [r1, #-4] @ if possibly changed, store updated sample + cmpne ip, #0 + beq .L350 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + +.L350: ldr r3, [r1, -r2, asl #3] @ do the same thing for right channel + ldr ip, [r1], #4 + movs r3, r3, asl #4 + mov r11, #0x80000000 + mov r8, ip + smlalne r11, r8, r0, r3 + strne r8, [r1, #-4] + cmpne ip, #0 + beq .L354 + teq ip, r3 + submi r0, r0, r6 + addpl r0, r0, r6 + +.L354: cmp r7, r1 @ loop back if more samples to do + bhi term_default_loop + +/* + * This exit is used by terms 1-8 to store the previous 8 samples into the decorr + * structure (even if they are not all used for the given term) + */ + +default_term_exit: + ldrsh r3, [r5, #0] + sub ip, r3, #1 + mov lr, #7 + +.L358: and r3, ip, #7 + add r3, r5, r3, asl #2 + ldr r2, [r1, #-4] + str r2, [r3, #40] + ldr r2, [r1, #-8]! + str r2, [r3, #8] + sub ip, ip, #1 + sub lr, lr, #1 + cmn lr, #1 + bne .L358 + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -1 condition + * + * r0 = dpp->weight_B r8 = + * r1 = bptr r9 = + * r2 = intermediate result r10 = -1024 (for clipping) + * r3 = previous right sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = updated left sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_1: + ldr r3, [r1, #-4] + +term_minus_1_loop: + ldr ip, [r1], #8 @ for left channel the decorrelation value + movs r3, r3, asl #4 @ is the previous right sample (in r3) + mov r11, #0x80000000 + mov lr, ip + smlalne r11, lr, r4, r3 + strne lr, [r1, #-8] + cmpne ip, #0 + beq .L361 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #(1024 << 18) + movgt r4, #(1024 << 18) + cmp r4, r10 + movlt r4, r10 + +.L361: ldr r2, [r1, #-4] @ for right channel the decorrelation value + movs lr, lr, asl #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r0, lr + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L369 + teq r2, lr + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #(1024 << 18) @ then clip weight to +/-1024 + movgt r0, #(1024 << 18) + cmp r0, r10 + movlt r0, r10 + +.L369: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_1_loop + + str r3, [r5, #8] @ else store right sample and exit + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -2 condition + * (note that the channels are processed in the reverse order here) + * + * r0 = dpp->weight_B r8 = + * r1 = bptr r9 = + * r2 = intermediate result r10 = -1024 (for clipping) + * r3 = previous left sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = current sample + * r5 = dpp sp = + * r6 = dpp->delta lr = updated right sample + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_2: + ldr r3, [r1, #-8] + +term_minus_2_loop: + ldr ip, [r1, #4] @ for right channel the decorrelation value + movs r3, r3, asl #4 @ is the previous left sample (in r3) + mov r11, #0x80000000 + mov lr, ip + smlalne r11, lr, r0, r3 + strne lr, [r1, #4] + cmpne ip, #0 + beq .L380 + teq ip, r3 @ update weight based on signs + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #(1024 << 18) @ then clip weight to +/-1024 + movgt r0, #(1024 << 18) + cmp r0, r10 + movlt r0, r10 + +.L380: ldr r2, [r1], #8 @ for left channel the decorrelation value + movs lr, lr, asl #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r4, lr + strne r3, [r1, #-8] + cmpne r2, #0 + beq .L388 + teq r2, lr + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #(1024 << 18) + movgt r4, #(1024 << 18) + cmp r4, r10 + movlt r4, r10 + +.L388: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_2_loop + + str r3, [r5, #40] @ else store left channel and exit + b common_exit + +/* + ****************************************************************************** + * Loop to handle term = -3 condition + * + * r0 = dpp->weight_B r8 = previous left sample + * r1 = bptr r9 = + * r2 = current left sample r10 = -1024 (for clipping) + * r3 = previous right sample r11 = lo accumulator (for rounding) + * r4 = dpp->weight_A ip = intermediate result + * r5 = dpp sp = + * r6 = dpp->delta lr = + * r7 = eptr pc = + ******************************************************************************* + */ + +term_minus_3: + ldr r3, [r1, #-4] @ load previous samples + ldr r8, [r1, #-8] + +term_minus_3_loop: + ldr ip, [r1], #4 + movs r3, r3, asl #4 + mov r11, #0x80000000 + mov r2, ip + smlalne r11, r2, r4, r3 + strne r2, [r1, #-4] + cmpne ip, #0 + beq .L399 + teq ip, r3 @ update weight based on signs + submi r4, r4, r6 + addpl r4, r4, r6 + cmp r4, #(1024 << 18) @ then clip weight to +/-1024 + movgt r4, #(1024 << 18) + cmp r4, r10 + movlt r4, r10 + +.L399: movs ip, r8, asl #4 @ ip = previous left we use now + mov r8, r2 @ r8 = current left we use next time + ldr r2, [r1], #4 + mov r11, #0x80000000 + mov r3, r2 + smlalne r11, r3, r0, ip + strne r3, [r1, #-4] + cmpne r2, #0 + beq .L407 + teq ip, r2 + submi r0, r0, r6 + addpl r0, r0, r6 + cmp r0, #(1024 << 18) + movgt r0, #(1024 << 18) + cmp r0, r10 + movlt r0, r10 + +.L407: cmp r7, r1 @ loop back if more samples to do + bhi term_minus_3_loop + + str r3, [r5, #8] @ else store previous samples & exit + str r8, [r5, #40] + +/* + * Before finally exiting we must store weights back for next time + */ + +common_exit: + mov r0, r0, asr #18 @ restore weights to real magnitude + mov r4, r4, asr #18 + strh r4, [r5, #4] + strh r0, [r5, #6] + ldmfd sp!, {r4 - r8, r10, r11, pc} + diff --git a/src/engine/external/wavpack/bits.c b/src/engine/external/wavpack/bits.c new file mode 100644 index 0000000..b4f0338 --- /dev/null +++ b/src/engine/external/wavpack/bits.c @@ -0,0 +1,140 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// bits.c + +// This module provides utilities to support the BitStream structure which is +// used to read and write all WavPack audio data streams. It also contains a +// wrapper for the stream I/O functions and a set of functions dealing with +// endian-ness, both for enhancing portability. Finally, a debug wrapper for +// the malloc() system is provided. + +#include "wavpack.h" + +#include <string.h> +#include <ctype.h> + +////////////////////////// Bitstream functions //////////////////////////////// + +// Open the specified BitStream and associate with the specified buffer. + +static void bs_read (Bitstream *bs); + +void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes) +{ + CLEAR (*bs); + bs->buf = buffer_start; + bs->end = buffer_end; + + if (file) { + bs->ptr = bs->end - 1; + bs->file_bytes = file_bytes; + bs->file = file; + } + else + bs->ptr = bs->buf - 1; + + bs->wrap = bs_read; +} + +// This function is only called from the getbit() and getbits() macros when +// the BitStream has been exhausted and more data is required. Sinve these +// bistreams no longer access files, this function simple sets an error and +// resets the buffer. + +static void bs_read (Bitstream *bs) +{ + if (bs->file && bs->file_bytes) { + uint32_t bytes_read, bytes_to_read = bs->end - bs->buf; + + if (bytes_to_read > bs->file_bytes) + bytes_to_read = bs->file_bytes; + + bytes_read = bs->file (bs->buf, bytes_to_read); + + if (bytes_read) { + bs->end = bs->buf + bytes_read; + bs->file_bytes -= bytes_read; + } + else { + memset (bs->buf, -1, bs->end - bs->buf); + bs->error = 1; + } + } + else + bs->error = 1; + + if (bs->error) + memset (bs->buf, -1, bs->end - bs->buf); + + bs->ptr = bs->buf; +} + +/////////////////////// Endian Correction Routines //////////////////////////// + +void little_endian_to_native (void *data, char *format) +{ + uchar *cp = (uchar *) data; + int32_t temp; + + while (*format) { + switch (*format) { + case 'L': + temp = cp [0] + ((int32_t) cp [1] << 8) + ((int32_t) cp [2] << 16) + ((int32_t) cp [3] << 24); + * (int32_t *) cp = temp; + cp += 4; + break; + + case 'S': + temp = cp [0] + (cp [1] << 8); + * (short *) cp = (short) temp; + cp += 2; + break; + + default: + if (isdigit (*format)) + cp += *format - '0'; + + break; + } + + format++; + } +} + +void native_to_little_endian (void *data, char *format) +{ + uchar *cp = (uchar *) data; + int32_t temp; + + while (*format) { + switch (*format) { + case 'L': + temp = * (int32_t *) cp; + *cp++ = (uchar) temp; + *cp++ = (uchar) (temp >> 8); + *cp++ = (uchar) (temp >> 16); + *cp++ = (uchar) (temp >> 24); + break; + + case 'S': + temp = * (short *) cp; + *cp++ = (uchar) temp; + *cp++ = (uchar) (temp >> 8); + break; + + default: + if (isdigit (*format)) + cp += *format - '0'; + + break; + } + + format++; + } +} diff --git a/src/engine/external/wavpack/coldfire.S b/src/engine/external/wavpack/coldfire.S new file mode 100644 index 0000000..8353090 --- /dev/null +++ b/src/engine/external/wavpack/coldfire.S @@ -0,0 +1,525 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +/* This is an assembly optimized version of the following WavPack function: + * + * void decorr_stereo_pass_cont (struct decorr_pass *dpp, + * long *buffer, long sample_count); + * + * It performs a single pass of stereo decorrelation on the provided buffer. + * Note that this version of the function requires that the 8 previous stereo + * samples are visible and correct. In other words, it ignores the "samples_*" + * fields in the decorr_pass structure and gets the history data directly + * from the buffer. It does, however, return the appropriate history samples + * to the decorr_pass structure before returning. + * + * This is written to work on a MCF5249 processor, or any processor based on + * the ColdFire V2 core with an EMAC unit. The EMAC is perfectly suited for + * the "apply_weight" function of WavPack decorrelation because it provides + * the requires 40-bit product. The fractional rounding mode of the EMAC is not + * configurable and uses "round to even" while WavPack uses "round to larger", + * so the rounding has to be done manually. + */ + + .text + .align 2 + .global decorr_stereo_pass_cont_mcf5249 + +decorr_stereo_pass_cont_mcf5249: + + lea (-44, %sp), %sp + movem.l %d2-%d7/%a2-%a6, (%sp) + move.l 44+4(%sp), %a2 | a2 = dpp-> + move.l 44+8(%sp), %a1 | a1 = bptr + move.w 2(%a2), %a3 | a3 = dpp->delta + move.w 4(%a2), %d3 | d3 = dpp->weight_A (sign extended) + ext.l %d3 + move.w 6(%a2), %d4 | d4 = dpp->weight_B (sign extended) + ext.l %d4 + move.l 44+12(%sp), %d0 | d0 = sample_count + jbeq return_only | if zero, nothing to do + + lsl.l #3, %d0 | d5 = bptr + (sample_count * 8) + move.l %d0, %d5 + add.l %a1, %d5 + + moveq.l #17, %d0 | left shift weights & delta 17 places + asl.l %d0, %d3 + asl.l %d0, %d4 + move.l %a3, %d1 + asl.l %d0, %d1 + move.l %d1, %a3 + + moveq.l #0x20, %d6 + move.l %d6, %macsr | set fractional mode for MAC + move.l #0, %acc1 | acc1 = 0x00 0000 80 (for rounding) + move.l #0x800000, %accext01 + + move.l #1024<<17, %d6 | d6 & d7 are weight clipping limits + move.l #-1024<<17, %d7 | (only used by negative terms) + + move.w (%a2), %d0 | d0 = term + ext.l %d0 + cmp.l #17, %d0 + jbeq term_17 | term = 17 + cmp.l #18, %d0 + jbeq term_18 | term = 18 + addq.l #1, %d0 + jbeq term_minus_1 | term = -1 + addq.l #1, %d0 + jbeq term_minus_2 | term = -2 + addq.l #1, %d0 + jbeq term_minus_3 | term = -3 + jbra term_default | default term = 1 - 8 + +|------------------------------------------------------------------------------ +| Loop to handle term = 17 condition +| +| a0 = d0 = (2 * bptr [-1]) - bptr [-2] +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_17: + move.l -8(%a1), %d0 | d0 = 2 * bptr [-1] - bptr [-2] + add.l %d0, %d0 + sub.l -16(%a1), %d0 + beq .L251 | if zero, skip calculation + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L255 + eor.l %d1, %d0 | else compare signs + bge .L256 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + sub.l %a3, %d3 | subtract again instead of branch +.L256: add.l %a3, %d3 | add delta to weight + +.L255: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | update bptr [0] and store + move.l %d2, (%a1)+ + +.L253: move.l -8(%a1), %d0 | d0 = 2 * bptr [-1] - bptr [-2] + add.l %d0, %d0 + sub.l -16(%a1), %d0 + beq .L257 | if zero, skip calculations + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B + mac.l %d0, %d4, %acc0 + move.l (%a1), %d1 + beq .L254 + eor.l %d1, %d0 | else compare signs + bge .L259 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + sub.l %a3, %d4 | subtract again instead of branch +.L259: add.l %a3, %d4 | add delta to weight + +.L254: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | update bptr [0] and store + move.l %d2, (%a1)+ + +.L252: cmp.l %a1, %d5 | loop if bptr < eptr + jbhi term_17 + bra term_17_18_finish | exit through common path + +.L251: addq.l #4, %a1 | update point and jump back into loop + bra .L253 + +.L257: addq.l #4, %a1 | update point and jump back into loop + bra .L252 + +|------------------------------------------------------------------------------ +| Loop to handle term = 18 condition +| +| a0 = d0 = ((3 * bptr [-1]) - bptr [-2]) >> 1 +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_18: + move.l -8(%a1), %a0 | d0 = (3 * bptr [-1] - bptr [-2]) >> 1 + lea (%a0,%a0.l*2), %a0 + move.l %a0, %d0 + sub.l -16(%a1), %d0 + asr.l #1, %d0 + beq .L260 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L266 + eor.l %d1, %d0 | else compare signs + bge .L267 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + sub.l %a3, %d3 | subtract again instead of branch +.L267: add.l %a3, %d3 | add delta to weight + +.L266: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [0], store + move.l %d2, (%a1)+ + +.L268: move.l -8(%a1), %a0 | d0 = (3 * bptr [-1] - bptr [-2]) >> 1 + lea (%a0,%a0.l*2), %a0 + move.l %a0, %d0 + sub.l -16(%a1), %d0 + asr.l #1, %d0 + beq .L261 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B + mac.l %d0, %d4, %acc0 + move.l (%a1), %d1 + beq .L265 + eor.l %d1, %d0 | else compare signs + bge .L270 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + sub.l %a3, %d4 | subtract again instead of branch +.L270: add.l %a3, %d4 | add delta to weight + +.L265: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [0], store + move.l %d2, (%a1)+ + +.L269: cmp.l %a1, %d5 | loop if bptr < eptr + jbhi term_18 + bra term_17_18_finish | exit through common path + +.L260: addq.l #4, %a1 | bump pointer and jump back into loop + bra .L268 + +.L261: addq.l #4, %a1 | bump pointer and jump back into loop + bra .L269 + +term_17_18_finish: + move.l -4(%a1), 40(%a2) | restore dpp->samples_A [0-1], B [0-1] + move.l -8(%a1), 8(%a2) + move.l -12(%a1), 44(%a2) + move.l -16(%a1), 12(%a2) + jbra finish_up + +|------------------------------------------------------------------------------ +| Loop to handle default terms (i.e. 1 - 8) +| +| a0 = tptr d0 = tptr [0] +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_default: + move.w (%a2), %d0 | a0 = a1 - (dpp->term * 8) + ext.l %d0 + lsl.l #3, %d0 + move.l %a1, %a0 + sub.l %d0, %a0 + +term_default_loop: + move.l (%a0)+, %d0 | d0 = tptr [0], skip ahead if zero + beq .L271 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L277 + eor.l %d1, %d0 | else compare signs + bge .L278 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + sub.l %a3, %d3 | subtract again instead of branch +.L278: add.l %a3, %d3 | add delta to weight + +.L277: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [0], store + move.l %d2, (%a1)+ + +.L275: move.l (%a0)+, %d0 | d0 = tptr [0], skip ahead if zero + beq .L272 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B + mac.l %d0, %d4, %acc0 + move.l (%a1), %d1 + beq .L276 + eor.l %d1, %d0 | else compare signs + bge .L281 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + sub.l %a3, %d4 | subtract again instead of branch +.L281: add.l %a3, %d4 | add delta to weight + +.L276: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [0], store + move.l %d2, (%a1)+ + +.L274: cmp.l %a1, %d5 | loop back if bptr < eptr + jbhi term_default_loop + move.w (%a2), %d0 | d0 = term - 1 + moveq.l #8, %d1 | d1 = loop counter + +.L323: subq.l #1, %d0 | back up & mask index + and.l #7, %d0 + move.l -(%a1), 40(%a2,%d0.l*4) | store dpp->samples_B [d0] + move.l -(%a1), 8(%a2,%d0.l*4) | store dpp->samples_A [d0] + subq.l #1, %d1 | loop on count + jbne .L323 + jbra finish_up + +.L271: addq.l #4, %a1 | bump pointer and jump back into loop + bra .L275 + +.L272: addq.l #4, %a1 | bump pointer and jump back into loop + bra .L274 + + +|------------------------------------------------------------------------------ +| Loop to handle term = -1 condition +| +| a0 = d0 = decorrelation sample +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| a6 = d6 = 1024 << 17 +| a7 = d7 = -1024 << 17 +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_minus_1: + move.l -4(%a1), %d0 | d0 = bptr [-1] + beq .L402 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L405 + eor.l %d1, %d0 | else compare signs + bge .L404 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + cmp.l %d7, %d3 | check for negative clip limit + bge .L405 + move.l %d7, %d3 + bra .L405 + +.L404: add.l %a3, %d3 | add delta to weight + cmp.l %d6, %d3 | check for positive clip limit + ble .L405 + move.l %d6, %d3 + +.L405: move.l %acc0, %d0 | d2 = rounded product + add.l %d1, %d0 | add applied weight to bptr [0], store + move.l %d0, (%a1)+ + beq .L401 + +.L410: move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) + mac.l %d0, %d4, %acc0 + move.l (%a1), %d1 + beq .L403 + eor.l %d1, %d0 | else compare signs + bge .L407 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + cmp.l %d7, %d4 | check for negative clip limit + bge .L403 + move.l %d7, %d4 + bra .L403 + +.L407: add.l %a3, %d4 | add delta to weight + cmp.l %d6, %d4 | check for positive clip limit + ble .L403 + move.l %d6, %d4 + +.L403: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [1], store + move.l %d2, (%a1)+ + +.L411: cmp.l %a1, %d5 | loop back if bptr < eptr + jbhi term_minus_1 + move.l -4(%a1), 8(%a2) | dpp->samples_A [0] = bptr [-1] + jbra finish_up + +.L402: move.l (%a1)+, %d0 + bne .L410 + +.L401: addq.l #4, %a1 + bra .L411 + + +|------------------------------------------------------------------------------ +| Loop to handle term = -2 condition +| +| a0 = d0 = decorrelation sample +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| a6 = d6 = 1024 << 17 +| a7 = d7 = -1024 << 17 +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_minus_2: + move.l -8(%a1), %d0 | d0 = bptr [-2] + beq .L511 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) + mac.l %d0, %d4, %acc0 + move.l 4(%a1), %d1 + beq .L505 + eor.l %d1, %d0 | else compare signs + bge .L504 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + cmp.l %d7, %d4 | ckeck for negative clip limit + bge .L505 + move.l %d7, %d4 + bra .L505 + +.L504: add.l %a3, %d4 | add delta to weight + cmp.l %d6, %d4 | check for positive clip limit + ble .L505 + move.l %d6, %d4 + +.L505: move.l %acc0, %d0 | d2 = rounded product + add.l %d1, %d0 | add applied weight to bptr [0], store + move.l %d0, 4(%a1) + beq .L512 + +.L510: move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L503 + eor.l %d1, %d0 | else compare signs + bge .L507 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + cmp.l %d7, %d3 | check for negative clip limit + bge .L503 + move.l %d7, %d3 + bra .L503 + +.L507: add.l %a3, %d3 | add delta to weight + cmp.l %d6, %d3 | check for negative clip limit + ble .L503 + move.l %d6, %d3 + +.L503: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [1], store + move.l %d2, (%a1) + +.L512: addq.l #8, %a1 + cmp.l %a1, %d5 | loop if bptr < eptr + jbhi term_minus_2 + move.l -8(%a1), 40(%a2) | dpp->samples_B [0] = bptr [-4] + jbra finish_up + +.L511: move.l 4(%a1), %d0 + beq .L512 + bra .L510 + + +|------------------------------------------------------------------------------ +| Loop to handle term = -3 condition +| +| a0 = d0 = decorrelation sample +| a1 = bptr d1 = initial bptr [0] +| a2 = dpp-> d2 = updated bptr [0] +| a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 +| a4 = d4 = dpp->weight_B << 17 +| a5 = d5 = eptr +| a6 = d6 = 1024 << 17 +| a7 = d7 = -1024 << 17 +| macsr = 0x20 acc1 = 0x00 0000 80 +|------------------------------------------------------------------------------ + +term_minus_3: + move.l -4(%a1), %d0 | d0 = bptr [-1] + beq .L301 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) + mac.l %d0, %d3, %acc0 + move.l (%a1), %d1 + beq .L320 + eor.l %d1, %d0 | else compare signs + bge .L319 | if same, add delta to weight + sub.l %a3, %d3 | else subtract delta from weight + cmp.l %d7, %d3 | check for negative clip limit + bge .L320 + move.l %d7, %d3 + bra .L320 + +.L319: add.l %a3, %d3 | add delta to weight + cmp.l %d6, %d3 | check for positive clip limit + ble .L320 + move.l %d6, %d3 + +.L320: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [0], store + move.l %d2, (%a1)+ + +.L330: move.l -12(%a1), %d0 | d0 = bptr [-2] + beq .L302 + move.l %acc1, %acc0 + asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) + mac.l %d0, %d4, %acc0 + move.l (%a1), %d1 + beq .L318 + eor.l %d1, %d0 | else compare signs + bge .L322 | if same, add delta to weight + sub.l %a3, %d4 | else subtract delta from weight + cmp.l %d7, %d4 | check for negative clip limit + bge .L318 + move.l %d7, %d4 + bra .L318 + +.L322: add.l %a3, %d4 | add delta to weight + cmp.l %d6, %d4 | check for positive clip limit + ble .L318 + move.l %d6, %d4 + +.L318: move.l %acc0, %d2 | d2 = rounded product + add.l %d1, %d2 | add applied weight to bptr [1], store + move.l %d2, (%a1)+ + +.L331: cmp.l %a1, %d5 | bptr, eptr + jbhi term_minus_3 + move.l -4(%a1), 8(%a2) | dpp->samples_A [0] = bptr [-1] + move.l -8(%a1), 40(%a2) | dpp->samples_B [0] = bptr [-2] + jbra finish_up + +.L301: addq.l #4, %a1 + bra .L330 + +.L302: addq.l #4, %a1 + bra .L331 + +| finish and return + +finish_up: + moveq.l #17, %d0 + asr.l %d0, %d3 + asr.l %d0, %d4 + move.w %d3, 4(%a2) | weight_A, dpp->weight_A + move.w %d4, 6(%a2) | weight_B, dpp->weight_B + + clr.l %d0 | clear up EMAC + move.l %d0, %acc0 + move.l %d0, %acc1 + +return_only: + movem.l (%sp), %d2-%d7/%a2-%a6 + lea (44,%sp), %sp + rts diff --git a/src/engine/external/wavpack/float.c b/src/engine/external/wavpack/float.c new file mode 100644 index 0000000..09f0e4c --- /dev/null +++ b/src/engine/external/wavpack/float.c @@ -0,0 +1,50 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// float.c + +#include "wavpack.h" + +int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd) +{ + int bytecnt = wpmd->byte_length; + char *byteptr = wpmd->data; + + if (bytecnt != 4) + return FALSE; + + wps->float_flags = *byteptr++; + wps->float_shift = *byteptr++; + wps->float_max_exp = *byteptr++; + wps->float_norm_exp = *byteptr; + return TRUE; +} + +void float_values (WavpackStream *wps, int32_t *values, int32_t num_values) +{ + int shift = wps->float_max_exp - wps->float_norm_exp + wps->float_shift; + + if (shift > 32) + shift = 32; + else if (shift < -32) + shift = -32; + + while (num_values--) { + if (shift > 0) + *values <<= shift; + else if (shift < 0) + *values >>= -shift; + + if (*values > 8388607L) + *values = 8388607L; + else if (*values < -8388608L) + *values = -8388608L; + + values++; + } +} diff --git a/src/engine/external/wavpack/license.txt b/src/engine/external/wavpack/license.txt new file mode 100644 index 0000000..d2ee90f --- /dev/null +++ b/src/engine/external/wavpack/license.txt @@ -0,0 +1,25 @@ + Copyright (c) 1998 - 2006 Conifer Software + All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Conifer Software nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/engine/external/wavpack/metadata.c b/src/engine/external/wavpack/metadata.c new file mode 100644 index 0000000..6a19ac9 --- /dev/null +++ b/src/engine/external/wavpack/metadata.c @@ -0,0 +1,105 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// metadata.c + +// This module handles the metadata structure introduced in WavPack 4.0 + +#include "wavpack.h" + +int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd) +{ + uchar tchar; + + if (!wpc->infile (&wpmd->id, 1) || !wpc->infile (&tchar, 1)) + return FALSE; + + wpmd->byte_length = tchar << 1; + + if (wpmd->id & ID_LARGE) { + wpmd->id &= ~ID_LARGE; + + if (!wpc->infile (&tchar, 1)) + return FALSE; + + wpmd->byte_length += (int32_t) tchar << 9; + + if (!wpc->infile (&tchar, 1)) + return FALSE; + + wpmd->byte_length += (int32_t) tchar << 17; + } + + if (wpmd->id & ID_ODD_SIZE) { + wpmd->id &= ~ID_ODD_SIZE; + wpmd->byte_length--; + } + + if (wpmd->byte_length && wpmd->byte_length <= sizeof (wpc->read_buffer)) { + uint32_t bytes_to_read = wpmd->byte_length + (wpmd->byte_length & 1); + + if (wpc->infile (wpc->read_buffer, bytes_to_read) != (int32_t) bytes_to_read) { + wpmd->data = NULL; + return FALSE; + } + + wpmd->data = wpc->read_buffer; + } + else + wpmd->data = NULL; + + return TRUE; +} + +int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd) +{ + WavpackStream *wps = &wpc->stream; + + switch (wpmd->id) { + case ID_DUMMY: + return TRUE; + + case ID_DECORR_TERMS: + return read_decorr_terms (wps, wpmd); + + case ID_DECORR_WEIGHTS: + return read_decorr_weights (wps, wpmd); + + case ID_DECORR_SAMPLES: + return read_decorr_samples (wps, wpmd); + + case ID_ENTROPY_VARS: + return read_entropy_vars (wps, wpmd); + + case ID_HYBRID_PROFILE: + return read_hybrid_profile (wps, wpmd); + + case ID_FLOAT_INFO: + return read_float_info (wps, wpmd); + + case ID_INT32_INFO: + return read_int32_info (wps, wpmd); + + case ID_CHANNEL_INFO: + return read_channel_info (wpc, wpmd); + + case ID_CONFIG_BLOCK: + return read_config_info (wpc, wpmd); + + case ID_WV_BITSTREAM: + return init_wv_bitstream (wpc, wpmd); + + case ID_SHAPING_WEIGHTS: + case ID_WVC_BITSTREAM: + case ID_WVX_BITSTREAM: + return TRUE; + + default: + return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE; + } +} diff --git a/src/engine/external/wavpack/readme.txt b/src/engine/external/wavpack/readme.txt new file mode 100644 index 0000000..07b7a26 --- /dev/null +++ b/src/engine/external/wavpack/readme.txt @@ -0,0 +1,68 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +This package contains a tiny version of the WavPack 4.40 decoder that might +be used in a "resource limited" CPU environment or form the basis for a +hardware decoding implementation. It is packaged with a demo command-line +program that accepts a WavPack audio file on stdin and outputs a RIFF wav +file to stdout. The program is standard C, and a win32 executable is +included which was compiled under MS Visual C++ 6.0 using this command: + +cl /O1 /DWIN32 wvfilter.c wputils.c unpack.c float.c metadata.c words.c bits.c + +WavPack data is read with a stream reading callback. No direct seeking is +provided for, but it is possible to start decoding anywhere in a WavPack +stream. In this case, WavPack will be able to provide the sample-accurate +position when it synchs with the data and begins decoding. The WIN32 macro +is used for Windows to force the stdin and stdout streams to be binary mode. + +Compared to the previous version, this library has been optimized somewhat +for improved performance in exchange for slightly larger code size. The +library also now includes hand-optimized assembly language versions of the +decorrelation functions for both the ColdFire (w/EMAC) and ARM processors. + +For demonstration purposes this uses a single static copy of the +WavpackContext structure, so obviously it cannot be used for more than one +file at a time. Also, this decoder will not handle "correction" files, plays +only the first two channels of multi-channel files, and is limited in +resolution in some large integer or floating point files (but always +provides at least 24 bits of resolution). It also will not accept WavPack +files from before version 4.0. + +The previous version of this library would handle float files by returning +32-bit floating-point data (even though no floating point math was used). +Because this library would normally be used for simply playing WavPack +files where lossless performance (beyond 24-bits) is not relevant, I have +changed this behavior. Now, these files will generate clipped 24-bit data. +The MODE_FLOAT flag will still be returned by WavpackGetMode(), but the +BitsPerSample and BytesPerSample queries will be 24 and 3, respectfully. +What this means is that an application that can handle 24-bit data will +now be able to handle floating point data (assuming that the MODE_FLOAT +flag is ignored). + +To make this code viable on the greatest number of hardware platforms, the +following are true: + + speed is about 5x realtime on an AMD K6 300 MHz + ("high" mode 16/44 stereo; normal mode is about twice that fast) + + no floating-point math required; just 32b * 32b = 32b int multiply + + large data areas are static and less than 4K total + executable code and tables are less than 40K + no malloc / free usage + +To maintain compatibility on various platforms, the following conventions +are used: + + a "char" must be exactly 8-bits + a "short" must be exactly 16-bits + an "int" must be at least 16-bits, but may be larger + the "long" type is not used to avoid problems with 64-bit compilers + +Questions or comments should be directed to david@wavpack.com diff --git a/src/engine/external/wavpack/unpack.c b/src/engine/external/wavpack/unpack.c new file mode 100644 index 0000000..317fe22 --- /dev/null +++ b/src/engine/external/wavpack/unpack.c @@ -0,0 +1,785 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// unpack.c + +// This module actually handles the decompression of the audio data, except +// for the entropy decoding which is handled by the words.c module. For +// maximum efficiency, the conversion is isolated to tight loops that handle +// an entire buffer. + +#include "wavpack.h" + +#include <stdlib.h> +#include <string.h> + +#define LOSSY_MUTE + +///////////////////////////// executable code //////////////////////////////// + +// This function initializes everything required to unpack a WavPack block +// and must be called before unpack_samples() is called to obtain audio data. +// It is assumed that the WavpackHeader has been read into the wps->wphdr +// (in the current WavpackStream). This is where all the metadata blocks are +// scanned up to the one containing the audio bitstream. + +int unpack_init (WavpackContext *wpc) +{ + WavpackStream *wps = &wpc->stream; + WavpackMetadata wpmd; + + if (wps->wphdr.block_samples && wps->wphdr.block_index != (uint32_t) -1) + wps->sample_index = wps->wphdr.block_index; + + wps->mute_error = FALSE; + wps->crc = 0xffffffff; + CLEAR (wps->wvbits); + CLEAR (wps->decorr_passes); + CLEAR (wps->w); + + while (read_metadata_buff (wpc, &wpmd)) { + if (!process_metadata (wpc, &wpmd)) { + strcpy (wpc->error_message, "invalid metadata!"); + return FALSE; + } + + if (wpmd.id == ID_WV_BITSTREAM) + break; + } + + if (wps->wphdr.block_samples && !bs_is_open (&wps->wvbits)) { + strcpy (wpc->error_message, "invalid WavPack file!"); + return FALSE; + } + + if (wps->wphdr.block_samples) { + if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits) + wpc->lossy_blocks = TRUE; + + if ((wps->wphdr.flags & FLOAT_DATA) && + wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME)) + wpc->lossy_blocks = TRUE; + } + + return TRUE; +} + +// This function initialzes the main bitstream for audio samples, which must +// be in the "wv" file. + +int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd) +{ + WavpackStream *wps = &wpc->stream; + + if (wpmd->data) + bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length, NULL, 0); + else if (wpmd->byte_length) + bs_open_read (&wps->wvbits, wpc->read_buffer, wpc->read_buffer + sizeof (wpc->read_buffer), + wpc->infile, wpmd->byte_length + (wpmd->byte_length & 1)); + + return TRUE; +} + +// Read decorrelation terms from specified metadata block into the +// decorr_passes array. The terms range from -3 to 8, plus 17 & 18; +// other values are reserved and generate errors for now. The delta +// ranges from 0 to 7 with all values valid. Note that the terms are +// stored in the opposite order in the decorr_passes array compared +// to packing. + +int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd) +{ + int termcnt = wpmd->byte_length; + uchar *byteptr = wpmd->data; + struct decorr_pass *dpp; + + if (termcnt > MAX_NTERMS) + return FALSE; + + wps->num_terms = termcnt; + + for (dpp = wps->decorr_passes + termcnt - 1; termcnt--; dpp--) { + dpp->term = (int)(*byteptr & 0x1f) - 5; + dpp->delta = (*byteptr++ >> 5) & 0x7; + + if (!dpp->term || dpp->term < -3 || (dpp->term > MAX_TERM && dpp->term < 17) || dpp->term > 18) + return FALSE; + } + + return TRUE; +} + +// Read decorrelation weights from specified metadata block into the +// decorr_passes array. The weights range +/-1024, but are rounded and +// truncated to fit in signed chars for metadata storage. Weights are +// separate for the two channels and are specified from the "last" term +// (first during encode). Unspecified weights are set to zero. + +int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd) +{ + int termcnt = wpmd->byte_length, tcount; + signed char *byteptr = wpmd->data; + struct decorr_pass *dpp; + + if (!(wps->wphdr.flags & MONO_DATA)) + termcnt /= 2; + + if (termcnt > wps->num_terms) + return FALSE; + + for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) + dpp->weight_A = dpp->weight_B = 0; + + while (--dpp >= wps->decorr_passes && termcnt--) { + dpp->weight_A = restore_weight (*byteptr++); + + if (!(wps->wphdr.flags & MONO_DATA)) + dpp->weight_B = restore_weight (*byteptr++); + } + + return TRUE; +} + +// Read decorrelation samples from specified metadata block into the +// decorr_passes array. The samples are signed 32-bit values, but are +// converted to signed log2 values for storage in metadata. Values are +// stored for both channels and are specified from the "last" term +// (first during encode) with unspecified samples set to zero. The +// number of samples stored varies with the actual term value, so +// those must obviously come first in the metadata. + +int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd) +{ + uchar *byteptr = wpmd->data; + uchar *endptr = byteptr + wpmd->byte_length; + struct decorr_pass *dpp; + int tcount; + + for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) { + CLEAR (dpp->samples_A); + CLEAR (dpp->samples_B); + } + + if (wps->wphdr.version == 0x402 && (wps->wphdr.flags & HYBRID_FLAG)) { + byteptr += 2; + + if (!(wps->wphdr.flags & MONO_DATA)) + byteptr += 2; + } + + while (dpp-- > wps->decorr_passes && byteptr < endptr) + if (dpp->term > MAX_TERM) { + dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + dpp->samples_A [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); + byteptr += 4; + + if (!(wps->wphdr.flags & MONO_DATA)) { + dpp->samples_B [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + dpp->samples_B [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); + byteptr += 4; + } + } + else if (dpp->term < 0) { + dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + dpp->samples_B [0] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); + byteptr += 4; + } + else { + int m = 0, cnt = dpp->term; + + while (cnt--) { + dpp->samples_A [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + byteptr += 2; + + if (!(wps->wphdr.flags & MONO_DATA)) { + dpp->samples_B [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + byteptr += 2; + } + + m++; + } + } + + return byteptr == endptr; +} + +// Read the int32 data from the specified metadata into the specified stream. +// This data is used for integer data that has more than 24 bits of magnitude +// or, in some cases, used to eliminate redundant bits from any audio stream. + +int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd) +{ + int bytecnt = wpmd->byte_length; + char *byteptr = wpmd->data; + + if (bytecnt != 4) + return FALSE; + + wps->int32_sent_bits = *byteptr++; + wps->int32_zeros = *byteptr++; + wps->int32_ones = *byteptr++; + wps->int32_dups = *byteptr; + return TRUE; +} + +// Read multichannel information from metadata. The first byte is the total +// number of channels and the following bytes represent the channel_mask +// as described for Microsoft WAVEFORMATEX. + +int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd) +{ + int bytecnt = wpmd->byte_length, shift = 0; + char *byteptr = wpmd->data; + uint32_t mask = 0; + + if (!bytecnt || bytecnt > 5) + return FALSE; + + wpc->config.num_channels = *byteptr++; + + while (--bytecnt) { + mask |= (uint32_t) *byteptr++ << shift; + shift += 8; + } + + wpc->config.channel_mask = mask; + return TRUE; +} + +// Read configuration information from metadata. + +int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) +{ + int bytecnt = wpmd->byte_length; + uchar *byteptr = wpmd->data; + + if (bytecnt >= 3) { + wpc->config.flags &= 0xff; + wpc->config.flags |= (int32_t) *byteptr++ << 8; + wpc->config.flags |= (int32_t) *byteptr++ << 16; + wpc->config.flags |= (int32_t) *byteptr << 24; + } + + return TRUE; +} + +// This monster actually unpacks the WavPack bitstream(s) into the specified +// buffer as 32-bit integers or floats (depending on orignal data). Lossy +// samples will be clipped to their original limits (i.e. 8-bit samples are +// clipped to -128/+127) but are still returned in int32_ts. It is up to the +// caller to potentially reformat this for the final output including any +// multichannel distribution, block alignment or endian compensation. The +// function unpack_init() must have been called and the entire WavPack block +// must still be visible (although wps->blockbuff will not be accessed again). +// For maximum clarity, the function is broken up into segments that handle +// various modes. This makes for a few extra infrequent flag checks, but +// makes the code easier to follow because the nesting does not become so +// deep. For maximum efficiency, the conversion is isolated to tight loops +// that handle an entire buffer. The function returns the total number of +// samples unpacked, which can be less than the number requested if an error +// occurs or the end of the block is reached. + +#if defined(CPU_COLDFIRE) && !defined(SIMULATOR) +extern void decorr_stereo_pass_cont_mcf5249 (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +#elif defined(CPU_ARM) && !defined(SIMULATOR) +extern void decorr_stereo_pass_cont_arm (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +extern void decorr_stereo_pass_cont_arml (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +#else +static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +#endif + +static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); +static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count); + +int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count) +{ + WavpackStream *wps = &wpc->stream; + uint32_t flags = wps->wphdr.flags, crc = wps->crc, i; + int32_t mute_limit = (1L << ((flags & MAG_MASK) >> MAG_LSB)) + 2; + struct decorr_pass *dpp; + int32_t *bptr, *eptr; + int tcount; + + if (wps->sample_index + sample_count > wps->wphdr.block_index + wps->wphdr.block_samples) + sample_count = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index; + + if (wps->mute_error) { + memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8)); + wps->sample_index += sample_count; + return sample_count; + } + + if (flags & HYBRID_FLAG) + mute_limit *= 2; + + ///////////////////// handle version 4 mono data ///////////////////////// + + if (flags & MONO_DATA) { + eptr = buffer + sample_count; + i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits); + + for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) + decorr_mono_pass (dpp, buffer, sample_count); + + for (bptr = buffer; bptr < eptr; ++bptr) { + if (labs (bptr [0]) > mute_limit) { + i = bptr - buffer; + break; + } + + crc = crc * 3 + bptr [0]; + } + } + + //////////////////// handle version 4 stereo data //////////////////////// + + else { + eptr = buffer + (sample_count * 2); + i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits); + + if (sample_count < 16) + for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) + decorr_stereo_pass (dpp, buffer, sample_count); + else + for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) { + decorr_stereo_pass (dpp, buffer, 8); +#if defined(CPU_COLDFIRE) && !defined(SIMULATOR) + decorr_stereo_pass_cont_mcf5249 (dpp, buffer + 16, sample_count - 8); +#elif defined(CPU_ARM) && !defined(SIMULATOR) + if (((flags & MAG_MASK) >> MAG_LSB) > 15) + decorr_stereo_pass_cont_arml (dpp, buffer + 16, sample_count - 8); + else + decorr_stereo_pass_cont_arm (dpp, buffer + 16, sample_count - 8); +#else + decorr_stereo_pass_cont (dpp, buffer + 16, sample_count - 8); +#endif + } + + if (flags & JOINT_STEREO) + for (bptr = buffer; bptr < eptr; bptr += 2) { + bptr [0] += (bptr [1] -= (bptr [0] >> 1)); + + if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) { + i = (bptr - buffer) / 2; + break; + } + + crc = (crc * 3 + bptr [0]) * 3 + bptr [1]; + } + else + for (bptr = buffer; bptr < eptr; bptr += 2) { + if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) { + i = (bptr - buffer) / 2; + break; + } + + crc = (crc * 3 + bptr [0]) * 3 + bptr [1]; + } + } + + if (i != sample_count) { + memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8)); + wps->mute_error = TRUE; + i = sample_count; + } + + fixup_samples (wps, buffer, i); + + if (flags & FALSE_STEREO) { + int32_t *dptr = buffer + i * 2; + int32_t *sptr = buffer + i; + int32_t c = i; + + while (c--) { + *--dptr = *--sptr; + *--dptr = *sptr; + } + } + + wps->sample_index += i; + wps->crc = crc; + + return i; +} + +static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) +{ + int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B; + int32_t *bptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B; + int m, k; + + switch (dpp->term) { + + case 17: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1]; + dpp->samples_A [1] = dpp->samples_A [0]; + dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [0]; + + sam_A = 2 * dpp->samples_B [0] - dpp->samples_B [1]; + dpp->samples_B [1] = dpp->samples_B [0]; + dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1]; + update_weight (weight_B, delta, sam_A, bptr [1]); + bptr [1] = dpp->samples_B [0]; + } + + break; + + case 18: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1; + dpp->samples_A [1] = dpp->samples_A [0]; + dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [0]; + + sam_A = (3 * dpp->samples_B [0] - dpp->samples_B [1]) >> 1; + dpp->samples_B [1] = dpp->samples_B [0]; + dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1]; + update_weight (weight_B, delta, sam_A, bptr [1]); + bptr [1] = dpp->samples_B [0]; + } + + break; + + default: + for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = dpp->samples_A [m]; + dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [k]; + + sam_A = dpp->samples_B [m]; + dpp->samples_B [k] = apply_weight (weight_B, sam_A) + bptr [1]; + update_weight (weight_B, delta, sam_A, bptr [1]); + bptr [1] = dpp->samples_B [k]; + + m = (m + 1) & (MAX_TERM - 1); + k = (k + 1) & (MAX_TERM - 1); + } + + if (m) { + int32_t temp_samples [MAX_TERM]; + + memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A)); + + for (k = 0; k < MAX_TERM; k++, m++) + dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)]; + + memcpy (temp_samples, dpp->samples_B, sizeof (dpp->samples_B)); + + for (k = 0; k < MAX_TERM; k++, m++) + dpp->samples_B [k] = temp_samples [m & (MAX_TERM - 1)]; + } + + break; + + case -1: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]); + update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]); + bptr [0] = sam_A; + dpp->samples_A [0] = bptr [1] + apply_weight (weight_B, sam_A); + update_weight_clip (weight_B, delta, sam_A, bptr [1]); + bptr [1] = dpp->samples_A [0]; + } + + break; + + case -2: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]); + update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]); + bptr [1] = sam_B; + dpp->samples_B [0] = bptr [0] + apply_weight (weight_A, sam_B); + update_weight_clip (weight_A, delta, sam_B, bptr [0]); + bptr [0] = dpp->samples_B [0]; + } + + break; + + case -3: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]); + update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]); + sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]); + update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]); + bptr [0] = dpp->samples_B [0] = sam_A; + bptr [1] = dpp->samples_A [0] = sam_B; + } + + break; + } + + dpp->weight_A = weight_A; + dpp->weight_B = weight_B; +} + +#if (!defined(CPU_COLDFIRE) && !defined(CPU_ARM)) || defined(SIMULATOR) + +static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) +{ + int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B; + int32_t *bptr, *tptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B; + int k, i; + + switch (dpp->term) { + + case 17: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = 2 * bptr [-2] - bptr [-4]; + bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]); + update_weight (weight_A, delta, sam_A, sam_B); + + sam_A = 2 * bptr [-1] - bptr [-3]; + bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]); + update_weight (weight_B, delta, sam_A, sam_B); + } + + dpp->samples_B [0] = bptr [-1]; + dpp->samples_A [0] = bptr [-2]; + dpp->samples_B [1] = bptr [-3]; + dpp->samples_A [1] = bptr [-4]; + break; + + case 18: + for (bptr = buffer; bptr < eptr; bptr += 2) { + sam_A = (3 * bptr [-2] - bptr [-4]) >> 1; + bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]); + update_weight (weight_A, delta, sam_A, sam_B); + + sam_A = (3 * bptr [-1] - bptr [-3]) >> 1; + bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]); + update_weight (weight_B, delta, sam_A, sam_B); + } + + dpp->samples_B [0] = bptr [-1]; + dpp->samples_A [0] = bptr [-2]; + dpp->samples_B [1] = bptr [-3]; + dpp->samples_A [1] = bptr [-4]; + break; + + default: + for (bptr = buffer, tptr = buffer - (dpp->term * 2); bptr < eptr; bptr += 2, tptr += 2) { + bptr [0] = apply_weight (weight_A, tptr [0]) + (sam_A = bptr [0]); + update_weight (weight_A, delta, tptr [0], sam_A); + + bptr [1] = apply_weight (weight_B, tptr [1]) + (sam_A = bptr [1]); + update_weight (weight_B, delta, tptr [1], sam_A); + } + + for (k = dpp->term - 1, i = 8; i--; k--) { + dpp->samples_B [k & (MAX_TERM - 1)] = *--bptr; + dpp->samples_A [k & (MAX_TERM - 1)] = *--bptr; + } + + break; + + case -1: + for (bptr = buffer; bptr < eptr; bptr += 2) { + bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]); + update_weight_clip (weight_A, delta, bptr [-1], sam_A); + bptr [1] = apply_weight (weight_B, bptr [0]) + (sam_A = bptr [1]); + update_weight_clip (weight_B, delta, bptr [0], sam_A); + } + + dpp->samples_A [0] = bptr [-1]; + break; + + case -2: + for (bptr = buffer; bptr < eptr; bptr += 2) { + bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]); + update_weight_clip (weight_B, delta, bptr [-2], sam_A); + bptr [0] = apply_weight (weight_A, bptr [1]) + (sam_A = bptr [0]); + update_weight_clip (weight_A, delta, bptr [1], sam_A); + } + + dpp->samples_B [0] = bptr [-2]; + break; + + case -3: + for (bptr = buffer; bptr < eptr; bptr += 2) { + bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]); + update_weight_clip (weight_A, delta, bptr [-1], sam_A); + bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]); + update_weight_clip (weight_B, delta, bptr [-2], sam_A); + } + + dpp->samples_A [0] = bptr [-1]; + dpp->samples_B [0] = bptr [-2]; + break; + } + + dpp->weight_A = weight_A; + dpp->weight_B = weight_B; +} + +#endif + +static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) +{ + int32_t delta = dpp->delta, weight_A = dpp->weight_A; + int32_t *bptr, *eptr = buffer + sample_count, sam_A; + int m, k; + + switch (dpp->term) { + + case 17: + for (bptr = buffer; bptr < eptr; bptr++) { + sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1]; + dpp->samples_A [1] = dpp->samples_A [0]; + dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [0]; + } + + break; + + case 18: + for (bptr = buffer; bptr < eptr; bptr++) { + sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1; + dpp->samples_A [1] = dpp->samples_A [0]; + dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [0]; + } + + break; + + default: + for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr++) { + sam_A = dpp->samples_A [m]; + dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0]; + update_weight (weight_A, delta, sam_A, bptr [0]); + bptr [0] = dpp->samples_A [k]; + m = (m + 1) & (MAX_TERM - 1); + k = (k + 1) & (MAX_TERM - 1); + } + + if (m) { + int32_t temp_samples [MAX_TERM]; + + memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A)); + + for (k = 0; k < MAX_TERM; k++, m++) + dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)]; + } + + break; + } + + dpp->weight_A = weight_A; +} + + +// This is a helper function for unpack_samples() that applies several final +// operations. First, if the data is 32-bit float data, then that conversion +// is done in the float.c module (whether lossy or lossless) and we return. +// Otherwise, if the extended integer data applies, then that operation is +// executed first. If the unpacked data is lossy (and not corrected) then +// it is clipped and shifted in a single operation. Otherwise, if it's +// lossless then the last step is to apply the final shift (if any). + +static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count) +{ + uint32_t flags = wps->wphdr.flags; + int shift = (flags & SHIFT_MASK) >> SHIFT_LSB; + + if (flags & FLOAT_DATA) { + float_values (wps, buffer, (flags & MONO_FLAG) ? sample_count : sample_count * 2); + return; + } + + if (flags & INT32_DATA) { + uint32_t count = (flags & MONO_FLAG) ? sample_count : sample_count * 2; + int sent_bits = wps->int32_sent_bits, zeros = wps->int32_zeros; + int ones = wps->int32_ones, dups = wps->int32_dups; + int32_t *dptr = buffer; + + if (!(flags & HYBRID_FLAG) && !sent_bits && (zeros + ones + dups)) + while (count--) { + if (zeros) + *dptr <<= zeros; + else if (ones) + *dptr = ((*dptr + 1) << ones) - 1; + else if (dups) + *dptr = ((*dptr + (*dptr & 1)) << dups) - (*dptr & 1); + + dptr++; + } + else + shift += zeros + sent_bits + ones + dups; + } + + if (flags & HYBRID_FLAG) { + int32_t min_value, max_value, min_shifted, max_shifted; + + switch (flags & BYTES_STORED) { + case 0: + min_shifted = (min_value = -128 >> shift) << shift; + max_shifted = (max_value = 127 >> shift) << shift; + break; + + case 1: + min_shifted = (min_value = -32768 >> shift) << shift; + max_shifted = (max_value = 32767 >> shift) << shift; + break; + + case 2: + min_shifted = (min_value = -8388608 >> shift) << shift; + max_shifted = (max_value = 8388607 >> shift) << shift; + break; + + case 3: + default: + min_shifted = (min_value = (int32_t) 0x80000000 >> shift) << shift; + max_shifted = (max_value = (int32_t) 0x7FFFFFFF >> shift) << shift; + break; + } + + if (!(flags & MONO_FLAG)) + sample_count *= 2; + + while (sample_count--) { + if (*buffer < min_value) + *buffer++ = min_shifted; + else if (*buffer > max_value) + *buffer++ = max_shifted; + else + *buffer++ <<= shift; + } + } + else if (shift) { + if (!(flags & MONO_FLAG)) + sample_count *= 2; + + while (sample_count--) + *buffer++ <<= shift; + } +} + +// This function checks the crc value(s) for an unpacked block, returning the +// number of actual crc errors detected for the block. The block must be +// completely unpacked before this test is valid. For losslessly unpacked +// blocks of float or extended integer data the extended crc is also checked. +// Note that WavPack's crc is not a CCITT approved polynomial algorithm, but +// is a much simpler method that is virtually as robust for real world data. + +int check_crc_error (WavpackContext *wpc) +{ + WavpackStream *wps = &wpc->stream; + int result = 0; + + if (wps->crc != wps->wphdr.crc) + ++result; + + return result; +} diff --git a/src/engine/external/wavpack/wavpack.h b/src/engine/external/wavpack/wavpack.h new file mode 100644 index 0000000..2e22fc5 --- /dev/null +++ b/src/engine/external/wavpack/wavpack.h @@ -0,0 +1,384 @@ +/*////////////////////////////////////////////////////////////////////////// */ +/* **** WAVPACK **** // */ +/* Hybrid Lossless Wavefile Compressor // */ +/* Copyright (c) 1998 - 2004 Conifer Software. // */ +/* All Rights Reserved. // */ +/* Distributed under the BSD Software License (see license.txt) // */ +/*////////////////////////////////////////////////////////////////////////// */ + +/* wavpack.h */ + +#include <sys/types.h> + +/* This header file contains all the definitions required by WavPack. */ + +#ifdef __BORLANDC__ +typedef unsigned long uint32_t; +typedef long int32_t; +#elif defined(_WIN32) && !defined(__MINGW32__) +#include <stdlib.h> +typedef unsigned __int64 uint64_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef __int32 int32_t; +#else +#include <inttypes.h> +#endif + +typedef unsigned char uchar; + +#if !defined(__GNUC__) || defined(WIN32) +typedef unsigned short ushort; +typedef unsigned int uint; +#endif + +#include <stdio.h> + +#define FALSE 0 +#define TRUE 1 + +/*//////////////////////////// WavPack Header ///////////////////////////////// */ + +/* Note that this is the ONLY structure that is written to (or read from) */ +/* WavPack 4.0 files, and is the preamble to every block in both the .wv */ +/* and .wvc files. */ + +typedef struct { + char ckID [4]; + uint32_t ckSize; + short version; + uchar track_no, index_no; + uint32_t total_samples, block_index, block_samples, flags, crc; +} WavpackHeader; + +#define WavpackHeaderFormat "4LS2LLLLL" + +/* or-values for "flags" */ + +#define BYTES_STORED 3 /* 1-4 bytes/sample */ +#define MONO_FLAG 4 /* not stereo */ +#define HYBRID_FLAG 8 /* hybrid mode */ +#define JOINT_STEREO 0x10 /* joint stereo */ +#define CROSS_DECORR 0x20 /* no-delay cross decorrelation */ +#define HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */ +#define FLOAT_DATA 0x80 /* ieee 32-bit floating point data */ + +#define INT32_DATA 0x100 /* special extended int handling */ +#define HYBRID_BITRATE 0x200 /* bitrate noise (hybrid mode only) */ +#define HYBRID_BALANCE 0x400 /* balance noise (hybrid stereo mode only) */ + +#define INITIAL_BLOCK 0x800 /* initial block of multichannel segment */ +#define FINAL_BLOCK 0x1000 /* final block of multichannel segment */ + +#define SHIFT_LSB 13 +#define SHIFT_MASK (0x1fL << SHIFT_LSB) + +#define MAG_LSB 18 +#define MAG_MASK (0x1fL << MAG_LSB) + +#define SRATE_LSB 23 +#define SRATE_MASK (0xfL << SRATE_LSB) + +#define FALSE_STEREO 0x40000000 /* block is stereo, but data is mono */ + +#define IGNORED_FLAGS 0x18000000 /* reserved, but ignore if encountered */ +#define NEW_SHAPING 0x20000000 /* use IIR filter for negative shaping */ +#define UNKNOWN_FLAGS 0x80000000 /* also reserved, but refuse decode if */ + /* encountered */ + +#define MONO_DATA (MONO_FLAG | FALSE_STEREO) + +#define MIN_STREAM_VERS 0x402 /* lowest stream version we'll decode */ +#define MAX_STREAM_VERS 0x410 /* highest stream version we'll decode */ + +/*////////////////////////// WavPack Metadata ///////////////////////////////// */ + +/* This is an internal representation of metadata. */ + +typedef struct { + int32_t byte_length; + void *data; + uchar id; +} WavpackMetadata; + +#define ID_OPTIONAL_DATA 0x20 +#define ID_ODD_SIZE 0x40 +#define ID_LARGE 0x80 + +#define ID_DUMMY 0x0 +#define ID_ENCODER_INFO 0x1 +#define ID_DECORR_TERMS 0x2 +#define ID_DECORR_WEIGHTS 0x3 +#define ID_DECORR_SAMPLES 0x4 +#define ID_ENTROPY_VARS 0x5 +#define ID_HYBRID_PROFILE 0x6 +#define ID_SHAPING_WEIGHTS 0x7 +#define ID_FLOAT_INFO 0x8 +#define ID_INT32_INFO 0x9 +#define ID_WV_BITSTREAM 0xa +#define ID_WVC_BITSTREAM 0xb +#define ID_WVX_BITSTREAM 0xc +#define ID_CHANNEL_INFO 0xd + +#define ID_RIFF_HEADER (ID_OPTIONAL_DATA | 0x1) +#define ID_RIFF_TRAILER (ID_OPTIONAL_DATA | 0x2) +#define ID_REPLAY_GAIN (ID_OPTIONAL_DATA | 0x3) +#define ID_CUESHEET (ID_OPTIONAL_DATA | 0x4) +#define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) +#define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) + +/*/////////////////////// WavPack Configuration /////////////////////////////// */ + +/* This internal structure is used during encode to provide configuration to */ +/* the encoding engine and during decoding to provide fle information back to */ +/* the higher level functions. Not all fields are used in both modes. */ + +typedef struct { + int bits_per_sample, bytes_per_sample; + int num_channels, float_norm_exp; + uint32_t flags, sample_rate, channel_mask; +} WavpackConfig; + +#define CONFIG_BYTES_STORED 3 /* 1-4 bytes/sample */ +#define CONFIG_MONO_FLAG 4 /* not stereo */ +#define CONFIG_HYBRID_FLAG 8 /* hybrid mode */ +#define CONFIG_JOINT_STEREO 0x10 /* joint stereo */ +#define CONFIG_CROSS_DECORR 0x20 /* no-delay cross decorrelation */ +#define CONFIG_HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */ +#define CONFIG_FLOAT_DATA 0x80 /* ieee 32-bit floating point data */ + +#define CONFIG_FAST_FLAG 0x200 /* fast mode */ +#define CONFIG_HIGH_FLAG 0x800 /* high quality mode */ +#define CONFIG_VERY_HIGH_FLAG 0x1000 /* very high */ +#define CONFIG_BITRATE_KBPS 0x2000 /* bitrate is kbps, not bits / sample */ +#define CONFIG_AUTO_SHAPING 0x4000 /* automatic noise shaping */ +#define CONFIG_SHAPE_OVERRIDE 0x8000 /* shaping mode specified */ +#define CONFIG_JOINT_OVERRIDE 0x10000 /* joint-stereo mode specified */ +#define CONFIG_CREATE_EXE 0x40000 /* create executable */ +#define CONFIG_CREATE_WVC 0x80000 /* create correction file */ +#define CONFIG_OPTIMIZE_WVC 0x100000 /* maximize bybrid compression */ +#define CONFIG_CALC_NOISE 0x800000 /* calc noise in hybrid mode */ +#define CONFIG_LOSSY_MODE 0x1000000 /* obsolete (for information) */ +#define CONFIG_EXTRA_MODE 0x2000000 /* extra processing mode */ +#define CONFIG_SKIP_WVX 0x4000000 /* no wvx stream w/ floats & big ints */ +#define CONFIG_MD5_CHECKSUM 0x8000000 /* compute & store MD5 signature */ +#define CONFIG_OPTIMIZE_MONO 0x80000000 /* optimize for mono streams posing as stereo */ + +/*////////////////////////////// WavPack Stream /////////////////////////////// */ + +/* This internal structure contains everything required to handle a WavPack */ +/* "stream", which is defined as a stereo or mono stream of audio samples. For */ +/* multichannel audio several of these would be required. Each stream contains */ +/* pointers to hold a complete allocated block of WavPack data, although it's */ +/* possible to decode WavPack blocks without buffering an entire block. */ + +typedef int32_t (*read_stream)(void *, int32_t); + +typedef struct bs { + uchar *buf, *end, *ptr; + void (*wrap)(struct bs *bs); + uint32_t file_bytes, sr; + int error, bc; + read_stream file; +} Bitstream; + +#define MAX_NTERMS 16 +#define MAX_TERM 8 + +struct decorr_pass { + short term, delta, weight_A, weight_B; + int32_t samples_A [MAX_TERM], samples_B [MAX_TERM]; +}; + +struct entropy_data { + uint32_t median [3], slow_level, error_limit; +}; + +struct words_data { + uint32_t bitrate_delta [2], bitrate_acc [2]; + uint32_t pend_data, holding_one, zeros_acc; + int holding_zero, pend_count; + struct entropy_data c [2]; +}; + +typedef struct { + WavpackHeader wphdr; + Bitstream wvbits; + + struct words_data w; + + int num_terms, mute_error; + uint32_t sample_index, crc; + + uchar int32_sent_bits, int32_zeros, int32_ones, int32_dups; + uchar float_flags, float_shift, float_max_exp, float_norm_exp; + + struct decorr_pass decorr_passes [MAX_NTERMS]; + +} WavpackStream; + +/* flags for float_flags: */ + +#define FLOAT_SHIFT_ONES 1 /* bits left-shifted into float = '1' */ +#define FLOAT_SHIFT_SAME 2 /* bits left-shifted into float are the same */ +#define FLOAT_SHIFT_SENT 4 /* bits shifted into float are sent literally */ +#define FLOAT_ZEROS_SENT 8 /* "zeros" are not all real zeros */ +#define FLOAT_NEG_ZEROS 0x10 /* contains negative zeros */ +#define FLOAT_EXCEPTIONS 0x20 /* contains exceptions (inf, nan, etc.) */ + +/*///////////////////////////// WavPack Context /////////////////////////////// */ + +/* This internal structure holds everything required to encode or decode WavPack */ +/* files. It is recommended that direct access to this structure be minimized */ +/* and the provided utilities used instead. */ + +typedef struct { + WavpackConfig config; + WavpackStream stream; + + uchar read_buffer [1024]; + char error_message [80]; + + read_stream infile; + uint32_t total_samples, crc_errors, first_flags; + int open_flags, norm_offset, reduced_channels, lossy_blocks; + +} WavpackContext; + +/*////////////////////// function prototypes and macros ////////////////////// */ + +#define CLEAR(destin) memset (&destin, 0, sizeof (destin)); + +/* bits.c */ + +void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes); + +#define bs_is_open(bs) ((bs)->ptr != NULL) + +#define getbit(bs) ( \ + (((bs)->bc) ? \ + ((bs)->bc--, (bs)->sr & 1) : \ + (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = 7, ((bs)->sr = *((bs)->ptr)) & 1) \ + ) ? \ + ((bs)->sr >>= 1, 1) : \ + ((bs)->sr >>= 1, 0) \ +) + +#define getbits(value, nbits, bs) { \ + while ((nbits) > (bs)->bc) { \ + if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ + (bs)->sr |= (int32_t)*((bs)->ptr) << (bs)->bc; \ + (bs)->bc += 8; \ + } \ + *(value) = (bs)->sr; \ + if ((bs)->bc > 32) { \ + (bs)->bc -= (nbits); \ + (bs)->sr = *((bs)->ptr) >> (8 - (bs)->bc); \ + } \ + else { \ + (bs)->bc -= (nbits); \ + (bs)->sr >>= (nbits); \ + } \ +} + +void little_endian_to_native (void *data, char *format); +void native_to_little_endian (void *data, char *format); + +/* These macros implement the weight application and update operations */ +/* that are at the heart of the decorrelation loops. Note that when there */ +/* are several alternative versions of the same macro (marked with PERFCOND) */ +/* then the versions are functionally equivalent with respect to WavPack */ +/* decoding and the user should choose the one that provides the best */ +/* performance. This may be easier to check when NOT using the assembly */ +/* language optimizations. */ + +#if 1 /* PERFCOND */ +#define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10) +#else +#define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2) +#endif + +#define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \ + (((sample & ~0xffffL) >> 9) * weight) + 1) >> 1) + +#if 1 /* PERFCOND */ +#define apply_weight(weight, sample) (sample != (short) sample ? \ + apply_weight_f (weight, sample) : apply_weight_i (weight, sample)) +#else +#define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10)) +#endif + +#if 0 /* PERFCOND */ +#define update_weight(weight, delta, source, result) \ + if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); } +#elif 1 +#define update_weight(weight, delta, source, result) \ + if (source && result) weight += (((source ^ result) >> 30) | 1) * delta +#else +#define update_weight(weight, delta, source, result) \ + if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta) +#endif + +#define update_weight_clip(weight, delta, source, result) \ + if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \ + weight = weight < 0 ? -1024 : 1024 + +/* unpack.c */ + +int unpack_init (WavpackContext *wpc); +int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd); +int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd); +int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd); +int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd); +int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); +int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd); +int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd); +int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd); +int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count); +int check_crc_error (WavpackContext *wpc); + +/* metadata.c stuff */ + +int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd); +int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd); + +/* words.c stuff */ + +int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd); +int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd); +int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags, + struct words_data *w, Bitstream *bs); +int32_t exp2s (int log); +int restore_weight (signed char weight); + +#define WORD_EOF (1L << 31) + +/* float.c */ + +int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); +void float_values (WavpackStream *wps, int32_t *values, int32_t num_values); + +/* wputils.c */ + +WavpackContext *WavpackOpenFileInput (read_stream infile, char *error); + +int WavpackGetMode (WavpackContext *wpc); + +#define MODE_WVC 0x1 +#define MODE_LOSSLESS 0x2 +#define MODE_HYBRID 0x4 +#define MODE_FLOAT 0x8 +#define MODE_VALID_TAG 0x10 +#define MODE_HIGH 0x20 +#define MODE_FAST 0x40 + +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples); +uint32_t WavpackGetNumSamples (WavpackContext *wpc); +uint32_t WavpackGetSampleIndex (WavpackContext *wpc); +int WavpackGetNumErrors (WavpackContext *wpc); +int WavpackLossyBlocks (WavpackContext *wpc); +uint32_t WavpackGetSampleRate (WavpackContext *wpc); +int WavpackGetBitsPerSample (WavpackContext *wpc); +int WavpackGetBytesPerSample (WavpackContext *wpc); +int WavpackGetNumChannels (WavpackContext *wpc); +int WavpackGetReducedChannels (WavpackContext *wpc); diff --git a/src/engine/external/wavpack/words.c b/src/engine/external/wavpack/words.c new file mode 100644 index 0000000..d39563b --- /dev/null +++ b/src/engine/external/wavpack/words.c @@ -0,0 +1,560 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// words.c + +// This module provides entropy word encoding and decoding functions using +// a variation on the Rice method. This was introduced in version 3.93 +// because it allows splitting the data into a "lossy" stream and a +// "correction" stream in a very efficient manner and is therefore ideal +// for the "hybrid" mode. For 4.0, the efficiency of this method was +// significantly improved by moving away from the normal Rice restriction of +// using powers of two for the modulus divisions and now the method can be +// used for both hybrid and pure lossless encoding. + +// Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%), +// and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the +// previous. Using standard Rice coding on this data would result in 1.4 +// bits per sample average (not counting sign bit). However, there is a +// very simple encoding that is over 99% efficient with this data and +// results in about 1.22 bits per sample. + +#include "wavpack.h" + +#include <string.h> + +//////////////////////////////// local macros ///////////////////////////////// + +#define LIMIT_ONES 16 // maximum consecutive 1s sent for "div" data + +// these control the time constant "slow_level" which is used for hybrid mode +// that controls bitrate as a function of residual level (HYBRID_BITRATE). +#define SLS 8 +#define SLO ((1 << (SLS - 1))) + +// these control the time constant of the 3 median level breakpoints +#define DIV0 128 // 5/7 of samples +#define DIV1 64 // 10/49 of samples +#define DIV2 32 // 20/343 of samples + +// this macro retrieves the specified median breakpoint (without frac; min = 1) +#define GET_MED(med) (((c->median [med]) >> 4) + 1) + +// These macros update the specified median breakpoints. Note that the median +// is incremented when the sample is higher than the median, else decremented. +// They are designed so that the median will never drop below 1 and the value +// is essentially stationary if there are 2 increments for every 5 decrements. + +#define INC_MED0() (c->median [0] += ((c->median [0] + DIV0) / DIV0) * 5) +#define DEC_MED0() (c->median [0] -= ((c->median [0] + (DIV0-2)) / DIV0) * 2) +#define INC_MED1() (c->median [1] += ((c->median [1] + DIV1) / DIV1) * 5) +#define DEC_MED1() (c->median [1] -= ((c->median [1] + (DIV1-2)) / DIV1) * 2) +#define INC_MED2() (c->median [2] += ((c->median [2] + DIV2) / DIV2) * 5) +#define DEC_MED2() (c->median [2] -= ((c->median [2] + (DIV2-2)) / DIV2) * 2) + +#define count_bits(av) ( \ + (av) < (1 << 8) ? nbits_table [av] : \ + ( \ + (av) < (1L << 16) ? nbits_table [(av) >> 8] + 8 : \ + ((av) < (1L << 24) ? nbits_table [(av) >> 16] + 16 : nbits_table [(av) >> 24] + 24) \ + ) \ +) + +///////////////////////////// local table storage //////////////////////////// + +const char nbits_table [] = { + 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, // 0 - 15 + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, // 16 - 31 + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, // 32 - 47 + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, // 48 - 63 + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 64 - 79 + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 80 - 95 + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 96 - 111 + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 112 - 127 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 128 - 143 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 144 - 159 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 160 - 175 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 176 - 191 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 192 - 207 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 208 - 223 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 224 - 239 + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 // 240 - 255 +}; + +static const uchar log2_table [] = { + 0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15, + 0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a, + 0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, + 0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51, + 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75, + 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, + 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, + 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, + 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2, + 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0, + 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce, + 0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb, + 0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7, + 0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4, + 0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff +}; + +static const uchar exp2_table [] = { + 0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16, + 0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23, + 0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d, + 0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b, + 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, + 0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a, + 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, + 0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, + 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, + 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4, + 0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9, + 0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff +}; + +static const char ones_count_table [] = { + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, + 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8 +}; + +///////////////////////////// executable code //////////////////////////////// + +void init_words (WavpackStream *wps) +{ + CLEAR (wps->w); +} + +static int mylog2 (uint32_t avalue); + +// Read the median log2 values from the specifed metadata structure, convert +// them back to 32-bit unsigned values and store them. If length is not +// exactly correct then we flag and return an error. + +int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd) +{ + uchar *byteptr = wpmd->data; + + if (wpmd->byte_length != ((wps->wphdr.flags & MONO_DATA) ? 6 : 12)) + return FALSE; + + wps->w.c [0].median [0] = exp2s (byteptr [0] + (byteptr [1] << 8)); + wps->w.c [0].median [1] = exp2s (byteptr [2] + (byteptr [3] << 8)); + wps->w.c [0].median [2] = exp2s (byteptr [4] + (byteptr [5] << 8)); + + if (!(wps->wphdr.flags & MONO_DATA)) { + wps->w.c [1].median [0] = exp2s (byteptr [6] + (byteptr [7] << 8)); + wps->w.c [1].median [1] = exp2s (byteptr [8] + (byteptr [9] << 8)); + wps->w.c [1].median [2] = exp2s (byteptr [10] + (byteptr [11] << 8)); + } + + return TRUE; +} + +// Read the hybrid related values from the specifed metadata structure, convert +// them back to their internal formats and store them. The extended profile +// stuff is not implemented yet, so return an error if we get more data than +// we know what to do with. + +int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd) +{ + uchar *byteptr = wpmd->data; + uchar *endptr = byteptr + wpmd->byte_length; + + if (wps->wphdr.flags & HYBRID_BITRATE) { + wps->w.c [0].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8)); + byteptr += 2; + + if (!(wps->wphdr.flags & MONO_DATA)) { + wps->w.c [1].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8)); + byteptr += 2; + } + } + + wps->w.bitrate_acc [0] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16; + byteptr += 2; + + if (!(wps->wphdr.flags & MONO_DATA)) { + wps->w.bitrate_acc [1] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16; + byteptr += 2; + } + + if (byteptr < endptr) { + wps->w.bitrate_delta [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + byteptr += 2; + + if (!(wps->wphdr.flags & MONO_DATA)) { + wps->w.bitrate_delta [1] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); + byteptr += 2; + } + + if (byteptr < endptr) + return FALSE; + } + else + wps->w.bitrate_delta [0] = wps->w.bitrate_delta [1] = 0; + + return TRUE; +} + +// This function is called during both encoding and decoding of hybrid data to +// update the "error_limit" variable which determines the maximum sample error +// allowed in the main bitstream. In the HYBRID_BITRATE mode (which is the only +// currently implemented) this is calculated from the slow_level values and the +// bitrate accumulators. Note that the bitrate accumulators can be changing. + +void update_error_limit (struct words_data *w, uint32_t flags) +{ + int bitrate_0 = (w->bitrate_acc [0] += w->bitrate_delta [0]) >> 16; + + if (flags & MONO_DATA) { + if (flags & HYBRID_BITRATE) { + int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS; + + if (slow_log_0 - bitrate_0 > -0x100) + w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100); + else + w->c [0].error_limit = 0; + } + else + w->c [0].error_limit = exp2s (bitrate_0); + } + else { + int bitrate_1 = (w->bitrate_acc [1] += w->bitrate_delta [1]) >> 16; + + if (flags & HYBRID_BITRATE) { + int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS; + int slow_log_1 = (w->c [1].slow_level + SLO) >> SLS; + + if (flags & HYBRID_BALANCE) { + int balance = (slow_log_1 - slow_log_0 + bitrate_1 + 1) >> 1; + + if (balance > bitrate_0) { + bitrate_1 = bitrate_0 * 2; + bitrate_0 = 0; + } + else if (-balance > bitrate_0) { + bitrate_0 = bitrate_0 * 2; + bitrate_1 = 0; + } + else { + bitrate_1 = bitrate_0 + balance; + bitrate_0 = bitrate_0 - balance; + } + } + + if (slow_log_0 - bitrate_0 > -0x100) + w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100); + else + w->c [0].error_limit = 0; + + if (slow_log_1 - bitrate_1 > -0x100) + w->c [1].error_limit = exp2s (slow_log_1 - bitrate_1 + 0x100); + else + w->c [1].error_limit = 0; + } + else { + w->c [0].error_limit = exp2s (bitrate_0); + w->c [1].error_limit = exp2s (bitrate_1); + } + } +} + +static uint32_t read_code (Bitstream *bs, uint32_t maxcode); + +// Read the next word from the bitstream "wvbits" and return the value. This +// function can be used for hybrid or lossless streams, but since an +// optimized version is available for lossless this function would normally +// be used for hybrid only. If a hybrid lossless stream is being read then +// the "correction" offset is written at the specified pointer. A return value +// of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or +// some other error occurred. + +int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags, + struct words_data *w, Bitstream *bs) +{ + register struct entropy_data *c = w->c; + int csamples; + + if (!(flags & MONO_DATA)) + nsamples *= 2; + + for (csamples = 0; csamples < nsamples; ++csamples) { + uint32_t ones_count, low, mid, high; + + if (!(flags & MONO_DATA)) + c = w->c + (csamples & 1); + + if (!(w->c [0].median [0] & ~1) && !w->holding_zero && !w->holding_one && !(w->c [1].median [0] & ~1)) { + uint32_t mask; + int cbits; + + if (w->zeros_acc) { + if (--w->zeros_acc) { + c->slow_level -= (c->slow_level + SLO) >> SLS; + *buffer++ = 0; + continue; + } + } + else { + for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); + + if (cbits == 33) + break; + + if (cbits < 2) + w->zeros_acc = cbits; + else { + for (mask = 1, w->zeros_acc = 0; --cbits; mask <<= 1) + if (getbit (bs)) + w->zeros_acc |= mask; + + w->zeros_acc |= mask; + } + + if (w->zeros_acc) { + c->slow_level -= (c->slow_level + SLO) >> SLS; + CLEAR (w->c [0].median); + CLEAR (w->c [1].median); + *buffer++ = 0; + continue; + } + } + } + + if (w->holding_zero) + ones_count = w->holding_zero = 0; + else { + int next8; + + if (bs->bc < 8) { + if (++(bs->ptr) == bs->end) + bs->wrap (bs); + + next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff; + bs->bc += 8; + } + else + next8 = bs->sr & 0xff; + + if (next8 == 0xff) { + bs->bc -= 8; + bs->sr >>= 8; + + for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count); + + if (ones_count == (LIMIT_ONES + 1)) + break; + + if (ones_count == LIMIT_ONES) { + uint32_t mask; + int cbits; + + for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); + + if (cbits == 33) + break; + + if (cbits < 2) + ones_count = cbits; + else { + for (mask = 1, ones_count = 0; --cbits; mask <<= 1) + if (getbit (bs)) + ones_count |= mask; + + ones_count |= mask; + } + + ones_count += LIMIT_ONES; + } + } + else { + bs->bc -= (ones_count = ones_count_table [next8]) + 1; + bs->sr >>= ones_count + 1; + } + + if (w->holding_one) { + w->holding_one = ones_count & 1; + ones_count = (ones_count >> 1) + 1; + } + else { + w->holding_one = ones_count & 1; + ones_count >>= 1; + } + + w->holding_zero = ~w->holding_one & 1; + } + + if ((flags & HYBRID_FLAG) && ((flags & MONO_DATA) || !(csamples & 1))) + update_error_limit (w, flags); + + if (ones_count == 0) { + low = 0; + high = GET_MED (0) - 1; + DEC_MED0 (); + } + else { + low = GET_MED (0); + INC_MED0 (); + + if (ones_count == 1) { + high = low + GET_MED (1) - 1; + DEC_MED1 (); + } + else { + low += GET_MED (1); + INC_MED1 (); + + if (ones_count == 2) { + high = low + GET_MED (2) - 1; + DEC_MED2 (); + } + else { + low += (ones_count - 2) * GET_MED (2); + high = low + GET_MED (2) - 1; + INC_MED2 (); + } + } + } + + mid = (high + low + 1) >> 1; + + if (!c->error_limit) + mid = read_code (bs, high - low) + low; + else while (high - low > c->error_limit) { + if (getbit (bs)) + mid = (high + (low = mid) + 1) >> 1; + else + mid = ((high = mid - 1) + low + 1) >> 1; + } + + *buffer++ = getbit (bs) ? ~mid : mid; + + if (flags & HYBRID_BITRATE) + c->slow_level = c->slow_level - ((c->slow_level + SLO) >> SLS) + mylog2 (mid); + } + + return (flags & MONO_DATA) ? csamples : (csamples / 2); +} + +// Read a single unsigned value from the specified bitstream with a value +// from 0 to maxcode. If there are exactly a power of two number of possible +// codes then this will read a fixed number of bits; otherwise it reads the +// minimum number of bits and then determines whether another bit is needed +// to define the code. + +static uint32_t read_code (Bitstream *bs, uint32_t maxcode) +{ + int bitcount = count_bits (maxcode); + uint32_t extras = (1L << bitcount) - maxcode - 1, code; + + if (!bitcount) + return 0; + + getbits (&code, bitcount - 1, bs); + code &= (1L << (bitcount - 1)) - 1; + + if (code >= extras) { + code = (code << 1) - extras; + + if (getbit (bs)) + ++code; + } + + return code; +} + +// The concept of a base 2 logarithm is used in many parts of WavPack. It is +// a way of sufficiently accurately representing 32-bit signed and unsigned +// values storing only 16 bits (actually fewer). It is also used in the hybrid +// mode for quickly comparing the relative magnitude of large values (i.e. +// division) and providing smooth exponentials using only addition. + +// These are not strict logarithms in that they become linear around zero and +// can therefore represent both zero and negative values. They have 8 bits +// of precision and in "roundtrip" conversions the total error never exceeds 1 +// part in 225 except for the cases of +/-115 and +/-195 (which error by 1). + + +// This function returns the log2 for the specified 32-bit unsigned value. +// The maximum value allowed is about 0xff800000 and returns 8447. + +static int mylog2 (uint32_t avalue) +{ + int dbits; + + if ((avalue += avalue >> 9) < (1 << 8)) { + dbits = nbits_table [avalue]; + return (dbits << 8) + log2_table [(avalue << (9 - dbits)) & 0xff]; + } + else { + if (avalue < (1L << 16)) + dbits = nbits_table [avalue >> 8] + 8; + else if (avalue < (1L << 24)) + dbits = nbits_table [avalue >> 16] + 16; + else + dbits = nbits_table [avalue >> 24] + 24; + + return (dbits << 8) + log2_table [(avalue >> (dbits - 9)) & 0xff]; + } +} + +// This function returns the log2 for the specified 32-bit signed value. +// All input values are valid and the return values are in the range of +// +/- 8192. + +int log2s (int32_t value) +{ + return (value < 0) ? -mylog2 (-value) : mylog2 (value); +} + +// This function returns the original integer represented by the supplied +// logarithm (at least within the provided accuracy). The log is signed, +// but since a full 32-bit value is returned this can be used for unsigned +// conversions as well (i.e. the input range is -8192 to +8447). + +int32_t exp2s (int log) +{ + uint32_t value; + + if (log < 0) + return -exp2s (-log); + + value = exp2_table [log & 0xff] | 0x100; + + if ((log >>= 8) <= 9) + return value >> (9 - log); + else + return value << (log - 9); +} + +// These two functions convert internal weights (which are normally +/-1024) +// to and from an 8-bit signed character version for storage in metadata. The +// weights are clipped here in the case that they are outside that range. + +int restore_weight (signed char weight) +{ + int result; + + if ((result = (int) weight << 3) > 0) + result += (result + 64) >> 7; + + return result; +} diff --git a/src/engine/external/wavpack/wputils.c b/src/engine/external/wavpack/wputils.c new file mode 100644 index 0000000..1bc6561 --- /dev/null +++ b/src/engine/external/wavpack/wputils.c @@ -0,0 +1,351 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wputils.c + +// This module provides a high-level interface for decoding WavPack 4.0 audio +// streams and files. WavPack data is read with a stream reading callback. No +// direct seeking is provided for, but it is possible to start decoding +// anywhere in a WavPack stream. In this case, WavPack will be able to provide +// the sample-accurate position when it synchs with the data and begins +// decoding. + +#include "wavpack.h" + +#include <string.h> + +///////////////////////////// local table storage //////////////////////////// + +const uint32_t sample_rates [] = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, + 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 }; + +///////////////////////////// executable code //////////////////////////////// + +static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr); + +// This function reads data from the specified stream in search of a valid +// WavPack 4.0 audio block. If this fails in 1 megabyte (or an invalid or +// unsupported WavPack block is encountered) then an appropriate message is +// copied to "error" and NULL is returned, otherwise a pointer to a +// WavpackContext structure is returned (which is used to call all other +// functions in this module). This can be initiated at the beginning of a +// WavPack file, or anywhere inside a WavPack file. To determine the exact +// position within the file use WavpackGetSampleIndex(). For demonstration +// purposes this uses a single static copy of the WavpackContext structure, +// so obviously it cannot be used for more than one file at a time. Also, +// this function will not handle "correction" files, plays only the first +// two channels of multi-channel files, and is limited in resolution in some +// large integer or floating point files (but always provides at least 24 bits +// of resolution). + +static WavpackContext wpc; + +WavpackContext *WavpackOpenFileInput (read_stream infile, char *error) +{ + WavpackStream *wps = &wpc.stream; + uint32_t bcount; + + CLEAR (wpc); + wpc.infile = infile; + wpc.total_samples = (uint32_t) -1; + wpc.norm_offset = 0; + wpc.open_flags = 0; + + // open the source file for reading and store the size + + while (!wps->wphdr.block_samples) { + + bcount = read_next_header (wpc.infile, &wps->wphdr); + + if (bcount == (uint32_t) -1) { + strcpy (error, "not compatible with this version of WavPack file!"); + return NULL; + } + + if (wps->wphdr.block_samples && wps->wphdr.total_samples != (uint32_t) -1) + wpc.total_samples = wps->wphdr.total_samples; + + if (!unpack_init (&wpc)) { + strcpy (error, wpc.error_message [0] ? wpc.error_message : + "not compatible with this version of WavPack file!"); + + return NULL; + } + } + + wpc.config.flags &= ~0xff; + wpc.config.flags |= wps->wphdr.flags & 0xff; + wpc.config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1; + wpc.config.float_norm_exp = wps->float_norm_exp; + + wpc.config.bits_per_sample = (wpc.config.bytes_per_sample * 8) - + ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB); + + if (wpc.config.flags & FLOAT_DATA) { + wpc.config.bytes_per_sample = 3; + wpc.config.bits_per_sample = 24; + } + + if (!wpc.config.sample_rate) { + if (!wps || !wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK) + wpc.config.sample_rate = 44100; + else + wpc.config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB]; + } + + if (!wpc.config.num_channels) { + wpc.config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; + wpc.config.channel_mask = 0x5 - wpc.config.num_channels; + } + + if (!(wps->wphdr.flags & FINAL_BLOCK)) + wpc.reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; + + return &wpc; +} + +// This function obtains general information about an open file and returns +// a mask with the following bit values: + +// MODE_LOSSLESS: file is lossless (pure lossless only) +// MODE_HYBRID: file is hybrid mode (lossy part only) +// MODE_FLOAT: audio data is 32-bit ieee floating point (but will provided +// in 24-bit integers for convenience) +// MODE_HIGH: file was created in "high" mode (information only) +// MODE_FAST: file was created in "fast" mode (information only) + +int WavpackGetMode (WavpackContext *wpc) +{ + int mode = 0; + + if (wpc) { + if (wpc->config.flags & CONFIG_HYBRID_FLAG) + mode |= MODE_HYBRID; + else if (!(wpc->config.flags & CONFIG_LOSSY_MODE)) + mode |= MODE_LOSSLESS; + + if (wpc->lossy_blocks) + mode &= ~MODE_LOSSLESS; + + if (wpc->config.flags & CONFIG_FLOAT_DATA) + mode |= MODE_FLOAT; + + if (wpc->config.flags & CONFIG_HIGH_FLAG) + mode |= MODE_HIGH; + + if (wpc->config.flags & CONFIG_FAST_FLAG) + mode |= MODE_FAST; + } + + return mode; +} + +// Unpack the specified number of samples from the current file position. +// Note that "samples" here refers to "complete" samples, which would be +// 2 longs for stereo files. The audio data is returned right-justified in +// 32-bit longs in the endian mode native to the executing processor. So, +// if the original data was 16-bit, then the values returned would be +// +/-32k. Floating point data will be returned as 24-bit integers (and may +// also be clipped). The actual number of samples unpacked is returned, +// which should be equal to the number requested unless the end of fle is +// encountered or an error occurs. + +uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples) +{ + WavpackStream *wps = &wpc->stream; + uint32_t bcount, samples_unpacked = 0, samples_to_unpack; + int num_channels = wpc->config.num_channels; + + while (samples) { + if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || + wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) { + bcount = read_next_header (wpc->infile, &wps->wphdr); + + if (bcount == (uint32_t) -1) + break; + + if (!wps->wphdr.block_samples || wps->sample_index == wps->wphdr.block_index) + if (!unpack_init (wpc)) + break; + } + + if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || + wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) + continue; + + if (wps->sample_index < wps->wphdr.block_index) { + samples_to_unpack = wps->wphdr.block_index - wps->sample_index; + + if (samples_to_unpack > samples) + samples_to_unpack = samples; + + wps->sample_index += samples_to_unpack; + samples_unpacked += samples_to_unpack; + samples -= samples_to_unpack; + + if (wpc->reduced_channels) + samples_to_unpack *= wpc->reduced_channels; + else + samples_to_unpack *= num_channels; + + while (samples_to_unpack--) + *buffer++ = 0; + + continue; + } + + samples_to_unpack = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index; + + if (samples_to_unpack > samples) + samples_to_unpack = samples; + + unpack_samples (wpc, buffer, samples_to_unpack); + + if (wpc->reduced_channels) + buffer += samples_to_unpack * wpc->reduced_channels; + else + buffer += samples_to_unpack * num_channels; + + samples_unpacked += samples_to_unpack; + samples -= samples_to_unpack; + + if (wps->sample_index == wps->wphdr.block_index + wps->wphdr.block_samples) { + if (check_crc_error (wpc)) + wpc->crc_errors++; + } + + if (wps->sample_index == wpc->total_samples) + break; + } + + return samples_unpacked; +} + +// Get total number of samples contained in the WavPack file, or -1 if unknown + +uint32_t WavpackGetNumSamples (WavpackContext *wpc) +{ + return wpc ? wpc->total_samples : (uint32_t) -1; +} + +// Get the current sample index position, or -1 if unknown + +uint32_t WavpackGetSampleIndex (WavpackContext *wpc) +{ + if (wpc) + return wpc->stream.sample_index; + + return (uint32_t) -1; +} + +// Get the number of errors encountered so far + +int WavpackGetNumErrors (WavpackContext *wpc) +{ + return wpc ? wpc->crc_errors : 0; +} + +// return TRUE if any uncorrected lossy blocks were actually written or read + +int WavpackLossyBlocks (WavpackContext *wpc) +{ + return wpc ? wpc->lossy_blocks : 0; +} + +// Returns the sample rate of the specified WavPack file + +uint32_t WavpackGetSampleRate (WavpackContext *wpc) +{ + return wpc ? wpc->config.sample_rate : 44100; +} + +// Returns the number of channels of the specified WavPack file. Note that +// this is the actual number of channels contained in the file, but this +// version can only decode the first two. + +int WavpackGetNumChannels (WavpackContext *wpc) +{ + return wpc ? wpc->config.num_channels : 2; +} + +// Returns the actual number of valid bits per sample contained in the +// original file, which may or may not be a multiple of 8. Floating data +// always has 32 bits, integers may be from 1 to 32 bits each. When this +// value is not a multiple of 8, then the "extra" bits are located in the +// LSBs of the results. That is, values are right justified when unpacked +// into longs, but are left justified in the number of bytes used by the +// original data. + +int WavpackGetBitsPerSample (WavpackContext *wpc) +{ + return wpc ? wpc->config.bits_per_sample : 16; +} + +// Returns the number of bytes used for each sample (1 to 4) in the original +// file. This is required information for the user of this module because the +// audio data is returned in the LOWER bytes of the long buffer and must be +// left-shifted 8, 16, or 24 bits if normalized longs are required. + +int WavpackGetBytesPerSample (WavpackContext *wpc) +{ + return wpc ? wpc->config.bytes_per_sample : 2; +} + +// This function will return the actual number of channels decoded from the +// file (which may or may not be less than the actual number of channels, but +// will always be 1 or 2). Normally, this will be the front left and right +// channels of a multi-channel file. + +int WavpackGetReducedChannels (WavpackContext *wpc) +{ + if (wpc) + return wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels; + else + return 2; +} + +// Read from current file position until a valid 32-byte WavPack 4.0 header is +// found and read into the specified pointer. The number of bytes skipped is +// returned. If no WavPack header is found within 1 meg, then a -1 is returned +// to indicate the error. No additional bytes are read past the header and it +// is returned in the processor's native endian mode. Seeking is not required. + +static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr) +{ + char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp; + uint32_t bytes_skipped = 0; + int bleft; + + while (1) { + if (sp < ep) { + bleft = ep - sp; + memcpy (buffer, sp, bleft); + } + else + bleft = 0; + + if (infile (buffer + bleft, sizeof (*wphdr) - bleft) != (int32_t) sizeof (*wphdr) - bleft) + return -1; + + sp = buffer; + + if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' && + !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 && + sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) { + memcpy (wphdr, buffer, sizeof (*wphdr)); + little_endian_to_native (wphdr, WavpackHeaderFormat); + return bytes_skipped; + } + + while (sp < ep && *sp != 'w') + sp++; + + if ((bytes_skipped += sp - buffer) > 1048576L) + return -1; + } +} diff --git a/src/engine/external/wavpack/wvfilter.c.no_compile b/src/engine/external/wavpack/wvfilter.c.no_compile new file mode 100644 index 0000000..236912d --- /dev/null +++ b/src/engine/external/wavpack/wvfilter.c.no_compile @@ -0,0 +1,200 @@ +//////////////////////////////////////////////////////////////////////////// +// **** WAVPACK **** // +// Hybrid Lossless Wavefile Compressor // +// Copyright (c) 1998 - 2006 Conifer Software. // +// All Rights Reserved. // +// Distributed under the BSD Software License (see license.txt) // +//////////////////////////////////////////////////////////////////////////// + +// wv_filter.c + +// This is the main module for the demonstration WavPack command-line +// decoder filter. It uses the tiny "hardware" version of the decoder and +// accepts WavPack files on stdin and outputs a standard MS wav file to +// stdout. Note that this involves converting the data to little-endian +// (if the executing processor is not), possibly packing the data into +// fewer bytes per sample, and generating an appropriate riff wav header. +// Note that this is NOT the copy of the RIFF header that might be stored +// in the file, and any additional RIFF information and tags are lost. +// See wputils.c for further limitations. + +#include "wavpack.h" + +#if defined(WIN32) +#include <io.h> +#include <fcntl.h> +#endif + +#include <string.h> + +// These structures are used to place a wav riff header at the beginning of +// the output. + +typedef struct { + char ckID [4]; + uint32_t ckSize; + char formType [4]; +} RiffChunkHeader; + +typedef struct { + char ckID [4]; + uint32_t ckSize; +} ChunkHeader; + +#define ChunkHeaderFormat "4L" + +typedef struct { + ushort FormatTag, NumChannels; + uint32_t SampleRate, BytesPerSecond; + ushort BlockAlign, BitsPerSample; +} WaveHeader; + +#define WaveHeaderFormat "SSLLSS" + +static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt); +static int32_t read_bytes (void *buff, int32_t bcount); +static int32_t temp_buffer [256]; + +int main () +{ + ChunkHeader FormatChunkHeader, DataChunkHeader; + RiffChunkHeader RiffChunkHeader; + WaveHeader WaveHeader; + + uint32_t total_unpacked_samples = 0, total_samples; + int num_channels, bps; + WavpackContext *wpc; + char error [80]; + +#if defined(WIN32) + setmode (fileno (stdin), O_BINARY); + setmode (fileno (stdout), O_BINARY); +#endif + + wpc = WavpackOpenFileInput (read_bytes, error); + + if (!wpc) { + fputs (error, stderr); + fputs ("\n", stderr); + return 1; + } + + num_channels = WavpackGetReducedChannels (wpc); + total_samples = WavpackGetNumSamples (wpc); + bps = WavpackGetBytesPerSample (wpc); + + strncpy (RiffChunkHeader.ckID, "RIFF", sizeof (RiffChunkHeader.ckID)); + RiffChunkHeader.ckSize = total_samples * num_channels * bps + sizeof (ChunkHeader) * 2 + sizeof (WaveHeader) + 4; + strncpy (RiffChunkHeader.formType, "WAVE", sizeof (RiffChunkHeader.formType)); + + strncpy (FormatChunkHeader.ckID, "fmt ", sizeof (FormatChunkHeader.ckID)); + FormatChunkHeader.ckSize = sizeof (WaveHeader); + + WaveHeader.FormatTag = 1; + WaveHeader.NumChannels = num_channels; + WaveHeader.SampleRate = WavpackGetSampleRate (wpc); + WaveHeader.BlockAlign = num_channels * bps; + WaveHeader.BytesPerSecond = WaveHeader.SampleRate * WaveHeader.BlockAlign; + WaveHeader.BitsPerSample = WavpackGetBitsPerSample (wpc); + + strncpy (DataChunkHeader.ckID, "data", sizeof (DataChunkHeader.ckID)); + DataChunkHeader.ckSize = total_samples * num_channels * bps; + + native_to_little_endian (&RiffChunkHeader, ChunkHeaderFormat); + native_to_little_endian (&FormatChunkHeader, ChunkHeaderFormat); + native_to_little_endian (&WaveHeader, WaveHeaderFormat); + native_to_little_endian (&DataChunkHeader, ChunkHeaderFormat); + + if (!fwrite (&RiffChunkHeader, sizeof (RiffChunkHeader), 1, stdout) || + !fwrite (&FormatChunkHeader, sizeof (FormatChunkHeader), 1, stdout) || + !fwrite (&WaveHeader, sizeof (WaveHeader), 1, stdout) || + !fwrite (&DataChunkHeader, sizeof (DataChunkHeader), 1, stdout)) { + fputs ("can't write .WAV data, disk probably full!\n", stderr); + return 1; + } + + while (1) { + uint32_t samples_unpacked; + + samples_unpacked = WavpackUnpackSamples (wpc, temp_buffer, 256 / num_channels); + total_unpacked_samples += samples_unpacked; + + if (samples_unpacked) { + format_samples (bps, (uchar *) temp_buffer, temp_buffer, samples_unpacked *= num_channels); + + if (fwrite (temp_buffer, bps, samples_unpacked, stdout) != samples_unpacked) { + fputs ("can't write .WAV data, disk probably full!\n", stderr); + return 1; + } + } + + if (!samples_unpacked) + break; + } + + fflush (stdout); + + if (WavpackGetNumSamples (wpc) != (uint32_t) -1 && + total_unpacked_samples != WavpackGetNumSamples (wpc)) { + fputs ("incorrect number of samples!\n", stderr); + return 1; + } + + if (WavpackGetNumErrors (wpc)) { + fputs ("crc errors detected!\n", stderr); + return 1; + } + + return 0; +} + +static int32_t read_bytes (void *buff, int32_t bcount) +{ + return fread (buff, 1, bcount, stdin); +} + +// Reformat samples from longs in processor's native endian mode to +// little-endian data with (possibly) less than 4 bytes / sample. + +static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt) +{ + int32_t temp; + + switch (bps) { + + case 1: + while (samcnt--) + *dst++ = *src++ + 128; + + break; + + case 2: + while (samcnt--) { + *dst++ = (uchar)(temp = *src++); + *dst++ = (uchar)(temp >> 8); + } + + break; + + case 3: + while (samcnt--) { + *dst++ = (uchar)(temp = *src++); + *dst++ = (uchar)(temp >> 8); + *dst++ = (uchar)(temp >> 16); + } + + break; + + case 4: + while (samcnt--) { + *dst++ = (uchar)(temp = *src++); + *dst++ = (uchar)(temp >> 8); + *dst++ = (uchar)(temp >> 16); + *dst++ = (uchar)(temp >> 24); + } + + break; + } + + return dst; +} diff --git a/src/engine/external/zlib/VERSION b/src/engine/external/zlib/VERSION new file mode 100644 index 0000000..db6fb4a --- /dev/null +++ b/src/engine/external/zlib/VERSION @@ -0,0 +1 @@ +1.2.8 diff --git a/src/engine/external/zlib/adler32.c b/src/engine/external/zlib/adler32.c new file mode 100644 index 0000000..a868f07 --- /dev/null +++ b/src/engine/external/zlib/adler32.c @@ -0,0 +1,179 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#define local static + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521 /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/src/engine/external/zlib/compress.c b/src/engine/external/zlib/compress.c new file mode 100644 index 0000000..6e97626 --- /dev/null +++ b/src/engine/external/zlib/compress.c @@ -0,0 +1,80 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/src/engine/external/zlib/crc32.c b/src/engine/external/zlib/crc32.c new file mode 100644 index 0000000..979a719 --- /dev/null +++ b/src/engine/external/zlib/crc32.c @@ -0,0 +1,425 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. + */ + +#ifdef MAKECRCH +# include <stdio.h> +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/src/engine/external/zlib/crc32.h b/src/engine/external/zlib/crc32.h new file mode 100644 index 0000000..9e0c778 --- /dev/null +++ b/src/engine/external/zlib/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/src/engine/external/zlib/deflate.c b/src/engine/external/zlib/deflate.c new file mode 100644 index 0000000..6969577 --- /dev/null +++ b/src/engine/external/zlib/deflate.c @@ -0,0 +1,1967 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_BLOCK); + if (err == Z_BUF_ERROR && s->pending == 0) + err = Z_OK; + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + Bytef *str; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (strm == Z_NULL || strm->state == Z_NULL) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + (s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush)); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if ((long)s->strstart > s->block_start) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (int)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/src/engine/external/zlib/deflate.h b/src/engine/external/zlib/deflate.h new file mode 100644 index 0000000..ce0299e --- /dev/null +++ b/src/engine/external/zlib/deflate.h @@ -0,0 +1,346 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2012 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/src/engine/external/zlib/gzclose.c b/src/engine/external/zlib/gzclose.c new file mode 100644 index 0000000..caeb99a --- /dev/null +++ b/src/engine/external/zlib/gzclose.c @@ -0,0 +1,25 @@ +/* gzclose.c -- zlib gzclose() function + * Copyright (C) 2004, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* gzclose() is in a separate file so that it is linked in only if it is used. + That way the other gzclose functions can be used instead to avoid linking in + unneeded compression or decompression routines. */ +int ZEXPORT gzclose(file) + gzFile file; +{ +#ifndef NO_GZCOMPRESS + gz_statep state; + + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file); +#else + return gzclose_r(file); +#endif +} diff --git a/src/engine/external/zlib/gzguts.h b/src/engine/external/zlib/gzguts.h new file mode 100644 index 0000000..d87659d --- /dev/null +++ b/src/engine/external/zlib/gzguts.h @@ -0,0 +1,209 @@ +/* gzguts.h -- zlib internal header definitions for gz* operations + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#ifdef _LARGEFILE64_SOURCE +# ifndef _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE 1 +# endif +# ifdef _FILE_OFFSET_BITS +# undef _FILE_OFFSET_BITS +# endif +#endif + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include <stdio.h> +#include "zlib.h" +#ifdef STDC +# include <string.h> +# include <stdlib.h> +# include <limits.h> +#endif +#include <fcntl.h> + +#ifdef _WIN32 +# include <stddef.h> +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include <io.h> +#endif + +#ifdef WINAPI_FAMILY +# define open _open +# define read _read +# define write _write +# define close _close +#endif + +#ifdef NO_DEFLATE /* for compatibility with old definition */ +# define NO_GZCOMPRESS +#endif + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif +#endif + +/* unlike snprintf (which is required in C99, yet still not supported by + Microsoft more than a decade later!), _snprintf does not guarantee null + termination of the result -- however this is only used in gzlib.c where + the result is assured to fit in the space provided */ +#ifdef _MSC_VER +# define snprintf _snprintf +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +/* gz* functions always use library allocation functions */ +#ifndef STDC + extern voidp malloc OF((uInt size)); + extern void free OF((voidpf ptr)); +#endif + +/* get errno and strerror definition */ +#if defined UNDER_CE +# include <windows.h> +# define zstrerror() gz_strwinerror((DWORD)GetLastError()) +#else +# ifndef NO_STRERROR +# include <errno.h> +# define zstrerror() strerror(errno) +# else +# define zstrerror() "stdio error (consult errno)" +# endif +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); +#endif + +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + +/* default i/o buffer size -- double this for output when reading (this and + twice this must be able to fit in an unsigned type) */ +#define GZBUFSIZE 8192 + +/* gzip modes, also provide a little integrity check on the passed structure */ +#define GZ_NONE 0 +#define GZ_READ 7247 +#define GZ_WRITE 31153 +#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */ + +/* values for gz_state how */ +#define LOOK 0 /* look for a gzip header */ +#define COPY 1 /* copy input directly */ +#define GZIP 2 /* decompress a gzip stream */ + +/* internal gzip file state data structure */ +typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ + /* used for both reading and writing */ + int mode; /* see gzip modes above */ + int fd; /* file descriptor */ + char *path; /* path or fd for error messages */ + unsigned size; /* buffer size, zero if not allocated yet */ + unsigned want; /* requested buffer size, default is GZBUFSIZE */ + unsigned char *in; /* input buffer */ + unsigned char *out; /* output buffer (double-sized when reading) */ + int direct; /* 0 if processing gzip, 1 if transparent */ + /* just for reading */ + int how; /* 0: get header, 1: copy, 2: decompress */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ + /* just for writing */ + int level; /* compression level */ + int strategy; /* compression strategy */ + /* seek request */ + z_off64_t skip; /* amount to skip (already rewound if backwards) */ + int seek; /* true if seek request pending */ + /* error information */ + int err; /* error code */ + char *msg; /* error message */ + /* zlib inflate or deflate stream */ + z_stream strm; /* stream structure in-place (not a pointer) */ +} gz_state; +typedef gz_state FAR *gz_statep; + +/* shared functions */ +void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *)); +#if defined UNDER_CE +char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error)); +#endif + +/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t + value -- needed when comparing unsigned to z_off64_t, which is signed + (possible z_off64_t types off_t, off64_t, and long are all signed) */ +#ifdef INT_MAX +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX) +#else +unsigned ZLIB_INTERNAL gz_intmax OF((void)); +# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) +#endif diff --git a/src/engine/external/zlib/gzlib.c b/src/engine/external/zlib/gzlib.c new file mode 100644 index 0000000..fae202e --- /dev/null +++ b/src/engine/external/zlib/gzlib.c @@ -0,0 +1,634 @@ +/* gzlib.c -- zlib functions common to reading and writing gzip files + * Copyright (C) 2004, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +#if defined(_WIN32) && !defined(__BORLANDC__) +# define LSEEK _lseeki64 +#else +#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +# define LSEEK lseek64 +#else +# define LSEEK lseek +#endif +#endif + +/* Local functions */ +local void gz_reset OF((gz_statep)); +local gzFile gz_open OF((const void *, int, const char *)); + +#if defined UNDER_CE + +/* Map the Windows error number in ERROR to a locale-dependent error message + string and return a pointer to it. Typically, the values for ERROR come + from GetLastError. + + The string pointed to shall not be modified by the application, but may be + overwritten by a subsequent call to gz_strwinerror + + The gz_strwinerror function does not change the current setting of + GetLastError. */ +char ZLIB_INTERNAL *gz_strwinerror (error) + DWORD error; +{ + static char buf[1024]; + + wchar_t *msgbuf; + DWORD lasterr = GetLastError(); + DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_ALLOCATE_BUFFER, + NULL, + error, + 0, /* Default language */ + (LPVOID)&msgbuf, + 0, + NULL); + if (chars != 0) { + /* If there is an \r\n appended, zap it. */ + if (chars >= 2 + && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { + chars -= 2; + msgbuf[chars] = 0; + } + + if (chars > sizeof (buf) - 1) { + chars = sizeof (buf) - 1; + msgbuf[chars] = 0; + } + + wcstombs(buf, msgbuf, chars + 1); + LocalFree(msgbuf); + } + else { + sprintf(buf, "unknown win32 error (%ld)", error); + } + + SetLastError(lasterr); + return buf; +} + +#endif /* UNDER_CE */ + +/* Reset gzip file state */ +local void gz_reset(state) + gz_statep state; +{ + state->x.have = 0; /* no output data available */ + if (state->mode == GZ_READ) { /* for reading ... */ + state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ + state->how = LOOK; /* look for gzip header */ + } + state->seek = 0; /* no seek request pending */ + gz_error(state, Z_OK, NULL); /* clear error */ + state->x.pos = 0; /* no uncompressed data yet */ + state->strm.avail_in = 0; /* no input data yet */ +} + +/* Open a gzip file either by name or file descriptor. */ +local gzFile gz_open(path, fd, mode) + const void *path; + int fd; + const char *mode; +{ + gz_statep state; + size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; + + /* allocate gzFile structure to return */ + state = (gz_statep)malloc(sizeof(gz_state)); + if (state == NULL) + return NULL; + state->size = 0; /* no buffers allocated yet */ + state->want = GZBUFSIZE; /* requested buffer size */ + state->msg = NULL; /* no error message yet */ + + /* interpret mode */ + state->mode = GZ_NONE; + state->level = Z_DEFAULT_COMPRESSION; + state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; + while (*mode) { + if (*mode >= '0' && *mode <= '9') + state->level = *mode - '0'; + else + switch (*mode) { + case 'r': + state->mode = GZ_READ; + break; +#ifndef NO_GZCOMPRESS + case 'w': + state->mode = GZ_WRITE; + break; + case 'a': + state->mode = GZ_APPEND; + break; +#endif + case '+': /* can't read and write at the same time */ + free(state); + return NULL; + case 'b': /* ignore -- will request binary anyway */ + break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif + case 'f': + state->strategy = Z_FILTERED; + break; + case 'h': + state->strategy = Z_HUFFMAN_ONLY; + break; + case 'R': + state->strategy = Z_RLE; + break; + case 'F': + state->strategy = Z_FIXED; + break; + case 'T': + state->direct = 1; + break; + default: /* could consider as an error, but just ignore */ + ; + } + mode++; + } + + /* must provide an "r", "w", or "a" */ + if (state->mode == GZ_NONE) { + free(state); + return NULL; + } + + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + + /* save the path name for error messages */ +#ifdef _WIN32 + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (size_t)-1) + len = 0; + } + else +#endif + len = strlen((const char *)path); + state->path = (char *)malloc(len + 1); + if (state->path == NULL) { + free(state); + return NULL; + } +#ifdef _WIN32 + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(state->path, len + 1, "%s", (const char *)path); +#else + strcpy(state->path, path); +#endif + + /* compute the flags for open() */ + oflag = +#ifdef O_LARGEFILE + O_LARGEFILE | +#endif +#ifdef O_BINARY + O_BINARY | +#endif +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | +#endif + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef _WIN32 + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open((const char *)path, oflag, 0666)); + if (state->fd == -1) { + free(state->path); + free(state); + return NULL; + } + if (state->mode == GZ_APPEND) + state->mode = GZ_WRITE; /* simplify later checks */ + + /* save the current position for rewinding (only if reading) */ + if (state->mode == GZ_READ) { + state->start = LSEEK(state->fd, 0, SEEK_CUR); + if (state->start == -1) state->start = 0; + } + + /* initialize stream */ + gz_reset(state); + + /* return stream */ + return (gzFile)state; +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzopen64(path, mode) + const char *path; + const char *mode; +{ + return gz_open(path, -1, mode); +} + +/* -- see zlib.h -- */ +gzFile ZEXPORT gzdopen(fd, mode) + int fd; + const char *mode; +{ + char *path; /* identifier for error messages */ + gzFile gz; + + if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) + return NULL; +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); /* for debugging */ +#else + sprintf(path, "<fd:%d>", fd); /* for debugging */ +#endif + gz = gz_open(path, fd, mode); + free(path); + return gz; +} + +/* -- see zlib.h -- */ +#ifdef _WIN32 +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzbuffer(file, size) + gzFile file; + unsigned size; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* make sure we haven't already allocated memory */ + if (state->size != 0) + return -1; + + /* check and set requested size */ + if (size < 2) + size = 2; /* need two bytes to check magic header */ + state->want = size; + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzrewind(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* back up and start over */ + if (LSEEK(state->fd, state->start, SEEK_SET) == -1) + return -1; + gz_reset(state); + return 0; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzseek64(file, offset, whence) + gzFile file; + z_off64_t offset; + int whence; +{ + unsigned n; + z_off64_t ret; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* check that there's no error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + + /* can only seek from start or relative to current position */ + if (whence != SEEK_SET && whence != SEEK_CUR) + return -1; + + /* normalize offset to a SEEK_CUR specification */ + if (whence == SEEK_SET) + offset -= state->x.pos; + else if (state->seek) + offset += state->skip; + state->seek = 0; + + /* if within raw area while reading, just go there */ + if (state->mode == GZ_READ && state->how == COPY && + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); + if (ret == -1) + return -1; + state->x.have = 0; + state->eof = 0; + state->past = 0; + state->seek = 0; + gz_error(state, Z_OK, NULL); + state->strm.avail_in = 0; + state->x.pos += offset; + return state->x.pos; + } + + /* calculate skip amount, rewinding if needed for back seek when reading */ + if (offset < 0) { + if (state->mode != GZ_READ) /* writing -- can't go backwards */ + return -1; + offset += state->x.pos; + if (offset < 0) /* before start of file! */ + return -1; + if (gzrewind(file) == -1) /* rewind, then skip to offset */ + return -1; + } + + /* if reading, skip what's in output buffer (one less gzgetc() check) */ + if (state->mode == GZ_READ) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + offset -= n; + } + + /* request skip (if not zero) */ + if (offset) { + state->seek = 1; + state->skip = offset; + } + return state->x.pos + offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzseek(file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + z_off64_t ret; + + ret = gzseek64(file, (z_off64_t)offset, whence); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gztell64(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* return position */ + return state->x.pos + (state->seek ? state->skip : 0); +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gztell(file) + gzFile file; +{ + z_off64_t ret; + + ret = gztell64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +z_off64_t ZEXPORT gzoffset64(file) + gzFile file; +{ + z_off64_t offset; + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return -1; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return -1; + + /* compute and return effective offset in file */ + offset = LSEEK(state->fd, 0, SEEK_CUR); + if (offset == -1) + return -1; + if (state->mode == GZ_READ) /* reading */ + offset -= state->strm.avail_in; /* don't count buffered input */ + return offset; +} + +/* -- see zlib.h -- */ +z_off_t ZEXPORT gzoffset(file) + gzFile file; +{ + z_off64_t ret; + + ret = gzoffset64(file); + return ret == (z_off_t)ret ? (z_off_t)ret : -1; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzeof(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return 0; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return 0; + + /* return end-of-file state */ + return state->mode == GZ_READ ? state->past : 0; +} + +/* -- see zlib.h -- */ +const char * ZEXPORT gzerror(file, errnum) + gzFile file; + int *errnum; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return NULL; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return NULL; + + /* return error information */ + if (errnum != NULL) + *errnum = state->err; + return state->err == Z_MEM_ERROR ? "out of memory" : + (state->msg == NULL ? "" : state->msg); +} + +/* -- see zlib.h -- */ +void ZEXPORT gzclearerr(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure and check integrity */ + if (file == NULL) + return; + state = (gz_statep)file; + if (state->mode != GZ_READ && state->mode != GZ_WRITE) + return; + + /* clear error and end-of-file */ + if (state->mode == GZ_READ) { + state->eof = 0; + state->past = 0; + } + gz_error(state, Z_OK, NULL); +} + +/* Create an error message in allocated memory and set state->err and + state->msg accordingly. Free any previous error message already there. Do + not try to free or allocate space if the error is Z_MEM_ERROR (out of + memory). Simply save the error message as a static string. If there is an + allocation failure constructing the error message, then convert the error to + out of memory. */ +void ZLIB_INTERNAL gz_error(state, err, msg) + gz_statep state; + int err; + const char *msg; +{ + /* free previously allocated message and clear */ + if (state->msg != NULL) { + if (state->err != Z_MEM_ERROR) + free(state->msg); + state->msg = NULL; + } + + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + + /* set error code, and if no message, then done */ + state->err = err; + if (msg == NULL) + return; + + /* for an out of memory error, return literal string when requested */ + if (err == Z_MEM_ERROR) + return; + + /* construct error message with path */ + if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == + NULL) { + state->err = Z_MEM_ERROR; + return; + } +#if !defined(NO_snprintf) && !defined(NO_vsnprintf) + snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, + "%s%s%s", state->path, ": ", msg); +#else + strcpy(state->msg, state->path); + strcat(state->msg, ": "); + strcat(state->msg, msg); +#endif + return; +} + +#ifndef INT_MAX +/* portably return maximum value for an int (when limits.h presumed not + available) -- we need to do this to cover cases where 2's complement not + used, since C standard permits 1's complement and sign-bit representations, + otherwise we could just use ((unsigned)-1) >> 1 */ +unsigned ZLIB_INTERNAL gz_intmax() +{ + unsigned p, q; + + p = 1; + do { + q = p; + p <<= 1; + p++; + } while (p > q); + return q >> 1; +} +#endif diff --git a/src/engine/external/zlib/gzread.c b/src/engine/external/zlib/gzread.c new file mode 100644 index 0000000..bf4538e --- /dev/null +++ b/src/engine/external/zlib/gzread.c @@ -0,0 +1,594 @@ +/* gzread.c -- zlib functions for reading gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); +local int gz_avail OF((gz_statep)); +local int gz_look OF((gz_statep)); +local int gz_decomp OF((gz_statep)); +local int gz_fetch OF((gz_statep)); +local int gz_skip OF((gz_statep, z_off64_t)); + +/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from + state->fd, and update state->eof, state->err, and state->msg as appropriate. + This function needs to loop on read(), since read() is not guaranteed to + read the number of bytes requested, depending on the type of descriptor. */ +local int gz_load(state, buf, len, have) + gz_statep state; + unsigned char *buf; + unsigned len; + unsigned *have; +{ + int ret; + + *have = 0; + do { + ret = read(state->fd, buf + *have, len - *have); + if (ret <= 0) + break; + *have += ret; + } while (*have < len); + if (ret < 0) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (ret == 0) + state->eof = 1; + return 0; +} + +/* Load up input buffer and set eof flag if last data loaded -- return -1 on + error, 0 otherwise. Note that the eof flag is set when the end of the input + file is reached, even though there may be unused data in the buffer. Once + that data has been used, no more attempts will be made to read the file. + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ +local int gz_avail(state) + gz_statep state; +{ + unsigned got; + z_streamp strm = &(state->strm); + + if (state->err != Z_OK && state->err != Z_BUF_ERROR) + return -1; + if (state->eof == 0) { + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in; + unsigned const char *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) + return -1; + strm->avail_in += got; + strm->next_in = state->in; + } + return 0; +} + +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. + If this is the first time in, allocate required memory. state->how will be + left unchanged if there is no more input data available, will be set to COPY + if there is no gzip header and direct copying will be performed, or it will + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + /* allocate read buffers and inflate memory */ + if (state->size == 0) { + /* allocate buffers */ + state->in = (unsigned char *)malloc(state->want); + state->out = (unsigned char *)malloc(state->want << 1); + if (state->in == NULL || state->out == NULL) { + if (state->out != NULL) + free(state->out); + if (state->in != NULL) + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + state->size = state->want; + + /* allocate inflate memory */ + state->strm.zalloc = Z_NULL; + state->strm.zfree = Z_NULL; + state->strm.opaque = Z_NULL; + state->strm.avail_in = 0; + state->strm.next_in = Z_NULL; + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ + free(state->out); + free(state->in); + state->size = 0; + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } + + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; + } + + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; + } + + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; + if (strm->avail_in) { + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; + strm->avail_in = 0; + } + state->how = COPY; + state->direct = 1; + return 0; +} + +/* Decompress from input to the provided next_out and avail_out in the state. + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ +local int gz_decomp(state) + gz_statep state; +{ + int ret = Z_OK; + unsigned had; + z_streamp strm = &(state->strm); + + /* fill output buffer up to end of deflate stream */ + had = strm->avail_out; + do { + /* get more input for inflate() */ + if (strm->avail_in == 0 && gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) { + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; + } + + /* decompress and handle errors */ + ret = inflate(strm, Z_NO_FLUSH); + if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { + gz_error(state, Z_STREAM_ERROR, + "internal error: inflate stream corrupt"); + return -1; + } + if (ret == Z_MEM_ERROR) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ + gz_error(state, Z_DATA_ERROR, + strm->msg == NULL ? "compressed data error" : strm->msg); + return -1; + } + } while (strm->avail_out && ret != Z_STREAM_END); + + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; + + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; + + /* good decompression */ + return 0; +} + +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. + Data is either copied from the input file or decompressed from the input + file depending on state->how. If state->how is LOOK, then a gzip header is + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) + gz_statep state; +{ + z_streamp strm = &(state->strm); + + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; + return 0; + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); + return 0; +} + +/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ +local int gz_skip(state, len) + gz_statep state; + z_off64_t len; +{ + unsigned n; + + /* skip over len bytes or reach end-of-file, whichever comes first */ + while (len) + /* skip over whatever is in output buffer */ + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + len -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && state->strm.avail_in == 0) + break; + + /* need more data to skip -- load up output buffer */ + else { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzread(file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + unsigned got, n; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return -1; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* get len bytes to buf, or less than len if at the end */ + got = 0; + do { + /* first just try copying data from the output buffer */ + if (state->x.have) { + n = state->x.have > len ? len : state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; + } + + /* output buffer empty -- return if we're at the end of the input */ + else if (state->eof && strm->avail_in == 0) { + state->past = 1; /* tried to read past end */ + break; + } + + /* need output data -- for small len or new stream load up our output + buffer */ + else if (state->how == LOOK || len < (state->size << 1)) { + /* get more output, looking for header if required */ + if (gz_fetch(state) == -1) + return -1; + continue; /* no progress yet -- go back to copy above */ + /* the copy above assures that we will leave with space in the + output buffer, allowing at least one gzungetc() to succeed */ + } + + /* large len -- read directly into user buffer */ + else if (state->how == COPY) { /* read directly */ + if (gz_load(state, (unsigned char *)buf, len, &n) == -1) + return -1; + } + + /* large len -- decompress directly into user buffer */ + else { /* state->how == GZIP */ + strm->avail_out = len; + strm->next_out = (unsigned char *)buf; + if (gz_decomp(state) == -1) + return -1; + n = state->x.have; + state->x.have = 0; + } + + /* update progress */ + len -= n; + buf = (char *)buf + n; + got += n; + state->x.pos += n; + } while (len); + + /* return number of bytes read into user buffer (will fit in int) */ + return (int)got; +} + +/* -- see zlib.h -- */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +#else +# undef gzgetc +#endif +int ZEXPORT gzgetc(file) + gzFile file; +{ + int ret; + unsigned char buf[1]; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* try output buffer (no need to check for skip request) */ + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; + } + + /* nothing there -- try gzread() */ + ret = gzread(file, buf, 1); + return ret < 1 ? -1 : buf[0]; +} + +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + +/* -- see zlib.h -- */ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return -1; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return -1; + } + + /* can't push EOF */ + if (c < 0) + return -1; + + /* if output buffer empty, put byte at end (allows more pushing) */ + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; + return c; + } + + /* if no room, give up (must have already done a gzungetc()) */ + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); + return -1; + } + + /* slide output data if needed and insert byte before existing data */ + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; + unsigned char *dest = state->out + (state->size << 1); + while (src > state->out) + *--dest = *--src; + state->x.next = dest; + } + state->x.have++; + state->x.next--; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; + return c; +} + +/* -- see zlib.h -- */ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + unsigned left, n; + char *str; + unsigned char *eol; + gz_statep state; + + /* check parameters and get internal structure */ + if (file == NULL || buf == NULL || len < 1) + return NULL; + state = (gz_statep)file; + + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) + return NULL; + + /* process a skip request */ + if (state->seek) { + state->seek = 0; + if (gz_skip(state, state->skip) == -1) + return NULL; + } + + /* copy output bytes up to new line or len - 1, whichever comes first -- + append a terminating zero to the string (we don't check for a zero in + the contents, let the user worry about that) */ + str = buf; + left = (unsigned)len - 1; + if (left) do { + /* assure that something is in the output buffer */ + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ + } + + /* look for end-of-line in current output buffer */ + n = state->x.have > left ? left : state->x.have; + eol = (unsigned char *)memchr(state->x.next, '\n', n); + if (eol != NULL) + n = (unsigned)(eol - state->x.next) + 1; + + /* copy through end-of-line, or remainder if not found */ + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + left -= n; + buf += n; + } while (left && eol == NULL); + + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; + buf[0] = 0; + return str; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzdirect(file) + gzFile file; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + + /* if the state is not known, but we can find out, then do so (this is + mainly for right after a gzopen() or gzdopen()) */ + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); + + /* return 1 if transparent, 0 if processing a gzip stream */ + return state->direct; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_r(file) + gzFile file; +{ + int ret, err; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're reading */ + if (state->mode != GZ_READ) + return Z_STREAM_ERROR; + + /* free memory and close file */ + if (state->size) { + inflateEnd(&(state->strm)); + free(state->out); + free(state->in); + } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; + gz_error(state, Z_OK, NULL); + free(state->path); + ret = close(state->fd); + free(state); + return ret ? Z_ERRNO : err; +} diff --git a/src/engine/external/zlib/gzwrite.c b/src/engine/external/zlib/gzwrite.c new file mode 100644 index 0000000..aa767fb --- /dev/null +++ b/src/engine/external/zlib/gzwrite.c @@ -0,0 +1,577 @@ +/* gzwrite.c -- zlib functions for writing gzip files + * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "gzguts.h" + +/* Local functions */ +local int gz_init OF((gz_statep)); +local int gz_comp OF((gz_statep, int)); +local int gz_zero OF((gz_statep, z_off64_t)); + +/* Initialize state for writing a gzip file. Mark initialization by setting + state->size to non-zero. Return -1 on failure or 0 on success. */ +local int gz_init(state) + gz_statep state; +{ + int ret; + z_streamp strm = &(state->strm); + + /* allocate input buffer */ + state->in = (unsigned char *)malloc(state->want); + if (state->in == NULL) { + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = (unsigned char *)malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + } + + /* mark state as initialized */ + state->size = state->want; + + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } + return 0; +} + +/* Compress whatever is at avail_in and next_in and write to the output file. + Return -1 if there is an error writing to the output file, otherwise 0. + flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, + then the deflate() state is reset to start a new gzip stream. If gz->direct + is true, then simply write to the output file without compressing, and + ignore flush. */ +local int gz_comp(state, flush) + gz_statep state; + int flush; +{ + int ret, got; + unsigned have; + z_streamp strm = &(state->strm); + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + + /* write directly if requested */ + if (state->direct) { + got = write(state->fd, strm->next_in, strm->avail_in); + if (got < 0 || (unsigned)got != strm->avail_in) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in = 0; + return 0; + } + + /* run deflate() on provided input until it produces no more output */ + ret = Z_OK; + do { + /* write out current buffer contents if full, or if flushing, but if + doing Z_FINISH then don't write until we get to Z_STREAM_END */ + if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && + (flush != Z_FINISH || ret == Z_STREAM_END))) { + have = (unsigned)(strm->next_out - state->x.next); + if (have && ((got = write(state->fd, state->x.next, have)) < 0 || + (unsigned)got != have)) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + if (strm->avail_out == 0) { + strm->avail_out = state->size; + strm->next_out = state->out; + } + state->x.next = strm->next_out; + } + + /* compress */ + have = strm->avail_out; + ret = deflate(strm, flush); + if (ret == Z_STREAM_ERROR) { + gz_error(state, Z_STREAM_ERROR, + "internal error: deflate stream corrupt"); + return -1; + } + have -= strm->avail_out; + } while (have); + + /* if that completed a deflate stream, allow another to start */ + if (flush == Z_FINISH) + deflateReset(strm); + + /* all done, no errors */ + return 0; +} + +/* Compress len zeros to output. Return -1 on error, 0 on success. */ +local int gz_zero(state, len) + gz_statep state; + z_off64_t len; +{ + int first; + unsigned n; + z_streamp strm = &(state->strm); + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + + /* compress len zeros (len guaranteed > 0) */ + first = 1; + while (len) { + n = GT_OFF(state->size) || (z_off64_t)state->size > len ? + (unsigned)len : state->size; + if (first) { + memset(state->in, 0, n); + first = 0; + } + strm->avail_in = n; + strm->next_in = state->in; + state->x.pos += n; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return -1; + len -= n; + } + return 0; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzwrite(file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + unsigned put = len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return 0; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* since an int is returned, make sure len fits in one, otherwise return + with an error (this avoids the flaw in the interface) */ + if ((int)len < 0) { + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); + return 0; + } + + /* if len is zero, avoid unnecessary operations */ + if (len == 0) + return 0; + + /* allocate memory if this is the first time through */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* for small len, copy to input buffer, otherwise compress directly */ + if (len < state->size) { + /* copy to input buffer, compress when full */ + do { + unsigned have, copy; + + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + copy = state->size - have; + if (copy > len) + copy = len; + memcpy(state->in + have, buf, copy); + strm->avail_in += copy; + state->x.pos += copy; + buf = (const char *)buf + copy; + len -= copy; + if (len && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } while (len); + } + else { + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* directly compress user buffer to file */ + strm->avail_in = len; + strm->next_in = (z_const Bytef *)buf; + state->x.pos += len; + if (gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + } + + /* input was all buffered or compressed (put will fit in int) */ + return (int)put; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned have; + unsigned char buf[1]; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return -1; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* try writing to input buffer for speed (state->size == 0 if buffer not + initialized) */ + if (state->size) { + if (strm->avail_in == 0) + strm->next_in = state->in; + have = (unsigned)((strm->next_in + strm->avail_in) - state->in); + if (have < state->size) { + state->in[have] = c; + strm->avail_in++; + state->x.pos++; + return c & 0xff; + } + } + + /* no room in buffer or not initialized, use gz_write() */ + buf[0] = c; + if (gzwrite(file, buf, 1) != 1) + return -1; + return c & 0xff; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzputs(file, str) + gzFile file; + const char *str; +{ + int ret; + unsigned len; + + /* write string */ + len = (unsigned)strlen(str); + ret = gzwrite(file, str, len); + return ret == 0 && len != 0 ? -1 : ret; +} + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +#include <stdarg.h> + +/* -- see zlib.h -- */ +int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) +{ + int size, len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf((char *)(state->in), format, va); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = vsprintf((char *)(state->in), format, va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf((char *)(state->in), size, format, va); + len = strlen((char *)(state->in)); +# else + len = vsnprintf((char *)(state->in), size, format, va); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->x.pos += len; + return len; +} + +int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) +{ + va_list va; + int ret; + + va_start(va, format); + ret = gzvprintf(file, format, va); + va_end(va); + return ret; +} + +#else /* !STDC && !Z_HAVE_STDARG_H */ + +/* -- see zlib.h -- */ +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + int size, len; + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return 0; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return 0; + + /* make sure we have some buffer space */ + if (state->size == 0 && gz_init(state) == -1) + return 0; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return 0; + } + + /* consume whatever's left in the input buffer */ + if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) + return 0; + + /* do the printf() into the input buffer, put length in len */ + size = (int)(state->size); + state->in[size - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < size; len++) + if (state->in[len] == 0) break; +# else + len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen((char *)(state->in)); +# else + len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, + a19, a20); +# endif +#endif + + /* check that printf() results fit in buffer */ + if (len <= 0 || len >= (int)size || state->in[size - 1] != 0) + return 0; + + /* update buffer and position, defer compression until needed */ + strm->avail_in = (unsigned)len; + strm->next_in = state->in; + state->x.pos += len; + return len; +} + +#endif + +/* -- see zlib.h -- */ +int ZEXPORT gzflush(file, flush) + gzFile file; + int flush; +{ + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return -1; + state = (gz_statep)file; + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* check flush parameter */ + if (flush < 0 || flush > Z_FINISH) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* compress remaining data with requested flush */ + gz_comp(state, flush); + return state->err; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzsetparams(file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_statep state; + z_streamp strm; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + strm = &(state->strm); + + /* check that we're writing and that there's no error */ + if (state->mode != GZ_WRITE || state->err != Z_OK) + return Z_STREAM_ERROR; + + /* if no change is requested, then do nothing */ + if (level == state->level && strategy == state->strategy) + return Z_OK; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + return -1; + } + + /* change compression parameters for subsequent input */ + if (state->size) { + /* flush previous input with previous parameters before changing */ + if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1) + return state->err; + deflateParams(strm, level, strategy); + } + state->level = level; + state->strategy = strategy; + return Z_OK; +} + +/* -- see zlib.h -- */ +int ZEXPORT gzclose_w(file) + gzFile file; +{ + int ret = Z_OK; + gz_statep state; + + /* get internal structure */ + if (file == NULL) + return Z_STREAM_ERROR; + state = (gz_statep)file; + + /* check that we're writing */ + if (state->mode != GZ_WRITE) + return Z_STREAM_ERROR; + + /* check for seek request */ + if (state->seek) { + state->seek = 0; + if (gz_zero(state, state->skip) == -1) + ret = state->err; + } + + /* flush, free memory, and close file */ + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (state->size) { + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } + gz_error(state, Z_OK, NULL); + free(state->path); + if (close(state->fd) == -1) + ret = Z_ERRNO; + free(state); + return ret; +} diff --git a/src/engine/external/zlib/infback.c b/src/engine/external/zlib/infback.c new file mode 100644 index 0000000..f3833c2 --- /dev/null +++ b/src/engine/external/zlib/infback.c @@ -0,0 +1,640 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2011 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_streamp strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->dmax = 32768U; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->wnext = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_streamp strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + state->length = (unsigned)here.val; + + /* process literal */ + if (here.op == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(here.bits); + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(here.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/src/engine/external/zlib/inffast.c b/src/engine/external/zlib/inffast.c new file mode 100644 index 0000000..bda59ce --- /dev/null +++ b/src/engine/external/zlib/inffast.c @@ -0,0 +1,340 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2008, 2010, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - M68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + PUP(out) = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + PUP(out) = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + PUP(out) = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + PUP(out) = PUP(from); + } while (--len); + continue; + } +#endif + } + from = window - OFF; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/src/engine/external/zlib/inffast.h b/src/engine/external/zlib/inffast.h new file mode 100644 index 0000000..e5c1aa4 --- /dev/null +++ b/src/engine/external/zlib/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/src/engine/external/zlib/inffixed.h b/src/engine/external/zlib/inffixed.h new file mode 100644 index 0000000..d628327 --- /dev/null +++ b/src/engine/external/zlib/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/src/engine/external/zlib/inflate.c b/src/engine/external/zlib/inflate.c new file mode 100644 index 0000000..870f89b --- /dev/null +++ b/src/engine/external/zlib/inflate.c @@ -0,0 +1,1512 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->window = Z_NULL; + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include <stdio.h> + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + else if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->sane = !subvert; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + return Z_OK; +#else + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; + state = (struct inflate_state FAR *)strm->state; + return ((long)(state->back) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} diff --git a/src/engine/external/zlib/inflate.h b/src/engine/external/zlib/inflate.h new file mode 100644 index 0000000..95f4986 --- /dev/null +++ b/src/engine/external/zlib/inflate.h @@ -0,0 +1,122 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2009 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 10K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/src/engine/external/zlib/inftrees.c b/src/engine/external/zlib/inftrees.c new file mode 100644 index 0000000..44d89cf --- /dev/null +++ b/src/engine/external/zlib/inftrees.c @@ -0,0 +1,306 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.8 Copyright 1995-2013 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + here.op = (unsigned char)(extra[work[sym]]); + here.val = base[work[sym]]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/src/engine/external/zlib/inftrees.h b/src/engine/external/zlib/inftrees.h new file mode 100644 index 0000000..baa53a0 --- /dev/null +++ b/src/engine/external/zlib/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/src/engine/external/zlib/trees.c b/src/engine/external/zlib/trees.c new file mode 100644 index 0000000..1fd7759 --- /dev/null +++ b/src/engine/external/zlib/trees.c @@ -0,0 +1,1226 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2012 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include <ctype.h> +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1<<extra_lbits[code]); n++) { + _length_code[length++] = (uch)code; + } + } + Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length-1] = (uch)code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<<extra_dbits[code]); n++) { + _dist_code[dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include <stdio.h> +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, + "inconsistent bit counts"); + Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); + + for (n = 0; n <= max_code; n++) { + int len = tree[n].Len; + if (len == 0) continue; + /* Now reverse the bits */ + tree[n].Code = bi_reverse(next_code[len]++, len); + + Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", + n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); + } +} + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +local void build_tree(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/src/engine/external/zlib/trees.h b/src/engine/external/zlib/trees.h new file mode 100644 index 0000000..d35639d --- /dev/null +++ b/src/engine/external/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/src/engine/external/zlib/uncompr.c b/src/engine/external/zlib/uncompr.c new file mode 100644 index 0000000..242e949 --- /dev/null +++ b/src/engine/external/zlib/uncompr.c @@ -0,0 +1,59 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (z_const Bytef *)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/src/engine/external/zlib/zconf.h b/src/engine/external/zlib/zconf.h new file mode 100644 index 0000000..9987a77 --- /dev/null +++ b/src/engine/external/zlib/zconf.h @@ -0,0 +1,511 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzvprintf z_gzvprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateGetDictionary z_inflateGetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include <windows.h> + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include <limits.h> +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include <sys/types.h> /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include <stdarg.h> /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include <stddef.h> /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include <unixio.h> /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/src/engine/external/zlib/zlib.h b/src/engine/external/zlib/zlib.h new file mode 100644 index 0000000..3e0c767 --- /dev/null +++ b/src/engine/external/zlib/zlib.h @@ -0,0 +1,1768 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.8, April 28th, 2013 + + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.8" +#define ZLIB_VERNUM 0x1280 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 8 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/src/engine/external/zlib/zutil.c b/src/engine/external/zlib/zutil.c new file mode 100644 index 0000000..23d2ebe --- /dev/null +++ b/src/engine/external/zlib/zutil.c @@ -0,0 +1,324 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +z_const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/src/engine/external/zlib/zutil.h b/src/engine/external/zlib/zutil.h new file mode 100644 index 0000000..24ab06b --- /dev/null +++ b/src/engine/external/zlib/zutil.h @@ -0,0 +1,253 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include <stddef.h> +# endif +# include <string.h> +# include <stdlib.h> +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include <alloc.h> +# endif +# else /* MSC or DJGPP */ +# include <malloc.h> +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# if defined(M_I86) && !defined(Z_SOLO) +# include <malloc.h> +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include <unix.h> /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include <stdio.h> + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/src/engine/fetcher.h b/src/engine/fetcher.h new file mode 100644 index 0000000..1b132fb --- /dev/null +++ b/src/engine/fetcher.h @@ -0,0 +1,61 @@ +#ifndef ENGINE_FETCHER_H +#define ENGINE_FETCHER_H + +#include "kernel.h" +#include "stddef.h" + +class CFetchTask; + +typedef void (*PROGFUNC)(CFetchTask *pTask, void *pUser); +typedef void (*COMPFUNC)(CFetchTask *pDest, void *pUser); + +class CFetchTask +{ + friend class CFetcher; + + CFetchTask *m_pNext; + + char m_pUrl[256]; + char m_pDest[128]; + PROGFUNC m_pfnProgressCallback; + COMPFUNC m_pfnCompCallback; + void *m_pUser; + + double m_Current; + double m_Size; + int m_Progress; + int m_State; + bool m_Abort; + bool m_CanTimeout; + int m_StorageType; +public: + CFetchTask(bool canTimeout); + + enum + { + STATE_ERROR = -1, + STATE_QUEUED, + STATE_RUNNING, + STATE_DONE, + STATE_ABORTED, + }; + + const double Current() const { return m_Current; }; + const double Size() const { return m_Size; }; + const int Progress() const { return m_Progress; }; + const int State() const { return m_State; }; + const char *Dest() const { return m_pDest; }; + + void Abort() { m_Abort = true; }; +}; + +class IFetcher : public IInterface +{ + MACRO_INTERFACE("fetcher", 0) +public: + virtual bool Init() = 0; + virtual void QueueAdd(CFetchTask *pTask, const char *pUrl, const char *pDest, int StorageType = -2, void *pUser = 0, COMPFUNC pfnCompCb = 0, PROGFUNC pfnProgCb = 0) = 0; + virtual void Escape(char *pBud, size_t size, const char *pStr) = 0; +}; + +#endif diff --git a/src/engine/friends.h b/src/engine/friends.h new file mode 100644 index 0000000..b62872e --- /dev/null +++ b/src/engine/friends.h @@ -0,0 +1,42 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_FRIENDS_H +#define ENGINE_FRIENDS_H + +#include <engine/shared/protocol.h> + +#include "kernel.h" + +struct CFriendInfo +{ + char m_aName[MAX_NAME_LENGTH]; + char m_aClan[MAX_CLAN_LENGTH]; + unsigned m_NameHash; + unsigned m_ClanHash; +}; + +class IFriends : public IInterface +{ + MACRO_INTERFACE("friends", 0) +public: + enum + { + FRIEND_NO=0, + FRIEND_CLAN, + FRIEND_PLAYER, + + MAX_FRIENDS=1024, + }; + + virtual void Init(bool Foes = false) = 0; + + virtual int NumFriends() const = 0; + virtual const CFriendInfo *GetFriend(int Index) const = 0; + virtual int GetFriendState(const char *pName, const char *pClan) 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; + virtual void RemoveFriend(const char *pName, const char *pClan) = 0; +}; + +#endif diff --git a/src/engine/graphics.h b/src/engine/graphics.h new file mode 100644 index 0000000..6f7729a --- /dev/null +++ b/src/engine/graphics.h @@ -0,0 +1,166 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_GRAPHICS_H +#define ENGINE_GRAPHICS_H + +#include "kernel.h" + + +class CImageInfo +{ +public: + enum + { + FORMAT_AUTO=-1, + FORMAT_RGB=0, + FORMAT_RGBA=1, + FORMAT_ALPHA=2, + }; + + /* 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; + + /* Variable: data + Pointer to the image data. */ + void *m_pData; +}; + +/* + Structure: CVideoMode +*/ +class CVideoMode +{ +public: + int m_Width, m_Height; + int m_Red, m_Green, m_Blue; +}; + +class IGraphics : public IInterface +{ + MACRO_INTERFACE("graphics", 0) +protected: + int m_ScreenWidth; + int m_ScreenHeight; +public: + /* Constants: Texture Loading Flags + TEXLOAD_NORESAMPLE - Prevents the texture from any resampling + */ + enum + { + TEXLOAD_NORESAMPLE = 1, + TEXLOAD_NOMIPMAPS = 2, + }; + + 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 void WrapNormal() = 0; + virtual void WrapClamp() = 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 int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData) = 0; + virtual void TextureSet(int TextureID) = 0; + + struct CLineItem + { + float m_X0, m_Y0, m_X1, m_Y1; + CLineItem() {} + CLineItem(float x0, float y0, float x1, float y1) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {} + }; + 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 TopLeftU, 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; + CQuadItem() {} + CQuadItem(float x, float y, float w, float h) : m_X(x), m_Y(y), m_Width(w), m_Height(h) {} + }; + 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; + CFreeformItem() {} + CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) + : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {} + }; + virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num) = 0; + virtual void QuadsText(float x, float y, float Size, const char *pText) = 0; + + struct CColorVertex + { + int m_Index; + float m_R, m_G, m_B, m_A; + CColorVertex() {} + CColorVertex(int i, float r, float g, float b, float a) : m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {} + }; + 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 void TakeCustomScreenshot(const char *pFilename) = 0; + virtual int GetVideoModes(CVideoMode *pModes, int MaxModes) = 0; + + virtual void Swap() = 0; + + // syncronization + virtual void InsertSignal(class semaphore *pSemaphore) = 0; + virtual bool IsIdle() = 0; + virtual void WaitForIdle() = 0; + + virtual void NotifyWindow() = 0; +}; + +class IEngineGraphics : public IGraphics +{ + MACRO_INTERFACE("enginegraphics", 0) +public: + virtual int 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(); +extern IEngineGraphics *CreateEngineGraphicsThreaded(); + +#endif diff --git a/src/engine/input.h b/src/engine/input.h new file mode 100644 index 0000000..908b431 --- /dev/null +++ b/src/engine/input.h @@ -0,0 +1,97 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_INPUT_H +#define ENGINE_INPUT_H + +#include "kernel.h" + +extern const char g_aaKeyStrings[512][16]; + +class IInput : public IInterface +{ + MACRO_INTERFACE("input", 0) +public: + class CEvent + { + public: + int m_Flags; + int m_Unicode; + int m_Key; + }; + +protected: + enum + { + INPUT_BUFFER_SIZE=32 + }; + + // quick access to events + int m_NumEvents; + IInput::CEvent m_aInputEvents[INPUT_BUFFER_SIZE]; + + //quick access to input + struct + { + unsigned char m_Presses; + unsigned char m_Releases; + } m_aInputCount[2][1024]; + + unsigned char m_aInputState[2][1024]; + int m_InputCurrent; + bool m_InputDispatched; + + int KeyWasPressed(int Key) { return m_aInputState[m_InputCurrent^1][Key]; } + +public: + enum + { + FLAG_PRESS=1, + FLAG_RELEASE=2, + FLAG_REPEAT=4 + }; + + // events + int NumEvents() const { return m_NumEvents; } + void ClearEvents() + { + m_NumEvents = 0; + m_InputDispatched = true; + } + CEvent GetEvent(int Index) const + { + if(Index < 0 || Index >= m_NumEvents) + { + IInput::CEvent e = {0,0}; + return e; + } + 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; +}; + + +class IEngineInput : public IInput +{ + MACRO_INTERFACE("engineinput", 0) +public: + virtual void Init() = 0; + virtual int Update() = 0; + virtual int VideoRestartNeeded() = 0; +}; + +extern IEngineInput *CreateEngineInput(); + +#endif diff --git a/src/engine/kernel.h b/src/engine/kernel.h new file mode 100644 index 0000000..b5961bc --- /dev/null +++ b/src/engine/kernel.h @@ -0,0 +1,68 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_KERNEL_H +#define ENGINE_KERNEL_H + +#include <base/system.h> + +class IKernel; +class IInterface; + +class IInterface +{ + // friend with the kernel implementation + friend class CKernel; + IKernel *m_pKernel; +protected: + IKernel *Kernel() { return m_pKernel; } +public: + IInterface() : m_pKernel(0) {} + virtual ~IInterface() {} + + //virtual unsigned InterfaceID() = 0; + //virtual const char *InterfaceName() = 0; +}; + +#define MACRO_INTERFACE(Name, ver) \ + public: \ + static const char *InterfaceName() { return Name; } \ + private: + + //virtual unsigned InterfaceID() { return INTERFACE_ID; } + //virtual const char *InterfaceName() { return name; } + + +// This kernel thingie makes the structure very flat and basiclly singletons. +// I'm not sure if this is a good idea but it works for now. +class IKernel +{ + // hide the implementation + virtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; + virtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; + virtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0; +public: + static IKernel *Create(); + virtual ~IKernel() {} + + // templated access to handle pointer convertions and interface names + template<class TINTERFACE> + bool RegisterInterface(TINTERFACE *pInterface) + { + return RegisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); + } + template<class TINTERFACE> + bool ReregisterInterface(TINTERFACE *pInterface) + { + return ReregisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); + } + + // Usage example: + // IMyInterface *pMyHandle = Kernel()->RequestInterface<IMyInterface>() + template<class TINTERFACE> + TINTERFACE *RequestInterface() + { + return reinterpret_cast<TINTERFACE *>(RequestInterfaceImpl(TINTERFACE::InterfaceName())); + } +}; + +#endif diff --git a/src/engine/keys.h b/src/engine/keys.h new file mode 100644 index 0000000..9a138b9 --- /dev/null +++ b/src/engine/keys.h @@ -0,0 +1,255 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_KEYS_H +#define ENGINE_KEYS_H +/* AUTO GENERATED! DO NOT EDIT MANUALLY! */ +enum +{ + KEY_UNKNOWN = 0, + KEY_FIRST = 0, + KEY_BACKSPACE = 8, + KEY_TAB = 9, + KEY_CLEAR = 12, + KEY_RETURN = 13, + KEY_PAUSE = 19, + KEY_ESCAPE = 27, + KEY_SPACE = 32, + KEY_EXCLAIM = 33, + KEY_QUOTEDBL = 34, + KEY_HASH = 35, + KEY_DOLLAR = 36, + KEY_AMPERSAND = 38, + KEY_QUOTE = 39, + KEY_LEFTPAREN = 40, + KEY_RIGHTPAREN = 41, + KEY_ASTERISK = 42, + KEY_PLUS = 43, + KEY_COMMA = 44, + KEY_MINUS = 45, + KEY_PERIOD = 46, + KEY_SLASH = 47, + KEY_0 = 48, + KEY_1 = 49, + KEY_2 = 50, + KEY_3 = 51, + KEY_4 = 52, + KEY_5 = 53, + KEY_6 = 54, + KEY_7 = 55, + KEY_8 = 56, + KEY_9 = 57, + KEY_COLON = 58, + KEY_SEMICOLON = 59, + KEY_LESS = 60, + KEY_EQUALS = 61, + KEY_GREATER = 62, + KEY_QUESTION = 63, + KEY_AT = 64, + KEY_LEFTBRACKET = 91, + KEY_BACKSLASH = 92, + KEY_RIGHTBRACKET = 93, + KEY_CARET = 94, + KEY_UNDERSCORE = 95, + KEY_BACKQUOTE = 96, + KEY_a = 97, + KEY_b = 98, + KEY_c = 99, + KEY_d = 100, + KEY_e = 101, + KEY_f = 102, + KEY_g = 103, + KEY_h = 104, + KEY_i = 105, + KEY_j = 106, + KEY_k = 107, + KEY_l = 108, + KEY_m = 109, + KEY_n = 110, + KEY_o = 111, + KEY_p = 112, + KEY_q = 113, + KEY_r = 114, + KEY_s = 115, + KEY_t = 116, + KEY_u = 117, + KEY_v = 118, + KEY_w = 119, + KEY_x = 120, + KEY_y = 121, + KEY_z = 122, + KEY_DELETE = 127, + KEY_WORLD_0 = 160, + KEY_WORLD_1 = 161, + KEY_WORLD_2 = 162, + KEY_WORLD_3 = 163, + KEY_WORLD_4 = 164, + KEY_WORLD_5 = 165, + KEY_WORLD_6 = 166, + KEY_WORLD_7 = 167, + KEY_WORLD_8 = 168, + KEY_WORLD_9 = 169, + KEY_WORLD_10 = 170, + KEY_WORLD_11 = 171, + KEY_WORLD_12 = 172, + KEY_WORLD_13 = 173, + KEY_WORLD_14 = 174, + KEY_WORLD_15 = 175, + KEY_WORLD_16 = 176, + KEY_WORLD_17 = 177, + KEY_WORLD_18 = 178, + KEY_WORLD_19 = 179, + KEY_WORLD_20 = 180, + KEY_WORLD_21 = 181, + KEY_WORLD_22 = 182, + KEY_WORLD_23 = 183, + KEY_WORLD_24 = 184, + KEY_WORLD_25 = 185, + KEY_WORLD_26 = 186, + KEY_WORLD_27 = 187, + KEY_WORLD_28 = 188, + KEY_WORLD_29 = 189, + KEY_WORLD_30 = 190, + KEY_WORLD_31 = 191, + KEY_WORLD_32 = 192, + KEY_WORLD_33 = 193, + KEY_WORLD_34 = 194, + KEY_WORLD_35 = 195, + KEY_WORLD_36 = 196, + KEY_WORLD_37 = 197, + KEY_WORLD_38 = 198, + KEY_WORLD_39 = 199, + KEY_WORLD_40 = 200, + KEY_WORLD_41 = 201, + KEY_WORLD_42 = 202, + KEY_WORLD_43 = 203, + KEY_WORLD_44 = 204, + KEY_WORLD_45 = 205, + KEY_WORLD_46 = 206, + KEY_WORLD_47 = 207, + KEY_WORLD_48 = 208, + KEY_WORLD_49 = 209, + KEY_WORLD_50 = 210, + KEY_WORLD_51 = 211, + KEY_WORLD_52 = 212, + KEY_WORLD_53 = 213, + KEY_WORLD_54 = 214, + KEY_WORLD_55 = 215, + KEY_WORLD_56 = 216, + KEY_WORLD_57 = 217, + KEY_WORLD_58 = 218, + KEY_WORLD_59 = 219, + KEY_WORLD_60 = 220, + KEY_WORLD_61 = 221, + KEY_WORLD_62 = 222, + KEY_WORLD_63 = 223, + KEY_WORLD_64 = 224, + KEY_WORLD_65 = 225, + KEY_WORLD_66 = 226, + KEY_WORLD_67 = 227, + KEY_WORLD_68 = 228, + KEY_WORLD_69 = 229, + KEY_WORLD_70 = 230, + KEY_WORLD_71 = 231, + KEY_WORLD_72 = 232, + KEY_WORLD_73 = 233, + KEY_WORLD_74 = 234, + KEY_WORLD_75 = 235, + KEY_WORLD_76 = 236, + KEY_WORLD_77 = 237, + KEY_WORLD_78 = 238, + KEY_WORLD_79 = 239, + KEY_WORLD_80 = 240, + KEY_WORLD_81 = 241, + KEY_WORLD_82 = 242, + KEY_WORLD_83 = 243, + KEY_WORLD_84 = 244, + KEY_WORLD_85 = 245, + KEY_WORLD_86 = 246, + KEY_WORLD_87 = 247, + KEY_WORLD_88 = 248, + KEY_WORLD_89 = 249, + KEY_WORLD_90 = 250, + KEY_WORLD_91 = 251, + KEY_WORLD_92 = 252, + KEY_WORLD_93 = 253, + KEY_WORLD_94 = 254, + KEY_WORLD_95 = 255, + KEY_KP0 = 256, + KEY_KP1 = 257, + KEY_KP2 = 258, + KEY_KP3 = 259, + KEY_KP4 = 260, + KEY_KP5 = 261, + KEY_KP6 = 262, + KEY_KP7 = 263, + KEY_KP8 = 264, + KEY_KP9 = 265, + KEY_KP_PERIOD = 266, + KEY_KP_DIVIDE = 267, + KEY_KP_MULTIPLY = 268, + KEY_KP_MINUS = 269, + KEY_KP_PLUS = 270, + KEY_KP_ENTER = 271, + KEY_KP_EQUALS = 272, + KEY_UP = 273, + KEY_DOWN = 274, + KEY_RIGHT = 275, + KEY_LEFT = 276, + KEY_INSERT = 277, + KEY_HOME = 278, + KEY_END = 279, + KEY_PAGEUP = 280, + KEY_PAGEDOWN = 281, + KEY_F1 = 282, + KEY_F2 = 283, + KEY_F3 = 284, + KEY_F4 = 285, + KEY_F5 = 286, + KEY_F6 = 287, + KEY_F7 = 288, + KEY_F8 = 289, + KEY_F9 = 290, + KEY_F10 = 291, + KEY_F11 = 292, + KEY_F12 = 293, + KEY_F13 = 294, + KEY_F14 = 295, + KEY_F15 = 296, + KEY_NUMLOCK = 300, + KEY_CAPSLOCK = 301, + KEY_SCROLLOCK = 302, + KEY_RSHIFT = 303, + KEY_LSHIFT = 304, + KEY_RCTRL = 305, + KEY_LCTRL = 306, + KEY_RALT = 307, + KEY_LALT = 308, + KEY_RMETA = 309, + KEY_LMETA = 310, + KEY_LSUPER = 311, + KEY_RSUPER = 312, + KEY_MODE = 313, + KEY_COMPOSE = 314, + KEY_HELP = 315, + KEY_PRINT = 316, + KEY_SYSREQ = 317, + KEY_BREAK = 318, + KEY_MENU = 319, + KEY_POWER = 320, + KEY_EURO = 321, + KEY_UNDO = 322, + KEY_MOUSE_1 = 323, + KEY_MOUSE_2 = 324, + KEY_MOUSE_3 = 325, + KEY_MOUSE_4 = 326, + KEY_MOUSE_5 = 327, + KEY_MOUSE_6 = 328, + KEY_MOUSE_7 = 329, + KEY_MOUSE_8 = 330, + KEY_MOUSE_WHEEL_UP = 331, + KEY_MOUSE_WHEEL_DOWN = 332, + KEY_MOUSE_9 = 333, + KEY_LAST, +}; + +#endif diff --git a/src/engine/map.h b/src/engine/map.h new file mode 100644 index 0000000..a831cd2 --- /dev/null +++ b/src/engine/map.h @@ -0,0 +1,36 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MAP_H +#define ENGINE_MAP_H + +#include "kernel.h" + +class IMap : public IInterface +{ + MACRO_INTERFACE("map", 0) +public: + virtual void *GetData(int Index) = 0; + virtual int GetUncompressedDataSize(int Index) = 0; + virtual void *GetDataSwapped(int Index) = 0; + virtual void UnloadData(int Index) = 0; + virtual void *GetItem(int Index, int *Type, int *pID) = 0; + virtual int GetItemSize(int Index) = 0; + virtual void GetType(int Type, int *pStart, int *pNum) = 0; + virtual void *FindItem(int Type, int ID) = 0; + virtual int NumItems() = 0; +}; + + +class IEngineMap : public IMap +{ + MACRO_INTERFACE("enginemap", 0) +public: + virtual bool Load(const char *pMapName) = 0; + virtual bool IsLoaded() = 0; + virtual void Unload() = 0; + virtual unsigned Crc() = 0; +}; + +extern IEngineMap *CreateEngineMap(); + +#endif diff --git a/src/engine/masterserver.h b/src/engine/masterserver.h new file mode 100644 index 0000000..d347e7c --- /dev/null +++ b/src/engine/masterserver.h @@ -0,0 +1,41 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MASTERSERVER_H +#define ENGINE_MASTERSERVER_H + +#include "kernel.h" + +class IMasterServer : public IInterface +{ + MACRO_INTERFACE("masterserver", 0) +public: + + enum + { + MAX_MASTERSERVERS=4 + }; + + virtual void Init() = 0; + virtual void SetDefault() = 0; + virtual int Load() = 0; + virtual int Save() = 0; + + virtual int RefreshAddresses(int Nettype) = 0; + virtual void Update() = 0; + virtual int IsRefreshing() = 0; + virtual NETADDR GetAddr(int Index) = 0; + virtual void SetCount(int Index, int Count) = 0; + virtual int GetCount(int Index) = 0; + virtual const char *GetName(int Index) = 0; + virtual bool IsValid(int Index) = 0; +}; + +class IEngineMasterServer : public IMasterServer +{ + MACRO_INTERFACE("enginemasterserver", 0) +public: +}; + +extern IEngineMasterServer *CreateEngineMasterServer(); + +#endif diff --git a/src/engine/message.h b/src/engine/message.h new file mode 100644 index 0000000..4f9cb4c --- /dev/null +++ b/src/engine/message.h @@ -0,0 +1,18 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_MESSAGE_H +#define ENGINE_MESSAGE_H + +#include <engine/shared/packer.h> + +class CMsgPacker : public CPacker +{ +public: + CMsgPacker(int Type) + { + Reset(); + AddInt(Type); + } +}; + +#endif diff --git a/src/engine/server.h b/src/engine/server.h new file mode 100644 index 0000000..e290906 --- /dev/null +++ b/src/engine/server.h @@ -0,0 +1,206 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_H +#define ENGINE_SERVER_H +#include "kernel.h" +#include "message.h" +#include <game/generated/protocol.h> +#include <engine/shared/protocol.h> + +class IServer : public IInterface +{ + MACRO_INTERFACE("server", 0) +protected: + int m_CurrentGameTick; + int m_TickSpeed; + +public: + /* + Structure: CClientInfo + */ + struct CClientInfo + { + const char *m_pName; + int m_Latency; + int m_ClientVersion; + }; + + int Tick() const { return m_CurrentGameTick; } + int TickSpeed() const { return m_TickSpeed; } + + virtual int MaxClients() const = 0; + virtual const char *ClientName(int ClientID) = 0; + virtual const char *ClientClan(int ClientID) = 0; + virtual int ClientCountry(int ClientID) = 0; + virtual bool ClientIngame(int ClientID) = 0; + virtual int GetClientInfo(int ClientID, CClientInfo *pInfo) = 0; + virtual void GetClientAddr(int ClientID, char *pAddrStr, int Size) = 0; + virtual void RestrictRconOutput(int ClientID) = 0; + + virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) = 0; + + template<class T> + int SendPackMsg(T *pMsg, int Flags, int ClientID) + { + int result = 0; + T tmp; + if (ClientID == -1) + { + for(int i = 0; i < MAX_CLIENTS; i++) + if(ClientIngame(i)) + { + mem_copy(&tmp, pMsg, sizeof(T)); + result = SendPackMsgTranslate(&tmp, Flags, i); + } + } else { + mem_copy(&tmp, pMsg, sizeof(T)); + result = SendPackMsgTranslate(&tmp, Flags, ClientID); + } + return result; + } + + template<class T> + int SendPackMsgTranslate(T *pMsg, int Flags, int ClientID) + { + return SendPackMsgOne(pMsg, Flags, ClientID); + } + + int SendPackMsgTranslate(CNetMsg_Sv_Emoticon *pMsg, int Flags, int ClientID) + { + return Translate(pMsg->m_ClientID, ClientID) && SendPackMsgOne(pMsg, Flags, ClientID); + } + + char msgbuf[1000]; + + int SendPackMsgTranslate(CNetMsg_Sv_Chat *pMsg, int Flags, int ClientID) + { + if (pMsg->m_ClientID >= 0 && !Translate(pMsg->m_ClientID, ClientID)) + { + str_format(msgbuf, sizeof(msgbuf), "%s: %s", ClientName(pMsg->m_ClientID), pMsg->m_pMessage); + pMsg->m_pMessage = msgbuf; + pMsg->m_ClientID = VANILLA_MAX_CLIENTS - 1; + } + return SendPackMsgOne(pMsg, Flags, ClientID); + } + + int SendPackMsgTranslate(CNetMsg_Sv_KillMsg *pMsg, int Flags, int ClientID) + { + if (!Translate(pMsg->m_Victim, ClientID)) return 0; + if (!Translate(pMsg->m_Killer, ClientID)) pMsg->m_Killer = pMsg->m_Victim; + return SendPackMsgOne(pMsg, Flags, ClientID); + } + + template<class T> + int SendPackMsgOne(T *pMsg, int Flags, int ClientID) + { + CMsgPacker Packer(pMsg->MsgID()); + if(pMsg->Pack(&Packer)) + return -1; + return SendMsg(&Packer, Flags, ClientID); + } + + bool Translate(int& target, int client) + { + CClientInfo info; + GetClientInfo(client, &info); + if (info.m_ClientVersion >= VERSION_DDNET_OLD) + return true; + int* map = GetIdMap(client); + bool found = false; + for (int i = 0; i < VANILLA_MAX_CLIENTS; i++) + { + if (target == map[i]) + { + target = i; + found = true; + break; + } + } + return found; + } + + bool ReverseTranslate(int& target, int client) + { + CClientInfo info; + GetClientInfo(client, &info); + if (info.m_ClientVersion >= VERSION_DDNET_OLD) + return true; + int* map = GetIdMap(client); + if (map[target] == -1) + return false; + target = map[target]; + return true; + } + + 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; + + enum + { + RCON_CID_SERV=-1, + RCON_CID_VOTE=-2, + }; + virtual void SetRconCID(int ClientID) = 0; + virtual bool IsAuthed(int ClientID) = 0; + virtual void Kick(int ClientID, const char *pReason) = 0; + + virtual void DemoRecorder_HandleAutoStart() = 0; + virtual bool DemoRecorder_IsRecording() = 0; + + // DDRace + + virtual void SaveDemo(int ClientID, float Time) = 0; + virtual void StartRecord(int ClientID) = 0; + virtual void StopRecord(int ClientID) = 0; + virtual bool IsRecording(int ClientID) = 0; + + virtual void GetClientAddr(int ClientID, NETADDR *pAddr) = 0; + + virtual int* GetIdMap(int ClientID) = 0; +}; + +class IGameServer : public IInterface +{ + MACRO_INTERFACE("gameserver", 0) +protected: +public: + virtual void OnInit() = 0; + virtual void OnConsoleInit() = 0; + virtual void OnMapChange(char *pNewMapName, int MapNameSize) = 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; + virtual void OnClientEnter(int ClientID) = 0; + virtual void OnClientDrop(int ClientID, const char *pReason) = 0; + virtual void OnClientDirectInput(int ClientID, void *pInput) = 0; + virtual void OnClientPredictedInput(int ClientID, void *pInput) = 0; + + 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; + + // DDRace + + virtual void OnSetAuthed(int ClientID, int Level) = 0; +}; + +extern IGameServer *CreateGameServer(); +#endif diff --git a/src/engine/server/register.cpp b/src/engine/server/register.cpp new file mode 100644 index 0000000..b287068 --- /dev/null +++ b/src/engine/server/register.cpp @@ -0,0 +1,289 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <engine/shared/network.h> +#include <engine/shared/config.h> +#include <engine/console.h> +#include <engine/masterserver.h> + +#include <mastersrv/mastersrv.h> + +#include "register.h" + +CRegister::CRegister() +{ + m_pNetServer = 0; + m_pMasterServer = 0; + m_pConsole = 0; + + m_RegisterState = REGISTERSTATE_START; + m_RegisterStateStart = 0; + m_RegisterFirst = 1; + m_RegisterCount = 0; + + mem_zero(m_aMasterserverInfo, sizeof(m_aMasterserverInfo)); + m_RegisterRegisteredServer = -1; +} + +void CRegister::RegisterNewState(int State) +{ + m_RegisterState = State; + m_RegisterStateStart = time_get(); +} + +void CRegister::RegisterSendFwcheckresponse(NETADDR *pAddr) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = *pAddr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE); + 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; + Packet.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2; + Packet.m_pData = &aData; + + // supply the set port that the master can use if it has problems + if(g_Config.m_SvExternalPort) + Port = g_Config.m_SvExternalPort; + aData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8; + aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff; + m_pNetServer->Send(&Packet); +} + +void CRegister::RegisterSendCountRequest(NETADDR Addr) +{ + CNetChunk Packet; + Packet.m_ClientID = -1; + Packet.m_Address = Addr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + Packet.m_DataSize = sizeof(SERVERBROWSE_GETCOUNT); + Packet.m_pData = SERVERBROWSE_GETCOUNT; + m_pNetServer->Send(&Packet); +} + +void CRegister::RegisterGotCount(CNetChunk *pChunk) +{ + unsigned char *pData = (unsigned char *)pChunk->m_pData; + int Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1]; + + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(net_addr_comp(&m_aMasterserverInfo[i].m_Addr, &pChunk->m_Address) == 0) + { + m_aMasterserverInfo[i].m_Count = Count; + break; + } + } +} + +void CRegister::Init(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole) +{ + m_pNetServer = pNetServer; + m_pMasterServer = pMasterServer; + m_pConsole = pConsole; +} + +void CRegister::RegisterUpdate(int Nettype) +{ + int64 Now = time_get(); + int64 Freq = time_freq(); + + if(!g_Config.m_SvRegister) + return; + + m_pMasterServer->Update(); + + if(m_RegisterState == REGISTERSTATE_START) + { + m_RegisterCount = 0; + m_RegisterFirst = 1; + RegisterNewState(REGISTERSTATE_UPDATE_ADDRS); + m_pMasterServer->RefreshAddresses(Nettype); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "refreshing ip addresses"); + } + else if(m_RegisterState == REGISTERSTATE_UPDATE_ADDRS) + { + m_RegisterRegisteredServer = -1; + + if(!m_pMasterServer->IsRefreshing()) + { + int i; + for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_pMasterServer->IsValid(i)) + { + m_aMasterserverInfo[i].m_Valid = 0; + m_aMasterserverInfo[i].m_Count = 0; + continue; + } + + NETADDR Addr = m_pMasterServer->GetAddr(i); + m_aMasterserverInfo[i].m_Addr = Addr; + m_aMasterserverInfo[i].m_Valid = 1; + 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); + } + } + else if(m_RegisterState == REGISTERSTATE_QUERY_COUNT) + { + int Left = 0; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + if(!m_aMasterserverInfo[i].m_Valid) + continue; + + if(m_aMasterserverInfo[i].m_Count == -1) + { + Left++; + if(m_aMasterserverInfo[i].m_LastSend+Freq < Now) + { + m_aMasterserverInfo[i].m_LastSend = Now; + RegisterSendCountRequest(m_aMasterserverInfo[i].m_Addr); + } + } + } + + // check if we are done or timed out + if(Left == 0 || Now > m_RegisterStateStart+Freq*3) + { + // choose server + int Best = -1; + int i; + for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + 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; + } + + // server chosen + m_RegisterRegisteredServer = Best; + if(m_RegisterRegisteredServer == -1) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: No master servers. Retrying in 60 seconds"); + 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); + m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = 0; + RegisterNewState(REGISTERSTATE_HEARTBEAT); + } + } + } + else if(m_RegisterState == REGISTERSTATE_HEARTBEAT) + { + // check if we should send heartbeat + if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15) + { + 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"); + RegisterNewState(REGISTERSTATE_START); + } + } + else if(m_RegisterState == REGISTERSTATE_REGISTERED) + { + 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) + { + if(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers + RegisterNewState(REGISTERSTATE_START); + else + { + m_RegisterCount++; + RegisterNewState(REGISTERSTATE_HEARTBEAT); + } + } + } + else if(m_RegisterState == REGISTERSTATE_ERROR) + { + // check for restart + if(Now > m_RegisterStateStart+Freq*60) + RegisterNewState(REGISTERSTATE_START); + } +} + +int CRegister::RegisterProcessPacket(CNetChunk *pPacket) +{ + // check for masterserver address + bool Valid = false; + NETADDR Addr1 = pPacket->m_Address; + Addr1.port = 0; + for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) + { + NETADDR Addr2 = m_aMasterserverInfo[i].m_Addr; + Addr2.port = 0; + if(net_addr_comp(&Addr1, &Addr2) == 0) + { + Valid = true; + break; + } + } + if(!Valid) + return 0; + + if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWCHECK) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0) + { + RegisterSendFwcheckresponse(&pPacket->m_Address); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWOK) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0) + { + if(m_RegisterFirst) + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "no firewall/nat problems detected"); + RegisterNewState(REGISTERSTATE_REGISTERED); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWERROR) && + mem_comp(pPacket->m_pData, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "ERROR: the master server reports that clients can not connect to this server."); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ERROR: configure your firewall/nat to let through udp on port %d.", g_Config.m_SvPort); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); + //RegisterNewState(REGISTERSTATE_ERROR); + return 1; + } + else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 && + mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) + { + RegisterGotCount(pPacket); + return 1; + } + + return 0; +} diff --git a/src/engine/server/register.h b/src/engine/server/register.h new file mode 100644 index 0000000..36ed0ce --- /dev/null +++ b/src/engine/server/register.h @@ -0,0 +1,53 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_REGISTER_H +#define ENGINE_SERVER_REGISTER_H + +#include <engine/masterserver.h> + +class CRegister +{ + enum + { + REGISTERSTATE_START=0, + REGISTERSTATE_UPDATE_ADDRS, + REGISTERSTATE_QUERY_COUNT, + REGISTERSTATE_HEARTBEAT, + REGISTERSTATE_REGISTERED, + REGISTERSTATE_ERROR + }; + + struct CMasterserverInfo + { + NETADDR m_Addr; + int m_Count; + int m_Valid; + int64 m_LastSend; + }; + + class CNetServer *m_pNetServer; + class IEngineMasterServer *m_pMasterServer; + class IConsole *m_pConsole; + + int m_RegisterState; + int64 m_RegisterStateStart; + int m_RegisterFirst; + int m_RegisterCount; + + CMasterserverInfo m_aMasterserverInfo[IMasterServer::MAX_MASTERSERVERS]; + int m_RegisterRegisteredServer; + + void RegisterNewState(int State); + void RegisterSendFwcheckresponse(NETADDR *pAddr); + void RegisterSendHeartbeat(NETADDR Addr); + void RegisterSendCountRequest(NETADDR Addr); + void RegisterGotCount(struct CNetChunk *pChunk); + +public: + CRegister(); + void Init(class CNetServer *pNetServer, class IEngineMasterServer *pMasterServer, class IConsole *pConsole); + void RegisterUpdate(int Nettype); + int RegisterProcessPacket(struct CNetChunk *pPacket); +}; + +#endif diff --git a/src/engine/server/server.cpp b/src/engine/server/server.cpp new file mode 100644 index 0000000..7fccfeb --- /dev/null +++ b/src/engine/server/server.cpp @@ -0,0 +1,2313 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/config.h> +#include <engine/console.h> +#include <engine/engine.h> +#include <engine/map.h> +#include <engine/masterserver.h> +#include <engine/server.h> +#include <engine/storage.h> + +#include <engine/shared/compression.h> +#include <engine/shared/config.h> +#include <engine/shared/datafile.h> +#include <engine/shared/demo.h> +#include <engine/shared/econ.h> +#include <engine/shared/filecollection.h> +#include <engine/shared/mapchecker.h> +#include <engine/shared/netban.h> +#include <engine/shared/network.h> +#include <engine/shared/packer.h> +#include <engine/shared/protocol.h> +#include <engine/shared/snapshot.h> +#include <engine/shared/fifoconsole.h> + +#include <mastersrv/mastersrv.h> + +// DDRace +#include <string.h> +#include <vector> +#include <engine/shared/linereader.h> +#include <game/server/gamecontext.h> + +#include "register.h" +#include "server.h" + +#if defined(CONF_FAMILY_WINDOWS) + #define _WIN32_WINNT 0x0501 + #define WIN32_LEAN_AND_MEAN + #include <windows.h> +#endif + +static const char *StrLtrim(const char *pStr) +{ + while(*pStr) + { + const char *pStrOld = pStr; + int Code = str_utf8_decode(&pStr); + + // check if unicode is not empty + if(str_utf8_isspace(Code)) + { + return pStrOld; + } + } + return pStr; +} + +static void StrRtrim(char *pStr) +{ + const char *p = pStr; + const char *pEnd = 0; + while(*p) + { + const char *pStrOld = p; + int Code = str_utf8_decode(&p); + + // check if unicode is not empty + if(str_utf8_isspace(Code)) + { + pEnd = 0; + } + else if(pEnd == 0) + pEnd = pStrOld; + } + if(pEnd != 0) + *(const_cast<char *>(pEnd)) = 0; +} + + +CSnapIDPool::CSnapIDPool() +{ + Reset(); +} + +void CSnapIDPool::Reset() +{ + for(int i = 0; i < MAX_IDS; i++) + { + 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; + m_LastTimed = -1; + m_Usage = 0; + m_InUsage = 0; +} + + +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--; +} + +int CSnapIDPool::NewID() +{ + int64 Now = time_get(); + + // 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) + return ID; + m_FirstFree = m_aIDs[m_FirstFree].m_Next; + m_aIDs[ID].m_State = 1; + m_Usage++; + m_InUsage++; + return ID; +} + +void CSnapIDPool::TimeoutIDs() +{ + // process timed ids + while(m_FirstTimed != -1) + RemoveFirstTimeout(); +} + +void CSnapIDPool::FreeID(int ID) +{ + if(ID < 0) + return; + dbg_assert(m_aIDs[ID].m_State == 1, "id is not alloced"); + + m_InUsage--; + 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; + m_LastTimed = ID; + } + else + { + m_FirstTimed = ID; + m_LastTimed = ID; + } +} + + +void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer) +{ + CNetBan::Init(pConsole, pStorage); + + m_pServer = pServer; + + // overwrites base command, todo: improve this + Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason"); +} + +template<class T> +int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) +{ + // validate address + if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS && + Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) + { + if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)"); + return -1; + } + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); + return -1; + } + } + } + else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); + return -1; + } + } + } + + int Result = Ban(pBanPool, pData, Seconds, pReason); + if(Result != 0) + return Result; + + // drop banned clients + typename T::CDataType Data = *pData; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + + if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i))) + { + CNetHash NetHash(&Data); + char aBuf[256]; + MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER); + Server()->m_NetServer.Drop(i, aBuf); + } + } + + return Result; +} + +int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) +{ + return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason); +} + +int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) +{ + if(pRange->IsValid()) + return BanExt(&m_BanRangePool, pRange, Seconds, pReason); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser) +{ + CServerBan *pThis = static_cast<CServerBan *>(pUser); + + const char *pStr = pResult->GetString(0); + int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; + const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; + + if(StrAllnum(pStr)) + { + int ClientID = str_toint(pStr); + if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)"); + else + pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason); + } + else + ConBan(pResult, pUser); +} + + +void CServer::CClient::Reset() +{ + // reset input + for(int i = 0; i < 200; i++) + m_aInputs[i].m_GameTick = -1; + m_CurrentInput = 0; + mem_zero(&m_LatestInput, sizeof(m_LatestInput)); + + m_Snapshots.PurgeAll(); + m_LastAckedSnapshot = -1; + m_LastInputTick = -1; + m_SnapRate = CClient::SNAPRATE_INIT; + m_Score = 0; +} + +CServer::CServer() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + m_aDemoRecorder[i] = CDemoRecorder(&m_SnapshotDelta, true); + m_aDemoRecorder[MAX_CLIENTS] = CDemoRecorder(&m_SnapshotDelta, false); + + m_TickSpeed = SERVER_TICK_SPEED; + + m_pGameServer = 0; + + m_CurrentGameTick = 0; + m_RunServer = 1; + + m_pCurrentMapData = 0; + m_CurrentMapSize = 0; + + m_MapReload = 0; + m_ReloadedWhenEmpty = false; + + m_RconClientID = IServer::RCON_CID_SERV; + m_RconAuthLevel = AUTHED_ADMIN; + + m_RconRestrict = -1; + m_GeneratedRconPassword = 0; + + m_ServerInfoFirstRequest = 0; + m_ServerInfoNumRequests = 0; + m_ServerInfoHighLoad = false; + + Init(); +} + + +int CServer::TrySetClientName(int ClientID, const char *pName) +{ + char aTrimmedName[64]; + + // trim the name + str_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName)); + StrRtrim(aTrimmedName); + + // check for empty names + if(!aTrimmedName[0]) + return -1; + + // make sure that two clients don't have the same name + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY) + { + if(str_utf8_comp_names(aTrimmedName, m_aClients[i].m_aName) == 0) + return -1; + } + } + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "'%s' -> '%s'", pName, aTrimmedName); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + pName = aTrimmedName; + + // set the client name + str_copy(m_aClients[ClientID].m_aName, pName, MAX_NAME_LENGTH); + return 0; +} + + + +void CServer::SetClientName(int ClientID, const char *pName) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State < CClient::STATE_READY and ClientID < MAX_CLIENTS-1)) + return; + + if(!pName) + return; + + char aNameTry[MAX_NAME_LENGTH]; + str_copy(aNameTry, pName, sizeof(aNameTry)); + if(TrySetClientName(ClientID, aNameTry)) + { + // auto rename + for(int i = 1;; i++) + { + str_format(aNameTry, sizeof(aNameTry), "(%d)%s", i, pName); + if(TrySetClientName(ClientID, aNameTry) == 0) + break; + } + } +} + +void CServer::SetClientClan(int ClientID, const char *pClan) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State < CClient::STATE_READY and ClientID < MAX_CLIENTS-1) || !pClan) + return; + + str_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH); +} + +void CServer::SetClientCountry(int ClientID, int Country) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State < CClient::STATE_READY and ClientID < MAX_CLIENTS-1)) + return; + + m_aClients[ClientID].m_Country = Country; +} + +void CServer::SetClientScore(int ClientID, int Score) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State < CClient::STATE_READY and ClientID < MAX_CLIENTS-1)) + return; + m_aClients[ClientID].m_Score = Score; +} + +void CServer::Kick(int ClientID, const char *pReason) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id to kick"); + return; + } + else if(m_RconClientID == ClientID) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself"); + return; + } + else if(m_aClients[ClientID].m_Authed > m_RconAuthLevel) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "kick command denied"); + return; + } + + m_NetServer.Drop(ClientID, pReason); +} + +/*int CServer::Tick() +{ + return m_CurrentGameTick; +}*/ + +int64 CServer::TickStartTime(int Tick) +{ + return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED; +} + +/*int CServer::TickSpeed() +{ + return SERVER_TICK_SPEED; +}*/ + +int CServer::Init() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + { + m_aClients[i].m_State = CClient::STATE_EMPTY; + m_aClients[i].m_aName[0] = 0; + m_aClients[i].m_aClan[0] = 0; + m_aClients[i].m_Country = -1; + m_aClients[i].m_Snapshots.Init(); + m_aClients[i].m_Traffic = 0; + m_aClients[i].m_TrafficSince = 0; + } + + m_CurrentGameTick = 0; + + m_AnnouncementLastLine = 0; + memset(m_aPrevStates, CClient::STATE_EMPTY, MAX_CLIENTS * sizeof(int)); + + return 0; +} + +void CServer::SetRconCID(int ClientID) +{ + m_RconClientID = ClientID; +} + +bool CServer::IsAuthed(int ClientID) +{ + return m_aClients[ClientID].m_Authed; +} + +int CServer::GetClientInfo(int ClientID, CClientInfo *pInfo) +{ + dbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, "client_id is not valid"); + dbg_assert(pInfo != 0, "info can not be null"); + + if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) + { + pInfo->m_pName = m_aClients[ClientID].m_aName; + pInfo->m_Latency = m_aClients[ClientID].m_Latency; + CGameContext *GameServer = (CGameContext *) m_pGameServer; + if (GameServer->m_apPlayers[ClientID]) + pInfo->m_ClientVersion = GameServer->m_apPlayers[ClientID]->m_ClientVersion; + return 1; + } + return 0; +} + +void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size) +{ + if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME) + net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false); +} + + +const char *CServer::ClientName(int ClientID) +{ + if((ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY and ClientID < MAX_CLIENTS-1))) + return "(invalid)"; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME or ClientID >= MAX_CLIENTS-1) + return m_aClients[ClientID].m_aName; + else + return "(connecting)"; + +} + +const char *CServer::ClientClan(int ClientID) +{ + if((ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY and ClientID < MAX_CLIENTS-1))) + return ""; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME or ClientID >= MAX_CLIENTS-1) + return m_aClients[ClientID].m_aClan; + else + return ""; +} + +int CServer::ClientCountry(int ClientID) +{ + if((ClientID < 0 || ClientID >= MAX_CLIENTS || (m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY and ClientID < MAX_CLIENTS-1))) + return -1; + if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME or ClientID >= MAX_CLIENTS-1) + return m_aClients[ClientID].m_Country; + else + return -1; +} + +bool CServer::ClientIngame(int ClientID) +{ + return ClientID >= 0 && ClientID < MAX_CLIENTS && (m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME or ClientID >= MAX_CLIENTS-1); +} + +int CServer::MaxClients() const +{ + return m_NetServer.MaxClients(); +} + +void CServer::InitRconPasswordIfEmpty() +{ + if(g_Config.m_SvRconPassword[0]) + { + return; + } + + static const char VALUES[] = "ABCDEFGHKLMNPRSTUVWXYZabcdefghjkmnopqt23456789"; + static const size_t NUM_VALUES = sizeof(VALUES) - 1; // Disregard the '\0'. + static const size_t PASSWORD_LENGTH = 6; + dbg_assert(NUM_VALUES * NUM_VALUES >= 2048, "need at least 2048 possibilities for 2-character sequences"); + // With 6 characters, we get a password entropy of log(2048) * 6/2 = 33bit. + + dbg_assert(PASSWORD_LENGTH % 2 == 0, "need an even password length"); + unsigned short aRandom[PASSWORD_LENGTH / 2]; + char aRandomPassword[PASSWORD_LENGTH+1]; + aRandomPassword[PASSWORD_LENGTH] = 0; + + secure_random_fill(aRandom, sizeof(aRandom)); + for(size_t i = 0; i < PASSWORD_LENGTH / 2; i++) + { + unsigned short RandomNumber = aRandom[i] % 2048; + aRandomPassword[2 * i + 0] = VALUES[RandomNumber / NUM_VALUES]; + aRandomPassword[2 * i + 1] = VALUES[RandomNumber % NUM_VALUES]; + } + + str_copy(g_Config.m_SvRconPassword, aRandomPassword, sizeof(g_Config.m_SvRconPassword)); + m_GeneratedRconPassword = 1; +} + +int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) +{ + return SendMsgEx(pMsg, Flags, ClientID, false); +} + +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) + *((unsigned char*)Packet.m_pData) |= 1; + + if(Flags&MSGFLAG_VITAL) + Packet.m_Flags |= NETSENDFLAG_VITAL; + if(Flags&MSGFLAG_FLUSH) + Packet.m_Flags |= NETSENDFLAG_FLUSH; + + // write message to demo recorder + if(!(Flags&MSGFLAG_NORECORD)) + { + if(ClientID > -1) + m_aDemoRecorder[ClientID].RecordMessage(pMsg->Data(), pMsg->Size()); + m_aDemoRecorder[MAX_CLIENTS].RecordMessage(pMsg->Data(), pMsg->Size()); + } + + if(!(Flags&MSGFLAG_NOSEND)) + { + if(ClientID == -1) + { + // broadcast + int i; + for(i = 0; i < MAX_CLIENTS; i++) + if(m_aClients[i].m_State == CClient::STATE_INGAME) + { + Packet.m_ClientID = i; + m_NetServer.Send(&Packet); + } + } + else + m_NetServer.Send(&Packet); + } + return 0; +} + +void CServer::DoSnapshot() +{ + GameServer()->OnPreSnap(); + + // create snapshot for demo recording + if(m_aDemoRecorder[MAX_CLIENTS].IsRecording()) + { + char aData[CSnapshot::MAX_SIZE]; + int SnapshotSize; + + // build snap and possibly add some messages + m_SnapshotBuilder.Init(); + GameServer()->OnSnap(-1); + SnapshotSize = m_SnapshotBuilder.Finish(aData); + + // for antiping: if the projectile netobjects contains extra data, this is removed and the original content restored before recording demo + unsigned char aExtraInfoRemoved[CSnapshot::MAX_SIZE]; + mem_copy(aExtraInfoRemoved, aData, SnapshotSize); + SnapshotRemoveExtraInfo(aExtraInfoRemoved); + // write snapshot + m_aDemoRecorder[MAX_CLIENTS].RecordSnapshot(Tick(), aExtraInfoRemoved, SnapshotSize); + } + + // create snapshots for all clients + for(int i = 0; i < MAX_CLIENTS; i++) + { + // 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 + char aDeltaData[CSnapshot::MAX_SIZE]; + char aCompData[CSnapshot::MAX_SIZE]; + int SnapshotSize; + int Crc; + static CSnapshot EmptySnap; + CSnapshot *pDeltashot = &EmptySnap; + int DeltashotSize; + int DeltaTick = -1; + int DeltaSize; + + m_SnapshotBuilder.Init(); + + GameServer()->OnSnap(i); + + // finish snapshot + SnapshotSize = m_SnapshotBuilder.Finish(pData); + + if(m_aDemoRecorder[i].IsRecording()) + { + // for antiping: if the projectile netobjects contains extra data, this is removed and the original content restored before recording demo + unsigned char aExtraInfoRemoved[CSnapshot::MAX_SIZE]; + mem_copy(aExtraInfoRemoved, aData, SnapshotSize); + SnapshotRemoveExtraInfo(aExtraInfoRemoved); + // write snapshot + m_aDemoRecorder[i].RecordSnapshot(Tick(), aExtraInfoRemoved, SnapshotSize); + } + + Crc = pData->Crc(); + + // 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) + DeltaTick = m_aClients[i].m_LastAckedSnapshot; + else + { + // no acked package found, force client to recover rate + if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL) + m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER; + } + } + + // create delta + DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData); + + if(DeltaSize) + { + // compress it + int SnapshotSize; + const int MaxSize = MAX_SNAPSHOT_PACKSIZE; + int NumPackets; + + 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; + Left -= Chunk; + + if(NumPackets == 1) + { + CMsgPacker Msg(NETMSG_SNAPSINGLE); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(Crc); + Msg.AddInt(Chunk); + Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true); + } + else + { + CMsgPacker Msg(NETMSG_SNAP); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + Msg.AddInt(NumPackets); + Msg.AddInt(n); + Msg.AddInt(Crc); + Msg.AddInt(Chunk); + Msg.AddRaw(&aCompData[n*MaxSize], Chunk); + SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true); + } + } + } + else + { + CMsgPacker Msg(NETMSG_SNAPEMPTY); + Msg.AddInt(m_CurrentGameTick); + Msg.AddInt(m_CurrentGameTick-DeltaTick); + SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true); + } + } + } + + GameServer()->OnPostSnap(); +} + +int CServer::ClientRejoinCallback(int ClientID, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + + pThis->m_aClients[ClientID].Reset(); + + pThis->SendMap(ClientID); + + return 0; +} + +int CServer::NewClientNoAuthCallback(int ClientID, bool Reset, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + if (Reset) + { + pThis->m_aClients[ClientID].m_State = CClient::STATE_CONNECTING; + pThis->m_aClients[ClientID].m_aName[0] = 0; + pThis->m_aClients[ClientID].m_aClan[0] = 0; + pThis->m_aClients[ClientID].m_Country = -1; + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_AuthTries = 0; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + pThis->m_aClients[ClientID].Reset(); + } + + pThis->SendMap(ClientID); + + return 0; +} + +int CServer::NewClientCallback(int ClientID, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + pThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH; + pThis->m_aClients[ClientID].m_aName[0] = 0; + pThis->m_aClients[ClientID].m_aClan[0] = 0; + pThis->m_aClients[ClientID].m_Country = -1; + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_AuthTries = 0; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + pThis->m_aClients[ClientID].m_Traffic = 0; + pThis->m_aClients[ClientID].m_TrafficSince = 0; + memset(&pThis->m_aClients[ClientID].m_Addr, 0, sizeof(NETADDR)); + pThis->m_aClients[ClientID].Reset(); + return 0; +} + +int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser) +{ + CServer *pThis = (CServer *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + + // 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; + pThis->m_aClients[ClientID].m_Country = -1; + pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; + pThis->m_aClients[ClientID].m_AuthTries = 0; + pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; + pThis->m_aClients[ClientID].m_Traffic = 0; + pThis->m_aClients[ClientID].m_TrafficSince = 0; + pThis->m_aPrevStates[ClientID] = CClient::STATE_EMPTY; + pThis->m_aClients[ClientID].m_Snapshots.PurgeAll(); + return 0; +} + +static int lastsent[MAX_CLIENTS]; +static int lastask[MAX_CLIENTS]; +static int lastasktick[MAX_CLIENTS]; + +void CServer::SendMap(int ClientID) +{ + lastsent[ClientID] = 0; + lastask[ClientID] = 0; + lastasktick[ClientID] = Tick(); + CMsgPacker Msg(NETMSG_MAP_CHANGE); + Msg.AddString(GetMapName(), 0); + Msg.AddInt(m_CurrentMapCrc); + Msg.AddInt(m_CurrentMapSize); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true); +} + +void CServer::SendConnectionReady(int ClientID) +{ + CMsgPacker Msg(NETMSG_CON_READY); + SendMsgEx(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID, true); +} + +void CServer::SendRconLine(int ClientID, const char *pLine) +{ + CMsgPacker Msg(NETMSG_RCON_LINE); + Msg.AddString(pLine, 512); + SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true); +} + +void CServer::SendRconLineAuthed(const char *pLine, void *pUser, bool Highlighted) +{ + 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->m_RconAuthLevel && (pThis->m_RconRestrict == -1 || pThis->m_RconRestrict == i)) + pThis->SendRconLine(i, pLine); + } + + ReentryGuard--; +} + +void CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID) +{ + CMsgPacker Msg(NETMSG_RCON_CMD_ADD); + Msg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH); + Msg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); + Msg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); + SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true); +} + +void CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID) +{ + CMsgPacker Msg(NETMSG_RCON_CMD_REM); + Msg.AddString(pCommandInfo->m_pName, 256); + SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true); +} + +void CServer::UpdateClientRconCommands() +{ + int ClientID = Tick() % MAX_CLIENTS; + + if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed) + { + int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : m_aClients[ClientID].m_Authed == AUTHED_MOD ? IConsole::ACCESS_LEVEL_MOD : IConsole::ACCESS_LEVEL_HELPER; + for(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i) + { + SendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID); + m_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER); + } + } +} + +void CServer::ProcessClientPacket(CNetChunk *pPacket) +{ + int ClientID = pPacket->m_ClientID; + 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(g_Config.m_SvNetlimit && Msg != NETMSG_REQUEST_MAP_DATA) + { + int64 Now = time_get(); + int64 Diff = Now - m_aClients[ClientID].m_TrafficSince; + float Alpha = g_Config.m_SvNetlimitAlpha / 100.0; + float Limit = (float) g_Config.m_SvNetlimit * 1024 / time_freq(); + + if (m_aClients[ClientID].m_Traffic > Limit) + { + m_NetServer.NetBan()->BanAddr(&pPacket->m_Address, 600, "Stressing network"); + return; + } + if (Diff > 100) + { + m_aClients[ClientID].m_Traffic = (Alpha * ((float) pPacket->m_DataSize / Diff)) + (1.0 - Alpha) * m_aClients[ClientID].m_Traffic; + m_aClients[ClientID].m_TrafficSince = Now; + } + } + + if(Sys) + { + // system message + if(Msg == NETMSG_INFO) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_AUTH) + { + const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(!str_utf8_check(pVersion)) + { + return; + } + if(str_comp(pVersion, GameServer()->NetVersion()) != 0) + { + // wrong version + char aReason[256]; + str_format(aReason, sizeof(aReason), "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion); + m_NetServer.Drop(ClientID, aReason); + return; + } + + const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(!str_utf8_check(pPassword)) + { + return; + } + if(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0) + { + // wrong password + m_NetServer.Drop(ClientID, "Wrong password"); + return; + } + + // reserved slot + if(ClientID >= (g_Config.m_SvMaxClients - g_Config.m_SvReservedSlots) && g_Config.m_SvReservedSlotsPass[0] != 0 && strcmp(g_Config.m_SvReservedSlotsPass, pPassword) != 0) + { + m_NetServer.Drop(ClientID, "This server is full"); + return; + } + + m_aClients[ClientID].m_State = CClient::STATE_CONNECTING; + SendMap(ClientID); + } + } + else if(Msg == NETMSG_REQUEST_MAP_DATA) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) == 0 || m_aClients[ClientID].m_State < CClient::STATE_CONNECTING) + return; + + int Chunk = Unpacker.GetInt(); + unsigned int ChunkSize = 1024-128; + unsigned int Offset = Chunk * ChunkSize; + int Last = 0; + + lastask[ClientID] = Chunk; + lastasktick[ClientID] = Tick(); + if (Chunk == 0) + { + lastsent[ClientID] = 0; + } + + // drop faulty map data requests + if(Chunk < 0 || Offset > m_CurrentMapSize) + return; + + if(Offset+ChunkSize >= m_CurrentMapSize) + { + ChunkSize = m_CurrentMapSize-Offset; + Last = 1; + } + + if (lastsent[ClientID] < Chunk+g_Config.m_SvMapWindow && g_Config.m_SvFastDownload) + return; + + CMsgPacker Msg(NETMSG_MAP_DATA); + Msg.AddInt(Last); + Msg.AddInt(m_CurrentMapCrc); + Msg.AddInt(Chunk); + Msg.AddInt(ChunkSize); + Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize); + SendMsgEx(&Msg, MSGFLAG_FLUSH, ClientID, true); + + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + else if(Msg == NETMSG_READY) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_CONNECTING) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%d addr=%s secure=%s", ClientID, aAddrStr, m_NetServer.HasSecurityToken(ClientID)?"yes":"no"); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + m_aClients[ClientID].m_State = CClient::STATE_READY; + GameServer()->OnClientConnected(ClientID); + } + + SendConnectionReady(ClientID); + } + else if(Msg == NETMSG_ENTERGAME) + { + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID)) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%d addr=%s", ClientID, aAddrStr); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + m_aClients[ClientID].m_State = CClient::STATE_INGAME; + GameServer()->OnClientEnter(ClientID); + } + } + else if(Msg == NETMSG_INPUT) + { + 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()); + + // add message to report the input timing + // skip packets that are old + 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); + SendMsgEx(&Msg, 0, ClientID, true); + } + + 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); + } + else if(Msg == NETMSG_RCON_CMD) + { + const char *pCmd = Unpacker.GetString(); + if(!str_utf8_check(pCmd)) + { + return; + } + if(Unpacker.Error() == 0 && !str_comp(pCmd, "crashmeplx")) + { + CGameContext *GameServer = (CGameContext *) m_pGameServer; + if (GameServer->m_apPlayers[ClientID] && GameServer->m_apPlayers[ClientID]->m_ClientVersion < VERSION_DDNET_OLD) + GameServer->m_apPlayers[ClientID]->m_ClientVersion = VERSION_DDNET_OLD; + } else + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) + { + CGameContext *GameServer = (CGameContext *) m_pGameServer; + if (GameServer->m_apPlayers[ClientID]) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); + m_RconClientID = ClientID; + m_RconAuthLevel = m_aClients[ClientID].m_Authed; + Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : m_aClients[ClientID].m_Authed == AUTHED_MOD ? IConsole::ACCESS_LEVEL_MOD : m_aClients[ClientID].m_Authed == AUTHED_HELPER ? IConsole::ACCESS_LEVEL_HELPER : IConsole::ACCESS_LEVEL_USER); + Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER, ClientID); + Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN); + m_RconClientID = IServer::RCON_CID_SERV; + m_RconAuthLevel = AUTHED_ADMIN; + } + } + } + else if(Msg == NETMSG_RCON_AUTH) + { + const char *pPw; + Unpacker.GetString(); // login name, not used + pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC); + if(!str_utf8_check(pPw)) + { + return; + } + + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && Unpacker.Error() == 0) + { + int AuthLevel = -1; + + if(g_Config.m_SvRconPassword[0] == 0 && g_Config.m_SvRconModPassword[0] == 0 && g_Config.m_SvRconHelperPassword[0] == 0) + { + SendRconLine(ClientID, "No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console."); + } + else if(g_Config.m_SvRconPassword[0] && str_comp(pPw, g_Config.m_SvRconPassword) == 0) + AuthLevel = AUTHED_ADMIN; + else if(g_Config.m_SvRconModPassword[0] && str_comp(pPw, g_Config.m_SvRconModPassword) == 0) + AuthLevel = AUTHED_MOD; + else if(g_Config.m_SvRconHelperPassword[0] && str_comp(pPw, g_Config.m_SvRconHelperPassword) == 0) + AuthLevel = AUTHED_HELPER; + + if(AuthLevel != -1) + { + if(m_aClients[ClientID].m_Authed != AuthLevel) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS); + Msg.AddInt(1); //authed + Msg.AddInt(1); //cmdlist + SendMsgEx(&Msg, MSGFLAG_VITAL, ClientID, true); + + m_aClients[ClientID].m_Authed = AuthLevel; + int SendRconCmds = Unpacker.GetInt(); + if(Unpacker.Error() == 0 && SendRconCmds) + // AUTHED_ADMIN - AuthLevel gets the proper IConsole::ACCESS_LEVEL_<x> + m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(AUTHED_ADMIN - AuthLevel, CFGFLAG_SERVER); + + char aBuf[256]; + switch (AuthLevel) + { + case AUTHED_ADMIN: + { + SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (admin)", ClientID); + break; + } + case AUTHED_MOD: + { + SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (moderator)", ClientID); + break; + } + case AUTHED_HELPER: + { + SendRconLine(ClientID, "Helper authentication successful. Limited remote console access granted."); + str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (helper)", ClientID); + break; + } + } + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + // DDRace + GameServer()->OnSetAuthed(ClientID, AuthLevel); + } + } + else if(g_Config.m_SvRconMaxTries) + { + m_aClients[ClientID].m_AuthTries++; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, g_Config.m_SvRconMaxTries); + SendRconLine(ClientID, aBuf); + if(m_aClients[ClientID].m_AuthTries >= g_Config.m_SvRconMaxTries) + { + if(!g_Config.m_SvRconBantime) + m_NetServer.Drop(ClientID, "Too many remote console authentication tries"); + else + m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries"); + } + } + else + { + SendRconLine(ClientID, "Wrong password."); + } + } + } + else if(Msg == NETMSG_PING) + { + CMsgPacker Msg(NETMSG_PING_REPLY); + SendMsgEx(&Msg, 0, ClientID, true); + } + else + { + if(g_Config.m_Debug) + { + char aHex[] = "0123456789ABCDEF"; + char aBuf[512]; + + for(int b = 0; b < pPacket->m_DataSize && b < 32; b++) + { + aBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4]; + aBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf]; + aBuf[b*3+2] = ' '; + aBuf[b*3+3] = 0; + } + + char aBufMsg[256]; + str_format(aBufMsg, sizeof(aBufMsg), "strange message ClientID=%d msg=%d data_size=%d", ClientID, Msg, pPacket->m_DataSize); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBufMsg); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + } + else + { + // game message + if((pPacket->m_Flags&NET_CHUNKFLAG_VITAL) != 0 && m_aClients[ClientID].m_State >= CClient::STATE_READY) + GameServer()->OnMessage(Msg, &Unpacker, ClientID); + } +} + +void CServer::SendServerInfoConnless(const NETADDR *pAddr, int Token, bool Extended) +{ + const int MaxRequests = g_Config.m_SvServerInfoPerSecond; + int64 Now = Tick(); + if(Now <= m_ServerInfoFirstRequest + TickSpeed()) + { + m_ServerInfoNumRequests++; + } + else + { + m_ServerInfoHighLoad = m_ServerInfoNumRequests > MaxRequests; + m_ServerInfoNumRequests = 1; + m_ServerInfoFirstRequest = Now; + } + + bool Short = m_ServerInfoNumRequests > MaxRequests || m_ServerInfoHighLoad; + SendServerInfo(pAddr, Token, Extended, 0, Short); +} + +void CServer::SendServerInfo(const NETADDR *pAddr, int Token, bool Extended, int Offset, bool Short) +{ + CNetChunk Packet; + CPacker p; + char aBuf[128]; + + Packet.m_ClientID = -1; + Packet.m_Address = *pAddr; + Packet.m_Flags = NETSENDFLAG_CONNLESS; + + // count the players + int PlayerCount = 0, ClientCount = 0; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + { + if(GameServer()->IsClientPlayer(i)) + PlayerCount++; + + ClientCount++; + } + } + + p.Reset(); + + if(Extended) + p.AddRaw(SERVERBROWSE_INFO64, sizeof(SERVERBROWSE_INFO64)); + else + p.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)); + + str_format(aBuf, sizeof(aBuf), "%d", Token); + p.AddString(aBuf, 6); + + p.AddString(GameServer()->Version(), 32); + if (Extended) + { + p.AddString(g_Config.m_SvName, 256); + } + else + { + if (m_NetServer.MaxClients() <= VANILLA_MAX_CLIENTS) + p.AddString(g_Config.m_SvName, 64); + else + { + str_format(aBuf, sizeof(aBuf), "%s [%d/%d]", g_Config.m_SvName, ClientCount, m_NetServer.MaxClients()); + p.AddString(aBuf, 64); + } + } + p.AddString(GetMapName(), 32); + + // gametype + p.AddString(GameServer()->GameType(), 16); + + // flags + int i = 0; + if(g_Config.m_Password[0]) // password set + i |= SERVER_FLAG_PASSWORD; + str_format(aBuf, sizeof(aBuf), "%d", i); + p.AddString(aBuf, 2); + + int MaxClients = m_NetServer.MaxClients(); + if (!Extended) + { + if (ClientCount >= VANILLA_MAX_CLIENTS) + { + if (ClientCount < MaxClients) + ClientCount = VANILLA_MAX_CLIENTS - 1; + else + ClientCount = VANILLA_MAX_CLIENTS; + } + if (MaxClients > VANILLA_MAX_CLIENTS) MaxClients = VANILLA_MAX_CLIENTS; + } + + if (PlayerCount > ClientCount) + PlayerCount = ClientCount; + + str_format(aBuf, sizeof(aBuf), "%d", PlayerCount); p.AddString(aBuf, 3); // num players + str_format(aBuf, sizeof(aBuf), "%d", 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", MaxClients); p.AddString(aBuf, 3); // max clients + + if (Extended) + p.AddInt(Offset); + + if(Short) + { + Packet.m_DataSize = p.Size(); + Packet.m_pData = p.Data(); + m_NetServer.Send(&Packet); + return; + } + + int ClientsPerPacket = Extended ? 24 : VANILLA_MAX_CLIENTS; + int Skip = Offset; + int Take = ClientsPerPacket; + + for(i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + { + if (Skip-- > 0) + continue; + if (--Take < 0) + break; + + 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_DataSize = p.Size(); + Packet.m_pData = p.Data(); + m_NetServer.Send(&Packet); + + if (Extended && Take < 0) + SendServerInfo(pAddr, Token, Extended, Offset + ClientsPerPacket); +} + +void CServer::UpdateServerInfo() +{ + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + { + SendServerInfo(m_NetServer.ClientAddr(i), -1, true); + SendServerInfo(m_NetServer.ClientAddr(i), -1, false); + } + } +} + + +void CServer::PumpNetwork() +{ + CNetChunk Packet; + + m_NetServer.Update(); + + // process packets + while(m_NetServer.Recv(&Packet)) + { + if(Packet.m_ClientID == -1) + { + // stateless + if(!m_Register.RegisterProcessPacket(&Packet)) + { + bool ServerInfo = false; + bool Extended = false; + + if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO)+1 && + mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0) + { + ServerInfo = true; + Extended = false; + } + else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO64)+1 && + mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO64, sizeof(SERVERBROWSE_GETINFO64)) == 0) + { + ServerInfo = true; + Extended = true; + } + if(ServerInfo) + { + int Token = ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)]; + SendServerInfoConnless(&Packet.m_Address, Token, Extended); + } + } + } + else + ProcessClientPacket(&Packet); + } + if(g_Config.m_SvFastDownload) + { + for (int i=0;i<MAX_CLIENTS;i++) + { + if (m_aClients[i].m_State != CClient::STATE_CONNECTING) + continue; + if (lastasktick[i] < Tick()-TickSpeed()) + { + lastsent[i] = lastask[i]; + lastasktick[i] = Tick(); + } + if (lastask[i]<lastsent[i]-g_Config.m_SvMapWindow) + continue; + + int Chunk = lastsent[i]++; + unsigned int ChunkSize = 1024-128; + unsigned int Offset = Chunk * ChunkSize; + int Last = 0; + + // drop faulty map data requests + if(Chunk < 0 || Offset > m_CurrentMapSize) + continue; + if(Offset+ChunkSize >= m_CurrentMapSize) + { + ChunkSize = m_CurrentMapSize-Offset; + Last = 1; + } + + CMsgPacker Msg(NETMSG_MAP_DATA); + Msg.AddInt(Last); + Msg.AddInt(m_CurrentMapCrc); + Msg.AddInt(Chunk); + Msg.AddInt(ChunkSize); + Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize); + SendMsgEx(&Msg, MSGFLAG_FLUSH, i, true); + + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + } + } + + m_ServerBan.Update(); + m_Econ.Update(); +} + +char *CServer::GetMapName() +{ + // get the name of the map without his path + char *pMapShortName = &g_Config.m_SvMap[0]; + for(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++) + { + if(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\') + pMapShortName = &g_Config.m_SvMap[i+1]; + } + return pMapShortName; +} + +int CServer::LoadMap(const char *pMapName) +{ + //DATAFILE *df; + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); + GameServer()->OnMapChange(aBuf, sizeof(aBuf)); + + /*df = datafile_load(buf); + if(!df) + return 0;*/ + + // check for valid standard map + if(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL)) + { + 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 + for(int i = 0; i < MAX_CLIENTS+1; i++) + { + m_aDemoRecorder[i].Stop(); + + // remove tmp demos + if(i < MAX_CLIENTS) + { + char aPath[256]; + str_format(aPath, sizeof(aPath), "demos/%s_%d_%d_tmp.demo", m_aCurrentMap, g_Config.m_SvPort, i); + Storage()->RemoveFile(aPath, IStorage::TYPE_SAVE); + } + } + + // 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 complete map into memory for download + { + IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); + m_CurrentMapSize = (unsigned int)io_length(File); + if(m_pCurrentMapData) + mem_free(m_pCurrentMapData); + m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1); + io_read(File, m_pCurrentMapData, m_CurrentMapSize); + io_close(File); + } + + for(int i=0; i<MAX_CLIENTS; i++) + m_aPrevStates[i] = m_aClients[i].m_State; + + return 1; +} + +void CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole) +{ + m_Register.Init(pNetServer, pMasterServer, pConsole); +} + +int CServer::Run() +{ + // + m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, SendRconLineAuthed, this); + + // load map + if(!LoadMap(g_Config.m_SvMap)) + { + dbg_msg("server", "failed to load map. mapname='%s'", g_Config.m_SvMap); + return -1; + } + + // start server + NETADDR BindAddr; + if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // sweet! + BindAddr.type = NETTYPE_ALL; + BindAddr.port = g_Config.m_SvPort; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = g_Config.m_SvPort; + } + + if(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0)) + { + dbg_msg("server", "couldn't open socket. port %d might already be in use", g_Config.m_SvPort); + return -1; + } + + m_NetServer.SetCallbacks(NewClientCallback, NewClientNoAuthCallback, ClientRejoinCallback, DelClientCallback, this); + + m_Econ.Init(Console(), &m_ServerBan); + + 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); + + // process pending commands + m_pConsole->StoreCommands(false); + + if(m_GeneratedRconPassword) + { + dbg_msg("server", "+-------------------------+"); + dbg_msg("server", "| rcon password: '%s' |", g_Config.m_SvRconPassword); + dbg_msg("server", "+-------------------------+"); + } + + // start game + { + bool NonActive = false; + + 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); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + } + + while(m_RunServer) + { + if(NonActive) + PumpNetwork(); + + set_new_tick(); + + 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; + m_ServerInfoFirstRequest = 0; + Kernel()->ReregisterInterface(GameServer()); + GameServer()->OnInit(); + UpdateServerInfo(); + } + else + { + str_format(aBuf, sizeof(aBuf), "failed to load map. mapname='%s'", g_Config.m_SvMap); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + 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++) + { + if(m_aClients[c].m_State != CClient::STATE_INGAME) + continue; + for(int i = 0; i < 200; i++) + { + if(m_aClients[c].m_aInputs[i].m_GameTick == Tick()) + { + GameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData); + break; + } + } + } + + GameServer()->OnTick(); + } + + // snap game + if(NewTicks) + { + if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0) + DoSnapshot(); + + UpdateClientRconCommands(); + } + + // master server stuff + m_Register.RegisterUpdate(m_NetServer.NetType()); + + if(!NonActive) + PumpNetwork(); + + NonActive = true; + + for(int c = 0; c < MAX_CLIENTS; c++) + if(m_aClients[c].m_State != CClient::STATE_EMPTY) + NonActive = false; + + // wait for incoming data + if (NonActive) + { + if(g_Config.m_SvReloadWhenEmpty == 1) + { + m_MapReload = true; + g_Config.m_SvReloadWhenEmpty = 0; + } + else if(g_Config.m_SvReloadWhenEmpty == 2 && !m_ReloadedWhenEmpty) + { + m_MapReload = true; + m_ReloadedWhenEmpty = true; + } + + if(g_Config.m_SvShutdownWhenEmpty) + m_RunServer = false; + else + net_socket_read_wait(m_NetServer.Socket(), 1000000); + } + else + { + m_ReloadedWhenEmpty = false; + + set_new_tick(); + int64 t = time_get(); + int x = (TickStartTime(m_CurrentGameTick+1) - t) * 1000000 / time_freq() + 1; + + if(x > 0) + { + net_socket_read_wait(m_NetServer.Socket(), x); + } + } + } + } + // disconnect all clients on shutdown + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_aClients[i].m_State != CClient::STATE_EMPTY) + m_NetServer.Drop(i, "Server shutdown"); + + m_Econ.Shutdown(); + } + + GameServer()->OnShutdown(); + m_pMap->Unload(); + + if(m_pCurrentMapData) + mem_free(m_pCurrentMapData); + return 0; +} + +void CServer::ConTestingCommands(CConsole::IResult *pResult, void *pUser) +{ + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Value: %d", g_Config.m_SvTestingCommands); + ((CConsole*)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CServer::ConRescue(CConsole::IResult *pResult, void *pUser) +{ + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Value: %d", g_Config.m_SvRescue); + ((CConsole*)pUser)->Print(CConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CServer::ConKick(IConsole::IResult *pResult, void *pUser) +{ + if(pResult->NumArguments() > 1) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Kicked (%s)", pResult->GetString(1)); + ((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf); + } + else + ((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console"); +} + +void CServer::ConStatus(IConsole::IResult *pResult, void *pUser) +{ + char aBuf[1024]; + char aAddrStr[NETADDR_MAXSTRSIZE]; + CServer* pThis = static_cast<CServer *>(pUser); + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY) + { + net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true); + if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME) + { + const char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? "(Admin)" : + pThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? "(Mod)" : + pThis->m_aClients[i].m_Authed == CServer::AUTHED_HELPER ? "(Helper)" : ""; + str_format(aBuf, sizeof(aBuf), "id=%d addr=%s name='%s' score=%d client=%d secure=%s %s", i, aAddrStr, + pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, ((CGameContext *)(pThis->GameServer()))->m_apPlayers[i]->m_ClientVersion, pThis->m_NetServer.HasSecurityToken(i) ? "yes":"no", pAuthStr); + } + else + str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf); + } + } +} + +void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser) +{ + ((CServer *)pUser)->m_RunServer = 0; +} + +void CServer::DemoRecorder_HandleAutoStart() +{ + if(g_Config.m_SvAutoDemoRecord) + { + m_aDemoRecorder[MAX_CLIENTS].Stop(); + char aFilename[128]; + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", "auto/autorecord", aDate); + m_aDemoRecorder[MAX_CLIENTS].Start(Storage(), m_pConsole, aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "server"); + if(g_Config.m_SvAutoDemoMax) + { + // clean up auto recorded demos + CFileCollection AutoDemos; + AutoDemos.Init(Storage(), "demos/server", "autorecord", ".demo", g_Config.m_SvAutoDemoMax); + } + } +} + +bool CServer::DemoRecorder_IsRecording() +{ + return m_aDemoRecorder[MAX_CLIENTS].IsRecording(); +} + +void CServer::SaveDemo(int ClientID, float Time) +{ + if(IsRecording(ClientID)) + { + m_aDemoRecorder[ClientID].Stop(true); + + // rename the demo + char aOldFilename[256]; + char aNewFilename[256]; + str_format(aOldFilename, sizeof(aOldFilename), "demos/%s_%d_%d_tmp.demo", m_aCurrentMap, g_Config.m_SvPort, ClientID); + str_format(aNewFilename, sizeof(aNewFilename), "demos/%s_%s_%5.2f.demo", m_aCurrentMap, m_aClients[ClientID].m_aName, Time); + Storage()->RenameFile(aOldFilename, aNewFilename, IStorage::TYPE_SAVE); + } +} + +void CServer::StartRecord(int ClientID) +{ + if(g_Config.m_SvPlayerDemoRecord) + { + char aFilename[128]; + str_format(aFilename, sizeof(aFilename), "demos/%s_%d_%d_tmp.demo", m_aCurrentMap, g_Config.m_SvPort, ClientID); + m_aDemoRecorder[ClientID].Start(Storage(), Console(), aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "client", m_CurrentMapSize, m_pCurrentMapData); + } +} + +void CServer::StopRecord(int ClientID) +{ + if(IsRecording(ClientID)) + { + m_aDemoRecorder[ClientID].Stop(); + + char aFilename[128]; + str_format(aFilename, sizeof(aFilename), "demos/%s_%d_%d_tmp.demo", m_aCurrentMap, g_Config.m_SvPort, ClientID); + Storage()->RemoveFile(aFilename, IStorage::TYPE_SAVE); + } +} + +bool CServer::IsRecording(int ClientID) +{ + return m_aDemoRecorder[ClientID].IsRecording(); +} + +void CServer::ConRecord(IConsole::IResult *pResult, void *pUser) +{ + CServer* pServer = (CServer *)pUser; + char aFilename[128]; + + if(pResult->NumArguments()) + str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pResult->GetString(0)); + else + { + char aDate[20]; + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "demos/demo_%s.demo", aDate); + } + pServer->m_aDemoRecorder[MAX_CLIENTS].Start(pServer->Storage(), pServer->Console(), aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapCrc, "server"); +} + +void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser) +{ + ((CServer *)pUser)->m_aDemoRecorder[MAX_CLIENTS].Stop(); +} + +void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser) +{ + ((CServer *)pUser)->m_MapReload = 1; +} + +void CServer::ConLogout(IConsole::IResult *pResult, void *pUser) +{ + CServer *pServer = (CServer *)pUser; + + if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS && + pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS); + Msg.AddInt(0); //authed + Msg.AddInt(0); //cmdlist + pServer->SendMsgEx(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID, true); + + pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO; + pServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0; + pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0; + pServer->SendRconLine(pServer->m_RconClientID, "Logout successful."); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID); + pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } +} + +void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CServer *)pUserData)->UpdateServerInfo(); +} + +void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0)); +} + +void CServer::ConchainCommandAccessUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + if(pResult->NumArguments() == 2) + { + CServer *pThis = static_cast<CServer *>(pUserData); + const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false); + int OldAccessLevel = 0; + if(pInfo) + OldAccessLevel = pInfo->GetAccessLevel(); + pfnCallback(pResult, pCallbackUserData); + if(pInfo && OldAccessLevel != pInfo->GetAccessLevel()) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || + (pInfo->GetAccessLevel() > AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed < OldAccessLevel) || + (pInfo->GetAccessLevel() < AUTHED_ADMIN - pThis->m_aClients[i].m_Authed && AUTHED_ADMIN - pThis->m_aClients[i].m_Authed > OldAccessLevel) || + (pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0)) + continue; + + if(OldAccessLevel < pInfo->GetAccessLevel()) + pThis->SendRconCmdAdd(pInfo, i); + else + pThis->SendRconCmdRem(pInfo, i); + } + } + } + else + pfnCallback(pResult, pCallbackUserData); +} + +void CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CServer *pThis = static_cast<CServer *>(pUserData); + pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); + } +} + +void CServer::LogoutByAuthLevel(int AuthLevel) // AUTHED_<x> +{ + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) + continue; + if(m_aClients[i].m_Authed == AuthLevel) + { + CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS); + Msg.AddInt(0); //authed + Msg.AddInt(0); //cmdlist + SendMsgEx(&Msg, MSGFLAG_VITAL, i, true); + + m_aClients[i].m_Authed = AUTHED_NO; + m_aClients[i].m_AuthTries = 0; + m_aClients[i].m_pRconCmdToSend = 0; + + SendRconLine(i, "Logged out by password change."); + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out by password change", i); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } + } +} + +void CServer::ConchainRconPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CServer *pServer = (CServer *)pUserData; + pServer->LogoutByAuthLevel(AUTHED_ADMIN); + } +} + +void CServer::ConchainRconModPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CServer *pServer = (CServer *)pUserData; + pServer->LogoutByAuthLevel(AUTHED_MOD); + } +} + +void CServer::ConchainRconHelperPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CServer *pServer = (CServer *)pUserData; + pServer->LogoutByAuthLevel(AUTHED_HELPER); + } +} + +void CServer::RegisterCommands() +{ + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_pGameServer = Kernel()->RequestInterface<IGameServer>(); + m_pMap = Kernel()->RequestInterface<IEngineMap>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + + // register console commands + Console()->Register("kick", "i[id] ?r[reason]", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason"); + Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players"); + Console()->Register("shutdown", "", CFGFLAG_SERVER, ConShutdown, this, "Shut down"); + Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon"); + + Console()->Register("record", "?s[file]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file"); + Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording"); + + Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map"); + + Console()->Chain("sv_name", ConchainSpecialInfoupdate, this); + Console()->Chain("password", ConchainSpecialInfoupdate, this); + + Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this); + Console()->Chain("access_level", ConchainCommandAccessUpdate, this); + Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this); + + Console()->Chain("sv_rcon_password", ConchainRconPasswordChange, this); + Console()->Chain("sv_rcon_mod_password", ConchainRconModPasswordChange, this); + Console()->Chain("sv_rcon_helper_password", ConchainRconHelperPasswordChange, this); + + // register console commands in sub parts + m_ServerBan.InitServerBan(Console(), Storage(), this); + m_pGameServer->OnConsoleInit(); +} + + +int CServer::SnapNewID() +{ + return m_IDPool.NewID(); +} + +void CServer::SnapFreeID(int ID) +{ + m_IDPool.FreeID(ID); +} + + +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); +} + +void CServer::SnapSetStaticsize(int ItemType, int Size) +{ + m_SnapshotDelta.SetStaticsize(ItemType, Size); +} + +static CServer *CreateServer() { return new CServer(); } + +int main(int argc, const char **argv) // ignore_convention +{ +#if !defined(CONF_PLATFORM_MACOSX) && !defined(FUZZING) + dbg_enable_threaded(); +#endif +#if defined(CONF_FAMILY_WINDOWS) + for(int i = 1; i < argc; i++) // ignore_convention + { + if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention + { + ShowWindow(GetConsoleWindow(), SW_HIDE); + break; + } + } +#endif + + if(secure_random_init() != 0) + { + dbg_msg("secure", "could not initialize secure RNG"); + return -1; + } + + CServer *pServer = CreateServer(); + IKernel *pKernel = IKernel::Create(); + + // create the components + IEngine *pEngine = CreateEngine("Teeworlds"); + IEngineMap *pEngineMap = CreateEngineMap(); + IGameServer *pGameServer = CreateGameServer(); + IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON); + IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); + IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention + IConfig *pConfig = CreateConfig(); + + pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole); + + { + bool RegisterFail = false; + + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both + RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap)); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); + RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); + 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(); + + // execute autoexec file + IOHANDLE file = pStorage->OpenFile(AUTOEXEC_SERVER_FILE, IOFLAG_READ, IStorage::TYPE_ALL); + if(file) + { + io_close(file); + pConsole->ExecuteFile(AUTOEXEC_SERVER_FILE); + } + else // fallback + { + pConsole->ExecuteFile(AUTOEXEC_FILE); + } + + // parse the command line arguments + if(argc > 1) // ignore_convention + pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention + + pConsole->Register("sv_test_cmds", "", CFGFLAG_SERVER, CServer::ConTestingCommands, pConsole, "Turns testing commands aka cheats on/off"); + pConsole->Register("sv_rescue", "", CFGFLAG_SERVER, CServer::ConRescue, pConsole, "Allow /rescue command so players can teleport themselves out of freeze"); + + pEngine->InitLogfile(); + +#if defined(CONF_FAMILY_UNIX) + FifoConsole *fifoConsole = new FifoConsole(pConsole, g_Config.m_SvInputFifo, CFGFLAG_SERVER); +#endif + pServer->InitRconPasswordIfEmpty(); + + // run the server + dbg_msg("server", "starting..."); + pServer->Run(); + + // free +#if defined(CONF_FAMILY_UNIX) + delete fifoConsole; +#endif + delete pServer; + delete pKernel; + delete pEngineMap; + delete pGameServer; + delete pConsole; + delete pEngineMasterServer; + delete pStorage; + delete pConfig; + return 0; +} + +// DDRace + +void CServer::GetClientAddr(int ClientID, NETADDR *pAddr) +{ + if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME) { + *pAddr = *m_NetServer.ClientAddr(ClientID); + } +} + +char *CServer::GetAnnouncementLine(char const *pFileName) +{ + IOHANDLE File = m_pStorage->OpenFile(pFileName, IOFLAG_READ, IStorage::TYPE_ALL); + if(File) + { + std::vector<char*> v; + char *pLine; + CLineReader *lr = new CLineReader(); + lr->Init(File); + while((pLine = lr->Get())) + if(str_length(pLine)) + if(pLine[0]!='#') + v.push_back(pLine); + if(v.size() == 1) + { + m_AnnouncementLastLine = 0; + } + else if(!g_Config.m_SvAnnouncementRandom) + { + if(m_AnnouncementLastLine >= v.size()) + m_AnnouncementLastLine %= v.size(); + } + else + { + unsigned Rand; + do + Rand = rand() % v.size(); + while(Rand == m_AnnouncementLastLine); + + m_AnnouncementLastLine = Rand; + } + return v[m_AnnouncementLastLine]; + } + return 0; +} + +int* CServer::GetIdMap(int ClientID) +{ + return (int*)(IdMap + VANILLA_MAX_CLIENTS * ClientID); +} diff --git a/src/engine/server/server.h b/src/engine/server/server.h new file mode 100644 index 0000000..6c4c9d3 --- /dev/null +++ b/src/engine/server/server.h @@ -0,0 +1,300 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVER_SERVER_H +#define ENGINE_SERVER_SERVER_H + +#include <engine/server.h> + +#include <engine/map.h> +#include <engine/shared/demo.h> +#include <engine/shared/protocol.h> +#include <engine/shared/snapshot.h> +#include <engine/shared/network.h> +#include <engine/server/register.h> +#include <engine/shared/console.h> +#include <base/math.h> +#include <engine/shared/mapchecker.h> +#include <engine/shared/econ.h> +#include <engine/shared/netban.h> + +class CSnapIDPool +{ + enum + { + MAX_IDS = 16*1024, + }; + + class CID + { + public: + short m_Next; + short m_State; // 0 = free, 1 = alloced, 2 = timed + int m_Timeout; + }; + + CID m_aIDs[MAX_IDS]; + + int m_FirstFree; + int m_FirstTimed; + int m_LastTimed; + int m_Usage; + int m_InUsage; + +public: + + CSnapIDPool(); + + void Reset(); + void RemoveFirstTimeout(); + int NewID(); + void TimeoutIDs(); + void FreeID(int ID); +}; + + +class CServerBan : public CNetBan +{ + class CServer *m_pServer; + + template<class T> int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + +public: + class CServer *Server() const { return m_pServer; } + + void InitServerBan(class IConsole *pConsole, class IStorage *pStorage, class CServer* pServer); + + virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); + virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); + + static void ConBanExt(class IConsole::IResult *pResult, void *pUser); +}; + + +class CServer : public IServer +{ + class IGameServer *m_pGameServer; + class IConsole *m_pConsole; + class IStorage *m_pStorage; +public: + class IGameServer *GameServer() { return m_pGameServer; } + class IConsole *Console() { return m_pConsole; } + class IStorage *Storage() { return m_pStorage; } + + enum + { + AUTHED_NO=0, + AUTHED_HELPER, + AUTHED_MOD, + AUTHED_ADMIN, + + MAX_RCONCMD_SEND=16, + }; + + class CClient + { + public: + + enum + { + STATE_EMPTY = 0, + STATE_AUTH, + 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; + + float m_Traffic; + int64 m_TrafficSince; + + 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; + + const IConsole::CCommandInfo *m_pRconCmdToSend; + + void Reset(); + + // DDRace + + NETADDR m_Addr; + }; + + CClient m_aClients[MAX_CLIENTS]; + int IdMap[MAX_CLIENTS * VANILLA_MAX_CLIENTS]; + + CSnapshotDelta m_SnapshotDelta; + CSnapshotBuilder m_SnapshotBuilder; + CSnapIDPool m_IDPool; + CNetServer m_NetServer; + CEcon m_Econ; + CServerBan m_ServerBan; + + IEngineMap *m_pMap; + + int64 m_GameStartTime; + //int m_CurrentGameTick; + int m_RunServer; + int m_MapReload; + bool m_ReloadedWhenEmpty; + int m_RconClientID; + int m_RconAuthLevel; + int m_PrintCBIndex; + + int64 m_Lastheartbeat; + //static NETADDR4 master_server; + + char m_aCurrentMap[64]; + unsigned m_CurrentMapCrc; + unsigned char *m_pCurrentMapData; + unsigned int m_CurrentMapSize; + + int m_GeneratedRconPassword; + + CDemoRecorder m_aDemoRecorder[MAX_CLIENTS+1]; + CRegister m_Register; + CMapChecker m_MapChecker; + + int m_RconRestrict; + + bool m_ServerInfoHighLoad; + int64 m_ServerInfoFirstRequest; + int m_ServerInfoNumRequests; + + CServer(); + + int TrySetClientName(int ClientID, const char *pName); + + virtual void SetClientName(int ClientID, const char *pName); + virtual void SetClientClan(int ClientID, char const *pClan); + virtual void SetClientCountry(int ClientID, int Country); + virtual void SetClientScore(int ClientID, int Score); + + void Kick(int ClientID, const char *pReason); + + void DemoRecorder_HandleAutoStart(); + bool DemoRecorder_IsRecording(); + + //int Tick() + int64 TickStartTime(int Tick); + //int TickSpeed() + + int Init(); + + void InitRconPasswordIfEmpty(); + + void SetRconCID(int ClientID); + bool IsAuthed(int ClientID); + int GetClientInfo(int ClientID, CClientInfo *pInfo); + void GetClientAddr(int ClientID, char *pAddrStr, int Size); + const char *ClientName(int ClientID); + const char *ClientClan(int ClientID); + int ClientCountry(int ClientID); + bool ClientIngame(int ClientID); + int MaxClients() const; + + virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID); + int SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System); + + void DoSnapshot(); + + static int NewClientCallback(int ClientID, void *pUser); + static int NewClientNoAuthCallback(int ClientID, bool Reset, void *pUser); + static int DelClientCallback(int ClientID, const char *pReason, void *pUser); + + static int ClientRejoinCallback(int ClientID, void *pUser); + + void SendMap(int ClientID); + void SendConnectionReady(int ClientID); + void SendRconLine(int ClientID, const char *pLine); + static void SendRconLineAuthed(const char *pLine, void *pUser, bool Highlighted = false); + + void SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID); + void SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID); + void UpdateClientRconCommands(); + + void ProcessClientPacket(CNetChunk *pPacket); + + void SendServerInfoConnless(const NETADDR *pAddr, int Token, bool Extended); + void SendServerInfo(const NETADDR *pAddr, int Token, bool Extended=false, int Offset=0, bool Short=false); + void UpdateServerInfo(); + + void PumpNetwork(); + + char *GetMapName(); + int LoadMap(const char *pMapName); + + void SaveDemo(int ClientID, float Time); + void StartRecord(int ClientID); + void StopRecord(int ClientID); + bool IsRecording(int ClientID); + + void InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole); + int Run(); + + static void ConTestingCommands(IConsole::IResult *pResult, void *pUser); + static void ConRescue(IConsole::IResult *pResult, void *pUser); + static void ConKick(IConsole::IResult *pResult, void *pUser); + static void ConStatus(IConsole::IResult *pResult, void *pUser); + static void ConShutdown(IConsole::IResult *pResult, void *pUser); + static void ConRecord(IConsole::IResult *pResult, void *pUser); + static void ConStopRecord(IConsole::IResult *pResult, void *pUser); + static void ConMapReload(IConsole::IResult *pResult, void *pUser); + static void ConLogout(IConsole::IResult *pResult, void *pUser); + static void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainCommandAccessUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + + void LogoutByAuthLevel(int AuthLevel); + + static void ConchainRconPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainRconModPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainRconHelperPasswordChange(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); + void SnapSetStaticsize(int ItemType, int Size); + + // DDRace + + void GetClientAddr(int ClientID, NETADDR *pAddr); + int m_aPrevStates[MAX_CLIENTS]; + char *GetAnnouncementLine(char const *FileName); + unsigned m_AnnouncementLastLine; + void RestrictRconOutput(int ClientID) { m_RconRestrict = ClientID; } + + virtual int* GetIdMap(int ClientID); +}; + +#endif diff --git a/src/engine/serverbrowser.h b/src/engine/serverbrowser.h new file mode 100644 index 0000000..612fa68 --- /dev/null +++ b/src/engine/serverbrowser.h @@ -0,0 +1,122 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SERVERBROWSER_H +#define ENGINE_SERVERBROWSER_H + +#include <engine/shared/protocol.h> + +#include "kernel.h" + +/* + Structure: CServerInfo +*/ +class CServerInfo +{ +public: + /* + Structure: CInfoClient + */ + class CClient + { + public: + char m_aName[MAX_NAME_LENGTH]; + char m_aClan[MAX_CLAN_LENGTH]; + int m_Country; + int m_Score; + bool m_Player; + + int m_FriendState; + }; + + int m_SortedIndex; + int m_ServerIndex; + + NETADDR m_NetAddr; + + int m_QuickSearchHit; + int m_FriendState; + + int m_MaxClients; + int m_NumClients; + int m_MaxPlayers; + int m_NumPlayers; + int m_Flags; + int m_Favorite; + int m_Latency; // in ms + char m_aGameType[16]; + char m_aName[64]; + char m_aMap[32]; + char m_aVersion[32]; + char m_aAddress[NETADDR_MAXSTRSIZE]; + CClient m_aClients[MAX_CLIENTS]; +}; + +bool IsRace(const CServerInfo *pInfo); +bool IsDDRace(const CServerInfo *pInfo); +bool IsDDNet(const CServerInfo *pInfo); +bool Is64Player(const CServerInfo *pInfo); +bool IsPlus(const CServerInfo *pInfo); + +class IServerBrowser : public IInterface +{ + MACRO_INTERFACE("serverbrowser", 0) +public: + + /* Constants: Server Browser Sorting + SORT_NAME - Sort by name. + SORT_PING - Sort by ping. + SORT_MAP - Sort by map + SORT_GAMETYPE - Sort by game type. DM, TDM etc. + SORT_NUMPLAYERS - Sort after how many players there are on the server. + */ + enum{ + SORT_NAME = 0, + SORT_PING, + SORT_MAP, + SORT_GAMETYPE, + SORT_NUMPLAYERS, + + QUICK_SERVERNAME=1, + QUICK_PLAYER=2, + QUICK_MAPNAME=4, + + TYPE_NONE = 0, + TYPE_INTERNET = 1, + TYPE_LAN = 2, + TYPE_FAVORITES = 3, + TYPE_DDNET = 4, + + SET_MASTER_ADD=1, + SET_FAV_ADD, + SET_DDNET_ADD, + SET_TOKEN + }; + + virtual void Refresh(int Type) = 0; + 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; + + virtual int NumDDNetCountries() = 0; + virtual int GetDDNetCountryFlag(int Index) = 0; + virtual const char *GetDDNetCountryName(int Index) = 0; + + virtual int NumDDNetTypes() = 0; + virtual const char *GetDDNetType(int Index) = 0; + + virtual void DDNetFilterAdd(char *pFilter, const char *pName) = 0; + virtual void DDNetFilterRem(char *pFilter, const char *pName) = 0; + virtual bool DDNetFiltered(char *pFilter, const char *pName) = 0; + virtual int GetCurrentType() = 0; +}; + +#endif diff --git a/src/engine/shared/compression.cpp b/src/engine/shared/compression.cpp new file mode 100644 index 0000000..daeefcf --- /dev/null +++ b/src/engine/shared/compression.cpp @@ -0,0 +1,88 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + +#include "compression.h" + +// 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 + + *pDst |= i&0x3F; // pack 6bit into dst + i >>= 6; // discard 6 bits + if(i) + { + *pDst |= 0x80; // set extend bit + while(1) + { + pDst++; + *pDst = i&(0x7F); // pack 7bit + i >>= 7; // discard 7 bits + *pDst |= (i!=0)<<7; // set extend bit (may branch) + if(!i) + break; + } + } + + pDst++; + return pDst; +} + +const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut) +{ + int Sign = (*pSrc>>6)&1; + *pInOut = *pSrc&0x3F; + + do + { + if(!(*pSrc&0x80)) break; + pSrc++; + *pInOut |= (*pSrc&(0x7F))<<(6); + + if(!(*pSrc&0x80)) break; + pSrc++; + *pInOut |= (*pSrc&(0x7F))<<(6+7); + + if(!(*pSrc&0x80)) break; + pSrc++; + *pInOut |= (*pSrc&(0x7F))<<(6+7+7); + + if(!(*pSrc&0x80)) break; + pSrc++; + *pInOut |= (*pSrc&(0x7F))<<(6+7+7+7); + } while(0); + + pSrc++; + *pInOut ^= -Sign; // if(sign) *i = ~(*i) + return pSrc; +} + + +long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_) +{ + const unsigned char *pSrc = (unsigned char *)pSrc_; + const unsigned char *pEnd = pSrc + Size; + int *pDst = (int *)pDst_; + while(pSrc < pEnd) + { + pSrc = CVariableInt::Unpack(pSrc, pDst); + pDst++; + } + return (long)((unsigned char *)pDst-(unsigned char *)pDst_); +} + +long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_) +{ + int *pSrc = (int *)pSrc_; + unsigned char *pDst = (unsigned char *)pDst_; + Size /= 4; + while(Size) + { + pDst = CVariableInt::Pack(pDst, *pSrc); + Size--; + pSrc++; + } + return (long)(pDst-(unsigned char *)pDst_); +} diff --git a/src/engine/shared/compression.h b/src/engine/shared/compression.h new file mode 100644 index 0000000..f11ab1b --- /dev/null +++ b/src/engine/shared/compression.h @@ -0,0 +1,14 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_COMPRESSION_H +#define ENGINE_SHARED_COMPRESSION_H +// variable int packing +class CVariableInt +{ +public: + static unsigned char *Pack(unsigned char *pDst, int i); + static const unsigned char *Unpack(const unsigned char *pSrc, int *pInOut); + static long Compress(const void *pSrc, int Size, void *pDst); + static long Decompress(const void *pSrc, int Size, void *pDst); +}; +#endif diff --git a/src/engine/shared/config.cpp b/src/engine/shared/config.cpp new file mode 100644 index 0000000..11f2947 --- /dev/null +++ b/src/engine/shared/config.cpp @@ -0,0 +1,110 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/config.h> +#include <engine/storage.h> +#include <engine/shared/config.h> +#include <engine/shared/protocol.h> + +CConfiguration g_Config; + +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) + { + if(*pSrc == '"' || *pSrc == '\\') // escape \ and " + *pDst++ = '\\'; + *pDst++ = *pSrc++; + } + *pDst = 0; + } + +public: + + CConfig() + { + 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" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + } + + virtual void Save() + { + if(!m_pStorage || !g_Config.m_ClSaveSettings) + return; + m_ConfigFile = m_pStorage->OpenFile(CONFIG_FILE ".tmp", 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" + + #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; + m_pStorage->RenameFile(CONFIG_FILE ".tmp", CONFIG_FILE, IStorage::TYPE_SAVE); + } + + virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) + { + dbg_assert(m_NumCallbacks < MAX_CALLBACKS, "too many config callbacks"); + m_aCallbacks[m_NumCallbacks].m_pfnFunc = pfnFunc; + m_aCallbacks[m_NumCallbacks].m_pUserData = pUserData; + m_NumCallbacks++; + } + + virtual void WriteLine(const char *pLine) + { + if(!m_ConfigFile) + return; + io_write(m_ConfigFile, pLine, str_length(pLine)); + io_write_newline(m_ConfigFile); + } +}; + +IConfig *CreateConfig() { return new CConfig; } diff --git a/src/engine/shared/config.h b/src/engine/shared/config.h new file mode 100644 index 0000000..d1fcc1a --- /dev/null +++ b/src/engine/shared/config.h @@ -0,0 +1,37 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONFIG_H +#define ENGINE_SHARED_CONFIG_H + +#define CONFIG_FILE "settings_ddnet.cfg" +#define AUTOEXEC_FILE "autoexec.cfg" +#define AUTOEXEC_CLIENT_FILE "autoexec_client.cfg" +#define AUTOEXEC_SERVER_FILE "autoexec_server.cfg" + +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 +}; + +extern CConfiguration g_Config; + +enum +{ + CFGFLAG_SAVE=1, + CFGFLAG_CLIENT=2, + CFGFLAG_SERVER=4, + CFGFLAG_STORE=8, + CFGFLAG_MASTER=16, + CFGFLAG_ECON=32, + // DDRace + + CMDFLAG_TEST=64, + CFGFLAG_CHAT=128, + CFGFLAG_GAME=256, +}; + +#endif diff --git a/src/engine/shared/config_variables.h b/src/engine/shared/config_variables.h new file mode 100644 index 0000000..617d3b0 --- /dev/null +++ b/src/engine/shared/config_variables.h @@ -0,0 +1,377 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONFIG_VARIABLES_H +#define ENGINE_SHARED_CONFIG_VARIABLES_H +#undef ENGINE_SHARED_CONFIG_VARIABLES_H // this file will be included several times + +// TODO: remove this +#include "././game/variables.h" + + +MACRO_CONFIG_STR(PlayerName, player_name, 16, "nameless tee", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Name of the player") +MACRO_CONFIG_STR(PlayerClan, player_clan, 12, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clan of the player") +MACRO_CONFIG_INT(PlayerCountry, player_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Country of the player") +MACRO_CONFIG_STR(Password, password, 32, "", CFGFLAG_CLIENT|CFGFLAG_SERVER, "Password to the server") +MACRO_CONFIG_STR(Logfile, logfile, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Filename to log all output to") +MACRO_CONFIG_INT(ConsoleOutputLevel, console_output_level, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Adjusts the amount of information in the console") + +MACRO_CONFIG_INT(ClSaveSettings, cl_save_settings, 1, 0, 1, CFGFLAG_CLIENT, "Write the settings file on exit") +MACRO_CONFIG_INT(ClCpuThrottle, cl_cpu_throttle, 0, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(ClCpuThrottleInactive, cl_cpu_throttle_inactive, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(ClEditor, cl_editor, 0, 0, 1, CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(ClEditorUndo, cl_editorundo, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Undo function in editor") +MACRO_CONFIG_INT(ClLoadCountryFlags, cl_load_country_flags, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Load and show country flags") +MACRO_CONFIG_STR(ClSkinFilterString, cl_skin_filter_string, 25, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Skin filtering string") + +MACRO_CONFIG_INT(ClAutoDemoRecord, cl_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically record demos") +MACRO_CONFIG_INT(ClAutoDemoMax, cl_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically recorded demos (0 = no limit)") +MACRO_CONFIG_INT(ClAutoScreenshot, cl_auto_screenshot, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically take game over screenshot") +MACRO_CONFIG_INT(ClAutoScreenshotMax, cl_auto_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically created screenshots (0 = no limit)") +MACRO_CONFIG_INT(ClResetWantedWeaponOnDeath, cl_reset_wanted_weapon_on_death, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Reset wanted weapon on death") +MACRO_CONFIG_INT(ClShowBroadcasts, cl_show_broadcasts, 1, 0, 1, CFGFLAG_CLIENT, "Show broadcasts ingame") +MACRO_CONFIG_INT(ClPrintBroadcasts, cl_print_broadcasts, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Print broadcasts to console") +MACRO_CONFIG_INT(ClFriendsIgnoreClan, cl_friends_ignore_clan, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Ignore clan tag when searching for friends") + +MACRO_CONFIG_INT(ClEventthread, cl_eventthread, 0, 0, 1, CFGFLAG_CLIENT, "Enables the usage of a thread to pump the events") + +#if !defined(CONF_PLATFORM_MACOSX) +MACRO_CONFIG_INT(InpGrab, inp_grab, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use forceful input grabbing method") +#else +MACRO_CONFIG_INT(InpGrab, inp_grab, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use forceful input grabbing method") +#endif + +MACRO_CONFIG_STR(BrFilterString, br_filter_string, 25, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server browser filtering string") +MACRO_CONFIG_STR(BrExcludeString, br_exclude_string, 25, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server browser exclusion string") +MACRO_CONFIG_INT(BrFilterFull, br_filter_full, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out full server in browser") +MACRO_CONFIG_INT(BrFilterEmpty, br_filter_empty, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out empty server in browser") +MACRO_CONFIG_INT(BrFilterSpectators, br_filter_spectators, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out spectators from player numbers") +MACRO_CONFIG_INT(BrFilterFriends, br_filter_friends, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out servers with no friends") +MACRO_CONFIG_INT(BrFilterCountry, br_filter_country, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out servers with non-matching player country") +MACRO_CONFIG_INT(BrFilterCountryIndex, br_filter_country_index, -1, -1, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Player country to filter by in the server browser") +MACRO_CONFIG_INT(BrFilterPw, br_filter_pw, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out password protected servers in browser") +MACRO_CONFIG_INT(BrFilterPing, br_filter_ping, 999, 0, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Ping to filter by in the server browser") +MACRO_CONFIG_STR(BrFilterGametype, br_filter_gametype, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Game types to filter") +MACRO_CONFIG_INT(BrFilterGametypeStrict, br_filter_gametype_strict, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Strict gametype filter") +MACRO_CONFIG_STR(BrFilterServerAddress, br_filter_serveraddress, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server address to filter") +MACRO_CONFIG_INT(BrFilterPure, br_filter_pure, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-standard servers in browser") +MACRO_CONFIG_INT(BrFilterPureMap, br_filter_pure_map, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-standard maps in browser") +MACRO_CONFIG_INT(BrFilterCompatversion, br_filter_compatversion, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-compatible servers in browser") + +MACRO_CONFIG_STR(BrFilterExcludeCountries, br_filter_exclude_countries, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out ddnet servers by country") +MACRO_CONFIG_STR(BrFilterExcludeTypes, br_filter_exclude_types, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out ddnet servers by type (mod)") + +MACRO_CONFIG_INT(BrSort, br_sort, 4, 0, 256, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(BrSortOrder, br_sort_order, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(BrMaxRequests, br_max_requests, 25, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Number of requests to use when refreshing server browser") + +MACRO_CONFIG_INT(BrDemoSort, br_demo_sort, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(BrDemoSortOrder, br_demo_sort_order, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") + +MACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 128, 32768, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound buffer size") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(SndRate, snd_rate, 44100, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound mixing rate") +#else +MACRO_CONFIG_INT(SndRate, snd_rate, 48000, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound mixing rate") +#endif +MACRO_CONFIG_INT(SndEnable, snd_enable, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound enable") +MACRO_CONFIG_INT(SndMusic, snd_enable_music, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Play background music") +MACRO_CONFIG_INT(SndVolume, snd_volume, 100, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound volume") +MACRO_CONFIG_INT(SndDevice, snd_device, -1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "(deprecated) Sound device to use") +MACRO_CONFIG_INT(SndMapSoundVolume, snd_ambient_volume, 70, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Map Sound sound volume") + +MACRO_CONFIG_INT(SndNonactiveMute, snd_nonactive_mute, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(SndGame, snd_game, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable game sounds") +MACRO_CONFIG_INT(SndGun, snd_gun, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable gun sound") +MACRO_CONFIG_INT(SndChat, snd_chat, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable regular chat sound") +MACRO_CONFIG_INT(SndTeamChat, snd_team_chat, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable team chat sound") +MACRO_CONFIG_INT(SndServerMessage, snd_servermessage, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable server message sound") +MACRO_CONFIG_INT(SndHighlight, snd_highlight, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable highlighted chat sound") + +MACRO_CONFIG_INT(GfxScreenWidth, gfx_screen_width, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution width") +MACRO_CONFIG_INT(GfxScreenHeight, gfx_screen_height, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution height") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(GfxBorderless, gfx_borderless, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Borderless window (not to be used with fullscreen)") +MACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Fullscreen") +MACRO_CONFIG_INT(GfxAlphabits, gfx_alphabits, 1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Alpha bits for framebuffer (fullscreen only)") +#else +MACRO_CONFIG_INT(GfxBorderless, gfx_borderless, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Borderless window (not to be used with fullscreen)") +MACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 0, 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)") +#endif +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, 1, 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") +MACRO_CONFIG_INT(GfxDisplayAllModes, gfx_display_all_modes, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(GfxTextureCompression, gfx_texture_compression, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use texture compression") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(GfxHighDetail, gfx_high_detail, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "High detail") +MACRO_CONFIG_INT(GfxTextureQuality, gfx_texture_quality, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +#else +MACRO_CONFIG_INT(GfxHighDetail, gfx_high_detail, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "High detail") +MACRO_CONFIG_INT(GfxTextureQuality, gfx_texture_quality, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +#endif +MACRO_CONFIG_INT(GfxFsaaSamples, gfx_fsaa_samples, 0, 0, 16, CFGFLAG_SAVE|CFGFLAG_CLIENT, "FSAA Samples") +MACRO_CONFIG_INT(GfxRefreshRate, gfx_refresh_rate, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen refresh rate") +MACRO_CONFIG_INT(GfxFinish, gfx_finish, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(GfxBackgroundRender, gfx_backgroundrender, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Render graphics when window is in background") +MACRO_CONFIG_INT(GfxTextOverlay, gfx_text_overlay, 10, 1, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Stop rendering textoverlay in editor or with entities: high value = less details = more speed") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(GfxAsyncRenderOld, gfx_asyncrender_old, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Do rendering async from the the update") +MACRO_CONFIG_INT(GfxThreadedOld, gfx_threaded_old, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use the threaded graphics backend") +#else +MACRO_CONFIG_INT(GfxAsyncRenderOld, gfx_asyncrender_old, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Do rendering async from the the update") +MACRO_CONFIG_INT(GfxThreadedOld, gfx_threaded_old, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use the threaded graphics backend") +#endif +MACRO_CONFIG_INT(GfxTuneOverlay, gfx_tune_overlay, 20, 1, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Stop rendering text overlay in tuning zone in editor: high value = less details = more speed") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(GfxQuadAsTriangle, gfx_quad_as_triangle, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Render quads as triangles (fixes quad coloring on some GPUs)") +#else +MACRO_CONFIG_INT(GfxQuadAsTriangle, gfx_quad_as_triangle, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Render quads as triangles (fixes quad coloring on some GPUs)") +#endif + +MACRO_CONFIG_INT(InpMousesens, inp_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity") + +MACRO_CONFIG_STR(SvName, sv_name, 128, "unnamed server", CFGFLAG_SERVER, "Server name") +MACRO_CONFIG_STR(Bindaddr, bindaddr, 128, "", CFGFLAG_CLIENT|CFGFLAG_SERVER|CFGFLAG_MASTER, "Address to bind the client/server to") +MACRO_CONFIG_INT(SvPort, sv_port, 8303, 0, 0, CFGFLAG_SERVER, "Port to use for the server (Only ports 8303-8310 work in LAN server browser)") +MACRO_CONFIG_INT(SvExternalPort, sv_external_port, 0, 0, 0, CFGFLAG_SERVER, "External port to report to the master servers") +MACRO_CONFIG_STR(SvMap, sv_map, 128, "WarioWare", CFGFLAG_SERVER, "Map to use on the server") +MACRO_CONFIG_INT(SvMaxClients, sv_max_clients, MAX_CLIENTS, 1, MAX_CLIENTS, CFGFLAG_SERVER, "Maximum number of clients that are allowed on a server") +MACRO_CONFIG_INT(SvMaxClientsPerIP, sv_max_clients_per_ip, 4, 1, MAX_CLIENTS, CFGFLAG_SERVER, "Maximum number of clients with the same IP that can connect to the server") +MACRO_CONFIG_INT(SvHighBandwidth, sv_high_bandwidth, 0, 0, 1, CFGFLAG_SERVER, "Use high bandwidth mode. Doubles the bandwidth required for the server. LAN use only") +MACRO_CONFIG_INT(SvRegister, sv_register, 1, 0, 1, CFGFLAG_SERVER, "Register server with master server for public listing") +MACRO_CONFIG_STR(SvRconPassword, sv_rcon_password, 32, "", CFGFLAG_SERVER, "Remote console password (full access)") +MACRO_CONFIG_STR(SvRconModPassword, sv_rcon_mod_password, 32, "", CFGFLAG_SERVER, "Remote console password for moderators (limited access)") +MACRO_CONFIG_STR(SvRconHelperPassword, sv_rcon_helper_password, 32, "", CFGFLAG_SERVER, "Remote console password for helpers (limited access)") +MACRO_CONFIG_INT(SvRconMaxTries, sv_rcon_max_tries, 30, 0, 100, CFGFLAG_SERVER, "Maximum number of tries for remote console authentication") +MACRO_CONFIG_INT(SvRconBantime, sv_rcon_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time a client gets banned if remote console authentication fails. 0 makes it just use kick") +MACRO_CONFIG_INT(SvAutoDemoRecord, sv_auto_demo_record, 0, 0, 1, CFGFLAG_SERVER, "Automatically record demos") +MACRO_CONFIG_INT(SvAutoDemoMax, sv_auto_demo_max, 10, 0, 1000, CFGFLAG_SERVER, "Maximum number of automatically recorded demos (0 = no limit)") +MACRO_CONFIG_INT(SvVanillaAntiSpoof, sv_vanilla_antispoof, 1, 0, 1, CFGFLAG_SERVER, "Enable vanilla Antispoof") + +MACRO_CONFIG_INT(SvPlayerDemoRecord, sv_player_demo_record, 0, 0, 1, CFGFLAG_SERVER, "Automatically record demos for each player") +MACRO_CONFIG_INT(SvDemoChat, sv_demo_chat, 0, 0, 1, CFGFLAG_SERVER, "Record chat for demos") +MACRO_CONFIG_INT(SvServerInfoPerSecond, sv_server_info_per_second, 50, 1, 1000, CFGFLAG_SERVER, "Maximum number of complete server info responses that are sent out per second") +MACRO_CONFIG_INT(SvVanConnPerSecond, sv_van_conn_per_second, 10, 1, 1000, CFGFLAG_SERVER, "Antispoof specific ratelimit") + +MACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, "localhost", CFGFLAG_ECON, "Address to bind the external console to. Anything but 'localhost' is dangerous") +MACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_ECON, "Port to use for the external console") +MACRO_CONFIG_STR(EcPassword, ec_password, 32, "", CFGFLAG_ECON, "External console password") +MACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_ECON, "The time a client gets banned if econ authentication fails. 0 just closes the connection") +MACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_ECON, "Time in seconds before the the econ authentification times out") +MACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_ECON, "Adjusts the amount of information in the external console") + +MACRO_CONFIG_INT(Debug, debug, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Debug mode") +MACRO_CONFIG_INT(DbgStress, dbg_stress, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress systems") +MACRO_CONFIG_INT(DbgStressNetwork, dbg_stress_network, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress network") +MACRO_CONFIG_INT(DbgPref, dbg_pref, 0, 0, 1, CFGFLAG_SERVER, "Performance outputs") +MACRO_CONFIG_INT(DbgGraphs, dbg_graphs, 0, 0, 1, CFGFLAG_CLIENT, "Performance graphs") +MACRO_CONFIG_INT(DbgHitch, dbg_hitch, 0, 0, 0, CFGFLAG_SERVER, "Hitch warnings") +MACRO_CONFIG_STR(DbgStressServer, dbg_stress_server, 32, "localhost", CFGFLAG_CLIENT, "Server to stress") +MACRO_CONFIG_INT(DbgResizable, dbg_resizable, 0, 0, 0, CFGFLAG_CLIENT, "Enables window resizing") + +// DDRace +MACRO_CONFIG_STR(SvWelcome, sv_welcome, 64, "", CFGFLAG_SERVER, "Message that will be displayed to players who join the server") +MACRO_CONFIG_INT(SvReservedSlots, sv_reserved_slots, 0, 0, 16, CFGFLAG_SERVER, "The number of slots that are reserved for special players") +MACRO_CONFIG_STR(SvReservedSlotsPass, sv_reserved_slots_pass, 32, "", CFGFLAG_SERVER, "The password that is required to use a reserved slot") +MACRO_CONFIG_INT(SvHit, sv_hit, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether players can hammer/grenade/laser eachother or not") +MACRO_CONFIG_INT(SvEndlessDrag, sv_endless_drag, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Turns endless hooking on/off") +MACRO_CONFIG_INT(SvTestingCommands, sv_test_cmds, 0, 0, 1, CFGFLAG_SERVER, "Turns testing commands aka cheats on/off") +MACRO_CONFIG_INT(SvFreezeDelay, sv_freeze_delay, 3, 1, 30, CFGFLAG_SERVER|CFGFLAG_GAME, "How many seconds the players will remain frozen (applies to all except delayed freeze in switch layer & deepfreeze)") +MACRO_CONFIG_INT(ClDDRaceBinds, cl_race_binds, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Enable Default DDRace builds when pressing the reset binds button") +MACRO_CONFIG_INT(ClDDRaceBindsSet, cl_race_binds_set, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether the DDRace binds set or not (this is automated you don't need to use this)") +MACRO_CONFIG_INT(SvEndlessSuperHook, sv_endless_super_hook, 0, 0, 1, CFGFLAG_SERVER, "Endless hook for super players on/off") +MACRO_CONFIG_INT(SvHideScore, sv_hide_score, 0, 0, 1, CFGFLAG_SERVER, "Whether players scores will be announced or not") +MACRO_CONFIG_INT(SvSaveWorseScores, sv_save_worse_scores, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether to save worse scores when you already have a better one") +MACRO_CONFIG_INT(SvPauseable, sv_pauseable, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether players can pause their char or not") +MACRO_CONFIG_INT(SvPauseMessages, sv_pause_messages, 0, 0, 1, CFGFLAG_SERVER, "Whether to show messages when a player pauses and resumes") +MACRO_CONFIG_INT(SvPauseTime, sv_pause_time, 0, 0, 1, CFGFLAG_SERVER, "Whether '/pause' and 'sv_max_dc_restore' pauses the time of player or not") +MACRO_CONFIG_INT(SvPauseFrequency, sv_pause_frequency, 1, 0, 9999, CFGFLAG_SERVER, "The minimum allowed delay between pauses") + +MACRO_CONFIG_INT(SvEmotionalTees, sv_emotional_tees, 1, -1, 1, CFGFLAG_SERVER, "Whether eye change of tees is enabled with emoticons = 1, not = 0, -1 not at all") +MACRO_CONFIG_INT(SvEmoticonDelay, sv_emoticon_delay, 3, 0, 9999, CFGFLAG_SERVER, "The time in seconds between over-head emoticons") +MACRO_CONFIG_INT(SvEyeEmoteChangeDelay, sv_eye_emote_change_delay, 1, 0, 9999, CFGFLAG_SERVER, "The time in seconds between eye emoticons change") + + +MACRO_CONFIG_INT(SvChatDelay, sv_chat_delay, 1, 0, 9999, CFGFLAG_SERVER, "The time in seconds between chat messages") +MACRO_CONFIG_INT(SvTeamChangeDelay, sv_team_change_delay, 3, 0, 9999, CFGFLAG_SERVER, "The time in seconds between team changes (spectator/in game)") +MACRO_CONFIG_INT(SvInfoChangeDelay, sv_info_change_delay, 5, 0, 9999, CFGFLAG_SERVER, "The time in seconds between info changes (name/skin/color), to avoid ranbow mod set this to a very high time") +MACRO_CONFIG_INT(SvVoteTime, sv_vote_time, 25, 1, 9999, CFGFLAG_SERVER, "The time in seconds a vote lasts") +MACRO_CONFIG_INT(SvVoteMapTimeDelay, sv_vote_map_delay,0,0,9999,CFGFLAG_SERVER, "The minimum time in seconds between map votes") +MACRO_CONFIG_INT(SvVoteDelay, sv_vote_delay, 3, 0, 9999, CFGFLAG_SERVER, "The time in seconds between any vote") +MACRO_CONFIG_INT(SvVoteKickTimeDelay, sv_vote_kick_delay, 0, 0, 9999, CFGFLAG_SERVER, "The minimum time in seconds between kick votes") +MACRO_CONFIG_INT(SvVoteYesPercentage, sv_vote_yes_percentage, 50, 1, 100, CFGFLAG_SERVER, "The percent of people that need to agree or deny for the vote to succeed/fail") +MACRO_CONFIG_INT(SvVoteMajority, sv_vote_majority, 0, 0, 1, CFGFLAG_SERVER, "Whether No. of Yes is compared to No. of No votes or to number of total Players ( Default is 0 Y compare N)") +MACRO_CONFIG_INT(SvVoteMaxTotal, sv_vote_max_total, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "How many people can participate in a vote at max (0 = no limit by default)") +MACRO_CONFIG_INT(SvVoteVetoTime, sv_vote_veto_time, 20, 0, 1000, CFGFLAG_SERVER, "Minutes of time on a server until a player can veto map change votes (0 = disabled)") +MACRO_CONFIG_INT(SvSpectatorVotes, sv_spectator_votes, 1, 0, 1, CFGFLAG_SERVER, "Choose if spectators are allowed to start votes") +MACRO_CONFIG_INT(SvKillDelay, sv_kill_delay,3,0,9999,CFGFLAG_SERVER, "The minimum time in seconds between kills") +MACRO_CONFIG_INT(SvSuicidePenalty, sv_suicide_penalty,0,0,9999,CFGFLAG_SERVER, "The minimum time in seconds between kill or /kills and respawn") + +MACRO_CONFIG_INT(SvMapWindow, sv_map_window, 15, 0, 100, CFGFLAG_SERVER, "Map downloading send-ahead window") +MACRO_CONFIG_INT(SvFastDownload, sv_fast_download, 1, 0, 1, CFGFLAG_SERVER, "Enables fast download of maps") + +MACRO_CONFIG_INT(SvShotgunBulletSound, sv_shotgun_bullet_sound, 0, 0, 1, CFGFLAG_SERVER, "Crazy shotgun bullet sound on/off") + +MACRO_CONFIG_INT(SvCheckpointSave, sv_checkpoint_save, 1, 0, 1, CFGFLAG_SERVER, "Whether to save checkpoint times to the score file") +MACRO_CONFIG_STR(SvScoreFolder, sv_score_folder, 32, "records", CFGFLAG_SERVER, "Folder to save score files to") + +#if defined(CONF_SQL) +MACRO_CONFIG_INT(SvUseSQL, sv_use_sql, 0, 0, 1, CFGFLAG_SERVER, "Enables SQL DB instead of record file") +MACRO_CONFIG_STR(SvSqlUser, sv_sql_user, 32, "nameless", CFGFLAG_SERVER, "SQL User") +MACRO_CONFIG_STR(SvSqlPw, sv_sql_pw, 32, "tee", CFGFLAG_SERVER, "SQL Password") +MACRO_CONFIG_STR(SvSqlIp, sv_sql_ip, 32, "127.0.0.1", CFGFLAG_SERVER, "SQL Database IP") +MACRO_CONFIG_INT(SvSqlPort, sv_sql_port, 3306, 0, 65535, CFGFLAG_SERVER, "SQL Database port") +MACRO_CONFIG_INT(SvSqlCreateTables, sv_sql_create_tables, 1, 0, 1, CFGFLAG_SERVER, "Try to create the SQL tables when starting") +MACRO_CONFIG_STR(SvSqlDatabase, sv_sql_database, 16, "teeworlds", CFGFLAG_SERVER, "SQL Database name") +MACRO_CONFIG_STR(SvSqlServerName, sv_sql_servername, 5, "UNK", CFGFLAG_SERVER, "SQL Server name that is inserted into record table") +MACRO_CONFIG_STR(SvSqlPrefix, sv_sql_prefix, 16, "record", CFGFLAG_SERVER, "SQL Database table prefix") +MACRO_CONFIG_INT(SvSaveGames, sv_savegames, 1, 0, 1, CFGFLAG_SERVER, "Enables savegames (/save and /load)") +MACRO_CONFIG_INT(SvSaveGamesDelay, sv_savegames_delay, 60, 0, 10000, CFGFLAG_SERVER, "Delay in seconds for loading a savegame") +#endif + +MACRO_CONFIG_INT(SvDDRaceRules, sv_ddrace_rules, 1, 0, 1, CFGFLAG_SERVER, "Whether the default mod rules are displayed or not") +MACRO_CONFIG_STR(SvRulesLine1, sv_rules_line1, 128, "", CFGFLAG_SERVER, "Rules line 1") +MACRO_CONFIG_STR(SvRulesLine2, sv_rules_line2, 128, "", CFGFLAG_SERVER, "Rules line 2") +MACRO_CONFIG_STR(SvRulesLine3, sv_rules_line3, 128, "", CFGFLAG_SERVER, "Rules line 3") +MACRO_CONFIG_STR(SvRulesLine4, sv_rules_line4, 128, "", CFGFLAG_SERVER, "Rules line 4") +MACRO_CONFIG_STR(SvRulesLine5, sv_rules_line5, 128, "", CFGFLAG_SERVER, "Rules line 5") +MACRO_CONFIG_STR(SvRulesLine6, sv_rules_line6, 128, "", CFGFLAG_SERVER, "Rules line 6") +MACRO_CONFIG_STR(SvRulesLine7, sv_rules_line7, 128, "", CFGFLAG_SERVER, "Rules line 7") +MACRO_CONFIG_STR(SvRulesLine8, sv_rules_line8, 128, "", CFGFLAG_SERVER, "Rules line 8") +MACRO_CONFIG_STR(SvRulesLine9, sv_rules_line9, 128, "", CFGFLAG_SERVER, "Rules line 9") +MACRO_CONFIG_STR(SvRulesLine10, sv_rules_line10, 128, "", CFGFLAG_SERVER, "Rules line 10") + +MACRO_CONFIG_INT(SvTeam, sv_team, 1, 0, 3, CFGFLAG_SERVER|CFGFLAG_GAME, "Teams configuration (0 = off, 1 = on but optional, 2 = must play only with teams, 3 = forced random team only for you)") +MACRO_CONFIG_INT(SvTeamMaxSize, sv_max_team_size, MAX_CLIENTS, 1, MAX_CLIENTS, CFGFLAG_SERVER|CFGFLAG_GAME, "Maximum team size (from 2 to 64)") +MACRO_CONFIG_INT(SvTeamLock, sv_team_lock, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Enable team lock") +MACRO_CONFIG_INT(SvMapVote, sv_map_vote, 1, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether to allow /map") + +MACRO_CONFIG_STR(SvAnnouncementFileName, sv_announcement_filename, 24, "announcement.txt", CFGFLAG_SERVER, "file which will have the announcement, each one at a line") +MACRO_CONFIG_INT(SvAnnouncementInterval, sv_announcement_interval, 300, 1, 9999, CFGFLAG_SERVER, "time(minutes) in which the announcement will be displayed from the announcement file") +MACRO_CONFIG_INT(SvAnnouncementRandom, sv_announcement_random, 1, 0, 1, CFGFLAG_SERVER, "Whether announcements are sequential or random") + +MACRO_CONFIG_INT(SvOldLaser, sv_old_laser, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether lasers can hit you if you shot them and that they pull you towards the bounce origin (0 for all new maps) or lasers can't hit you if you shot them, and they pull others towards the shooter") +MACRO_CONFIG_INT(SvSlashMe, sv_slash_me, 0, 0, 1, CFGFLAG_SERVER, "Whether /me is active on the server or not") +MACRO_CONFIG_INT(SvRejoinTeam0, sv_rejoin_team_0, 1, 0, 1, CFGFLAG_SERVER, "Make a team automatically rejoin team 0 after finish (only if not locked)") + +MACRO_CONFIG_INT(ClReconnectBan, cl_reconnect_ban, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Auto reconnect when banned") +MACRO_CONFIG_INT(ClReconnectFull, cl_reconnect_full, 1, 0, 1, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Auto reconnect when server is full") +MACRO_CONFIG_INT(ClReconnectBanTimeout, cl_reconnect_ban_timeout, 30, 5, 120, CFGFLAG_CLIENT | CFGFLAG_SAVE, "How many seconds to wait before reconnecting (when banned)") +MACRO_CONFIG_INT(ClReconnectFullTimeout, cl_reconnect_full_timeout, 5, 1, 120, CFGFLAG_CLIENT | CFGFLAG_SAVE, "How many seconds to wait before reconnecting (when server is full)") + +MACRO_CONFIG_INT(ClMessageSystemHue, cl_message_system_hue, 42, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "System message color hue") +MACRO_CONFIG_INT(ClMessageSystemSat, cl_message_system_sat, 255, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "System message color saturation") +MACRO_CONFIG_INT(ClMessageSystemLht, cl_message_system_lht, 192, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "System message color lightness") + +MACRO_CONFIG_INT(ClMessageHighlightHue, cl_message_highlight_hue, 0, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Highlighted message color hue") +MACRO_CONFIG_INT(ClMessageHighlightSat, cl_message_highlight_sat, 255, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Highlighted message color saturation") +MACRO_CONFIG_INT(ClMessageHighlightLht, cl_message_highlight_lht, 192, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Highlighted message color lightness") + +MACRO_CONFIG_INT(ClMessageTeamHue, cl_message_team_hue, 85, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Team message color hue") +MACRO_CONFIG_INT(ClMessageTeamSat, cl_message_team_sat, 255, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Team message color saturation") +MACRO_CONFIG_INT(ClMessageTeamLht, cl_message_team_lht, 212, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Team message color lightness") + +MACRO_CONFIG_INT(ClMessageHue, cl_message_hue, 0, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Message color hue") +MACRO_CONFIG_INT(ClMessageSat, cl_message_sat, 0, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Message color saturation") +MACRO_CONFIG_INT(ClMessageLht, cl_message_lht, 255, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Message color lightness") + +MACRO_CONFIG_INT(ClLaserInnerHue, cl_laser_inner_hue, 170, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser inner color hue") +MACRO_CONFIG_INT(ClLaserInnerSat, cl_laser_inner_sat, 255, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser inner color saturation") +MACRO_CONFIG_INT(ClLaserInnerLht, cl_laser_inner_lht, 191, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser inner color lightness") + +MACRO_CONFIG_INT(ClLaserOutlineHue, cl_laser_outline_hue, 170, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser outline color hue") +MACRO_CONFIG_INT(ClLaserOutlineSat, cl_laser_outline_sat, 137, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser outline color saturation") +MACRO_CONFIG_INT(ClLaserOutlineLht, cl_laser_outline_lht, 41, 0, 255, CFGFLAG_CLIENT | CFGFLAG_SAVE, "Laser outline color lightness") + +MACRO_CONFIG_INT(ConnTimeout, conn_timeout, 100, 5, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Network timeout") +MACRO_CONFIG_INT(ConnTimeoutProtection, conn_timeout_protection, 1000, 5, 10000, CFGFLAG_SAVE|CFGFLAG_SERVER, "Network timeout protection") +MACRO_CONFIG_INT(ClShowIDs, cl_show_ids, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Whether to show client ids in scoreboard") +MACRO_CONFIG_INT(ClScoreboardOnDeath, cl_scoreboard_on_death, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Whether to show scoreboard after death or not") +MACRO_CONFIG_INT(ClAutoRaceRecord, cl_auto_race_record, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Save the best demo of each race") +MACRO_CONFIG_INT(ClDemoName, cl_demo_name, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Save the player name within the demo") +MACRO_CONFIG_INT(ClDemoAssumeRace, cl_demo_assume_race, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Assume that demos are race demos") +MACRO_CONFIG_INT(ClRaceGhost, cl_race_ghost, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Enable ghost") +MACRO_CONFIG_INT(ClRaceShowGhost, cl_race_show_ghost, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ghost") +MACRO_CONFIG_INT(ClRaceSaveGhost, cl_race_save_ghost, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Save ghost") +MACRO_CONFIG_INT(ClDDRaceScoreBoard, cl_ddrace_scoreboard, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Enable DDRace Scoreboard ") +MACRO_CONFIG_INT(ClShowDecisecs, cl_show_decisecs, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show deciseconds in game time") +MACRO_CONFIG_INT(SvResetPickups, sv_reset_pickups, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Whether the weapons are reset on passing the start tile or not") +MACRO_CONFIG_INT(ClShowOthers, cl_show_others, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show players in other teams") +MACRO_CONFIG_INT(ClShowOthersAlpha, cl_show_others_alpha, 40, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show players in other teams (alpha value, 0 invisible, 100 fully visible)") +MACRO_CONFIG_INT(ClOverlayEntities, cl_overlay_entities, 0, 0, 100, CFGFLAG_CLIENT, "Overlay game tiles with a percentage of opacity") +MACRO_CONFIG_INT(ClShowQuads, cl_show_quads, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show quads") +MACRO_CONFIG_INT(ClZoomBackgroundLayers, cl_zoom_background_layers, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Zoom background layers") +MACRO_CONFIG_INT(ClBackgroundHue, cl_background_hue, 0, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background color hue") +MACRO_CONFIG_INT(ClBackgroundSat, cl_background_sat, 0, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background color saturation") +MACRO_CONFIG_INT(ClBackgroundLht, cl_background_lht, 128, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background color lightness") +MACRO_CONFIG_INT(ClBackgroundEntitiesHue, cl_background_entities_hue, 0, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background (entities) color hue") +MACRO_CONFIG_INT(ClBackgroundEntitiesSat, cl_background_entities_sat, 0, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background (entities) color saturation") +MACRO_CONFIG_INT(ClBackgroundEntitiesLht, cl_background_entities_lht, 128, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background (entities) color lightness") +MACRO_CONFIG_STR(ClBackgroundEntities, cl_background_entities, 100, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background (entities)") +MACRO_CONFIG_INT(ClBackgroundShowTilesLayers, cl_background_show_tiles_layers, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether draw tiles layers when using custom background (entities)") +MACRO_CONFIG_INT(SvShowOthers, sv_show_others, 1, 0, 1, CFGFLAG_SERVER, "Whether players can user the command showothers or not") +MACRO_CONFIG_INT(SvShowOthersDefault, sv_show_others_default, 0, 0, 1, CFGFLAG_SERVER, "Whether players see others by default") +MACRO_CONFIG_INT(SvShowAllDefault, sv_show_all_default, 0, 0, 1, CFGFLAG_SERVER, "Whether players see all tees by default") +MACRO_CONFIG_INT(SvMaxAfkTime, sv_max_afk_time, 0, 0, 9999, CFGFLAG_SERVER, "The time in seconds a player is allowed to be afk (0 = disabled)") +MACRO_CONFIG_INT(SvMaxAfkVoteTime, sv_max_afk_vote_time, 300, 0, 9999, CFGFLAG_SERVER, "The time in seconds a player can be afk and his votes still count (0 = disabled)") +MACRO_CONFIG_INT(SvPlasmaRange, sv_plasma_range, 700, 1, 99999, CFGFLAG_SERVER|CFGFLAG_GAME, "How far will the plasma gun track tees") +MACRO_CONFIG_INT(SvPlasmaPerSec, sv_plasma_per_sec, 3, 0, 50, CFGFLAG_SERVER|CFGFLAG_GAME, "How many shots does the plasma gun fire per seconds") +MACRO_CONFIG_INT(SvDraggerRange, sv_dragger_range, 700, 1, 99999, CFGFLAG_SERVER|CFGFLAG_GAME, "How far will the dragger track tees") +MACRO_CONFIG_INT(SvVotePause, sv_vote_pause, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to pause players (instead of moving to spectators)") +MACRO_CONFIG_INT(SvVotePauseTime, sv_vote_pause_time, 10, 0, 360, CFGFLAG_SERVER, "The time (in seconds) players have to wait in pause when paused by vote") +MACRO_CONFIG_INT(SvTuneReset, sv_tune_reset, 1, 0, 1, CFGFLAG_SERVER, "Whether tuning is reset after each map change or not") +MACRO_CONFIG_STR(SvResetFile, sv_reset_file, 128, "reset.cfg", CFGFLAG_SERVER, "File to execute on map change or reload to set the default server settings") +MACRO_CONFIG_STR(SvInputFifo, sv_input_fifo, 128, "", CFGFLAG_SERVER, "Fifo file to use as input for server console") +MACRO_CONFIG_INT(SvDDRaceTuneReset, sv_ddrace_tune_reset, 1, 0, 1, CFGFLAG_SERVER, "Whether DDRace tuning(sv_hit, Sv_Endless_Drag & Sv_Old_Laser) is reset after each map change or not") +MACRO_CONFIG_INT(SvNamelessScore, sv_nameless_score, 0, 0, 1, CFGFLAG_SERVER, "Whether nameless tee has a score or not") +MACRO_CONFIG_INT(SvTimeInBroadcastInterval, sv_time_in_broadcast_interval, 1, 0, 60, CFGFLAG_SERVER, "How often to update the broadcast time") +MACRO_CONFIG_INT(SvDefaultTimerType, sv_default_timer_type, 0, 0, 1, CFGFLAG_SERVER, "Default way of displaying time either game/round timer or broadcast. 0 = game/round timer, 1 = broadcast") + + +// these might need some fine tuning +MACRO_CONFIG_INT(SvChatPenalty, sv_chat_penalty, 250, 50, 1000, CFGFLAG_SERVER, "chat score will be increased by this on every message, and decremented by 1 on every tick.") +MACRO_CONFIG_INT(SvChatThreshold, sv_chat_threshold, 1000, 50, 10000 , CFGFLAG_SERVER, "if chats core exceeds this, the player will be muted for sv_spam_mute_duration seconds") +MACRO_CONFIG_INT(SvSpamMuteDuration, sv_spam_mute_duration, 60, 0, 3600 , CFGFLAG_SERVER, "how many seconds to mute, if player triggers mute on spam. 0 = off") + +MACRO_CONFIG_INT(SvEvents, sv_events, 1, 0, 1, CFGFLAG_SERVER, "Enable triggering of server events, like the happy eyeemotes on some holidays.") +MACRO_CONFIG_INT(SvRankCheats, sv_rank_cheats, 0, 0, 1, CFGFLAG_SERVER, "Enable ranks after cheats have been used (file based server only)") +MACRO_CONFIG_INT(SvShutdownWhenEmpty, sv_shutdown_when_empty, 0, 0, 1, CFGFLAG_SERVER, "Shutdown server as soon as noone is on it anymore") +MACRO_CONFIG_INT(SvReloadWhenEmpty, sv_reload_when_empty, 0, 0, 2, CFGFLAG_SERVER, "Reload map when server is empty (1 = reload once, 2 = reload everytime server gets empty)") +MACRO_CONFIG_INT(SvKillProtection, sv_kill_protection, 20, 0, 9999, CFGFLAG_SERVER, "0 - Disable, 1-9999 minutes") +MACRO_CONFIG_INT(SvSoloServer, sv_solo_server, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Set server to solo mode (no player interactions, has to be set before loading the map)") +MACRO_CONFIG_STR(SvClientSuggestion, sv_client_suggestion, 128, "Get DDNet client from DDNet.tw to use all features on DDNet!", CFGFLAG_SERVER, "Broadcast to display to players without DDNet client") +MACRO_CONFIG_STR(SvClientSuggestionOld, sv_client_suggestion_old, 128, "Your DDNet client is old, update it on DDNet.tw!", CFGFLAG_SERVER, "Broadcast to display to players with an old version of DDNet client") +MACRO_CONFIG_STR(SvClientSuggestionBot, sv_client_suggestion_bot, 128, "Your client has bots and can be remote controlled!\nPlease use another client like DDNet client from DDNet.tw", CFGFLAG_SERVER, "Broadcast to display to players with a known botting client") + +// netlimit +MACRO_CONFIG_INT(SvNetlimit, sv_netlimit, 0, 0, 10000, CFGFLAG_SERVER, "Netlimit: Maximum amount of traffic a client is allowed to use (in kb/s)") +MACRO_CONFIG_INT(SvNetlimitAlpha, sv_netlimit_alpha, 50, 1, 100, CFGFLAG_SERVER, "Netlimit: Alpha of Exponention moving average") + +MACRO_CONFIG_INT(ClUnpredictedShadow, cl_unpredicted_shadow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show unpredicted shadow tee to estimate your delay") +MACRO_CONFIG_INT(ClPredictDDRace, cl_predict_ddrace, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict some DDRace tiles") +MACRO_CONFIG_INT(ClShowNinja, cl_show_ninja, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ninja skin") +MACRO_CONFIG_INT(ClShowOtherHookColl, cl_show_other_hook_coll, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show other players' hook collision line") +MACRO_CONFIG_INT(ClChatTeamColors, cl_chat_teamcolors, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show names in chat in team colors") +MACRO_CONFIG_INT(ClChatReset, cl_chat_reset, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Reset chat when pressing escape") +MACRO_CONFIG_INT(ClShowDirection, cl_show_direction, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show tee direction") +MACRO_CONFIG_INT(ClHttpMapDownload, cl_http_map_download, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Try fast HTTP map download first") +MACRO_CONFIG_INT(ClOldGunPosition, cl_old_gun_position, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Tees hold gun a bit higher like in TW 0.6.1 and older") +MACRO_CONFIG_INT(ClConfirmDisconnect, cl_confirm_disconnect, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Confirmation popup before disconnecting") +MACRO_CONFIG_STR(ClTimeoutCode, cl_timeout_code, 64, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Timeout code to use") +MACRO_CONFIG_STR(ClDummyTimeoutCode, cl_dummy_timeout_code, 64, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Dummy Timeout code to use") +MACRO_CONFIG_STR(ClInputFifo, cl_input_fifo, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Fifo file to use as input for client console") +MACRO_CONFIG_INT(ClShowConsole, cl_show_console, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show console window (Windows only)") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(InpJoystick, inp_joystick, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Try to use a joystick as input") +#else +MACRO_CONFIG_INT(InpJoystick, inp_joystick, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Try to use a joystick as input") +#endif +MACRO_CONFIG_INT(ClConfigVersion, cl_config_version, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "The config version. Helps newer clients fix bugs with older configs.") + +// demo editor +MACRO_CONFIG_INT(ClDemoSliceBegin, cl_demo_slice_begin, -1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Begin marker for demo slice") +MACRO_CONFIG_INT(ClDemoSliceEnd, cl_demo_slice_end, -1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "End marer for demo slice") +MACRO_CONFIG_INT(ClDemoShowSpeed, cl_demo_show_speed, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Show speed meter on change") + +#endif diff --git a/src/engine/shared/console.cpp b/src/engine/shared/console.cpp new file mode 100644 index 0000000..8bd9882 --- /dev/null +++ b/src/engine/shared/console.cpp @@ -0,0 +1,1117 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <new> + +#include <base/math.h> +#include <base/system.h> + +#include <engine/storage.h> +#include <engine/shared/protocol.h> + +#include "config.h" +#include "console.h" +#include "linereader.h" + +// todo: rework this + +const char *CConsole::CResult::GetString(unsigned Index) +{ + if (Index >= m_NumArgs) + return ""; + return m_apArgs[Index]; +} + +int CConsole::CResult::GetInteger(unsigned Index) +{ + if (Index >= m_NumArgs) + return 0; + return str_toint(m_apArgs[Index]); +} + +float CConsole::CResult::GetFloat(unsigned Index) +{ + if (Index >= m_NumArgs) + return 0.0f; + return str_tofloat(m_apArgs[Index]); +} + +const IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLevel, int FlagMask) const +{ + const CCommand *pInfo = m_pNext; + while(pInfo) + { + if(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel) + break; + pInfo = pInfo->m_pNext; + } + return pInfo; +} + +const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int FlagMask) const +{ + for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel) + return pCommand; + } + + return 0; +} + +// the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces + + +int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) +{ + char *pStr; + int Len = sizeof(pResult->m_aStringStorage); + if(Length < Len) + Len = Length; + + str_copy(pResult->m_aStringStorage, pString, Len); + 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; +} + +int CConsole::ParseArgs(CResult *pResult, const char *pFormat) +{ + char Command = *pFormat; + char *pStr; + int Optional = 0; + int Error = 0; + + pResult->ResetVictim(); + + pStr = pResult->m_pArgsStart; + + while(1) + { + 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; + } + + while(Command) + { + if(Command == 'v') + { + pResult->SetVictim(CResult::VICTIM_ME); + break; + } + Command = NextParam(pFormat); + } + break; + } + + // add token + if(*pStr == '"') + { + char *pDst; + pStr++; + pResult->AddArgument(pStr); + + pDst = pStr; // we might have to process escape data + while(1) + { + if(pStr[0] == '"') + break; + else if(pStr[0] == '\\') + { + if(pStr[1] == '\\') + pStr++; // skip due to escape + else if(pStr[1] == '"') + pStr++; // skip due to escape + } + else if(pStr[0] == 0) + return 1; // return error + + *pDst = *pStr; + pDst++; + pStr++; + } + + // write null termination + *pDst = 0; + + + pStr++; + } + else + { + char* pVictim = 0; + + if (Command != 'v') + pResult->AddArgument(pStr); + else + pVictim = pStr; + + if(Command == 'r') // rest of the string + break; + else if(Command == 'v') // validate victim + pStr = str_skip_to_whitespace(pStr); + else if(Command == 'i') // validate int + pStr = str_skip_to_whitespace(pStr); + else if(Command == 'f') // validate float + pStr = str_skip_to_whitespace(pStr); + else if(Command == 's') // validate string + pStr = str_skip_to_whitespace(pStr); + + if(pStr[0] != 0) // check for end of string + { + pStr[0] = 0; + pStr++; + } + + if (pVictim) + pResult->SetVictim(pVictim); + } + } + // fetch next command + Command = NextParam(pFormat); + } + + return Error; +} + +char CConsole::NextParam(const char *&pFormat) +{ + if (*pFormat) + { + pFormat++; + + if (*pFormat == '[') + { + // skip bracket contents + for (; *pFormat != ']'; pFormat++) + { + if (!*pFormat) + return *pFormat; + } + + // skip ']' + pFormat++; + + // skip space if there is one + if (*pFormat == ' ') + pFormat++; + } + } + return *pFormat; +} + +int CConsole::RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) +{ + if(m_NumPrintCB == MAX_PRINT_CB) + return -1; + + m_aPrintCB[m_NumPrintCB].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); + m_aPrintCB[m_NumPrintCB].m_pfnPrintCallback = pfnPrintCallback; + m_aPrintCB[m_NumPrintCB].m_pPrintCallbackUserdata = pUserData; + return m_NumPrintCB++; +} + +void CConsole::SetPrintOutputLevel(int Index, int OutputLevel) +{ + if(Index >= 0 && Index < MAX_PRINT_CB) + m_aPrintCB[Index].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); +} + +void CConsole::Print(int Level, const char *pFrom, const char *pStr, bool Highlighted) +{ + dbg_msg(pFrom ,"%s", pStr); + for(int i = 0; i < m_NumPrintCB; ++i) + { + if(Level <= m_aPrintCB[i].m_OutputLevel && m_aPrintCB[i].m_pfnPrintCallback) + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "[%s]: %s", pFrom, pStr); + m_aPrintCB[i].m_pfnPrintCallback(aBuf, m_aPrintCB[i].m_pPrintCallbackUserdata, Highlighted); + } + } +} + +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 == '"') + InString ^= 1; + else if(*pEnd == '\\') // escape sequences + { + if(pEnd[1] == '"') + pEnd++; + } + else if(!InString) + { + if(*pEnd == ';') // command separator + { + pNextPart = pEnd+1; + break; + } + 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); + + return true; +} + +void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID) +{ + while(pStr && *pStr) + { + CResult Result; + Result.m_ClientID = ClientID; + const char *pEnd = pStr; + const char *pNextPart = 0; + int InString = 0; + + while(*pEnd) + { + if(*pEnd == '"') + InString ^= 1; + else if(*pEnd == '\\') // escape sequences + { + if(pEnd[1] == '"') + pEnd++; + } + else if(!InString) + { + if(*pEnd == ';') // command separator + { + pNextPart = pEnd+1; + break; + } + else if(*pEnd == '#') // comment, no need to do anything more + break; + } + + pEnd++; + } + + if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) + return; + + if(!*Result.m_pCommand) + return; + + CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); + + if(pCommand) + { + if(ClientID == IConsole::CLIENT_ID_GAME + && !(pCommand->m_Flags & CFGFLAG_GAME)) + { + if(Stroke) + { + char aBuf[96]; + str_format(aBuf, sizeof(aBuf), "Command '%s' cannot be executed from a map.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + } + else if(ClientID == IConsole::CLIENT_ID_NO_GAME + && pCommand->m_Flags & CFGFLAG_GAME) + { + if(Stroke) + { + char aBuf[96]; + str_format(aBuf, sizeof(aBuf), "Command '%s' cannot be executed from a non-map config file.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_format(aBuf, sizeof(aBuf), "Hint: Put the command in '%s.cfg' instead of '%s.map.cfg' ", g_Config.m_SvMap, g_Config.m_SvMap); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + } + else if(pCommand->GetAccessLevel() >= m_AccessLevel) + { + int IsStrokeCommand = 0; + if(Result.m_pCommand[0] == '+') + { + // insert the stroke direction token + Result.AddArgument(m_paStrokeStr[Stroke]); + IsStrokeCommand = 1; + } + + if(Stroke || IsStrokeCommand) + { + if(ParseArgs(&Result, pCommand->m_pParams)) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Invalid arguments... Usage: %s %s", pCommand->m_pName, pCommand->m_pParams); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + else if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE) + { + m_ExecutionQueue.AddEntry(); + m_ExecutionQueue.m_pLast->m_pfnCommandCallback = pCommand->m_pfnCallback; + m_ExecutionQueue.m_pLast->m_pCommandUserData = pCommand->m_pUserData; + m_ExecutionQueue.m_pLast->m_Result = Result; + } + else + { + if(Result.GetVictim() == CResult::VICTIM_ME) + Result.SetVictim(ClientID); + + if(pCommand->m_Flags&CMDFLAG_TEST && !g_Config.m_SvTestingCommands) + return; + + if (Result.HasVictim()) + { + if(Result.GetVictim() == CResult::VICTIM_ALL) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + Result.SetVictim(i); + pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); + } + } + else + pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); + } + else + pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); + + if (pCommand->m_Flags&CMDFLAG_TEST) + m_Cheated = true; + } + } + } + else if(Stroke) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Access for command %s denied.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + } + else if(Stroke) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "No such command: %s.", Result.m_pCommand); + Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + + pStr = pNextPart; + } +} + +void CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) +{ + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) + { + if(str_find_nocase(pCommand->m_pName, pStr)) + pfnCallback(pCommand->m_pName, pUser); + } + } +} + +CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) +{ + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask) + { + if(str_comp_nocase(pCommand->m_pName, pName) == 0) + return pCommand; + } + } + + return 0x0; +} + +void CConsole::ExecuteLine(const char *pStr, int ClientID) +{ + CConsole::ExecuteLineStroked(1, pStr, ClientID); // press it + CConsole::ExecuteLineStroked(0, pStr, ClientID); // then release it +} + +void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask, int ClientID) +{ + int Temp = m_FlagMask; + m_FlagMask = FlagMask; + ExecuteLine(pStr, ClientID); + m_FlagMask = Temp; +} + + +void CConsole::ExecuteFile(const char *pFilename, int ClientID) +{ + // make sure that this isn't being executed already + for(CExecFile *pCur = m_pFirstExec; pCur; pCur = pCur->m_pPrev) + if(str_comp(pFilename, pCur->m_pFilename) == 0) + return; + + if(!m_pStorage) + m_pStorage = Kernel()->RequestInterface<IStorage>(); + if(!m_pStorage) + return; + + // push this one to the stack + CExecFile ThisFile; + CExecFile *pPrev = m_pFirstExec; + ThisFile.m_pFilename = pFilename; + ThisFile.m_pPrev = m_pFirstExec; + m_pFirstExec = &ThisFile; + + // exec the file + IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); + + char aBuf[128]; + if(File) + { + char *pLine; + CLineReader lr; + + str_format(aBuf, sizeof(aBuf), "executing '%s'", pFilename); + Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + lr.Init(File); + + while((pLine = lr.Get())) + ExecuteLine(pLine, ClientID); + + io_close(File); + } + else + { + str_format(aBuf, sizeof(aBuf), "failed to open '%s'", pFilename); + Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + } + + m_pFirstExec = pPrev; +} + +void CConsole::Con_Echo(IResult *pResult, void *pUserData) +{ + ((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0)); +} + +void CConsole::Con_Exec(IResult *pResult, void *pUserData) +{ + ((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0)); +} + +void CConsole::ConCommandAccess(IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast<CConsole *>(pUser); + char aBuf[128]; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), CFGFLAG_SERVER); + if(pCommand) + { + if(pResult->NumArguments() == 2) + { + pCommand->SetAccessLevel(pResult->GetInteger(1)); + str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_format(aBuf, sizeof(aBuf), "helper access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() >= ACCESS_LEVEL_HELPER ? "enabled" : "disabled"); + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_format(aBuf, sizeof(aBuf), "user access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() >= ACCESS_LEVEL_USER ? "enabled" : "disabled"); + } + else + { + str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_format(aBuf, sizeof(aBuf), "helper access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() >= ACCESS_LEVEL_HELPER ? "enabled" : "disabled"); + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + str_format(aBuf, sizeof(aBuf), "user access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() >= ACCESS_LEVEL_USER ? "enabled" : "disabled"); + } + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); + + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CConsole::ConCommandStatus(IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast<CConsole *>(pUser); + char aBuf[240]; + mem_zero(aBuf, sizeof(aBuf)); + int Used = 0; + + for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() >= clamp(pResult->GetInteger(0), (int)ACCESS_LEVEL_ADMIN, (int)ACCESS_LEVEL_USER)) + { + int Length = str_length(pCommand->m_pName); + if(Used + Length + 2 < (int)(sizeof(aBuf))) + { + if(Used > 0) + { + Used += 2; + str_append(aBuf, ", ", sizeof(aBuf)); + } + str_append(aBuf, pCommand->m_pName, sizeof(aBuf)); + Used += Length; + } + else + { + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); + mem_zero(aBuf, sizeof(aBuf)); + str_copy(aBuf, pCommand->m_pName, sizeof(aBuf)); + Used = Length; + } + } + } + if(Used > 0) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CConsole::ConUserCommandStatus(IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast<CConsole *>(pUser); + CResult Result; + Result.m_pCommand = "access_status"; + char aBuf[4]; + str_format(aBuf, sizeof(aBuf), "%d", IConsole::ACCESS_LEVEL_USER); + Result.AddArgument(aBuf); + + pConsole->ConCommandStatus(&Result, pConsole); +} + +struct CIntVariableData +{ + IConsole *m_pConsole; + int *m_pVariable; + int m_Min; + int m_Max; + int m_OldValue; +}; + +struct CStrVariableData +{ + IConsole *m_pConsole; + char *m_pStr; + int m_MaxSize; + char *m_pOldValue; +}; + +static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData) +{ + CIntVariableData *pData = (CIntVariableData *)pUserData; + + if(pResult->NumArguments()) + { + int Val = pResult->GetInteger(0); + + // do clamping + if(pData->m_Min != pData->m_Max) + { + if (Val < pData->m_Min) + Val = pData->m_Min; + if (pData->m_Max != 0 && Val > pData->m_Max) + Val = pData->m_Max; + } + + *(pData->m_pVariable) = Val; + if(pResult->m_ClientID != IConsole::CLIENT_ID_GAME) + pData->m_OldValue = Val; + } + else + { + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "Value: %d", *(pData->m_pVariable)); + pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + } +} + +static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData) +{ + CStrVariableData *pData = (CStrVariableData *)pUserData; + + if(pResult->NumArguments()) + { + const char *pString = pResult->GetString(0); + if(!str_utf8_check(pString)) + { + char Temp[4]; + int Length = 0; + while(*pString) + { + int Size = str_utf8_encode(Temp, static_cast<const unsigned char>(*pString++)); + if(Length+Size < pData->m_MaxSize) + { + mem_copy(pData->m_pStr+Length, &Temp, Size); + Length += Size; + } + else + break; + } + pData->m_pStr[Length] = 0; + } + else + str_copy(pData->m_pStr, pString, pData->m_MaxSize); + + if(pResult->m_ClientID != IConsole::CLIENT_ID_GAME) + str_copy(pData->m_pOldValue, pData->m_pStr, pData->m_MaxSize); + } + else + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "Value: %s", pData->m_pStr); + pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); + } +} + +void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast<CConsole *>(pUser); + char aBuf[128] = {0}; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask); + if(pCommand) + { + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + void *pUserData = pCommand->m_pUserData; + + // check for chain + if(pCommand->m_pfnCallback == Con_Chain) + { + CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData); + pfnCallback = pChainInfo->m_pfnCallback; + pUserData = pChainInfo->m_pCallbackUserData; + } + + if(pfnCallback == IntVariableCommand) + { + CIntVariableData *pData = static_cast<CIntVariableData *>(pUserData); + int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1); + str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val); + pConsole->ExecuteLine(aBuf); + aBuf[0] = 0; + } + else + str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(0)); + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); + + if(aBuf[0] != 0) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser) +{ + CConsole* pConsole = static_cast<CConsole *>(pUser); + char aBuf[128] = {0}; + CCommand *pCommand = pConsole->FindCommand(pResult->GetString(1), pConsole->m_FlagMask); + if(pCommand) + { + FCommandCallback pfnCallback = pCommand->m_pfnCallback; + + // check for chain + if(pCommand->m_pfnCallback == Con_Chain) + { + CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData); + pfnCallback = pChainInfo->m_pfnCallback; + } + + if(pfnCallback == IntVariableCommand) + { + int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2); + str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val); + pConsole->ExecuteLine(aBuf); + aBuf[0] = 0; + } + else + str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(1)); + } + else + str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(1)); + + if(aBuf[0] != 0) + pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); +} + +CConsole::CConsole(int FlagMask) +{ + m_FlagMask = FlagMask; + m_AccessLevel = ACCESS_LEVEL_ADMIN; + m_pRecycleList = 0; + m_TempCommands.Reset(); + m_StoreCommands = true; + m_paStrokeStr[0] = "0"; + m_paStrokeStr[1] = "1"; + m_ExecutionQueue.Reset(); + m_pFirstCommand = 0; + m_pFirstExec = 0; + mem_zero(m_aPrintCB, sizeof(m_aPrintCB)); + m_NumPrintCB = 0; + + m_pStorage = 0; + + // register some basic commands + Register("echo", "r[text]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, "Echo the text"); + Register("exec", "r[file]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); + + Register("toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value"); + Register("+toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress"); + + Register("access_level", "s[command] ?i[accesslevel]", CFGFLAG_SERVER, ConCommandAccess, this, "Specify command accessibility (admin = 0, moderator = 1, helper = 2, all = 3)"); + Register("access_status", "i[accesslevel]", CFGFLAG_SERVER, ConCommandStatus, this, "List all commands which are accessible for admin = 0, moderator = 1, helper = 2, all = 3"); + Register("cmdlist", "", CFGFLAG_SERVER|CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users"); + + // 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, Def }; \ + Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \ + } + + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ + { \ + static char OldValue[Len] = Def; \ + static CStrVariableData Data = { this, g_Config.m_##Name, Len, OldValue }; \ + Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ + } + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR + + // DDRace + + m_Cheated = false; +} + +void CConsole::ParseArguments(int NumArgs, const char **ppArguments) +{ + for(int i = 0; i < NumArgs; i++) + { + // check for scripts to execute + if(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0) + { + if(NumArgs - i > 1) + ExecuteFile(ppArguments[i+1]); + i++; + } + else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i])) + { + // skip silent param + continue; + } + else + { + // search arguments for overrides + ExecuteLine(ppArguments[i]); + } + } +} + +void CConsole::AddCommandSorted(CCommand *pCommand) +{ + if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0) + { + if(m_pFirstCommand && m_pFirstCommand->m_pNext) + pCommand->m_pNext = m_pFirstCommand; + else + pCommand->m_pNext = 0; + m_pFirstCommand = pCommand; + } + else + { + for(CCommand *p = m_pFirstCommand; p; p = p->m_pNext) + { + if(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) <= 0) + { + pCommand->m_pNext = p->m_pNext; + p->m_pNext = pCommand; + break; + } + } + } +} + +void CConsole::Register(const char *pName, const char *pParams, + int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) +{ + CCommand *pCommand = FindCommand(pName, Flags); + bool DoAdd = false; + if(pCommand == 0) + { + pCommand = new(mem_alloc(sizeof(CCommand), sizeof(void*))) CCommand; + DoAdd = true; + } + pCommand->m_pfnCallback = pfnFunc; + pCommand->m_pUserData = pUser; + + pCommand->m_pName = pName; + pCommand->m_pHelp = pHelp; + pCommand->m_pParams = pParams; + + pCommand->m_Flags = Flags; + pCommand->m_Temp = false; + + if(DoAdd) + AddCommandSorted(pCommand); + + if(pCommand->m_Flags&CFGFLAG_CHAT) + pCommand->SetAccessLevel(ACCESS_LEVEL_USER); +} + +void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) +{ + CCommand *pCommand; + if(m_pRecycleList) + { + pCommand = m_pRecycleList; + str_copy(const_cast<char *>(pCommand->m_pName), pName, TEMPCMD_NAME_LENGTH); + str_copy(const_cast<char *>(pCommand->m_pHelp), pHelp, TEMPCMD_HELP_LENGTH); + str_copy(const_cast<char *>(pCommand->m_pParams), pParams, TEMPCMD_PARAMS_LENGTH); + + m_pRecycleList = m_pRecycleList->m_pNext; + } + else + { + pCommand = new(m_TempCommands.Allocate(sizeof(CCommand))) CCommand; + char *pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_NAME_LENGTH)); + str_copy(pMem, pName, TEMPCMD_NAME_LENGTH); + pCommand->m_pName = pMem; + pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_HELP_LENGTH)); + str_copy(pMem, pHelp, TEMPCMD_HELP_LENGTH); + pCommand->m_pHelp = pMem; + pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_PARAMS_LENGTH)); + str_copy(pMem, pParams, TEMPCMD_PARAMS_LENGTH); + pCommand->m_pParams = pMem; + } + + pCommand->m_pfnCallback = 0; + pCommand->m_pUserData = 0; + pCommand->m_Flags = Flags; + pCommand->m_Temp = true; + + AddCommandSorted(pCommand); +} + +void CConsole::DeregisterTemp(const char *pName) +{ + if(!m_pFirstCommand) + return; + + CCommand *pRemoved = 0; + + // remove temp entry from command list + if(m_pFirstCommand->m_Temp && str_comp(m_pFirstCommand->m_pName, pName) == 0) + { + pRemoved = m_pFirstCommand; + m_pFirstCommand = m_pFirstCommand->m_pNext; + } + else + { + for(CCommand *pCommand = m_pFirstCommand; pCommand->m_pNext; pCommand = pCommand->m_pNext) + if(pCommand->m_pNext->m_Temp && str_comp(pCommand->m_pNext->m_pName, pName) == 0) + { + pRemoved = pCommand->m_pNext; + pCommand->m_pNext = pCommand->m_pNext->m_pNext; + break; + } + } + + // add to recycle list + if(pRemoved) + { + pRemoved->m_pNext = m_pRecycleList; + m_pRecycleList = pRemoved; + } +} + +void CConsole::DeregisterTempAll() +{ + // set non temp as first one + for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext); + + // remove temp entries from command list + for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext) + { + CCommand *pNext = pCommand->m_pNext; + if(pNext->m_Temp) + { + for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext); + pCommand->m_pNext = pNext; + } + } + + m_TempCommands.Reset(); + m_pRecycleList = 0; +} + +void CConsole::Con_Chain(IResult *pResult, void *pUserData) +{ + CChain *pInfo = (CChain *)pUserData; + pInfo->m_pfnChainCallback(pResult, pInfo->m_pUserData, pInfo->m_pfnCallback, pInfo->m_pCallbackUserData); +} + +void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) +{ + CCommand *pCommand = FindCommand(pName, m_FlagMask); + + if(!pCommand) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "failed to chain '%s'", pName); + Print(IConsole::OUTPUT_LEVEL_DEBUG, "console", aBuf); + return; + } + + CChain *pChainInfo = (CChain *)mem_alloc(sizeof(CChain), sizeof(void*)); + + // store info + pChainInfo->m_pfnChainCallback = pfnChainFunc; + 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; +} + +void CConsole::StoreCommands(bool Store) +{ + if(!Store) + { + for(CExecutionQueue::CQueueEntry *pEntry = m_ExecutionQueue.m_pFirst; pEntry; pEntry = pEntry->m_pNext) + pEntry->m_pfnCommandCallback(&pEntry->m_Result, pEntry->m_pCommandUserData); + m_ExecutionQueue.Reset(); + } + m_StoreCommands = Store; +} + + +const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp) +{ + for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) + { + if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) + { + if(str_comp_nocase(pCommand->m_pName, pName) == 0) + return pCommand; + } + } + + return 0; +} + + +extern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); } + +void CConsole::ResetServerGameSettings() +{ + #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ + { \ + if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \ + { \ + CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \ + void *pUserData = pCommand->m_pUserData; \ + FCommandCallback pfnCallback = pCommand->m_pfnCallback; \ + while(pfnCallback == Con_Chain) \ + { \ + CChain *pChainInfo = (CChain *)pUserData; \ + pUserData = pChainInfo->m_pCallbackUserData; \ + pfnCallback = pChainInfo->m_pfnCallback; \ + } \ + CIntVariableData *pData = (CIntVariableData *)pUserData; \ + *pData->m_pVariable = pData->m_OldValue; \ + } \ + } + + #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ + { \ + if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \ + { \ + CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \ + void *pUserData = pCommand->m_pUserData; \ + FCommandCallback pfnCallback = pCommand->m_pfnCallback; \ + while(pfnCallback == Con_Chain) \ + { \ + CChain *pChainInfo = (CChain *)pUserData; \ + pUserData = pChainInfo->m_pCallbackUserData; \ + pfnCallback = pChainInfo->m_pfnCallback; \ + } \ + CStrVariableData *pData = (CStrVariableData *)pUserData; \ + str_copy(pData->m_pOldValue, pData->m_pStr, pData->m_MaxSize); \ + } \ + } + + #include "config_variables.h" + + #undef MACRO_CONFIG_INT + #undef MACRO_CONFIG_STR +} + +int CConsole::CResult::GetVictim() +{ + return m_Victim; +} + +void CConsole::CResult::ResetVictim() +{ + m_Victim = VICTIM_NONE; +} + +bool CConsole::CResult::HasVictim() +{ + return m_Victim != VICTIM_NONE; +} + +void CConsole::CResult::SetVictim(int Victim) +{ + m_Victim = clamp<int>(Victim, VICTIM_NONE, MAX_CLIENTS - 1); +} + +void CConsole::CResult::SetVictim(const char *pVictim) +{ + if(!str_comp(pVictim, "me")) + m_Victim = VICTIM_ME; + else if(!str_comp(pVictim, "all")) + m_Victim = VICTIM_ALL; + else + m_Victim = clamp<int>(str_toint(pVictim), 0, MAX_CLIENTS - 1); +} diff --git a/src/engine/shared/console.h b/src/engine/shared/console.h new file mode 100644 index 0000000..b97d16a --- /dev/null +++ b/src/engine/shared/console.h @@ -0,0 +1,213 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_CONSOLE_H +#define ENGINE_SHARED_CONSOLE_H + +#include <engine/console.h> +#include "memheap.h" + +class CConsole : public IConsole +{ + class CCommand : public CCommandInfo + { + public: + CCommand *m_pNext; + int m_Flags; + bool m_Temp; + FCommandCallback m_pfnCallback; + void *m_pUserData; + + virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const; + + void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_USER)); } + }; + + + class CChain + { + public: + FChainCommandCallback m_pfnChainCallback; + FCommandCallback m_pfnCallback; + void *m_pCallbackUserData; + void *m_pUserData; + }; + + int m_FlagMask; + bool m_StoreCommands; + const char *m_paStrokeStr[2]; + CCommand *m_pFirstCommand; + + class CExecFile + { + public: + const char *m_pFilename; + CExecFile *m_pPrev; + }; + + CExecFile *m_pFirstExec; + class IStorage *m_pStorage; + int m_AccessLevel; + + CCommand *m_pRecycleList; + CHeap m_TempCommands; + + static void Con_Chain(IResult *pResult, void *pUserData); + static void Con_Echo(IResult *pResult, void *pUserData); + static void Con_Exec(IResult *pResult, void *pUserData); + static void ConToggle(IResult *pResult, void *pUser); + static void ConToggleStroke(IResult *pResult, void *pUser); + static void ConCommandAccess(IResult *pResult, void *pUser); + static void ConCommandStatus(IConsole::IResult *pResult, void *pUser); + + void ExecuteFileRecurse(const char *pFilename); + void ExecuteLineStroked(int Stroke, const char *pStr, int ClientID = -1); + + struct + { + int m_OutputLevel; + FPrintCallback m_pfnPrintCallback; + void *m_pPrintCallbackUserdata; + } m_aPrintCB[MAX_PRINT_CB]; + int m_NumPrintCB; + + enum + { + CONSOLE_MAX_STR_LENGTH = 8192, + 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]; + + CResult() : IResult() + { + mem_zero(m_aStringStorage, sizeof(m_aStringStorage)); + m_pArgsStart = 0; + m_pCommand = 0; + mem_zero(m_apArgs, sizeof(m_apArgs)); + } + + CResult &operator =(const CResult &Other) + { + if(this != &Other) + { + IResult::operator=(Other); + mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage)); + m_pArgsStart = m_aStringStorage+(Other.m_pArgsStart-Other.m_aStringStorage); + m_pCommand = m_aStringStorage+(Other.m_pCommand-Other.m_aStringStorage); + for(unsigned i = 0; i < Other.m_NumArgs; ++i) + m_apArgs[i] = m_aStringStorage+(Other.m_apArgs[i]-Other.m_aStringStorage); + } + return *this; + } + + void AddArgument(const char *pArg) + { + m_apArgs[m_NumArgs++] = pArg; + } + + virtual const char *GetString(unsigned Index); + virtual int GetInteger(unsigned Index); + virtual float GetFloat(unsigned Index); + + // DDRace + + enum + { + VICTIM_NONE=-3, + VICTIM_ME=-2, + VICTIM_ALL=-1, + }; + + int m_Victim; + void ResetVictim(); + bool HasVictim(); + void SetVictim(int Victim); + void SetVictim(const char *pVictim); + virtual int GetVictim(); + }; + + int ParseStart(CResult *pResult, const char *pString, int Length); + int ParseArgs(CResult *pResult, const char *pFormat); + + /* + this function will set pFormat to the next parameter (i,s,r,v,?) it contains and + return the parameter; descriptions in brackets like [file] will be skipped; + returns '\0' if there is no next parameter; expects pFormat to point at a + parameter + */ + char NextParam(const char *&pFormat); + + class CExecutionQueue + { + CHeap m_Queue; + + public: + struct CQueueEntry + { + CQueueEntry *m_pNext; + FCommandCallback m_pfnCommandCallback; + void *m_pCommandUserData; + CResult m_Result; + } *m_pFirst, *m_pLast; + + void AddEntry() + { + CQueueEntry *pEntry = static_cast<CQueueEntry *>(m_Queue.Allocate(sizeof(CQueueEntry))); + pEntry->m_pNext = 0; + if(!m_pFirst) + m_pFirst = pEntry; + if(m_pLast) + m_pLast->m_pNext = pEntry; + m_pLast = pEntry; + (void)new(&(pEntry->m_Result)) CResult; + } + void Reset() + { + m_Queue.Reset(); + m_pFirst = m_pLast = 0; + } + } m_ExecutionQueue; + + void AddCommandSorted(CCommand *pCommand); + CCommand *FindCommand(const char *pName, int FlagMask); + +public: + CConsole(int FlagMask); + + virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int FlagMask) const; + virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp); + virtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser); + + virtual void ParseArguments(int NumArgs, const char **ppArguments); + virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp); + virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp); + virtual void DeregisterTemp(const char *pName); + virtual void DeregisterTempAll(); + 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, int ClientID = -1); + virtual void ExecuteLineFlag(const char *pStr, int FlagMask, int ClientID = -1); + virtual void ExecuteFile(const char *pFilename, int ClientID = -1); + + virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData); + virtual void SetPrintOutputLevel(int Index, int OutputLevel); + virtual void Print(int Level, const char *pFrom, const char *pStr, bool Highlighted = false); + + void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_USER)); } + void ResetServerGameSettings(); + // DDRace + + static void ConUserCommandStatus(IConsole::IResult *pResult, void *pUser); + void SetFlagMask(int FlagMask) { m_FlagMask = FlagMask; } +}; + +#endif diff --git a/src/engine/shared/datafile.cpp b/src/engine/shared/datafile.cpp new file mode 100644 index 0000000..8d6538b --- /dev/null +++ b/src/engine/shared/datafile.cpp @@ -0,0 +1,741 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> +#include <engine/storage.h> +#include "datafile.h" +#include <zlib.h> + +static const int DEBUG=0; + +struct CDatafileItemType +{ + int m_Type; + int m_Start; + int m_Num; +} ; + +struct CDatafileItem +{ + int m_TypeAndID; + int m_Size; +}; + +struct CDatafileHeader +{ + char m_aID[4]; + int m_Version; + int m_Size; + int m_Swaplen; + int m_NumItemTypes; + int m_NumItems; + int m_NumRawData; + int m_ItemSize; + int m_DataSize; +}; + +struct CDatafileData +{ + int m_NumItemTypes; + int m_NumItems; + int m_NumRawData; + int m_ItemSize; + int m_DataSize; + char m_aStart[4]; +}; + +struct CDatafileInfo +{ + CDatafileItemType *m_pItemTypes; + int *m_pItemOffsets; + int *m_pDataOffsets; + int *m_pDataSizes; + + char *m_pItemStart; + char *m_pDataStart; +}; + +struct CDatafile +{ + IOHANDLE m_File; + unsigned m_Crc; + CDatafileInfo m_Info; + CDatafileHeader m_Header; + int m_DataStartOffset; + char **m_ppDataPtrs; + char *m_pData; +}; + +bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int StorageType) +{ + dbg_msg("datafile", "loading. filename='%s'", pFilename); + + IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!File) + { + dbg_msg("datafile", "could not open '%s'", pFilename); + return false; + } + + + // take the CRC of the file and store it + unsigned Crc = 0; + { + enum + { + BUFFER_SIZE = 64*1024 + }; + + unsigned char aBuffer[BUFFER_SIZE]; + + while(1) + { + unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE); + if(Bytes <= 0) + break; + Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention + } + + io_seek(File, 0, IOSEEK_START); + } + + + // TODO: change this header + CDatafileHeader Header; + if (sizeof(Header) != io_read(File, &Header, sizeof(Header))) + { + dbg_msg("datafile", "couldn't load header"); + return 0; + } + if(Header.m_aID[0] != 'A' || Header.m_aID[1] != 'T' || Header.m_aID[2] != 'A' || Header.m_aID[3] != 'D') + { + if(Header.m_aID[0] != 'D' || Header.m_aID[1] != 'A' || Header.m_aID[2] != 'T' || Header.m_aID[3] != 'A') + { + dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aID[0], Header.m_aID[1], Header.m_aID[2], Header.m_aID[3]); + return 0; + } + } + +#if defined(CONF_ARCH_ENDIAN_BIG) + 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); + Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(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 + + CDatafile *pTmpDataFile = (CDatafile*)mem_alloc(AllocSize, 1); + pTmpDataFile->m_Header = Header; + pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size; + pTmpDataFile->m_ppDataPtrs = (char**)(pTmpDataFile+1); + 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) + { + io_close(pTmpDataFile->m_File); + mem_free(pTmpDataFile); + pTmpDataFile = 0; + dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", Size, ReadSize); + return false; + } + + Close(); + m_pDataFile = pTmpDataFile; + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(m_pDataFile->m_pData, sizeof(int), min(static_cast<unsigned>(Header.m_Swaplen), Size) / sizeof(int)); +#endif + + //if(DEBUG) + { + dbg_msg("datafile", "allocsize=%d", AllocSize); + dbg_msg("datafile", "readsize=%d", ReadSize); + 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 + m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; + m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize; + + dbg_msg("datafile", "loading done. datafile='%s'", pFilename); + + if(DEBUG) + { + /* + for(int i = 0; i < m_pDataFile->data.num_raw_data; i++) + { + 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; + void *data = datafile_get_item(df, i, &type, &id); + dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]); + int *idata = (int*)data; + for(int k = 0; k < 3; k++) + dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]); + } + + for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++) + { + dbg_msg("map", "\t%d: type=%x start=%d num=%d", i, + m_pDataFile->info.m_aItemTypes[i].type, + m_pDataFile->info.m_aItemTypes[i].start, + m_pDataFile->info.m_aItemTypes[i].num); + for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++) + { + int type, id; + datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id); + if(type != m_pDataFile->info.m_aItemTypes[i].type) + dbg_msg("map", "\tERROR"); + } + } + */ + } + + return true; +} + +bool CDataFileReader::GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize) +{ + IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!File) + return false; + + // get crc and size + unsigned Crc = 0; + unsigned Size = 0; + unsigned char aBuffer[64*1024]; + while(1) + { + unsigned Bytes = io_read(File, aBuffer, sizeof(aBuffer)); + if(Bytes <= 0) + break; + Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention + Size += Bytes; + } + + io_close(File); + + *pCrc = Crc; + *pSize = Size; + return true; +} + +int CDataFileReader::NumData() +{ + if(!m_pDataFile) { return 0; } + return m_pDataFile->m_Header.m_NumRawData; +} + +// always returns the size in the file +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]; +} + +// always returns the size in the file +int CDataFileReader::GetUncompressedDataSize(int Index) +{ + if(!m_pDataFile) { return 0; } + + if(m_pDataFile->m_Header.m_Version == 4) + return m_pDataFile->m_Info.m_pDataSizes[Index]; + else + return GetDataSize(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); +#if defined(CONF_ARCH_ENDIAN_BIG) + int SwapSize = DataSize; +#endif + + if(m_pDataFile->m_Header.m_Version == 4) + { + // v4 has compressed data + void *pTemp = (char *)mem_alloc(DataSize, 1); + unsigned long UncompressedSize = m_pDataFile->m_Info.m_pDataSizes[Index]; + unsigned long s; + + 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); + + // decompress the data, TODO: check for errors + s = UncompressedSize; + uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention +#if defined(CONF_ARCH_ENDIAN_BIG) + SwapSize = s; +#endif + + // clean up the temporary buffers + mem_free(pTemp); + } + else + { + // load the data + dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize); + m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(DataSize, 1); + 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, m_pDataFile->m_ppDataPtrs[Index], DataSize); + } + +#if defined(CONF_ARCH_ENDIAN_BIG) + if(Swap && SwapSize) + swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int)); +#endif + } + + return m_pDataFile->m_ppDataPtrs[Index]; +} + +void *CDataFileReader::GetData(int Index) +{ + return GetDataImpl(Index, 0); +} + +void *CDataFileReader::GetDataSwapped(int Index) +{ + return GetDataImpl(Index, 1); +} + +void CDataFileReader::UnloadData(int Index) +{ + if(Index < 0) + return; + + // + mem_free(m_pDataFile->m_ppDataPtrs[Index]); + m_pDataFile->m_ppDataPtrs[Index] = 0x0; +} + +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]; +} + +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 + if(pID) + *pID = i->m_TypeAndID&0xffff; + return (void *)(i+1); +} + +void CDataFileReader::GetType(int Type, int *pStart, int *pNum) +{ + *pStart = 0; + *pNum = 0; + + 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) + { + *pStart = m_pDataFile->m_Info.m_pItemTypes[i].m_Start; + *pNum = m_pDataFile->m_Info.m_pItemTypes[i].m_Num; + return; + } + } +} + +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++) + { + int ItemID; + void *pItem = GetItem(Start+i,0, &ItemID); + if(ID == ItemID) + return pItem; + } + return 0; +} + +int CDataFileReader::NumItems() +{ + if(!m_pDataFile) return 0; + return m_pDataFile->m_Header.m_NumItems; +} + +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; + return true; +} + +unsigned CDataFileReader::Crc() +{ + if(!m_pDataFile) return 0xFFFFFFFF; + return m_pDataFile->m_Crc; +} + + +CDataFileWriter::CDataFileWriter() +{ + m_File = 0; + m_pItemTypes = static_cast<CItemTypeInfo *>(mem_alloc(sizeof(CItemTypeInfo) * MAX_ITEM_TYPES, 1)); + m_pItems = static_cast<CItemInfo *>(mem_alloc(sizeof(CItemInfo) * MAX_ITEMS, 1)); + m_pDatas = static_cast<CDataInfo *>(mem_alloc(sizeof(CDataInfo) * MAX_DATAS, 1)); +} + +CDataFileWriter::~CDataFileWriter() +{ + mem_free(m_pItemTypes); + m_pItemTypes = 0; + mem_free(m_pItems); + m_pItems = 0; + mem_free(m_pDatas); + m_pDatas = 0; +} + +bool CDataFileWriter::OpenFile(class IStorage *pStorage, const char *pFilename) +{ + dbg_assert(!m_File, "a file already exists"); + m_File = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + return m_File != 0; +} + +void CDataFileWriter::Init() +{ + dbg_assert(!m_File, "a file already exists"); + m_NumItems = 0; + m_NumDatas = 0; + m_NumItemTypes = 0; + mem_zero(m_pItemTypes, sizeof(CItemTypeInfo) * MAX_ITEM_TYPES); + + for(int i = 0; i < MAX_ITEM_TYPES; i++) + { + m_pItemTypes[i].m_First = -1; + m_pItemTypes[i].m_Last = -1; + } +} + +bool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename) +{ + Init(); + return OpenFile(pStorage, pFilename); +} + +int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) +{ + dbg_assert(Type >= 0 && Type < 0xFFFF, "incorrect type"); + dbg_assert(m_NumItems < 1024, "too many items"); + dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + + m_pItems[m_NumItems].m_Type = Type; + m_pItems[m_NumItems].m_ID = ID; + m_pItems[m_NumItems].m_Size = Size; + + // copy data + m_pItems[m_NumItems].m_pData = mem_alloc(Size, 1); + mem_copy(m_pItems[m_NumItems].m_pData, pData, Size); + + if(!m_pItemTypes[Type].m_Num) // count item types + m_NumItemTypes++; + + // link + m_pItems[m_NumItems].m_Prev = m_pItemTypes[Type].m_Last; + m_pItems[m_NumItems].m_Next = -1; + + if(m_pItemTypes[Type].m_Last != -1) + m_pItems[m_pItemTypes[Type].m_Last].m_Next = m_NumItems; + m_pItemTypes[Type].m_Last = m_NumItems; + + if(m_pItemTypes[Type].m_First == -1) + m_pItemTypes[Type].m_First = m_NumItems; + + m_pItemTypes[Type].m_Num++; + + m_NumItems++; + return m_NumItems-1; +} + +int CDataFileWriter::AddData(int Size, void *pData) +{ + dbg_assert(m_NumDatas < 1024, "too much data"); + + CDataInfo *pInfo = &m_pDatas[m_NumDatas]; + unsigned long s = compressBound(Size); + void *pCompData = mem_alloc(s, 1); // temporary buffer that we use during compression + + int Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention + if(Result != Z_OK) + { + 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); + mem_copy(pInfo->m_pCompressedData, pCompData, pInfo->m_CompressedSize); + mem_free(pCompData); + + m_NumDatas++; + return m_NumDatas-1; +} + +int CDataFileWriter::AddDataSwapped(int Size, void *pData) +{ + dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); + +#if defined(CONF_ARCH_ENDIAN_BIG) + void *pSwapped = mem_alloc(Size, 1); // temporary buffer that we use during compression + mem_copy(pSwapped, pData, Size); + swap_endian(pSwapped, sizeof(int), Size/sizeof(int)); + int Index = AddData(Size, pSwapped); + mem_free(pSwapped); + return Index; +#else + return AddData(Size, pData); +#endif +} + + +int CDataFileWriter::Finish() +{ + if(!m_File) return 1; + + int ItemSize = 0; + int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize; + int DataSize = 0; + CDatafileHeader Header; + + // we should now write this file! + if(DEBUG) + dbg_msg("datafile", "writing"); + + // calculate sizes + for(int i = 0; i < m_NumItems; i++) + { + if(DEBUG) + dbg_msg("datafile", "item=%d size=%d (%d)", i, m_pItems[i].m_Size, m_pItems[i].m_Size+sizeof(CDatafileItem)); + ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem); + } + + + for(int i = 0; i < m_NumDatas; i++) + DataSize += m_pDatas[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'; + Header.m_aID[1] = 'A'; + Header.m_aID[2] = 'T'; + Header.m_aID[3] = 'A'; + Header.m_Version = 4; + Header.m_Size = FileSize - 16; + Header.m_Swaplen = SwapSize - 16; + Header.m_NumItemTypes = m_NumItemTypes; + Header.m_NumItems = m_NumItems; + Header.m_NumRawData = m_NumDatas; + Header.m_ItemSize = ItemSize; + Header.m_DataSize = DataSize; + + // write Header + if(DEBUG) + dbg_msg("datafile", "HeaderSize=%d", sizeof(Header)); +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); +#endif + io_write(m_File, &Header, sizeof(Header)); + } + + // write types + for(int i = 0, Count = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write info + CDatafileItemType Info; + Info.m_Type = i; + Info.m_Start = Count; + Info.m_Num = m_pItemTypes[i].m_Num; + if(DEBUG) + dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num); +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int)); +#endif + io_write(m_File, &Info, sizeof(Info)); + Count += m_pItemTypes[i].m_Num; + } + } + + // write item offsets + for(int i = 0, Offset = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write all m_pItems in of this type + int k = m_pItemTypes[i].m_First; + while(k != -1) + { + if(DEBUG) + dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset); + int Temp = Offset; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); +#endif + io_write(m_File, &Temp, sizeof(Temp)); + Offset += m_pItems[k].m_Size + sizeof(CDatafileItem); + + // next + k = m_pItems[k].m_Next; + } + } + } + + // write data offsets + for(int i = 0, Offset = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset); + int Temp = Offset; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); +#endif + io_write(m_File, &Temp, sizeof(Temp)); + Offset += m_pDatas[i].m_CompressedSize; + } + + // write data uncompressed sizes + for(int i = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize); + int UncompressedSize = m_pDatas[i].m_UncompressedSize; +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int)); +#endif + io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); + } + + // write m_pItems + for(int i = 0; i < 0xffff; i++) + { + if(m_pItemTypes[i].m_Num) + { + // write all m_pItems in of this type + int k = m_pItemTypes[i].m_First; + while(k != -1) + { + CDatafileItem Item; + Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID; + Item.m_Size = m_pItems[k].m_Size; + if(DEBUG) + dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size); + +#if defined(CONF_ARCH_ENDIAN_BIG) + swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); + swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int)); +#endif + io_write(m_File, &Item, sizeof(Item)); + io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size); + + // next + k = m_pItems[k].m_Next; + } + } + } + + // write data + for(int i = 0; i < m_NumDatas; i++) + { + if(DEBUG) + dbg_msg("datafile", "writing data id=%d size=%d", i, m_pDatas[i].m_CompressedSize); + io_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize); + } + + // free data + for(int i = 0; i < m_NumItems; i++) + mem_free(m_pItems[i].m_pData); + for(int i = 0; i < m_NumDatas; ++i) + mem_free(m_pDatas[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 new file mode 100644 index 0000000..0c2e07a --- /dev/null +++ b/src/engine/shared/datafile.h @@ -0,0 +1,93 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_DATAFILE_H +#define ENGINE_SHARED_DATAFILE_H + +// raw datafile access +class CDataFileReader +{ + struct CDatafile *m_pDataFile; + void *GetDataImpl(int Index, int Swap); +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); + int GetUncompressedDataSize(int Index); + void UnloadData(int Index); + void *GetItem(int Index, int *pType, int *pID); + int GetItemSize(int Index); + void GetType(int Type, int *pStart, int *pNum); + void *FindItem(int Type, int ID); + int NumItems(); + int NumData(); + void Unload(); + + unsigned Crc(); +}; + +// write access +class CDataFileWriter +{ + struct CDataInfo + { + int m_UncompressedSize; + int m_CompressedSize; + void *m_pCompressedData; + }; + + struct CItemInfo + { + int m_Type; + int m_ID; + int m_Size; + int m_Next; + int m_Prev; + void *m_pData; + }; + + struct CItemTypeInfo + { + int m_Num; + int m_First; + int m_Last; + }; + + enum + { + MAX_ITEM_TYPES=0xffff, + MAX_ITEMS=1024, + MAX_DATAS=1024, + }; + + IOHANDLE m_File; + int m_NumItems; + int m_NumDatas; + int m_NumItemTypes; + CItemTypeInfo *m_pItemTypes; + CItemInfo *m_pItems; + CDataInfo *m_pDatas; + +public: + CDataFileWriter(); + ~CDataFileWriter(); + void Init(); + bool OpenFile(class IStorage *pStorage, const char *pFilename); + bool Open(class IStorage *pStorage, const char *Filename); + int AddData(int Size, void *pData); + int AddDataSwapped(int Size, void *pData); + int AddItem(int Type, int ID, int Size, void *pData); + int Finish(); +}; + + +#endif diff --git a/src/engine/shared/demo.cpp b/src/engine/shared/demo.cpp new file mode 100644 index 0000000..ea0905f --- /dev/null +++ b/src/engine/shared/demo.cpp @@ -0,0 +1,977 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/console.h> +#include <engine/storage.h> + +#include <engine/shared/config.h> + +#include "compression.h" +#include "demo.h" +#include "memheap.h" +#include "network.h" +#include "snapshot.h" + +static const unsigned char gs_aHeaderMarker[7] = {'T', 'W', 'D', 'E', 'M', 'O', 0}; +static const unsigned char gs_ActVersion = 5; +static const unsigned char gs_OldVersion = 3; +static const unsigned char gs_VersionTickCompression = 5; // demo files with this version or higher will use `CHUNKTICKFLAG_TICK_COMPRESSED` +static const int gs_LengthOffset = 152; +static const int gs_NumMarkersOffset = 176; + + +CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool DelayedMapData) +{ + m_File = 0; + m_LastTickMarker = -1; + m_pSnapshotDelta = pSnapshotDelta; + m_DelayedMapData = DelayedMapData; +} + +// Record +int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetVersion, const char *pMap, unsigned Crc, const char *pType, unsigned int MapSize, unsigned char *pMapData) +{ + m_MapSize = MapSize; + m_pMapData = pMapData; + + IOHANDLE DemoFile = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!DemoFile) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Unable to open '%s' for recording", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); + return -1; + } + + CDemoHeader Header; + CTimelineMarkers TimelineMarkers; + if(m_File) + return -1; + + m_pConsole = pConsole; + + IOHANDLE MapFile = NULL; + + if(!m_DelayedMapData) + { + // open mapfile + char aMapFilename[128]; + // try the normal maps folder + str_format(aMapFilename, sizeof(aMapFilename), "maps/%s.map", pMap); + MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); + if(!MapFile) + { + // try the downloaded maps + str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", pMap, Crc); + MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); + } + if(!MapFile) + { + // search for the map within subfolders + 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); + } + if(!MapFile) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Unable to open mapfile '%s'", pMap); + 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)); + Header.m_Version = gs_ActVersion; + str_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion)); + str_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName)); + if(!m_DelayedMapData) + MapSize = io_length(MapFile); + Header.m_aMapSize[0] = (MapSize>>24)&0xff; + Header.m_aMapSize[1] = (MapSize>>16)&0xff; + Header.m_aMapSize[2] = (MapSize>>8)&0xff; + Header.m_aMapSize[3] = (MapSize)&0xff; + Header.m_aMapCrc[0] = (Crc>>24)&0xff; + Header.m_aMapCrc[1] = (Crc>>16)&0xff; + Header.m_aMapCrc[2] = (Crc>>8)&0xff; + Header.m_aMapCrc[3] = (Crc)&0xff; + str_copy(Header.m_aType, pType, sizeof(Header.m_aType)); + // Header.m_Length - add this on stop + str_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp)); + io_write(DemoFile, &Header, sizeof(Header)); + io_write(DemoFile, &TimelineMarkers, sizeof(TimelineMarkers)); // fill this on stop + + if(m_DelayedMapData) + { + io_seek(DemoFile, MapSize, IOSEEK_CUR); + } + else + { + // write map data + while(1) + { + unsigned char aChunk[1024*64]; + int Bytes = io_read(MapFile, &aChunk, sizeof(aChunk)); + if(Bytes <= 0) + break; + io_write(DemoFile, &aChunk, Bytes); + } + io_close(MapFile); + } + + m_LastKeyFrame = -1; + m_LastTickMarker = -1; + m_FirstTick = -1; + m_NumTimelineMarkers = 0; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Recording to '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); + m_File = DemoFile; + + return 0; +} + +/* + Tickmarker + 7 = Always set + 6 = Keyframe flag + 0-5 = Delta tick + + Normal + 7 = Not set + 5-6 = Type + 0-4 = Size +*/ + +enum +{ + CHUNKTYPEFLAG_TICKMARKER = 0x80, + CHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set + CHUNKTICKFLAG_TICK_COMPRESSED = 0x20, // when we store the tick value in the first chunk + + CHUNKMASK_TICK = 0x1f, + CHUNKMASK_TICK_LEGACY = 0x3f, + CHUNKMASK_TYPE = 0x60, + CHUNKMASK_SIZE = 0x1f, + + CHUNKTYPE_SNAPSHOT = 1, + CHUNKTYPE_MESSAGE = 2, + CHUNKTYPE_DELTA = 3, + + CHUNKFLAG_BIGSIZE = 0x10 +}; + +void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) +{ + if(m_LastTickMarker == -1 || Tick-m_LastTickMarker > CHUNKMASK_TICK || Keyframe) + { + unsigned char aChunk[5]; + aChunk[0] = CHUNKTYPEFLAG_TICKMARKER; + aChunk[1] = (Tick>>24)&0xff; + aChunk[2] = (Tick>>16)&0xff; + aChunk[3] = (Tick>>8)&0xff; + aChunk[4] = (Tick)&0xff; + + if(Keyframe) + aChunk[0] |= CHUNKTICKFLAG_KEYFRAME; + + io_write(m_File, aChunk, sizeof(aChunk)); + } + else + { + unsigned char aChunk[1]; + aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick-m_LastTickMarker); + io_write(m_File, aChunk, sizeof(aChunk)); + } + + m_LastTickMarker = Tick; + if(m_FirstTick < 0) + m_FirstTick = Tick; +} + +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; + + if(Size > 64*1024) + return; + + /* pad the data with 0 so we get an alignment of 4, + else the compression won't work and miss some bytes */ + mem_copy(aBuffer2, pData, Size); + while(Size&3) + 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) + { + aChunk[0] |= Size; + io_write(m_File, aChunk, 1); + } + else + { + if(Size < 256) + { + aChunk[0] |= 30; + aChunk[1] = Size&0xff; + io_write(m_File, aChunk, 2); + } + else + { + aChunk[0] |= 31; + aChunk[1] = Size&0xff; + aChunk[2] = Size>>8; + io_write(m_File, aChunk, 3); + } + } + + io_write(m_File, aBuffer2, Size); +} + +void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) +{ + if(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5) + { + // write full tickmarker + WriteTickMarker(Tick, 1); + + // write snapshot + Write(CHUNKTYPE_SNAPSHOT, pData, Size); + + m_LastKeyFrame = Tick; + mem_copy(m_aLastSnapshotData, pData, Size); + } + else + { + // create delta, prepend tick + char aDeltaData[CSnapshot::MAX_SIZE+sizeof(int)]; + int DeltaSize; + + // write tickmarker + WriteTickMarker(Tick, 0); + + DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData); + if(DeltaSize) + { + // record delta + Write(CHUNKTYPE_DELTA, aDeltaData, DeltaSize); + mem_copy(m_aLastSnapshotData, pData, Size); + } + } +} + +void CDemoRecorder::RecordMessage(const void *pData, int Size) +{ + Write(CHUNKTYPE_MESSAGE, pData, Size); +} + +int CDemoRecorder::Stop(bool Finalize) +{ + if(!m_File) + return -1; + + // add the demo length to the header + io_seek(m_File, gs_LengthOffset, IOSEEK_START); + int DemoLength = Length(); + char aLength[4]; + aLength[0] = (DemoLength>>24)&0xff; + aLength[1] = (DemoLength>>16)&0xff; + aLength[2] = (DemoLength>>8)&0xff; + aLength[3] = (DemoLength)&0xff; + io_write(m_File, aLength, sizeof(aLength)); + + // add the timeline markers to the header + io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START); + char aNumMarkers[4]; + aNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff; + aNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff; + aNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff; + aNumMarkers[3] = (m_NumTimelineMarkers)&0xff; + io_write(m_File, aNumMarkers, sizeof(aNumMarkers)); + for(int i = 0; i < m_NumTimelineMarkers; i++) + { + int Marker = m_aTimelineMarkers[i]; + char aMarker[4]; + aMarker[0] = (Marker>>24)&0xff; + aMarker[1] = (Marker>>16)&0xff; + aMarker[2] = (Marker>>8)&0xff; + aMarker[3] = (Marker)&0xff; + io_write(m_File, aMarker, sizeof(aMarker)); + } + + if(Finalize && m_DelayedMapData) + { + io_seek(m_File, gs_NumMarkersOffset + sizeof(CTimelineMarkers), IOSEEK_START); + io_write(m_File, m_pMapData, m_MapSize); + } + + io_close(m_File); + m_File = 0; + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Stopped recording"); + + return 0; +} + +void CDemoRecorder::AddDemoMarker() +{ + if(m_LastTickMarker < 0 || m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS) + return; + + // not more than 1 marker in a second + if(m_NumTimelineMarkers > 0) + { + int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1]; + if(Diff < SERVER_TICK_SPEED*1.0f) + return; + } + + m_aTimelineMarkers[m_NumTimelineMarkers++] = m_LastTickMarker; + + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker"); +} + + + +CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta) +{ + m_File = 0; + m_pKeyFrames = 0; + + m_pSnapshotDelta = pSnapshotDelta; + m_LastSnapshotDataSize = -1; +} + +void CDemoPlayer::SetListner(IListner *pListner) +{ + m_pListner = pListner; +} + + +int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) +{ + unsigned char Chunk = 0; + + *pSize = 0; + *pType = 0; + + if(m_File == NULL) + return -1; + + if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk)) + return -1; + + if(Chunk&CHUNKTYPEFLAG_TICKMARKER) + { + // decode tick marker + int Tickdelta_legacy = Chunk&(CHUNKMASK_TICK_LEGACY); // compatibility + *pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME); + + if(m_Info.m_Header.m_Version < gs_VersionTickCompression && Tickdelta_legacy != 0) + { + *pTick += Tickdelta_legacy; + } + else if(Chunk&(CHUNKTICKFLAG_TICK_COMPRESSED)) + { + int Tickdelta = Chunk&(CHUNKMASK_TICK); + *pTick += Tickdelta; + } + else + { + unsigned char aTickdata[4]; + if(io_read(m_File, aTickdata, sizeof(aTickdata)) != sizeof(aTickdata)) + return -1; + *pTick = (aTickdata[0]<<24) | (aTickdata[1]<<16) | (aTickdata[2]<<8) | aTickdata[3]; + } + + } + 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) + { + unsigned char aSizedata[2]; + if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) + return -1; + *pSize = (aSizedata[1]<<8) | aSizedata[0]; + } + } + + return 0; +} + +void CDemoPlayer::ScanFile() +{ + long StartPos; + CHeap Heap; + CKeyFrameSearch *pFirstKey = 0; + CKeyFrameSearch *pCurrentKey = 0; + //DEMOREC_CHUNK chunk; + int ChunkSize, ChunkType, ChunkTick = 0; + int i; + + StartPos = io_tell(m_File); + m_Info.m_SeekablePoints = 0; + + 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; + pKey->m_Frame.m_Tick = ChunkTick; + pKey->m_pNext = 0; + if(pCurrentKey) + pCurrentKey->m_pNext = pKey; + if(!pFirstKey) + pFirstKey = pKey; + 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); +} + +void CDemoPlayer::DoTick() +{ + static char aCompresseddata[CSnapshot::MAX_SIZE]; + static char aDecompressed[CSnapshot::MAX_SIZE]; + static char aData[CSnapshot::MAX_SIZE]; + int ChunkType, ChunkTick, ChunkSize; + int DataSize = 0; + int GotSnapshot = 0; + + // update ticks + m_Info.m_PreviousTick = m_Info.m_Info.m_CurrentTick; + m_Info.m_Info.m_CurrentTick = m_Info.m_NextTick; + ChunkTick = m_Info.m_Info.m_CurrentTick; + + while(1) + { + if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "end of file"); + if(m_Info.m_PreviousTick == -1) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "empty demo"); + Stop(); + } + else + Pause(); + break; + } + + // read the chunk + if(ChunkSize) + { + if(io_read(m_File, aCompresseddata, ChunkSize) != (unsigned)ChunkSize) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error reading chunk"); + Stop(); + break; + } + + DataSize = CNetBase::Decompress(aCompresseddata, ChunkSize, aDecompressed, sizeof(aDecompressed)); + if(DataSize < 0) + { + // stop on error or eof + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during network decompression"); + Stop(); + break; + } + + DataSize = CVariableInt::Decompress(aDecompressed, DataSize, aData); + + if(DataSize < 0) + { + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during intpack decompression"); + Stop(); + 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) + m_pListner->OnDemoPlayerSnapshot(aNewsnap, DataSize); + + m_LastSnapshotDataSize = DataSize; + mem_copy(m_aLastSnapshotData, aNewsnap, DataSize); + } + else + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "error during unpacking of delta, err=%d", DataSize); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); + } + } + else if(ChunkType == CHUNKTYPE_SNAPSHOT) + { + // process full snapshot + GotSnapshot = 1; + + m_LastSnapshotDataSize = DataSize; + mem_copy(m_aLastSnapshotData, aData, DataSize); + if(m_pListner) + m_pListner->OnDemoPlayerSnapshot(aData, DataSize); + } + else + { + // if there were no snapshots in this tick, replay the last one + if(!GotSnapshot && m_pListner && m_LastSnapshotDataSize != -1) + { + GotSnapshot = 1; + m_pListner->OnDemoPlayerSnapshot(m_aLastSnapshotData, m_LastSnapshotDataSize); + } + + // check the remaining types + if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) + { + m_Info.m_NextTick = ChunkTick; + break; + } + else if(ChunkType == CHUNKTYPE_MESSAGE) + { + if(m_pListner) + m_pListner->OnDemoPlayerMessage(aData, DataSize); + } + } + } +} + +void CDemoPlayer::Pause() +{ + m_Info.m_Info.m_Paused = 1; +} + +void CDemoPlayer::Unpause() +{ + if(m_Info.m_Info.m_Paused) + { + /*m_Info.start_tick = m_Info.current_tick; + m_Info.start_time = time_get();*/ + m_Info.m_Info.m_Paused = 0; + } +} + +int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType) +{ + m_pConsole = pConsole; + m_File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); + if(!m_File) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "could not open '%s'", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", aBuf); + return -1; + } + + // store the filename + str_copy(m_aFilename, pFilename, sizeof(m_aFilename)); + + // clear the playback info + mem_zero(&m_Info, sizeof(m_Info)); + m_Info.m_Info.m_FirstTick = -1; + m_Info.m_Info.m_LastTick = -1; + m_Info.m_NextTick = -1; + 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 + io_read(m_File, &m_Info.m_Header, sizeof(m_Info.m_Header)); + if(mem_comp(m_Info.m_Header.m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) != 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "'%s' is not a demo file", pFilename); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", aBuf); + io_close(m_File); + m_File = 0; + return -1; + } + + if(m_Info.m_Header.m_Version < gs_OldVersion) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "demo version %d is not supported", m_Info.m_Header.m_Version); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", aBuf); + io_close(m_File); + m_File = 0; + return -1; + } + else if(m_Info.m_Header.m_Version > gs_OldVersion) + io_read(m_File, &m_Info.m_TimelineMarkers, sizeof(m_Info.m_TimelineMarkers)); + + // get demo type + if(!str_comp(m_Info.m_Header.m_aType, "client")) + m_DemoType = DEMOTYPE_CLIENT; + else if(!str_comp(m_Info.m_Header.m_aType, "server")) + 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); + io_close(MapFile); + } + else if(MapSize > 0) + { + // 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); + } + + // store map inforation + m_MapInfo.m_Crc = Crc; + m_MapInfo.m_Size = MapSize; + str_copy(m_MapInfo.m_aName, m_Info.m_Header.m_aMapName, sizeof(m_MapInfo.m_aName)); + + + if(m_Info.m_Header.m_Version > gs_OldVersion) + { + // get timeline markers + int Num = ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[1]<<16)&0xFF0000) | + ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[3]&0xFF); + m_Info.m_Info.m_NumTimelineMarkers = Num; + for(int i = 0; i < Num && i < MAX_TIMELINE_MARKERS; i++) + { + char *pTimelineMarker = m_Info.m_TimelineMarkers.m_aTimelineMarkers[i]; + m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) | + ((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF); + } + } + + // scan the file for interessting points + ScanFile(); + + // reset slice markers + g_Config.m_ClDemoSliceBegin = -1; + g_Config.m_ClDemoSliceEnd = -1; + + // ready for playback + return 0; +} + +int CDemoPlayer::NextFrame() +{ + DoTick(); + return IsPlaying(); +} + +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();*/ + m_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED; + m_Info.m_LastUpdate = time_get(); + return 0; +} + +int CDemoPlayer::SetPos(float Percent) +{ + int Keyframe; + 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) + Keyframe++; + + 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); + + //m_Info.start_tick = -1; + m_Info.m_NextTick = -1; + m_Info.m_Info.m_CurrentTick = -1; + m_Info.m_PreviousTick = -1; + + // playback everything until we hit our tick + while(m_Info.m_PreviousTick < WantedTick && IsPlaying()) + DoTick(); + + Play(); + + return 0; +} + +void CDemoPlayer::SetSpeed(float Speed) +{ + m_Info.m_Info.m_Speed = Speed; +} + +int CDemoPlayer::Update(bool RealTime) +{ + 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; + + // break if we are ready + if(RealTime && 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) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "tick error prev=%d cur=%d next=%d", + m_Info.m_PreviousTick, m_Info.m_Info.m_CurrentTick, m_Info.m_NextTick); + m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); + } + } + + return 0; +} + +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; + mem_free(m_pKeyFrames); + m_pKeyFrames = 0; + str_copy(m_aFilename, "", sizeof(m_aFilename)); + return 0; +} + +void CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const +{ + const char *pFileName = m_aFilename; + const char *pExtractedName = pFileName; + const char *pEnd = 0; + for(; *pFileName; ++pFileName) + { + if(*pFileName == '/' || *pFileName == '\\') + pExtractedName = pFileName+1; + else if(*pFileName == '.') + pEnd = pFileName; + } + + int Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; + str_copy(pBuffer, pExtractedName, Length); +} + +bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const +{ + 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_OldVersion) + { + io_close(File); + return false; + } + + io_close(File); + return true; +} + +int CDemoPlayer::GetDemoType() const +{ + if(m_File) + return m_DemoType; + return DEMOTYPE_INVALID; +} + +void CDemoEditor::Init(const char *pNetVersion, class CSnapshotDelta *pSnapshotDelta, class IConsole *pConsole, class IStorage *pStorage) +{ + m_pNetVersion = pNetVersion; + m_pSnapshotDelta = pSnapshotDelta; + m_pConsole = pConsole; + m_pStorage = pStorage; +} + +void CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick) +{ + class CDemoPlayer DemoPlayer(m_pSnapshotDelta); + class CDemoRecorder DemoRecorder(m_pSnapshotDelta); + + m_pDemoPlayer = &DemoPlayer; + m_pDemoRecorder = &DemoRecorder; + + m_pDemoPlayer->SetListner(this); + + m_SliceFrom = StartTick; + m_SliceTo = EndTick; + m_Stop = false; + + if (m_pDemoPlayer->Load(m_pStorage, m_pConsole, pDemo, IStorage::TYPE_ALL) == -1) + return; + + const CDemoPlayer::CMapInfo *pMapInfo = m_pDemoPlayer->GetMapInfo(); + if (m_pDemoRecorder->Start(m_pStorage, m_pConsole, pDst, m_pNetVersion, pMapInfo->m_aName, pMapInfo->m_Crc, "client") == -1) + return; + + + m_pDemoPlayer->Play(); + const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info(); + + while (m_pDemoPlayer->IsPlaying() && !m_Stop) { + m_pDemoPlayer->Update(false); + + if (pInfo->m_Info.m_Paused) + break; + } + + m_pDemoRecorder->Stop(); +} + +void CDemoEditor::OnDemoPlayerSnapshot(void *pData, int Size) +{ + const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info(); + + if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) + m_Stop = true; + else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) + m_pDemoRecorder->RecordSnapshot(pInfo->m_Info.m_CurrentTick, pData, Size); +} + +void CDemoEditor::OnDemoPlayerMessage(void *pData, int Size) +{ + const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info(); + + if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo) + m_Stop = true; + else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom) + m_pDemoRecorder->RecordMessage(pData, Size); +} diff --git a/src/engine/shared/demo.h b/src/engine/shared/demo.h new file mode 100644 index 0000000..2a4ede8 --- /dev/null +++ b/src/engine/shared/demo.h @@ -0,0 +1,162 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_DEMO_H +#define ENGINE_SHARED_DEMO_H + +#include <engine/demo.h> +#include <engine/shared/protocol.h> + +#include "snapshot.h" + +class CDemoRecorder : public IDemoRecorder +{ + class IConsole *m_pConsole; + IOHANDLE m_File; + int m_LastTickMarker; + int m_LastKeyFrame; + int m_FirstTick; + unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; + class CSnapshotDelta *m_pSnapshotDelta; + int m_NumTimelineMarkers; + int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; + bool m_DelayedMapData; + unsigned int m_MapSize; + unsigned char *m_pMapData; + + void WriteTickMarker(int Tick, int Keyframe); + void Write(int Type, const void *pData, int Size); +public: + CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool DelayedMapData = false); + CDemoRecorder() {} + + int Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetversion, const char *pMap, unsigned MapCrc, const char *pType, unsigned int MapSize = 0, unsigned char *pMapData = 0); + int Stop(bool Finalize = false); + void AddDemoMarker(); + + void RecordSnapshot(int Tick, const void *pData, int Size); + void RecordMessage(const void *pData, int Size); + + bool IsRecording() const { return m_File != 0; } + + int Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; } +}; + +class CDemoPlayer : public IDemoPlayer +{ +public: + class IListner + { + public: + virtual ~IListner() {} + virtual void OnDemoPlayerSnapshot(void *pData, int Size) = 0; + virtual void OnDemoPlayerMessage(void *pData, int Size) = 0; + }; + + struct CPlaybackInfo + { + CDemoHeader m_Header; + CTimelineMarkers m_TimelineMarkers; + + 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; + }; + + struct CMapInfo + { + char m_aName[128]; + int m_Crc; + int m_Size; + }; + +private: + IListner *m_pListner; + + + // Playback + struct CKeyFrame + { + long m_Filepos; + int m_Tick; + }; + + struct CKeyFrameSearch + { + CKeyFrame m_Frame; + CKeyFrameSearch *m_pNext; + }; + + class IConsole *m_pConsole; + IOHANDLE m_File; + char m_aFilename[256]; + CKeyFrame *m_pKeyFrames; + CMapInfo m_MapInfo; + + CPlaybackInfo m_Info; + int m_DemoType; + unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; + int m_LastSnapshotDataSize; + class CSnapshotDelta *m_pSnapshotDelta; + + int ReadChunkHeader(int *pType, int *pSize, int *pTick); + void DoTick(); + void ScanFile(); + 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(); + void SetSpeed(float Speed); + int SetPos(float Percent); + const CInfo *BaseInfo() const { return &m_Info.m_Info; } + void GetDemoName(char *pBuffer, int BufferSize) const; + bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const; + const char *GetDemoFileName() { return m_aFilename; }; + int GetDemoType() const; + + int Update(bool RealTime=true); + + const CPlaybackInfo *Info() const { return &m_Info; } + virtual bool IsPlaying() const { return m_File != 0; } + const CMapInfo *GetMapInfo() { return &m_MapInfo; }; +}; + +class CDemoEditor : public IDemoEditor, public CDemoPlayer::IListner +{ + CDemoPlayer *m_pDemoPlayer; + CDemoRecorder *m_pDemoRecorder; + IConsole *m_pConsole; + IStorage *m_pStorage; + class CSnapshotDelta *m_pSnapshotDelta; + const char *m_pNetVersion; + + bool m_Stop; + int m_SliceFrom; + int m_SliceTo; + +public: + virtual void Init(const char *pNetVersion, class CSnapshotDelta *pSnapshotDelta, class IConsole *pConsole, class IStorage *pStorage); + virtual void Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick); + + virtual void OnDemoPlayerSnapshot(void *pData, int Size); + virtual void OnDemoPlayerMessage(void *pData, int Size); +}; + +#endif diff --git a/src/engine/shared/econ.cpp b/src/engine/shared/econ.cpp new file mode 100644 index 0000000..d3e4b22 --- /dev/null +++ b/src/engine/shared/econ.cpp @@ -0,0 +1,187 @@ +#include <engine/console.h> +#include <engine/shared/config.h> + +#include "econ.h" +#include "netban.h" + + +int CEcon::NewClientCallback(int ClientID, void *pUser) +{ + CEcon *pThis = (CEcon *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "client accepted. cid=%d addr=%s'", ClientID, aAddrStr); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); + + pThis->m_aClients[ClientID].m_State = CClient::STATE_CONNECTED; + pThis->m_aClients[ClientID].m_TimeConnected = time_get(); + pThis->m_aClients[ClientID].m_AuthTries = 0; + + pThis->m_NetConsole.Send(ClientID, "Enter password:"); + return 0; +} + +int CEcon::DelClientCallback(int ClientID, const char *pReason, void *pUser) +{ + CEcon *pThis = (CEcon *)pUser; + + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); + + pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; + return 0; +} + +void CEcon::SendLineCB(const char *pLine, void *pUserData, bool Highlighted) +{ + static_cast<CEcon *>(pUserData)->Send(-1, pLine); +} + +void CEcon::ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CEcon *pThis = static_cast<CEcon *>(pUserData); + pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); + } +} + +void CEcon::ConLogout(IConsole::IResult *pResult, void *pUserData) +{ + CEcon *pThis = static_cast<CEcon *>(pUserData); + + if(pThis->m_UserClientID >= 0 && pThis->m_UserClientID < NET_MAX_CONSOLE_CLIENTS && pThis->m_aClients[pThis->m_UserClientID].m_State != CClient::STATE_EMPTY) + pThis->m_NetConsole.Drop(pThis->m_UserClientID, "Logout"); +} + +void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan) +{ + m_pConsole = pConsole; + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + m_aClients[i].m_State = CClient::STATE_EMPTY; + + m_Ready = false; + m_UserClientID = -1; + + if(g_Config.m_EcPort == 0 || g_Config.m_EcPassword[0] == 0) + return; + + NETADDR BindAddr; + if(g_Config.m_EcBindaddr[0] && net_host_lookup(g_Config.m_EcBindaddr, &BindAddr, NETTYPE_ALL) == 0) + { + // got bindaddr + BindAddr.type = NETTYPE_ALL; + BindAddr.port = g_Config.m_EcPort; + } + else + { + mem_zero(&BindAddr, sizeof(BindAddr)); + BindAddr.type = NETTYPE_ALL; + BindAddr.port = g_Config.m_EcPort; + } + + if(m_NetConsole.Open(BindAddr, pNetBan, 0)) + { + m_NetConsole.SetCallbacks(NewClientCallback, DelClientCallback, this); + m_Ready = true; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "bound to %s:%d", g_Config.m_EcBindaddr, g_Config.m_EcPort); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", aBuf); + + Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this); + m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this); + + Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ"); + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", "couldn't open socket. port might already be in use"); +} + +void CEcon::Update() +{ + if(!m_Ready) + return; + + m_NetConsole.Update(); + + char aBuf[NET_MAX_PACKETSIZE]; + int ClientID; + + while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID)) + { + dbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, "got message from empty slot"); + if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED) + { + if(str_comp(aBuf, g_Config.m_EcPassword) == 0) + { + m_aClients[ClientID].m_State = CClient::STATE_AUTHED; + m_NetConsole.Send(ClientID, "Authentication successful. External console access granted."); + + str_format(aBuf, sizeof(aBuf), "cid=%d authed", ClientID); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", aBuf); + } + else + { + m_aClients[ClientID].m_AuthTries++; + char aMsg[128]; + str_format(aMsg, sizeof(aMsg), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES); + m_NetConsole.Send(ClientID, aMsg); + if(m_aClients[ClientID].m_AuthTries >= MAX_AUTH_TRIES) + { + if(!g_Config.m_EcBantime) + m_NetConsole.Drop(ClientID, "Too many authentication tries"); + else + m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, "Too many authentication tries"); + } + } + } + else if(m_aClients[ClientID].m_State == CClient::STATE_AUTHED) + { + char aFormatted[256]; + str_format(aFormatted, sizeof(aFormatted), "cid=%d cmd='%s'", ClientID, aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aFormatted); + m_UserClientID = ClientID; + Console()->ExecuteLine(aBuf); + m_UserClientID = -1; + } + } + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; ++i) + { + if(m_aClients[i].m_State == CClient::STATE_CONNECTED && + time_get() > m_aClients[i].m_TimeConnected + g_Config.m_EcAuthTimeout * time_freq()) + m_NetConsole.Drop(i, "authentication timeout"); + } +} + +void CEcon::Send(int ClientID, const char *pLine) +{ + if(!m_Ready) + return; + + if(ClientID == -1) + { + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aClients[i].m_State == CClient::STATE_AUTHED) + m_NetConsole.Send(i, pLine); + } + } + else if(ClientID >= 0 && ClientID < NET_MAX_CONSOLE_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_AUTHED) + m_NetConsole.Send(ClientID, pLine); +} + +void CEcon::Shutdown() +{ + if(!m_Ready) + return; + + m_NetConsole.Close(); +} diff --git a/src/engine/shared/econ.h b/src/engine/shared/econ.h new file mode 100644 index 0000000..3478c7e --- /dev/null +++ b/src/engine/shared/econ.h @@ -0,0 +1,53 @@ +#ifndef ENGINE_SHARED_ECON_H +#define ENGINE_SHARED_ECON_H + +#include "network.h" + + +class CEcon +{ + enum + { + MAX_AUTH_TRIES=3, + }; + + class CClient + { + public: + enum + { + STATE_EMPTY=0, + STATE_CONNECTED, + STATE_AUTHED, + }; + + int m_State; + int64 m_TimeConnected; + int m_AuthTries; + }; + CClient m_aClients[NET_MAX_CONSOLE_CLIENTS]; + + IConsole *m_pConsole; + CNetConsole m_NetConsole; + + bool m_Ready; + int m_PrintCBIndex; + int m_UserClientID; + + static void SendLineCB(const char *pLine, void *pUserData,bool Highlighted); + static void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConLogout(IConsole::IResult *pResult, void *pUserData); + + static int NewClientCallback(int ClientID, void *pUser); + static int DelClientCallback(int ClientID, const char *pReason, void *pUser); + +public: + IConsole *Console() { return m_pConsole; } + + void Init(IConsole *pConsole, class CNetBan *pNetBan); + void Update(); + void Send(int ClientID, const char *pLine); + void Shutdown(); +}; + +#endif diff --git a/src/engine/shared/engine.cpp b/src/engine/shared/engine.cpp new file mode 100644 index 0000000..5cc19c0 --- /dev/null +++ b/src/engine/shared/engine.cpp @@ -0,0 +1,116 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/system.h> + +#include <engine/console.h> +#include <engine/engine.h> +#include <engine/storage.h> +#include <engine/shared/config.h> +#include <engine/shared/network.h> + + +static int HostLookupThread(void *pUser) +{ + CHostLookup *pLookup = (CHostLookup *)pUser; + return net_host_lookup(pLookup->m_aHostname, &pLookup->m_Addr, pLookup->m_Nettype); +} + +class CEngine : public IEngine +{ +public: + IConsole *m_pConsole; + IStorage *m_pStorage; + bool m_Logging; + + static void Con_DbgDumpmem(IConsole::IResult *pResult, void *pUserData) + { + CEngine *pEngine = static_cast<CEngine *>(pUserData); + char aBuf[32]; + str_timestamp(aBuf, sizeof(aBuf)); + char aFilename[128]; + str_format(aFilename, sizeof(aFilename), "dumps/memory_%s.txt", aBuf); + mem_debug_dump(pEngine->m_pStorage->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE)); + } + + static void Con_DbgLognetwork(IConsole::IResult *pResult, void *pUserData) + { + CEngine *pEngine = static_cast<CEngine *>(pUserData); + + if(pEngine->m_Logging) + { + CNetBase::CloseLog(); + pEngine->m_Logging = false; + } + else + { + char aBuf[32]; + str_timestamp(aBuf, sizeof(aBuf)); + char aFilenameSent[128], aFilenameRecv[128]; + str_format(aFilenameSent, sizeof(aFilenameSent), "dumps/network_sent_%s.txt", aBuf); + str_format(aFilenameRecv, sizeof(aFilenameRecv), "dumps/network_recv_%s.txt", aBuf); + CNetBase::OpenLog(pEngine->m_pStorage->OpenFile(aFilenameSent, IOFLAG_WRITE, IStorage::TYPE_SAVE), + pEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE)); + pEngine->m_Logging = true; + } + } + + CEngine(const char *pAppname) + { + 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 + dbg_msg("engine", "arch is little endian"); + #elif defined(CONF_ARCH_ENDIAN_BIG) + dbg_msg("engine", "arch is big endian"); + #else + dbg_msg("engine", "unknown endian"); + #endif + + // init the network + net_init(); + CNetBase::Init(); + + m_JobPool.Init(1); + + m_Logging = false; + } + + void Init() + { + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + + if(!m_pConsole || !m_pStorage) + return; + + m_pConsole->Register("dbg_dumpmem", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgDumpmem, this, "Dump the memory"); + m_pConsole->Register("dbg_lognetwork", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgLognetwork, this, "Log the network"); + } + + void InitLogfile() + { + // open logfile if needed + if(g_Config.m_Logfile[0]) + dbg_logger_file(g_Config.m_Logfile); + } + + void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) + { + str_copy(pLookup->m_aHostname, pHostname, sizeof(pLookup->m_aHostname)); + pLookup->m_Nettype = Nettype; + AddJob(&pLookup->m_Job, HostLookupThread, pLookup); + } + + void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) + { + if(g_Config.m_Debug) + dbg_msg("engine", "job added"); + m_JobPool.Add(pJob, pfnFunc, pData); + } +}; + +IEngine *CreateEngine(const char *pAppname) { return new CEngine(pAppname); } diff --git a/src/engine/shared/fifoconsole.cpp b/src/engine/shared/fifoconsole.cpp new file mode 100644 index 0000000..7d3b5c7 --- /dev/null +++ b/src/engine/shared/fifoconsole.cpp @@ -0,0 +1,91 @@ +#include "fifoconsole.h" + +#if defined(CONF_FAMILY_UNIX) + +#include <engine/shared/config.h> + +#include <fstream> + +#include <pthread.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <stdlib.h> + +static LOCK gs_FifoLock = 0; +static volatile bool gs_stopFifoThread = false; + +FifoConsole::FifoConsole(IConsole *pConsole, char *pFifoFile, int flag) +{ + m_pFifoFile = pFifoFile; + if(m_pFifoFile[0] == '\0') + return; + + gs_stopFifoThread = false; + if(gs_FifoLock == 0) + gs_FifoLock = lock_create(); + + m_pFifoThread = thread_init(ListenFifoThread, this); + m_pConsole = pConsole; + m_flag = flag; + + thread_detach(m_pFifoThread); +} + +FifoConsole::~FifoConsole() +{ + if(m_pFifoFile[0] == '\0') + return; + + lock_wait(gs_FifoLock); + gs_stopFifoThread = true; + lock_unlock(gs_FifoLock); + gs_FifoLock = 0; +} + +void FifoConsole::ListenFifoThread(void *pUser) +{ + FifoConsole *pData = (FifoConsole *)pUser; + + if(!gs_FifoLock) + { + dbg_msg("fifo", "FIFO not properly initialized"); + exit(2); + } + + lock_wait(gs_FifoLock); + if(gs_stopFifoThread) + return; + + mkfifo(pData->m_pFifoFile, 0600); + + struct stat attribute; + stat(pData->m_pFifoFile, &attribute); + + if(!S_ISFIFO(attribute.st_mode)) + { + dbg_msg("fifo", "'%s' is not a FIFO, removing", pData->m_pFifoFile); + fs_remove(pData->m_pFifoFile); + mkfifo(pData->m_pFifoFile, 0600); + stat(pData->m_pFifoFile, &attribute); + + if(!S_ISFIFO(attribute.st_mode)) + { + dbg_msg("fifo", "Can't remove file, quitting"); + exit(2); + } + } + + lock_unlock(gs_FifoLock); + + std::ifstream f; + char aBuf[8192]; + + while (true) + { + f.open(pData->m_pFifoFile); + while (f.getline(aBuf, sizeof(aBuf))) + pData->m_pConsole->ExecuteLineFlag(aBuf, pData->m_flag, -1); + f.close(); + } +} +#endif diff --git a/src/engine/shared/fifoconsole.h b/src/engine/shared/fifoconsole.h new file mode 100644 index 0000000..83d14bc --- /dev/null +++ b/src/engine/shared/fifoconsole.h @@ -0,0 +1,22 @@ +#ifndef ENGINE_FIFOCONSOLE_H +#define ENGINE_FIFOCONSOLE_H + +#include <engine/console.h> + +#if defined(CONF_FAMILY_UNIX) + +class FifoConsole +{ + static void ListenFifoThread(void *pUser); + IConsole *m_pConsole; + void *m_pFifoThread; + char *m_pFifoFile; + int m_flag; + +public: + FifoConsole(IConsole *pConsole, char *pFifoFile, int flag); + ~FifoConsole(); +}; +#endif + +#endif // FILE_ENGINE_FIFOCONSOLE_H diff --git a/src/engine/shared/filecollection.cpp b/src/engine/shared/filecollection.cpp new file mode 100644 index 0000000..b1a774f --- /dev/null +++ b/src/engine/shared/filecollection.cpp @@ -0,0 +1,246 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/math.h> + +#include <engine/storage.h> + +#include "filecollection.h" + +bool CFileCollection::IsFilenameValid(const char *pFilename) +{ + if(m_aFileDesc[0] == '\0') + { + int FilenameLength = str_length(pFilename); + if(m_FileExtLength+TIMESTAMP_LENGTH > FilenameLength) + { + return false; + } + + pFilename += FilenameLength-m_FileExtLength-TIMESTAMP_LENGTH; + } + else + { + if(str_length(pFilename) != m_FileDescLength+TIMESTAMP_LENGTH+m_FileExtLength || + str_comp_num(pFilename, m_aFileDesc, m_FileDescLength) || + str_comp(pFilename+m_FileDescLength+TIMESTAMP_LENGTH, m_aFileExt)) + return false; + + pFilename += m_FileDescLength; + } + + if(pFilename[0] == '_' && + pFilename[1] >= '0' && pFilename[1] <= '9' && + pFilename[2] >= '0' && pFilename[2] <= '9' && + pFilename[3] >= '0' && pFilename[3] <= '9' && + pFilename[4] >= '0' && pFilename[4] <= '9' && + pFilename[5] == '-' && + pFilename[6] >= '0' && pFilename[6] <= '9' && + pFilename[7] >= '0' && pFilename[7] <= '9' && + pFilename[8] == '-' && + pFilename[9] >= '0' && pFilename[9] <= '9' && + pFilename[10] >= '0' && pFilename[10] <= '9' && + pFilename[11] == '_' && + pFilename[12] >= '0' && pFilename[12] <= '9' && + pFilename[13] >= '0' && pFilename[13] <= '9' && + pFilename[14] == '-' && + pFilename[15] >= '0' && pFilename[15] <= '9' && + pFilename[16] >= '0' && pFilename[16] <= '9' && + pFilename[17] == '-' && + pFilename[18] >= '0' && pFilename[18] <= '9' && + pFilename[19] >= '0' && pFilename[19] <= '9') + return true; + + return false; +} + +int64 CFileCollection::ExtractTimestamp(const char *pTimestring) +{ + int64 Timestamp = pTimestring[0]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[1]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[2]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[3]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[5]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[6]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[8]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[9]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[11]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[12]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[14]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[15]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[17]-'0'; Timestamp <<= 4; + Timestamp += pTimestring[18]-'0'; + + return Timestamp; +} + +void CFileCollection::BuildTimestring(int64 Timestamp, char *pTimestring) +{ + pTimestring[19] = 0; + pTimestring[18] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[17] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[16] = '-'; + pTimestring[15] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[14] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[13] = '-'; + pTimestring[12] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[11] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[10] = '_'; + pTimestring[9] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[8] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[7] = '-'; + pTimestring[6] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[5] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[4] = '-'; + pTimestring[3] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[2] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[1] = (Timestamp&0xF)+'0'; Timestamp >>= 4; + pTimestring[0] = (Timestamp&0xF)+'0'; +} + +void CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries) +{ + mem_zero(m_aTimestamps, sizeof(m_aTimestamps)); + m_NumTimestamps = 0; + m_Remove = -1; + m_MaxEntries = clamp(MaxEntries, 1, static_cast<int>(MAX_ENTRIES)); + str_copy(m_aFileDesc, pFileDesc, sizeof(m_aFileDesc)); + m_FileDescLength = str_length(m_aFileDesc); + str_copy(m_aFileExt, pFileExt, sizeof(m_aFileExt)); + m_FileExtLength = str_length(m_aFileExt); + str_copy(m_aPath, pPath, sizeof(m_aPath)); + m_pStorage = pStorage; + + m_pStorage->ListDirectory(IStorage::TYPE_SAVE, m_aPath, FilelistCallback, this); +} + +void CFileCollection::AddEntry(int64 Timestamp) +{ + if(m_NumTimestamps == 0) + { + // empty list + m_aTimestamps[m_NumTimestamps++] = Timestamp; + } + else + { + // remove old file + if(m_NumTimestamps >= m_MaxEntries) + { + if(m_aFileDesc[0] == '\0') // consider an empty file desc as a wild card + { + m_Remove = m_aTimestamps[0]; + m_pStorage->ListDirectory(IStorage::TYPE_SAVE, m_aPath, RemoveCallback, this); + } + else + { + char aBuf[512]; + char aTimestring[TIMESTAMP_LENGTH]; + BuildTimestring(m_aTimestamps[0], aTimestring); + + str_format(aBuf, sizeof(aBuf), "%s/%s_%s%s", m_aPath, m_aFileDesc, aTimestring, m_aFileExt); + m_pStorage->RemoveFile(aBuf, IStorage::TYPE_SAVE); + } + } + + // add entry to the sorted list + if(m_aTimestamps[0] > Timestamp) + { + // first entry + if(m_NumTimestamps < m_MaxEntries) + { + mem_move(m_aTimestamps+1, m_aTimestamps, m_NumTimestamps*sizeof(int64)); + m_aTimestamps[0] = Timestamp; + ++m_NumTimestamps; + } + } + else if(m_aTimestamps[m_NumTimestamps-1] <= Timestamp) + { + // last entry + if(m_NumTimestamps == m_MaxEntries) + { + mem_move(m_aTimestamps, m_aTimestamps+1, (m_NumTimestamps-1)*sizeof(int64)); + m_aTimestamps[m_NumTimestamps-1] = Timestamp; + } + else + m_aTimestamps[m_NumTimestamps++] = Timestamp; + } + else + { + // middle entry + int Left = 0, Right = m_NumTimestamps-1; + while(Right-Left > 1) + { + int Mid = (Left+Right)/2; + if(m_aTimestamps[Mid] > Timestamp) + Right = Mid; + else + Left = Mid; + } + + if(m_NumTimestamps == m_MaxEntries) + { + mem_move(m_aTimestamps, m_aTimestamps+1, (Right-1)*sizeof(int64)); + m_aTimestamps[Right-1] = Timestamp; + } + else + { + mem_move(m_aTimestamps+Right+1, m_aTimestamps+Right, (m_NumTimestamps-Right)*sizeof(int64)); + m_aTimestamps[Right] = Timestamp; + ++m_NumTimestamps; + } + } + } +} + +int64 CFileCollection::GetTimestamp(const char *pFilename) +{ + if(m_aFileDesc[0] == '\0') + { + int FilenameLength = str_length(pFilename); + return ExtractTimestamp(pFilename+FilenameLength-m_FileExtLength-TIMESTAMP_LENGTH); + } + else + { + return ExtractTimestamp(pFilename+m_FileDescLength+1); + } +} + +int CFileCollection::FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser) +{ + CFileCollection *pThis = static_cast<CFileCollection *>(pUser); + + // check for valid file name format + if(IsDir || !pThis->IsFilenameValid(pFilename)) + return 0; + + // extract the timestamp + int64 Timestamp = pThis->GetTimestamp(pFilename); + + // add the entry + pThis->AddEntry(Timestamp); + + return 0; +} + +int CFileCollection::RemoveCallback(const char *pFilename, int IsDir, int StorageType, void *pUser) +{ + CFileCollection *pThis = static_cast<CFileCollection *>(pUser); + + // check for valid file name format + if(IsDir || !pThis->IsFilenameValid(pFilename)) + return 0; + + // extract the timestamp + int64 Timestamp = pThis->GetTimestamp(pFilename); + + if(Timestamp == pThis->m_Remove) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s/%s", pThis->m_aPath, pFilename); + pThis->m_pStorage->RemoveFile(aBuf, IStorage::TYPE_SAVE); + pThis->m_Remove = -1; + return 1; + } + + return 0; +} diff --git a/src/engine/shared/filecollection.h b/src/engine/shared/filecollection.h new file mode 100644 index 0000000..3270206 --- /dev/null +++ b/src/engine/shared/filecollection.h @@ -0,0 +1,38 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_FILECOLLECTION_H +#define ENGINE_SHARED_FILECOLLECTION_H + +class CFileCollection +{ + enum + { + MAX_ENTRIES=1000, + TIMESTAMP_LENGTH=20, // _YYYY-MM-DD_HH-MM-SS + }; + + int64 m_aTimestamps[MAX_ENTRIES]; + int m_NumTimestamps; + int m_MaxEntries; + char m_aFileDesc[128]; + int m_FileDescLength; + char m_aFileExt[32]; + int m_FileExtLength; + char m_aPath[512]; + IStorage *m_pStorage; + int64 m_Remove; // Timestamp we want to remove + + bool IsFilenameValid(const char *pFilename); + int64 ExtractTimestamp(const char *pTimestring); + void BuildTimestring(int64 Timestamp, char *pTimestring); + int64 GetTimestamp(const char *pFilename); + +public: + void Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries); + void AddEntry(int64 Timestamp); + + static int FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser); + static int RemoveCallback(const char *pFilename, int IsDir, int StorageType, void *pUser); +}; + +#endif diff --git a/src/engine/shared/huffman.cpp b/src/engine/shared/huffman.cpp new file mode 100644 index 0000000..892a719 --- /dev/null +++ b/src/engine/shared/huffman.cpp @@ -0,0 +1,282 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "huffman.h" + +struct CHuffmanConstructNode +{ + unsigned short m_NodeId; + int m_Frequency; +}; + +void CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth) +{ + if(pNode->m_aLeafs[1] != 0xffff) + 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; + pNode->m_NumBits = Depth; + } +} + +// TODO: this should be something faster, but it's enough for now +static void BubbleSort(CHuffmanConstructNode **ppList, int Size) +{ + int Changed = 1; + CHuffmanConstructNode *pTemp; + + while(Changed) + { + Changed = 0; + for(int i = 0; i < Size-1; i++) + { + if(ppList[i]->m_Frequency < ppList[i+1]->m_Frequency) + { + pTemp = ppList[i]; + ppList[i] = ppList[i+1]; + ppList[i+1] = pTemp; + Changed = 1; + } + } + Size--; + } +} + +void CHuffman::ConstructTree(const unsigned *pFrequencies) +{ + CHuffmanConstructNode aNodesLeftStorage[HUFFMAN_MAX_SYMBOLS]; + CHuffmanConstructNode *apNodesLeft[HUFFMAN_MAX_SYMBOLS]; + int NumNodesLeft = HUFFMAN_MAX_SYMBOLS; + + // add the symbols + for(int i = 0; i < HUFFMAN_MAX_SYMBOLS; i++) + { + m_aNodes[i].m_NumBits = 0xFFFFFFFF; + m_aNodes[i].m_Symbol = i; + m_aNodes[i].m_aLeafs[0] = 0xffff; + m_aNodes[i].m_aLeafs[1] = 0xffff; + + if(i == HUFFMAN_EOF_SYMBOL) + aNodesLeftStorage[i].m_Frequency = 1; + else + aNodesLeftStorage[i].m_Frequency = pFrequencies[i]; + aNodesLeftStorage[i].m_NodeId = i; + 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; + apNodesLeft[NumNodesLeft-2]->m_NodeId = m_NumNodes; + apNodesLeft[NumNodesLeft-2]->m_Frequency = apNodesLeft[NumNodesLeft-1]->m_Frequency + apNodesLeft[NumNodesLeft-2]->m_Frequency; + + m_NumNodes++; + NumNodesLeft--; + } + + // set start node + m_pStartNode = &m_aNodes[m_NumNodes-1]; + + // build symbol bits + Setbits_r(m_pStartNode, 0, 0); +} + +void CHuffman::Init(const unsigned *pFrequencies) +{ + int i; + + // make sure to cleanout every thing + mem_zero(this, sizeof(*this)); + + // construct the tree + ConstructTree(pFrequencies); + + // build decode LUT + for(i = 0; i < HUFFMAN_LUTSIZE; i++) + { + unsigned Bits = i; + int k; + CNode *pNode = m_pStartNode; + for(k = 0; k < HUFFMAN_LUTBITS; k++) + { + pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + Bits >>= 1; + + if(!pNode) + break; + + if(pNode->m_NumBits) + { + m_apDecodeLut[i] = pNode; + break; + } + } + + if(k == HUFFMAN_LUTBITS) + m_apDecodeLut[i] = pNode; + } + +} + +//*************************************************************** +int CHuffman::Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize) +{ + // this macro loads a symbol for a byte into bits and bitcount +#define HUFFMAN_MACRO_LOADSYMBOL(Sym) \ + Bits |= m_aNodes[Sym].m_Bits << Bitcount; \ + Bitcount += m_aNodes[Sym].m_NumBits; + + // this macro writes the symbol stored in bits and bitcount to the dst pointer +#define HUFFMAN_MACRO_WRITE() \ + while(Bitcount >= 8) \ + { \ + *pDst++ = (unsigned char)(Bits&0xff); \ + if(pDst == pDstEnd) \ + return -1; \ + Bits >>= 8; \ + Bitcount -= 8; \ + } + + // setup buffer pointers + const unsigned char *pSrc = (const unsigned char *)pInput; + const unsigned char *pSrcEnd = pSrc + InputSize; + unsigned char *pDst = (unsigned char *)pOutput; + unsigned char *pDstEnd = pDst + OutputSize; + + // symbol variables + unsigned Bits = 0; + unsigned Bitcount = 0; + + // make sure that we have data that we want to compress + if(InputSize) + { + // {A} load the first symbol + int Symbol = *pSrc++; + + while(pSrc != pSrcEnd) + { + // {B} load the symbol + HUFFMAN_MACRO_LOADSYMBOL(Symbol) + + // {C} fetch next symbol, this is done here because it will reduce dependency in the code + Symbol = *pSrc++; + + // {B} write the symbol loaded at + HUFFMAN_MACRO_WRITE() + } + + // write the last symbol loaded from {C} or {A} in the case of only 1 byte input buffer + HUFFMAN_MACRO_LOADSYMBOL(Symbol) + HUFFMAN_MACRO_WRITE() + } + + // write EOF symbol + HUFFMAN_MACRO_LOADSYMBOL(HUFFMAN_EOF_SYMBOL) + HUFFMAN_MACRO_WRITE() + + // write out the last bits + *pDst++ = Bits; + + // return the size of the output + return (int)(pDst - (const unsigned char *)pOutput); + + // remove macros +#undef HUFFMAN_MACRO_LOADSYMBOL +#undef HUFFMAN_MACRO_WRITE +} + +//*************************************************************** +int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize) +{ + // setup buffer pointers + unsigned char *pDst = (unsigned char *)pOutput; + unsigned char *pSrc = (unsigned char *)pInput; + unsigned char *pDstEnd = pDst + OutputSize; + unsigned char *pSrcEnd = pSrc + InputSize; + + unsigned Bits = 0; + unsigned Bitcount = 0; + + CNode *pEof = &m_aNodes[HUFFMAN_EOF_SYMBOL]; + CNode *pNode = 0; + + while(1) + { + // {A} try to load a node now, this will reduce dependency at location {D} + pNode = 0; + if(Bitcount >= HUFFMAN_LUTBITS) + pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; + + // {B} fill with new bits + while(Bitcount < 24 && pSrc != pSrcEnd) + { + Bits |= (*pSrc++) << Bitcount; + Bitcount += 8; + } + + // {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; + + // {D} check if we hit a symbol already + if(pNode->m_NumBits) + { + // remove the bits for that symbol + Bits >>= pNode->m_NumBits; + Bitcount -= pNode->m_NumBits; + } + else + { + // remove the bits that the lut checked up for us + Bits >>= HUFFMAN_LUTBITS; + Bitcount -= HUFFMAN_LUTBITS; + + // walk the tree bit by bit + while(1) + { + // traverse tree + pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; + + // remove bit + Bitcount--; + Bits >>= 1; + + // check if we hit a symbol + if(pNode->m_NumBits) + break; + + // no more bits, decoding error + if(Bitcount == 0) + return -1; + } + } + + // check for eof + if(pNode == pEof) + break; + + // output character + if(pDst == pDstEnd) + return -1; + *pDst++ = pNode->m_Symbol; + } + + // return the size of the decompressed buffer + return (int)(pDst - (const unsigned char *)pOutput); +} diff --git a/src/engine/shared/huffman.h b/src/engine/shared/huffman.h new file mode 100644 index 0000000..0d15ed9 --- /dev/null +++ b/src/engine/shared/huffman.h @@ -0,0 +1,91 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_HUFFMAN_H +#define ENGINE_SHARED_HUFFMAN_H + + + +class CHuffman +{ + enum + { + HUFFMAN_EOF_SYMBOL = 256, + + 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) + }; + + struct CNode + { + // symbol + unsigned m_Bits; + unsigned m_NumBits; + + // don't use pointers for this. shorts are smaller so we can fit more data into the cache + unsigned short m_aLeafs[2]; + + // what the symbol represents + unsigned char m_Symbol; + }; + + CNode m_aNodes[HUFFMAN_MAX_NODES]; + 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 + Inits the compressor/decompressor. + + Parameters: + huff - Pointer to the state to init + frequencies - A pointer to an array of 256 entries of the frequencies of the bytes + + Remarks: + - Does no allocation what so ever. + - You don't have to call any cleanup functions when you are done with it + */ + void Init(const unsigned *pFrequencies); + + /* + Function: huffman_compress + Compresses a buffer and outputs a compressed buffer. + + Parameters: + huff - Pointer to the huffman state + input - Buffer to compress + input_size - Size of the buffer to compress + output - Buffer to put the compressed data into + output_size - Size of the output buffer + + Returns: + Returns the size of the compressed data. Negative value on failure. + */ + int Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize); + + /* + Function: huffman_decompress + Decompresses a buffer + + Parameters: + huff - Pointer to the huffman state + input - Buffer to decompress + input_size - Size of the buffer to decompress + output - Buffer to put the uncompressed data into + output_size - Size of the output buffer + + Returns: + 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 new file mode 100644 index 0000000..cc36c16 --- /dev/null +++ b/src/engine/shared/jobs.cpp @@ -0,0 +1,74 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "jobs.h" + +CJobPool::CJobPool() +{ + // empty the pool + m_Lock = lock_create(); + m_pFirstJob = 0; + m_pLastJob = 0; +} + +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) + { + pJob = pPool->m_pFirstJob; + pPool->m_pFirstJob = pPool->m_pFirstJob->m_pNext; + if(pPool->m_pFirstJob) + pPool->m_pFirstJob->m_pPrev = 0; + else + pPool->m_pLastJob = 0; + } + lock_unlock(pPool->m_Lock); + + // do the job if we have one + if(pJob) + { + pJob->m_Status = CJob::STATE_RUNNING; + pJob->m_Result = pJob->m_pfnFunc(pJob->m_pFuncData); + pJob->m_Status = CJob::STATE_DONE; + } + else + thread_sleep(10); + } + +} + +int CJobPool::Init(int NumThreads) +{ + // start threads + for(int i = 0; i < NumThreads; i++) + thread_init(WorkerThread, this); + return 0; +} + +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) + m_pLastJob->m_pNext = pJob; + m_pLastJob = pJob; + if(!m_pFirstJob) + m_pFirstJob = pJob; + + lock_unlock(m_Lock); + return 0; +} diff --git a/src/engine/shared/jobs.h b/src/engine/shared/jobs.h new file mode 100644 index 0000000..b8af973 --- /dev/null +++ b/src/engine/shared/jobs.h @@ -0,0 +1,53 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_JOBS_H +#define ENGINE_SHARED_JOBS_H +typedef int (*JOBFUNC)(void *pData); + +class CJobPool; + +class CJob +{ + friend class CJobPool; + + CJob *m_pPrev; + CJob *m_pNext; + + volatile int m_Status; + volatile int m_Result; + + JOBFUNC m_pfnFunc; + void *m_pFuncData; +public: + CJob() + { + 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; } +}; + +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); +}; +#endif diff --git a/src/engine/shared/kernel.cpp b/src/engine/shared/kernel.cpp new file mode 100644 index 0000000..b422b59 --- /dev/null +++ b/src/engine/shared/kernel.cpp @@ -0,0 +1,101 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <engine/kernel.h> + +class CKernel : public IKernel +{ + enum + { + MAX_INTERFACES=32, + }; + + class CInterfaceInfo + { + public: + CInterfaceInfo() + { + 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++) + { + if(str_comp(pName, m_aInterfaces[i].m_aName) == 0) + return &m_aInterfaces[i]; + } + return 0x0; + } + +public: + + CKernel() + { + m_NumInterfaces = 0; + } + + + virtual bool RegisterInterfaceImpl(const char *pName, IInterface *pInterface) + { + // TODO: More error checks here + if(!pInterface) + { + dbg_msg("kernel", "ERROR: couldn't register interface %s. null pointer given", pName); + return false; + } + + if(m_NumInterfaces == MAX_INTERFACES) + { + 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; + } + + virtual bool ReregisterInterfaceImpl(const char *pName, IInterface *pInterface) + { + if(FindInterfaceInfo(pName) == 0) + { + 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); + if(!pInfo) + { + dbg_msg("kernel", "failed to find interface with the name '%s'", pName); + return 0; + } + return pInfo->m_pInterface; + } +}; + +IKernel *IKernel::Create() { return new CKernel; } diff --git a/src/engine/shared/linereader.cpp b/src/engine/shared/linereader.cpp new file mode 100644 index 0000000..b705ff0 --- /dev/null +++ b/src/engine/shared/linereader.cpp @@ -0,0 +1,82 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "linereader.h" + +void CLineReader::Init(IOHANDLE io) +{ + m_BufferMaxSize = sizeof(m_aBuffer); + m_BufferSize = 0; + m_BufferPos = 0; + m_IO = io; +} + +char *CLineReader::Get() +{ + unsigned LineStart = m_BufferPos; + bool CRLFBreak = false; + + while(1) + { + if(m_BufferPos >= m_BufferSize) + { + // fetch more + + // move the remaining part to the front + unsigned Read; + unsigned Left = m_BufferSize - LineStart; + + if(LineStart > m_BufferSize) + Left = 0; + if(Left) + mem_move(m_aBuffer, &m_aBuffer[LineStart], Left); + m_BufferPos = Left; + + // fill the buffer + Read = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize-m_BufferPos); + m_BufferSize = Left + Read; + LineStart = 0; + + if(!Read) + { + if(Left) + { + m_aBuffer[Left] = 0; // return the last line + m_BufferPos = Left; + m_BufferSize = Left; + return m_aBuffer; + } + else + return 0x0; // we are done! + } + } + else + { + if(m_aBuffer[m_BufferPos] == '\n' || m_aBuffer[m_BufferPos] == '\r') + { + // line found + if(m_aBuffer[m_BufferPos] == '\r') + { + if(m_BufferPos+1 >= m_BufferSize) + { + // read more to get the connected '\n' + CRLFBreak = true; + ++m_BufferPos; + continue; + } + else if(m_aBuffer[m_BufferPos+1] == '\n') + m_aBuffer[m_BufferPos++] = 0; + } + m_aBuffer[m_BufferPos++] = 0; + return &m_aBuffer[LineStart]; + } + else if(CRLFBreak) + { + if(m_aBuffer[m_BufferPos] == '\n') + m_aBuffer[m_BufferPos++] = 0; + return &m_aBuffer[LineStart]; + } + else + m_BufferPos++; + } + } +} diff --git a/src/engine/shared/linereader.h b/src/engine/shared/linereader.h new file mode 100644 index 0000000..f75615f --- /dev/null +++ b/src/engine/shared/linereader.h @@ -0,0 +1,19 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_LINEREADER_H +#define ENGINE_SHARED_LINEREADER_H +#include <base/system.h> + +// buffered stream for reading lines, should perhaps be something smaller +class CLineReader +{ + char m_aBuffer[4*8192]; + unsigned m_BufferPos; + unsigned m_BufferSize; + unsigned m_BufferMaxSize; + IOHANDLE m_IO; +public: + void Init(IOHANDLE IoHandle); + char *Get(); +}; +#endif diff --git a/src/engine/shared/map.cpp b/src/engine/shared/map.cpp new file mode 100644 index 0000000..923dc83 --- /dev/null +++ b/src/engine/shared/map.cpp @@ -0,0 +1,48 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <engine/map.h> +#include <engine/storage.h> +#include "datafile.h" + +class CMap : public IEngineMap +{ + CDataFileReader m_DataFile; +public: + CMap() {} + + virtual void *GetData(int Index) { return m_DataFile.GetData(Index); } + virtual int GetUncompressedDataSize(int Index) { return m_DataFile.GetUncompressedDataSize(Index); } + virtual void *GetDataSwapped(int Index) { return m_DataFile.GetDataSwapped(Index); } + virtual void UnloadData(int Index) { m_DataFile.UnloadData(Index); } + virtual void *GetItem(int Index, int *pType, int *pID) { return m_DataFile.GetItem(Index, pType, pID); } + virtual int GetItemSize(int Index) { return m_DataFile.GetItemSize(Index); } + 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(); + } + + virtual bool Load(const char *pMapName) + { + IStorage *pStorage = Kernel()->RequestInterface<IStorage>(); + if(!pStorage) + 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(); + } +}; + +extern IEngineMap *CreateEngineMap() { return new CMap; } diff --git a/src/engine/shared/mapchecker.cpp b/src/engine/shared/mapchecker.cpp new file mode 100644 index 0000000..5a7d062 --- /dev/null +++ b/src/engine/shared/mapchecker.cpp @@ -0,0 +1,107 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/storage.h> + +#include <versionsrv/versionsrv.h> +#include <versionsrv/mapversions.h> + +#include "datafile.h" +#include "memheap.h" +#include "mapchecker.h" + +CMapChecker::CMapChecker() +{ + Init(); + SetDefaults(); +} + +void CMapChecker::Init() +{ + m_Whitelist.Reset(); + m_pFirst = 0; + m_RemoveDefaultList = false; +} + +void CMapChecker::SetDefaults() +{ + AddMaplist(s_aMapVersionList, s_NumMapVersionItems); + m_RemoveDefaultList = true; +} + +void CMapChecker::AddMaplist(CMapVersion *pMaplist, int Num) +{ + if(m_RemoveDefaultList) + Init(); + + for(int i = 0; i < Num; ++i) + { + CWhitelistEntry *pEntry = (CWhitelistEntry *)m_Whitelist.Allocate(sizeof(CWhitelistEntry)); + pEntry->m_pNext = m_pFirst; + 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_MapSize = (pMaplist[i].m_aSize[0]<<24) | (pMaplist[i].m_aSize[1]<<16) | (pMaplist[i].m_aSize[2]<<8) | pMaplist[i].m_aSize[3]; + } +} + +bool CMapChecker::IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize) +{ + bool StandardMap = false; + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + { + if(str_comp(pCurrent->m_aMapName, pMapName) == 0) + { + StandardMap = true; + if(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize) + return true; + } + } + return StandardMap?false:true; +} + +bool CMapChecker::ReadAndValidateMap(IStorage *pStorage, const char *pFilename, int StorageType) +{ + bool LoadedMapInfo = false; + bool StandardMap = false; + unsigned MapCrc = 0; + unsigned MapSize = 0; + + // extract map name + char aMapName[MAX_MAP_LENGTH]; + const char *pExtractedName = pFilename; + const char *pEnd = 0; + for(const char *pSrc = pFilename; *pSrc; ++pSrc) + { + if(*pSrc == '/' || *pSrc == '\\') + pExtractedName = pSrc+1; + else if(*pSrc == '.') + pEnd = pSrc; + } + int Length = (int)(pEnd - pExtractedName); + if(Length <= 0 || Length >= MAX_MAP_LENGTH) + return true; + str_copy(aMapName, pExtractedName, min((int)MAX_MAP_LENGTH, (int)(pEnd-pExtractedName+1))); + + // check for valid map + for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) + { + if(str_comp(pCurrent->m_aMapName, aMapName) == 0) + { + StandardMap = true; + if(!LoadedMapInfo) + { + if(!CDataFileReader::GetCrcSize(pStorage, pFilename, StorageType, &MapCrc, &MapSize)) + return true; + LoadedMapInfo = true; + } + + if(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize) + return true; + } + } + return StandardMap?false:true; +} diff --git a/src/engine/shared/mapchecker.h b/src/engine/shared/mapchecker.h new file mode 100644 index 0000000..8f6d24e --- /dev/null +++ b/src/engine/shared/mapchecker.h @@ -0,0 +1,38 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_MAPCHECKER_H +#define ENGINE_SHARED_MAPCHECKER_H + +#include "memheap.h" + +class CMapChecker +{ + enum + { + MAX_MAP_LENGTH=8, + }; + + struct CWhitelistEntry + { + char m_aMapName[MAX_MAP_LENGTH]; + unsigned m_MapCrc; + unsigned m_MapSize; + CWhitelistEntry *m_pNext; + }; + + class CHeap m_Whitelist; + CWhitelistEntry *m_pFirst; + + bool m_RemoveDefaultList; + + void Init(); + void SetDefaults(); + +public: + CMapChecker(); + void AddMaplist(struct CMapVersion *pMaplist, int Num); + bool IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize); + bool ReadAndValidateMap(class IStorage *pStorage, const char *pFilename, int StorageType); +}; + +#endif diff --git a/src/engine/shared/masterserver.cpp b/src/engine/shared/masterserver.cpp new file mode 100644 index 0000000..1968da3 --- /dev/null +++ b/src/engine/shared/masterserver.cpp @@ -0,0 +1,228 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <stdio.h> // sscanf + +#include <base/system.h> + +#include <engine/engine.h> +#include <engine/masterserver.h> +#include <engine/storage.h> + +#include "linereader.h" + +class CMasterServer : public IEngineMasterServer +{ +public: + // master server functions + struct CMasterInfo + { + char m_aHostname[128]; + NETADDR m_Addr; + bool m_Valid; + int m_Count; + CHostLookup m_Lookup; + }; + + enum + { + STATE_INIT, + STATE_UPDATE, + STATE_READY, + }; + + CMasterInfo m_aMasterServers[MAX_MASTERSERVERS]; + int m_State; + IEngine *m_pEngine; + IStorage *m_pStorage; + + CMasterServer() + { + SetDefault(); + m_State = STATE_INIT; + m_pEngine = 0; + m_pStorage = 0; + } + + virtual int RefreshAddresses(int Nettype) + { + if(m_State != STATE_INIT && m_State != STATE_READY) + return -1; + + dbg_msg("engine/mastersrv", "refreshing master server addresses"); + + // add lookup jobs + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + m_pEngine->HostLookup(&m_aMasterServers[i].m_Lookup, m_aMasterServers[i].m_aHostname, Nettype); + m_aMasterServers[i].m_Valid = false; + m_aMasterServers[i].m_Count = 0; + + //dbg_msg("MasterServer", "Lookup id: %d, name: %s, nettype: %d", i, m_aMasterServers[i].m_aHostname, Nettype); + } + + m_State = STATE_UPDATE; + return 0; + } + + virtual void Update() + { + // check if we need to update + if(m_State != STATE_UPDATE) + return; + m_State = STATE_READY; + + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + if(m_aMasterServers[i].m_Lookup.m_Job.Status() != CJob::STATE_DONE) + m_State = STATE_UPDATE; + else + { + if(m_aMasterServers[i].m_Lookup.m_Job.Result() == 0) + { + m_aMasterServers[i].m_Addr = m_aMasterServers[i].m_Lookup.m_Addr; + m_aMasterServers[i].m_Addr.port = 8300; + m_aMasterServers[i].m_Valid = true; + + //dbg_msg("MasterServer", "Set server %d, name: %s with addr-port: %d addr-ip %s addr-type %d", i, m_aMasterServers[i].m_aHostname, m_aMasterServers[i].m_Addr.port, m_aMasterServers[i].m_Addr.ip, m_aMasterServers[i].m_Addr.type); + } + else + { + m_aMasterServers[i].m_Valid = false; + + // dbg_msg("MasterServer", "Dropped %d, name: %s with addr-port: %d addr-ip %s addr-type %d", i, m_aMasterServers[i].m_aHostname); + } + } + } + + if(m_State == STATE_READY) + { + dbg_msg("engine/mastersrv", "saving addresses"); + Save(); + } + } + + virtual int IsRefreshing() + { + return m_State != STATE_READY; + } + + virtual NETADDR GetAddr(int Index) + { + return m_aMasterServers[Index].m_Addr; + } + + virtual void SetCount(int Index, int Count) + { + m_aMasterServers[Index].m_Count = Count; + } + + virtual int GetCount(int Index) + { + return m_aMasterServers[Index].m_Count; + } + + virtual const char *GetName(int Index) + { + return m_aMasterServers[Index].m_aHostname; + } + + virtual bool IsValid(int Index) + { + return m_aMasterServers[Index].m_Valid; + } + + virtual void Init() + { + m_pEngine = Kernel()->RequestInterface<IEngine>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + } + + virtual void SetDefault() + { + mem_zero(m_aMasterServers, sizeof(m_aMasterServers)); + for(int i = 0; i < MAX_MASTERSERVERS; i++) + str_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), "master%d.teeworlds.com", i+1); + } + + virtual int Load() + { + if(!m_pStorage) + return -1; + + // try to open file + IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_READ, IStorage::TYPE_SAVE); + if(!File) + return -1; + + CLineReader LineReader; + LineReader.Init(File); + while(1) + { + CMasterInfo Info = {{0}}; + const char *pLine = LineReader.Get(); + if(!pLine) + break; + + // parse line + char aAddrStr[NETADDR_MAXSTRSIZE]; + if(sscanf(pLine, "%127s %47s", Info.m_aHostname, aAddrStr) == 2 && net_addr_from_str(&Info.m_Addr, aAddrStr) == 0) + { + Info.m_Addr.port = 8300; + bool Added = false; + for(int i = 0; i < MAX_MASTERSERVERS; ++i) + if(str_comp(m_aMasterServers[i].m_aHostname, Info.m_aHostname) == 0) + { + m_aMasterServers[i] = Info; + Added = true; + break; + } + + if(!Added) + { + for(int i = 0; i < MAX_MASTERSERVERS; ++i) + if(m_aMasterServers[i].m_Addr.type == NETTYPE_INVALID) + { + m_aMasterServers[i] = Info; + Added = true; + break; + } + } + + if(!Added) + break; + } + } + + io_close(File); + return 0; + } + + virtual int Save() + { + if(!m_pStorage) + return -1; + + // try to open file + IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!File) + return -1; + + for(int i = 0; i < MAX_MASTERSERVERS; i++) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + if(m_aMasterServers[i].m_Addr.type != NETTYPE_INVALID) + net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr), true); + else + aAddrStr[0] = 0; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s %s", m_aMasterServers[i].m_aHostname, aAddrStr); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + + io_close(File); + return 0; + } +}; + +IEngineMasterServer *CreateEngineMasterServer() { return new CMasterServer; } diff --git a/src/engine/shared/memheap.cpp b/src/engine/shared/memheap.cpp new file mode 100644 index 0000000..dd55984 --- /dev/null +++ b/src/engine/shared/memheap.cpp @@ -0,0 +1,95 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "memheap.h" + +// allocates a new chunk to be used +void CHeap::NewChunk() +{ + CChunk *pChunk; + char *pMem; + + // allocate memory + pMem = (char*)mem_alloc(sizeof(CChunk)+CHUNK_SIZE, 1); + if(!pMem) + return; + + // the chunk structure is located in the begining of the chunk + // init it and return the chunk + pChunk = (CChunk*)pMem; + pChunk->m_pMemory = (char*)(pChunk+1); + pChunk->m_pCurrent = pChunk->m_pMemory; + pChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE; + pChunk->m_pNext = (CChunk *)0x0; + + pChunk->m_pNext = m_pCurrent; + 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; + + // get memory and move the pointer forward + pMem = m_pCurrent->m_pCurrent; + m_pCurrent->m_pCurrent += Size; + return pMem; +} + +// creates a heap +CHeap::CHeap() +{ + m_pCurrent = 0x0; + Reset(); +} + +CHeap::~CHeap() +{ + Clear(); +} + +void CHeap::Reset() +{ + Clear(); + NewChunk(); +} + +// destroys the heap +void CHeap::Clear() +{ + CChunk *pChunk = m_pCurrent; + CChunk *pNext; + + while(pChunk) + { + pNext = pChunk->m_pNext; + mem_free(pChunk); + pChunk = pNext; + } + + m_pCurrent = 0x0; +} + +// +void *CHeap::Allocate(unsigned Size) +{ + char *pMem; + + // try to allocate from current chunk + pMem = (char *)AllocateFromChunk(Size); + if(!pMem) + { + // 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 new file mode 100644 index 0000000..39adf2b --- /dev/null +++ b/src/engine/shared/memheap.h @@ -0,0 +1,34 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_MEMHEAP_H +#define ENGINE_SHARED_MEMHEAP_H +class CHeap +{ + struct CChunk + { + char *m_pMemory; + char *m_pCurrent; + 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(); + void Reset(); + void *Allocate(unsigned Size); +}; +#endif diff --git a/src/engine/shared/message.h b/src/engine/shared/message.h new file mode 100644 index 0000000..8d9d860 --- /dev/null +++ b/src/engine/shared/message.h @@ -0,0 +1,11 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_MESSAGE_H +#define ENGINE_SHARED_MESSAGE_H +class CMessage +{ +public: + virtual bool Pack(void *pData, unsigned MaxDataSize); + virtual bool Unpack(const void *pData, unsigned DataSize); +}; +#endif diff --git a/src/engine/shared/netban.cpp b/src/engine/shared/netban.cpp new file mode 100644 index 0000000..663cf7b --- /dev/null +++ b/src/engine/shared/netban.cpp @@ -0,0 +1,573 @@ +#include <base/math.h> + +#include <engine/console.h> +#include <engine/storage.h> +#include <engine/shared/config.h> + +#include "netban.h" + + +bool CNetBan::StrAllnum(const char *pStr) +{ + while(*pStr) + { + if(!(*pStr >= '0' && *pStr <= '9')) + return false; + pStr++; + } + return true; +} + + +CNetBan::CNetHash::CNetHash(const NETADDR *pAddr) +{ + if(pAddr->type==NETTYPE_IPV4) + m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF; + else + m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+ + pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF; + m_HashIndex = 0; +} + +CNetBan::CNetHash::CNetHash(const CNetRange *pRange) +{ + m_Hash = 0; + m_HashIndex = 0; + for(int i = 0; pRange->m_LB.ip[i] == pRange->m_UB.ip[i]; ++i) + { + m_Hash += pRange->m_LB.ip[i]; + ++m_HashIndex; + } + m_Hash &= 0xFF; +} + +int CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]) +{ + int Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16; + aHash[0].m_Hash = 0; + aHash[0].m_HashIndex = 0; + for(int i = 1, Sum = 0; i <= Length; ++i) + { + Sum += pAddr->ip[i-1]; + aHash[i].m_Hash = Sum&0xFF; + aHash[i].m_HashIndex = i%Length; + } + return Length; +} + + +template<class T, int HashCount> +typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Add(const T *pData, const CBanInfo *pInfo, const CNetHash *pNetHash) +{ + if(!m_pFirstFree) + return 0; + + // create new ban + CBan<T> *pBan = m_pFirstFree; + pBan->m_Data = *pData; + pBan->m_Info = *pInfo; + pBan->m_NetHash = *pNetHash; + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstFree = pBan->m_pNext; + + // add it to the hash list + if(m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]) + m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]->m_pHashPrev = pBan; + pBan->m_pHashPrev = 0; + pBan->m_pHashNext = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; + m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash] = pBan; + + // insert it into the used list + if(m_pFirstUsed) + { + for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext) + { + if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) + { + // insert before + pBan->m_pNext = p; + pBan->m_pPrev = p->m_pPrev; + if(p->m_pPrev) + p->m_pPrev->m_pNext = pBan; + else + m_pFirstUsed = pBan; + p->m_pPrev = pBan; + break; + } + + if(!p->m_pNext) + { + // last entry + p->m_pNext = pBan; + pBan->m_pPrev = p; + pBan->m_pNext = 0; + break; + } + } + } + else + { + m_pFirstUsed = pBan; + pBan->m_pNext = pBan->m_pPrev = 0; + } + + // update ban count + ++m_CountUsed; + + return pBan; +} + +template<class T, int HashCount> +int CNetBan::CBanPool<T, HashCount>::Remove(CBan<T> *pBan) +{ + if(pBan == 0) + return -1; + + // remove from hash list + if(pBan->m_pHashNext) + pBan->m_pHashNext->m_pHashPrev = pBan->m_pHashPrev; + if(pBan->m_pHashPrev) + pBan->m_pHashPrev->m_pHashNext = pBan->m_pHashNext; + else + m_paaHashList[pBan->m_NetHash.m_HashIndex][pBan->m_NetHash.m_Hash] = pBan->m_pHashNext; + pBan->m_pHashNext = pBan->m_pHashPrev = 0; + + // remove from used list + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstUsed = pBan->m_pNext; + + // add to recycle list + if(m_pFirstFree) + m_pFirstFree->m_pPrev = pBan; + pBan->m_pPrev = 0; + pBan->m_pNext = m_pFirstFree; + m_pFirstFree = pBan; + + // update ban count + --m_CountUsed; + + return 0; +} + +template<class T, int HashCount> +void CNetBan::CBanPool<T, HashCount>::Update(CBan<CDataType> *pBan, const CBanInfo *pInfo) +{ + pBan->m_Info = *pInfo; + + // remove from used list + if(pBan->m_pNext) + pBan->m_pNext->m_pPrev = pBan->m_pPrev; + if(pBan->m_pPrev) + pBan->m_pPrev->m_pNext = pBan->m_pNext; + else + m_pFirstUsed = pBan->m_pNext; + + // insert it into the used list + if(m_pFirstUsed) + { + for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext) + { + if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) + { + // insert before + pBan->m_pNext = p; + pBan->m_pPrev = p->m_pPrev; + if(p->m_pPrev) + p->m_pPrev->m_pNext = pBan; + else + m_pFirstUsed = pBan; + p->m_pPrev = pBan; + break; + } + + if(!p->m_pNext) + { + // last entry + p->m_pNext = pBan; + pBan->m_pPrev = p; + pBan->m_pNext = 0; + break; + } + } + } + else + { + m_pFirstUsed = pBan; + pBan->m_pNext = pBan->m_pPrev = 0; + } +} + +void CNetBan::UnbanAll() +{ + m_BanAddrPool.Reset(); + m_BanRangePool.Reset(); +} + +template<class T, int HashCount> +void CNetBan::CBanPool<T, HashCount>::Reset() +{ + mem_zero(m_paaHashList, sizeof(m_paaHashList)); + mem_zero(m_aBans, sizeof(m_aBans)); + m_pFirstUsed = 0; + m_CountUsed = 0; + + for(int i = 1; i < MAX_BANS-1; ++i) + { + m_aBans[i].m_pNext = &m_aBans[i+1]; + m_aBans[i].m_pPrev = &m_aBans[i-1]; + } + + m_aBans[0].m_pNext = &m_aBans[1]; + m_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2]; + m_pFirstFree = &m_aBans[0]; +} + +template<class T, int HashCount> +typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Get(int Index) const +{ + if(Index < 0 || Index >= Num()) + return 0; + + for(CNetBan::CBan<T> *pBan = m_pFirstUsed; pBan; pBan = pBan->m_pNext, --Index) + { + if(Index == 0) + return pBan; + } + + return 0; +} + + +template<class T> +int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) +{ + // do not ban localhost + if(NetMatch(pData, &m_LocalhostIPV4) || NetMatch(pData, &m_LocalhostIPV6)) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (localhost)"); + return -1; + } + + int Stamp = Seconds > 0 ? time_timestamp()+Seconds : CBanInfo::EXPIRES_NEVER; + + // set up info + CBanInfo Info = {0}; + Info.m_Expires = Stamp; + str_copy(Info.m_aReason, pReason, sizeof(Info.m_aReason)); + + // check if it already exists + CNetHash NetHash(pData); + CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash); + if(pBan) + { + // adjust the ban + pBanPool->Update(pBan, &Info); + char aBuf[128]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 1; + } + + // add ban and print result + pBan = pBanPool->Add(pData, &Info, &NetHash); + if(pBan) + { + char aBuf[128]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANADD); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 0; + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (full banlist)"); + return -1; +} + +template<class T> +int CNetBan::Unban(T *pBanPool, const typename T::CDataType *pData) +{ + CNetHash NetHash(pData); + CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash); + if(pBan) + { + char aBuf[256]; + MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANREM); + pBanPool->Remove(pBan); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return 0; + } + else + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid entry)"); + return -1; +} + +void CNetBan::Init(IConsole *pConsole, IStorage *pStorage) +{ + m_pConsole = pConsole; + m_pStorage = pStorage; + m_BanAddrPool.Reset(); + m_BanRangePool.Reset(); + + net_host_lookup("localhost", &m_LocalhostIPV4, NETTYPE_IPV4); + net_host_lookup("localhost", &m_LocalhostIPV6, NETTYPE_IPV6); + + Console()->Register("ban", "s[ip|id] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, "Ban ip for x minutes for any reason"); + Console()->Register("ban_range", "s[first ip] s[last ip] ?i[minutes] r[reason]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBanRange, this, "Ban ip range for x minutes for any reason"); + Console()->Register("unban", "s[ip|entry]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, "Unban ip/banlist entry"); + Console()->Register("unban_range", "s[first ip] s[last ip]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanRange, this, "Unban ip range"); + Console()->Register("unban_all", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries"); + Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, "Show banlist"); + Console()->Register("bans_save", "s[file]", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file"); +} + +void CNetBan::Update() +{ + int Now = time_timestamp(); + + // remove expired bans + char aBuf[256], aNetStr[256]; + while(m_BanAddrPool.First() && m_BanAddrPool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanAddrPool.First()->m_Info.m_Expires < Now) + { + str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanAddrPool.First()->m_Data, aNetStr, sizeof(aNetStr))); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + m_BanAddrPool.Remove(m_BanAddrPool.First()); + } + while(m_BanRangePool.First() && m_BanRangePool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanRangePool.First()->m_Info.m_Expires < Now) + { + str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanRangePool.First()->m_Data, aNetStr, sizeof(aNetStr))); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + m_BanRangePool.Remove(m_BanRangePool.First()); + } +} + +int CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) +{ + return Ban(&m_BanAddrPool, pAddr, Seconds, pReason); +} + +int CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) +{ + if(pRange->IsValid()) + return Ban(&m_BanRangePool, pRange, Seconds, pReason); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +int CNetBan::UnbanByAddr(const NETADDR *pAddr) +{ + return Unban(&m_BanAddrPool, pAddr); +} + +int CNetBan::UnbanByRange(const CNetRange *pRange) +{ + if(pRange->IsValid()) + return Unban(&m_BanRangePool, pRange); + + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); + return -1; +} + +int CNetBan::UnbanByIndex(int Index) +{ + int Result; + char aBuf[256]; + CBanAddr *pBan = m_BanAddrPool.Get(Index); + if(pBan) + { + NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); + Result = m_BanAddrPool.Remove(pBan); + } + else + { + CBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num()); + if(pBan) + { + NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); + Result = m_BanRangePool.Remove(pBan); + } + else + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid index)"); + return -1; + } + } + + char aMsg[256]; + str_format(aMsg, sizeof(aMsg), "unbanned index %i (%s)", Index, aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + return Result; +} + +bool CNetBan::IsBanned(const NETADDR *pOrigAddr, char *pBuf, unsigned BufferSize) const +{ + NETADDR addr; + const NETADDR *pAddr = pOrigAddr; + if (pOrigAddr->type == NETTYPE_WEBSOCKET_IPV4) { + mem_copy(&addr, pOrigAddr, sizeof(NETADDR)); + pAddr = &addr; + addr.type = NETTYPE_IPV4; + } + CNetHash aHash[17]; + int Length = CNetHash::MakeHashArray(pAddr, aHash); + + // check ban adresses + CBanAddr *pBan = m_BanAddrPool.Find(pAddr, &aHash[Length]); + if(pBan) + { + MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER); + return true; + } + + // check ban ranges + for(int i = Length-1; i >= 0; --i) + { + for(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext) + { + if(NetMatch(&pBan->m_Data, pAddr, i, Length)) + { + MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER); + return true; + } + } + } + + return false; +} + +void CNetBan::ConBan(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + const char *pStr = pResult->GetString(0); + int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; + const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; + + NETADDR Addr; + if(net_addr_from_str(&Addr, pStr) == 0) + pThis->BanAddr(&Addr, Minutes*60, pReason); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid network address)"); +} + +void CNetBan::ConBanRange(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + const char *pStr1 = pResult->GetString(0); + const char *pStr2 = pResult->GetString(1); + int Minutes = pResult->NumArguments()>2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30; + const char *pReason = pResult->NumArguments()>3 ? pResult->GetString(3) : "No reason given"; + + CNetRange Range; + if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0) + pThis->BanRange(&Range, Minutes*60, pReason); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid range)"); +} + +void CNetBan::ConUnban(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + const char *pStr = pResult->GetString(0); + if(StrAllnum(pStr)) + pThis->UnbanByIndex(str_toint(pStr)); + else + { + NETADDR Addr; + if(net_addr_from_str(&Addr, pStr) == 0) + pThis->UnbanByAddr(&Addr); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid network address)"); + } +} + +void CNetBan::ConUnbanRange(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + const char *pStr1 = pResult->GetString(0); + const char *pStr2 = pResult->GetString(1); + + CNetRange Range; + if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0) + pThis->UnbanByRange(&Range); + else + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid range)"); +} + +void CNetBan::ConUnbanAll(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + pThis->UnbanAll(); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unbanned all entries"); +} + +void CNetBan::ConBans(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + int Count = 0; + char aBuf[256], aMsg[256]; + for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) + { + pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + } + for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) + { + pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); + str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); + } + str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count==1?"ban":"bans"); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); +} + +void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser) +{ + CNetBan *pThis = static_cast<CNetBan *>(pUser); + + char aBuf[256]; + IOHANDLE File = pThis->Storage()->OpenFile(pResult->GetString(0), IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!File) + { + str_format(aBuf, sizeof(aBuf), "failed to save banlist to '%s'", pResult->GetString(0)); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); + return; + } + + int Now = time_timestamp(); + char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; + for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) + { + int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + net_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false); + str_format(aBuf, sizeof(aBuf), "ban %s %i %s", aAddrStr1, Min, pBan->m_Info.m_aReason); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) + { + int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; + net_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false); + net_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false); + str_format(aBuf, sizeof(aBuf), "ban_range %s %s %i %s", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason); + io_write(File, aBuf, str_length(aBuf)); + io_write_newline(File); + } + + io_close(File); + str_format(aBuf, sizeof(aBuf), "saved banlist to '%s'", pResult->GetString(0)); + pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); +} diff --git a/src/engine/shared/netban.h b/src/engine/shared/netban.h new file mode 100644 index 0000000..11aed13 --- /dev/null +++ b/src/engine/shared/netban.h @@ -0,0 +1,235 @@ +#ifndef ENGINE_SHARED_NETBAN_H +#define ENGINE_SHARED_NETBAN_H + +#include <base/system.h> + +inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2) +{ + return mem_comp(pAddr1, pAddr2, pAddr1->type==NETTYPE_IPV4 ? 8 : 20); +} + +class CNetRange +{ +public: + NETADDR m_LB; + NETADDR m_UB; + + bool IsValid() const { return m_LB.type == m_UB.type && NetComp(&m_LB, &m_UB) < 0; } +}; + +inline int NetComp(const CNetRange *pRange1, const CNetRange *pRange2) +{ + return NetComp(&pRange1->m_LB, &pRange2->m_LB) || NetComp(&pRange1->m_UB, &pRange2->m_UB); +} + +class CNetBan +{ +protected: + bool NetMatch(const NETADDR *pAddr1, const NETADDR *pAddr2) const + { + return NetComp(pAddr1, pAddr2) == 0; + } + + bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const + { + return pRange->m_LB.type == pAddr->type && (Start == 0 || mem_comp(&pRange->m_LB.ip[0], &pAddr->ip[0], Start) == 0) && + mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0; + } + + bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const + { + return NetMatch(pRange, pAddr, 0, pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16); + } + + const char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(pData, aAddrStr, sizeof(aAddrStr), false); + str_format(pBuffer, BufferSize, "'%s'", aAddrStr); + return pBuffer; + } + + const char *NetToString(const CNetRange *pData, char *pBuffer, unsigned BufferSize) const + { + char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; + net_addr_str(&pData->m_LB, aAddrStr1, sizeof(aAddrStr1), false); + net_addr_str(&pData->m_UB, aAddrStr2, sizeof(aAddrStr2), false); + str_format(pBuffer, BufferSize, "'%s' - '%s'", aAddrStr1, aAddrStr2); + return pBuffer; + } + + // todo: move? + static bool StrAllnum(const char *pStr); + + class CNetHash + { + public: + int m_Hash; + int m_HashIndex; // matching parts for ranges, 0 for addr + + CNetHash() {} + CNetHash(const NETADDR *pAddr); + CNetHash(const CNetRange *pRange); + + static int MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]); + }; + + struct CBanInfo + { + enum + { + EXPIRES_NEVER=-1, + REASON_LENGTH=64, + }; + int m_Expires; + char m_aReason[REASON_LENGTH]; + }; + + template<class T> struct CBan + { + T m_Data; + CBanInfo m_Info; + CNetHash m_NetHash; + + // hash list + CBan *m_pHashNext; + CBan *m_pHashPrev; + + // used or free list + CBan *m_pNext; + CBan *m_pPrev; + }; + + template<class T, int HashCount> class CBanPool + { + public: + typedef T CDataType; + + CBan<CDataType> *Add(const CDataType *pData, const CBanInfo *pInfo, const CNetHash *pNetHash); + int Remove(CBan<CDataType> *pBan); + void Update(CBan<CDataType> *pBan, const CBanInfo *pInfo); + void Reset(); + + int Num() const { return m_CountUsed; } + bool IsFull() const { return m_CountUsed == MAX_BANS; } + + CBan<CDataType> *First() const { return m_pFirstUsed; } + CBan<CDataType> *First(const CNetHash *pNetHash) const { return m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; } + CBan<CDataType> *Find(const CDataType *pData, const CNetHash *pNetHash) const + { + for(CBan<CDataType> *pBan = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; pBan; pBan = pBan->m_pHashNext) + { + if(NetComp(&pBan->m_Data, pData) == 0) + return pBan; + } + + return 0; + } + CBan<CDataType> *Get(int Index) const; + + private: + enum + { + MAX_BANS=1024, + }; + + CBan<CDataType> *m_paaHashList[HashCount][256]; + CBan<CDataType> m_aBans[MAX_BANS]; + CBan<CDataType> *m_pFirstFree; + CBan<CDataType> *m_pFirstUsed; + int m_CountUsed; + }; + + typedef CBanPool<NETADDR, 1> CBanAddrPool; + typedef CBanPool<CNetRange, 16> CBanRangePool; + typedef CBan<NETADDR> CBanAddr; + typedef CBan<CNetRange> CBanRange; + + template<class T> void MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const; + template<class T> int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); + template<class T> int Unban(T *pBanPool, const typename T::CDataType *pData); + + class IConsole *m_pConsole; + class IStorage *m_pStorage; + CBanAddrPool m_BanAddrPool; + CBanRangePool m_BanRangePool; + NETADDR m_LocalhostIPV4, m_LocalhostIPV6; + +public: + enum + { + MSGTYPE_PLAYER=0, + MSGTYPE_LIST, + MSGTYPE_BANADD, + MSGTYPE_BANREM, + }; + + class IConsole *Console() const { return m_pConsole; } + class IStorage *Storage() const { return m_pStorage; } + + virtual ~CNetBan() {} + void Init(class IConsole *pConsole, class IStorage *pStorage); + void Update(); + + virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); + virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); + int UnbanByAddr(const NETADDR *pAddr); + int UnbanByRange(const CNetRange *pRange); + int UnbanByIndex(int Index); + void UnbanAll(); + bool IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const; + + static void ConBan(class IConsole::IResult *pResult, void *pUser); + static void ConBanRange(class IConsole::IResult *pResult, void *pUser); + static void ConUnban(class IConsole::IResult *pResult, void *pUser); + static void ConUnbanRange(class IConsole::IResult *pResult, void *pUser); + static void ConUnbanAll(class IConsole::IResult *pResult, void *pUser); + static void ConBans(class IConsole::IResult *pResult, void *pUser); + static void ConBansSave(class IConsole::IResult *pResult, void *pUser); +}; + + +template<class T> +void CNetBan::MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const +{ + if(pBan == 0 || pBuf == 0) + { + if(BuffSize > 0) + pBuf[0] = 0; + return; + } + + // build type based part + char aBuf[256]; + if(Type == MSGTYPE_PLAYER) + str_copy(aBuf, "You have been banned", sizeof(aBuf)); + else + { + char aTemp[256]; + switch(Type) + { + case MSGTYPE_LIST: + str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + case MSGTYPE_BANADD: + str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + case MSGTYPE_BANREM: + str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; + default: + aBuf[0] = 0; + } + } + + // add info part + if(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER) + { + int Mins = ((pBan->m_Info.m_Expires-time_timestamp()) + 59) / 60; + if(Mins <= 1) + str_format(pBuf, BuffSize, "%s for 1 minute (%s)", aBuf, pBan->m_Info.m_aReason); + else + str_format(pBuf, BuffSize, "%s for %d minutes (%s)", aBuf, Mins, pBan->m_Info.m_aReason); + } + else + str_format(pBuf, BuffSize, "%s for life (%s)", aBuf, pBan->m_Info.m_aReason); +} + +#endif diff --git a/src/engine/shared/network.cpp b/src/engine/shared/network.cpp new file mode 100644 index 0000000..fd9ba5e --- /dev/null +++ b/src/engine/shared/network.cpp @@ -0,0 +1,376 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + + +#include "config.h" +#include "network.h" +#include "huffman.h" + +void CNetRecvUnpacker::Clear() +{ + m_Valid = false; +} + +void CNetRecvUnpacker::Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID) +{ + m_Addr = *pAddr; + m_pConnection = pConnection; + m_ClientID = ClientID; + m_CurrentChunk = 0; + m_Valid = true; +} + +// TODO: rename this function +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)) + { + // anti spoof: ignore unknown sequence + if(Header.m_Sequence == (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE || m_pConnection->m_UnknownSeq) + { + m_pConnection->m_UnknownSeq = false; + + // in sequence + m_pConnection->m_Ack = Header.m_Sequence; + } + else + { + // old packet that we already got + if(CNetBase::IsSeqInBackroom(Header.m_Sequence, m_pConnection->m_Ack)) + continue; + + // out of sequence, request resend + if(g_Config.m_Debug) + dbg_msg("conn", "asking for resend %d %d", Header.m_Sequence, (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE); + m_pConnection->SignalResend(); + continue; // take the next chunk in the packet + } + } + + // fill in the info + pChunk->m_ClientID = m_ClientID; + pChunk->m_Address = m_Addr; + pChunk->m_Flags = Header.m_Flags; + pChunk->m_DataSize = Header.m_Size; + pChunk->m_pData = pData; + return 1; + } +} + +// packs the data tight and sends it +void CNetBase::SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize) +{ + unsigned char aBuffer[NET_MAX_PACKETSIZE]; + aBuffer[0] = 0xff; + aBuffer[1] = 0xff; + aBuffer[2] = 0xff; + aBuffer[3] = 0xff; + aBuffer[4] = 0xff; + aBuffer[5] = 0xff; + mem_copy(&aBuffer[6], pData, DataSize); + net_udp_send(Socket, pAddr, aBuffer, 6+DataSize); +} + +void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket, SECURITY_TOKEN SecurityToken) +{ + unsigned char aBuffer[NET_MAX_PACKETSIZE]; + int CompressedSize = -1; + int FinalSize = -1; + + // log the data + if(ms_DataLogSent) + { + int Type = 1; + io_write(ms_DataLogSent, &Type, sizeof(Type)); + io_write(ms_DataLogSent, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); + io_write(ms_DataLogSent, &pPacket->m_aChunkData, pPacket->m_DataSize); + io_flush(ms_DataLogSent); + } + + if (SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) + { + // append security token + // if SecurityToken is NET_SECURITY_TOKEN_UNKNOWN we will still append it hoping to negotiate it + mem_copy(&pPacket->m_aChunkData[pPacket->m_DataSize], &SecurityToken, sizeof(SecurityToken)); + pPacket->m_DataSize += sizeof(SecurityToken); + } + + // compress + CompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[3], NET_MAX_PACKETSIZE-4); + + // check if the compression was enabled, successful and good enough +#ifndef FUZZING + if(CompressedSize > 0 && CompressedSize < pPacket->m_DataSize) + { + FinalSize = CompressedSize; + pPacket->m_Flags |= NET_PACKETFLAG_COMPRESSION; + } + else +#endif + { + // use uncompressed data + FinalSize = pPacket->m_DataSize; + mem_copy(&aBuffer[3], pPacket->m_aChunkData, pPacket->m_DataSize); + pPacket->m_Flags &= ~NET_PACKETFLAG_COMPRESSION; + } + + // set header and send the packet if all things are good + if(FinalSize >= 0) + { + FinalSize += NET_PACKETHEADERSIZE; + aBuffer[0] = ((pPacket->m_Flags<<4)&0xf0)|((pPacket->m_Ack>>8)&0xf); + aBuffer[1] = pPacket->m_Ack&0xff; + aBuffer[2] = pPacket->m_NumChunks; + net_udp_send(Socket, pAddr, aBuffer, FinalSize); + + // log raw socket data + if(ms_DataLogSent) + { + int Type = 0; + io_write(ms_DataLogSent, &Type, sizeof(Type)); + io_write(ms_DataLogSent, &FinalSize, sizeof(FinalSize)); + io_write(ms_DataLogSent, aBuffer, FinalSize); + io_flush(ms_DataLogSent); + } + } +} + +// TODO: rename this function +int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket) +{ + // check the size + if(Size < NET_PACKETHEADERSIZE || Size > NET_MAX_PACKETSIZE) + { + //dbg_msg("", "packet too small, %d", Size); + return -1; + } + + // log the data + if(ms_DataLogRecv) + { + int Type = 0; + io_write(ms_DataLogRecv, &Type, sizeof(Type)); + io_write(ms_DataLogRecv, &Size, sizeof(Size)); + 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]; + pPacket->m_NumChunks = pBuffer[2]; + pPacket->m_DataSize = Size - NET_PACKETHEADERSIZE; + + if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) + { + if(Size < 6) + { + //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; + pPacket->m_DataSize = Size - 6; + mem_copy(pPacket->m_aChunkData, &pBuffer[6], pPacket->m_DataSize); + } + else + { + if(pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION) + pPacket->m_DataSize = ms_Huffman.Decompress(&pBuffer[3], pPacket->m_DataSize, pPacket->m_aChunkData, sizeof(pPacket->m_aChunkData)); + else + mem_copy(pPacket->m_aChunkData, &pBuffer[3], pPacket->m_DataSize); + } + + // check for errors + if(pPacket->m_DataSize < 0) + { + if(g_Config.m_Debug) + dbg_msg("network", "error during packet decoding"); + return -1; + } + + // log the data + if(ms_DataLogRecv) + { + int Type = 1; + io_write(ms_DataLogRecv, &Type, sizeof(Type)); + io_write(ms_DataLogRecv, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); + io_write(ms_DataLogRecv, pPacket->m_aChunkData, pPacket->m_DataSize); + io_flush(ms_DataLogRecv); + } + + // return success + return 0; +} + + +void CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken) +{ + CNetPacketConstruct Construct; + Construct.m_Flags = NET_PACKETFLAG_CONTROL; + Construct.m_Ack = Ack; + Construct.m_NumChunks = 0; + 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, SecurityToken); +} + + + +unsigned char *CNetChunkHeader::Pack(unsigned char *pData) +{ + pData[0] = ((m_Flags&3)<<6)|((m_Size>>4)&0x3f); + pData[1] = (m_Size&0xf); + if(m_Flags&NET_CHUNKFLAG_VITAL) + { + pData[1] |= (m_Sequence>>2)&0xf0; + pData[2] = m_Sequence&0xff; + return pData + 3; + } + return pData + 2; +} + +unsigned char *CNetChunkHeader::Unpack(unsigned char *pData) +{ + m_Flags = (pData[0]>>6)&3; + m_Size = ((pData[0]&0x3f)<<4) | (pData[1]&0xf); + m_Sequence = -1; + if(m_Flags&NET_CHUNKFLAG_VITAL) + { + m_Sequence = ((pData[1]&0xf0)<<2) | pData[2]; + return pData + 3; + } + return pData + 2; +} + + +int CNetBase::IsSeqInBackroom(int Seq, int Ack) +{ + int Bottom = (Ack-NET_MAX_SEQUENCE/2); + if(Bottom < 0) + { + if(Seq <= Ack) + return 1; + if(Seq >= (Bottom + NET_MAX_SEQUENCE)) + return 1; + } + else + { + if(Seq <= Ack && Seq >= Bottom) + return 1; + } + + return 0; +} + +IOHANDLE CNetBase::ms_DataLogSent = 0; +IOHANDLE CNetBase::ms_DataLogRecv = 0; +CHuffman CNetBase::ms_Huffman; + + +void CNetBase::OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv) +{ + if(DataLogSent) + { + ms_DataLogSent = DataLogSent; + dbg_msg("network", "logging sent packages"); + } + else + dbg_msg("network", "failed to start logging sent packages"); + + if(DataLogRecv) + { + ms_DataLogRecv = DataLogRecv; + dbg_msg("network", "logging recv packages"); + } + else + dbg_msg("network", "failed to start logging recv packages"); +} + +void CNetBase::CloseLog() +{ + if(ms_DataLogSent) + { + dbg_msg("network", "stopped logging sent packages"); + io_close(ms_DataLogSent); + ms_DataLogSent = 0; + } + + if(ms_DataLogRecv) + { + dbg_msg("network", "stopped logging recv packages"); + io_close(ms_DataLogRecv); + ms_DataLogRecv = 0; + } +} + +int CNetBase::Compress(const void *pData, int DataSize, void *pOutput, int OutputSize) +{ + return ms_Huffman.Compress(pData, DataSize, pOutput, OutputSize); +} + +int CNetBase::Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize) +{ + return ms_Huffman.Decompress(pData, DataSize, pOutput, OutputSize); +} + + +static const unsigned gs_aFreqTable[256+1] = { + 1<<30,4545,2657,431,1950,919,444,482,2244,617,838,542,715,1814,304,240,754,212,647,186, + 283,131,146,166,543,164,167,136,179,859,363,113,157,154,204,108,137,180,202,176, + 872,404,168,134,151,111,113,109,120,126,129,100,41,20,16,22,18,18,17,19, + 16,37,13,21,362,166,99,78,95,88,81,70,83,284,91,187,77,68,52,68, + 59,66,61,638,71,157,50,46,69,43,11,24,13,19,10,12,12,20,14,9, + 20,20,10,10,15,15,12,12,7,19,15,14,13,18,35,19,17,14,8,5, + 15,17,9,15,14,18,8,10,2173,134,157,68,188,60,170,60,194,62,175,71, + 148,67,167,78,211,67,156,69,1674,90,174,53,147,89,181,51,174,63,163,80, + 167,94,128,122,223,153,218,77,200,110,190,73,174,69,145,66,277,143,141,60, + 136,53,180,57,142,57,158,61,166,112,152,92,26,22,21,28,20,26,30,21, + 32,27,20,17,23,21,30,22,22,21,27,25,17,27,23,18,39,26,15,21, + 12,18,18,27,20,18,15,19,11,17,33,12,18,15,19,18,16,26,17,18, + 9,10,25,22,22,17,20,16,6,16,15,20,14,18,24,335,1517}; + +void CNetBase::Init() +{ +#ifndef FUZZING + ms_Huffman.Init(gs_aFreqTable); +#endif +} diff --git a/src/engine/shared/network.h b/src/engine/shared/network.h new file mode 100644 index 0000000..1c10e01 --- /dev/null +++ b/src/engine/shared/network.h @@ -0,0 +1,460 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_NETWORK_H +#define ENGINE_SHARED_NETWORK_H + +#include "ringbuffer.h" +#include "huffman.h" + +#include <base/math.h> + +#include <engine/message.h> + +/* + +CURRENT: + packet header: 3 bytes + 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 + + chunk header: 2-3 bytes + unsigned char flags_size; // 2bit flags, 6 bit size + unsigned char size_seq; // 4bit size, 4bit seq + (unsigned char seq;) // 8bit seq, if vital flag is set +*/ + +enum +{ + NETFLAG_ALLOWSTATELESS=1, + NETSENDFLAG_VITAL=1, + NETSENDFLAG_CONNLESS=2, + NETSENDFLAG_FLUSH=4, + + NETSTATE_OFFLINE=0, + NETSTATE_CONNECTING, + NETSTATE_ONLINE, + + NETBANTYPE_SOFT=1, + NETBANTYPE_DROP=2 +}; + + +enum +{ + NET_VERSION = 2, + + NET_MAX_PACKETSIZE = 1400, + NET_MAX_PAYLOAD = NET_MAX_PACKETSIZE-6, + NET_MAX_CHUNKHEADERSIZE = 5, + NET_PACKETHEADERSIZE = 3, + NET_MAX_CLIENTS = 64, + NET_MAX_CONSOLE_CLIENTS = 4, + NET_MAX_SEQUENCE = 1<<10, + NET_SEQUENCE_MASK = NET_MAX_SEQUENCE-1, + + NET_CONNSTATE_OFFLINE=0, + NET_CONNSTATE_CONNECT=1, + NET_CONNSTATE_PENDING=2, + NET_CONNSTATE_ONLINE=3, + NET_CONNSTATE_ERROR=4, + + NET_PACKETFLAG_CONTROL=1, + NET_PACKETFLAG_CONNLESS=2, + NET_PACKETFLAG_RESEND=4, + NET_PACKETFLAG_COMPRESSION=8, + + 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_CONN_BUFFERSIZE=1024*32, + + NET_ENUM_TERMINATOR +}; + +typedef int SECURITY_TOKEN; + +SECURITY_TOKEN ToSecurityToken(unsigned char* pData); + +static const unsigned char SECURITY_TOKEN_MAGIC[] = {'T', 'K', 'E', 'N'}; + +enum +{ + NET_SECURITY_TOKEN_UNKNOWN = -1, + NET_SECURITY_TOKEN_UNSUPPORTED = 0, +}; + +typedef int (*NETFUNC_DELCLIENT)(int ClientID, const char* pReason, void *pUser); +typedef int (*NETFUNC_NEWCLIENT)(int ClientID, void *pUser); +typedef int (*NETFUNC_NEWCLIENT_NOAUTH)(int ClientID, bool Reset, void *pUser); +typedef int (*NETFUNC_CLIENTREJOIN)(int ClientID, void *pUser); + +struct CNetChunk +{ + // -1 means that it's a stateless packet + // 0 on the client means the server + int m_ClientID; + NETADDR m_Address; // only used when client_id == -1 + int m_Flags; + int m_DataSize; + const void *m_pData; +}; + +class CNetChunkHeader +{ +public: + int m_Flags; + int m_Size; + int m_Sequence; + + unsigned char *Pack(unsigned char *pData); + unsigned char *Unpack(unsigned char *pData); +}; + +class CNetChunkResend +{ +public: + int m_Flags; + int m_DataSize; + unsigned char *m_pData; + + int m_Sequence; + int64 m_LastSendTime; + int64 m_FirstSendTime; +}; + +class CNetPacketConstruct +{ +public: + int m_Flags; + int m_Ack; + int m_NumChunks; + int m_DataSize; + unsigned char m_aChunkData[NET_MAX_PAYLOAD]; +}; + + +class CNetConnection +{ + // TODO: is this needed because this needs to be aware of + // the ack sequencing number and is also responible for updating + // that. this should be fixed. + friend class CNetRecvUnpacker; +private: + unsigned short m_Sequence; + unsigned short m_Ack; + unsigned short m_PeerAck; + unsigned m_State; + + int m_Token; + SECURITY_TOKEN m_SecurityToken; + int m_RemoteClosed; + bool m_BlockCloseMsg; + bool m_UnknownSeq; + + 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 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); + void Resend(); + + bool HasSecurityToken; + +public: + bool m_TimeoutProtected; + bool m_TimeoutSituation; + + void Reset(bool Rejoin=false); + void Init(NETSOCKET Socket, bool BlockCloseMsg); + int Connect(NETADDR *pAddr); + void Disconnect(const char *pReason); + + int Update(); + int Flush(); + + int Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_TOKEN SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED); + int QueueChunk(int Flags, int DataSize, const void *pData); + + const char *ErrorString(); + void SignalResend(); + int State() const { return m_State; } + const 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; } + int64 ConnectTime() const { return m_LastUpdateTime; } + + int AckSequence() const { return m_Ack; } + int SeqSequence() const { return m_Sequence; } + int SecurityToken() const { return m_SecurityToken; } + void SetTimedOut(const NETADDR *pAddr, int Sequence, int Ack, SECURITY_TOKEN SecurityToken); + + // anti spoof + void DirectInit(NETADDR &Addr, SECURITY_TOKEN SecurityToken); + void SetUnknownSeq() { m_UnknownSeq = true; } + void SetSequence(int Sequence) { m_Sequence = Sequence; } +}; + +class CConsoleNetConnection +{ +private: + int m_State; + + NETADDR m_PeerAddr; + NETSOCKET m_Socket; + + char m_aBuffer[NET_MAX_PACKETSIZE]; + int m_BufferOffset; + + char m_aErrorString[256]; + + bool m_LineEndingDetected; + char m_aLineEnding[3]; + +public: + void Init(NETSOCKET Socket, const NETADDR *pAddr); + void Disconnect(const char *pReason); + + int State() const { return m_State; } + const NETADDR *PeerAddress() const { return &m_PeerAddr; } + const char *ErrorString() const { return m_aErrorString; } + + void Reset(); + int Update(); + int Send(const char *pLine); + int Recv(char *pLine, int MaxLength); +}; + +class CNetRecvUnpacker +{ +public: + bool m_Valid; + + NETADDR m_Addr; + CNetConnection *m_pConnection; + int m_CurrentChunk; + int m_ClientID; + CNetPacketConstruct m_Data; + unsigned char m_aBuffer[NET_MAX_PACKETSIZE]; + + CNetRecvUnpacker() { Clear(); } + void Clear(); + void Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID); + int FetchChunk(CNetChunk *pChunk); +}; + +// server side +class CNetServer +{ + struct CSlot + { + public: + CNetConnection m_Connection; + }; + + NETSOCKET m_Socket; + class CNetBan *m_pNetBan; + CSlot m_aSlots[NET_MAX_CLIENTS]; + int m_MaxClients; + int m_MaxClientsPerIP; + + NETFUNC_NEWCLIENT m_pfnNewClient; + NETFUNC_NEWCLIENT_NOAUTH m_pfnNewClientNoAuth; + NETFUNC_DELCLIENT m_pfnDelClient; + NETFUNC_CLIENTREJOIN m_pfnClientRejoin; + void *m_UserPtr; + + + int m_NumConAttempts; // log flooding attacks + int64 m_TimeNumConAttempts; + unsigned char m_SecurityTokenSeed[16]; + + // vanilla connect flood detection + bool m_VConnHighLoad; + int64 m_VConnFirst; + int m_VConnNum; + + CNetRecvUnpacker m_RecvUnpacker; + + void OnTokenCtrlMsg(NETADDR &Addr, int ControlMsg, const CNetPacketConstruct &Packet); + void OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet); + void OnConnCtrlMsg(NETADDR &Addr, int ClientID, int ControlMsg, const CNetPacketConstruct &Packet); + bool ClientExists(const NETADDR &Addr) { return GetClientSlot(Addr) != -1; }; + int GetClientSlot(const NETADDR &Addr); + void SendControl(NETADDR &Addr, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken); + + int TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, bool VanillaAuth=false); + int NumClientsWithAddr(NETADDR Addr); + void SendMsgs(NETADDR &Addr, const CMsgPacker *Msgs[], int num); + +public: + int SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); + int SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_NEWCLIENT_NOAUTH pfnNewClientNoAuth, NETFUNC_CLIENTREJOIN pfnClientRejoin, NETFUNC_DELCLIENT pfnDelClient, void *pUser); + + // + bool Open(NETADDR BindAddr, class CNetBan *pNetBan, 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); + + // status requests + const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } + bool HasSecurityToken(int ClientID) const { return m_aSlots[ClientID].m_Connection.SecurityToken() != NET_SECURITY_TOKEN_UNSUPPORTED; } + NETSOCKET Socket() const { return m_Socket; } + class CNetBan *NetBan() const { return m_pNetBan; } + int NetType() const { return m_Socket.type; } + int MaxClients() const { return m_MaxClients; } + + // + void SetMaxClientsPerIP(int Max); + bool SetTimedOut(int ClientID, int OrigID); + void SetTimeoutProtected(int ClientID); + + int ResetErrorString(int ClientID); + const char *ErrorString(int ClientID); + + // anti spoof + SECURITY_TOKEN GetToken(const NETADDR &Addr); + // vanilla token/gametick shouldn't be negative + SECURITY_TOKEN GetVanillaToken(const NETADDR &Addr) { return absolute(GetToken(Addr)); } +}; + +class CNetConsole +{ + struct CSlot + { + CConsoleNetConnection m_Connection; + }; + + NETSOCKET m_Socket; + class CNetBan *m_pNetBan; + CSlot m_aSlots[NET_MAX_CONSOLE_CLIENTS]; + + NETFUNC_NEWCLIENT m_pfnNewClient; + NETFUNC_DELCLIENT m_pfnDelClient; + void *m_UserPtr; + + CNetRecvUnpacker m_RecvUnpacker; + +public: + void SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); + + // + bool Open(NETADDR BindAddr, class CNetBan *pNetBan, int Flags); + int Close(); + + // + int Recv(char *pLine, int MaxLength, int *pClientID = 0); + int Send(int ClientID, const char *pLine); + int Update(); + + // + int AcceptClient(NETSOCKET Socket, const NETADDR *pAddr); + int Drop(int ClientID, const char *pReason); + + // status requests + const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } + class CNetBan *NetBan() const { return m_pNetBan; } +}; + + + +// client side +class CNetClient +{ + CNetConnection m_Connection; + CNetRecvUnpacker m_RecvUnpacker; +public: + NETSOCKET m_Socket; + // 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 NetType() const { return m_Socket.type; } + int State(); + int GotProblems(); + const char *ErrorString(); + + bool SecurityTokenUnknown() { return m_Connection.SecurityToken() == NET_SECURITY_TOKEN_UNKNOWN; } +}; + + + +// TODO: both, fix these. This feels like a junk class for stuff that doesn't fit anywere +class CNetBase +{ + static IOHANDLE ms_DataLogSent; + static IOHANDLE ms_DataLogRecv; + static CHuffman ms_Huffman; +public: + static void OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv); + static void CloseLog(); + 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, SECURITY_TOKEN SecurityToken); + static void SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize); + static void SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket, SECURITY_TOKEN SecurityToken); + + + 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); +}; + + +#endif diff --git a/src/engine/shared/network_client.cpp b/src/engine/shared/network_client.cpp new file mode 100644 index 0000000..22a17de --- /dev/null +++ b/src/engine/shared/network_client.cpp @@ -0,0 +1,148 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "network.h" + +bool CNetClient::Open(NETADDR BindAddr, int Flags) +{ + // open socket + NETSOCKET Socket; + Socket = net_udp_create(BindAddr); + if(!Socket.type) + return false; + + // clean it + mem_zero(this, sizeof(*this)); + + // init + m_Socket = Socket; + m_Connection.Init(m_Socket, false); + return true; +} + +int CNetClient::Close() +{ + // TODO: implement me + return 0; +} + + +int CNetClient::Disconnect(const char *pReason) +{ + //dbg_msg("netclient", "disconnected. reason=\"%s\"", pReason); + m_Connection.Disconnect(pReason); + return 0; +} + +int CNetClient::Update() +{ + m_Connection.Update(); + if(m_Connection.State() == NET_CONNSTATE_ERROR) + Disconnect(m_Connection.ErrorString()); + return 0; +} + +int CNetClient::Connect(NETADDR *pAddr) +{ + m_Connection.Connect(pAddr); + return 0; +} + +int CNetClient::ResetErrorString() +{ + m_Connection.ResetErrorString(); + return 0; +} + +int CNetClient::Recv(CNetChunk *pChunk) +{ + while(1) + { + // 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); + + // no more packets for now + if(Bytes <= 0) + break; + + if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0) + { + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) + { + pChunk->m_Flags = NETSENDFLAG_CONNLESS; + pChunk->m_ClientID = -1; + pChunk->m_Address = Addr; + pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; + pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; + return 1; + } + else + { + if(m_Connection.State() != NET_CONNSTATE_OFFLINE && m_Connection.State() != NET_CONNSTATE_ERROR && net_addr_comp(m_Connection.PeerAddress(), &Addr) == 0 + && m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) + m_RecvUnpacker.Start(&Addr, &m_Connection, 0); + } + } + } + return 0; +} + +int CNetClient::Send(CNetChunk *pChunk) +{ + if(pChunk->m_DataSize >= NET_MAX_PAYLOAD) + { + dbg_msg("netclient", "chunk payload too big. %d. dropping chunk", pChunk->m_DataSize); + return -1; + } + + if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) + { + // send connectionless packet + CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize); + } + else + { + 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) + m_Connection.Flush(); + } + return 0; +} + +int CNetClient::State() +{ + if(m_Connection.State() == NET_CONNSTATE_ONLINE) + return NETSTATE_ONLINE; + if(m_Connection.State() == NET_CONNSTATE_OFFLINE) + return NETSTATE_OFFLINE; + return NETSTATE_CONNECTING; +} + +int CNetClient::Flush() +{ + return m_Connection.Flush(); +} + +int CNetClient::GotProblems() +{ + if(time_get() - m_Connection.LastRecvTime() > time_freq()) + return 1; + return 0; +} + +const char *CNetClient::ErrorString() +{ + return m_Connection.ErrorString(); +} diff --git a/src/engine/shared/network_conn.cpp b/src/engine/shared/network_conn.cpp new file mode 100644 index 0000000..e68ef5a --- /dev/null +++ b/src/engine/shared/network_conn.cpp @@ -0,0 +1,486 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "config.h" +#include "network.h" + +SECURITY_TOKEN ToSecurityToken(unsigned char* pData) +{ + return (int)pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24); +} + +void CNetConnection::ResetStats() +{ + mem_zero(&m_Stats, sizeof(m_Stats)); + mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); + m_LastUpdateTime = 0; +} + +void CNetConnection::Reset(bool Rejoin) +{ + m_Sequence = 0; + m_Ack = 0; + m_PeerAck = 0; + m_RemoteClosed = 0; + + if (!Rejoin) + { + m_TimeoutProtected = false; + m_TimeoutSituation = false; + + m_State = NET_CONNSTATE_OFFLINE; + m_Token = -1; + m_SecurityToken = NET_SECURITY_TOKEN_UNKNOWN; + } + + m_LastSendTime = 0; + m_LastRecvTime = 0; + //m_LastUpdateTime = 0; + + //mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); + m_UnknownSeq = false; + + m_Buffer.Init(); + + mem_zero(&m_Construct, sizeof(m_Construct)); +} + +const char *CNetConnection::ErrorString() +{ + return m_ErrorString; +} + +void CNetConnection::SetError(const char *pString) +{ + str_copy(m_ErrorString, pString, sizeof(m_ErrorString)); +} + +void CNetConnection::Init(NETSOCKET Socket, bool BlockCloseMsg) +{ + Reset(); + ResetStats(); + + m_Socket = Socket; + m_BlockCloseMsg = BlockCloseMsg; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); +} + +void CNetConnection::AckChunks(int Ack) +{ + while(1) + { + CNetChunkResend *pResend = m_Buffer.First(); + if(!pResend) + break; + + if(CNetBase::IsSeqInBackroom(pResend->m_Sequence, Ack)) + m_Buffer.PopFirst(); + else + break; + } +} + +void CNetConnection::SignalResend() +{ + m_Construct.m_Flags |= NET_PACKETFLAG_RESEND; +} + +int CNetConnection::Flush() +{ + int NumChunks = m_Construct.m_NumChunks; + if(!NumChunks && !m_Construct.m_Flags) + return 0; + + // send of the packets + m_Construct.m_Ack = m_Ack; + CNetBase::SendPacket(m_Socket, &m_PeerAddr, &m_Construct, m_SecurityToken); + + // 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; +} + +int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence) +{ + if (m_State == NET_CONNSTATE_OFFLINE || m_State == NET_CONNSTATE_ERROR) + return -1; + + 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) - (int)sizeof(SECURITY_TOKEN)) + Flush(); + + // pack all the data + CNetChunkHeader Header; + Header.m_Flags = Flags; + Header.m_Size = DataSize; + Header.m_Sequence = Sequence; + pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize]; + pChunkData = Header.Pack(pChunkData); + mem_copy(pChunkData, pData, DataSize); + pChunkData += DataSize; + + // + 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 + CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+DataSize); + if(pResend) + { + pResend->m_Sequence = Sequence; + pResend->m_Flags = Flags; + pResend->m_DataSize = DataSize; + pResend->m_pData = (unsigned char *)(pResend+1); + pResend->m_FirstSendTime = time_get(); + pResend->m_LastSendTime = pResend->m_FirstSendTime; + mem_copy(pResend->m_pData, pData, DataSize); + } + else + { + // out of buffer, don't save the packet and hope nobody will ask for resend + return -1; + } + } + + return 0; +} + +int CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData) +{ + if(Flags&NET_CHUNKFLAG_VITAL) + m_Sequence = (m_Sequence+1)%NET_MAX_SEQUENCE; + return QueueChunkEx(Flags, DataSize, pData, m_Sequence); +} + +void CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSize) +{ + // send the control message + m_LastSendTime = time_get(); + CNetBase::SendControlMsg(m_Socket, &m_PeerAddr, m_Ack, ControlMsg, pExtra, ExtraSize, m_SecurityToken); +} + +void CNetConnection::ResendChunk(CNetChunkResend *pResend) +{ + QueueChunkEx(pResend->m_Flags|NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence); + pResend->m_LastSendTime = time_get(); +} + +void CNetConnection::Resend() +{ + for(CNetChunkResend *pResend = m_Buffer.First(); pResend; pResend = m_Buffer.Next(pResend)) + ResendChunk(pResend); +} + +int CNetConnection::Connect(NETADDR *pAddr) +{ + if(State() != NET_CONNSTATE_OFFLINE) + return -1; + + // init connection + Reset(); + m_PeerAddr = *pAddr; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + m_State = NET_CONNSTATE_CONNECT; + SendControl(NET_CTRLMSG_CONNECT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + return 0; +} + +void CNetConnection::Disconnect(const char *pReason) +{ + if(State() == NET_CONNSTATE_OFFLINE) + return; + + if(m_RemoteClosed == 0) + { + if(pReason) + SendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason)+1); + else + SendControl(NET_CTRLMSG_CLOSE, 0, 0); + + if(pReason != m_ErrorString) + { + m_ErrorString[0] = 0; + if(pReason) + str_copy(m_ErrorString, pReason, sizeof(m_ErrorString)); + } + } + + Reset(); +} + +void CNetConnection::DirectInit(NETADDR &Addr, SECURITY_TOKEN SecurityToken) +{ + Reset(); + + m_State = NET_CONNSTATE_ONLINE; + + m_PeerAddr = Addr; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + + int64 Now = time_get(); + m_LastSendTime = Now; + m_LastRecvTime = Now; + m_LastUpdateTime = Now; + + m_SecurityToken = SecurityToken; +} + +int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr, SECURITY_TOKEN SecurityToken) +{ + if (State() != NET_CONNSTATE_OFFLINE && m_SecurityToken != NET_SECURITY_TOKEN_UNKNOWN && m_SecurityToken != NET_SECURITY_TOKEN_UNSUPPORTED) + { + // supposed to have a valid token in this packet, check it + if (pPacket->m_DataSize < (int)sizeof(m_SecurityToken)) + return 0; + pPacket->m_DataSize -= sizeof(m_SecurityToken); + if (m_SecurityToken != ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize])) + { + if(g_Config.m_Debug) + dbg_msg("security", "token mismatch, expected %d got %d", m_SecurityToken, ToSecurityToken(&pPacket->m_aChunkData[pPacket->m_DataSize])); + return 0; + } + } + + // check if actual ack value is valid(own sequence..latest peer ack) + if(m_Sequence >= m_PeerAck) + { + if(pPacket->m_Ack < m_PeerAck || pPacket->m_Ack > m_Sequence) + return 0; + } + else + { + if(pPacket->m_Ack < m_PeerAck && pPacket->m_Ack > m_Sequence) + return 0; + } + m_PeerAck = pPacket->m_Ack; + + int64 Now = time_get(); + + // check if resend is requested + if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) + Resend(); + + // + 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; + + char Str[128] = {0}; + if(pPacket->m_DataSize > 1) + { + // make sure to sanitize the error string form the other party + if(pPacket->m_DataSize < 128) + str_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize); + else + str_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str)); + str_sanitize_strong(Str); + } + + if(!m_BlockCloseMsg) + { + // set the error string + SetError(Str); + } + + if(g_Config.m_Debug) + dbg_msg("conn", "closed reason='%s'", Str); + } + return 0; + } + else + { + if(State() == NET_CONNSTATE_OFFLINE) + { + if(CtrlMsg == NET_CTRLMSG_CONNECT) + { + NETADDR nAddr; + mem_copy(&nAddr, pAddr, sizeof(nAddr)); + nAddr.port = 0; + m_PeerAddr.port = 0; +#ifndef FUZZING + if(net_addr_comp(&m_PeerAddr, &nAddr) == 0 && time_get() - m_LastUpdateTime < time_freq() * 3) + return 0; +#endif + + // send response and init connection + Reset(); + m_State = NET_CONNSTATE_PENDING; + m_PeerAddr = *pAddr; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + m_LastSendTime = Now; + m_LastRecvTime = Now; + m_LastUpdateTime = Now; + if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN + && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) + && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) + { + m_SecurityToken = SecurityToken; + if(g_Config.m_Debug) + dbg_msg("security", "generated token %d", m_SecurityToken); + } + else + { + if(g_Config.m_Debug) + dbg_msg("security", "token not supported by client (packet size %d)", pPacket->m_DataSize); + m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED; + } + SendControl(NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + if(g_Config.m_Debug) + dbg_msg("connection", "got connection, sending connect+accept"); + } + } + else if(State() == NET_CONNSTATE_CONNECT) + { + // connection made + if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT) + { + if (m_SecurityToken == NET_SECURITY_TOKEN_UNKNOWN + && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(m_SecurityToken)) + && !mem_comp(&pPacket->m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC))) + { + m_SecurityToken = ToSecurityToken(&pPacket->m_aChunkData[1 + sizeof(SECURITY_TOKEN_MAGIC)]); + if(g_Config.m_Debug) + dbg_msg("security", "got token %d", m_SecurityToken); + } + else + { + m_SecurityToken = NET_SECURITY_TOKEN_UNSUPPORTED; + if(g_Config.m_Debug) + dbg_msg("security", "token not supported by server"); + } + m_LastRecvTime = Now; + SendControl(NET_CTRLMSG_ACCEPT, 0, 0); + m_State = NET_CONNSTATE_ONLINE; + if(g_Config.m_Debug) + dbg_msg("connection", "got connect+accept, sending accept. connection online"); + } + } + } + } + else + { + if(State() == NET_CONNSTATE_PENDING) + { + m_LastRecvTime = Now; + m_State = NET_CONNSTATE_ONLINE; + if(g_Config.m_Debug) + dbg_msg("connection", "connecting online"); + } + } + + if(State() == NET_CONNSTATE_ONLINE) + { + m_LastRecvTime = Now; + AckChunks(pPacket->m_Ack); + } + + return 1; +} + +int CNetConnection::Update() +{ + int64 Now = time_get(); + + if(State() == NET_CONNSTATE_ERROR && m_TimeoutSituation && (Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeoutProtection) + { + m_TimeoutSituation = false; + SetError("Timeout Protection over"); + } + + if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR) + return 0; + + m_TimeoutSituation = false; + + // check for timeout + if(State() != NET_CONNSTATE_OFFLINE && + State() != NET_CONNSTATE_CONNECT && + (Now-m_LastRecvTime) > time_freq()*g_Config.m_ConnTimeout) + { + m_State = NET_CONNSTATE_ERROR; + SetError("Timeout"); + m_TimeoutSituation = true; + } + + // fix resends + if(m_Buffer.First()) + { + CNetChunkResend *pResend = m_Buffer.First(); + + // check if we have some really old stuff laying around and abort if not acked + if(Now-pResend->m_FirstSendTime > time_freq()*g_Config.m_ConnTimeout) + { + m_State = NET_CONNSTATE_ERROR; + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Too weak connection (not acked for %d seconds)", g_Config.m_ConnTimeout); + SetError(aBuf); + m_TimeoutSituation = true; + } + else + { + // resend packet if we havn't got it acked in 1 second + if(Now-pResend->m_LastSendTime > time_freq()) + ResendChunk(pResend); + } + } + + // send keep alives if nothing has happend for 250ms + if(State() == NET_CONNSTATE_ONLINE) + { + if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed + { + int NumFlushedChunks = Flush(); + 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); + } + else if(State() == NET_CONNSTATE_CONNECT) + { + if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms + SendControl(NET_CTRLMSG_CONNECT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + } + else if(State() == NET_CONNSTATE_PENDING) + { + if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms + SendControl(NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + } + + return 0; +} + +void CNetConnection::SetTimedOut(const NETADDR *pAddr, int Sequence, int Ack, SECURITY_TOKEN SecurityToken) +{ + int64 Now = time_get(); + + m_Sequence = Sequence; + m_Ack = Ack; + m_RemoteClosed = 0; + + m_State = NET_CONNSTATE_ONLINE; + m_PeerAddr = *pAddr; + mem_zero(m_ErrorString, sizeof(m_ErrorString)); + m_LastSendTime = Now; + m_LastRecvTime = Now; + m_LastUpdateTime = Now; + m_SecurityToken = SecurityToken; + m_Buffer.Init(); +} diff --git a/src/engine/shared/network_console.cpp b/src/engine/shared/network_console.cpp new file mode 100644 index 0000000..ded83f6 --- /dev/null +++ b/src/engine/shared/network_console.cpp @@ -0,0 +1,150 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + +#include <engine/console.h> + +#include "netban.h" +#include "network.h" + + +bool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, int Flags) +{ + // zero out the whole structure + mem_zero(this, sizeof(*this)); + m_Socket.type = NETTYPE_INVALID; + m_Socket.ipv4sock = -1; + m_Socket.ipv6sock = -1; + m_pNetBan = pNetBan; + + // open socket + m_Socket = net_tcp_create(BindAddr); + if(!m_Socket.type) + return false; + if(net_tcp_listen(m_Socket, NET_MAX_CONSOLE_CLIENTS)) + return false; + net_set_non_blocking(m_Socket); + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + m_aSlots[i].m_Connection.Reset(); + + return true; +} + +void CNetConsole::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) +{ + m_pfnNewClient = pfnNewClient; + m_pfnDelClient = pfnDelClient; + m_UserPtr = pUser; +} + +int CNetConsole::Close() +{ + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + m_aSlots[i].m_Connection.Disconnect("closing console"); + + net_tcp_close(m_Socket); + + return 0; +} + +int CNetConsole::Drop(int ClientID, const char *pReason) +{ + if(m_pfnDelClient) + m_pfnDelClient(ClientID, pReason, m_UserPtr); + + m_aSlots[ClientID].m_Connection.Disconnect(pReason); + + return 0; +} + +int CNetConsole::AcceptClient(NETSOCKET Socket, const NETADDR *pAddr) +{ + char aError[256] = { 0 }; + int FreeSlot = -1; + + // look for free slot or multiple client + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(FreeSlot == -1 && m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + FreeSlot = i; + if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE) + { + if(net_addr_comp(pAddr, m_aSlots[i].m_Connection.PeerAddress()) == 0) + { + str_copy(aError, "only one client per IP allowed", sizeof(aError)); + break; + } + } + } + + // accept client + if(!aError[0] && FreeSlot != -1) + { + m_aSlots[FreeSlot].m_Connection.Init(Socket, pAddr); + if(m_pfnNewClient) + m_pfnNewClient(FreeSlot, m_UserPtr); + return 0; + } + + // reject client + if(!aError[0]) + str_copy(aError, "no free slot available", sizeof(aError)); + + net_tcp_send(Socket, aError, str_length(aError)); + net_tcp_close(Socket); + + return -1; +} + +int CNetConsole::Update() +{ + NETSOCKET Socket; + NETADDR Addr; + + if(net_tcp_accept(m_Socket, &Socket, &Addr) > 0) + { + // check if we just should drop the packet + char aBuf[128]; + if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf))) + { + // banned, reply with a message and drop + net_tcp_send(Socket, aBuf, str_length(aBuf)); + net_tcp_close(Socket); + } + else + AcceptClient(Socket, &Addr); + } + + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE) + m_aSlots[i].m_Connection.Update(); + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) + Drop(i, m_aSlots[i].m_Connection.ErrorString()); + } + + return 0; +} + +int CNetConsole::Recv(char *pLine, int MaxLength, int *pClientID) +{ + for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE && m_aSlots[i].m_Connection.Recv(pLine, MaxLength)) + { + if(pClientID) + *pClientID = i; + return 1; + } + } + return 0; +} + +int CNetConsole::Send(int ClientID, const char *pLine) +{ + if(m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_ONLINE) + return m_aSlots[ClientID].m_Connection.Send(pLine); + else + return -1; +} diff --git a/src/engine/shared/network_console_conn.cpp b/src/engine/shared/network_console_conn.cpp new file mode 100644 index 0000000..9bc163a --- /dev/null +++ b/src/engine/shared/network_console_conn.cpp @@ -0,0 +1,186 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include "network.h" + +void CConsoleNetConnection::Reset() +{ + m_State = NET_CONNSTATE_OFFLINE; + mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); + m_aErrorString[0] = 0; + + m_Socket.type = NETTYPE_INVALID; + m_Socket.ipv4sock = -1; + m_Socket.ipv6sock = -1; + m_aBuffer[0] = 0; + m_BufferOffset = 0; + + m_LineEndingDetected = false; + #if defined(CONF_FAMILY_WINDOWS) + m_aLineEnding[0] = '\r'; + m_aLineEnding[1] = '\n'; + m_aLineEnding[2] = 0; + #else + m_aLineEnding[0] = '\n'; + m_aLineEnding[1] = 0; + m_aLineEnding[2] = 0; + #endif +} + +void CConsoleNetConnection::Init(NETSOCKET Socket, const NETADDR *pAddr) +{ + Reset(); + + m_Socket = Socket; + net_set_non_blocking(m_Socket); + + m_PeerAddr = *pAddr; + m_State = NET_CONNSTATE_ONLINE; +} + +void CConsoleNetConnection::Disconnect(const char *pReason) +{ + if(State() == NET_CONNSTATE_OFFLINE) + return; + + if(pReason && pReason[0]) + Send(pReason); + + net_tcp_close(m_Socket); + + Reset(); +} + +int CConsoleNetConnection::Update() +{ + if(State() == NET_CONNSTATE_ONLINE) + { + if((int)(sizeof(m_aBuffer)) <= m_BufferOffset) + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "too weak connection (out of buffer)", sizeof(m_aErrorString)); + return -1; + } + + int Bytes = net_tcp_recv(m_Socket, m_aBuffer+m_BufferOffset, (int)(sizeof(m_aBuffer))-m_BufferOffset); + + if(Bytes > 0) + { + m_BufferOffset += Bytes; + } + else if(Bytes < 0) + { + if(net_would_block()) // no data received + return 0; + + m_State = NET_CONNSTATE_ERROR; // error + str_copy(m_aErrorString, "connection failure", sizeof(m_aErrorString)); + return -1; + } + else + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "remote end closed the connection", sizeof(m_aErrorString)); + return -1; + } + } + + return 0; +} + +int CConsoleNetConnection::Recv(char *pLine, int MaxLength) +{ + if(State() == NET_CONNSTATE_ONLINE) + { + if(m_BufferOffset) + { + // find message start + int StartOffset = 0; + while(m_aBuffer[StartOffset] == '\r' || m_aBuffer[StartOffset] == '\n') + { + // detect clients line ending format + if(!m_LineEndingDetected) + { + m_aLineEnding[0] = m_aBuffer[StartOffset]; + if(StartOffset+1 < m_BufferOffset && (m_aBuffer[StartOffset+1] == '\r' || m_aBuffer[StartOffset+1] == '\n') && + m_aBuffer[StartOffset] != m_aBuffer[StartOffset+1]) + m_aLineEnding[1] = m_aBuffer[StartOffset+1]; + m_LineEndingDetected = true; + } + + if(++StartOffset >= m_BufferOffset) + { + m_BufferOffset = 0; + return 0; + } + } + + // find message end + int EndOffset = StartOffset; + while(m_aBuffer[EndOffset] != '\r' && m_aBuffer[EndOffset] != '\n') + { + if(++EndOffset >= m_BufferOffset) + { + if(StartOffset > 0) + { + mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + m_BufferOffset -= StartOffset; + } + return 0; + } + } + + // extract message and update buffer + if(MaxLength-1 < EndOffset-StartOffset) + { + if(StartOffset > 0) + { + mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); + m_BufferOffset -= StartOffset; + } + return 0; + } + mem_copy(pLine, m_aBuffer+StartOffset, EndOffset-StartOffset); + pLine[EndOffset-StartOffset] = 0; + str_sanitize_cc(pLine); + mem_move(m_aBuffer, m_aBuffer+EndOffset, m_BufferOffset-EndOffset); + m_BufferOffset -= EndOffset; + return 1; + } + } + return 0; +} + +int CConsoleNetConnection::Send(const char *pLine) +{ + if(State() != NET_CONNSTATE_ONLINE) + return -1; + + char aBuf[1024]; + str_copy(aBuf, pLine, (int)(sizeof(aBuf))-2); + int Length = str_length(aBuf); + aBuf[Length] = m_aLineEnding[0]; + aBuf[Length+1] = m_aLineEnding[1]; + aBuf[Length+2] = m_aLineEnding[2]; + Length += 3; + const char *pData = aBuf; + + while(true) + { + int Send = net_tcp_send(m_Socket, pData, Length); + if(Send < 0) + { + m_State = NET_CONNSTATE_ERROR; + str_copy(m_aErrorString, "failed to send packet", sizeof(m_aErrorString)); + return -1; + } + + if(Send >= Length) + break; + + pData += Send; + Length -= Send; + } + + return 0; +} diff --git a/src/engine/shared/network_server.cpp b/src/engine/shared/network_server.cpp new file mode 100644 index 0000000..1854989 --- /dev/null +++ b/src/engine/shared/network_server.cpp @@ -0,0 +1,668 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + +#include <engine/console.h> + +#include <stdio.h> +#include "config.h" +#include "netban.h" +#include "network.h" +#include <engine/external/md5/md5.h> +#include <engine/message.h> +#include <engine/shared/protocol.h> + +//TODO: reduce dummy map size +const int DummyMapCrc = 0xbeae0b9f; +static const unsigned char g_aDummyMapData[] = {0x44,0x41,0x54,0x41,0x04,0x00,0x00,0x00,0x15,0x02,0x00,0x00,0xC8,0x01,0x00,0x00,0x05,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4C,0x01,0x00,0x00,0x4D,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x6C,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0xE0,0x00,0x00,0x00,0x44,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x42,0x00,0x00,0x00,0x98,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x14,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x04,0x00,0x3C,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x01,0x00,0x04,0x00,0x3C,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE5,0xED,0xE1,0xC7,0x80,0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x05,0x00,0x28,0x00,0x00,0x00,0x90,0x72,0xDE,0x98,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xE4,0xE1,0xF5,0xD1,0x80,0x80,0x80,0xF3,0x00,0x80,0x80,0x80,0x01,0x00,0x05,0x00,0x5C,0x00,0x00,0x00,0x90,0x72,0xDE,0x98,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,0xE5,0xED,0xE1,0xC7,0x80,0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x20,0xA1,0xEA,0x00,0x63,0xE7,0x3D,0x44,0x0C,0x00,0x00,0x00,0x00,0x00,0x80,0x40,0x00,0x00,0x8D,0x42,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x78,0x9C,0x63,0x38,0xFD,0xF9,0xBF,0xC3,0x8D,0x6F,0xFF,0x19,0x4C,0x79,0x18,0xC0,0x34,0x90,0x7F,0x40,0x9D,0x93,0x01,0xC4,0x07,0xD3,0x0D,0x0C,0x60,0x1C,0x07,0xA4,0x5A,0x80,0x78,0x1D,0x10,0xFF,0x67,0xC0,0xE4,0x9F,0x01,0xE2,0x17,0x50,0x36,0x36,0x3E,0x1C,0xB0,0xA0,0xB1,0xA1,0xF8,0x3F,0x10,0x80,0x84,0x60,0x34,0x00,0x3E,0x5E,0x23,0x81,0x78,0x9C,0x63,0x60,0x40,0x05,0x00,0x00,0x10,0x00,0x01}; + +static SECURITY_TOKEN ToSecurityToken(const unsigned char* pData) +{ + return (int)pData[0] | (pData[1] << 8) | (pData[2] << 16) | (pData[3] << 24); +} + +bool CNetServer::Open(NETADDR BindAddr, CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags) +{ + // zero out the whole structure + mem_zero(this, sizeof(*this)); + + // open socket + m_Socket = net_udp_create(BindAddr); + if(!m_Socket.type) + return false; + + m_pNetBan = pNetBan; + + // clamp clients + m_MaxClients = MaxClients; + if(m_MaxClients > NET_MAX_CLIENTS) + m_MaxClients = NET_MAX_CLIENTS; + if(m_MaxClients < 1) + m_MaxClients = 1; + + m_MaxClientsPerIP = MaxClientsPerIP; + + m_NumConAttempts = 0; + m_TimeNumConAttempts = time_get(); + + m_VConnHighLoad = false; + m_VConnNum = 0; + m_VConnFirst = 0; + + secure_random_fill(m_SecurityTokenSeed, sizeof(m_SecurityTokenSeed)); + + for(int i = 0; i < NET_MAX_CLIENTS; i++) + m_aSlots[i].m_Connection.Init(m_Socket, true); + + return true; +} + +int CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) +{ + m_pfnNewClient = pfnNewClient; + m_pfnDelClient = pfnDelClient; + m_UserPtr = pUser; + return 0; +} + +int CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_NEWCLIENT_NOAUTH pfnNewClientNoAuth, NETFUNC_CLIENTREJOIN pfnClientRejoin, NETFUNC_DELCLIENT pfnDelClient, void *pUser) +{ + m_pfnNewClient = pfnNewClient; + m_pfnNewClientNoAuth = pfnNewClientNoAuth; + m_pfnClientRejoin = pfnClientRejoin; + m_pfnDelClient = pfnDelClient; + m_UserPtr = pUser; + return 0; +} + +int CNetServer::Close() +{ + // TODO: implement me + return 0; +} + +int CNetServer::Drop(int ClientID, const char *pReason) +{ + // TODO: insert lots of checks here + /*NETADDR Addr = ClientAddr(ClientID); + + dbg_msg("net_server", "client dropped. cid=%d ip=%d.%d.%d.%d reason=\"%s\"", + ClientID, + Addr.ip[0], Addr.ip[1], Addr.ip[2], Addr.ip[3], + pReason + );*/ + if(m_pfnDelClient) + m_pfnDelClient(ClientID, pReason, m_UserPtr); + + m_aSlots[ClientID].m_Connection.Disconnect(pReason); + + return 0; +} + +int CNetServer::Update() +{ + for(int i = 0; i < MaxClients(); i++) + { + m_aSlots[i].m_Connection.Update(); + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR && + (!m_aSlots[i].m_Connection.m_TimeoutProtected || + !m_aSlots[i].m_Connection.m_TimeoutSituation)) + { + Drop(i, m_aSlots[i].m_Connection.ErrorString()); + } + } + + return 0; +} + +SECURITY_TOKEN CNetServer::GetToken(const NETADDR &Addr) +{ + md5_state_t md5; + md5_byte_t digest[16]; + SECURITY_TOKEN SecurityToken; + md5_init(&md5); + + md5_append(&md5, (unsigned char*)m_SecurityTokenSeed, sizeof(m_SecurityTokenSeed)); + md5_append(&md5, (unsigned char*)&Addr, sizeof(Addr)); + + md5_finish(&md5, digest); + SecurityToken = ToSecurityToken(digest); + + if (SecurityToken == NET_SECURITY_TOKEN_UNKNOWN || + SecurityToken == NET_SECURITY_TOKEN_UNSUPPORTED) + SecurityToken = 1; + + return SecurityToken; +} + +void CNetServer::SendControl(NETADDR &Addr, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken) +{ + CNetBase::SendControlMsg(m_Socket, &Addr, 0, ControlMsg, pExtra, ExtraSize, SecurityToken); +} + +int CNetServer::NumClientsWithAddr(NETADDR Addr) +{ + NETADDR ThisAddr = Addr, OtherAddr; + + int FoundAddr = 0; + ThisAddr.port = 0; + + for(int i = 0; i < MaxClients(); ++i) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE || + (m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR && + (!m_aSlots[i].m_Connection.m_TimeoutProtected || + !m_aSlots[i].m_Connection.m_TimeoutSituation))) + continue; + + OtherAddr = *m_aSlots[i].m_Connection.PeerAddress(); + OtherAddr.port = 0; + if(!net_addr_comp(&ThisAddr, &OtherAddr)) + FoundAddr++; + } + + return FoundAddr; +} + + +int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, bool VanillaAuth) +{ + // check for sv_max_clients_per_ip + if (NumClientsWithAddr(Addr) + 1 > m_MaxClientsPerIP) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Only %d players with the same IP are allowed", m_MaxClientsPerIP); + CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, sizeof(aBuf), SecurityToken); + return -1; // failed to add client + } + + int Slot = -1; + for(int i = 0; i < MaxClients(); i++) + { + if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) + { + Slot = i; + break; + } + } + + if (Slot == -1) + { + const char FullMsg[] = "This server is full"; + CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, FullMsg, sizeof(FullMsg), SecurityToken); + + return -1; // failed to add client + } + + // init connection slot + m_aSlots[Slot].m_Connection.DirectInit(Addr, SecurityToken); + + if (VanillaAuth) + { + // client sequence is unknown if the auth was done + // connection-less + m_aSlots[Slot].m_Connection.SetUnknownSeq(); + // correct sequence + m_aSlots[Slot].m_Connection.SetSequence(6); + } + + if (g_Config.m_Debug) + { + char aAddrStr[NETADDR_MAXSTRSIZE]; + net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); + dbg_msg("security", "Client accepted %s", aAddrStr); + } + + + if (VanillaAuth) + m_pfnNewClientNoAuth(Slot, true, m_UserPtr); + else + m_pfnNewClient(Slot, m_UserPtr); + + return Slot; // done +} + +void CNetServer::SendMsgs(NETADDR &Addr, const CMsgPacker *Msgs[], int num) +{ + CNetPacketConstruct m_Construct; + mem_zero(&m_Construct, sizeof(m_Construct)); + unsigned char *pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize]; + + for (int i = 0; i < num; i++) + { + const CMsgPacker *pMsg = Msgs[i]; + CNetChunkHeader Header; + Header.m_Flags = NET_CHUNKFLAG_VITAL; + Header.m_Size = pMsg->Size(); + Header.m_Sequence = i+1; + pChunkData = Header.Pack(pChunkData); + mem_copy(pChunkData, pMsg->Data(), pMsg->Size()); + *((unsigned char*)pChunkData) <<= 1; + *((unsigned char*)pChunkData) |= 1; + pChunkData += pMsg->Size(); + m_Construct.m_NumChunks++; + } + + // + m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); + CNetBase::SendPacket(m_Socket, &Addr, &m_Construct, GetToken(Addr)); +} + +// connection-less msg packet without token-support +void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet) +{ + bool IsCtrl = Packet.m_Flags&NET_PACKETFLAG_CONTROL; + int CtrlMsg = m_RecvUnpacker.m_Data.m_aChunkData[0]; + + // log flooding + //TODO: remove + if (g_Config.m_Debug) + { + int64 Now = time_get(); + + if (Now - m_TimeNumConAttempts > time_freq()) + // reset + m_NumConAttempts = 0; + + m_NumConAttempts++; + + if (m_NumConAttempts > 100) + { + dbg_msg("security", "flooding detected"); + + m_TimeNumConAttempts = Now; + m_NumConAttempts = 0; + } + } + + + if (IsCtrl && CtrlMsg == NET_CTRLMSG_CONNECT) + { + if (g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0') + { + // detect flooding + int64 Now = time_get(); + if(Now <= m_VConnFirst + time_freq()) + { + m_VConnNum++; + } + else + { + m_VConnHighLoad = m_VConnNum > g_Config.m_SvVanConnPerSecond; + m_VConnNum = 1; + m_VConnFirst = Now; + } + + bool Flooding = m_VConnNum > g_Config.m_SvVanConnPerSecond || m_VConnHighLoad; + + if (g_Config.m_Debug && Flooding) + { + dbg_msg("security", "vanilla connection flooding detected"); + } + + // simulate accept + SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, + sizeof(SECURITY_TOKEN_MAGIC), NET_SECURITY_TOKEN_UNSUPPORTED); + + // Begin vanilla compatible token handshake + // The idea is to pack a security token in the gametick + // parameter of NETMSG_SNAPEMPTY. The Client then will + // return the token/gametick in NETMSG_INPUT, allowing + // us to validate the token. + // https://github.com/eeeee/ddnet/commit/b8e40a244af4e242dc568aa34854c5754c75a39a + + // Before we can send NETMSG_SNAPEMPTY, the client needs + // to load a map, otherwise it might crash. The map + // should be as small as is possible and directly available + // to the client. Therefor a dummy map is sent in the same + // packet. To reduce the traffic we'll fallback to a default + // map if there are too many connection attempts at once. + + // send mapchange + map data + con_ready + 3 x empty snap (with token) + CMsgPacker MapChangeMsg(NETMSG_MAP_CHANGE); + + if (Flooding) + { + // Fallback to dm1 + MapChangeMsg.AddString("dm1", 0); + MapChangeMsg.AddInt(0xf2159e6e); + MapChangeMsg.AddInt(5805); + } + else + { + // dummy map + MapChangeMsg.AddString("dummy", 0); + MapChangeMsg.AddInt(DummyMapCrc); + MapChangeMsg.AddInt(sizeof(g_aDummyMapData)); + } + + CMsgPacker MapDataMsg(NETMSG_MAP_DATA); + + if (Flooding) + { + // send empty map data to keep 0.6.4 support + MapDataMsg.AddInt(1); // last chunk + MapDataMsg.AddInt(0); // crc + MapDataMsg.AddInt(0); // chunk index + MapDataMsg.AddInt(0); // map size + MapDataMsg.AddRaw(NULL, 0); // map data + } + else + { + // send dummy map data + MapDataMsg.AddInt(1); // last chunk + MapDataMsg.AddInt(DummyMapCrc); // crc + MapDataMsg.AddInt(0); // chunk index + MapDataMsg.AddInt(sizeof(g_aDummyMapData)); // map size + MapDataMsg.AddRaw(g_aDummyMapData, sizeof(g_aDummyMapData)); // map data + } + + CMsgPacker ConReadyMsg(NETMSG_CON_READY); + + CMsgPacker SnapEmptyMsg(NETMSG_SNAPEMPTY); + SECURITY_TOKEN SecurityToken = GetVanillaToken(Addr); + SnapEmptyMsg.AddInt((int)SecurityToken); + SnapEmptyMsg.AddInt((int)SecurityToken + 1); + + // send all chunks/msgs in one packet + const CMsgPacker *Msgs[] = {&MapChangeMsg, &MapDataMsg, &ConReadyMsg, + &SnapEmptyMsg, &SnapEmptyMsg, &SnapEmptyMsg}; + SendMsgs(Addr, Msgs, 6); + } + else + { + // accept client directy + SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, + sizeof(SECURITY_TOKEN_MAGIC), NET_SECURITY_TOKEN_UNSUPPORTED); + + TryAcceptClient(Addr, NET_SECURITY_TOKEN_UNSUPPORTED); + } + } + else if(!IsCtrl && g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0') + { + CNetChunkHeader h; + + unsigned char *pData = Packet.m_aChunkData; + pData = h.Unpack(pData); + CUnpacker Unpacker; + Unpacker.Reset(pData, h.m_Size); + int Msg = Unpacker.GetInt() >> 1; + + if (Msg == NETMSG_INPUT) + { + SECURITY_TOKEN SecurityToken = Unpacker.GetInt(); + if (SecurityToken == GetVanillaToken(Addr)) + { + if (g_Config.m_Debug) + dbg_msg("security", "new client (vanilla handshake)"); + // try to accept client skipping auth state + TryAcceptClient(Addr, NET_SECURITY_TOKEN_UNSUPPORTED, true); + } + else if (g_Config.m_Debug) + dbg_msg("security", "invalid token (vanilla handshake)"); + + } + else + { + if (g_Config.m_Debug) + { + dbg_msg("security", "invalid preconn msg %d", Msg); + } + } + } +} + +void CNetServer::OnConnCtrlMsg(NETADDR &Addr, int ClientID, int ControlMsg, const CNetPacketConstruct &Packet) +{ + if (ControlMsg == NET_CTRLMSG_CONNECT) + { + // got connection attempt inside of valid session + // the client probably wants to reconnect + bool SupportsToken = Packet.m_DataSize >= + (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && + !mem_comp(&Packet.m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + + if (SupportsToken) + { + // response connection request with token + SECURITY_TOKEN Token = GetToken(Addr); + SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC), Token); + } + + if (g_Config.m_Debug) + dbg_msg("security", "client %d wants to reconnect", ClientID); + } + else if (ControlMsg == NET_CTRLMSG_ACCEPT && Packet.m_DataSize == 1 + sizeof(SECURITY_TOKEN)) + { + SECURITY_TOKEN Token = ToSecurityToken(&Packet.m_aChunkData[1]); + if (Token == GetToken(Addr)) + { + // correct token + // try to accept client + if (g_Config.m_Debug) + dbg_msg("security", "client %d reconnect"); + + // reset netconn and process rejoin + m_aSlots[ClientID].m_Connection.Reset(true); + m_pfnClientRejoin(ClientID, m_UserPtr); + } + } +} + +void CNetServer::OnTokenCtrlMsg(NETADDR &Addr, int ControlMsg, const CNetPacketConstruct &Packet) +{ + if (ClientExists(Addr)) + return; // silently ignore + + + if (Addr.type == NETTYPE_WEBSOCKET_IPV4) + { + // websocket client doesn't send token + // direct accept + SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC), NET_SECURITY_TOKEN_UNSUPPORTED); + TryAcceptClient(Addr, NET_SECURITY_TOKEN_UNSUPPORTED); + } + else if (ControlMsg == NET_CTRLMSG_CONNECT) + { + bool SupportsToken = Packet.m_DataSize >= + (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && + !mem_comp(&Packet.m_aChunkData[1], SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC)); + + if (SupportsToken) + { + // response connection request with token + SECURITY_TOKEN Token = GetToken(Addr); + SendControl(Addr, NET_CTRLMSG_CONNECTACCEPT, SECURITY_TOKEN_MAGIC, sizeof(SECURITY_TOKEN_MAGIC), Token); + } + } + else if (ControlMsg == NET_CTRLMSG_ACCEPT && Packet.m_DataSize == 1 + sizeof(SECURITY_TOKEN)) + { + SECURITY_TOKEN Token = ToSecurityToken(&Packet.m_aChunkData[1]); + if (Token == GetToken(Addr)) + { + // correct token + // try to accept client + if (g_Config.m_Debug) + dbg_msg("security", "new client (ddnet token)"); + TryAcceptClient(Addr, Token); + } + else + { + // invalid token + if (g_Config.m_Debug) + dbg_msg("security", "invalid token"); + } + } +} + +int CNetServer::GetClientSlot(const NETADDR &Addr) +{ + int Slot = -1; + + for(int i = 0; i < MaxClients(); i++) + { + if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE && + m_aSlots[i].m_Connection.State() != NET_CONNSTATE_ERROR && + net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0) + + { + Slot = i; + } + } + + return Slot; +} + +/* + TODO: chopp up this function into smaller working parts +*/ +int CNetServer::Recv(CNetChunk *pChunk) +{ + 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; + + // check if we just should drop the packet + char aBuf[128]; + if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf))) + { + // banned, reply with a message + CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf)+1, NET_SECURITY_TOKEN_UNSUPPORTED); + continue; + } + + if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0) + { + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) + { + pChunk->m_Flags = NETSENDFLAG_CONNLESS; + pChunk->m_ClientID = -1; + pChunk->m_Address = Addr; + pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; + pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; + return 1; + } + else + { + // drop invalid ctrl packets + if (m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && + m_RecvUnpacker.m_Data.m_DataSize == 0) + return 0; + + // normal packet, find matching slot + int Slot = GetClientSlot(Addr); + + if (Slot != -1) + { + // found + + // control + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL) + OnConnCtrlMsg(Addr, Slot, m_RecvUnpacker.m_Data.m_aChunkData[0], m_RecvUnpacker.m_Data); + + if(m_aSlots[Slot].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) + { + if(m_RecvUnpacker.m_Data.m_DataSize) + m_RecvUnpacker.Start(&Addr, &m_aSlots[Slot].m_Connection, Slot); + } + } + else + { + // not found, client that wants to connect + + if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && + m_RecvUnpacker.m_Data.m_DataSize > 1) + // got control msg with extra size (should support token) + OnTokenCtrlMsg(Addr, m_RecvUnpacker.m_Data.m_aChunkData[0], m_RecvUnpacker.m_Data); + else + // got connection-less ctrl or sys msg + OnPreConnMsg(Addr, m_RecvUnpacker.m_Data); + } + } + } + } + return 0; +} + +int CNetServer::Send(CNetChunk *pChunk) +{ + if(pChunk->m_DataSize >= NET_MAX_PAYLOAD) + { + dbg_msg("netserver", "packet payload too big. %d. dropping packet", pChunk->m_DataSize); + return -1; + } + + if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) + { + // send connectionless packet + CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize); + } + else + { + 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) + m_aSlots[pChunk->m_ClientID].m_Connection.Flush(); + } + else + { + //Drop(pChunk->m_ClientID, "Error sending data"); + } + } + return 0; +} + +void CNetServer::SetMaxClientsPerIP(int Max) +{ + // clamp + if(Max < 1) + Max = 1; + else if(Max > NET_MAX_CLIENTS) + Max = NET_MAX_CLIENTS; + + m_MaxClientsPerIP = Max; +} + +bool CNetServer::SetTimedOut(int ClientID, int OrigID) +{ + if (m_aSlots[ClientID].m_Connection.State() != NET_CONNSTATE_ERROR) + return false; + + m_aSlots[ClientID].m_Connection.SetTimedOut(ClientAddr(OrigID), m_aSlots[OrigID].m_Connection.SeqSequence(), m_aSlots[OrigID].m_Connection.AckSequence(), m_aSlots[OrigID].m_Connection.SecurityToken()); + m_aSlots[OrigID].m_Connection.Reset(); + return true; +} + +void CNetServer::SetTimeoutProtected(int ClientID) +{ + m_aSlots[ClientID].m_Connection.m_TimeoutProtected = true; +} + +int CNetServer::ResetErrorString(int ClientID) +{ + m_aSlots[ClientID].m_Connection.ResetErrorString(); + return 0; +} + +const char *CNetServer::ErrorString(int ClientID) +{ + return m_aSlots[ClientID].m_Connection.ErrorString(); +} diff --git a/src/engine/shared/packer.cpp b/src/engine/shared/packer.cpp new file mode 100644 index 0000000..788e564 --- /dev/null +++ b/src/engine/shared/packer.cpp @@ -0,0 +1,158 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + +#include "packer.h" +#include "compression.h" +#include "config.h" + +void CPacker::Reset() +{ + m_Error = 0; + m_pCurrent = m_aBuffer; + m_pEnd = m_pCurrent + PACKER_BUFFER_SIZE; +} + +void CPacker::AddInt(int i) +{ + if(m_Error) + return; + + // make sure that we have space enough + if(m_pEnd - m_pCurrent < 6) + { + dbg_break(); + m_Error = 1; + } + else + m_pCurrent = CVariableInt::Pack(m_pCurrent, i); +} + +void CPacker::AddString(const char *pStr, int Limit) +{ + if(m_Error) + return; + + // + if(Limit > 0) + { + while(*pStr && Limit != 0) + { + *m_pCurrent++ = *pStr++; + Limit--; + + if(m_pCurrent >= m_pEnd) + { + m_Error = 1; + break; + } + } + *m_pCurrent++ = 0; + } + else + { + while(*pStr) + { + *m_pCurrent++ = *pStr++; + + if(m_pCurrent >= m_pEnd) + { + m_Error = 1; + break; + } + } + *m_pCurrent++ = 0; + } +} + +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) + { + *m_pCurrent++ = *pSrc++; + Size--; + } +} + + +void CUnpacker::Reset(const void *pData, int Size) +{ + m_Error = 0; + m_pStart = (const unsigned char *)pData; + m_pEnd = m_pStart + Size; + m_pCurrent = m_pStart; +} + +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) + { + m_Error = 1; + return 0; + } + return i; +} + +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 + { + m_pCurrent++; + if(m_pCurrent == m_pEnd) + { + m_Error = 1;; + return ""; + } + } + m_pCurrent++; + + // sanitize all strings + if(SanitizeType&SANITIZE) + str_sanitize(pPtr); + else if(SanitizeType&SANITIZE_CC) + str_sanitize_cc(pPtr); + return SanitizeType&SKIP_START_WHITESPACES ? str_utf8_skip_whitespaces(pPtr) : pPtr; +} + +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) + { + m_Error = 1; + return 0; + } + + // "unpack" the data + m_pCurrent += Size; + return pPtr; +} diff --git a/src/engine/shared/packer.h b/src/engine/shared/packer.h new file mode 100644 index 0000000..bd04e36 --- /dev/null +++ b/src/engine/shared/packer.h @@ -0,0 +1,51 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_PACKER_H +#define ENGINE_SHARED_PACKER_H + + + +class CPacker +{ + enum + { + PACKER_BUFFER_SIZE=1024*2 + }; + + unsigned char m_aBuffer[PACKER_BUFFER_SIZE]; + unsigned char *m_pCurrent; + unsigned char *m_pEnd; + int m_Error; +public: + void Reset(); + 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; } +}; + +class CUnpacker +{ + const unsigned char *m_pStart; + const unsigned char *m_pCurrent; + const unsigned char *m_pEnd; + int m_Error; +public: + enum + { + SANITIZE=1, + SANITIZE_CC=2, + SKIP_START_WHITESPACES=4 + }; + + void Reset(const void *pData, int Size); + int GetInt(); + const char *GetString(int SanitizeType = SANITIZE); + const unsigned char *GetRaw(int Size); + bool Error() const { return m_Error; } +}; + +#endif diff --git a/src/engine/shared/protocol.h b/src/engine/shared/protocol.h new file mode 100644 index 0000000..096abe7 --- /dev/null +++ b/src/engine/shared/protocol.h @@ -0,0 +1,114 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_PROTOCOL_H +#define ENGINE_SHARED_PROTOCOL_H + +#include <base/system.h> + +/* + 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. + modc_connected is called on the client and + 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. +*/ + + +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 + NETMSG_CON_READY, // connection is ready, client should send start info + NETMSG_SNAP, // normal snapshot, multiple parts + NETMSG_SNAPEMPTY, // empty snapshot + NETMSG_SNAPSINGLE, // ? + NETMSG_SNAPSMALL, // + NETMSG_INPUTTIMING, // reports how off the input was + NETMSG_RCON_AUTH_STATUS,// result of the authentication + NETMSG_RCON_LINE, // line that should be printed to the remote console + + 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_AUTH, // + NETMSG_REQUEST_MAP_DATA,// + + NETMSG_AUTH_START, // + NETMSG_AUTH_RESPONSE, // + + // sent by both + NETMSG_PING, + NETMSG_PING_REPLY, + NETMSG_ERROR, + + // sent by server (todo: move it up) + NETMSG_RCON_CMD_ADD, + NETMSG_RCON_CMD_REM, +}; + +// this should be revised +enum +{ + SERVER_TICK_SPEED=50, + SERVER_FLAG_PASSWORD = 0x1, + + MAX_CLIENTS=64, + VANILLA_MAX_CLIENTS=16, + + MAX_INPUT_SIZE=128, + MAX_SNAPSHOT_PACKSIZE=900, + + MAX_NAME_LENGTH=16, + MAX_CLAN_LENGTH=12, + + // message packing + MSGFLAG_VITAL=1, + MSGFLAG_FLUSH=2, + MSGFLAG_NORECORD=4, + MSGFLAG_RECORD=8, + MSGFLAG_NOSEND=16 +}; + +enum +{ + VERSION_VANILLA = 0, + VERSION_DDRACE = 1, + VERSION_DDNET_OLD = 2, + VERSION_DDNET_WHISPER = 217, + VERSION_DDNET_GOODHOOK = 221, + VERSION_DDNET_EXTRATUNES = 302, + VERSION_DDNET_RCONPROTECT = 408, + VERSION_DDNET_ANTIPING_PROJECTILE = 11030, // th (x) onby + VERSION_DDNET_HOOKDURATION_TUNE = 607, + VERSION_DDNET_FIREDELAY_TUNE = 701, + VERSION_DDNET_UPDATER_FIXED = 707, + VERSION_DDNET_GAMETICK = 10042 // th (x) onby +}; + +#endif diff --git a/src/engine/shared/ringbuffer.cpp b/src/engine/shared/ringbuffer.cpp new file mode 100644 index 0000000..781e523 --- /dev/null +++ b/src/engine/shared/ringbuffer.cpp @@ -0,0 +1,193 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> + +#include "ringbuffer.h" + +CRingBufferBase::CItem *CRingBufferBase::NextBlock(CItem *pItem) +{ + if(pItem->m_pNext) + return pItem->m_pNext; + return m_pFirst; +} + +CRingBufferBase::CItem *CRingBufferBase::PrevBlock(CItem *pItem) +{ + if(pItem->m_pPrev) + return pItem->m_pPrev; + return m_pLast; +} + +CRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem) +{ + // make sure that this block and previous block is free + if(!pItem->m_Free || !pItem->m_pPrev || !pItem->m_pPrev->m_Free) + return 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; +} + +void CRingBufferBase::Init(void *pMemory, int Size, int Flags) +{ + mem_zero(pMemory, Size); + m_Size = (Size)/sizeof(CItem)*sizeof(CItem); + m_pFirst = (CItem *)pMemory; + m_pFirst->m_Free = 1; + m_pFirst->m_Size = m_Size; + m_pLast = m_pFirst; + m_pProduce = m_pFirst; + m_pConsume = m_pFirst; + m_Flags = Flags; + +} + +void *CRingBufferBase::Allocate(int Size) +{ + int WantedSize = (Size+sizeof(CItem)+sizeof(CItem)-1)/sizeof(CItem)*sizeof(CItem); + CItem *pBlock = 0; + + // check if we even can fit this block + if(WantedSize > m_Size) + return 0; + + while(1) + { + // check for space + if(m_pProduce->m_Free) + { + if(m_pProduce->m_Size >= WantedSize) + pBlock = m_pProduce; + else + { + // wrap around to try to find a block + if(m_pFirst->m_Free && m_pFirst->m_Size >= WantedSize) + pBlock = m_pFirst; + } + } + + if(pBlock) + break; + else + { + // we have no block, check our policy and see what todo + if(m_Flags&FLAG_RECYCLE) + { + if(!PopFirst()) + return 0; + } + else + return 0; + } + } + + // okey, we have our block + + // split the block if needed + if(pBlock->m_Size > WantedSize+(int)sizeof(CItem)) + { + CItem *pNewItem = (CItem *)((char *)pBlock + WantedSize); + pNewItem->m_pPrev = pBlock; + pNewItem->m_pNext = pBlock->m_pNext; + 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); +} + +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) + { + 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); + return 1; +} + + +void *CRingBufferBase::Prev(void *pCurrent) +{ + CItem *pItem = ((CItem *)pCurrent) - 1; + + while(1) + { + pItem = PrevBlock(pItem); + if(pItem == m_pProduce) + return 0; + if(!pItem->m_Free) + return pItem+1; + } +} + +void *CRingBufferBase::Next(void *pCurrent) +{ + CItem *pItem = ((CItem *)pCurrent) - 1; + + while(1) + { + pItem = NextBlock(pItem); + if(pItem == m_pProduce) + return 0; + if(!pItem->m_Free) + return pItem+1; + } +} + +void *CRingBufferBase::First() +{ + if(m_pConsume->m_Free) + return 0; + return (void *)(m_pConsume+1); +} + +void *CRingBufferBase::Last() +{ + return Prev(m_pProduce+1); +} diff --git a/src/engine/shared/ringbuffer.h b/src/engine/shared/ringbuffer.h new file mode 100644 index 0000000..acce232 --- /dev/null +++ b/src/engine/shared/ringbuffer.h @@ -0,0 +1,67 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_RINGBUFFER_H +#define ENGINE_SHARED_RINGBUFFER_H + +typedef struct RINGBUFFER RINGBUFFER; + +class CRingBufferBase +{ + class CItem + { + public: + CItem *m_pPrev; + CItem *m_pNext; + int m_Free; + int m_Size; + }; + + CItem *m_pProduce; + CItem *m_pConsume; + + CItem *m_pFirst; + CItem *m_pLast; + + 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: + enum + { + // Will start to destroy items to try to fit the next one + FLAG_RECYCLE=1 + }; +}; + +template<typename T, int TSIZE, int TFLAGS=0> +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(); } + + T *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); } + T *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); } + T *First() { return (T*)CRingBufferBase::First(); } + T *Last() { return (T*)CRingBufferBase::Last(); } +}; + +#endif diff --git a/src/engine/shared/serverbrowser.cpp b/src/engine/shared/serverbrowser.cpp new file mode 100644 index 0000000..45bc441 --- /dev/null +++ b/src/engine/shared/serverbrowser.cpp @@ -0,0 +1,32 @@ +#include <engine/serverbrowser.h> +#include <base/system.h> + +bool IsRace(const CServerInfo *pInfo) +{ + return str_find_nocase(pInfo->m_aGameType, "race") + || str_find_nocase(pInfo->m_aGameType, "fastcap"); +} + +bool IsDDRace(const CServerInfo *pInfo) +{ + return str_find_nocase(pInfo->m_aGameType, "ddrace") + || str_find_nocase(pInfo->m_aGameType, "mkrace"); +} + +bool IsDDNet(const CServerInfo *pInfo) +{ + return str_find_nocase(pInfo->m_aGameType, "ddracenet") + || str_find_nocase(pInfo->m_aGameType, "ddnet"); +} + +bool Is64Player(const CServerInfo *pInfo) +{ + return str_find(pInfo->m_aGameType, "64") + || str_find(pInfo->m_aName, "64") + || IsDDNet(pInfo); +} + +bool IsPlus(const CServerInfo *pInfo) +{ + return str_find(pInfo->m_aGameType, "+"); +} diff --git a/src/engine/shared/snapshot.cpp b/src/engine/shared/snapshot.cpp new file mode 100644 index 0000000..9f62ef7 --- /dev/null +++ b/src/engine/shared/snapshot.cpp @@ -0,0 +1,544 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "snapshot.h" +#include "compression.h" + +// CSnapshot + +CSnapshotItem *CSnapshot::GetItem(int Index) +{ + return (CSnapshotItem *)(DataStart() + Offsets()[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); +} + +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; +} + +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]; + } + return Crc; +} + +void CSnapshot::DebugDump() +{ + dbg_msg("snapshot", "data_size=%d num_items=%d", m_DataSize, m_NumItems); + for(int i = 0; i < m_NumItems; i++) + { + CSnapshotItem *pItem = GetItem(i); + int Size = GetItemSize(i); + dbg_msg("snapshot", "\ttype=%d id=%d", pItem->Type(), pItem->ID()); + for(int b = 0; b < Size/4; b++) + dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, pItem->Data()[b], pItem->Data()[b]); + } +} + + +// CSnapshotDelta + +struct CItemList +{ + int m_Num; + int m_aKeys[64]; + int m_aIndex[64]; +}; + +enum +{ + HASHLIST_SIZE = 256, +}; + +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(); + int HashID = ((Key>>12)&0xf0) | (Key&0xf); + if(pHashlist[HashID].m_Num != 64) + { + pHashlist[HashID].m_aIndex[pHashlist[HashID].m_Num] = i; + pHashlist[HashID].m_aKeys[pHashlist[HashID].m_Num] = Key; + pHashlist[HashID].m_Num++; + } + } +} + +static int GetItemIndexHashed(int Key, const CItemList *pHashlist) +{ + int HashID = ((Key>>12)&0xf0) | (Key&0xf); + for(int i = 0; i < pHashlist[HashID].m_Num; i++) + { + if(pHashlist[HashID].m_aKeys[i] == Key) + return pHashlist[HashID].m_aIndex[i]; + } + + return -1; +} + +static int DiffItem(int *pPast, int *pCurrent, int *pOut, int Size) +{ + int Needed = 0; + while(Size) + { + *pOut = *pCurrent-*pPast; + Needed |= *pOut; + pOut++; + pPast++; + pCurrent++; + Size--; + } + + return Needed; +} + +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); + m_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char*)aBuf) * 8; + } + + pOut++; + pPast++; + pDiff++; + Size--; + } +} + +CSnapshotDelta::CSnapshotDelta() +{ + mem_zero(m_aItemSizes, sizeof(m_aItemSizes)); + mem_zero(m_aSnapshotDataRate, sizeof(m_aSnapshotDataRate)); + mem_zero(m_aSnapshotDataUpdates, sizeof(m_aSnapshotDataUpdates)); + m_SnapshotCurrent = 0; + mem_zero(&m_Empty, sizeof(m_Empty)); +} + +void CSnapshotDelta::SetStaticsize(int ItemType, int Size) +{ + m_aItemSizes[ItemType] = Size; +} + +CSnapshotDelta::CData *CSnapshotDelta::EmptyDelta() +{ + return &m_Empty; +} + +// TODO: OPT: this should be made much faster +int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData) +{ + CData *pDelta = (CData *)pDstData; + int *pData = (int *)pDelta->m_pData; + int i, ItemSize, PastIndex; + CSnapshotItem *pFromItem; + CSnapshotItem *pCurItem; + 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); + + // pack deleted stuff + for(i = 0; i < pFrom->NumItems(); i++) + { + pFromItem = pFrom->GetItem(i); + if(GetItemIndexHashed(pFromItem->Key(), Hashlist) == -1) + { + // deleted + pDelta->m_NumDeletedItems++; + *pData = pFromItem->Key(); + pData++; + } + } + + GenerateHash(Hashlist, pFrom); + int aPastIndecies[1024]; + + // fetch previous indices + // we do this as a separate pass because it helps the cache + const int NumItems = pTo->NumItems(); + for(i = 0; i < NumItems; i++) + { + pCurItem = pTo->GetItem(i); // O(1) .. O(n) + aPastIndecies[i] = GetItemIndexHashed(pCurItem->Key(), Hashlist); // O(n) .. O(n^n) + } + + for(i = 0; i < NumItems; i++) + { + // do delta + ItemSize = pTo->GetItemSize(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()]) + *pData++ = ItemSize/4; + pData += ItemSize/4; + pDelta->m_NumUpdateItems++; + } + } + else + { + *pData++ = pCurItem->Type(); + *pData++ = pCurItem->ID(); + if(!m_aItemSizes[pCurItem->Type()]) + *pData++ = ItemSize/4; + + mem_copy(pData, pCurItem->Data(), ItemSize); + SizeCount += ItemSize; + pData += ItemSize/4; + pDelta->m_NumUpdateItems++; + Count++; + } + } + + if(0) + { + dbg_msg("snapshot", "%d %d %d", + pDelta->m_NumDeletedItems, + pDelta->m_NumUpdateItems, + pDelta->m_NumTempItems); + } + + /* + // 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)); + //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items+pDelta->num_update_items]), temp, pDelta->num_temp_items*sizeof(int)); + //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); +} + +static int RangeCheck(void *pEnd, void *pPtr, int Size) +{ + if((const char *)pPtr + Size > (const char *)pEnd) + return -1; + return 0; +} + +int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData, int DataSize) +{ + CSnapshotBuilder Builder; + 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; + if(pData > pEnd) + return -1; + + // copy all non deleted stuff + for(int i = 0; i < pFrom->NumItems(); i++) + { + // dbg_assert(0, "fail!"); + pFromItem = pFrom->GetItem(i); + ItemSize = pFrom->GetItemSize(i); + Keep = 1; + for(int d = 0; d < pDelta->m_NumDeletedItems; d++) + { + if(pDeleted[d] == pFromItem->Key()) + { + Keep = 0; + break; + } + } + + if(Keep) + { + // keep it + mem_copy( + Builder.NewItem(pFromItem->Type(), pFromItem->ID(), ItemSize), + 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 ((unsigned int) Type < sizeof(m_aItemSizes) && m_aItemSizes[Type]) + ItemSize = m_aItemSizes[Type]; + else + { + if(pData+1 > pEnd) + return -2; + ItemSize = (*pData++) * 4; + } + m_SnapshotCurrent = Type; + + if(m_SnapshotCurrent < 0 || m_SnapshotCurrent > 0xFFFF) return -3; + 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) + { + // we got an update so we need pTo apply the diff + UndiffItem((int *)pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize/4); + m_aSnapshotDataUpdates[m_SnapshotCurrent]++; + } + else // no previous, just copy the pData + { + mem_copy(pNewData, pData, ItemSize); + m_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize*8; + m_aSnapshotDataUpdates[m_SnapshotCurrent]++; + } + + pData += ItemSize/4; + } + + // finish up + return Builder.Finish(pTo); +} + + +// CSnapshotStorage + +void CSnapshotStorage::Init() +{ + m_pFirst = 0; + m_pLast = 0; +} + +void CSnapshotStorage::PurgeAll() +{ + CHolder *pHolder = m_pFirst; + CHolder *pNext; + + while(pHolder) + { + pNext = pHolder->m_pNext; + mem_free(pHolder); + pHolder = pNext; + } + + // no more snapshots in storage + m_pFirst = 0; + m_pLast = 0; +} + +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; + + m_pFirst = pNext; + pNext->m_pPrev = 0x0; + + pHolder = pNext; + } + + // no more snapshots in storage + m_pFirst = 0; + m_pLast = 0; +} + +void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt) +{ + // 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; + pHolder->m_SnapSize = DataSize; + pHolder->m_pSnap = (CSnapshot*)(pHolder+1); + mem_copy(pHolder->m_pSnap, pData, DataSize); + + if(CreateAlt) // create alternative if wanted + { + pHolder->m_pAltSnap = (CSnapshot*)(((char *)pHolder->m_pSnap) + DataSize); + mem_copy(pHolder->m_pAltSnap, pData, DataSize); + } + else + pHolder->m_pAltSnap = 0; + + + // link + pHolder->m_pNext = 0; + pHolder->m_pPrev = m_pLast; + if(m_pLast) + m_pLast->m_pNext = pHolder; + else + m_pFirst = pHolder; + m_pLast = pHolder; +} + +int CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData) +{ + CHolder *pHolder = m_pFirst; + + while(pHolder) + { + if(pHolder->m_Tick == Tick) + { + if(pTagtime) + *pTagtime = pHolder->m_Tagtime; + if(ppData) + *ppData = pHolder->m_pSnap; + if(ppAltData) + *ppAltData = pHolder->m_pAltSnap; + return pHolder->m_SnapSize; + } + + pHolder = pHolder->m_pNext; + } + + return -1; +} + +// CSnapshotBuilder + +void CSnapshotBuilder::Init() +{ + m_DataSize = 0; + m_NumItems = 0; +} + +CSnapshotItem *CSnapshotBuilder::GetItem(int Index) +{ + return (CSnapshotItem *)&(m_aData[m_aOffsets[Index]]); +} + +int *CSnapshotBuilder::GetItemData(int Key) +{ + int i; + for(i = 0; i < m_NumItems; i++) + { + if(GetItem(i)->Key() == Key) + return (int *)GetItem(i)->Data(); + } + return 0; +} + +int CSnapshotBuilder::Finish(void *SpnapData) +{ + // flattern and make the snapshot + CSnapshot *pSnap = (CSnapshot *)SpnapData; + int OffsetSize = sizeof(int)*m_NumItems; + pSnap->m_DataSize = m_DataSize; + pSnap->m_NumItems = m_NumItems; + mem_copy(pSnap->Offsets(), m_aOffsets, OffsetSize); + mem_copy(pSnap->DataStart(), m_aData, m_DataSize); + return sizeof(CSnapshot) + OffsetSize + m_DataSize; +} + +void *CSnapshotBuilder::NewItem(int Type, int ID, int Size) +{ + if(m_DataSize + sizeof(CSnapshotItem) + Size >= CSnapshot::MAX_SIZE || + m_NumItems+1 >= MAX_ITEMS) + { + dbg_assert(m_DataSize < CSnapshot::MAX_SIZE, "too much data"); + dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); + return 0; + } + + CSnapshotItem *pObj = (CSnapshotItem *)(m_aData + m_DataSize); + + mem_zero(pObj, sizeof(CSnapshotItem) + Size); + pObj->m_TypeAndID = (Type<<16)|ID; + m_aOffsets[m_NumItems] = m_DataSize; + m_DataSize += sizeof(CSnapshotItem) + Size; + m_NumItems++; + + return pObj->Data(); +} diff --git a/src/engine/shared/snapshot.h b/src/engine/shared/snapshot.h new file mode 100644 index 0000000..ebd13f2 --- /dev/null +++ b/src/engine/shared/snapshot.h @@ -0,0 +1,138 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SHARED_SNAPSHOT_H +#define ENGINE_SHARED_SNAPSHOT_H + +#include <base/system.h> + +// CSnapshot + +class CSnapshotItem +{ +public: + int m_TypeAndID; + + int *Data() { return (int *)(this+1); } + int Type() { return m_TypeAndID>>16; } + int ID() { return m_TypeAndID&0xffff; } + int Key() { return m_TypeAndID; } +}; + + +class CSnapshot +{ + friend class CSnapshotBuilder; + int m_DataSize; + int m_NumItems; + + int *Offsets() const { return (int *)(this+1); } + char *DataStart() const { return (char*)(Offsets()+m_NumItems); } + +public: + enum + { + MAX_SIZE=64*1024 + }; + + void Clear() { m_DataSize = 0; m_NumItems = 0; } + int NumItems() const { return m_NumItems; } + CSnapshotItem *GetItem(int Index); + int GetItemSize(int Index); + int GetItemIndex(int Key); + + int Crc(); + void DebugDump(); +}; + + +// CSnapshotDelta + +class CSnapshotDelta +{ +public: + class CData + { + public: + int m_NumDeletedItems; + int m_NumUpdateItems; + int m_NumTempItems; // needed? + int m_pData[1]; + }; + +private: + // TODO: strange arbitrary number + short m_aItemSizes[64]; + int m_aSnapshotDataRate[0xffff]; + int m_aSnapshotDataUpdates[0xffff]; + int m_SnapshotCurrent; + CData m_Empty; + + void UndiffItem(int *pPast, int *pDiff, int *pOut, int Size); + +public: + CSnapshotDelta(); + int GetDataRate(int Index) { return m_aSnapshotDataRate[Index]; } + int GetDataUpdates(int Index) { return m_aSnapshotDataUpdates[Index]; } + void SetStaticsize(int ItemType, int Size); + CData *EmptyDelta(); + int CreateDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData); + int UnpackDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData, int DataSize); +}; + + +// CSnapshotStorage + +class CSnapshotStorage +{ +public: + class CHolder + { + 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; + + void Init(); + void PurgeAll(); + void PurgeUntil(int Tick); + void Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt); + int Get(int Tick, int64 *Tagtime, CSnapshot **pData, CSnapshot **ppAltData); +}; + +class CSnapshotBuilder +{ + enum + { + MAX_ITEMS = 1024 + }; + + char m_aData[CSnapshot::MAX_SIZE]; + int m_DataSize; + + int m_aOffsets[MAX_ITEMS]; + int m_NumItems; + +public: + void Init(); + + void *NewItem(int Type, int ID, int Size); + + CSnapshotItem *GetItem(int Index); + int *GetItemData(int Key); + + int Finish(void *Snapdata); +}; + + +#endif // ENGINE_SNAPSHOT_H diff --git a/src/engine/shared/storage.cpp b/src/engine/shared/storage.cpp new file mode 100644 index 0000000..8c69c85 --- /dev/null +++ b/src/engine/shared/storage.cpp @@ -0,0 +1,469 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <engine/storage.h> +#include "linereader.h" + +// compiled-in data-dir path +#define DATA_DIR "data" + +class CStorage : public IStorage +{ +public: + enum + { + MAX_PATHS = 16, + MAX_PATH_LENGTH = 512 + }; + + char m_aaStoragePaths[MAX_PATHS][MAX_PATH_LENGTH]; + int m_NumPaths; + char m_aDatadir[MAX_PATH_LENGTH]; + char m_aUserdir[MAX_PATH_LENGTH]; + char m_aCurrentdir[MAX_PATH_LENGTH]; + char m_aBinarydir[MAX_PATH_LENGTH]; + + CStorage() + { + mem_zero(m_aaStoragePaths, sizeof(m_aaStoragePaths)); + m_NumPaths = 0; + m_aDatadir[0] = 0; + m_aUserdir[0] = 0; + } + + int Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) + { + // get userdir + fs_storage_path(pApplicationName, m_aUserdir, sizeof(m_aUserdir)); + + // get datadir + FindDatadir(ppArguments[0]); + + // get currentdir + if(!fs_getcwd(m_aCurrentdir, sizeof(m_aCurrentdir))) + m_aCurrentdir[0] = 0; + + // load paths from storage.cfg + LoadPaths(ppArguments[0]); + + if(!m_NumPaths) + { + dbg_msg("storage", "using standard paths"); + AddDefaultPaths(); + } + + // add save directories + if(StorageType != STORAGETYPE_BASIC && m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE]))) + { + char aPath[MAX_PATH_LENGTH]; + if(StorageType == STORAGETYPE_CLIENT) + { + fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto/stats", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath))); + } + fs_makedir(GetPath(TYPE_SAVE, "dumps", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "demos", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "demos/auto", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "editor", aPath, sizeof(aPath))); + fs_makedir(GetPath(TYPE_SAVE, "ghosts", aPath, sizeof(aPath))); + } + + return m_NumPaths ? 0 : 1; + } + + void LoadPaths(const char *pArgv0) + { + // check current directory + IOHANDLE File = io_open("storage.cfg", IOFLAG_READ); + if(!File) + { + // check 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 aBuffer[MAX_PATH_LENGTH]; + str_copy(aBuffer, pArgv0, Pos+1); + 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"); + return; + } + } + + char *pLine; + CLineReader LineReader; + LineReader.Init(File); + + while((pLine = LineReader.Get())) + { + if(str_length(pLine) > 9 && !str_comp_num(pLine, "add_path ", 9)) + AddPath(pLine+9); + } + + io_close(File); + + if(!m_NumPaths) + dbg_msg("storage", "no paths found in storage.cfg"); + } + + void AddDefaultPaths() + { + AddPath("$USERDIR"); + AddPath("$DATADIR"); + AddPath("$CURRENTDIR"); + } + + void AddPath(const char *pPath) + { + if(m_NumPaths >= MAX_PATHS || !pPath[0]) + return; + + if(!str_comp(pPath, "$USERDIR")) + { + if(m_aUserdir[0]) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aUserdir, MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$USERDIR' ('%s')", m_aUserdir); + } + } + else if(!str_comp(pPath, "$DATADIR")) + { + if(m_aDatadir[0]) + { + str_copy(m_aaStoragePaths[m_NumPaths++], m_aDatadir, MAX_PATH_LENGTH); + dbg_msg("storage", "added path '$DATADIR' ('%s')", m_aDatadir); + } + } + else if(!str_comp(pPath, "$CURRENTDIR")) + { + m_aaStoragePaths[m_NumPaths++][0] = 0; + dbg_msg("storage", "added path '$CURRENTDIR' ('%s')", m_aCurrentdir); + } + else + { + if(fs_is_dir(pPath)) + { + str_copy(m_aaStoragePaths[m_NumPaths++], pPath, MAX_PATH_LENGTH); + dbg_msg("storage", "added path '%s'", pPath); + } + } + } + + void FindDatadir(const char *pArgv0) + { + // 1) use data-dir in PWD if present + if(fs_is_dir("data/mapres")) + { + str_copy(m_aDatadir, "data", sizeof(m_aDatadir)); + str_copy(m_aBinarydir, "", sizeof(m_aBinarydir)); + 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)); + str_copy(m_aBinarydir, "", sizeof(m_aBinarydir)); + 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_copy(m_aBinarydir, aBaseDir, sizeof(m_aBinarydir)); + 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 + { + const char *aDirs[] = { + "/usr/share/teeworlds/data", + "/usr/share/games/teeworlds/data", + "/usr/local/share/teeworlds/data", + "/usr/local/share/games/teeworlds/data", + "/usr/pkg/share/teeworlds/data", + "/usr/pkg/share/games/teeworlds/data", + "/opt/teeworlds/data" + }; + const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); + + int i; + for (i = 0; i < DirsCount; i++) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s/mapres", aDirs[i]); + if(fs_is_dir(aBuf)) + { + str_copy(m_aBinarydir, aDirs[i], sizeof(aDirs[i])-5); + str_copy(m_aDatadir, aDirs[i], sizeof(m_aDatadir)); + return; + } + } + } + #endif + + // no data-dir found + dbg_msg("storage", "warning no data directory found"); + } + + + virtual void ListDirectoryInfo(int Type, const char *pPath, FS_LISTDIR_INFO_CALLBACK pfnCallback, void *pUser) + { + char aBuffer[MAX_PATH_LENGTH]; + if(Type == TYPE_ALL) + { + // list all available directories + for(int i = 0; i < m_NumPaths; ++i) + fs_listdir_info(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser); + } + else if(Type >= 0 && Type < m_NumPaths) + { + // list wanted directory + fs_listdir_info(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser); + } + } + + virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) + { + char aBuffer[MAX_PATH_LENGTH]; + if(Type == TYPE_ALL) + { + // list all available directories + for(int i = 0; i < m_NumPaths; ++i) + fs_listdir(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser); + } + else if(Type >= 0 && Type < m_NumPaths) + { + // list wanted directory + fs_listdir(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser); + } + } + + virtual const char *GetPath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) + { + 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]; + if(!pBuffer) + { + pBuffer = aBuffer; + BufferSize = sizeof(aBuffer); + } + + if(Flags&IOFLAG_WRITE) + { + return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags); + } + else + { + IOHANDLE Handle = 0; + + if(Type == TYPE_ALL) + { + // check all available directories + for(int i = 0; i < m_NumPaths; ++i) + { + Handle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags); + if(Handle) + return Handle; + } + } + else if(Type >= 0 && Type < m_NumPaths) + { + // check wanted directory + Handle = io_open(GetPath(Type, pFilename, pBuffer, BufferSize), Flags); + if(Handle) + return Handle; + } + } + + pBuffer[0] = 0; + return 0; + } + + struct CFindCBData + { + CStorage *pStorage; + const char *pFilename; + const char *pPath; + char *pBuffer; + int BufferSize; + }; + + static int FindFileCallback(const char *pName, int IsDir, int Type, void *pUser) + { + CFindCBData Data = *static_cast<CFindCBData *>(pUser); + if(IsDir) + { + if(pName[0] == '.') + return 0; + + // search within the folder + char aBuf[MAX_PATH_LENGTH]; + char aPath[MAX_PATH_LENGTH]; + str_format(aPath, sizeof(aPath), "%s/%s", Data.pPath, pName); + Data.pPath = aPath; + fs_listdir(Data.pStorage->GetPath(Type, aPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data); + if(Data.pBuffer[0]) + return 1; + } + else if(!str_comp(pName, Data.pFilename)) + { + // found the file = end + str_format(Data.pBuffer, Data.BufferSize, "%s/%s", Data.pPath, Data.pFilename); + return 1; + } + + return 0; + } + + virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) + { + if(BufferSize < 1) + return false; + + pBuffer[0] = 0; + char aBuf[MAX_PATH_LENGTH]; + CFindCBData Data; + Data.pStorage = this; + Data.pFilename = pFilename; + Data.pPath = pPath; + Data.pBuffer = pBuffer; + Data.BufferSize = BufferSize; + + if(Type == TYPE_ALL) + { + // search within all available directories + for(int i = 0; i < m_NumPaths; ++i) + { + fs_listdir(GetPath(i, pPath, aBuf, sizeof(aBuf)), FindFileCallback, i, &Data); + if(pBuffer[0]) + return true; + } + } + else if(Type >= 0 && Type < m_NumPaths) + { + // search within wanted directory + fs_listdir(GetPath(Type, pPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data); + } + + return pBuffer[0] != 0; + } + + virtual bool RemoveFile(const char *pFilename, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + + char aBuffer[MAX_PATH_LENGTH]; + return !fs_remove(GetPath(Type, pFilename, aBuffer, sizeof(aBuffer))); + } + + virtual bool RemoveBinaryFile(const char *pFilename) + { + char aBuffer[MAX_PATH_LENGTH]; + return !fs_remove(GetBinaryPath(pFilename, aBuffer, sizeof(aBuffer))); + } + + virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + char aOldBuffer[MAX_PATH_LENGTH]; + char aNewBuffer[MAX_PATH_LENGTH]; + return !fs_rename(GetPath(Type, pOldFilename, aOldBuffer, sizeof(aOldBuffer)), GetPath(Type, pNewFilename, aNewBuffer, sizeof (aNewBuffer))); + } + + virtual bool RenameBinaryFile(const char* pOldFilename, const char* pNewFilename) + { + char aOldBuffer[MAX_PATH_LENGTH]; + char aNewBuffer[MAX_PATH_LENGTH]; + return !fs_rename(GetBinaryPath(pOldFilename, aOldBuffer, sizeof(aOldBuffer)), GetBinaryPath(pNewFilename, aNewBuffer, sizeof (aNewBuffer))); + } + + virtual bool CreateFolder(const char *pFoldername, int Type) + { + if(Type < 0 || Type >= m_NumPaths) + return false; + + char aBuffer[MAX_PATH_LENGTH]; + return !fs_makedir(GetPath(Type, pFoldername, aBuffer, sizeof(aBuffer))); + } + + virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) + { + if(Type < 0 || Type >= m_NumPaths) + { + if(BufferSize > 0) + pBuffer[0] = 0; + return; + } + + GetPath(Type, pDir, pBuffer, BufferSize); + } + + virtual const char* GetBinaryPath(const char *pDir, char *pBuffer, unsigned BufferSize) + { + str_format(pBuffer, BufferSize, "%s%s%s", m_aBinarydir, !m_aBinarydir[0] ? "" : "/", pDir); + return pBuffer; + } + + static IStorage *Create(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) + { + CStorage *p = new CStorage(); + if(p && p->Init(pApplicationName, StorageType, NumArgs, ppArguments)) + { + dbg_msg("storage", "initialisation failed"); + delete p; + p = 0; + } + return p; + } +}; + +IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, StorageType, NumArgs, ppArguments); } + +IStorage *CreateLocalStorage() +{ + CStorage *pStorage = new CStorage(); + if(pStorage) + { + if(!fs_getcwd(pStorage->m_aCurrentdir, sizeof(pStorage->m_aCurrentdir))) + { + delete pStorage; + return NULL; + } + pStorage->AddPath("$CURRENTDIR"); + } + return pStorage; +} diff --git a/src/engine/shared/storage.h b/src/engine/shared/storage.h new file mode 100644 index 0000000..0781a06 --- /dev/null +++ b/src/engine/shared/storage.h @@ -0,0 +1,48 @@ +#ifndef STORAGE_H +#define STORAGE_H + +#include <base/system.h> +#include <engine/storage.h> +#include "engine.h" + +// compiled-in data-dir path +#define DATA_DIR "data" + + + +class CStorage : public IStorage +{ +public: + char m_aApplicationSavePath[512]; + char m_aDatadir[512]; + + CStorage() + { + m_aApplicationSavePath[0] = 0; + m_aDatadir[0] = 0; + } + + int Init(const char *pApplicationName, const char *pArgv0); + + int FindDatadir(const char *pArgv0); + + virtual void ListDirectory(int Types, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser); + virtual void ListDirectoryInfo(int Type, const char *pPath, FS_LISTDIR_INFO_CALLBACK pfnCallback, void *pUser) = 0; + + virtual IOHANDLE OpenFile(const char *pFilename, int Flags, char *pBuffer = 0, int BufferSize = 0); + + static IStorage *Create(const char *pApplicationName, const char *pArgv0) + { + CStorage *p = new CStorage(); + if(p->Init(pApplicationName, pArgv0)) + { + delete p; + p = 0; + } + return p; + } +}; + +IStorage *CreateStorage(const char *pApplicationName, const char *pArgv0); + +#endif diff --git a/src/engine/shared/websockets.cpp b/src/engine/shared/websockets.cpp new file mode 100644 index 0000000..795af2c --- /dev/null +++ b/src/engine/shared/websockets.cpp @@ -0,0 +1,275 @@ +#if defined(WEBSOCKETS) + +#include <string.h> +#include <stdlib.h> + +#include "engine/external/libwebsockets/libwebsockets.h" +#include "base/system.h" +#include "protocol.h" +#include "ringbuffer.h" +#include <arpa/inet.h> + +extern "C" { + +#include "websockets.h" + +// not sure why would anyone need more than one but well... +#define WS_CONTEXTS 4 +// ddnet client opens two connections for whatever reason +#define WS_CLIENTS MAX_CLIENTS*2 + +typedef TStaticRingBuffer<unsigned char, WS_CLIENTS * 4 * 1024, CRingBufferBase::FLAG_RECYCLE> TRecvBuffer; +typedef TStaticRingBuffer<unsigned char, 4 * 1024, CRingBufferBase::FLAG_RECYCLE> TSendBuffer; + +typedef struct +{ + size_t size; + size_t read; + sockaddr_in addr; + unsigned char data[0]; +} websocket_chunk; + +struct per_session_data +{ + struct libwebsocket *wsi; + int port; + sockaddr_in addr; + TSendBuffer send_buffer; +}; + +struct context_data +{ + libwebsocket_context *context; + per_session_data *port_map[WS_CLIENTS]; + TRecvBuffer recv_buffer; + int last_used_port; +}; + +static int receive_chunk(context_data *ctx_data, struct per_session_data *pss, void *in, size_t len) +{ + websocket_chunk *chunk = (websocket_chunk *)ctx_data->recv_buffer.Allocate(len + sizeof(websocket_chunk)); + if(chunk == 0) + return 1; + chunk->size = len; + chunk->read = 0; + memcpy(&chunk->addr, &pss->addr, sizeof(sockaddr_in)); + memcpy(&chunk->data[0], in, len); + return 0; +} + +static int websocket_callback(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) +{ + struct per_session_data *pss = (struct per_session_data *)user; + context_data *ctx_data = (context_data *)libwebsocket_context_user(context); + + switch(reason) + { + + case LWS_CALLBACK_ESTABLISHED: + { + int port = -1; + for(int i = 0; i < WS_CLIENTS; i++) + { + int j = (ctx_data->last_used_port + i + 1) % WS_CLIENTS; + if(ctx_data->port_map[j] == NULL) + { + port = j; + break; + } + } + if(port == -1) + { + dbg_msg("websockets", "no free ports, dropping"); + pss->port = -1; + return -1; + } + ctx_data->last_used_port = port; + pss->wsi = wsi; + int fd = libwebsocket_get_socket_fd(wsi); + socklen_t addr_size = sizeof(pss->addr); + getpeername(fd, (struct sockaddr *)&pss->addr, &addr_size); + int orig_port = ntohs(pss->addr.sin_port); + pss->addr.sin_port = htons(port); + pss->send_buffer.Init(); + pss->port = port; + ctx_data->port_map[port] = pss; + char addr_str[NETADDR_MAXSTRSIZE]; + inet_ntop(AF_INET, &pss->addr.sin_addr, addr_str, sizeof(addr_str)); + dbg_msg("websockets", "connection established with %s:%d , assigned fake port %d", addr_str, orig_port, port); + } + break; + + case LWS_CALLBACK_CLOSED: + { + dbg_msg("websockets", "connection with fake port %d closed", pss->port); + if (pss->port > -1) { + unsigned char close_packet[] = { 0x10, 0x0e, 0x00, 0x04 }; + receive_chunk(ctx_data, pss, &close_packet, sizeof(close_packet)); + pss->wsi = 0; + ctx_data->port_map[pss->port] = NULL; + } + } + break; + + case LWS_CALLBACK_SERVER_WRITEABLE: + { + websocket_chunk *chunk = (websocket_chunk *)pss->send_buffer.First(); + if(chunk == NULL) + break; + int len = chunk->size - chunk->read; + int n = libwebsocket_write(wsi, &chunk->data[LWS_SEND_BUFFER_PRE_PADDING + chunk->read], chunk->size - chunk->read, LWS_WRITE_BINARY); + if(n < 0) + return 1; + if(n < len) + { + chunk->read += n; + libwebsocket_callback_on_writable(context, wsi); + break; + } + pss->send_buffer.PopFirst(); + libwebsocket_callback_on_writable(context, wsi); + } + break; + + case LWS_CALLBACK_RECEIVE: + if(pss->port == -1) + return -1; + if(!receive_chunk(ctx_data, pss, in, len)) + return 1; + break; + + default: + break; + } + + return 0; +} + +static struct libwebsocket_protocols protocols[] = { { + "binary", /* name */ + websocket_callback, /* callback */ + sizeof(struct per_session_data) /* per_session_data_size */ + }, + { + NULL, NULL, 0 /* End of list */ + } }; + +static context_data contexts[WS_CONTEXTS]; + +int websocket_create(const char *addr, int port) +{ + struct lws_context_creation_info info; + memset(&info, 0, sizeof(info)); + info.port = port; + info.iface = addr; + info.protocols = protocols; + info.gid = -1; + info.uid = -1; + + // find free context + int first_free = -1; + for(int i = 0; i < WS_CONTEXTS; i++) + { + if(contexts[i].context == NULL) + { + first_free = i; + break; + } + } + if(first_free == -1) + return -1; + + context_data *ctx_data = &contexts[first_free]; + info.user = (void *)ctx_data; + + ctx_data->context = libwebsocket_create_context(&info); + if(ctx_data->context == NULL) + { + return -1; + } + memset(ctx_data->port_map, 0, sizeof(ctx_data->port_map)); + ctx_data->recv_buffer.Init(); + ctx_data->last_used_port = 0; + return first_free; +} + +int websocket_destroy(int socket) +{ + libwebsocket_context *context = contexts[socket].context; + if(context == NULL) + return -1; + libwebsocket_context_destroy(context); + contexts[socket].context = NULL; + return 0; +} + +int websocket_recv(int socket, unsigned char *data, size_t maxsize, struct sockaddr_in *sockaddrbuf, size_t fromLen) +{ + libwebsocket_context *context = contexts[socket].context; + if(context == NULL) + return -1; + int n = libwebsocket_service(context, 0); + if(n < 0) + return n; + context_data *ctx_data = (context_data *)libwebsocket_context_user(context); + websocket_chunk *chunk = (websocket_chunk *)ctx_data->recv_buffer.First(); + if(chunk == 0) + return 0; + if(maxsize >= chunk->size - chunk->read) + { + int len = chunk->size - chunk->read; + memcpy(data, &chunk->data[chunk->read], len); + memcpy(sockaddrbuf, &chunk->addr, fromLen); + ctx_data->recv_buffer.PopFirst(); + return len; + } + else + { + memcpy(data, &chunk->data[chunk->read], maxsize); + memcpy(sockaddrbuf, &chunk->addr, fromLen); + chunk->read += maxsize; + return maxsize; + } +} + +int websocket_send(int socket, const unsigned char *data, size_t size, int port) +{ + libwebsocket_context *context = contexts[socket].context; + if(context == NULL) + return -1; + context_data *ctx_data = (context_data *)libwebsocket_context_user(context); + struct per_session_data *pss = ctx_data->port_map[port]; + if(pss == NULL) + return -1; + websocket_chunk *chunk = (websocket_chunk *)pss->send_buffer.Allocate(size + sizeof(websocket_chunk) + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING); + if(chunk == NULL) + return -1; + chunk->size = size; + chunk->read = 0; + memcpy(&chunk->addr, &pss->addr, sizeof(sockaddr_in)); + memcpy(&chunk->data[LWS_SEND_BUFFER_PRE_PADDING], data, size); + libwebsocket_callback_on_writable(context, pss->wsi); + return size; +} + +int websocket_fd_set(int socket, fd_set *set) +{ + libwebsocket_context *context = contexts[socket].context; + if(context == NULL) + return -1; + context_data *ctx_data = (context_data *)libwebsocket_context_user(context); + int max = 0; + for(int i = 0; i < WS_CLIENTS; i++) + { + per_session_data *pss = ctx_data->port_map[i]; + if(pss == NULL) + continue; + int fd = libwebsocket_get_socket_fd(pss->wsi); + if(fd > max) + max = fd; + FD_SET(fd, set); + } + return max; +} +} +#endif diff --git a/src/engine/shared/websockets.h b/src/engine/shared/websockets.h new file mode 100644 index 0000000..95f6fc1 --- /dev/null +++ b/src/engine/shared/websockets.h @@ -0,0 +1,16 @@ +#ifndef WEBSOCKETS_H +#define WEBSOCKETS_H + +#if !defined(CONF_FAMILY_UNIX) + #error websockets only work on unix, sorry +#endif + +#include <netinet/in.h> + +int websocket_create(const char *addr, int port); +int websocket_destroy(int socket); +int websocket_recv(int socket, unsigned char *data, size_t maxsize, struct sockaddr_in *sockaddrbuf, size_t fromLen); +int websocket_send(int socket, const unsigned char *data, size_t size, int port); +int websocket_fd_set(int socket, fd_set *set); + +#endif diff --git a/src/engine/sound.h b/src/engine/sound.h new file mode 100644 index 0000000..db69a9f --- /dev/null +++ b/src/engine/sound.h @@ -0,0 +1,104 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_SOUND_H +#define ENGINE_SOUND_H + +#include "kernel.h" + +class ISound : public IInterface +{ + MACRO_INTERFACE("sound", 0) +public: + enum + { + FLAG_LOOP=1<<0, + FLAG_POS=1<<1, + FLAG_NO_PANNING=1<<2, + FLAG_ALL=FLAG_LOOP|FLAG_POS|FLAG_NO_PANNING, + }; + + enum + { + SHAPE_CIRCLE, + SHAPE_RECTANGLE, + }; + + struct CVoiceShapeCircle + { + float m_Radius; + }; + + struct CVoiceShapeRectangle + { + float m_Width; + float m_Height; + }; + + class CVoiceHandle + { + friend class ISound; + int m_Id; + int m_Age; + public: + CVoiceHandle() + : m_Id(-1), m_Age(-1) + {} + + bool IsValid() const { return (Id() >= 0) && (Age() >= 0); } + int Id() const { return m_Id; } + int Age() const { return m_Age; } + + bool operator ==(const CVoiceHandle &Other) const { return m_Id == Other.m_Id && m_Age == Other.m_Age; } + }; + + + virtual bool IsSoundEnabled() = 0; + + virtual int LoadWV(const char *pFilename) = 0; + virtual int LoadOpus(const char *pFilename) = 0; + virtual int LoadWVFromMem(const void *pData, unsigned DataSize, bool FromEditor = false) = 0; + virtual int LoadOpusFromMem(const void *pData, unsigned DataSize, bool FromEditor = false) = 0; + virtual void UnloadSample(int SampleID) = 0; + + virtual float GetSampleDuration(int SampleID) = 0; // in s + + virtual void SetChannel(int ChannelID, float Volume, float Panning) = 0; + virtual void SetListenerPos(float x, float y) = 0; + + virtual void SetVoiceVolume(CVoiceHandle Voice, float Volume) = 0; + virtual void SetVoiceFalloff(CVoiceHandle Voice, float Falloff) = 0; + virtual void SetVoiceLocation(CVoiceHandle Voice, float x, float y) = 0; + virtual void SetVoiceTimeOffset(CVoiceHandle Voice, float offset) = 0; // in s + + virtual void SetVoiceCircle(CVoiceHandle Voice, float Radius) = 0; + virtual void SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height) = 0; + + virtual CVoiceHandle PlayAt(int ChannelID, int SampleID, int Flags, float x, float y) = 0; + virtual CVoiceHandle Play(int ChannelID, int SampleID, int Flags) = 0; + virtual void Stop(int SampleID) = 0; + virtual void StopAll() = 0; + virtual void StopVoice(CVoiceHandle Voice) = 0; + +protected: + inline CVoiceHandle CreateVoiceHandle(int Index, int Age) + { + CVoiceHandle Voice; + Voice.m_Id = Index; + Voice.m_Age = Age; + return Voice; + } +}; + + +class IEngineSound : public ISound +{ + MACRO_INTERFACE("enginesound", 0) +public: + virtual int Init() = 0; + virtual int Update() = 0; + virtual int Shutdown() = 0; +}; + +extern IEngineSound *CreateEngineSound(); + +#endif diff --git a/src/engine/storage.h b/src/engine/storage.h new file mode 100644 index 0000000..ed904d5 --- /dev/null +++ b/src/engine/storage.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_STORAGE_H +#define ENGINE_STORAGE_H + +#include "kernel.h" + +class IStorage : public IInterface +{ + MACRO_INTERFACE("storage", 0) +public: + enum + { + TYPE_SAVE = 0, + TYPE_ALL = -1, + + STORAGETYPE_BASIC = 0, + STORAGETYPE_SERVER, + STORAGETYPE_CLIENT, + }; + + virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0; + virtual void ListDirectoryInfo(int Type, const char *pPath, FS_LISTDIR_INFO_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; + virtual bool RemoveFile(const char *pFilename, int Type) = 0; + virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0; + virtual bool CreateFolder(const char *pFoldername, int Type) = 0; + virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0; + + virtual bool RemoveBinaryFile(const char *pFilename) = 0; + virtual bool RenameBinaryFile(const char* pOldFilename, const char* pNewFilename) = 0; + virtual const char* GetBinaryPath(const char *pDir, char *pBuffer, unsigned BufferSize) = 0; +}; + +extern IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments); +extern IStorage *CreateLocalStorage(); + + +#endif diff --git a/src/engine/textrender.h b/src/engine/textrender.h new file mode 100644 index 0000000..ddd2be5 --- /dev/null +++ b/src/engine/textrender.h @@ -0,0 +1,64 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef ENGINE_TEXTRENDER_H +#define ENGINE_TEXTRENDER_H +#include "kernel.h" + +enum +{ + TEXTFLAG_RENDER=1, + TEXTFLAG_ALLOW_NEWLINE=2, + TEXTFLAG_STOP_AT_END=4 +}; + +class CFont; + +class CTextCursor +{ +public: + int m_Flags; + 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; +}; + +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; + virtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth) = 0; + virtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length) = 0; + virtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) = 0; +}; + +class IEngineTextRender : public ITextRender +{ + MACRO_INTERFACE("enginetextrender", 0) +public: + virtual void Init() = 0; +}; + +extern IEngineTextRender *CreateEngineTextRender(); + +#endif diff --git a/src/engine/updater.h b/src/engine/updater.h new file mode 100644 index 0000000..3489276 --- /dev/null +++ b/src/engine/updater.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_UPDATER_H +#define ENGINE_UPDATER_H + +#include "kernel.h" + +class IUpdater : public IInterface +{ + MACRO_INTERFACE("updater", 0) +public: + enum + { + CLEAN = 0, + GETTING_MANIFEST, + GOT_MANIFEST, + PARSING_UPDATE, + DOWNLOADING, + NEED_RESTART, + FAIL, + }; + + virtual void Update() = 0; + virtual void InitiateUpdate() = 0; + + virtual int GetCurrentState() = 0; + virtual char *GetCurrentFile() = 0; + virtual int GetCurrentPercent() = 0; +}; + +#endif diff --git a/src/game/animation.cpp b/src/game/animation.cpp new file mode 100644 index 0000000..3f0aa26 --- /dev/null +++ b/src/game/animation.cpp @@ -0,0 +1,95 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <game/gamecore.h> +#include <game/layers.h> +#include <game/animation.h> + +void GetAnimationTransform(float GlobalTime, int Env, CLayers* pLayers, vec2& Position, float& Angle) +{ + CEnvPoint *pPoints = 0; + + Position.x = 0.0f; + Position.y = 0.0f; + Angle = 0.0f; + + { + int Start, Num; + pLayers->Map()->GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num); + if(Num) + pPoints = (CEnvPoint *)pLayers->Map()->GetItem(Start, 0, 0); + } + + int Start, Num; + pLayers->Map()->GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); + + if(Env >= Num) + return; + + CMapItemEnvelope *pItem = (CMapItemEnvelope *)pLayers->Map()->GetItem(Start+Env, 0, 0); + + pPoints += pItem->m_StartPoint; + + if(pItem->m_NumPoints == 0) + return; + + if(pItem->m_NumPoints == 1) + { + Position.x = fx2f(pPoints[0].m_aValues[0]); + Position.y = fx2f(pPoints[0].m_aValues[1]); + Angle = fx2f(pPoints[0].m_aValues[2])/360.0f*pi*2.0f; + return; + } + + float Time = fmod(GlobalTime, pPoints[pItem->m_NumPoints-1].m_Time/1000.0f)*1000.0f; + for(int i = 0; i < pItem->m_NumPoints-1; i++) + { + if(Time >= pPoints[i].m_Time && Time <= pPoints[i+1].m_Time) + { + float Delta = pPoints[i+1].m_Time-pPoints[i].m_Time; + float a = (Time-pPoints[i].m_Time)/Delta; + + + if(pPoints[i].m_Curvetype == CURVETYPE_SMOOTH) + a = -2*a*a*a + 3*a*a; // second hermite basis + else if(pPoints[i].m_Curvetype == CURVETYPE_SLOW) + a = a*a*a; + else if(pPoints[i].m_Curvetype == CURVETYPE_FAST) + { + a = 1-a; + a = 1-a*a*a; + } + else if (pPoints[i].m_Curvetype == CURVETYPE_STEP) + a = 0; + else + { + // linear + } + + // X + { + float v0 = fx2f(pPoints[i].m_aValues[0]); + float v1 = fx2f(pPoints[i+1].m_aValues[0]); + Position.x = v0 + (v1-v0) * a; + } + // Y + { + float v0 = fx2f(pPoints[i].m_aValues[1]); + float v1 = fx2f(pPoints[i+1].m_aValues[1]); + Position.y = v0 + (v1-v0) * a; + } + // angle + { + float v0 = fx2f(pPoints[i].m_aValues[2]); + float v1 = fx2f(pPoints[i+1].m_aValues[2]); + Angle = (v0 + (v1-v0) * a)/360.0f*pi*2.0f; + } + + return; + } + } + + Position.x = fx2f(pPoints[pItem->m_NumPoints-1].m_aValues[0]); + Position.y = fx2f(pPoints[pItem->m_NumPoints-1].m_aValues[1]); + Angle = fx2f(pPoints[pItem->m_NumPoints-1].m_aValues[2]); + return; +} diff --git a/src/game/animation.h b/src/game/animation.h new file mode 100644 index 0000000..d013bc9 --- /dev/null +++ b/src/game/animation.h @@ -0,0 +1,10 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_ANIMATION_H +#define GAME_ANIMATION_H + +#include <base/vmath.h> + +void GetAnimationTransform(float GlobalTime, int Env, class CLayers* pLayers, vec2& Position, float& Angle); + +#endif diff --git a/src/game/client/animstate.cpp b/src/game/client/animstate.cpp new file mode 100644 index 0000000..ce59535 --- /dev/null +++ b/src/game/client/animstate.cpp @@ -0,0 +1,96 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/math.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include "animstate.h" + +static void AnimSeqEval(CAnimSequence *pSeq, float Time, CAnimKeyframe *pFrame) +{ + if(pSeq->m_NumFrames == 0) + { + pFrame->m_Time = 0; + pFrame->m_X = 0; + pFrame->m_Y = 0; + pFrame->m_Angle = 0; + } + else if(pSeq->m_NumFrames == 1) + { + *pFrame = pSeq->m_aFrames[0]; + } + else + { + //time = max(0.0f, min(1.0f, time / duration)); // TODO: use clamp + CAnimKeyframe *pFrame1 = 0; + CAnimKeyframe *pFrame2 = 0; + float Blend = 0.0f; + + // TODO: make this smarter.. binary search + for (int i = 1; i < pSeq->m_NumFrames; i++) + { + if (pSeq->m_aFrames[i-1].m_Time <= Time && pSeq->m_aFrames[i].m_Time >= Time) + { + pFrame1 = &pSeq->m_aFrames[i-1]; + pFrame2 = &pSeq->m_aFrames[i]; + Blend = (Time - pFrame1->m_Time) / (pFrame2->m_Time - pFrame1->m_Time); + break; + } + } + + if (pFrame1 && pFrame2) + { + pFrame->m_Time = Time; + pFrame->m_X = mix(pFrame1->m_X, pFrame2->m_X, Blend); + pFrame->m_Y = mix(pFrame1->m_Y, pFrame2->m_Y, Blend); + pFrame->m_Angle = mix(pFrame1->m_Angle, pFrame2->m_Angle, Blend); + } + } +} + +static void AnimAddKeyframe(CAnimKeyframe *pSeq, CAnimKeyframe *pAdded, float Amount) +{ + pSeq->m_X += pAdded->m_X*Amount; + pSeq->m_Y += pAdded->m_Y*Amount; + pSeq->m_Angle += pAdded->m_Angle*Amount; +} + +static void AnimAdd(CAnimState *pState, CAnimState *pAdded, float Amount) +{ + AnimAddKeyframe(pState->GetBody(), pAdded->GetBody(), Amount); + AnimAddKeyframe(pState->GetBackFoot(), pAdded->GetBackFoot(), Amount); + AnimAddKeyframe(pState->GetFrontFoot(), pAdded->GetFrontFoot(), Amount); + AnimAddKeyframe(pState->GetAttach(), pAdded->GetAttach(), Amount); +} + + +void CAnimState::Set(CAnimation *pAnim, float Time) +{ + AnimSeqEval(&pAnim->m_Body, Time, &m_Body); + AnimSeqEval(&pAnim->m_BackFoot, Time, &m_BackFoot); + AnimSeqEval(&pAnim->m_FrontFoot, Time, &m_FrontFoot); + AnimSeqEval(&pAnim->m_Attach, Time, &m_Attach); +} + +void CAnimState::Add(CAnimation *pAnim, float Time, float Amount) +{ + CAnimState Add; + Add.Set(pAnim, Time); + AnimAdd(this, &Add, Amount); +} + +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 new file mode 100644 index 0000000..fbc0a2f --- /dev/null +++ b/src/game/client/animstate.h @@ -0,0 +1,24 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_ANIMSTATE_H +#define GAME_CLIENT_ANIMSTATE_H + +class CAnimState +{ + CAnimKeyframe m_Body; + CAnimKeyframe m_BackFoot; + CAnimKeyframe m_FrontFoot; + CAnimKeyframe m_Attach; + +public: + CAnimKeyframe *GetBody() { return &m_Body; }; + CAnimKeyframe *GetBackFoot() { return &m_BackFoot; }; + CAnimKeyframe *GetFrontFoot() { return &m_FrontFoot; }; + CAnimKeyframe *GetAttach() { return &m_Attach; }; + void Set(CAnimation *pAnim, float Time); + void Add(CAnimation *pAdded, float Time, float Amount); + + static CAnimState *GetIdle(); +}; + +#endif diff --git a/src/game/client/component.h b/src/game/client/component.h new file mode 100644 index 0000000..b39c2cd --- /dev/null +++ b/src/game/client/component.h @@ -0,0 +1,49 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENT_H +#define GAME_CLIENT_COMPONENT_H + +#include <engine/input.h> +#include "gameclient.h" + +class CComponent +{ +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(); } + class ITextRender *TextRender() const { return m_pClient->TextRender(); } + class IInput *Input() const { return m_pClient->Input(); } + class IStorage *Storage() const { return m_pClient->Storage(); } + class CUI *UI() const { return m_pClient->UI(); } + class ISound *Sound() const { return m_pClient->Sound(); } + class CRenderTools *RenderTools() const { return m_pClient->RenderTools(); } + class IConsole *Console() const { return m_pClient->Console(); } + class IDemoPlayer *DemoPlayer() const { return m_pClient->DemoPlayer(); } + class IDemoRecorder *DemoRecorder(int Recorder) const { return m_pClient->DemoRecorder(Recorder); } + class IServerBrowser *ServerBrowser() const { return m_pClient->ServerBrowser(); } + class CLayers *Layers() const { return m_pClient->Layers(); } + class CCollision *Collision() const { return m_pClient->Collision(); } + class IUpdater *Updater() const { return m_pClient->Updater(); } +public: + virtual ~CComponent() {} + class CGameClient *GameClient() const { return m_pClient; } + class IClient *Client() const { return m_pClient->Client(); } + + virtual void OnStateChange(int NewState, int OldState) {}; + virtual void OnConsoleInit() {}; + virtual void OnInit() {}; + virtual void OnReset() {}; + virtual void OnRender() {}; + virtual void OnRelease() {}; + virtual void OnMapLoad() {}; + virtual void OnMessage(int Msg, void *pRawMsg) {} + virtual bool OnMouseMove(float x, float y) { return false; } + virtual bool OnInput(IInput::CEvent e) { return false; } +}; + +#endif diff --git a/src/game/client/components/background.cpp b/src/game/client/components/background.cpp new file mode 100644 index 0000000..92d32c5 --- /dev/null +++ b/src/game/client/components/background.cpp @@ -0,0 +1,198 @@ +#include <base/system.h> + +#include <engine/shared/config.h> +#include <engine/map.h> +#include <engine/graphics.h> + +#include <game/client/components/camera.h> +#include <game/client/components/maplayers.h> +#include <game/client/components/mapimages.h> + +#include "background.h" + +CBackground::CBackground() +{ + m_pLayers = new CMapLayers(CMapLayers::TYPE_BACKGROUND); + m_pLayers->m_pLayers = new CLayers; + m_pBackgroundLayers = m_pLayers->m_pLayers; + m_pImages = new CMapImages; + m_pBackgroundImages = m_pImages; + m_pMap = CreateEngineMap(); + m_pBackgroundMap = m_pMap; + m_Loaded = false; + m_aMapName[0] = '\0'; +} + +CBackground::~CBackground() +{ + if(m_pLayers->m_pLayers != GameClient()->Layers()) + { + delete m_pLayers->m_pLayers; + delete m_pLayers; + delete m_pImages; + } +} + +void CBackground::OnInit() +{ + m_pImages->m_pClient = GameClient(); + m_pLayers->m_pClient = GameClient(); + Kernel()->ReregisterInterface(static_cast<IEngineMap*>(m_pMap)); + str_format(m_aMapName, sizeof(m_aMapName), "%s", g_Config.m_ClBackgroundEntities); + if(str_comp(g_Config.m_ClBackgroundEntities, CURRENT)) + LoadBackground(); +} + +void CBackground::LoadBackground() +{ + if(time_get()-m_LastLoad < 10*time_freq()) + return; + + if(m_Loaded && m_pMap == m_pBackgroundMap) + m_pMap->Unload(); + + m_Loaded = false; + m_pMap = m_pBackgroundMap; + m_pLayers->m_pLayers = m_pBackgroundLayers; + m_pImages = m_pBackgroundImages; + + str_format(m_aMapName, sizeof(m_aMapName), "%s", g_Config.m_ClBackgroundEntities); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "maps/%s", g_Config.m_ClBackgroundEntities); + if(m_pMap->Load(aBuf)) + { + m_pLayers->m_pLayers->InitBackground(m_pMap); + m_pImages->LoadBackground(m_pMap); + RenderTools()->RenderTilemapGenerateSkip(m_pLayers->m_pLayers); + m_Loaded = true; + } + else if(str_comp(g_Config.m_ClBackgroundEntities, CURRENT) == 0) + { + m_pMap = Kernel()->RequestInterface<IEngineMap>(); + m_pLayers->m_pLayers = GameClient()->Layers(); + m_pImages = GameClient()->m_pMapimages; + m_Loaded = true; + } + + m_LastLoad = time_get(); +} + +void CBackground::OnMapLoad() +{ + if(str_comp(g_Config.m_ClBackgroundEntities, CURRENT) == 0 || str_comp(g_Config.m_ClBackgroundEntities, m_aMapName)) + LoadBackground(); +} + +//code is from CMapLayers::OnRender() +void CBackground::OnRender() +{ + //probably not the best place for this + if(str_comp(g_Config.m_ClBackgroundEntities, m_aMapName)) + LoadBackground(); + + if(!m_Loaded) + return; + + if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) + return; + + if(g_Config.m_ClOverlayEntities != 100) + return; + + CUIRect Screen; + Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); + + vec2 Center = m_pClient->m_pCamera->m_Center; + + bool PassedGameLayer = false; + + for(int g = 0; g < m_pLayers->m_pLayers->NumGroups() && !PassedGameLayer; g++) + { + CMapItemGroup *pGroup = m_pLayers->m_pLayers->GetGroup(g); + + if(!pGroup) + { + dbg_msg("MapLayers", "Error:Group was null, Group Number = %d, Total Groups = %d", g, m_pLayers->m_pLayers->NumGroups()); + dbg_msg("MapLayers", "This is here to prevent a crash but the source of this is unknown, please report this for it to get fixed"); + dbg_msg("MapLayers", "we need mapname and crc and the map that caused this if possible, and anymore info you think is relevant"); + continue; + } + + if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) + { + // set clipping + float Points[4]; + m_pLayers->MapScreenToGroup(Center.x, Center.y, m_pLayers->m_pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom); + Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); + float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); + 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())); + } + + if(!g_Config.m_ClZoomBackgroundLayers && !pGroup->m_ParallaxX && !pGroup->m_ParallaxY) + m_pLayers->MapScreenToGroup(Center.x, Center.y, pGroup, 1.0); + else + m_pLayers->MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom); + + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = m_pLayers->m_pLayers->GetLayer(pGroup->m_StartLayer+l); + // skip rendering if detail layers if not wanted + if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail) + continue; + + if(pLayer == (CMapItemLayer*)m_pLayers->m_pLayers->GameLayer()) + { + PassedGameLayer = true; + break; + } + + if(pLayer->m_Type == LAYERTYPE_TILES && g_Config.m_ClBackgroundShowTilesLayers) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + if(pTMap->m_Image == -1) + Graphics()->TextureSet(-1); + else + Graphics()->TextureSet(m_pImages->Get(pTMap->m_Image)); + + CTile *pTiles = (CTile *)m_pMap->GetData(pTMap->m_Data); + unsigned int Size = m_pMap->GetUncompressedDataSize(pTMap->m_Data); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile)) + { + 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); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, + m_pLayers->EnvelopeEval, m_pLayers, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + Graphics()->BlendNormal(); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, + m_pLayers->EnvelopeEval, m_pLayers, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + } + } + else if(pLayer->m_Type == LAYERTYPE_QUADS && g_Config.m_ClShowQuads) + { + CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; + if(pQLayer->m_Image == -1) + Graphics()->TextureSet(-1); + else + Graphics()->TextureSet(m_pImages->Get(pQLayer->m_Image)); + + CQuad *pQuads = (CQuad *)m_pMap->GetDataSwapped(pQLayer->m_Data); + + Graphics()->BlendNone(); + RenderTools()->ForceRenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, m_pLayers->EnvelopeEval, m_pLayers); + Graphics()->BlendNormal(); + RenderTools()->ForceRenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, m_pLayers->EnvelopeEval, m_pLayers); + } + } + 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/background.h b/src/game/client/components/background.h new file mode 100644 index 0000000..700af9e --- /dev/null +++ b/src/game/client/components/background.h @@ -0,0 +1,34 @@ +#ifndef GAME_CLIENT_COMPONENTS_BACKGROUND_H +#define GAME_CLIENT_COMPONENTS_BACKGROUND_H +#include <game/client/component.h> + +#define CURRENT "%current%" + +class CBackground : public CComponent +{ + class CMapLayers *m_pLayers; + class CMapImages *m_pImages; + IEngineMap *m_pMap; + bool m_Loaded; + char m_aMapName[128]; + + //to avoid spam when in menu + int64 m_LastLoad; + + //to avoid memory leak when switching to %current% + IEngineMap *m_pBackgroundMap; + CLayers *m_pBackgroundLayers; + CMapImages *m_pBackgroundImages; + +public: + CBackground(); + ~CBackground(); + + virtual void OnInit(); + virtual void OnMapLoad(); + virtual void OnRender(); + + void LoadBackground(); +}; + +#endif diff --git a/src/game/client/components/binds.cpp b/src/game/client/components/binds.cpp new file mode 100644 index 0000000..666ce12 --- /dev/null +++ b/src/game/client/components/binds.cpp @@ -0,0 +1,372 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/config.h> +#include <engine/shared/config.h> +#include "binds.h" + +bool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event) +{ + // don't handle invalid events and keys that arn't set to anything + if(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15 && m_pBinds->m_aaKeyBindings[Event.m_Key][0] != 0) + { + 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; +} + +CBinds::CBinds() +{ + mem_zero(m_aaKeyBindings, sizeof(m_aaKeyBindings)); + m_SpecialBinds.m_pBinds = this; +} + +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]) + str_format(aBuf, sizeof(aBuf), "unbound %s (%d)", Input()->KeyName(KeyID), KeyID); + else + str_format(aBuf, sizeof(aBuf), "bound %s (%d) = %s", Input()->KeyName(KeyID), KeyID, m_aaKeyBindings[KeyID]); + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); +} + + +bool CBinds::OnInput(IInput::CEvent e) +{ + // don't handle invalid events and keys that arn't set to anything + if(e.m_Key <= 0 || e.m_Key >= KEY_LAST || m_aaKeyBindings[e.m_Key][0] == 0) + return false; + + int Stroke = 0; + if(e.m_Flags&IInput::FLAG_PRESS) + Stroke = 1; + Console()->ExecuteLineStroked(Stroke, m_aaKeyBindings[e.m_Key]); + return true; +} + +void CBinds::UnbindAll() +{ + for(int i = 0; i < KEY_LAST; i++) + m_aaKeyBindings[i][0] = 0; +} + +const char *CBinds::Get(int KeyID) +{ + if(KeyID > 0 && KeyID < KEY_LAST) + return m_aaKeyBindings[KeyID]; + return ""; +} + +const char *CBinds::GetKey(const char *pBindStr) +{ + for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) + { + const char *pBind = Get(KeyId); + if(!pBind[0]) + continue; + + if(str_comp(pBind, pBindStr) == 0) + return Input()->KeyName(KeyId); + } + + return ""; +} + +void CBinds::SetDefaults() +{ + // set default key bindings + UnbindAll(); + Bind(KEY_F1, "toggle_local_console"); + Bind(KEY_F2, "toggle_remote_console"); + Bind(KEY_TAB, "+scoreboard"); + Bind(KEY_BACKQUOTE, "+statboard"); + Bind(KEY_F10, "screenshot"); + + Bind('a', "+left"); + Bind('d', "+right"); + + Bind(KEY_SPACE, "+jump"); + Bind(KEY_MOUSE_1, "+fire"); + Bind(KEY_MOUSE_2, "+hook"); + Bind(KEY_LSHIFT, "+emote"); +#if defined(__ANDROID__) + Bind(KEY_RCTRL, "+fire"); + Bind(KEY_RETURN, "+hook"); + Bind(KEY_RIGHT, "+right"); + Bind(KEY_LEFT, "+left"); + Bind(KEY_UP, "+jump"); + Bind(KEY_DOWN, "+hook"); + Bind(KEY_PAGEUP, "+prevweapon"); + Bind(KEY_PAGEDOWN, "+nextweapon"); + Bind(KEY_F5, "spectate_previous"); + Bind(KEY_F6, "spectate_next"); +#else + Bind(KEY_RETURN, "+show_chat; chat all"); + Bind(KEY_RIGHT, "spectate_next"); + Bind(KEY_LEFT, "spectate_previous"); + Bind(KEY_RSHIFT, "+spectate"); +#endif + + + Bind('1', "+weapon1"); + Bind('2', "+weapon2"); + Bind('3', "+weapon3"); + Bind('4', "+weapon4"); + Bind('5', "+weapon5"); + + Bind(KEY_MOUSE_WHEEL_UP, "+prevweapon"); + Bind(KEY_MOUSE_WHEEL_DOWN, "+nextweapon"); + + Bind('t', "+show_chat; chat all"); + Bind('y', "+show_chat; chat team"); + Bind('z', "+show_chat; chat team"); // For German keyboards + Bind('u', "+show_chat"); + Bind('i', "+show_chat; chat all /c "); + + Bind(KEY_F3, "vote yes"); + Bind(KEY_F4, "vote no"); + + Bind('k', "kill"); + Bind('q', "say /pause"); + Bind('p', "say /pause"); + + // DDRace + + if(g_Config.m_ClDDRaceBinds) + SetDDRaceBinds(false); +} + +void CBinds::OnConsoleInit() +{ + // bindings + IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); + if(pConfig) + pConfig->RegisterCallback(ConfigSaveCallback, this); + + Console()->Register("bind", "s[key] r[command]", CFGFLAG_CLIENT, ConBind, this, "Bind key to execute the command"); + Console()->Register("unbind", "s[key]", 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(); +} + +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]; + str_format(aBuf, sizeof(aBuf), "key %s not found", pKeyName); + pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); + return; + } + + pBinds->Bind(id, pResult->GetString(1)); +} + + +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]; + str_format(aBuf, sizeof(aBuf), "key %s not found", pKeyName); + pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); + return; + } + + pBinds->Bind(id, ""); +} + + +void CBinds::ConUnbindAll(IConsole::IResult *pResult, void *pUserData) +{ + CBinds *pBinds = (CBinds *)pUserData; + pBinds->UnbindAll(); +} + + +void CBinds::ConDumpBinds(IConsole::IResult *pResult, void *pUserData) +{ + CBinds *pBinds = (CBinds *)pUserData; + char aBuf[1024]; + for(int i = 0; i < KEY_LAST; i++) + { + if(pBinds->m_aaKeyBindings[i][0] == 0) + continue; + str_format(aBuf, sizeof(aBuf), "%s (%d) = %s", pBinds->Input()->KeyName(i), i, pBinds->m_aaKeyBindings[i]); + pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); + } +} + +int CBinds::GetKeyID(const char *pKeyName) +{ + // check for numeric + if(pKeyName[0] == '&') + { + int i = str_toint(pKeyName+1); + 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"); + for(int i = 0; i < KEY_LAST; i++) + { + 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); + *pDst++ = '"'; + while(*pSrc && pDst < pEnd) + { + if(*pSrc == '"' || *pSrc == '\\') // escape \ and " + *pDst++ = '\\'; + *pDst++ = *pSrc++; + } + *pDst++ = '"'; + *pDst++ = 0; + + pConfig->WriteLine(aBuffer); + } +} + +// DDRace + +void CBinds::SetDDRaceBinds(bool FreeOnly) +{ + if(!FreeOnly) + { + Bind(KEY_KP_PLUS, "zoom+"); + Bind(KEY_KP_MINUS, "zoom-"); + Bind(KEY_KP_MULTIPLY, "zoom"); + Bind(KEY_HOME, "kill"); + Bind(KEY_PAUSE, "say /pause"); + Bind(KEY_UP, "+jump"); + Bind(KEY_LEFT, "+left"); + Bind(KEY_RIGHT, "+right"); + Bind('[', "+prevweapon"); + Bind(']', "+nextweapon"); + Bind('c', "say /rank"); + Bind('v', "say /info"); + Bind('b', "say /top5"); + Bind('x', "emote 14"); + Bind('h', "emote 2"); + Bind('m', "emote 5"); + Bind('s', "+showhookcoll"); + Bind('x', "toggle cl_dummy 0 1"); +#if !defined(__ANDROID__) + Bind(KEY_PAGEDOWN, "toggle cl_show_quads 0 1"); + Bind(KEY_PAGEUP, "toggle cl_overlay_entities 0 100"); +#endif + Bind(KEY_KP0, "say /emote normal 999999"); + Bind(KEY_KP1, "say /emote happy 999999"); + Bind(KEY_KP2, "say /emote angry 999999"); + Bind(KEY_KP3, "say /emote pain 999999"); + Bind(KEY_KP4, "say /emote surprise 999999"); + Bind(KEY_KP5, "say /emote blink 999999"); + Bind(KEY_MOUSE_3, "+spectate"); + Bind(KEY_MINUS, "spectate_previous"); + Bind(KEY_EQUALS, "spectate_next"); + } + else + { + if(!Get(KEY_KP_PLUS)[0]) + Bind(KEY_KP_PLUS, "zoom+"); + if(!Get(KEY_KP_MINUS)[0]) + Bind(KEY_KP_MINUS, "zoom-"); + if(!Get(KEY_KP_MULTIPLY)[0]) + Bind(KEY_KP_MULTIPLY, "zoom"); + if(!Get(KEY_HOME)[0]) + Bind(KEY_HOME, "kill"); + if(!Get(KEY_PAUSE)[0]) + Bind(KEY_PAUSE, "say /pause"); + if(!Get(KEY_UP)[0]) + Bind(KEY_UP, "+jump"); + if(!Get(KEY_LEFT)[0]) + Bind(KEY_LEFT, "+left"); + if(!Get(KEY_RIGHT)[0]) + Bind(KEY_RIGHT, "+right"); + if(!Get('[')[0]) + Bind('[', "+prevweapon"); + if(!Get(']')[0]) + Bind(']', "+nextweapon"); + if(!Get('c')[0]) + Bind('c', "say /rank"); + if(!Get('v')[0]) + Bind('v', "say /info"); + if(!Get('b')[0]) + Bind('b', "say /top5"); + if(!Get('x')[0]) + Bind('x', "emote 14"); + if(!Get(KEY_KP_PLUS)[0]) + Bind('h', "emote 2"); + if(!Get('m')[0]) + Bind('m', "emote 5"); + if(!Get('s')[0]) + Bind('s', "+showhookcoll"); + if(!Get('x')[0]) + Bind('x', "toggle cl_dummy 0 1"); + if(!Get(KEY_PAGEDOWN)[0]) + Bind(KEY_PAGEDOWN, "toggle cl_show_quads 0 1"); + if(!Get(KEY_PAGEUP)[0]) + Bind(KEY_PAGEUP, "toggle cl_overlay_entities 0 100"); + if(!Get(KEY_KP0)[0]) + Bind(KEY_KP0, "say /emote normal 999999"); + if(!Get(KEY_KP1)[0]) + Bind(KEY_KP1, "say /emote happy 999999"); + if(!Get(KEY_KP2)[0]) + Bind(KEY_KP2, "say /emote angry 999999"); + if(!Get(KEY_KP3)[0]) + Bind(KEY_KP3, "say /emote pain 999999"); + if(!Get(KEY_KP4)[0]) + Bind(KEY_KP4, "say /emote surprise 999999"); + if(!Get(KEY_KP5)[0]) + Bind(KEY_KP5, "say /emote blink 999999"); + if(!Get(KEY_MOUSE_3)[0]) + Bind(KEY_MOUSE_3, "+spectate"); + if(!Get(KEY_MINUS)[0]) + Bind(KEY_MINUS, "spectate_previous"); + if(!Get(KEY_EQUALS)[0]) + Bind(KEY_EQUALS, "spectate_next"); + } + + g_Config.m_ClDDRaceBindsSet = 1; +} diff --git a/src/game/client/components/binds.h b/src/game/client/components/binds.h new file mode 100644 index 0000000..35d3d87 --- /dev/null +++ b/src/game/client/components/binds.h @@ -0,0 +1,47 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_BINDS_H +#define GAME_CLIENT_COMPONENTS_BINDS_H +#include <game/client/component.h> +#include <engine/keys.h> + +class CBinds : public CComponent +{ + char m_aaKeyBindings[KEY_LAST][128]; + + int GetKeyID(const char *pKeyName); + + static void ConBind(IConsole::IResult *pResult, void *pUserData); + static void ConUnbind(IConsole::IResult *pResult, void *pUserData); + 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); + + // DDRace + + void SetDDRaceBinds(bool FreeOnly); +}; +#endif diff --git a/src/game/client/components/broadcast.cpp b/src/game/client/components/broadcast.cpp new file mode 100644 index 0000000..8225cd8 --- /dev/null +++ b/src/game/client/components/broadcast.cpp @@ -0,0 +1,71 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/client/gameclient.h> + +#include <game/client/components/motd.h> +#include <game/client/components/scoreboard.h> + +#include "broadcast.h" + +void CBroadcast::OnReset() +{ + m_BroadcastTime = 0; +} + +void CBroadcast::OnRender() +{ + if(m_pClient->m_pScoreboard->Active() || m_pClient->m_pMotd->IsActive() || !g_Config.m_ClShowBroadcasts) + return; + + Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); + + if(time_get() < m_BroadcastTime) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, m_BroadcastRenderOffset, 40.0f, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = 300*Graphics()->ScreenAspect()-m_BroadcastRenderOffset; + TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); + } +} + +void CBroadcast::OnMessage(int MsgType, void *pRawMsg) +{ + if(MsgType == NETMSGTYPE_SV_BROADCAST) + { + CNetMsg_Sv_Broadcast *pMsg = (CNetMsg_Sv_Broadcast *)pRawMsg; + str_copy(m_aBroadcastText, pMsg->m_pMessage, sizeof(m_aBroadcastText)); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, 0, 0, 12.0f, TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = 300*Graphics()->ScreenAspect(); + TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); + m_BroadcastRenderOffset = 150*Graphics()->ScreenAspect()-Cursor.m_X/2; + m_BroadcastTime = time_get()+time_freq()*10; + if (g_Config.m_ClPrintBroadcasts) + { + char aBuf[1024]; + int i, ii; + for (i = 0, ii = 0; i < str_length(m_aBroadcastText); i++) + { + if (m_aBroadcastText[i] == '\n') + { + aBuf[ii] = '\0'; + ii = 0; + m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "broadcast", aBuf, true); + } + else + { + aBuf[ii] = m_aBroadcastText[i]; + ii++; + } + } + aBuf[ii] = '\0'; + m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "broadcast", aBuf, true); + } + } +} diff --git a/src/game/client/components/broadcast.h b/src/game/client/components/broadcast.h new file mode 100644 index 0000000..47c6661 --- /dev/null +++ b/src/game/client/components/broadcast.h @@ -0,0 +1,20 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_BROADCAST_H +#define GAME_CLIENT_COMPONENTS_BROADCAST_H +#include <game/client/component.h> + +class CBroadcast : public CComponent +{ + // broadcasts + char m_aBroadcastText[1024]; + int64 m_BroadcastTime; + float m_BroadcastRenderOffset; + +public: + virtual void OnReset(); + virtual void OnRender(); + virtual void OnMessage(int MsgType, void *pRawMsg); +}; + +#endif diff --git a/src/game/client/components/camera.cpp b/src/game/client/components/camera.cpp new file mode 100644 index 0000000..cf52501 --- /dev/null +++ b/src/game/client/components/camera.cpp @@ -0,0 +1,112 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/string.h> + +#include <engine/shared/config.h> + +#include <base/math.h> +#include <game/collision.h> +#include <game/client/gameclient.h> +#include <game/client/component.h> + +#include "camera.h" +#include "controls.h" + +#include <engine/serverbrowser.h> + +CCamera::CCamera() +{ + m_CamType = CAMTYPE_UNDEFINED; + m_ZoomSet = false; + m_Zoom = 1.0; +} + +void CCamera::OnRender() +{ + CServerInfo Info; + Client()->GetServerInfo(&Info); + + m_ZoomSet = true; + OnReset(); + + // 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) + { + m_LastPos[g_Config.m_ClDummy] = m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy]; + m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy] = m_PrevCenter; + m_pClient->m_pControls->ClampMousePos(); + m_CamType = CAMTYPE_SPEC; + } + m_Center = m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy]; + } + else + { + if(m_CamType != CAMTYPE_PLAYER) + { + m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy] = m_LastPos[g_Config.m_ClDummy]; + m_pClient->m_pControls->ClampMousePos(); + m_CamType = CAMTYPE_PLAYER; + } + + vec2 CameraOffset(0, 0); + + float l = length(m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy]); + if(l > 0.0001f) // make sure that this isn't 0 + { + float DeadZone = g_Config.m_ClDyncam ? g_Config.m_ClDyncamDeadzone : g_Config.m_ClMouseDeadzone; + float FollowFactor = (g_Config.m_ClDyncam ? g_Config.m_ClDyncamFollowFactor : g_Config.m_ClMouseFollowfactor) / 100.0f; + float OffsetAmount = max(l-DeadZone, 0.0f) * FollowFactor; + + CameraOffset = normalize(m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy])*OffsetAmount; + } + + if(m_pClient->m_Snap.m_SpecInfo.m_Active) + m_Center = m_pClient->m_Snap.m_SpecInfo.m_Position + CameraOffset; + else + m_Center = m_pClient->m_LocalCharacterPos + CameraOffset; + } + + m_PrevCenter = m_Center; +} + +void CCamera::OnConsoleInit() +{ + Console()->Register("zoom+", "", CFGFLAG_CLIENT, ConZoomPlus, this, "Zoom increase"); + Console()->Register("zoom-", "", CFGFLAG_CLIENT, ConZoomMinus, this, "Zoom decrease"); + Console()->Register("zoom", "", CFGFLAG_CLIENT, ConZoomReset, this, "Zoom reset"); +} + +const float ZoomStep = 0.866025f; + +void CCamera::OnReset() +{ + m_Zoom = 1.0f; + + for (int i = g_Config.m_ClDefaultZoom; i < 10; i++) + { + m_Zoom *= 1/ZoomStep; + } + for (int i = g_Config.m_ClDefaultZoom; i > 10; i--) + { + m_Zoom *= ZoomStep; + } +} + +void CCamera::ConZoomPlus(IConsole::IResult *pResult, void *pUserData) +{ + CCamera *pSelf = (CCamera *)pUserData; + ((CCamera *)pUserData)->m_Zoom *= ZoomStep; +} +void CCamera::ConZoomMinus(IConsole::IResult *pResult, void *pUserData) +{ + CCamera *pSelf = (CCamera *)pUserData; + ((CCamera *)pUserData)->m_Zoom *= 1/ZoomStep; +} +void CCamera::ConZoomReset(IConsole::IResult *pResult, void *pUserData) +{ + CCamera *pSelf = (CCamera *)pUserData; + ((CCamera *)pUserData)->OnReset(); +} diff --git a/src/game/client/components/camera.h b/src/game/client/components/camera.h new file mode 100644 index 0000000..0db841c --- /dev/null +++ b/src/game/client/components/camera.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_CAMERA_H +#define GAME_CLIENT_COMPONENTS_CAMERA_H +#include <base/vmath.h> +#include <game/client/component.h> + +class CCamera : public CComponent +{ + enum + { + CAMTYPE_UNDEFINED=-1, + CAMTYPE_SPEC, + CAMTYPE_PLAYER, + }; + + int m_CamType; + vec2 m_LastPos[2]; + vec2 m_PrevCenter; + +public: + vec2 m_Center; + bool m_ZoomSet; + float m_Zoom; + + CCamera(); + virtual void OnRender(); + + // DDRace + + virtual void OnConsoleInit(); + virtual void OnReset(); + +private: + static void ConZoomPlus(IConsole::IResult *pResult, void *pUserData); + static void ConZoomMinus(IConsole::IResult *pResult, void *pUserData); + static void ConZoomReset(IConsole::IResult *pResult, void *pUserData); +}; + +#endif diff --git a/src/game/client/components/chat.cpp b/src/game/client/components/chat.cpp new file mode 100644 index 0000000..9683340 --- /dev/null +++ b/src/game/client/components/chat.cpp @@ -0,0 +1,727 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/string.h> + +#include <engine/engine.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/keys.h> +#include <engine/shared/config.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/client/gameclient.h> + +#include <game/client/components/scoreboard.h> +#include <game/client/components/sounds.h> +#include <game/localization.h> + +#ifdef CONF_PLATFORM_MACOSX +#include <osx/notification.h> +#endif + +#include "chat.h" + + +CChat::CChat() +{ + OnReset(); +} + +void CChat::OnReset() +{ + for(int i = 0; i < MAX_LINES; i++) + { + m_aLines[i].m_Time = 0; + m_aLines[i].m_aText[0] = 0; + m_aLines[i].m_aName[0] = 0; + } + + m_ReverseTAB = false; + m_Mode = MODE_NONE; + m_Show = false; + m_InputUpdate = false; + m_ChatStringOffset = 0; + m_CompletionChosen = -1; + m_aCompletionBuffer[0] = 0; + m_PlaceholderOffset = 0; + m_PlaceholderLength = 0; + m_pHistoryEntry = 0x0; + m_PendingChatCounter = 0; + m_LastChatSend = 0; + + for(int i = 0; i < CHAT_NUM; ++i) + m_aLastSoundPlayed[i] = 0; +} + +void CChat::OnRelease() +{ + m_Show = false; +} + +void CChat::OnStateChange(int NewState, int OldState) +{ + if(OldState <= IClient::STATE_CONNECTING) + { + m_Mode = MODE_NONE; + for(int i = 0; i < MAX_LINES; i++) + m_aLines[i].m_Time = 0; + m_CurrentLine = 0; + } +} + +void CChat::ConSay(IConsole::IResult *pResult, void *pUserData) +{ + ((CChat*)pUserData)->Say(0, pResult->GetString(0)); +} + +void CChat::ConSayTeam(IConsole::IResult *pResult, void *pUserData) +{ + ((CChat*)pUserData)->Say(1, pResult->GetString(0)); +} + +void CChat::ConChat(IConsole::IResult *pResult, void *pUserData) +{ + const char *pMode = pResult->GetString(0); + if(str_comp(pMode, "all") == 0) + ((CChat*)pUserData)->EnableMode(0); + else if(str_comp(pMode, "team") == 0) + ((CChat*)pUserData)->EnableMode(1); + else + ((CChat*)pUserData)->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", "expected all or team as mode"); + + if(pResult->GetString(1)[0] || g_Config.m_ClChatReset) + ((CChat*)pUserData)->m_Input.Set(pResult->GetString(1)); +} + +void CChat::ConShowChat(IConsole::IResult *pResult, void *pUserData) +{ + ((CChat *)pUserData)->m_Show = pResult->GetInteger(0) != 0; +} + +void CChat::OnConsoleInit() +{ + Console()->Register("say", "r[message]", CFGFLAG_CLIENT, ConSay, this, "Say in chat"); + Console()->Register("say_team", "r[message]", CFGFLAG_CLIENT, ConSayTeam, this, "Say in team chat"); + Console()->Register("chat", "s['team'|'all'] ?r[message]", CFGFLAG_CLIENT, ConChat, this, "Enable chat with all/team mode"); + Console()->Register("+show_chat", "", CFGFLAG_CLIENT, ConShowChat, this, "Show chat"); +} + +bool CChat::OnInput(IInput::CEvent Event) +{ + if(m_Mode == MODE_NONE) + return false; + + if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) + { + m_Mode = MODE_NONE; + m_pClient->OnRelease(); + if(g_Config.m_ClChatReset) + m_Input.Clear(); + } + else if(Event.m_Flags&IInput::FLAG_PRESS && (Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)) + { + if(m_Input.GetString()[0]) + { + bool AddEntry = false; + + if(m_LastChatSend+time_freq() < time_get()) + { + Say(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString()); + AddEntry = true; + } + else if(m_PendingChatCounter < 3) + { + ++m_PendingChatCounter; + AddEntry = true; + } + + if(AddEntry) + { + CHistoryEntry *pEntry = m_History.Allocate(sizeof(CHistoryEntry)+m_Input.GetLength()); + pEntry->m_Team = m_Mode == MODE_ALL ? 0 : 1; + mem_copy(pEntry->m_aText, m_Input.GetString(), m_Input.GetLength()+1); + } + } + m_pHistoryEntry = 0x0; + m_Mode = MODE_NONE; + m_pClient->OnRelease(); + m_Input.Clear(); + } + if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_TAB) + { + // fill the completion buffer + if(m_CompletionChosen < 0) + { + const char *pCursor = m_Input.GetString()+m_Input.GetCursorOffset(); + for(int Count = 0; Count < m_Input.GetCursorOffset() && *(pCursor-1) != ' '; --pCursor, ++Count); + m_PlaceholderOffset = pCursor-m_Input.GetString(); + + 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)); + } + + // find next possible name + const char *pCompletionString = 0; + + if(m_ReverseTAB) + m_CompletionChosen = (m_CompletionChosen-1 + 2*MAX_CLIENTS)%(2*MAX_CLIENTS); + else + m_CompletionChosen = (m_CompletionChosen+1)%(2*MAX_CLIENTS); + + for(int i = 0; i < 2*MAX_CLIENTS; ++i) + { + int SearchType; + int Index; + + if(m_ReverseTAB) + { + SearchType = ((m_CompletionChosen-i +2*MAX_CLIENTS)%(2*MAX_CLIENTS))/MAX_CLIENTS; + Index = (m_CompletionChosen-i + MAX_CLIENTS )%MAX_CLIENTS; + } + else + { + SearchType = ((m_CompletionChosen+i)%(2*MAX_CLIENTS))/MAX_CLIENTS; + Index = (m_CompletionChosen+i)%MAX_CLIENTS; + } + + + if(!m_pClient->m_Snap.m_paInfoByName[Index]) + continue; + + int Index2 = m_pClient->m_Snap.m_paInfoByName[Index]->m_ClientID; + + bool Found = false; + if(SearchType == 1) + { + if(str_comp_nocase_num(m_pClient->m_aClients[Index2].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer)) && + str_find_nocase(m_pClient->m_aClients[Index2].m_aName, m_aCompletionBuffer)) + Found = true; + } + else if(!str_comp_nocase_num(m_pClient->m_aClients[Index2].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer))) + Found = true; + + if(Found) + { + pCompletionString = m_pClient->m_aClients[Index2].m_aName; + m_CompletionChosen = Index+SearchType*MAX_CLIENTS; + break; + } + } + + // insert the name + if(pCompletionString) + { + char aBuf[256]; + // add part before the name + str_copy(aBuf, m_Input.GetString(), min(static_cast<int>(sizeof(aBuf)), m_PlaceholderOffset+1)); + + // add the name + str_append(aBuf, pCompletionString, sizeof(aBuf)); + + // add seperator + const char *pSeparator = ""; + if(*(m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength) != ' ') + pSeparator = m_PlaceholderOffset == 0 ? ": " : " "; + else if(m_PlaceholderOffset == 0) + pSeparator = ":"; + if(*pSeparator) + str_append(aBuf, pSeparator, sizeof(aBuf)); + + // add part after the name + str_append(aBuf, m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength, sizeof(aBuf)); + + m_PlaceholderLength = str_length(pSeparator)+str_length(pCompletionString); + m_OldChatStringLength = m_Input.GetLength(); + m_Input.Set(aBuf); + m_Input.SetCursorOffset(m_PlaceholderOffset+m_PlaceholderLength); + m_InputUpdate = true; + } + } + else + { + // reset name completion process + if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key != KEY_TAB) + if(Event.m_Key != KEY_LSHIFT) + m_CompletionChosen = -1; + + m_OldChatStringLength = m_Input.GetLength(); + m_Input.ProcessInput(Event); + m_InputUpdate = true; + } + if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_LSHIFT) + { + m_ReverseTAB = true; + } + else if(Event.m_Flags&IInput::FLAG_RELEASE && Event.m_Key == KEY_LSHIFT) + { + m_ReverseTAB = false; + } + if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_UP) + { + if(m_pHistoryEntry) + { + CHistoryEntry *pTest = m_History.Prev(m_pHistoryEntry); + + if(pTest) + m_pHistoryEntry = pTest; + } + else + m_pHistoryEntry = m_History.Last(); + + if(m_pHistoryEntry) + m_Input.Set(m_pHistoryEntry->m_aText); + } + else if (Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN) + { + if(m_pHistoryEntry) + m_pHistoryEntry = m_History.Next(m_pHistoryEntry); + + if (m_pHistoryEntry) + m_Input.Set(m_pHistoryEntry->m_aText); + else + m_Input.Clear(); + } + + return true; +} + + +void CChat::EnableMode(int Team) +{ + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + return; + + if(m_Mode == MODE_NONE) + { + if(Team) + m_Mode = MODE_TEAM; + else + m_Mode = MODE_ALL; + + Input()->ClearEvents(); + m_CompletionChosen = -1; + UI()->AndroidShowTextInput("", Team ? Localize("Team chat") : Localize("Chat")); + } +} + +void CChat::OnMessage(int MsgType, void *pRawMsg) +{ + if(MsgType == NETMSGTYPE_SV_CHAT) + { + CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; + AddLine(pMsg->m_ClientID, pMsg->m_Team, pMsg->m_pMessage); + } +} + +bool CChat::LineShouldHighlight(const char *pLine, const char *pName) +{ + const char *pHL = str_find_nocase(pLine, pName); + + if (pHL) + { + int Length = str_length(pName); + + if((pLine == pHL || pHL[-1] == ' ') && (pHL[Length] == 0 || pHL[Length] == ' ' || pHL[Length] == '.' || pHL[Length] == '!' || pHL[Length] == ',' || pHL[Length] == '?' || pHL[Length] == ':')) + return true; + + } + + return false; +} + +void CChat::AddLine(int ClientID, int Team, const char *pLine) +{ + if(*pLine == 0 || (ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\0' || // unknown client + m_pClient->m_aClients[ClientID].m_ChatIgnore || + (m_pClient->m_Snap.m_LocalClientID != ClientID && g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[ClientID].m_Friend) || + (m_pClient->m_Snap.m_LocalClientID != ClientID && m_pClient->m_aClients[ClientID].m_Foe)))) + return; + + // trim right and set maximum length to 256 utf8-characters + int Length = 0; + const char *pStr = pLine; + const char *pEnd = 0; + while(*pStr) + { + const char *pStrOld = pStr; + int Code = str_utf8_decode(&pStr); + + // check if unicode is not empty + if(str_utf8_isspace(Code)) + { + pEnd = 0; + } + else if(pEnd == 0) + pEnd = pStrOld; + + if(++Length >= 256) + { + *(const_cast<char *>(pStr)) = 0; + break; + } + } + if(pEnd != 0) + *(const_cast<char *>(pEnd)) = 0; + + bool Highlighted = false; + char *p = const_cast<char*>(pLine); + while(*p) + { + Highlighted = false; + pLine = p; + // find line seperator and strip multiline + while(*p) + { + if(*p++ == '\n') + { + *(p-1) = 0; + break; + } + } + + m_CurrentLine = (m_CurrentLine+1)%MAX_LINES; + m_aLines[m_CurrentLine].m_Time = time_get(); + m_aLines[m_CurrentLine].m_YOffset[0] = -1.0f; + m_aLines[m_CurrentLine].m_YOffset[1] = -1.0f; + m_aLines[m_CurrentLine].m_ClientID = ClientID; + m_aLines[m_CurrentLine].m_Team = Team; + m_aLines[m_CurrentLine].m_NameColor = -2; + + // check for highlighted name + if (Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(ClientID != m_pClient->Client()->m_LocalIDs[0]) + { + // main character + if (LineShouldHighlight(pLine, m_pClient->m_aClients[m_pClient->Client()->m_LocalIDs[0]].m_aName)) + Highlighted = true; + // dummy + if(m_pClient->Client()->DummyConnected() && LineShouldHighlight(pLine, m_pClient->m_aClients[m_pClient->Client()->m_LocalIDs[1]].m_aName)) + Highlighted = true; + } + } + else + { + // on demo playback use local id from snap directly, + // since m_LocalIDs isn't valid there + if (LineShouldHighlight(pLine, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName)) + Highlighted = true; + } + + + m_aLines[m_CurrentLine].m_Highlighted = Highlighted; + + if(ClientID == -1) // server message + { + str_copy(m_aLines[m_CurrentLine].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); + } + else + { + if(m_pClient->m_aClients[ClientID].m_Team == TEAM_SPECTATORS) + m_aLines[m_CurrentLine].m_NameColor = TEAM_SPECTATORS; + + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + if(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED) + m_aLines[m_CurrentLine].m_NameColor = TEAM_RED; + else if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE) + m_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE; + } + + if (Team == 2) // whisper send + { + str_format(m_aLines[m_CurrentLine].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName), "→ %s", m_pClient->m_aClients[ClientID].m_aName); + m_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE; + m_aLines[m_CurrentLine].m_Highlighted = false; + m_aLines[m_CurrentLine].m_Team = 0; + Highlighted = false; + } + else if (Team == 3) // whisper recv + { + str_format(m_aLines[m_CurrentLine].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName), "← %s", m_pClient->m_aClients[ClientID].m_aName); + m_aLines[m_CurrentLine].m_NameColor = TEAM_RED; + m_aLines[m_CurrentLine].m_Highlighted = true; + m_aLines[m_CurrentLine].m_Team = 0; + Highlighted = true; + } + else + { + 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, Team >= 2?"whisper":(m_aLines[m_CurrentLine].m_Team?"teamchat":"chat"), aBuf, Highlighted); + } + + // play sound + int64 Now = time_get(); + if(ClientID == -1) + { + if(Now-m_aLastSoundPlayed[CHAT_SERVER] >= time_freq()*3/10) + { + if(g_Config.m_SndServerMessage) + { + m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0); + m_aLastSoundPlayed[CHAT_SERVER] = Now; + } + } + } + else if(Highlighted) + { + if(Now-m_aLastSoundPlayed[CHAT_HIGHLIGHT] >= time_freq()*3/10) + { +#ifdef CONF_PLATFORM_MACOSX + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "%s%s", m_aLines[m_CurrentLine].m_aName, m_aLines[m_CurrentLine].m_aText); + CNotification::notify("DDNet-Chat", aBuf); +#else + Graphics()->NotifyWindow(); +#endif + if(g_Config.m_SndHighlight) + { + m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0); + m_aLastSoundPlayed[CHAT_HIGHLIGHT] = Now; + } + } + } + else if(Team != 2) + { + if(Now-m_aLastSoundPlayed[CHAT_CLIENT] >= time_freq()*3/10) + { + if ((g_Config.m_SndTeamChat || !m_aLines[m_CurrentLine].m_Team) + && (g_Config.m_SndChat || m_aLines[m_CurrentLine].m_Team)) + { + m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0); + m_aLastSoundPlayed[CHAT_CLIENT] = Now; + } + } + } +} + +void CChat::OnRender() +{ + if (!g_Config.m_ClShowChat) + return; + + // send pending chat messages + if(m_PendingChatCounter > 0 && m_LastChatSend+time_freq() < time_get()) + { + CHistoryEntry *pEntry = m_History.Last(); + for(int i = m_PendingChatCounter-1; pEntry; --i, pEntry = m_History.Prev(pEntry)) + { + if(i == 0) + { + Say(pEntry->m_Team, pEntry->m_aText); + break; + } + } + --m_PendingChatCounter; + } + + float Width = 300.0f*Graphics()->ScreenAspect(); + Graphics()->MapScreen(0.0f, 0.0f, Width, 300.0f); + float x = 5.0f; + float y = 300.0f-20.0f; + if(m_Mode != MODE_NONE) + { + // render chat input + CTextCursor Cursor; + 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) + TextRender()->TextEx(&Cursor, Localize("Team"), -1); + else + TextRender()->TextEx(&Cursor, Localize("Chat"), -1); + + TextRender()->TextEx(&Cursor, ": ", -1); + + // check if the visible text has to be moved + if(m_InputUpdate) + { + if(m_ChatStringOffset > 0 && m_Input.GetLength() < m_OldChatStringLength) + m_ChatStringOffset = max(0, m_ChatStringOffset-(m_OldChatStringLength-m_Input.GetLength())); + + if(m_ChatStringOffset > m_Input.GetCursorOffset()) + m_ChatStringOffset -= m_ChatStringOffset-m_Input.GetCursorOffset(); + else + { + CTextCursor Temp = Cursor; + Temp.m_Flags = 0; + TextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); + TextRender()->TextEx(&Temp, "|", -1); + while(Temp.m_LineCount > 2) + { + ++m_ChatStringOffset; + Temp = Cursor; + Temp.m_Flags = 0; + TextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); + TextRender()->TextEx(&Temp, "|", -1); + } + } + m_InputUpdate = false; + } + + TextRender()->TextEx(&Cursor, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); + static float MarkerOffset = TextRender()->TextWidth(0, 8.0f, "|", -1)/3; + CTextCursor Marker = Cursor; + Marker.m_X -= MarkerOffset; + TextRender()->TextEx(&Marker, "|", -1); + TextRender()->TextEx(&Cursor, m_Input.GetString()+m_Input.GetCursorOffset(), -1); + } + + y -= 8.0f; +#if defined(__ANDROID__) + x += 120.0f; +#endif + + int64 Now = time_get(); + float LineWidth = m_pClient->m_pScoreboard->Active() ? 90.0f : 200.0f; + float HeightLimit = m_pClient->m_pScoreboard->Active() ? 230.0f : m_Show ? 50.0f : 200.0f; + float Begin = x; +#if defined(__ANDROID__) + float FontSize = 10.0f; +#else + float FontSize = 6.0f; +#endif + CTextCursor Cursor; + int OffsetType = m_pClient->m_pScoreboard->Active() ? 1 : 0; + for(int i = 0; i < MAX_LINES; i++) + { + 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) + { + TextRender()->SetCursor(&Cursor, Begin, 0.0f, FontSize, 0); + Cursor.m_LineWidth = LineWidth; + TextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1); + TextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1); + m_aLines[r].m_YOffset[OffsetType] = Cursor.m_Y + Cursor.m_FontSize; + } + y -= m_aLines[r].m_YOffset[OffsetType]; + + // 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 + TextRender()->SetCursor(&Cursor, Begin, y, FontSize, TEXTFLAG_RENDER); + Cursor.m_LineWidth = LineWidth; + + // render name + if (m_aLines[r].m_ClientID == -1) + { + //TextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageSystemHue / 255.0f, g_Config.m_ClMessageSystemSat / 255.0f, g_Config.m_ClMessageSystemLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + else if (m_aLines[r].m_Team) + TextRender()->TextColor(0.45f, 0.9f, 0.45f, Blend); // team message + else if(m_aLines[r].m_NameColor == TEAM_RED) + TextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // red + else if(m_aLines[r].m_NameColor == TEAM_BLUE) + TextRender()->TextColor(0.7f, 0.7f, 1.0f, Blend); // blue + else if(m_aLines[r].m_NameColor == TEAM_SPECTATORS) + TextRender()->TextColor(0.75f, 0.5f, 0.75f, Blend); // spectator + else if(m_aLines[r].m_ClientID >= 0 && g_Config.m_ClChatTeamColors && m_pClient->m_Teams.Team(m_aLines[r].m_ClientID)) + { + vec3 rgb = HslToRgb(vec3(m_pClient->m_Teams.Team(m_aLines[r].m_ClientID) / 64.0f, 1.0f, 0.75f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + else + TextRender()->TextColor(0.8f, 0.8f, 0.8f, Blend); + + TextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1); + + // render line + if (m_aLines[r].m_ClientID == -1) + { + //TextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageSystemHue / 255.0f, g_Config.m_ClMessageSystemSat / 255.0f, g_Config.m_ClMessageSystemLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + else if (m_aLines[r].m_Highlighted) + { + //TextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // highlighted + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHighlightHue / 255.0f, g_Config.m_ClMessageHighlightSat / 255.0f, g_Config.m_ClMessageHighlightLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + else if (m_aLines[r].m_Team) + { + //TextRender()->TextColor(0.65f, 1.0f, 0.65f, Blend); // team message + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageTeamHue / 255.0f, g_Config.m_ClMessageTeamSat / 255.0f, g_Config.m_ClMessageTeamLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + else + { + //TextRender()->TextColor(1.0f, 1.0f, 1.0f, Blend); + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHue / 255.0f, g_Config.m_ClMessageSat / 255.0f, g_Config.m_ClMessageLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, Blend); + } + + + TextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1); + } + + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + +#if defined(__ANDROID__) + static int deferEvent = 0; + if( UI()->AndroidTextInputShown() ) + { + if(m_Mode == MODE_NONE) + { + deferEvent++; + if( deferEvent > 2 ) + EnableMode(0); + } + else + deferEvent = 0; + } + else + { + if(m_Mode != MODE_NONE) + { + deferEvent++; + if( deferEvent > 2 ) + { + IInput::CEvent Event; + Event.m_Flags = IInput::FLAG_PRESS; + Event.m_Key = KEY_RETURN; + OnInput(Event); + } + } + else + deferEvent = 0; + } +#endif +} + +void CChat::Say(int Team, const char *pLine) +{ + m_LastChatSend = time_get(); + + // send chat message + CNetMsg_Cl_Say Msg; + Msg.m_Team = Team; + Msg.m_pMessage = pLine; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); +} diff --git a/src/game/client/components/chat.h b/src/game/client/components/chat.h new file mode 100644 index 0000000..4ce37f2 --- /dev/null +++ b/src/game/client/components/chat.h @@ -0,0 +1,95 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_CHAT_H +#define GAME_CLIENT_COMPONENTS_CHAT_H +#include <engine/shared/ringbuffer.h> +#include <game/client/component.h> +#include <game/client/lineinput.h> + +class CChat : public CComponent +{ + CLineInput m_Input; + + enum + { + MAX_LINES = 25, + }; + + struct CLine + { + int64 m_Time; + float m_YOffset[2]; + int m_ClientID; + int m_Team; + int m_NameColor; + char m_aName[64]; + char m_aText[512]; + bool m_Highlighted; + }; + + CLine m_aLines[MAX_LINES]; + int m_CurrentLine; + + // chat + enum + { + MODE_NONE=0, + MODE_ALL, + MODE_TEAM, + + CHAT_SERVER=0, + CHAT_HIGHLIGHT, + CHAT_CLIENT, + CHAT_NUM, + }; + + int m_Mode; + bool m_Show; + bool m_InputUpdate; + int m_ChatStringOffset; + int m_OldChatStringLength; + int m_CompletionChosen; + char m_aCompletionBuffer[256]; + int m_PlaceholderOffset; + int m_PlaceholderLength; + + bool m_ReverseTAB; + + struct CHistoryEntry + { + int m_Team; + char m_aText[1]; + }; + CHistoryEntry *m_pHistoryEntry; + TStaticRingBuffer<CHistoryEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History; + int m_PendingChatCounter; + int64 m_LastChatSend; + int64 m_aLastSoundPlayed[CHAT_NUM]; + + 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); + + bool LineShouldHighlight(const char *pLine, const char *pName); + +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); + virtual void OnRender(); + virtual void OnRelease(); + virtual void OnMessage(int MsgType, void *pRawMsg); + virtual bool OnInput(IInput::CEvent Event); +}; +#endif diff --git a/src/game/client/components/console.cpp b/src/game/client/components/console.cpp new file mode 100644 index 0000000..f3585fe --- /dev/null +++ b/src/game/client/components/console.cpp @@ -0,0 +1,727 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/sorted_array.h> + +#include <math.h> + +#include <game/generated/client_data.h> + +#include <base/system.h> + +#include <engine/shared/ringbuffer.h> +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/storage.h> +#include <engine/keys.h> +#include <engine/console.h> + +#include <cstring> +#include <cstdio> + +#include <game/client/ui.h> + +#include <game/version.h> + +#include <game/client/lineinput.h> +#include <game/client/render.h> +#include <game/client/components/controls.h> +#include <game/client/components/menus.h> + +#include "console.h" + +CGameConsole::CInstance::CInstance(int Type) +{ + m_pHistoryEntry = 0x0; + + m_Type = Type; + + if(Type == CGameConsole::CONSOLETYPE_LOCAL) + m_CompletionFlagmask = CFGFLAG_CLIENT; + else + m_CompletionFlagmask = CFGFLAG_SERVER; + + m_aCompletionBuffer[0] = 0; + m_CompletionChosen = -1; + m_CompletionRenderOffset = 0.0f; + m_ReverseTAB = false; + + m_IsCommand = false; +} + +void CGameConsole::CInstance::Init(CGameConsole *pGameConsole) +{ + m_pGameConsole = pGameConsole; +}; + +void CGameConsole::CInstance::ClearBacklog() +{ + m_Backlog.Init(); + m_BacklogActPage = 0; +} + +void CGameConsole::CInstance::ClearHistory() +{ + m_History.Init(); + m_pHistoryEntry = 0; +} + +void CGameConsole::CInstance::ExecuteLine(const char *pLine) +{ + if(m_Type == CGameConsole::CONSOLETYPE_LOCAL) + m_pGameConsole->m_pConsole->ExecuteLine(pLine); + else + { + if(m_pGameConsole->Client()->RconAuthed()) + m_pGameConsole->Client()->Rcon(pLine); + else + m_pGameConsole->Client()->RconAuth("", pLine); + } +} + +void CGameConsole::CInstance::PossibleCommandsCompleteCallback(const char *pStr, void *pUser) +{ + CGameConsole::CInstance *pInstance = (CGameConsole::CInstance *)pUser; + if(pInstance->m_CompletionChosen == pInstance->m_CompletionEnumerationCount) + pInstance->m_Input.Set(pStr); + pInstance->m_CompletionEnumerationCount++; +} + +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) + { + if(m_Input.GetString()[0]) + { + if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) + { + char *pEntry = m_History.Allocate(m_Input.GetLength()+1); + mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1); + } + ExecuteLine(m_Input.GetString()); + m_Input.Clear(); + m_pHistoryEntry = 0x0; + } + + Handled = true; + } + else if (Event.m_Key == KEY_UP) + { + if (m_pHistoryEntry) + { + char *pTest = m_History.Prev(m_pHistoryEntry); + + if (pTest) + m_pHistoryEntry = pTest; + } + else + m_pHistoryEntry = m_History.Last(); + + if (m_pHistoryEntry) + m_Input.Set(m_pHistoryEntry); + Handled = true; + } + else if (Event.m_Key == KEY_DOWN) + { + if (m_pHistoryEntry) + m_pHistoryEntry = m_History.Next(m_pHistoryEntry); + + if (m_pHistoryEntry) + m_Input.Set(m_pHistoryEntry); + else + m_Input.Clear(); + Handled = true; + } + else if(Event.m_Key == KEY_TAB) + { + if(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) + { + if(m_ReverseTAB) + m_CompletionChosen--; + else + m_CompletionChosen++; + m_CompletionEnumerationCount = 0; + m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && + m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); + + // handle wrapping + if(m_CompletionEnumerationCount && (m_CompletionChosen >= m_CompletionEnumerationCount || m_CompletionChosen <0)) + { + m_CompletionChosen= (m_CompletionChosen + m_CompletionEnumerationCount) % m_CompletionEnumerationCount; + m_CompletionEnumerationCount = 0; + m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && + m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); + } + } + } + else if(Event.m_Key == KEY_PAGEUP) + { + ++m_BacklogActPage; + } + else if(Event.m_Key == KEY_PAGEDOWN) + { + --m_BacklogActPage; + if(m_BacklogActPage < 0) + m_BacklogActPage = 0; + } + else if(Event.m_Key == KEY_LSHIFT) + { + m_ReverseTAB = true; + Handled = true; + } + } + if(Event.m_Flags&IInput::FLAG_RELEASE && Event.m_Key == KEY_LSHIFT) + { + m_ReverseTAB = false; + Handled = true; + } + + if(!Handled) + m_Input.ProcessInput(Event); + + if(Event.m_Flags&IInput::FLAG_PRESS) + { + if((Event.m_Key != KEY_TAB) && (Event.m_Key != KEY_LSHIFT)) + { + m_CompletionChosen = -1; + str_copy(m_aCompletionBuffer, m_Input.GetString(), sizeof(m_aCompletionBuffer)); + } + + // find the current command + { + char aBuf[64] = {0}; + const char *pSrc = GetString(); + int i = 0; + for(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++) + aBuf[i] = *pSrc; + aBuf[i] = 0; + + const IConsole::CCommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask, + m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands()); + if(pCommand) + { + m_IsCommand = true; + str_copy(m_aCommandName, pCommand->m_pName, IConsole::TEMPCMD_NAME_LENGTH); + str_copy(m_aCommandHelp, pCommand->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); + str_copy(m_aCommandParams, pCommand->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); + } + else + m_IsCommand = false; + } + } +} + +void CGameConsole::CInstance::PrintLine(const char *pLine, bool Highlighted) +{ + int Len = str_length(pLine); + + if (Len > 255) + Len = 255; + + CBacklogEntry *pEntry = m_Backlog.Allocate(sizeof(CBacklogEntry)+Len); + pEntry->m_YOffset = -1.0f; + pEntry->m_Highlighted = Highlighted; + mem_copy(pEntry->m_aText, pLine, Len); + pEntry->m_aText[Len] = 0; +} + +CGameConsole::CGameConsole() +: m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE) +{ + m_ConsoleType = CONSOLETYPE_LOCAL; + m_ConsoleState = CONSOLE_CLOSED; + m_StateChangeEnd = 0.0f; + m_StateChangeDuration = 0.1f; +} + +float CGameConsole::TimeNow() +{ + static long long s_TimeStart = time_get(); + return float(time_get()-s_TimeStart)/float(time_freq()); +} + +CGameConsole::CInstance *CGameConsole::CurrentConsole() +{ + if(m_ConsoleType == CONSOLETYPE_REMOTE) + return &m_RemoteConsole; + return &m_LocalConsole; +} + +void CGameConsole::OnReset() +{ +} + +// only defined for 0<=t<=1 +static float ConsoleScaleFunc(float t) +{ + //return t; + return sinf(acosf(1.0f-t)); +} + +struct CRenderInfo +{ + CGameConsole *m_pSelf; + CTextCursor m_Cursor; + const char *m_pCurrentCmd; + int m_WantedCompletion; + int m_EnumCount; + float m_Offset; + float m_Width; +}; + +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); + pInfo->m_pSelf->Graphics()->TextureSet(-1); + pInfo->m_pSelf->Graphics()->QuadsBegin(); + 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; + else if(pInfo->m_Cursor.m_X+tw > pInfo->m_Width) + pInfo->m_Offset -= pInfo->m_Width/2; + + pInfo->m_pSelf->TextRender()->TextColor(0.05f, 0.05f, 0.05f,1); + pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1); + } + 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); + pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, pMatchStart-pStr); + pInfo->m_pSelf->TextRender()->TextColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,1); + pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart, str_length(pInfo->m_pCurrentCmd)); + pInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1); + pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart+str_length(pInfo->m_pCurrentCmd), -1); + } + else + { + pInfo->m_pSelf->TextRender()->TextColor(0.75f,0.75f,0.75f,1); + 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(); + float ConsoleMaxHeight = Screen.h*3/5.0f; + float ConsoleHeight; + + float Progress = (TimeNow()-(m_StateChangeEnd-m_StateChangeDuration))/float(m_StateChangeDuration); + + if (Progress >= 1.0f) + { + if (m_ConsoleState == CONSOLE_CLOSING) + m_ConsoleState = CONSOLE_CLOSED; + else if (m_ConsoleState == CONSOLE_OPENING) + m_ConsoleState = CONSOLE_OPEN; + + Progress = 1.0f; + } + + if (m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor) + Toggle(CONSOLETYPE_LOCAL); + + if (m_ConsoleState == CONSOLE_CLOSED) + return; + + if (m_ConsoleState == CONSOLE_OPEN) + Input()->MouseModeAbsolute(); + + float ConsoleHeightScale; + + if (m_ConsoleState == CONSOLE_OPENING) + ConsoleHeightScale = ConsoleScaleFunc(Progress); + else if (m_ConsoleState == CONSOLE_CLOSING) + ConsoleHeightScale = ConsoleScaleFunc(1.0f-Progress); + else //if (console_state == CONSOLE_OPEN) + ConsoleHeightScale = ConsoleScaleFunc(1.0f); + + ConsoleHeight = ConsoleHeightScale*ConsoleMaxHeight; + + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + // do console shadow + Graphics()->TextureSet(-1); + 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(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(); + + // 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); + QuadItem = IGraphics::CQuadItem(0, 0, Screen.w, ConsoleHeight); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + // do small bar shadow + Graphics()->TextureSet(-1); + 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); + Array[3] = IGraphics::CColorVertex(3, 0,0,0, 0.25f); + Graphics()->SetColorVertex(Array, 4); + QuadItem = IGraphics::CQuadItem(0, ConsoleHeight-20, Screen.w, 10); + Graphics()->QuadsDrawTL(&QuadItem, 1); + 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); + QuadItem = IGraphics::CQuadItem(0,ConsoleHeight-10.0f,Screen.w,10.0f); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + ConsoleHeight -= 22.0f; + + CInstance *pConsole = CurrentConsole(); + + { + float FontSize = 10.0f; + float RowHeight = FontSize*1.25f; + float x = 3; + float y = ConsoleHeight - RowHeight - 5.0f; + + CRenderInfo Info; + Info.m_pSelf = this; + Info.m_WantedCompletion = pConsole->m_CompletionChosen; + Info.m_EnumCount = 0; + Info.m_Offset = pConsole->m_CompletionRenderOffset; + Info.m_Width = Screen.w; + Info.m_pCurrentCmd = pConsole->m_aCompletionBuffer; + TextRender()->SetCursor(&Info.m_Cursor, x+Info.m_Offset, y+RowHeight+2.0f, FontSize, TEXTFLAG_RENDER); + + // render prompt + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); + const char *pPrompt = "> "; + if(m_ConsoleType == CONSOLETYPE_REMOTE) + { + if(Client()->State() == IClient::STATE_ONLINE) + { + if(Client()->RconAuthed()) + pPrompt = "rcon> "; + else + pPrompt = "ENTER PASSWORD> "; + } + else + pPrompt = "NOT CONNECTED> "; + } + TextRender()->TextEx(&Cursor, pPrompt, -1); + + x = Cursor.m_X; + + //hide rcon password + char aInputString[512]; + str_copy(aInputString, pConsole->m_Input.GetString(), sizeof(aInputString)); + if(m_ConsoleType == CONSOLETYPE_REMOTE && Client()->State() == IClient::STATE_ONLINE && !Client()->RconAuthed()) + { + for(int i = 0; i < pConsole->m_Input.GetLength(); ++i) + aInputString[i] = '*'; + } + + // render console input (wrap line) + TextRender()->SetCursor(&Cursor, x, y, FontSize, 0); + Cursor.m_LineWidth = Screen.w - 10.0f - x; + TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); + TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); + int Lines = Cursor.m_LineCount; + + y -= (Lines - 1) * FontSize; + TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); + Cursor.m_LineWidth = Screen.w - 10.0f - x; + + TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); + static float MarkerOffset = TextRender()->TextWidth(0, FontSize, "|", -1)/3; + CTextCursor Marker = Cursor; + Marker.m_X -= MarkerOffset; + Marker.m_LineWidth = -1; + TextRender()->TextEx(&Marker, "|", -1); + TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); + + // render possible commands + if(m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed()) + { + if(pConsole->m_Input.GetString()[0] != 0) + { + m_pConsole->PossibleCommands(pConsole->m_aCompletionBuffer, pConsole->m_CompletionFlagmask, m_ConsoleType != CGameConsole::CONSOLETYPE_LOCAL && + Client()->RconAuthed() && Client()->UseTempRconCommands(), PossibleCommandsRenderCallback, &Info); + pConsole->m_CompletionRenderOffset = Info.m_Offset; + + if(Info.m_EnumCount <= 0) + { + if(pConsole->m_IsCommand) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Help: %s ", pConsole->m_aCommandHelp); + TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); + TextRender()->TextColor(0.75f, 0.75f, 0.75f, 1); + str_format(aBuf, sizeof(aBuf), "Usage: %s %s", pConsole->m_aCommandName, pConsole->m_aCommandParams); + TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); + } + } + } + } + + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHighlightHue / 255.0f, g_Config.m_ClMessageHighlightSat / 255.0f, g_Config.m_ClMessageHighlightLht / 255.0f)); + + // render log (actual page, wrap lines) + CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.Last(); + float OffsetY = 0.0f; + float LineOffset = 1.0f; + + for(int Page = 0; Page <= pConsole->m_BacklogActPage; ++Page, OffsetY = 0.0f) + { + while(pEntry) + { + if(pEntry->m_Highlighted) + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1); + else + TextRender()->TextColor(1,1,1,1); + + // get y offset (calculate it if we haven't yet) + if(pEntry->m_YOffset < 0.0f) + { + TextRender()->SetCursor(&Cursor, 0.0f, 0.0f, FontSize, 0); + Cursor.m_LineWidth = Screen.w-10; + TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); + 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; + + // just render output from actual backlog page (render bottom up) + if(Page == pConsole->m_BacklogActPage) + { + TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); + Cursor.m_LineWidth = Screen.w-10.0f; + TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); + } + pEntry = pConsole->m_Backlog.Prev(pEntry); + + // reset color + TextRender()->TextColor(1,1,1,1); + } + + // actual backlog page number is too high, render last available page (current checked one, render top down) + if(!pEntry && Page < pConsole->m_BacklogActPage) + { + pConsole->m_BacklogActPage = Page; + pEntry = pConsole->m_Backlog.First(); + while(OffsetY > 0.0f && pEntry) + { + TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); + Cursor.m_LineWidth = Screen.w-10.0f; + TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); + OffsetY -= pEntry->m_YOffset; + pEntry = pConsole->m_Backlog.Next(pEntry); + } + break; + } + } + + // render page + char aBuf[128]; + TextRender()->TextColor(1,1,1,1); + str_format(aBuf, sizeof(aBuf), Localize("-Page %d-"), pConsole->m_BacklogActPage+1); + TextRender()->Text(0, 10.0f, 0.0f, FontSize, aBuf, -1); + + // render version + 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) +{ +} + +bool CGameConsole::OnInput(IInput::CEvent Event) +{ + if(m_ConsoleState == CONSOLE_CLOSED) + return false; + if(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15) + return false; + + if(Event.m_Key == KEY_ESCAPE && (Event.m_Flags&IInput::FLAG_PRESS)) + Toggle(m_ConsoleType); + else + CurrentConsole()->OnInput(Event); + + return true; +} + +void CGameConsole::Toggle(int Type) +{ + if(m_ConsoleType != Type && (m_ConsoleState == CONSOLE_OPEN || m_ConsoleState == CONSOLE_OPENING)) + { + // 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; + } + else + { + float Progress = m_StateChangeEnd-TimeNow(); + float ReversedProgress = m_StateChangeDuration-Progress; + + m_StateChangeEnd = TimeNow()+ReversedProgress; + } + + if (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_CLOSING) + { + /*Input()->MouseModeAbsolute(); + m_pClient->m_pMenus->UseMouseButtons(false);*/ + m_ConsoleState = CONSOLE_OPENING; + /*// reset controls + m_pClient->m_pControls->OnReset();*/ + } + else + { + Input()->MouseModeRelative(); + m_pClient->m_pMenus->UseMouseButtons(true); + m_pClient->OnRelease(); + m_ConsoleState = CONSOLE_CLOSING; + } + } + + m_ConsoleType = Type; +} + +void CGameConsole::Dump(int Type) +{ + CInstance *pConsole = Type == CONSOLETYPE_REMOTE ? &m_RemoteConsole : &m_LocalConsole; + char aFilename[128]; + char aDate[20]; + + str_timestamp(aDate, sizeof(aDate)); + str_format(aFilename, sizeof(aFilename), "dumps/%s_dump_%s.txt", Type==CONSOLETYPE_REMOTE?"remote_console":"local_console", aDate); + IOHANDLE io = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(io) + { + for(CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.First(); pEntry; pEntry = pConsole->m_Backlog.Next(pEntry)) + { + io_write(io, pEntry->m_aText, str_length(pEntry->m_aText)); + io_write_newline(io); + } + io_close(io); + } +} + +void CGameConsole::ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_LOCAL); +} + +void CGameConsole::ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_REMOTE); +} + +void CGameConsole::ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->m_LocalConsole.ClearBacklog(); +} + +void CGameConsole::ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->m_RemoteConsole.ClearBacklog(); +} + +void CGameConsole::ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->Dump(CONSOLETYPE_LOCAL); +} + +void CGameConsole::ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameConsole *)pUserData)->Dump(CONSOLETYPE_REMOTE); +} + +void CGameConsole::ClientConsolePrintCallback(const char *pStr, void *pUserData, bool Highlighted) +{ + ((CGameConsole *)pUserData)->m_LocalConsole.PrintLine(pStr, Highlighted); +} + +void CGameConsole::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 1) + { + CGameConsole *pThis = static_cast<CGameConsole *>(pUserData); + pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); + } +} + +void CGameConsole::PrintLine(int Type, const char *pLine) +{ + if(Type == CONSOLETYPE_LOCAL) + m_LocalConsole.PrintLine(pLine); + else if(Type == CONSOLETYPE_REMOTE) + m_RemoteConsole.PrintLine(pLine); +} + +void CGameConsole::OnConsoleInit() +{ + // init console instances + m_LocalConsole.Init(this); + m_RemoteConsole.Init(this); + + m_pConsole = Kernel()->RequestInterface<IConsole>(); + + // + m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, 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"); + Console()->Register("clear_remote_console", "", CFGFLAG_CLIENT, ConClearRemoteConsole, this, "Clear remote console"); + Console()->Register("dump_local_console", "", CFGFLAG_CLIENT, ConDumpLocalConsole, this, "Dump local console"); + Console()->Register("dump_remote_console", "", CFGFLAG_CLIENT, ConDumpRemoteConsole, this, "Dump remote console"); + + Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this); +} + +void CGameConsole::OnStateChange(int NewState, int OldState) +{ +} diff --git a/src/game/client/components/console.h b/src/game/client/components/console.h new file mode 100644 index 0000000..05ffb70 --- /dev/null +++ b/src/game/client/components/console.h @@ -0,0 +1,113 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_CONSOLE_H +#define GAME_CLIENT_COMPONENTS_CONSOLE_H +#include <engine/shared/ringbuffer.h> +#include <game/client/component.h> +#include <game/client/lineinput.h> + +enum +{ + CONSOLE_CLOSED, + CONSOLE_OPENING, + CONSOLE_OPEN, + CONSOLE_CLOSING, +}; + +class CGameConsole : public CComponent +{ + class CInstance + { + public: + struct CBacklogEntry + { + float m_YOffset; + bool m_Highlighted; + char m_aText[1]; + }; + TStaticRingBuffer<CBacklogEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_Backlog; + TStaticRingBuffer<char, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History; + char *m_pHistoryEntry; + + CLineInput m_Input; + 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; + bool m_ReverseTAB; + + bool m_IsCommand; + char m_aCommandName[IConsole::TEMPCMD_NAME_LENGTH]; + char m_aCommandHelp[IConsole::TEMPCMD_HELP_LENGTH]; + char m_aCommandParams[IConsole::TEMPCMD_PARAMS_LENGTH]; + + CInstance(int t); + void Init(CGameConsole *pGameConsole); + + void ClearBacklog(); + void ClearHistory(); + + void ExecuteLine(const char *pLine); + + void OnInput(IInput::CEvent Event); + void PrintLine(const char *pLine, bool Highlighted = false); + + 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_PrintCBIndex; + + int m_ConsoleType; + int m_ConsoleState; + float m_StateChangeEnd; + float m_StateChangeDuration; + + void Toggle(int Type); + void Dump(int Type); + + static void PossibleCommandsRenderCallback(const char *pStr, void *pUser); + static void ClientConsolePrintCallback(const char *pStr, void *pUserData, bool Highlighted); + static void ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData); + static void ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData); + static void ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData); + static void ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData); + static void ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData); + static void ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData); + static void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + +public: + enum + { + CONSOLETYPE_LOCAL=0, + CONSOLETYPE_REMOTE, + }; + + CGameConsole(); + + void PrintLine(int Type, const char *pLine); + + virtual void OnStateChange(int NewState, int OldState); + virtual void OnConsoleInit(); + virtual void OnReset(); + virtual void OnRender(); + virtual void OnMessage(int MsgType, void *pRawMsg); + virtual bool OnInput(IInput::CEvent Events); + + bool IsClosed() { return m_ConsoleState == CONSOLE_CLOSED; } +}; +#endif diff --git a/src/game/client/components/controls.cpp b/src/game/client/components/controls.cpp new file mode 100644 index 0000000..3440d23 --- /dev/null +++ b/src/game/client/components/controls.cpp @@ -0,0 +1,575 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <stdio.h> + +#include <base/tl/sorted_array.h> + +#include <base/math.h> + +#include <SDL.h> + +#include <engine/shared/config.h> +#include <engine/serverbrowser.h> + +#include <game/collision.h> +#include <game/client/gameclient.h> +#include <game/client/component.h> +#include <game/client/components/chat.h> +#include <game/client/components/menus.h> +#include <game/client/components/scoreboard.h> + +#include "controls.h" + +enum { LEFT_JOYSTICK_X = 0, LEFT_JOYSTICK_Y = 1, + RIGHT_JOYSTICK_X = 2, RIGHT_JOYSTICK_Y = 3, + SECOND_RIGHT_JOYSTICK_X = 20, SECOND_RIGHT_JOYSTICK_Y = 21, + NUM_JOYSTICK_AXES = 22 }; + +CControls::CControls() +{ + mem_zero(&m_LastData, sizeof(m_LastData)); + m_LastDummy = 0; + m_OtherFire = 0; + +#if !defined(__ANDROID__) + if (g_Config.m_InpJoystick) +#endif + { + SDL_Init(SDL_INIT_JOYSTICK); + m_Joystick = SDL_JoystickOpen(0); + if( m_Joystick && SDL_JoystickNumAxes(m_Joystick) < NUM_JOYSTICK_AXES ) + { + SDL_JoystickClose(m_Joystick); + m_Joystick = NULL; + } + + m_Gamepad = SDL_JoystickOpen(2); + + SDL_JoystickEventState(SDL_QUERY); + + m_UsingGamepad = false; +#if defined(CONF_FAMILY_UNIX) + if( getenv("OUYA") ) + m_UsingGamepad = true; +#endif + } +#if !defined(__ANDROID__) + else + { + m_Joystick = NULL; + m_Gamepad = NULL; + m_UsingGamepad = false; + } +#endif +} + +void CControls::OnReset() +{ + ResetInput(0); + ResetInput(1); + + m_JoystickFirePressed = false; + m_JoystickRunPressed = false; + m_JoystickTapTime = 0; + for( int i = 0; i < NUM_WEAPONS; i++ ) + m_AmmoCount[i] = 0; + m_OldMouseX = m_OldMouseY = 0.0f; +} + +void CControls::ResetInput(int dummy) +{ + m_LastData[dummy].m_Direction = 0; + //m_LastData.m_Hook = 0; + // simulate releasing the fire button + if((m_LastData[dummy].m_Fire&1) != 0) + m_LastData[dummy].m_Fire++; + m_LastData[dummy].m_Fire &= INPUT_STATE_MASK; + m_LastData[dummy].m_Jump = 0; + m_InputData[dummy] = m_LastData[dummy]; + + m_InputDirectionLeft[dummy] = 0; + m_InputDirectionRight[dummy] = 0; +} + +void CControls::OnRelease() +{ + //OnReset(); +} + +void CControls::OnPlayerDeath() +{ + if (g_Config.m_ClResetWantedWeaponOnDeath) + m_LastData[g_Config.m_ClDummy].m_WantedWeapon = m_InputData[g_Config.m_ClDummy].m_WantedWeapon = 0; + for( int i = 0; i < NUM_WEAPONS; i++ ) + m_AmmoCount[i] = 0; + m_JoystickTapTime = 0; // Do not launch hook on first tap +} + +struct CInputState +{ + CControls *m_pControls; + int *m_pVariable1; + int *m_pVariable2; +}; + +static void ConKeyInputState(IConsole::IResult *pResult, void *pUserData) +{ + CInputState *pState = (CInputState *)pUserData; + + CServerInfo Info; + pState->m_pControls->GameClient()->Client()->GetServerInfo(&Info); + + if ((IsRace(&Info) || IsDDRace(&Info)) && pState->m_pControls->GameClient()->m_Snap.m_SpecInfo.m_Active) + return; + + if (g_Config.m_ClDummy) + *pState->m_pVariable2 = pResult->GetInteger(0); + else + *pState->m_pVariable1 = pResult->GetInteger(0); +} + +static void ConKeyInputCounter(IConsole::IResult *pResult, void *pUserData) +{ + CInputState *pState = (CInputState *)pUserData; + + CServerInfo Info; + pState->m_pControls->GameClient()->Client()->GetServerInfo(&Info); + + if ((IsRace(&Info) || IsDDRace(&Info)) && pState->m_pControls->GameClient()->m_Snap.m_SpecInfo.m_Active) + return; + + int *v; + if (g_Config.m_ClDummy) + v = pState->m_pVariable2; + else + v = pState->m_pVariable1; + + if(((*v)&1) != pResult->GetInteger(0)) + (*v)++; + *v &= INPUT_STATE_MASK; +} + +struct CInputSet +{ + CControls *m_pControls; + int *m_pVariable1; + int *m_pVariable2; + int m_Value; +}; + +static void ConKeyInputSet(IConsole::IResult *pResult, void *pUserData) +{ + CInputSet *pSet = (CInputSet *)pUserData; + if(pResult->GetInteger(0)) + { + if (g_Config.m_ClDummy) + *pSet->m_pVariable2 = pSet->m_Value; + else + *pSet->m_pVariable1 = pSet->m_Value; + } +} + +static void ConKeyInputNextPrevWeapon(IConsole::IResult *pResult, void *pUserData) +{ + CInputSet *pSet = (CInputSet *)pUserData; + ConKeyInputCounter(pResult, pSet); + pSet->m_pControls->m_InputData[g_Config.m_ClDummy].m_WantedWeapon = 0; +} + +void CControls::OnConsoleInit() +{ + // game commands + { static CInputState s_State = {this, &m_InputDirectionLeft[0], &m_InputDirectionLeft[1]}; Console()->Register("+left", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move left"); } + { static CInputState s_State = {this, &m_InputDirectionRight[0], &m_InputDirectionRight[1]}; Console()->Register("+right", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Move right"); } + { static CInputState s_State = {this, &m_InputData[0].m_Jump, &m_InputData[1].m_Jump}; Console()->Register("+jump", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Jump"); } + { static CInputState s_State = {this, &m_InputData[0].m_Hook, &m_InputData[1].m_Hook}; Console()->Register("+hook", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Hook"); } + { static CInputState s_State = {this, &m_InputData[0].m_Fire, &m_InputData[1].m_Fire}; Console()->Register("+fire", "", CFGFLAG_CLIENT, ConKeyInputCounter, (void *)&s_State, "Fire"); } + { static CInputState s_State = {this, &m_ShowHookColl[0], &m_ShowHookColl[1]}; Console()->Register("+showhookcoll", "", CFGFLAG_CLIENT, ConKeyInputState, (void *)&s_State, "Show Hook Collision"); } + + { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 1}; Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); } + { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 2}; Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); } + { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 3}; Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); } + { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 4}; Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); } + { static CInputSet s_Set = {this, &m_InputData[0].m_WantedWeapon, &m_InputData[1].m_WantedWeapon, 5}; Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to rifle"); } + + { static CInputSet s_Set = {this, &m_InputData[0].m_NextWeapon, &m_InputData[1].m_NextWeapon, 0}; Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); } + { static CInputSet s_Set = {this, &m_InputData[0].m_PrevWeapon, &m_InputData[1].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[g_Config.m_ClDummy].m_WantedWeapon = pMsg->m_Weapon+1; + // We don't really know ammo count, until we'll switch to that weapon, but any non-zero count will suffice here + m_AmmoCount[pMsg->m_Weapon%NUM_WEAPONS] = 10; + } +} + +int CControls::SnapInput(int *pData) +{ + static int64 LastSendTime = 0; + bool Send = false; + + // update player state + if(m_pClient->m_pChat->IsActive()) + m_InputData[g_Config.m_ClDummy].m_PlayerFlags = PLAYERFLAG_CHATTING; + else if(m_pClient->m_pMenus->IsActive()) + m_InputData[g_Config.m_ClDummy].m_PlayerFlags = PLAYERFLAG_IN_MENU; + else + m_InputData[g_Config.m_ClDummy].m_PlayerFlags = PLAYERFLAG_PLAYING; + + if(m_pClient->m_pScoreboard->Active()) + m_InputData[g_Config.m_ClDummy].m_PlayerFlags |= PLAYERFLAG_SCOREBOARD; + + if(m_InputData[g_Config.m_ClDummy].m_PlayerFlags != PLAYERFLAG_PLAYING) + m_JoystickTapTime = 0; // Do not launch hook on first tap + + if (m_pClient->m_pControls->m_ShowHookColl[g_Config.m_ClDummy]) + m_InputData[g_Config.m_ClDummy].m_PlayerFlags |= PLAYERFLAG_AIM; + + if(m_LastData[g_Config.m_ClDummy].m_PlayerFlags != m_InputData[g_Config.m_ClDummy].m_PlayerFlags) + Send = true; + + m_LastData[g_Config.m_ClDummy].m_PlayerFlags = m_InputData[g_Config.m_ClDummy].m_PlayerFlags; + + // we freeze the input if chat or menu is activated + if(!(m_InputData[g_Config.m_ClDummy].m_PlayerFlags&PLAYERFLAG_PLAYING)) + { + ResetInput(g_Config.m_ClDummy); + + mem_copy(pData, &m_InputData[g_Config.m_ClDummy], sizeof(m_InputData[0])); + + // send once a second just to be sure + if(time_get() > LastSendTime + time_freq()) + Send = true; + } + else + { + switch(g_Config.m_ClAutoFire) + { + case 1: + m_InputData[g_Config.m_ClDummy].m_Fire = -m_InputData[g_Config.m_ClDummy].m_Fire+1; + break; + case 2: + m_InputData[g_Config.m_ClDummy].m_Hook = -m_InputData[g_Config.m_ClDummy].m_Hook+1; + break; + } + + if (not g_Config.m_ClWeirdControls) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = (int)m_MousePos[g_Config.m_ClDummy].x; + m_InputData[g_Config.m_ClDummy].m_TargetY = (int)m_MousePos[g_Config.m_ClDummy].y; + if(!m_InputData[g_Config.m_ClDummy].m_TargetX && !m_InputData[g_Config.m_ClDummy].m_TargetY) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = 1; + m_MousePos[g_Config.m_ClDummy].x = 1; + } + } + + else if (g_Config.m_ClWeirdControls == 1) + { + if (m_InputData[g_Config.m_ClDummy].m_Hook or m_InputData[g_Config.m_ClDummy].m_Fire == 1) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = (int)m_MousePos[g_Config.m_ClDummy].x; + m_InputData[g_Config.m_ClDummy].m_TargetY = (int)m_MousePos[g_Config.m_ClDummy].y; + if(!m_InputData[g_Config.m_ClDummy].m_TargetX && !m_InputData[g_Config.m_ClDummy].m_TargetY) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = 1; + m_MousePos[g_Config.m_ClDummy].x = 1; + } + } + else if (m_InputData[g_Config.m_ClDummy].m_Fire > 1) m_InputData[g_Config.m_ClDummy].m_Fire = 0; + } + + else if (g_Config.m_ClWeirdControls == 2) + { + if (not m_InputData[g_Config.m_ClDummy].m_Hook and not m_InputData[g_Config.m_ClDummy].m_Fire) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = -(int)m_MousePos[g_Config.m_ClDummy].x; + m_InputData[g_Config.m_ClDummy].m_TargetY = -(int)m_MousePos[g_Config.m_ClDummy].y; + if(!m_InputData[g_Config.m_ClDummy].m_TargetX && !m_InputData[g_Config.m_ClDummy].m_TargetY) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = 1; + m_MousePos[g_Config.m_ClDummy].x = 1; + } + } + else if (m_InputData[g_Config.m_ClDummy].m_Hook or m_InputData[g_Config.m_ClDummy].m_Fire == 1) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = (int)m_MousePos[g_Config.m_ClDummy].x; + m_InputData[g_Config.m_ClDummy].m_TargetY = (int)m_MousePos[g_Config.m_ClDummy].y; + if(!m_InputData[g_Config.m_ClDummy].m_TargetX && !m_InputData[g_Config.m_ClDummy].m_TargetY) + { + m_InputData[g_Config.m_ClDummy].m_TargetX = 1; + m_MousePos[g_Config.m_ClDummy].x = 1; + } + } + if (m_InputData[g_Config.m_ClDummy].m_Fire > 1) m_InputData[g_Config.m_ClDummy].m_Fire = 0; + } + + // set direction + m_InputData[g_Config.m_ClDummy].m_Direction = 0; + if(m_InputDirectionLeft[g_Config.m_ClDummy] && !m_InputDirectionRight[g_Config.m_ClDummy]) + m_InputData[g_Config.m_ClDummy].m_Direction = -1; + if(!m_InputDirectionLeft[g_Config.m_ClDummy] && m_InputDirectionRight[g_Config.m_ClDummy]) + m_InputData[g_Config.m_ClDummy].m_Direction = 1; + + // dummy copy moves + if(g_Config.m_ClDummyCopyMoves) + { + CNetObj_PlayerInput *DummyInput = &Client()->m_DummyInput; + DummyInput->m_Direction = m_InputData[g_Config.m_ClDummy].m_Direction; + DummyInput->m_Hook = m_InputData[g_Config.m_ClDummy].m_Hook; + DummyInput->m_Jump = m_InputData[g_Config.m_ClDummy].m_Jump; + DummyInput->m_PlayerFlags = m_InputData[g_Config.m_ClDummy].m_PlayerFlags; + DummyInput->m_TargetX = m_InputData[g_Config.m_ClDummy].m_TargetX; + DummyInput->m_TargetY = m_InputData[g_Config.m_ClDummy].m_TargetY; + DummyInput->m_WantedWeapon = m_InputData[g_Config.m_ClDummy].m_WantedWeapon; + + + + DummyInput->m_Fire += m_InputData[g_Config.m_ClDummy].m_Fire - m_LastData[g_Config.m_ClDummy].m_Fire; + DummyInput->m_NextWeapon += m_InputData[g_Config.m_ClDummy].m_NextWeapon - m_LastData[g_Config.m_ClDummy].m_NextWeapon; + DummyInput->m_PrevWeapon += m_InputData[g_Config.m_ClDummy].m_PrevWeapon - m_LastData[g_Config.m_ClDummy].m_PrevWeapon; + + m_InputData[!g_Config.m_ClDummy] = *DummyInput; + } + + // stress testing + if(g_Config.m_DbgStress) + { + float t = Client()->LocalTime(); + mem_zero(&m_InputData[g_Config.m_ClDummy], sizeof(m_InputData[0])); + + m_InputData[g_Config.m_ClDummy].m_Direction = ((int)t/2)&1; + m_InputData[g_Config.m_ClDummy].m_Jump = ((int)t); + m_InputData[g_Config.m_ClDummy].m_Fire = ((int)(t*10)); + m_InputData[g_Config.m_ClDummy].m_Hook = ((int)(t*2))&1; + m_InputData[g_Config.m_ClDummy].m_WantedWeapon = ((int)t)%NUM_WEAPONS; + m_InputData[g_Config.m_ClDummy].m_TargetX = (int)(sinf(t*3)*100.0f); + m_InputData[g_Config.m_ClDummy].m_TargetY = (int)(cosf(t*3)*100.0f); + } + + // check if we need to send input + if(m_InputData[g_Config.m_ClDummy].m_Direction != m_LastData[g_Config.m_ClDummy].m_Direction) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Jump != m_LastData[g_Config.m_ClDummy].m_Jump) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Fire != m_LastData[g_Config.m_ClDummy].m_Fire) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_Hook != m_LastData[g_Config.m_ClDummy].m_Hook) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_WantedWeapon != m_LastData[g_Config.m_ClDummy].m_WantedWeapon) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_NextWeapon != m_LastData[g_Config.m_ClDummy].m_NextWeapon) Send = true; + else if(m_InputData[g_Config.m_ClDummy].m_PrevWeapon != m_LastData[g_Config.m_ClDummy].m_PrevWeapon) Send = true; + + // send at at least 10hz + if(time_get() > LastSendTime + time_freq()/25) + Send = true; + + if(m_pClient->m_Snap.m_pLocalCharacter && m_pClient->m_Snap.m_pLocalCharacter->m_Weapon == WEAPON_NINJA + && (m_InputData[g_Config.m_ClDummy].m_Direction || m_InputData[g_Config.m_ClDummy].m_Jump || m_InputData[g_Config.m_ClDummy].m_Hook)) + Send = true; + } + + // copy and return size + m_LastData[g_Config.m_ClDummy] = m_InputData[g_Config.m_ClDummy]; + + if(!Send) + return 0; + + LastSendTime = time_get(); + mem_copy(pData, &m_InputData[g_Config.m_ClDummy], sizeof(m_InputData[0])); + return sizeof(m_InputData[0]); +} + +void CControls::OnRender() +{ + enum { + JOYSTICK_RUN_DISTANCE = 65536 / 8, + GAMEPAD_DEAD_ZONE = 65536 / 8, + }; + + int64 CurTime = time_get(); + bool FireWasPressed = false; + + if( m_Joystick ) + { + // Get input from left joystick + int RunX = SDL_JoystickGetAxis(m_Joystick, LEFT_JOYSTICK_X); + int RunY = SDL_JoystickGetAxis(m_Joystick, LEFT_JOYSTICK_Y); + bool RunPressed = (RunX != 0 || RunY != 0); + // Get input from right joystick + int AimX = SDL_JoystickGetAxis(m_Joystick, SECOND_RIGHT_JOYSTICK_X); + int AimY = SDL_JoystickGetAxis(m_Joystick, SECOND_RIGHT_JOYSTICK_Y); + bool AimPressed = (AimX != 0 || AimY != 0); + // Get input from another right joystick + int HookX = SDL_JoystickGetAxis(m_Joystick, RIGHT_JOYSTICK_X); + int HookY = SDL_JoystickGetAxis(m_Joystick, RIGHT_JOYSTICK_Y); + bool HookPressed = (HookX != 0 || HookY != 0); + + if( m_JoystickRunPressed != RunPressed ) + { + if( RunPressed ) + { + if( m_JoystickTapTime + time_freq() > CurTime ) // Tap in less than 1 second to jump + m_InputData[g_Config.m_ClDummy].m_Jump = 1; + } + else + m_InputData[g_Config.m_ClDummy].m_Jump = 0; + m_JoystickTapTime = CurTime; + } + + m_JoystickRunPressed = RunPressed; + + if( RunPressed ) + { + m_InputDirectionLeft[g_Config.m_ClDummy] = (RunX < -JOYSTICK_RUN_DISTANCE); + m_InputDirectionRight[g_Config.m_ClDummy] = (RunX > JOYSTICK_RUN_DISTANCE); + } + + // Move 500ms in the same direction, to prevent speed bump when tapping + if( !RunPressed && m_JoystickTapTime + time_freq() / 2 > CurTime ) + { + m_InputDirectionLeft[g_Config.m_ClDummy] = 0; + m_InputDirectionRight[g_Config.m_ClDummy] = 0; + } + + //dbg_msg("dbg", "RunPressed %d m_JoystickSwipeJumpClear %lld m_JoystickSwipeJumpY %d RunY %d cond %d", + // RunPressed, m_JoystickSwipeJumpClear, (int)m_JoystickSwipeJumpY, RunY, + // (int)((!m_JoystickSwipeJumpY && RunY > SWIPE_JUMP_THRESHOLD) || (m_JoystickSwipeJumpY && RunY < -SWIPE_JUMP_THRESHOLD))); + + if( HookPressed ) + { + m_MousePos[g_Config.m_ClDummy] = vec2(HookX / 30, HookY / 30); + ClampMousePos(); + m_InputData[g_Config.m_ClDummy].m_Hook = 1; + } + else + { + m_InputData[g_Config.m_ClDummy].m_Hook = 0; + } + + if( AimPressed ) + { + m_MousePos[g_Config.m_ClDummy] = vec2(AimX / 30, AimY / 30); + ClampMousePos(); + } + + if( AimPressed != m_JoystickFirePressed ) + { + // Fire when releasing joystick + if( !AimPressed ) + { + m_InputData[g_Config.m_ClDummy].m_Fire ++; + if( (bool)(m_InputData[g_Config.m_ClDummy].m_Fire % 2) != AimPressed ) + m_InputData[g_Config.m_ClDummy].m_Fire ++; + FireWasPressed = true; + } + } + + m_JoystickFirePressed = AimPressed; + } + + if( m_Gamepad ) + { + // Get input from left joystick + int RunX = SDL_JoystickGetAxis(m_Gamepad, LEFT_JOYSTICK_X); + int RunY = SDL_JoystickGetAxis(m_Gamepad, LEFT_JOYSTICK_Y); + if( m_UsingGamepad ) + { + m_InputDirectionLeft[g_Config.m_ClDummy] = (RunX < -GAMEPAD_DEAD_ZONE); + m_InputDirectionRight[g_Config.m_ClDummy] = (RunX > GAMEPAD_DEAD_ZONE); + } + + // Get input from right joystick + int AimX = SDL_JoystickGetAxis(m_Gamepad, RIGHT_JOYSTICK_X); + int AimY = SDL_JoystickGetAxis(m_Gamepad, RIGHT_JOYSTICK_Y); + if( abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE ) + { + m_MousePos[g_Config.m_ClDummy] = vec2(AimX / 30, AimY / 30); + ClampMousePos(); + } + + if( !m_UsingGamepad && (abs(AimX) > GAMEPAD_DEAD_ZONE || abs(AimY) > GAMEPAD_DEAD_ZONE || abs(RunX) > GAMEPAD_DEAD_ZONE || abs(RunY) > GAMEPAD_DEAD_ZONE) ) + { + UI()->AndroidShowScreenKeys(false); + m_UsingGamepad = true; + } + } + + CServerInfo Info; + GameClient()->Client()->GetServerInfo(&Info); + + if( g_Config.m_ClAutoswitchWeaponsOutOfAmmo && !IsRace(&Info) && !IsDDRace(&Info) && m_pClient->m_Snap.m_pLocalCharacter ) + { + // Keep track of ammo count, we know weapon ammo only when we switch to that weapon, this is tracked on server and protocol does not track that + m_AmmoCount[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS] = m_pClient->m_Snap.m_pLocalCharacter->m_AmmoCount; + // Autoswitch weapon if we're out of ammo + if( (m_InputData[g_Config.m_ClDummy].m_Fire % 2 != 0 || FireWasPressed) && + m_pClient->m_Snap.m_pLocalCharacter->m_AmmoCount == 0 && + m_pClient->m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_HAMMER && + m_pClient->m_Snap.m_pLocalCharacter->m_Weapon != WEAPON_NINJA ) + { + int w; + for( w = WEAPON_RIFLE; w > WEAPON_GUN; w-- ) + { + if( w == m_pClient->m_Snap.m_pLocalCharacter->m_Weapon ) + continue; + if( m_AmmoCount[w] > 0 ) + break; + } + if( w != m_pClient->m_Snap.m_pLocalCharacter->m_Weapon ) + m_InputData[g_Config.m_ClDummy].m_WantedWeapon = w+1; + } + } + + // update target pos + if(m_pClient->m_Snap.m_pGameInfoObj && !m_pClient->m_Snap.m_SpecInfo.m_Active) + m_TargetPos[g_Config.m_ClDummy] = m_pClient->m_LocalCharacterPos + m_MousePos[g_Config.m_ClDummy]; + else if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_UsePosition) + m_TargetPos[g_Config.m_ClDummy] = m_pClient->m_Snap.m_SpecInfo.m_Position + m_MousePos[g_Config.m_ClDummy]; + else + m_TargetPos[g_Config.m_ClDummy] = m_MousePos[g_Config.m_ClDummy]; +} + +bool CControls::OnMouseMove(float x, float y) +{ + if((m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) || + (m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_pChat->IsActive())) + return false; + +#if defined(__ANDROID__) // No relative mouse on Android + // We're using joystick on Android, mouse is disabled + if( m_OldMouseX != x || m_OldMouseY != y ) + { + m_OldMouseX = x; + m_OldMouseY = y; + m_MousePos[g_Config.m_ClDummy] = vec2((x - g_Config.m_GfxScreenWidth/2), (y - g_Config.m_GfxScreenHeight/2)); + ClampMousePos(); + } +#else + m_MousePos[g_Config.m_ClDummy] += vec2(x, y); // TODO: ugly + ClampMousePos(); +#endif + + return true; +} + +void CControls::ClampMousePos() +{ + if(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition) + { + m_MousePos[g_Config.m_ClDummy].x = clamp(m_MousePos[g_Config.m_ClDummy].x, 200.0f, Collision()->GetWidth()*32-200.0f); + m_MousePos[g_Config.m_ClDummy].y = clamp(m_MousePos[g_Config.m_ClDummy].y, 200.0f, Collision()->GetHeight()*32-200.0f); + } + else + { + float CameraMaxDistance = 200.0f; + float FollowFactor = (g_Config.m_ClDyncam ? g_Config.m_ClDyncamFollowFactor : g_Config.m_ClMouseFollowfactor) / 100.0f; + float DeadZone = g_Config.m_ClDyncam ? g_Config.m_ClDyncamDeadzone : g_Config.m_ClMouseDeadzone; + float MaxDistance = g_Config.m_ClDyncam ? g_Config.m_ClDyncamMaxDistance : g_Config.m_ClMouseMaxDistance; + float MouseMax = min(CameraMaxDistance/FollowFactor + DeadZone, MaxDistance); + + if(length(m_MousePos[g_Config.m_ClDummy]) > MouseMax) + m_MousePos[g_Config.m_ClDummy] = normalize(m_MousePos[g_Config.m_ClDummy])*MouseMax; + } +} diff --git a/src/game/client/components/controls.h b/src/game/client/components/controls.h new file mode 100644 index 0000000..413091d --- /dev/null +++ b/src/game/client/components/controls.h @@ -0,0 +1,49 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_CONTROLS_H +#define GAME_CLIENT_COMPONENTS_CONTROLS_H +#include <SDL_joystick.h> +#include <base/vmath.h> +#include <base/system.h> +#include <game/client/component.h> + +class CControls : public CComponent +{ +public: + vec2 m_MousePos[2]; + vec2 m_TargetPos[2]; + float m_OldMouseX; + float m_OldMouseY; + SDL_Joystick *m_Joystick; + bool m_JoystickFirePressed; + bool m_JoystickRunPressed; + int64 m_JoystickTapTime; + + SDL_Joystick *m_Gamepad; + bool m_UsingGamepad; + + int m_AmmoCount[NUM_WEAPONS]; + + CNetObj_PlayerInput m_InputData[2]; + CNetObj_PlayerInput m_LastData[2]; + int m_InputDirectionLeft[2]; + int m_InputDirectionRight[2]; + int m_ShowHookColl[2]; + int m_LastDummy; + int m_OtherFire; + + CControls(); + + virtual void OnReset(); + virtual void OnRelease(); + virtual void OnRender(); + virtual void OnMessage(int MsgType, void *pRawMsg); + virtual bool OnMouseMove(float x, float y); + virtual void OnConsoleInit(); + virtual void OnPlayerDeath(); + + int SnapInput(int *pData); + void ClampMousePos(); + void ResetInput(int dummy); +}; +#endif diff --git a/src/game/client/components/countryflags.cpp b/src/game/client/components/countryflags.cpp new file mode 100644 index 0000000..f9310f8 --- /dev/null +++ b/src/game/client/components/countryflags.cpp @@ -0,0 +1,164 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <base/system.h> + +#include <engine/console.h> +#include <engine/graphics.h> +#include <engine/storage.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> +#include <engine/shared/linereader.h> + +#include "countryflags.h" + + +void CCountryFlags::LoadCountryflagsIndexfile() +{ + IOHANDLE File = Storage()->OpenFile("countryflags/index.txt", IOFLAG_READ, IStorage::TYPE_ALL); + if(!File) + { + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "couldn't open index file"); + return; + } + + char aOrigin[128]; + CLineReader LineReader; + LineReader.Init(File); + char *pLine; + while((pLine = LineReader.Get())) + { + if(!str_length(pLine) || pLine[0] == '#') // skip empty lines and comments + continue; + + str_copy(aOrigin, pLine, sizeof(aOrigin)); + char *pReplacement = LineReader.Get(); + if(!pReplacement) + { + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "unexpected end of index file"); + break; + } + + if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ') + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "malform replacement for index '%s'", aOrigin); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); + continue; + } + + int CountryCode = str_toint(pReplacement+3); + if(CountryCode < CODE_LB || CountryCode > CODE_UB) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "country code '%i' not within valid code range [%i..%i]", CountryCode, CODE_LB, CODE_UB); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); + continue; + } + + // load the graphic file + char aBuf[128]; + CImageInfo Info; + if(g_Config.m_ClLoadCountryFlags) + { + str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", aOrigin); + if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL)) + { + char aMsg[128]; + str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg); + continue; + } + } + + // add entry + CCountryFlag CountryFlag; + CountryFlag.m_CountryCode = CountryCode; + str_copy(CountryFlag.m_aCountryCodeString, aOrigin, sizeof(CountryFlag.m_aCountryCodeString)); + if(g_Config.m_ClLoadCountryFlags) + { + CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); + mem_free(Info.m_pData); + } + else + CountryFlag.m_Texture = -1; + if(g_Config.m_Debug) + { + str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", aOrigin); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); + } + m_aCountryFlags.add_unsorted(CountryFlag); + } + io_close(File); + m_aCountryFlags.sort_range(); + + // find index of default item + int DefaultIndex = 0, Index = 0; + for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index) + if(r.front().m_CountryCode == -1) + { + DefaultIndex = Index; + break; + } + + // init LUT + if(DefaultIndex != 0) + for(int i = 0; i < CODE_RANGE; ++i) + m_CodeIndexLUT[i] = DefaultIndex; + else + mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT)); + for(int i = 0; i < m_aCountryFlags.size(); ++i) + m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i; +} + +void CCountryFlags::OnInit() +{ + // load country flags + m_aCountryFlags.clear(); + LoadCountryflagsIndexfile(); + if(!m_aCountryFlags.size()) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "countryflags", "failed to load country flags. folder='countryflags/'"); + CCountryFlag DummyEntry; + DummyEntry.m_CountryCode = -1; + DummyEntry.m_Texture = -1; + mem_zero(DummyEntry.m_aCountryCodeString, sizeof(DummyEntry.m_aCountryCodeString)); + m_aCountryFlags.add(DummyEntry); + } +} + +int CCountryFlags::Num() const +{ + return m_aCountryFlags.size(); +} + +const CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const +{ + return GetByIndex(m_CodeIndexLUT[max(0, (CountryCode-CODE_LB)%CODE_RANGE)]); +} + +const CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index) const +{ + return &m_aCountryFlags[max(0, Index%m_aCountryFlags.size())]; +} + +void CCountryFlags::Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h) +{ + const CCountryFlag *pFlag = GetByCountryCode(CountryCode); + if(pFlag->m_Texture != -1) + { + Graphics()->TextureSet(pFlag->m_Texture); + Graphics()->QuadsBegin(); + Graphics()->SetColor(pColor->r, pColor->g, pColor->b, pColor->a); + IGraphics::CQuadItem QuadItem(x, y, w, h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + else + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = w; + TextRender()->TextEx(&Cursor, pFlag->m_aCountryCodeString, -1); + } +} diff --git a/src/game/client/components/countryflags.h b/src/game/client/components/countryflags.h new file mode 100644 index 0000000..df93482 --- /dev/null +++ b/src/game/client/components/countryflags.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H +#define GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H +#include <base/vmath.h> +#include <base/tl/sorted_array.h> +#include <game/client/component.h> + +class CCountryFlags : public CComponent +{ +public: + struct CCountryFlag + { + int m_CountryCode; + char m_aCountryCodeString[8]; + int m_Texture; + + bool operator<(const CCountryFlag &Other) { return str_comp(m_aCountryCodeString, Other.m_aCountryCodeString) < 0; } + }; + + void OnInit(); + + int Num() const; + const CCountryFlag *GetByCountryCode(int CountryCode) const; + const CCountryFlag *GetByIndex(int Index) const; + void Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h); + +private: + enum + { + CODE_LB=-1, + CODE_UB=999, + CODE_RANGE=CODE_UB-CODE_LB+1, + }; + sorted_array<CCountryFlag> m_aCountryFlags; + int m_CodeIndexLUT[CODE_RANGE]; + + void LoadCountryflagsIndexfile(); +}; +#endif diff --git a/src/game/client/components/damageind.cpp b/src/game/client/components/damageind.cpp new file mode 100644 index 0000000..6303059 --- /dev/null +++ b/src/game/client/components/damageind.cpp @@ -0,0 +1,92 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/demo.h> +#include <engine/graphics.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/gamecore.h> // get_angle +#include <game/client/ui.h> +#include <game/client/render.h> +#include "damageind.h" + +CDamageInd::CDamageInd() +{ + m_Lastupdate = 0; + m_NumItems = 0; +} + +CDamageInd::CItem *CDamageInd::CreateI() +{ + if (m_NumItems < MAX_ITEMS) + { + CItem *p = &m_aItems[m_NumItems]; + m_NumItems++; + return p; + } + return 0; +} + +void CDamageInd::DestroyI(CDamageInd::CItem *i) +{ + m_NumItems--; + *i = m_aItems[m_NumItems]; +} + +void CDamageInd::Create(vec2 Pos, vec2 Dir) +{ + CItem *i = CreateI(); + if (i) + { + i->m_Pos = Pos; + i->m_StartTime = Client()->LocalTime(); + i->m_Dir = Dir*-1; + i->m_StartAngle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi; + } +} + +void CDamageInd::OnRender() +{ + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + static float s_LastLocalTime = Client()->LocalTime(); + for(int i = 0; i < m_NumItems;) + { + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(pInfo->m_Paused) + m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime; + else + m_aItems[i].m_StartTime += (Client()->LocalTime()-s_LastLocalTime)*(1.0f-pInfo->m_Speed); + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime; + } + + float Life = 0.75f - (Client()->LocalTime() - m_aItems[i].m_StartTime); + if(Life < 0.0f) + DestroyI(&m_aItems[i]); + else + { + vec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((Life-0.60f)/0.15f, 0.0f, 1.0f)); + Graphics()->SetColor(1.0f,1.0f,1.0f, Life/0.1f); + Graphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + Life * 2.0f); + RenderTools()->SelectSprite(SPRITE_STAR1); + RenderTools()->DrawSprite(Pos.x, Pos.y, 48.0f); + i++; + } + } + s_LastLocalTime = Client()->LocalTime(); + Graphics()->QuadsEnd(); +} + +void CDamageInd::Reset() +{ + for(int i = 0; i < m_NumItems;) + { + DestroyI(&m_aItems[i]); + } +} diff --git a/src/game/client/components/damageind.h b/src/game/client/components/damageind.h new file mode 100644 index 0000000..dd9e41f --- /dev/null +++ b/src/game/client/components/damageind.h @@ -0,0 +1,37 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_DAMAGEIND_H +#define GAME_CLIENT_COMPONENTS_DAMAGEIND_H +#include <base/vmath.h> +#include <game/client/component.h> + +class CDamageInd : public CComponent +{ + int64 m_Lastupdate; + struct CItem + { + vec2 m_Pos; + vec2 m_Dir; + float m_StartTime; + float m_StartAngle; + }; + + enum + { + MAX_ITEMS=64, + }; + + CItem m_aItems[MAX_ITEMS]; + int m_NumItems; + + CItem *CreateI(); + void DestroyI(CItem *i); + +public: + CDamageInd(); + + void Create(vec2 Pos, vec2 Dir); + void Reset(); + virtual void OnRender(); +}; +#endif diff --git a/src/game/client/components/debughud.cpp b/src/game/client/components/debughud.cpp new file mode 100644 index 0000000..45849ec --- /dev/null +++ b/src/game/client/components/debughud.cpp @@ -0,0 +1,142 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/textrender.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/layers.h> + +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include <game/client/render.h> + +//#include "controls.h" +//#include "camera.h" +#include "debughud.h" + +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(); + 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[g_Config.m_ClDummy].m_VelrampStart, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); + + 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; + + float x = Width-100.0f, y = 50.0f; + for(int i = 0; i < Num; ++i) + TextRender()->Text(0, x, y+i*LineHeight, Fontsize, paStrings[i], -1); + + x = Width-10.0f; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32); + float w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += LineHeight; + str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32*Ramp); + w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += LineHeight; + str_format(aBuf, sizeof(aBuf), "%.2f", Ramp); + w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += 2*LineHeight; + str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_Snap.m_pLocalCharacter->m_X/32); + w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += LineHeight; + str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_Snap.m_pLocalCharacter->m_Y/32); + w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += 2*LineHeight; + str_format(aBuf, sizeof(aBuf), "%d", m_pClient->NetobjNumCorrections()); + w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); + TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); + y += LineHeight; + w = TextRender()->TextWidth(0, Fontsize, m_pClient->NetobjCorrectedOn(), -1); + TextRender()->Text(0, x-w, y, Fontsize, m_pClient->NetobjCorrectedOn(), -1); +} + +void CDebugHud::RenderTuning() +{ + // render tuning debugging + if(!g_Config.m_DbgTuning) + return; + + CTuningParams StandardTuning; + + Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); + + float y = 27.0f; + int Count = 0; + for(int i = 0; i < m_pClient->m_Tuning[g_Config.m_ClDummy].Num(); i++) + { + char aBuf[128]; + float Current, Standard; + m_pClient->m_Tuning[g_Config.m_ClDummy].Get(i, &Current); + StandardTuning.Get(i, &Standard); + + if(Standard == Current) + TextRender()->TextColor(1,1,1,1.0f); + else + TextRender()->TextColor(1,0.25f,0.25f,1.0f); + + float w; + float x = 5.0f; + + str_format(aBuf, sizeof(aBuf), "%.2f", Standard); + x += 20.0f; + w = TextRender()->TextWidth(0, 5, aBuf, -1); + TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1); + + str_format(aBuf, sizeof(aBuf), "%.2f", Current); + x += 20.0f; + w = TextRender()->TextWidth(0, 5, aBuf, -1); + TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1); + + x += 5.0f; + TextRender()->Text(0x0, x, y+Count*6, 5, m_pClient->m_Tuning[g_Config.m_ClDummy].m_apNames[i], -1); + + Count++; + } + + y = y+Count*6; + + Graphics()->TextureSet(-1); + Graphics()->BlendNormal(); + Graphics()->LinesBegin(); + float Height = 50.0f; + float pv = 1; + IGraphics::CLineItem Array[100]; + for(int i = 0; i < 100; i++) + { + float Speed = i/100.0f * 3000; + float Ramp = VelocityRamp(Speed, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pClient->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); + float RampedSpeed = (Speed * Ramp)/1000.0f; + Array[i] = IGraphics::CLineItem((i-1)*2, y+Height-pv*Height, i*2, y+Height-RampedSpeed*Height); + //Graphics()->LinesDraw((i-1)*2, 200, i*2, 200); + pv = RampedSpeed; + } + Graphics()->LinesDraw(Array, 100); + Graphics()->LinesEnd(); + TextRender()->TextColor(1,1,1,1); +} + +void CDebugHud::OnRender() +{ + RenderTuning(); + RenderNetCorrections(); +} diff --git a/src/game/client/components/debughud.h b/src/game/client/components/debughud.h new file mode 100644 index 0000000..145f921 --- /dev/null +++ b/src/game/client/components/debughud.h @@ -0,0 +1,15 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_DEBUGHUD_H +#define GAME_CLIENT_COMPONENTS_DEBUGHUD_H +#include <game/client/component.h> + +class CDebugHud : public CComponent +{ + void RenderNetCorrections(); + void RenderTuning(); +public: + virtual void OnRender(); +}; + +#endif diff --git a/src/game/client/components/effects.cpp b/src/game/client/components/effects.cpp new file mode 100644 index 0000000..3a23f87 --- /dev/null +++ b/src/game/client/components/effects.cpp @@ -0,0 +1,308 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/sorted_array.h> + +#include <engine/demo.h> +#include <engine/engine.h> + +#include <engine/shared/config.h> + +#include <game/generated/client_data.h> + +#include <game/client/components/particles.h> +#include <game/client/components/skins.h> +#include <game/client/components/flow.h> +#include <game/client/components/damageind.h> +#include <game/client/components/sounds.h> +#include <game/client/gameclient.h> + +#include "effects.h" + +inline vec2 RandomDir() { return normalize(vec2(frandom()-0.5f, frandom()-0.5f)); } + +CEffects::CEffects() +{ + m_Add50hz = false; + m_Add100hz = false; +} + +void CEffects::AirJump(vec2 Pos) +{ + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_AIRJUMP; + p.m_Pos = Pos + vec2(-6.0f, 16.0f); + p.m_Vel = vec2(0, -200); + p.m_LifeSpan = 0.5f; + p.m_StartSize = 48.0f; + p.m_EndSize = 0; + p.m_Rot = frandom()*pi*2; + p.m_Rotspeed = pi*2; + p.m_Gravity = 500; + p.m_Friction = 0.7f; + p.m_FlowAffected = 0.0f; + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); + + p.m_Pos = Pos + vec2(6.0f, 16.0f); + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); + + if(g_Config.m_SndGame) + m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos); +} + +void CEffects::DamageIndicator(vec2 Pos, vec2 Dir) +{ + m_pClient->m_pDamageind->Create(Pos, Dir); +} + +void CEffects::ResetDamageIndicator() +{ + m_pClient->m_pDamageind->Reset(); +} + +void CEffects::PowerupShine(vec2 Pos, vec2 size) +{ + if(!m_Add50hz) + return; + + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SLICE; + p.m_Pos = Pos + vec2((frandom()-0.5f)*size.x, (frandom()-0.5f)*size.y); + p.m_Vel = vec2(0, 0); + p.m_LifeSpan = 0.5f; + p.m_StartSize = 16.0f; + p.m_EndSize = 0; + p.m_Rot = frandom()*pi*2; + p.m_Rotspeed = pi*2; + p.m_Gravity = 500; + p.m_Friction = 0.9f; + p.m_FlowAffected = 0.0f; + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); +} + +void CEffects::SmokeTrail(vec2 Pos, vec2 Vel) +{ + if(!m_Add50hz) + return; + + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SMOKE; + p.m_Pos = Pos; + p.m_Vel = Vel + RandomDir()*50.0f; + p.m_LifeSpan = 0.5f + frandom()*0.5f; + p.m_StartSize = 12.0f + frandom()*8; + p.m_EndSize = 0; + p.m_Friction = 0.7f; + p.m_Gravity = frandom()*-500.0f; + m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); +} + + +void CEffects::SkidTrail(vec2 Pos, vec2 Vel) +{ + if(!m_Add100hz) + return; + + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SMOKE; + p.m_Pos = Pos; + p.m_Vel = Vel + RandomDir()*50.0f; + p.m_LifeSpan = 0.5f + frandom()*0.5f; + p.m_StartSize = 24.0f + frandom()*12; + p.m_EndSize = 0; + 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); +} + +void CEffects::BulletTrail(vec2 Pos) +{ + if(!m_Add100hz) + return; + + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_BALL; + p.m_Pos = Pos; + p.m_LifeSpan = 0.25f + frandom()*0.25f; + p.m_StartSize = 8.0f; + p.m_EndSize = 0; + p.m_Friction = 0.7f; + m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); +} + +void CEffects::PlayerSpawn(vec2 Pos) +{ + for(int i = 0; i < 32; i++) + { + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SHELL; + p.m_Pos = Pos; + p.m_Vel = RandomDir() * (powf(frandom(), 3)*600.0f); + p.m_LifeSpan = 0.3f + frandom()*0.3f; + p.m_StartSize = 64.0f + frandom()*32; + p.m_EndSize = 0; + p.m_Rot = frandom()*pi*2; + p.m_Rotspeed = frandom(); + p.m_Gravity = frandom()*-400.0f; + 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); + + } + if(g_Config.m_SndGame) + m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos); +} + +void CEffects::PlayerDeath(vec2 Pos, int ClientID) +{ + vec3 BloodColor(1.0f,1.0f,1.0f); + + if(ClientID >= 0) + { + if(m_pClient->m_aClients[ClientID].m_UseCustomColor) + BloodColor = m_pClient->m_pSkins->GetColorV3(m_pClient->m_aClients[ClientID].m_ColorBody); + else + { + const CSkins::CSkin *s = m_pClient->m_pSkins->Get(m_pClient->m_aClients[ClientID].m_SkinID); + if(s) + BloodColor = s->m_BloodColor; + } + } + + for(int i = 0; i < 64; i++) + { + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SPLAT01 + (rand()%3); + p.m_Pos = Pos; + p.m_Vel = RandomDir() * ((frandom()+0.1f)*900.0f); + p.m_LifeSpan = 0.3f + frandom()*0.3f; + p.m_StartSize = 24.0f + frandom()*16; + p.m_EndSize = 0; + p.m_Rot = frandom()*pi*2; + p.m_Rotspeed = (frandom()-0.5f) * pi; + p.m_Gravity = 800.0f; + p.m_Friction = 0.8f; + vec3 c = BloodColor * (0.75f + frandom()*0.25f); + p.m_Color = vec4(c.r, c.g, c.b, 0.75f); + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); + } +} + + +void CEffects::Explosion(vec2 Pos) +{ + // add to flow + for(int y = -8; y <= 8; y++) + for(int x = -8; x <= 8; x++) + { + 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(); + p.m_Spr = SPRITE_PART_EXPL01; + p.m_Pos = Pos; + p.m_LifeSpan = 0.4f; + p.m_StartSize = 150.0f; + 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++) + { + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_SMOKE; + p.m_Pos = Pos; + p.m_Vel = RandomDir() * ((1.0f + frandom()*0.2f) * 1000.0f); + p.m_LifeSpan = 0.5f + frandom()*0.4f; + p.m_StartSize = 32.0f + frandom()*8; + p.m_EndSize = 0; + p.m_Gravity = frandom()*-800.0f; + p.m_Friction = 0.4f; + p.m_Color = mix(vec4(0.75f,0.75f,0.75f,1.0f), vec4(0.5f,0.5f,0.5f,1.0f), frandom()); + m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); + } +} + + +void CEffects::HammerHit(vec2 Pos) +{ + // add the explosion + CParticle p; + p.SetDefault(); + p.m_Spr = SPRITE_PART_HIT01; + p.m_Pos = Pos; + p.m_LifeSpan = 0.3f; + p.m_StartSize = 120.0f; + p.m_EndSize = 0; + p.m_Rot = frandom()*pi*2; + m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); + if(g_Config.m_SndGame) + m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos); +} + +void CEffects::OnRender() +{ + static int64 LastUpdate100hz = 0; + static int64 LastUpdate50hz = 0; + + 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; + LastUpdate100hz = time_get(); + } + else + m_Add100hz = false; + + if(time_get()-LastUpdate50hz > time_freq()/(100*pInfo->m_Speed)) + { + m_Add50hz = true; + LastUpdate50hz = time_get(); + } + else + m_Add50hz = false; + + if(m_Add50hz) + m_pClient->m_pFlow->Update(); + + return; + } + + if(time_get()-LastUpdate100hz > time_freq()/100) + { + m_Add100hz = true; + LastUpdate100hz = time_get(); + } + else + m_Add100hz = false; + + if(time_get()-LastUpdate50hz > time_freq()/100) + { + m_Add50hz = true; + LastUpdate50hz = time_get(); + } + 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 new file mode 100644 index 0000000..2b43c61 --- /dev/null +++ b/src/game/client/components/effects.h @@ -0,0 +1,30 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_EFFECTS_H +#define GAME_CLIENT_COMPONENTS_EFFECTS_H +#include <game/client/component.h> + +class CEffects : public CComponent +{ + bool m_Add50hz; + bool m_Add100hz; +public: + CEffects(); + + virtual void OnRender(); + + void BulletTrail(vec2 Pos); + void SmokeTrail(vec2 Pos, vec2 Vel); + void SkidTrail(vec2 Pos, vec2 Vel); + void Explosion(vec2 Pos); + void HammerHit(vec2 Pos); + void AirJump(vec2 Pos); + void DamageIndicator(vec2 Pos, vec2 Dir); + void ResetDamageIndicator(); + void PlayerSpawn(vec2 Pos); + void PlayerDeath(vec2 Pos, int ClientID); + void PowerupShine(vec2 Pos, vec2 Size); + + void Update(); +}; +#endif diff --git a/src/game/client/components/emoticon.cpp b/src/game/client/components/emoticon.cpp new file mode 100644 index 0000000..18ed2cc --- /dev/null +++ b/src/game/client/components/emoticon.cpp @@ -0,0 +1,231 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/serverbrowser.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/gamecore.h> // get_angle +#include <game/client/animstate.h> +#include <game/client/ui.h> +#include <game/client/render.h> +#include "chat.h" +#include "emoticon.h" + +CEmoticon::CEmoticon() +{ + OnReset(); +} + +void CEmoticon::ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData) +{ + CEmoticon *pSelf = (CEmoticon *)pUserData; + if(!pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active && pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK) + pSelf->m_Active = pResult->GetInteger(0) != 0; +} + +void CEmoticon::ConEmote(IConsole::IResult *pResult, void *pUserData) +{ + ((CEmoticon *)pUserData)->Emote(pResult->GetInteger(0)); +} + +void CEmoticon::OnConsoleInit() +{ + Console()->Register("+emote", "", CFGFLAG_CLIENT, ConKeyEmoticon, this, "Open emote selector"); + Console()->Register("emote", "i[emote-id]", CFGFLAG_CLIENT, ConEmote, this, "Use emote"); +} + +void CEmoticon::OnReset() +{ + m_WasActive = false; + m_Active = false; + m_SelectedEmote = -1; + m_SelectedEyeEmote = -1; +} + +void CEmoticon::OnRelease() +{ + m_Active = false; +} + +bool CEmoticon::OnMouseMove(float x, float y) +{ + if(!m_Active) + return false; + +#if defined(__ANDROID__) // No relative mouse on Android + m_SelectorMouse = vec2(x,y); +#else + UI()->ConvertMouseMove(&x, &y); + m_SelectorMouse += vec2(x,y); +#endif + return true; +} + +void CEmoticon::DrawCircle(float x, float y, float r, int Segments) +{ + RenderTools()->DrawCircle(x, y, r, Segments); +} + + +void CEmoticon::OnRender() +{ + if(!m_Active) + { + if(m_WasActive && m_SelectedEmote != -1) + Emote(m_SelectedEmote); + if(m_WasActive && m_SelectedEyeEmote != -1) + EyeEmote(m_SelectedEyeEmote); + m_WasActive = false; + return; + } + + if(m_pClient->m_Snap.m_SpecInfo.m_Active) + { + m_Active = false; + m_WasActive = false; + return; + } + + m_WasActive = true; + + if (length(m_SelectorMouse) > 170.0f) + m_SelectorMouse = normalize(m_SelectorMouse) * 170.0f; + + float SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24; + if (SelectedAngle < 0) + SelectedAngle += 2*pi; + + m_SelectedEmote = -1; + m_SelectedEyeEmote = -1; + if (length(m_SelectorMouse) > 110.0f) + m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS); + else if(length(m_SelectorMouse) > 40.0f) + m_SelectedEyeEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTES); + + + CUIRect Screen = *UI()->Screen(); + + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + Graphics()->BlendNormal(); + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.3f); + DrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64); + Graphics()->QuadsEnd(); + + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); + Graphics()->QuadsBegin(); + + for (int i = 0; i < NUM_EMOTICONS; i++) + { + float Angle = 2*pi*i/NUM_EMOTICONS; + if (Angle > pi) + Angle -= 2*pi; + + bool Selected = m_SelectedEmote == i; + + float Size = Selected ? 80.0f : 50.0f; + + float NudgeX = 150.0f * cosf(Angle); + float NudgeY = 150.0f * sinf(Angle); + RenderTools()->SelectSprite(SPRITE_OOP + i); + IGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size); + Graphics()->QuadsDraw(&QuadItem, 1); + } + + Graphics()->QuadsEnd(); + + CServerInfo pServerInfo; + Client()->GetServerInfo(&pServerInfo); + if((IsDDRace(&pServerInfo) || IsDDNet(&pServerInfo) || IsPlus(&pServerInfo)) && g_Config.m_ClEyeWheel) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0,1.0,1.0,0.3f); + DrawCircle(Screen.w/2, Screen.h/2, 100.0f, 64); + Graphics()->QuadsEnd(); + + CTeeRenderInfo *pTeeInfo; + if(g_Config.m_ClDummy) + pTeeInfo = &m_pClient->m_aClients[m_pClient->Client()->m_LocalIDs[1]].m_RenderInfo; + else + pTeeInfo = &m_pClient->m_aClients[m_pClient->Client()->m_LocalIDs[0]].m_RenderInfo; + + Graphics()->TextureSet(pTeeInfo->m_Texture); + + for (int i = 0; i < NUM_EMOTES; i++) + { + float Angle = 2*pi*i/NUM_EMOTES; + if (Angle > pi) + Angle -= 2*pi; + + bool Selected = m_SelectedEyeEmote == i; + + pTeeInfo->m_Size = Selected ? 64.0f : 48.0f; + + float NudgeX = 70.0f * cosf(Angle); + float NudgeY = 70.0f * sinf(Angle); + RenderTools()->RenderTee(CAnimState::GetIdle(), pTeeInfo, i, vec2(-1,0), vec2(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY)); + } + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.3f); + DrawCircle(Screen.w/2, Screen.h/2, 30.0f, 64); + Graphics()->QuadsEnd(); + } + else + m_SelectedEyeEmote = -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(); +} + +void CEmoticon::Emote(int Emoticon) +{ + CNetMsg_Cl_Emoticon Msg; + Msg.m_Emoticon = Emoticon; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + + if(g_Config.m_ClDummyCopyMoves) + { + CMsgPacker Msg(NETMSGTYPE_CL_EMOTICON); + Msg.AddInt(Emoticon); + Client()->SendMsgExY(&Msg, MSGFLAG_VITAL, false, !g_Config.m_ClDummy); + } +} + +void CEmoticon::EyeEmote(int Emote) +{ + char aBuf[32]; + switch(Emote) + { + case EMOTE_NORMAL: + str_format(aBuf, sizeof(aBuf), "/emote normal %d", g_Config.m_ClEyeDuration); + break; + case EMOTE_PAIN: + str_format(aBuf, sizeof(aBuf), "/emote pain %d", g_Config.m_ClEyeDuration); + break; + case EMOTE_HAPPY: + str_format(aBuf, sizeof(aBuf), "/emote happy %d", g_Config.m_ClEyeDuration); + break; + case EMOTE_SURPRISE: + str_format(aBuf, sizeof(aBuf), "/emote surprise %d", g_Config.m_ClEyeDuration); + break; + case EMOTE_ANGRY: + str_format(aBuf, sizeof(aBuf), "/emote angry %d", g_Config.m_ClEyeDuration); + break; + case EMOTE_BLINK: + str_format(aBuf, sizeof(aBuf), "/emote blink %d", g_Config.m_ClEyeDuration); + break; + } + GameClient()->m_pChat->Say(0, aBuf); +} diff --git a/src/game/client/components/emoticon.h b/src/game/client/components/emoticon.h new file mode 100644 index 0000000..4d56450 --- /dev/null +++ b/src/game/client/components/emoticon.h @@ -0,0 +1,35 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_EMOTICON_H +#define GAME_CLIENT_COMPONENTS_EMOTICON_H +#include <base/vmath.h> +#include <game/client/component.h> + +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; + int m_SelectedEyeEmote; + + 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(); + virtual void OnRelease(); + virtual bool OnMouseMove(float x, float y); + + void Emote(int Emote); + void EyeEmote(int EyeEmote); +}; + +#endif diff --git a/src/game/client/components/flow.cpp b/src/game/client/components/flow.cpp new file mode 100644 index 0000000..8cfc54e --- /dev/null +++ b/src/game/client/components/flow.cpp @@ -0,0 +1,96 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <game/mapitems.h> +#include <game/layers.h> +#include "flow.h" + +CFlow::CFlow() +{ + m_pCells = 0; + m_Height = 0; + m_Width = 0; + m_Spacing = 16; +} + +void CFlow::DbgRender() +{ + if(!m_pCells) + return; + + IGraphics::CLineItem Array[1024]; + int NumItems = 0; + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + { + vec2 Pos(x*m_Spacing, y*m_Spacing); + vec2 Vel = m_pCells[y*m_Width+x].m_Vel * 0.01f; + Array[NumItems++] = IGraphics::CLineItem(Pos.x, Pos.y, Pos.x+Vel.x, Pos.y+Vel.y); + if(NumItems == 1024) + { + Graphics()->LinesDraw(Array, 1024); + NumItems = 0; + } + } + + if(NumItems) + Graphics()->LinesDraw(Array, NumItems); + Graphics()->LinesEnd(); +} + +void CFlow::Init() +{ + if(m_pCells) + { + 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 + 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++) + m_pCells[y*m_Width+x].m_Vel = vec2(0.0f, 0.0f); +} + +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; +} + +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; +} + +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 new file mode 100644 index 0000000..0b8e590 --- /dev/null +++ b/src/game/client/components/flow.h @@ -0,0 +1,30 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_FLOW_H +#define GAME_CLIENT_COMPONENTS_FLOW_H +#include <base/vmath.h> +#include <game/client/component.h> + +class CFlow : public CComponent +{ + struct CCell + { + vec2 m_Vel; + }; + + CCell *m_pCells; + 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(); +}; + +#endif diff --git a/src/game/client/components/ghost.cpp b/src/game/client/components/ghost.cpp new file mode 100644 index 0000000..18dea4d --- /dev/null +++ b/src/game/client/components/ghost.cpp @@ -0,0 +1,607 @@ +/* (c) Rajh, Redix and Sushi. */ + +#include <cstdio> + +#include <engine/storage.h> +#include <engine/graphics.h> +#include <engine/shared/config.h> +#include <engine/shared/compression.h> +#include <engine/shared/network.h> + +#include <game/generated/client_data.h> +#include <game/client/animstate.h> + +#include "skins.h" +#include "menus.h" +#include "ghost.h" + +/* +Note: +Freezing fucks up the ghost +the ghost isnt really sync +don't really get the client tick system for prediction +can used PrevChar and PlayerChar and it would be fluent and accurate but won't be predicted +so it will be affected by lags +*/ + +static const unsigned char gs_aHeaderMarker[8] = {'T', 'W', 'G', 'H', 'O', 'S', 'T', 0}; +static const unsigned char gs_ActVersion = 2; + +CGhost::CGhost() +{ + m_lGhosts.clear(); + m_CurGhost.m_Path.clear(); + m_CurGhost.m_ID = -1; + m_CurPos = 0; + m_Recording = false; + m_Rendering = false; + m_RaceState = RACE_NONE; + m_NewRecord = false; + m_BestTime = -1; + m_StartRenderTick = -1; +} + +void CGhost::AddInfos(CGhostCharacter Player) +{ + if(!m_Recording) + return; + + // Just to be sure it doesnt eat too much memory, the first test should be enough anyway + if(m_CurGhost.m_Path.size() > Client()->GameTickSpeed()*60*20) + { + dbg_msg("ghost", "20 minutes elapsed. Stopping ghost record"); + StopRecord(); + m_CurGhost.m_Path.clear(); + return; + } + + m_CurGhost.m_Path.add(Player); +} + +void CGhost::OnRender() +{ + if(!g_Config.m_ClRaceGhost || Client()->State() != IClient::STATE_ONLINE) + return; + + // Check if the race line is crossed then start the render of the ghost if one + bool start = false; + + std::list < int > Indices = m_pClient->Collision()->GetMapIndices(m_pClient->m_PredictedPrevChar.m_Pos, m_pClient->m_LocalCharacterPos); + if(!Indices.empty()) + { + for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + if(m_pClient->Collision()->GetTileIndex(*i) == TILE_BEGIN) start = true; + } + else + { + start = m_pClient->Collision()->GetTileIndex(m_pClient->Collision()->GetPureMapIndex(m_pClient->m_LocalCharacterPos)) == TILE_BEGIN; + } + + if(start) + { + OnReset(); + m_RaceState = RACE_STARTED; + StartRender(); + StartRecord(); + } + + if(m_RaceState == RACE_FINISHED) + { + if(m_NewRecord) + { + // search for own ghost + array<CGhostItem>::range r = find_linear(m_lGhosts.all(), m_CurGhost); + m_NewRecord = false; + if(r.empty()) + m_lGhosts.add(m_CurGhost); + else + r.front() = m_CurGhost; + + Save(); + } + StopRecord(); + StopRender(); + m_RaceState = RACE_NONE; + } + + CNetObj_Character Char = m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_LocalClientID].m_Cur; + m_pClient->m_PredictedChar.Write(&Char); + + if(m_pClient->m_NewPredictedTick) + AddInfos(GetGhostCharacter(Char)); + + // Play the ghost + if(!m_Rendering || !g_Config.m_ClRaceShowGhost) + return; + + m_CurPos = Client()->PredGameTick()-m_StartRenderTick; + + if(m_lGhosts.size() == 0 || m_CurPos < 0) + { + StopRender(); + return; + } + + for(int i = 0; i < m_lGhosts.size(); i++) + { + CGhostItem *pGhost = &m_lGhosts[i]; + if(m_CurPos >= pGhost->m_Path.size()) + continue; + + int PrevPos = (m_CurPos > 0) ? m_CurPos-1 : m_CurPos; + CGhostCharacter Player = pGhost->m_Path[m_CurPos]; + CGhostCharacter Prev = pGhost->m_Path[PrevPos]; + CNetObj_ClientInfo Info = pGhost->m_Info; + + RenderGhostHook(Player, Prev); + RenderGhost(Player, Prev, Info); + } +} + +void CGhost::RenderGhost(CGhostCharacter Player, CGhostCharacter Prev, CNetObj_ClientInfo Info) +{ + char aSkinName[64]; + IntsToStr(&Info.m_Skin0, 6, aSkinName); + int SkinId = m_pClient->m_pSkins->Find(aSkinName); + if(SkinId < 0) + { + SkinId = m_pClient->m_pSkins->Find("default"); + if(SkinId < 0) + SkinId = 0; + } + + CTeeRenderInfo RenderInfo; + RenderInfo.m_ColorBody = m_pClient->m_pSkins->GetColorV4(Info.m_ColorBody); + RenderInfo.m_ColorFeet = m_pClient->m_pSkins->GetColorV4(Info.m_ColorFeet); + + if(Info.m_UseCustomColor) + RenderInfo.m_Texture = m_pClient->m_pSkins->Get(SkinId)->m_ColorTexture; + else + { + RenderInfo.m_Texture = m_pClient->m_pSkins->Get(SkinId)->m_OrgTexture; + RenderInfo.m_ColorBody = vec4(1,1,1,1); + RenderInfo.m_ColorFeet = vec4(1,1,1,1); + } + + RenderInfo.m_ColorBody.a = 0.5f; + RenderInfo.m_ColorFeet.a = 0.5f; + RenderInfo.m_Size = 64; + + float IntraTick = Client()->PredIntraGameTick(); + + float Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f; + 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); + + bool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1; + bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16); + bool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0); + + float WalkTime = fmod(absolute(Position.x), 100.0f)/100.0f; + CAnimState State; + State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); + + if(InAir) + State.Add(&g_pData->m_aAnimations[ANIM_INAIR], 0, 1.0f); + else if(Stationary) + State.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); + else if(!WantOtherDir) + State.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f); + + if (Player.m_Weapon == WEAPON_GRENADE) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + Graphics()->QuadsSetRotation(State.GetAttach()->m_Angle*pi*2+Angle); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); + + // normal weapons + int iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS-1); + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_pSpriteBody, Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0); + + vec2 Dir = Direction; + float Recoil = 0.0f; + // TODO: is this correct? + float a = (Client()->PredGameTick()-Player.m_AttackTick+IntraTick)/5.0f; + if(a < 1) + Recoil = sinf(a*pi); + + vec2 p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Direction*Recoil*10.0f; + p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; + RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); + Graphics()->QuadsEnd(); + } + + // Render ghost + RenderTools()->RenderTee(&State, &RenderInfo, 0, Direction, Position, true); +} + +void CGhost::RenderGhostHook(CGhostCharacter Player, CGhostCharacter Prev) +{ + if (Prev.m_HookState<=0 || Player.m_HookState<=0) + return; + + float IntraTick = Client()->PredIntraGameTick(); + + vec2 Pos = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); + + vec2 HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick); + float d = distance(Pos, HookPos); + vec2 Dir = normalize(Pos-HookPos); + + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + Graphics()->QuadsSetRotation(GetAngle(Dir)+pi); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); + + // render head + RenderTools()->SelectSprite(SPRITE_HOOK_HEAD); + IGraphics::CQuadItem QuadItem(HookPos.x, HookPos.y, 24, 16); + Graphics()->QuadsDraw(&QuadItem, 1); + + // render chain + RenderTools()->SelectSprite(SPRITE_HOOK_CHAIN); + IGraphics::CQuadItem Array[1024]; + int j = 0; + for(float f = 24; f < d && j < 1024; f += 24, j++) + { + vec2 p = HookPos + Dir*f; + Array[j] = IGraphics::CQuadItem(p.x, p.y, 24, 16); + } + + Graphics()->QuadsDraw(Array, j); + Graphics()->QuadsSetRotation(0); + Graphics()->QuadsEnd(); +} + +CGhost::CGhostCharacter CGhost::GetGhostCharacter(CNetObj_Character Char) +{ + CGhostCharacter Player; + Player.m_X = Char.m_X; + Player.m_Y = Char.m_Y; + Player.m_VelX = Char.m_VelX; + Player.m_VelY = Char.m_VelY; + Player.m_Angle = Char.m_Angle; + Player.m_Direction = Char.m_Direction; + Player.m_Weapon = Char.m_Weapon; + Player.m_HookState = Char.m_HookState; + Player.m_HookX = Char.m_HookX; + Player.m_HookY = Char.m_HookY; + Player.m_AttackTick = Char.m_AttackTick; + + return Player; +} + +void CGhost::StartRecord() +{ + m_Recording = true; + m_CurGhost.m_Path.clear(); + CNetObj_ClientInfo *pInfo = (CNetObj_ClientInfo *) Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_CLIENTINFO, m_pClient->m_Snap.m_LocalClientID); + if (pInfo) + m_CurGhost.m_Info = *pInfo; +} + +void CGhost::StopRecord() +{ + m_Recording = false; +} + +void CGhost::StartRender() +{ + m_CurPos = 0; + m_Rendering = true; + m_StartRenderTick = Client()->PredGameTick(); +} + +void CGhost::StopRender() +{ + m_Rendering = false; +} + +void CGhost::Save() +{ + if(!g_Config.m_ClRaceSaveGhost) + return; + + CGhostHeader Header; + + // check the player name + char aName[MAX_NAME_LENGTH]; + str_copy(aName, g_Config.m_PlayerName, sizeof(aName)); + for(int i = 0; i < MAX_NAME_LENGTH; i++) + { + if(!aName[i]) + break; + + if(aName[i] == '\\' || aName[i] == '/' || aName[i] == '|' || aName[i] == ':' || aName[i] == '*' || aName[i] == '?' || aName[i] == '<' || aName[i] == '>' || aName[i] == '"') + aName[i] = '%'; + } + + char aFilename[256]; + char aBuf[256]; + str_format(aFilename, sizeof(aFilename), "%s_%s_%.3f_%08x.gho", Client()->GetCurrentMap(), aName, m_BestTime, Client()->GetCurrentMapCrc()); + str_format(aBuf, sizeof(aBuf), "ghosts/%s", aFilename); + IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(!File) + return; + + // write header + int Crc = Client()->GetCurrentMapCrc(); + mem_zero(&Header, sizeof(Header)); + mem_copy(Header.m_aMarker, gs_aHeaderMarker, sizeof(Header.m_aMarker)); + Header.m_Version = gs_ActVersion; + IntsToStr(&m_CurGhost.m_Info.m_Name0, 4, Header.m_aOwner); + str_copy(Header.m_aMap, Client()->GetCurrentMap(), sizeof(Header.m_aMap)); + Header.m_aCrc[0] = (Crc>>24)&0xff; + Header.m_aCrc[1] = (Crc>>16)&0xff; + Header.m_aCrc[2] = (Crc>>8)&0xff; + Header.m_aCrc[3] = (Crc)&0xff; + Header.m_Time = m_BestTime; + Header.m_NumShots = m_CurGhost.m_Path.size(); + io_write(File, &Header, sizeof(Header)); + + // write client info + io_write(File, &m_CurGhost.m_Info, sizeof(m_CurGhost.m_Info)); + + // write data + int ItemsPerPackage = 500; // 500 ticks per package + int Num = Header.m_NumShots; + CGhostCharacter *Data = &m_CurGhost.m_Path[0]; + + while(Num) + { + int Items = min(Num, ItemsPerPackage); + Num -= Items; + + char aBuffer[100*500]; + char aBuffer2[100*500]; + unsigned char aSize[4]; + + int Size = sizeof(CGhostCharacter)*Items; + mem_copy(aBuffer2, Data, Size); + Data += Items; + + Size = CVariableInt::Compress(aBuffer2, Size, aBuffer); + Size = CNetBase::Compress(aBuffer, Size, aBuffer2, sizeof(aBuffer2)); + + aSize[0] = (Size>>24)&0xff; + aSize[1] = (Size>>16)&0xff; + aSize[2] = (Size>>8)&0xff; + aSize[3] = (Size)&0xff; + + io_write(File, aSize, sizeof(aSize)); + io_write(File, aBuffer2, Size); + } + + io_close(File); + + // remove old ghost from list (TODO: remove other ghosts?) + if(m_pClient->m_pMenus->m_OwnGhost) + { + char aFile[256]; + str_format(aFile, sizeof(aFile), "ghosts/%s", m_pClient->m_pMenus->m_OwnGhost->m_aFilename); + Storage()->RemoveFile(aFile, IStorage::TYPE_SAVE); + + m_pClient->m_pMenus->m_lGhosts.remove(*m_pClient->m_pMenus->m_OwnGhost); + } + + CMenus::CGhostItem Item; + str_copy(Item.m_aFilename, aFilename, sizeof(Item.m_aFilename)); + str_copy(Item.m_aPlayer, Header.m_aOwner, sizeof(Item.m_aPlayer)); + Item.m_Time = m_BestTime; + Item.m_Active = true; + Item.m_ID = -1; + + m_pClient->m_pMenus->m_lGhosts.add(Item); + m_pClient->m_pMenus->m_OwnGhost = &find_linear(m_pClient->m_pMenus->m_lGhosts.all(), Item).front(); + + dbg_msg("ghost", "Saved better ghost"); + m_Saving = false; +} + +bool CGhost::GetHeader(IOHANDLE *pFile, CGhostHeader *pHeader) +{ + if(!*pFile) + return 0; + + CGhostHeader Header; + io_read(*pFile, &Header, sizeof(Header)); + + *pHeader = Header; + + if(mem_comp(Header.m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) != 0) + return 0; + + if(Header.m_Version != gs_ActVersion) + return 0; + + int Crc = (Header.m_aCrc[0]<<24) | (Header.m_aCrc[1]<<16) | (Header.m_aCrc[2]<<8) | (Header.m_aCrc[3]); + if(str_comp(Header.m_aMap, Client()->GetCurrentMap()) != 0 || Crc != Client()->GetCurrentMapCrc()) + return 0; + + return 1; +} + +bool CGhost::GetInfo(const char* pFilename, CGhostHeader *pHeader) +{ + char aFilename[256]; + str_format(aFilename, sizeof(aFilename), "ghosts/%s", pFilename); + IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_READ, IStorage::TYPE_SAVE); + if(!File) + return 0; + + bool Check = GetHeader(&File, pHeader); + io_close(File); + + return Check; +} + +void CGhost::Load(const char* pFilename, int ID) +{ + char aFilename[256]; + str_format(aFilename, sizeof(aFilename), "ghosts/%s", pFilename); + IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_READ, IStorage::TYPE_SAVE); + if(!File) + return; + + // read header + CGhostHeader Header; + if(!GetHeader(&File, &Header)) + { + io_close(File); + return; + } + + if(ID == -1) + m_BestTime = Header.m_Time; + + int NumShots = Header.m_NumShots; + + // create ghost + CGhostItem Ghost; + Ghost.m_ID = ID; + Ghost.m_Path.clear(); + Ghost.m_Path.set_size(NumShots); + + // read client info + io_read(File, &Ghost.m_Info, sizeof(Ghost.m_Info)); + + // read data + int Index = 0; + while(Index < NumShots) + { + static char aCompresseddata[100*500]; + static char aDecompressed[100*500]; + static char aData[100*500]; + + unsigned char aSize[4]; + if(io_read(File, aSize, sizeof(aSize)) != sizeof(aSize)) + break; + int Size = (aSize[0]<<24) | (aSize[1]<<16) | (aSize[2]<<8) | aSize[3]; + + if(io_read(File, aCompresseddata, Size) != (unsigned)Size) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ghost", "error reading chunk"); + break; + } + + Size = CNetBase::Decompress(aCompresseddata, Size, aDecompressed, sizeof(aDecompressed)); + if(Size < 0) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ghost", "error during network decompression"); + break; + } + + Size = CVariableInt::Decompress(aDecompressed, Size, aData); + if(Size < 0) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "ghost", "error during intpack decompression"); + break; + } + + CGhostCharacter *Tmp = (CGhostCharacter*)aData; + for(unsigned i = 0; i < Size/sizeof(CGhostCharacter); i++) + { + if(Index >= NumShots) + break; + + Ghost.m_Path[Index] = *Tmp; + Index++; + Tmp++; + } + } + + io_close(File); + + m_lGhosts.add(Ghost); +} + +void CGhost::Unload(int ID) +{ + CGhostItem Item; + Item.m_ID = ID; + m_lGhosts.remove_fast(Item); +} + +void CGhost::ConGPlay(IConsole::IResult *pResult, void *pUserData) +{ + ((CGhost *)pUserData)->StartRender(); +} + +void CGhost::OnConsoleInit() +{ + Console()->Register("gplay", "", CFGFLAG_CLIENT, ConGPlay, this, ""); +} + +void CGhost::OnMessage(int MsgType, void *pRawMsg) +{ + if(!g_Config.m_ClRaceGhost || Client()->State() != IClient::STATE_ONLINE || m_pClient->m_Snap.m_SpecInfo.m_Active) + return; + + // check for messages from server + if(MsgType == NETMSGTYPE_SV_KILLMSG) + { + CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; + if(pMsg->m_Victim == m_pClient->m_Snap.m_LocalClientID) + { + if(!m_Saving) + OnReset(); + } + } + else if(MsgType == NETMSGTYPE_SV_CHAT) + { + CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; + if(pMsg->m_ClientID == -1 && m_RaceState == RACE_STARTED) + { + const char* pMessage = pMsg->m_pMessage; + + int Num = 0; + while(str_comp_num(pMessage, " finished in: ", 14)) + { + pMessage++; + Num++; + if(!pMessage[0]) + return; + } + + // store the name + char aName[64]; + str_copy(aName, pMsg->m_pMessage, Num+1); + + // prepare values and state for saving + int Minutes; + float Seconds; + if(!str_comp(aName, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName) && sscanf(pMessage, " finished in: %d minute(s) %f", &Minutes, &Seconds) == 2) + { + m_RaceState = RACE_FINISHED; + float CurTime = Minutes*60 + Seconds; + if(m_Recording && (CurTime < m_BestTime || m_BestTime == -1)) + { + m_NewRecord = true; + m_BestTime = CurTime; + m_Saving = true; + } + } + } + } +} + +void CGhost::OnReset() +{ + StopRecord(); + StopRender(); + m_RaceState = RACE_NONE; + m_NewRecord = false; + m_CurGhost.m_Path.clear(); + m_StartRenderTick = -1; + m_Saving = false; +} + +void CGhost::OnMapLoad() +{ + OnReset(); + m_BestTime = -1; + m_lGhosts.clear(); + m_pClient->m_pMenus->GhostlistPopulate(); +} diff --git a/src/game/client/components/ghost.h b/src/game/client/components/ghost.h new file mode 100644 index 0000000..eb5810f --- /dev/null +++ b/src/game/client/components/ghost.h @@ -0,0 +1,98 @@ +/* (c) Rajh, Redix and Sushi. */ + +#ifndef GAME_CLIENT_COMPONENTS_GHOST_H +#define GAME_CLIENT_COMPONENTS_GHOST_H + +#include <game/client/component.h> + +class CGhost : public CComponent +{ +public: + struct CGhostHeader + { + unsigned char m_aMarker[8]; + unsigned char m_Version; + char m_aOwner[MAX_NAME_LENGTH]; + char m_aMap[64]; + unsigned char m_aCrc[4]; + int m_NumShots; + float m_Time; + }; + +private: + struct CGhostCharacter + { + int m_X; + int m_Y; + int m_VelX; + int m_VelY; + int m_Angle; + int m_Direction; + int m_Weapon; + int m_HookState; + int m_HookX; + int m_HookY; + int m_AttackTick; + }; + + struct CGhostItem + { + int m_ID; + CNetObj_ClientInfo m_Info; + array<CGhostCharacter> m_Path; + + bool operator==(const CGhostItem &Other) { return m_ID == Other.m_ID; } + }; + + array<CGhostItem> m_lGhosts; + CGhostItem m_CurGhost; + + int m_StartRenderTick; + int m_CurPos; + bool m_Recording; + bool m_Rendering; + int m_RaceState; + float m_BestTime; + bool m_NewRecord; + bool m_Saving; + + enum + { + RACE_NONE = 0, + RACE_STARTED, + RACE_FINISHED, + }; + + void AddInfos(CGhostCharacter Player); + + CGhostCharacter GetGhostCharacter(CNetObj_Character Char); + + void StartRecord(); + void StopRecord(); + void StartRender(); + void StopRender(); + void RenderGhost(CGhostCharacter Player, CGhostCharacter Prev, CNetObj_ClientInfo Info); + void RenderGhostHook(CGhostCharacter Player, CGhostCharacter Prev); + + bool GetHeader(IOHANDLE *pFile, CGhostHeader *pHeader); + + void Save(); + + static void ConGPlay(IConsole::IResult *pResult, void *pUserData); + +public: + CGhost(); + + virtual void OnRender(); + virtual void OnConsoleInit(); + virtual void OnReset(); + virtual void OnMessage(int MsgType, void *pRawMsg); + virtual void OnMapLoad(); + + void Load(const char* pFilename, int ID); + void Unload(int ID); + + bool GetInfo(const char* pFilename, CGhostHeader *pHeader); +}; + +#endif diff --git a/src/game/client/components/hud.cpp b/src/game/client/components/hud.cpp new file mode 100644 index 0000000..66ab7f8 --- /dev/null +++ b/src/game/client/components/hud.cpp @@ -0,0 +1,694 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/serverbrowser.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> +#include <game/layers.h> +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include <game/client/render.h> +#include <game/client/components/scoreboard.h> + +#include "controls.h" +#include "camera.h" +#include "hud.h" +#include "voting.h" +#include "binds.h" + +CHud::CHud() +{ + // won't work if zero + m_AverageFPS = 1.0f; + OnReset(); +} + +void CHud::OnReset() +{ + m_CheckpointDiff = 0.0f; + m_DDRaceTime = 0; + m_LastReceivedTimeTick = 0; + m_CheckpointTick = 0; + m_DDRaceTick = 0; + m_FinishTime = false; + m_DDRaceTimeReceived = false; + m_ServerRecord = -1.0f; + m_PlayerRecord = -1.0f; +} + +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]; + int Time = 0; + if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit && !m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer) + { + 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; + } + else + Time = (Client()->GameTick()-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick)/Client()->GameTickSpeed(); + + CServerInfo Info; + Client()->GetServerInfo(&Info); + + if(Time <= 0 && g_Config.m_ClShowDecisecs) + str_format(Buf, sizeof(Buf), "00:00.0"); + else if(Time <= 0) + str_format(Buf, sizeof(Buf), "00:00"); + else if(IsRace(&Info) && !IsDDRace(&Info) && m_ServerRecord >= 0) + str_format(Buf, sizeof(Buf), "%02d:%02d", (int)(m_ServerRecord*100)/60, ((int)(m_ServerRecord*100)%60)); + else if(g_Config.m_ClShowDecisecs) + str_format(Buf, sizeof(Buf), "%02d:%02d.%d", Time/60, Time%60, m_DDRaceTick/10); + else + str_format(Buf, sizeof(Buf), "%02d:%02d", Time/60, Time%60); + float FontSize = 10.0f; + float w; + if(g_Config.m_ClShowDecisecs) + w = TextRender()->TextWidth(0, 12,"00:00.0",-1); + else + w = TextRender()->TextWidth(0, 12,"00:00",-1); + // last 60 sec red, last 10 sec blink + if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit && Time <= 60 && !m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer) + { + float Alpha = Time <= 10 && (2*time_get()/time_freq()) % 2 ? 0.5f : 1.0f; + TextRender()->TextColor(1.0f, 0.25f, 0.25f, Alpha); + } + TextRender()->Text(0, Half-w/2, 2, FontSize, Buf, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } +} + +void CHud::RenderPauseNotification() +{ + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED && + !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + const char *pText = Localize("Game paused"); + float FontSize = 20.0f; + float w = TextRender()->TextWidth(0, FontSize,pText, -1); + TextRender()->Text(0, 150.0f*Graphics()->ScreenAspect()+-w/2.0f, 50.0f, FontSize, pText, -1); + } +} + +void CHud::RenderSuddenDeath() +{ + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH) + { + float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; + const char *pText = Localize("Sudden Death"); + float FontSize = 12.0f; + float w = TextRender()->TextWidth(0, FontSize, pText, -1); + TextRender()->Text(0, Half-w/2, 2, FontSize, pText, -1); + } +} + +void CHud::RenderScoreHud() +{ + // render small score hud + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + int GameFlags = m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags; + float Whole = 300*Graphics()->ScreenAspect(); + float StartY = 229.0f; + + if(GameFlags&GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataObj) + { + char aScoreTeam[2][32]; + str_format(aScoreTeam[TEAM_RED], sizeof(aScoreTeam)/2, "%d", m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed); + str_format(aScoreTeam[TEAM_BLUE], sizeof(aScoreTeam)/2, "%d", m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue); + float aScoreTeamWidth[2] = { TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_RED], -1), TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_BLUE], -1) }; + int FlagCarrier[2] = { m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed, m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue }; + 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 + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + if(t == 0) + Graphics()->SetColor(1.0f, 0.0f, 0.0f, 0.25f); + else + Graphics()->SetColor(0.0f, 0.0f, 1.0f, 0.25f); + RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split, StartY+t*20, ScoreWidthMax+ImageSize+2*Split, 18.0f, 5.0f, CUI::CORNER_L); + Graphics()->QuadsEnd(); + + // draw score + TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreTeamWidth[t])/2-Split, StartY+t*20, 14.0f, aScoreTeam[t], -1); + + if(GameFlags&GAMEFLAG_FLAGS) + { + int BlinkTimer = (m_pClient->m_FlagDropTick[t] != 0 && + (Client()->GameTick()-m_pClient->m_FlagDropTick[t])/Client()->GameTickSpeed() >= 25) ? 10 : 20; + if(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick()/BlinkTimer)&1))) + { + // draw flag + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(t==0?SPRITE_FLAG_RED:SPRITE_FLAG_BLUE); + IGraphics::CQuadItem QuadItem(Whole-ScoreWidthMax-ImageSize, StartY+1.0f+t*20, ImageSize/2, ImageSize); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + else if(FlagCarrier[t] >= 0) + { + // draw name of the flag holder + int ID = FlagCarrier[t]%MAX_CLIENTS; + const char *pName = m_pClient->m_aClients[ID].m_aName; + float w = TextRender()->TextWidth(0, 8.0f, pName, -1); + TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1); + + // draw tee of the flag holder + CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; + Info.m_Size = 18.0f; + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), + vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); + } + } + StartY += 8.0f; + } + } + else + { + int Local = -1; + int aPos[2] = { 1, 2 }; + const CNetObj_PlayerInfo *apPlayerInfo[2] = { 0, 0 }; + int i = 0; + for(int t = 0; t < 2 && i < MAX_CLIENTS && m_pClient->m_Snap.m_paInfoByScore[i]; ++i) + { + if(m_pClient->m_Snap.m_paInfoByScore[i]->m_Team != TEAM_SPECTATORS) + { + apPlayerInfo[t] = m_pClient->m_Snap.m_paInfoByScore[i]; + if(apPlayerInfo[t]->m_ClientID == m_pClient->m_Snap.m_LocalClientID) + Local = t; + ++t; + } + } + // search local player info if not a spectator, nor within top2 scores + if(Local == -1 && m_pClient->m_Snap.m_pLocalInfo && m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_SPECTATORS) + { + for(; i < MAX_CLIENTS && m_pClient->m_Snap.m_paInfoByScore[i]; ++i) + { + if(m_pClient->m_Snap.m_paInfoByScore[i]->m_Team != TEAM_SPECTATORS) + ++aPos[1]; + if(m_pClient->m_Snap.m_paInfoByScore[i]->m_ClientID == m_pClient->m_Snap.m_LocalClientID) + { + apPlayerInfo[1] = m_pClient->m_Snap.m_paInfoByScore[i]; + Local = 1; + break; + } + } + } + char aScore[2][32]; + for(int t = 0; t < 2; ++t) + { + if(apPlayerInfo[t]) + { + CServerInfo Info; + Client()->GetServerInfo(&Info); + if(IsRace(&Info) && g_Config.m_ClDDRaceScoreBoard) + { + if (apPlayerInfo[t]->m_Score != -9999) + str_format(aScore[t], sizeof(aScore[t]), "%02d:%02d", abs(apPlayerInfo[t]->m_Score)/60, abs(apPlayerInfo[t]->m_Score)%60); + else + aScore[t][0] = 0; + } + else + str_format(aScore[t], sizeof(aScore)/2, "%d", apPlayerInfo[t]->m_Score); + } + else + aScore[t][0] = 0; + } + 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 + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + if(t == Local) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); + else + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.25f); + RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split-PosSize, StartY+t*20, ScoreWidthMax+ImageSize+2*Split+PosSize, 18.0f, 5.0f, CUI::CORNER_L); + Graphics()->QuadsEnd(); + + // draw score + TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreWidth[t])/2-Split, StartY+t*20, 14.0f, aScore[t], -1); + + if(apPlayerInfo[t]) + { + // draw name + int ID = apPlayerInfo[t]->m_ClientID; + if(ID >= 0 && ID < MAX_CLIENTS) + { + const char *pName = m_pClient->m_aClients[ID].m_aName; + float w = TextRender()->TextWidth(0, 8.0f, pName, -1); + TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split-PosSize), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1); + + // draw tee + CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; + Info.m_Size = 18.0f; + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), + vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); + } + } + + // draw position + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "%d.", aPos[t]); + TextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-Split-PosSize, StartY+2.0f+t*20, 10.0f, aBuf, -1); + + StartY += 8.0f; + } + } + } +} + +void CHud::RenderWarmupTimer() +{ + // render warmup timer + if(m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer) + { + char Buf[256]; + float FontSize = 20.0f; + float w = TextRender()->TextWidth(0, FontSize, Localize("Warmup"), -1); + TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, Localize("Warmup"), -1); + + int Seconds = m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer/SERVER_TICK_SPEED; + if(Seconds < 5) + str_format(Buf, sizeof(Buf), "%d.%d", Seconds, (m_pClient->m_Snap.m_pGameInfoObj->m_WarmupTimer*10/SERVER_TICK_SPEED)%10); + else + 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) +{ + float Points[4]; + RenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f, + pGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), 1.0f, Points); + Graphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]); +} + +void CHud::RenderFps() +{ + if(g_Config.m_ClShowfps) + { + // calculate avg. fps + float FPS = 1.0f / Client()->RenderFrameTime(); + m_AverageFPS = (m_AverageFPS*(1.0f-(1.0f/m_AverageFPS))) + (FPS*(1.0f/m_AverageFPS)); + char Buf[512]; + str_format(Buf, sizeof(Buf), "%d", (int)m_AverageFPS); + TextRender()->Text(0, m_Width-10-TextRender()->TextWidth(0,12,Buf,-1), 5, 12, Buf, -1); + } +} + +void CHud::RenderConnectionWarning() +{ + if(Client()->ConnectionProblems()) + { + const char *pText = Localize("Connection Problems..."); + float w = TextRender()->TextWidth(0, 24, pText, -1); + TextRender()->Text(0, 150*Graphics()->ScreenAspect()-w/2, 50, 24, pText, -1); + } +} + +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)) + { + const char *pText = Localize("Please balance teams!"); + if(Flash) + TextRender()->TextColor(1,1,0.5f,1); + else + TextRender()->TextColor(0.7f,0.7f,0.2f,1.0f); + TextRender()->Text(0x0, 5, 50, 6, pText, -1); + TextRender()->TextColor(1,1,1,1); + } + } +} + + +void CHud::RenderVoting() +{ + if((!g_Config.m_ClShowVotesAfterVoting && !m_pClient->m_pScoreboard->Active() && m_pClient->m_pVoting->TakenChoice()) || !m_pClient->m_pVoting->IsVoting() || Client()->State() == IClient::STATE_DEMOPLAYBACK) + return; + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.40f); + +#if defined(__ANDROID__) + static const float TextX = 265; + static const float TextY = 1; + static const float TextW = 200; + static const float TextH = 42; + RenderTools()->DrawRoundRect(TextX-5, TextY, TextW+15, TextH, 5.0f); + RenderTools()->DrawRoundRect(TextX-5, TextY+TextH+2, TextW/2-10, 20, 5.0f); + RenderTools()->DrawRoundRect(TextX+TextW/2+20, TextY+TextH+2, TextW/2-10, 20, 5.0f); +#else + RenderTools()->DrawRoundRect(-10, 60-2, 100+10+4+5, 46, 5.0f); +#endif + Graphics()->QuadsEnd(); + + TextRender()->TextColor(1,1,1,1); + + CTextCursor Cursor; + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), Localize("%ds left"), m_pClient->m_pVoting->SecondsLeft()); +#if defined(__ANDROID__) + float tw = TextRender()->TextWidth(0x0, 10, aBuf, -1); + TextRender()->SetCursor(&Cursor, TextX+TextW-tw, 0.0f, 10.0f, TEXTFLAG_RENDER); +#else + float tw = TextRender()->TextWidth(0x0, 6, aBuf, -1); + TextRender()->SetCursor(&Cursor, 5.0f+100.0f-tw, 60.0f, 6.0f, TEXTFLAG_RENDER); +#endif + TextRender()->TextEx(&Cursor, aBuf, -1); + +#if defined(__ANDROID__) + TextRender()->SetCursor(&Cursor, TextX, 0.0f, 10.0f, TEXTFLAG_RENDER); + Cursor.m_LineWidth = TextW-tw; +#else + TextRender()->SetCursor(&Cursor, 5.0f, 60.0f, 6.0f, TEXTFLAG_RENDER); + Cursor.m_LineWidth = 100.0f-tw; +#endif + 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()); +#if defined(__ANDROID__) + TextRender()->SetCursor(&Cursor, TextX, 23.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); +#else + TextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); +#endif + Cursor.m_LineWidth = 100.0f; + TextRender()->TextEx(&Cursor, aBuf, -1); + +#if defined(__ANDROID__) + CUIRect Base = {TextX, TextH - 8, TextW, 4}; +#else + CUIRect Base = {5, 88, 100, 4}; +#endif + m_pClient->m_pVoting->RenderBars(Base, false); + +#if defined(__ANDROID__) + Base.y += Base.h+6; + UI()->DoLabel(&Base, Localize("Vote yes"), 16.0f, -1); + UI()->DoLabel(&Base, Localize("Vote no"), 16.0f, 1); + if( Input()->KeyDown(KEY_MOUSE_1) ) + { + float mx, my; + Input()->MouseRelative(&mx, &my); + mx *= m_Width / Graphics()->ScreenWidth(); + my *= m_Height / Graphics()->ScreenHeight(); + if( my > TextY+TextH-40 && my < TextY+TextH+20 ) { + if( mx > TextX-5 && mx < TextX-5+TextW/2-10 ) + m_pClient->m_pVoting->Vote(1); + if( mx > TextX+TextW/2+20 && mx < TextX+TextW/2+20+TextW/2-10 ) + m_pClient->m_pVoting->Vote(-1); + } + } +#else + 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")); + Base.y += Base.h+1; + UI()->DoLabel(&Base, aBuf, 6.0f, -1); + + str_format(aBuf, sizeof(aBuf), "%s - %s", Localize("Vote no"), pNoKey); + UI()->DoLabel(&Base, aBuf, 6.0f, 1); +#endif +} + +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(); + + // render cursor + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteCursor); + float CursorSize = 64; + RenderTools()->DrawSprite(m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy].x, m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy].y, CursorSize); + Graphics()->QuadsEnd(); +} + +void CHud::RenderHealthAndAmmo(const CNetObj_Character *pCharacter) +{ + if(!pCharacter) + return; + + //mapscreen_to_group(gacenter_x, center_y, layers_game_group()); + + float x = 5; + float y = 5; + + // render ammo count + // 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]; + int i; + for (i = 0; i < min(pCharacter->m_AmmoCount, 10); i++) + Array[i] = IGraphics::CQuadItem(x+i*12,y+24,10,10); + Graphics()->QuadsDrawTL(Array, i); + Graphics()->QuadsEnd(); + + Graphics()->QuadsBegin(); + int h = 0; + + // render health + RenderTools()->SelectSprite(SPRITE_HEALTH_FULL); + for(; h < min(pCharacter->m_Health, 10); h++) + Array[h] = IGraphics::CQuadItem(x+h*12,y,10,10); + Graphics()->QuadsDrawTL(Array, h); + + i = 0; + RenderTools()->SelectSprite(SPRITE_HEALTH_EMPTY); + for(; h < 10; h++) + Array[i++] = IGraphics::CQuadItem(x+h*12,y,10,10); + Graphics()->QuadsDrawTL(Array, i); + + // render armor meter + h = 0; + RenderTools()->SelectSprite(SPRITE_ARMOR_FULL); + for(; h < min(pCharacter->m_Armor, 10); h++) + Array[h] = IGraphics::CQuadItem(x+h*12,y+12,10,10); + Graphics()->QuadsDrawTL(Array, h); + + i = 0; + RenderTools()->SelectSprite(SPRITE_ARMOR_EMPTY); + for(; h < 10; h++) + Array[i++] = IGraphics::CQuadItem(x+h*12,y+12,10,10); + Graphics()->QuadsDrawTL(Array, i); + Graphics()->QuadsEnd(); +} + +void CHud::RenderSpectatorHud() +{ + // draw the box + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); + RenderTools()->DrawRoundRectExt(m_Width-180.0f, m_Height-15.0f, 180.0f, 15.0f, 5.0f, CUI::CORNER_TL); + Graphics()->QuadsEnd(); + + // draw the text + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Spectate"), m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW ? + m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName : Localize("Free-View")); + TextRender()->Text(0, m_Width-174.0f, m_Height-13.0f, 8.0f, aBuf, -1); +} + +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); + + if(g_Config.m_ClShowhud) + { + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + if (g_Config.m_ClShowhudHealthAmmo) + RenderHealthAndAmmo(m_pClient->m_Snap.m_pLocalCharacter); + RenderDDRaceEffects(); + } + else if(m_pClient->m_Snap.m_SpecInfo.m_Active) + { + if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW && g_Config.m_ClShowhudHealthAmmo) + RenderHealthAndAmmo(&m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_Cur); + RenderSpectatorHud(); + } + + RenderGameTimer(); + RenderPauseNotification(); + RenderSuddenDeath(); + if (g_Config.m_ClShowhudScore) + RenderScoreHud(); + RenderWarmupTimer(); + RenderFps(); + if(Client()->State() != IClient::STATE_DEMOPLAYBACK) + RenderConnectionWarning(); + RenderTeambalanceWarning(); + RenderVoting(); + if (g_Config.m_ClShowRecord) + RenderRecord(); + } + RenderCursor(); +} + +void CHud::OnMessage(int MsgType, void *pRawMsg) +{ + + if(MsgType == NETMSGTYPE_SV_DDRACETIME) + { + m_DDRaceTimeReceived = true; + + CNetMsg_Sv_DDRaceTime *pMsg = (CNetMsg_Sv_DDRaceTime *)pRawMsg; + + m_DDRaceTime = pMsg->m_Time; + m_DDRaceTick = 0; + + m_LastReceivedTimeTick = Client()->GameTick(); + + m_FinishTime = pMsg->m_Finish ? true : false; + + if(pMsg->m_Check) + { + m_CheckpointDiff = (float)pMsg->m_Check/100; + m_CheckpointTick = Client()->GameTick(); + } + } + else if(MsgType == NETMSGTYPE_SV_KILLMSG) + { + CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; + if(pMsg->m_Victim == m_pClient->m_Snap.m_LocalClientID) + { + m_CheckpointTick = 0; + m_DDRaceTime = 0; + } + } + else if(MsgType == NETMSGTYPE_SV_RECORD) + { + CNetMsg_Sv_Record *pMsg = (CNetMsg_Sv_Record *)pRawMsg; + m_ServerRecord = (float)pMsg->m_ServerTimeBest/100; + m_PlayerRecord = (float)pMsg->m_PlayerTimeBest/100; + } +} + +void CHud::RenderDDRaceEffects() +{ + // check racestate + if(m_FinishTime && m_LastReceivedTimeTick + Client()->GameTickSpeed()*2 < Client()->GameTick()) + { + m_FinishTime = false; + m_DDRaceTimeReceived = false; + return; + } + + if(m_DDRaceTime) + { + char aBuf[64]; + if(m_FinishTime) + { + str_format(aBuf, sizeof(aBuf), "Finish time: %02d:%02d.%02d", m_DDRaceTime/6000, m_DDRaceTime/100-m_DDRaceTime/6000 * 60, m_DDRaceTime % 100); + TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0,12,aBuf,-1)/2, 20, 12, aBuf, -1); + } + else if(m_CheckpointTick + Client()->GameTickSpeed()*6 > Client()->GameTick()) + { + str_format(aBuf, sizeof(aBuf), "%+5.2f", m_CheckpointDiff); + + // calculate alpha (4 sec 1 than get lower the next 2 sec) + float a = 1.0f; + if(m_CheckpointTick+Client()->GameTickSpeed()*4 < Client()->GameTick() && m_CheckpointTick+Client()->GameTickSpeed()*6 > Client()->GameTick()) + { + // lower the alpha slowly to blend text out + a = ((float)(m_CheckpointTick+Client()->GameTickSpeed()*6) - (float)Client()->GameTick()) / (float)(Client()->GameTickSpeed()*2); + } + + if(m_CheckpointDiff > 0) + TextRender()->TextColor(1.0f,0.5f,0.5f,a); // red + else if(m_CheckpointDiff < 0) + TextRender()->TextColor(0.5f,1.0f,0.5f,a); // green + else if(!m_CheckpointDiff) + TextRender()->TextColor(1,1,1,a); // white + TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0, 10, aBuf, -1)/2, 20, 10, aBuf, -1); + + TextRender()->TextColor(1,1,1,1); + } + } + /*else if(m_DDRaceTimeReceived) + { + str_format(aBuf, sizeof(aBuf), "%02d:%02d.%d", m_DDRaceTime/60, m_DDRaceTime%60, m_DDRaceTick/10); + TextRender()->Text(0, 150*Graphics()->ScreenAspect()-TextRender()->TextWidth(0, 12,"00:00.0",-1)/2, 20, 12, aBuf, -1); // use fixed value for text width so its not shaky + }*/ + + + + static int LastChangeTick = 0; + if(LastChangeTick != Client()->PredGameTick()) + { + m_DDRaceTick += 100/Client()->GameTickSpeed(); + LastChangeTick = Client()->PredGameTick(); + } + + if(m_DDRaceTick >= 100) + m_DDRaceTick = 0; +} + +void CHud::RenderRecord() +{ + if(m_ServerRecord > 0 ) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "Server best:"); + TextRender()->Text(0, 5, 40, 6, aBuf, -1); + str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)m_ServerRecord/60, m_ServerRecord-((int)m_ServerRecord/60*60)); + TextRender()->Text(0, 53, 40, 6, aBuf, -1); + } + + if(m_PlayerRecord > 0 ) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "Personal best:"); + TextRender()->Text(0, 5, 47, 6, aBuf, -1); + str_format(aBuf, sizeof(aBuf), "%02d:%05.2f", (int)m_PlayerRecord/60, m_PlayerRecord-((int)m_PlayerRecord/60*60)); + TextRender()->Text(0, 53, 47, 6, aBuf, -1); + } +} diff --git a/src/game/client/components/hud.h b/src/game/client/components/hud.h new file mode 100644 index 0000000..73eee3d --- /dev/null +++ b/src/game/client/components/hud.h @@ -0,0 +1,52 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_HUD_H +#define GAME_CLIENT_COMPONENTS_HUD_H +#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(); + void RenderVoting(); + void RenderHealthAndAmmo(const CNetObj_Character *pCharacter); + void RenderGameTimer(); + void RenderPauseNotification(); + void RenderSuddenDeath(); + void RenderScoreHud(); + void RenderSpectatorHud(); + void RenderWarmupTimer(); + + void MapscreenToGroup(float CenterX, float CenterY, struct CMapItemGroup *PGroup); +public: + CHud(); + + virtual void OnReset(); + virtual void OnRender(); + + // DDRace + + virtual void OnMessage(int MsgType, void *pRawMsg); + +private: + + void RenderRecord(); + void RenderDDRaceEffects(); + float m_CheckpointDiff; + float m_ServerRecord; + float m_PlayerRecord; + int m_DDRaceTime; + int m_LastReceivedTimeTick; + int m_CheckpointTick; + int m_DDRaceTick; + bool m_FinishTime; + bool m_DDRaceTimeReceived; +}; + +#endif diff --git a/src/game/client/components/items.cpp b/src/game/client/components/items.cpp new file mode 100644 index 0000000..f60650a --- /dev/null +++ b/src/game/client/components/items.cpp @@ -0,0 +1,361 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/demo.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> +#include <engine/shared/config.h> + +#include <game/gamecore.h> // get_angle +#include <game/client/gameclient.h> +#include <game/client/ui.h> +#include <game/client/render.h> + +#include <game/client/components/flow.h> +#include <game/client/components/effects.h> + +#include "items.h" +#include <stdio.h> + +#include <engine/serverbrowser.h> +void CItems::OnReset() +{ + m_NumExtraProjectiles = 0; +} + +void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) +{ + // get positions + float Curvature = 0; + float Speed = 0; + if(pCurrent->m_Type == WEAPON_GRENADE) + { + Curvature = m_pClient->m_Tuning[g_Config.m_ClDummy].m_GrenadeCurvature; + Speed = m_pClient->m_Tuning[g_Config.m_ClDummy].m_GrenadeSpeed; + } + else if(pCurrent->m_Type == WEAPON_SHOTGUN) + { + Curvature = m_pClient->m_Tuning[g_Config.m_ClDummy].m_ShotgunCurvature; + Speed = m_pClient->m_Tuning[g_Config.m_ClDummy].m_ShotgunSpeed; + } + else if(pCurrent->m_Type == WEAPON_GUN) + { + Curvature = m_pClient->m_Tuning[g_Config.m_ClDummy].m_GunCurvature; + Speed = m_pClient->m_Tuning[g_Config.m_ClDummy].m_GunSpeed; + } + + // + bool LocalPlayerInGame = false; + + if(m_pClient->m_Snap.m_pLocalInfo) + LocalPlayerInGame = m_pClient->m_aClients[m_pClient->m_Snap.m_pLocalInfo->m_ClientID].m_Team != -1; + + // + static float s_LastGameTickTime = Client()->GameTickTime(); + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + s_LastGameTickTime = Client()->GameTickTime(); + + int PrevTick = Client()->PrevGameTick(); + + if (m_pClient->AntiPingGrenade() && LocalPlayerInGame && !(Client()->State() == IClient::STATE_DEMOPLAYBACK)) + { + // calc predicted game tick + static int Offset = 0; + Offset = (int)(0.8f * (float)Offset + 0.2f * (float)(Client()->PredGameTick() - Client()->GameTick())); + + PrevTick += Offset; + } + + float Ct = (PrevTick-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; + if(Ct < 0) + return; // projectile havn't been shot yet + + vec2 StartPos; + vec2 StartVel; + + CServerInfo Info; + Client()->GetServerInfo(&Info); + ExtractInfo(pCurrent, &StartPos, &StartVel, IsDDNet(&Info)); + + vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct); + vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct-0.001f); + + + 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); + static float s_Time = 0.0f; + static float s_LastLocalTime = Client()->LocalTime(); + + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(!pInfo->m_Paused) + s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed; + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + s_Time += Client()->LocalTime()-s_LastLocalTime; + } + + Graphics()->QuadsSetRotation(s_Time*pi*2*2 + ItemID); + s_LastLocalTime = Client()->LocalTime(); + } + else + { + m_pClient->m_pEffects->BulletTrail(Pos); + + if(length(Vel) > 0.00001f) + Graphics()->QuadsSetRotation(GetAngle(Vel)); + else + Graphics()->QuadsSetRotation(0); + + } + + IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 32, 32); + Graphics()->QuadsDraw(&QuadItem, 1); + + Graphics()->QuadsSetRotation(0); + Graphics()->QuadsEnd(); +} + +void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent) +{ + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + vec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick()); + float Angle = 0.0f; + float Size = 64.0f; + if (pCurrent->m_Type == POWERUP_WEAPON) + { + Angle = 0; //-pi/6;//-0.25f * pi * 2.0f; + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Subtype, 0, NUM_WEAPONS-1)].m_pSpriteBody); + Size = g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Subtype, 0, NUM_WEAPONS-1)].m_VisualSize; + } + else + { + const int c[] = { + SPRITE_PICKUP_HEALTH, + SPRITE_PICKUP_ARMOR, + SPRITE_PICKUP_WEAPON, + SPRITE_PICKUP_NINJA + }; + RenderTools()->SelectSprite(c[pCurrent->m_Type]); + + if(c[pCurrent->m_Type] == SPRITE_PICKUP_NINJA) + { + m_pClient->m_pEffects->PowerupShine(Pos, vec2(96,18)); + Size *= 2.0f; + Pos.x -= 10.0f; + } + } + + Graphics()->QuadsSetRotation(Angle); + + static float s_Time = 0.0f; + static float s_LastLocalTime = Client()->LocalTime(); + float Offset = Pos.y/32.0f + Pos.x/32.0f; + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(!pInfo->m_Paused) + s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed; + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + s_Time += Client()->LocalTime()-s_LastLocalTime; + } + Pos.x += cosf(s_Time*2.0f+Offset)*2.5f; + Pos.y += sinf(s_Time*2.0f+Offset)*2.5f; + s_LastLocalTime = Client()->LocalTime(); + RenderTools()->DrawSprite(Pos.x, Pos.y, Size); + Graphics()->QuadsEnd(); +} + +void CItems::RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameData *pPrevGameData, const CNetObj_GameData *pCurGameData) +{ + float Angle = 0.0f; + float Size = 42.0f; + + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + + if(pCurrent->m_Team == TEAM_RED) + RenderTools()->SelectSprite(SPRITE_FLAG_RED); + else + RenderTools()->SelectSprite(SPRITE_FLAG_BLUE); + + 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 + if(pPrevGameData && + ((pCurrent->m_Team == TEAM_RED && pPrevGameData->m_FlagCarrierRed != pCurGameData->m_FlagCarrierRed) || + (pCurrent->m_Team == TEAM_BLUE && pPrevGameData->m_FlagCarrierBlue != pCurGameData->m_FlagCarrierBlue))) + Pos = vec2(pCurrent->m_X, pCurrent->m_Y); + + // make sure to use predicted position if we are the carrier + if(m_pClient->m_Snap.m_pLocalInfo && + ((pCurrent->m_Team == TEAM_RED && pCurGameData->m_FlagCarrierRed == m_pClient->m_Snap.m_LocalClientID) || + (pCurrent->m_Team == TEAM_BLUE && pCurGameData->m_FlagCarrierBlue == m_pClient->m_Snap.m_LocalClientID))) + Pos = m_pClient->m_LocalCharacterPos; + } + + IGraphics::CQuadItem QuadItem(Pos.x, Pos.y-Size*0.75f, Size, Size*2); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); +} + + +void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent) +{ + vec3 RGB; + vec2 Pos = vec2(pCurrent->m_X, pCurrent->m_Y); + vec2 From = vec2(pCurrent->m_FromX, pCurrent->m_FromY); + vec2 Dir = normalize(Pos-From); + + float Ticks = Client()->GameTick() + Client()->IntraGameTick() - pCurrent->m_StartTick; + float Ms = (Ticks/50.0f) * 1000.0f; + float a = Ms / m_pClient->m_Tuning[g_Config.m_ClDummy].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); + + // do outline + RGB = HslToRgb(vec3(g_Config.m_ClLaserOutlineHue / 255.0f, g_Config.m_ClLaserOutlineSat / 255.0f, g_Config.m_ClLaserOutlineLht / 255.0f)); + vec4 OuterColor(RGB.r, RGB.g, RGB.b, 1.0f); + Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); + Out = vec2(Dir.y, -Dir.x) * (7.0f*Ia); + + IGraphics::CFreeformItem Freeform( + 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); + + // do inner + RGB = HslToRgb(vec3(g_Config.m_ClLaserInnerHue / 255.0f, g_Config.m_ClLaserInnerSat / 255.0f, g_Config.m_ClLaserInnerLht / 255.0f)); + vec4 InnerColor(RGB.r, RGB.g, RGB.b, 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(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); + Graphics()->QuadsBegin(); + + int Sprites[] = {SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03}; + RenderTools()->SelectSprite(Sprites[Client()->GameTick()%3]); + Graphics()->QuadsSetRotation(Client()->GameTick()); + Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); + IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 24, 24); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); + QuadItem = IGraphics::CQuadItem(Pos.x, Pos.y, 20, 20); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + Graphics()->BlendNormal(); +} + +void CItems::OnRender() +{ + if(Client()->State() < IClient::STATE_ONLINE) + return; + + int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); + for(int i = 0; i < Num; i++) + { + IClient::CSnapItem Item; + const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); + + if(Item.m_Type == NETOBJTYPE_PROJECTILE) + { + RenderProjectile((const CNetObj_Projectile *)pData, Item.m_ID); + } + else if(Item.m_Type == NETOBJTYPE_PICKUP) + { + const void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID); + if(pPrev) + RenderPickup((const CNetObj_Pickup *)pPrev, (const CNetObj_Pickup *)pData); + } + else if(Item.m_Type == NETOBJTYPE_LASER) + { + RenderLaser((const CNetObj_Laser *)pData); + } + } + + // render flag + for(int i = 0; i < Num; i++) + { + IClient::CSnapItem Item; + const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); + + if(Item.m_Type == NETOBJTYPE_FLAG) + { + 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); + 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); + } + } + } + + // render extra projectiles + for(int i = 0; i < m_NumExtraProjectiles; i++) + { + if(m_aExtraProjectiles[i].m_StartTick < Client()->GameTick()) + { + m_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles-1]; + m_NumExtraProjectiles--; + } + else + RenderProjectile(&m_aExtraProjectiles[i], 0); + } +} + +void CItems::AddExtraProjectile(CNetObj_Projectile *pProj) +{ + if(m_NumExtraProjectiles != MAX_EXTRA_PROJECTILES) + { + m_aExtraProjectiles[m_NumExtraProjectiles] = *pProj; + m_NumExtraProjectiles++; + } +} diff --git a/src/game/client/components/items.h b/src/game/client/components/items.h new file mode 100644 index 0000000..caf6176 --- /dev/null +++ b/src/game/client/components/items.h @@ -0,0 +1,29 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_ITEMS_H +#define GAME_CLIENT_COMPONENTS_ITEMS_H +#include <game/client/component.h> + +class CItems : public CComponent +{ + enum + { + MAX_EXTRA_PROJECTILES=32, + }; + + CNetObj_Projectile m_aExtraProjectiles[MAX_EXTRA_PROJECTILES]; + int m_NumExtraProjectiles; + + 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); +}; + +#endif diff --git a/src/game/client/components/killmessages.cpp b/src/game/client/components/killmessages.cpp new file mode 100644 index 0000000..772bd1f --- /dev/null +++ b/src/game/client/components/killmessages.cpp @@ -0,0 +1,155 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> +#include <engine/shared/config.h> + +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include "killmessages.h" + +void CKillMessages::OnReset() +{ + m_KillmsgCurrent = 0; + for(int i = 0; i < MAX_KILLMSGS; i++) + m_aKillmsgs[i].m_Tick = -100000; +} + +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; + Kill.m_VictimTeam = m_pClient->m_aClients[Kill.m_VictimID].m_Team; + Kill.m_VictimDDTeam = m_pClient->m_Teams.Team(Kill.m_VictimID); + str_copy(Kill.m_aVictimName, m_pClient->m_aClients[Kill.m_VictimID].m_aName, sizeof(Kill.m_aVictimName)); + Kill.m_VictimRenderInfo = m_pClient->m_aClients[Kill.m_VictimID].m_RenderInfo; + Kill.m_KillerID = pMsg->m_Killer; + Kill.m_KillerTeam = m_pClient->m_aClients[Kill.m_KillerID].m_Team; + str_copy(Kill.m_aKillerName, m_pClient->m_aClients[Kill.m_KillerID].m_aName, sizeof(Kill.m_aKillerName)); + Kill.m_KillerRenderInfo = m_pClient->m_aClients[Kill.m_KillerID].m_RenderInfo; + Kill.m_Weapon = pMsg->m_Weapon; + Kill.m_ModeSpecial = pMsg->m_ModeSpecial; + Kill.m_Tick = Client()->GameTick(); + + // add the message + m_KillmsgCurrent = (m_KillmsgCurrent+1)%MAX_KILLMSGS; + m_aKillmsgs[m_KillmsgCurrent] = Kill; + } +} + +void CKillMessages::OnRender() +{ + if (!g_Config.m_ClShowKillMessages) + return; + + float Width = 400*3.0f*Graphics()->ScreenAspect(); + float Height = 400*3.0f; + + Graphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f); + float StartX = Width*1.5f-10.0f; + float y = 20.0f; + if(g_Config.m_ClShowfps) + y = 150.0f; + + for(int i = 1; i <= MAX_KILLMSGS; i++) + { + int r = (m_KillmsgCurrent+i)%MAX_KILLMSGS; + if(Client()->GameTick() > m_aKillmsgs[r].m_Tick+50*10) + continue; + + float FontSize = 36.0f; + float KillerNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aKillerName, -1); + float VictimNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aVictimName, -1); + + float x = StartX; + + // render victim name + x -= VictimNameW; + if(m_aKillmsgs[r].m_VictimID >= 0 && g_Config.m_ClChatTeamColors && m_aKillmsgs[r].m_VictimDDTeam) + { + vec3 rgb = HslToRgb(vec3(m_aKillmsgs[r].m_VictimDDTeam / 64.0f, 1.0f, 0.75f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0); + } + TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aVictimName, -1); + TextRender()->TextColor(1.0, 1.0, 1.0, 1.0); + + // 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) + { + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + + if(m_aKillmsgs[r].m_VictimTeam == TEAM_RED) + 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(); + } + } + + 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) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_aKillmsgs[r].m_Weapon].m_pSpriteBody); + RenderTools()->DrawSprite(x, y+28, 96); + Graphics()->QuadsEnd(); + } + x -= 52.0f; + + if(m_aKillmsgs[r].m_VictimID != m_aKillmsgs[r].m_KillerID) + { + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS) + { + if(m_aKillmsgs[r].m_ModeSpecial&2) + { + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + + if(m_aKillmsgs[r].m_KillerTeam == TEAM_RED) + 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(); + } + } + + // render killer tee + x -= 24.0f; + RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28)); + x -= 32.0f; + + // render killer name + x -= KillerNameW; + TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aKillerName, -1); + } + + y += 46.0f; + } +} diff --git a/src/game/client/components/killmessages.h b/src/game/client/components/killmessages.h new file mode 100644 index 0000000..cbeb53a --- /dev/null +++ b/src/game/client/components/killmessages.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_KILLMESSAGES_H +#define GAME_CLIENT_COMPONENTS_KILLMESSAGES_H +#include <game/client/component.h> + +class CKillMessages : public CComponent +{ +public: + // kill messages + struct CKillMsg + { + int m_Weapon; + int m_VictimID; + int m_VictimTeam; + int m_VictimDDTeam; + char m_aVictimName[64]; + CTeeRenderInfo m_VictimRenderInfo; + int m_KillerID; + int m_KillerTeam; + char m_aKillerName[64]; + CTeeRenderInfo m_KillerRenderInfo; + int m_ModeSpecial; // for CTF, if the guy is carrying a flag for example + int m_Tick; + }; + + enum + { + MAX_KILLMSGS = 5, + }; + + CKillMsg m_aKillmsgs[MAX_KILLMSGS]; + int m_KillmsgCurrent; + + virtual void OnReset(); + virtual void OnRender(); + virtual void OnMessage(int MsgType, void *pRawMsg); +}; + +#endif diff --git a/src/game/client/components/mapimages.cpp b/src/game/client/components/mapimages.cpp new file mode 100644 index 0000000..c6d41e6 --- /dev/null +++ b/src/game/client/components/mapimages.cpp @@ -0,0 +1,98 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/map.h> +#include <engine/storage.h> +#include <game/client/component.h> +#include <game/mapitems.h> + +#include "mapimages.h" + +CMapImages::CMapImages() +{ + m_Count = 0; + m_EntitiesTextures = -1; +} + +void CMapImages::OnMapLoad() +{ + IMap *pMap = Kernel()->RequestInterface<IMap>(); + + // unload all textures + for(int i = 0; i < m_Count; i++) + { + Graphics()->UnloadTexture(m_aTextures[i]); + m_aTextures[i] = -1; + } + m_Count = 0; + + 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) + { + char Buf[256]; + char *pName = (char *)pMap->GetData(pImg->m_ImageName); + str_format(Buf, sizeof(Buf), "mapres/%s.png", pName); + m_aTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + } + else + { + void *pData = pMap->GetData(pImg->m_ImageData); + m_aTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, CImageInfo::FORMAT_RGBA, pData, CImageInfo::FORMAT_RGBA, 0); + pMap->UnloadData(pImg->m_ImageData); + } + } +} + +void CMapImages::LoadBackground(class IMap *pMap) +{ + // unload all textures + for(int i = 0; i < m_Count; i++) + { + Graphics()->UnloadTexture(m_aTextures[i]); + m_aTextures[i] = -1; + } + m_Count = 0; + + 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) + { + char Buf[256]; + char *pName = (char *)pMap->GetData(pImg->m_ImageName); + str_format(Buf, sizeof(Buf), "mapres/%s.png", pName); + m_aTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + } + else + { + void *pData = pMap->GetData(pImg->m_ImageData); + m_aTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, CImageInfo::FORMAT_RGBA, pData, CImageInfo::FORMAT_RGBA, 0); + pMap->UnloadData(pImg->m_ImageData); + } + } +} + +int CMapImages::GetEntities() +{ + if(m_EntitiesTextures == -1) + { + m_EntitiesTextures = Graphics()->LoadTexture("editor/entities_clear.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + if(m_EntitiesTextures == -1) + m_EntitiesTextures = Graphics()->LoadTexture("editor/entities.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + } + return m_EntitiesTextures; +} diff --git a/src/game/client/components/mapimages.h b/src/game/client/components/mapimages.h new file mode 100644 index 0000000..089d912 --- /dev/null +++ b/src/game/client/components/mapimages.h @@ -0,0 +1,31 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_MAPIMAGES_H +#define GAME_CLIENT_COMPONENTS_MAPIMAGES_H +#include <game/client/component.h> + +class CMapImages : public CComponent +{ + friend class CBackground; + + int m_aTextures[64]; + int m_Count; +public: + CMapImages(); + + int Get(int Index) const { return m_aTextures[Index]; } + int Num() const { return m_Count; } + + virtual void OnMapLoad(); + void LoadBackground(class IMap *pMap); + + // DDRace + + int GetEntities(); + +private: + + int m_EntitiesTextures; +}; + +#endif diff --git a/src/game/client/components/maplayers.cpp b/src/game/client/components/maplayers.cpp new file mode 100644 index 0000000..2fabba7 --- /dev/null +++ b/src/game/client/components/maplayers.cpp @@ -0,0 +1,384 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/graphics.h> +#include <engine/keys.h> +#include <engine/demo.h> +#include <engine/serverbrowser.h> +#include <engine/shared/config.h> +#include <engine/storage.h> + +#include <game/layers.h> +#include <game/client/gameclient.h> +#include <game/client/component.h> +#include <game/client/render.h> + +#include <game/client/components/camera.h> +#include <game/client/components/mapimages.h> + + +#include "maplayers.h" + +CMapLayers::CMapLayers(int t) +{ + m_Type = t; + m_pLayers = 0; + m_CurrentLocalTick = 0; + m_LastLocalTick = 0; + m_EnvelopeUpdate = false; +} + +void CMapLayers::OnInit() +{ + m_pLayers = Layers(); +} + +void CMapLayers::EnvelopeUpdate() +{ + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + m_CurrentLocalTick = pInfo->m_CurrentTick; + m_LastLocalTick = pInfo->m_CurrentTick; + m_EnvelopeUpdate = true; + } +} + + +void CMapLayers::MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup, float Zoom) +{ + float Points[4]; + RenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f, + pGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), Zoom, Points); + Graphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]); +} + +void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser) +{ + CMapLayers *pThis = (CMapLayers *)pUser; + pChannels[0] = 0; + pChannels[1] = 0; + pChannels[2] = 0; + pChannels[3] = 0; + + CEnvPoint *pPoints = 0; + + { + int Start, Num; + pThis->m_pLayers->Map()->GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num); + 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); + + static float s_Time = 0.0f; + static float s_LastLocalTime = pThis->Client()->LocalTime(); + if(pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = pThis->DemoPlayer()->BaseInfo(); + + if(!pInfo->m_Paused || pThis->m_EnvelopeUpdate) + { + if(pThis->m_CurrentLocalTick != pInfo->m_CurrentTick) + { + pThis->m_LastLocalTick = pThis->m_CurrentLocalTick; + pThis->m_CurrentLocalTick = pInfo->m_CurrentTick; + } + + s_Time = mix(pThis->m_LastLocalTick / (float)pThis->Client()->GameTickSpeed(), + pThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(), + pThis->Client()->IntraGameTick()); + } + + pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); + } + else + { + if(pThis->m_pClient->m_Snap.m_pGameInfoObj) // && !(pThis->m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + { + if(pItem->m_Version < 2 || pItem->m_Synchronized) + { + s_Time = mix((pThis->Client()->PrevGameTick()-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + (pThis->Client()->GameTick()-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(), + pThis->Client()->IntraGameTick()); + } + else + s_Time += pThis->Client()->LocalTime()-s_LastLocalTime; + } + pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); + s_LastLocalTime = pThis->Client()->LocalTime(); + } +} + +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; + + bool PassedGameLayer = false; + + for(int g = 0; g < m_pLayers->NumGroups(); g++) + { + CMapItemGroup *pGroup = m_pLayers->GetGroup(g); + + if(!pGroup) + { + dbg_msg("MapLayers", "Error:Group was null, Group Number = %d, Total Groups = %d", g, m_pLayers->NumGroups()); + dbg_msg("MapLayers", "This is here to prevent a crash but the source of this is unknown, please report this for it to get fixed"); + dbg_msg("MapLayers", "we need mapname and crc and the map that caused this if possible, and anymore info you think is relevant"); + continue; + } + + if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) + { + // set clipping + float Points[4]; + MapScreenToGroup(Center.x, Center.y, m_pLayers->GameGroup(), m_pClient->m_pCamera->m_Zoom); + Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); + float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); + 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())); + } + + if(!g_Config.m_ClZoomBackgroundLayers && !pGroup->m_ParallaxX && !pGroup->m_ParallaxY) + MapScreenToGroup(Center.x, Center.y, pGroup, 1.0); + else + MapScreenToGroup(Center.x, Center.y, pGroup, m_pClient->m_pCamera->m_Zoom); + + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); + bool Render = false; + bool IsGameLayer = false; + bool IsFrontLayer = false; + bool IsSwitchLayer = false; + bool IsTeleLayer = false; + bool IsSpeedupLayer = false; + bool IsTuneLayer = false; + + if(pLayer == (CMapItemLayer*)m_pLayers->GameLayer()) + { + IsGameLayer = true; + PassedGameLayer = true; + } + + if(pLayer == (CMapItemLayer*)m_pLayers->FrontLayer()) + IsFrontLayer = true; + + if(pLayer == (CMapItemLayer*)m_pLayers->SwitchLayer()) + IsSwitchLayer = true; + + if(pLayer == (CMapItemLayer*)m_pLayers->TeleLayer()) + IsTeleLayer = true; + + if(pLayer == (CMapItemLayer*)m_pLayers->SpeedupLayer()) + IsSpeedupLayer = true; + + if(pLayer == (CMapItemLayer*)m_pLayers->TuneLayer()) + IsTuneLayer = true; + + // 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 == TYPE_BACKGROUND) + { + if(PassedGameLayer) + return; + Render = true; + } + else // TYPE_FOREGROUND + { + 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; + CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); + CServerInfo CurrentServerInfo; + Client()->GetServerInfo(&CurrentServerInfo); + char aFilename[256]; + str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height); + IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); + if(File) + { + for(int y = 0; y < pTMap->m_Height; y++) + { + for(int x = 0; x < pTMap->m_Width; x++) + io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); + io_write_newline(File); + } + io_close(File); + } + } + + if((Render && g_Config.m_ClOverlayEntities < 100 && !IsGameLayer && !IsFrontLayer && !IsSwitchLayer && !IsTeleLayer && !IsSpeedupLayer && !IsTuneLayer) || (g_Config.m_ClOverlayEntities && IsGameLayer)) + { + if(pLayer->m_Type == LAYERTYPE_TILES) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + if(pTMap->m_Image == -1) + { + if(!IsGameLayer) + Graphics()->TextureSet(-1); + else + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + } + else + Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); + + CTile *pTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Data); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Data); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile)) + { + 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); + if(IsGameLayer && g_Config.m_ClOverlayEntities) + 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*g_Config.m_ClOverlayEntities/100.0f); + if(!IsGameLayer && g_Config.m_ClOverlayEntities) + 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*(100-g_Config.m_ClOverlayEntities)/100.0f); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + Graphics()->BlendNormal(); + RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + } + } + else if(pLayer->m_Type == LAYERTYPE_QUADS) + { + CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; + if(pQLayer->m_Image == -1) + Graphics()->TextureSet(-1); + else + 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); + } + } + else if(Render && g_Config.m_ClOverlayEntities && IsFrontLayer) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + + CTile *pFrontTiles = (CTile *)m_pLayers->Map()->GetData(pTMap->m_Front); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Front); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTile)) + { + 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*g_Config.m_ClOverlayEntities/100.0f); + RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + Graphics()->BlendNormal(); + RenderTools()->RenderTilemap(pFrontTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, + EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); + } + } + else if(Render && g_Config.m_ClOverlayEntities && IsSwitchLayer) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + + CSwitchTile *pSwitchTiles = (CSwitchTile *)m_pLayers->Map()->GetData(pTMap->m_Switch); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Switch); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSwitchTile)) + { + 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*g_Config.m_ClOverlayEntities/100.0f); + RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + Graphics()->BlendNormal(); + RenderTools()->RenderSwitchmap(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); + RenderTools()->RenderSwitchOverlay(pSwitchTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f); + } + } + else if(Render && g_Config.m_ClOverlayEntities && IsTeleLayer) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + + CTeleTile *pTeleTiles = (CTeleTile *)m_pLayers->Map()->GetData(pTMap->m_Tele); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Tele); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTeleTile)) + { + 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*g_Config.m_ClOverlayEntities/100.0f); + RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + Graphics()->BlendNormal(); + RenderTools()->RenderTelemap(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); + RenderTools()->RenderTeleOverlay(pTeleTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f); + } + } + else if(Render && g_Config.m_ClOverlayEntities && IsSpeedupLayer) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + + CSpeedupTile *pSpeedupTiles = (CSpeedupTile *)m_pLayers->Map()->GetData(pTMap->m_Speedup); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Speedup); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CSpeedupTile)) + { + 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*g_Config.m_ClOverlayEntities/100.0f); + RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + Graphics()->BlendNormal(); + RenderTools()->RenderSpeedupmap(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); + RenderTools()->RenderSpeedupOverlay(pSpeedupTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f); + } + } + else if(Render && g_Config.m_ClOverlayEntities && IsTuneLayer) + { + CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; + Graphics()->TextureSet(m_pClient->m_pMapimages->GetEntities()); + + CTuneTile *pTuneTiles = (CTuneTile *)m_pLayers->Map()->GetData(pTMap->m_Tune); + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(pTMap->m_Tune); + + if (Size >= pTMap->m_Width*pTMap->m_Height*sizeof(CTuneTile)) + { + 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*g_Config.m_ClOverlayEntities/100.0f); + RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE); + Graphics()->BlendNormal(); + RenderTools()->RenderTunemap(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT); + //RenderTools()->RenderTuneOverlay(pTuneTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, g_Config.m_ClOverlayEntities/100.0f); + } + } + } + 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 new file mode 100644 index 0000000..cff896d --- /dev/null +++ b/src/game/client/components/maplayers.h @@ -0,0 +1,34 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_MAPLAYERS_H +#define GAME_CLIENT_COMPONENTS_MAPLAYERS_H +#include <game/client/component.h> + +class CMapLayers : public CComponent +{ + friend class CBackground; + + CLayers *m_pLayers; // todo refactor: maybe remove it and access it through client* + int m_Type; + int m_CurrentLocalTick; + int m_LastLocalTick; + bool m_EnvelopeUpdate; + + void MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup, float Zoom = 1.0f); +public: + enum + { + TYPE_BACKGROUND=0, + TYPE_FOREGROUND, + }; + + CMapLayers(int Type); + virtual void OnInit(); + virtual void OnRender(); + + void EnvelopeUpdate(); + + static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser); +}; + +#endif diff --git a/src/game/client/components/mapsounds.cpp b/src/game/client/components/mapsounds.cpp new file mode 100644 index 0000000..16c7761 --- /dev/null +++ b/src/game/client/components/mapsounds.cpp @@ -0,0 +1,240 @@ +#include <engine/engine.h> +#include <engine/sound.h> + +#include <game/client/components/camera.h> +#include <game/client/components/maplayers.h> // envelope +#include <game/client/components/sounds.h> + +#include "mapsounds.h" + +CMapSounds::CMapSounds() +{ + m_Count = 0; +} + +void CMapSounds::OnMapLoad() +{ + IMap *pMap = Kernel()->RequestInterface<IMap>(); + + Clear(); + + // load samples + int Start; + pMap->GetType(MAPITEMTYPE_SOUND, &Start, &m_Count); + + // load new samples + for(int i = 0; i < m_Count; i++) + { + m_aSounds[i] = 0; + + CMapItemSound *pSound = (CMapItemSound *)pMap->GetItem(Start+i, 0, 0); + if(pSound->m_External) + { + char Buf[256]; + char *pName = (char *)pMap->GetData(pSound->m_SoundName); + str_format(Buf, sizeof(Buf), "mapres/%s.opus", pName); + m_aSounds[i] = Sound()->LoadOpus(Buf); + } + else + { + void *pData = pMap->GetData(pSound->m_SoundData); + m_aSounds[i] = Sound()->LoadOpusFromMem(pData, pSound->m_SoundDataSize); + pMap->UnloadData(pSound->m_SoundData); + } + } + + // enqueue sound sources + m_lSourceQueue.clear(); + for(int g = 0; g < Layers()->NumGroups(); g++) + { + CMapItemGroup *pGroup = Layers()->GetGroup(g); + + if(!pGroup) + continue; + + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer+l); + + if(!pLayer) + continue; + + if(pLayer->m_Type == LAYERTYPE_SOUNDS) + { + CMapItemLayerSounds *pSoundLayer = (CMapItemLayerSounds *)pLayer; + + if(pSoundLayer->m_Version < 1 || pSoundLayer->m_Version > CMapItemLayerSounds::CURRENT_VERSION) + continue; + + if(pSoundLayer->m_Sound == -1) + continue; + + CSoundSource *pSources = (CSoundSource *)Layers()->Map()->GetDataSwapped(pSoundLayer->m_Data); + + if(!pSources) + continue; + + for(int i = 0; i < pSoundLayer->m_NumSources; i++) { + CSourceQueueEntry source; + source.m_Sound = pSoundLayer->m_Sound; + source.m_pSource = &pSources[i]; + source.m_HighDetail = pLayer->m_Flags&LAYERFLAG_DETAIL; + + if(!source.m_pSource || source.m_Sound == -1) + continue; + + m_lSourceQueue.add(source); + } + } + } + } +} + +void CMapSounds::OnRender() +{ + if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) + return; + + // enqueue sounds + for(int i = 0; i < m_lSourceQueue.size(); i++) + { + CSourceQueueEntry *pSource = &m_lSourceQueue[i]; + + static float s_Time = 0.0f; + if(m_pClient->m_Snap.m_pGameInfoObj) // && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + { + s_Time = mix((Client()->PrevGameTick()-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), + (Client()->GameTick()-m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)Client()->GameTickSpeed(), + Client()->IntraGameTick()); + } + float offset = s_Time-pSource->m_pSource->m_TimeDelay; + if(offset >= 0.0f && g_Config.m_SndEnable && (g_Config.m_GfxHighDetail || !pSource->m_HighDetail)) + { + if(pSource->m_Voice.IsValid()) + { + // currently playing, set offset + Sound()->SetVoiceTimeOffset(pSource->m_Voice, offset); + } + else + { + // need to enqueue + int Flags = 0; + if(pSource->m_pSource->m_Loop) Flags |= ISound::FLAG_LOOP; + if(!pSource->m_pSource->m_Pan) Flags |= ISound::FLAG_NO_PANNING; + + pSource->m_Voice = m_pClient->m_pSounds->PlaySampleAt(CSounds::CHN_MAPSOUND, m_aSounds[pSource->m_Sound], 1.0f, vec2(fx2f(pSource->m_pSource->m_Position.x), fx2f(pSource->m_pSource->m_Position.y)), Flags); + Sound()->SetVoiceTimeOffset(pSource->m_Voice, offset); + Sound()->SetVoiceFalloff(pSource->m_Voice, pSource->m_pSource->m_Falloff/255.0f); + switch(pSource->m_pSource->m_Shape.m_Type) + { + case CSoundShape::SHAPE_CIRCLE: + { + Sound()->SetVoiceCircle(pSource->m_Voice, pSource->m_pSource->m_Shape.m_Circle.m_Radius); + break; + } + + case CSoundShape::SHAPE_RECTANGLE: + { + Sound()->SetVoiceRectangle(pSource->m_Voice, fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Width), fx2f(pSource->m_pSource->m_Shape.m_Rectangle.m_Height)); + break; + } + }; + } + } + else + { + // stop voice + Sound()->StopVoice(pSource->m_Voice); + pSource->m_Voice = ISound::CVoiceHandle(); + } + } + + vec2 Center = m_pClient->m_pCamera->m_Center; + for(int g = 0; g < Layers()->NumGroups(); g++) + { + CMapItemGroup *pGroup = Layers()->GetGroup(g); + + if(!pGroup) + continue; + + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = Layers()->GetLayer(pGroup->m_StartLayer+l); + + if(!pLayer) + continue; + + if(pLayer->m_Type == LAYERTYPE_SOUNDS) + { + CMapItemLayerSounds *pSoundLayer = (CMapItemLayerSounds *)pLayer; + + if(pSoundLayer->m_Version < 1 || pSoundLayer->m_Version > CMapItemLayerSounds::CURRENT_VERSION) + continue; + + CSoundSource *pSources = (CSoundSource *)Layers()->Map()->GetDataSwapped(pSoundLayer->m_Data); + + if(!pSources) + continue; + + for(int s = 0; s < pSoundLayer->m_NumSources; s++) { + for(int i = 0; i < m_lSourceQueue.size(); i++) + { + CSourceQueueEntry *pVoice = &m_lSourceQueue[i]; + + if(pVoice->m_pSource != &pSources[s]) + continue; + + if(!pVoice->m_Voice.IsValid()) + continue; + + float OffsetX = 0, OffsetY = 0; + + if(pVoice->m_pSource->m_PosEnv >= 0) + { + float aChannels[4]; + CMapLayers::EnvelopeEval(pVoice->m_pSource->m_PosEnvOffset/1000.0f, pVoice->m_pSource->m_PosEnv, aChannels, m_pClient->m_pMapLayersBackGround); + OffsetX = aChannels[0]; + OffsetY = aChannels[1]; + } + + float x = fx2f(pVoice->m_pSource->m_Position.x)+OffsetX; + float y = fx2f(pVoice->m_pSource->m_Position.y)+OffsetY; + + x += Center.x*(1.0f-pGroup->m_ParallaxX/100.0f); + y += Center.y*(1.0f-pGroup->m_ParallaxY/100.0f); + + x -= pGroup->m_OffsetX; y -= pGroup->m_OffsetY; + + Sound()->SetVoiceLocation(pVoice->m_Voice, x, y); + + if(pVoice->m_pSource->m_SoundEnv >= 0) + { + float aChannels[4]; + CMapLayers::EnvelopeEval(pVoice->m_pSource->m_SoundEnvOffset/1000.0f, pVoice->m_pSource->m_SoundEnv, aChannels, m_pClient->m_pMapLayersBackGround); + float Volume = clamp(aChannels[0], 0.0f, 1.0f); + + Sound()->SetVoiceVolume(pVoice->m_Voice, Volume); + } + } + } + } + } + } +} + +void CMapSounds::Clear() +{ + // unload all samples + for(int i = 0; i < m_Count; i++) + { + Sound()->UnloadSample(m_aSounds[i]); + m_aSounds[i] = -1; + } + m_Count = 0; +} + +void CMapSounds::OnStateChange(int NewState, int OldState) +{ + if(NewState < IClient::STATE_ONLINE) + Clear(); +} diff --git a/src/game/client/components/mapsounds.h b/src/game/client/components/mapsounds.h new file mode 100644 index 0000000..7273f77 --- /dev/null +++ b/src/game/client/components/mapsounds.h @@ -0,0 +1,35 @@ + +#pragma once + +#include <base/tl/array.h> + +#include <engine/sound.h> + +#include <game/client/component.h> + +class CMapSounds : public CComponent +{ + int m_aSounds[64]; + int m_Count; + + struct CSourceQueueEntry + { + int m_Sound; + bool m_HighDetail; + ISound::CVoiceHandle m_Voice; + CSoundSource *m_pSource; + + bool operator ==(const CSourceQueueEntry &Other) const { return (m_Sound == Other.m_Sound) && (m_Voice == Other.m_Voice) && (m_pSource == Other.m_pSource); } + }; + + array<CSourceQueueEntry> m_lSourceQueue; + + void Clear(); + +public: + CMapSounds(); + + virtual void OnMapLoad(); + virtual void OnRender(); + virtual void OnStateChange(int NewState, int OldState); +}; diff --git a/src/game/client/components/menus.cpp b/src/game/client/components/menus.cpp new file mode 100644 index 0000000..b19294a --- /dev/null +++ b/src/game/client/components/menus.cpp @@ -0,0 +1,1977 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/array.h> +#include <sstream> +#include <string> + +#include <math.h> + +#include <base/system.h> +#include <base/math.h> +#include <base/vmath.h> + +#include <engine/config.h> +#include <engine/editor.h> +#include <engine/engine.h> +#include <engine/friends.h> +#include <engine/graphics.h> +#include <engine/keys.h> +#include <engine/serverbrowser.h> +#include <engine/storage.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> + +#include <game/version.h> +#include <game/generated/protocol.h> + +#include <game/generated/client_data.h> +#include <game/client/components/sounds.h> +#include <game/client/gameclient.h> +#include <game/client/lineinput.h> +#include <game/localization.h> +#include <mastersrv/mastersrv.h> +#include <versionsrv/versionsrv.h> + +#include "countryflags.h" +#include "menus.h" +#include "skins.h" +#include "controls.h" + +vec4 CMenus::ms_GuiColor; +vec4 CMenus::ms_ColorTabbarInactiveOutgame; +vec4 CMenus::ms_ColorTabbarActiveOutgame; +vec4 CMenus::ms_ColorTabbarInactive; +vec4 CMenus::ms_ColorTabbarActive = vec4(0,0,0,0.5f); +vec4 CMenus::ms_ColorTabbarInactiveIngame; +vec4 CMenus::ms_ColorTabbarActiveIngame; + +#if defined(__ANDROID__) +float CMenus::ms_ButtonHeight = 50.0f; +float CMenus::ms_ListheaderHeight = 17.0f; +float CMenus::ms_ListitemAdditionalHeight = 33.0f; +#else +float CMenus::ms_ButtonHeight = 25.0f; +float CMenus::ms_ListheaderHeight = 17.0f; +#endif +float CMenus::ms_FontmodHeight = 0.8f; + +IInput::CEvent CMenus::m_aInputEvents[MAX_INPUTEVENTS]; +int CMenus::m_NumInputEvents; + + +CMenus::CMenus() +{ + m_Popup = POPUP_NONE; + m_ActivePage = PAGE_INTERNET; + m_GamePage = PAGE_GAME; + + m_NeedRestartGraphics = false; + m_NeedRestartSound = false; + m_NeedSendinfo = false; + m_NeedSendDummyinfo = 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; + + m_FriendlistSelectedIndex = -1; + m_DoubleClickIndex = -1; + + m_DDRacePage = PAGE_BROWSER; + + m_DemoPlayerState = DEMOPLAYER_NONE; + m_Dummy = false; +} + +vec4 CMenus::ButtonColorMul(const void *pID) +{ + if(UI()->ActiveItem() == pID) + return vec4(1,1,1,0.5f); + else if(UI()->HotItem() == pID) + return vec4(1,1,1,1.5f); + return vec4(1,1,1,1); +} + +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; +} + +int CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active) +{ + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIBUTTONS].m_Id); + Graphics()->QuadsBegin(); + if(!Active) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); + RenderTools()->SelectSprite(Checked?SPRITE_GUIBUTTON_ON:SPRITE_GUIBUTTON_OFF); + IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + if(UI()->HotItem() == pID && Active) + { + RenderTools()->SelectSprite(SPRITE_GUIBUTTON_HOVER); + IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + Graphics()->QuadsEnd(); + + return Active ? UI()->DoButtonLogic(pID, "", Checked, pRect) : 0; +} + +int CMenus::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + RenderTools()->DrawUIRect(pRect, vec4(1,1,1,0.5f)*ButtonColorMul(pID), CUI::CORNER_ALL, 5.0f); + CUIRect Temp; + pRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp); +#if defined(__ANDROID__) + float TextH = min(22.0f, Temp.h); + Temp.y += (Temp.h - TextH) / 2; + UI()->DoLabel(&Temp, pText, TextH*ms_FontmodHeight, 0); +#else + UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); +#endif + return UI()->DoButtonLogic(pID, pText, Checked, pRect); +} + +void CMenus::DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + RenderTools()->DrawUIRect(pRect, vec4(1,1,1,0.5f)*ButtonColorMul(pID), CUI::CORNER_ALL, 5.0f); + CUIRect Temp; + pRect->HMargin(1.0f, &Temp); + UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); +} + +int CMenus::DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners) +{ + if(Checked) + RenderTools()->DrawUIRect(pRect, ms_ColorTabbarActive, Corners, 10.0f); + else + RenderTools()->DrawUIRect(pRect, ms_ColorTabbarInactive, Corners, 10.0f); + CUIRect Temp; + pRect->HMargin(2.0f, &Temp); +#if defined(__ANDROID__) + float TextH = min(22.0f, Temp.h); + Temp.y += (Temp.h - TextH) / 2; + UI()->DoLabel(&Temp, pText, TextH*ms_FontmodHeight, 0); +#else + UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); +#endif + + return UI()->DoButtonLogic(pID, pText, Checked, pRect); +} + +int CMenus::DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +//void CMenus::ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra) +{ + if(Checked) + RenderTools()->DrawUIRect(pRect, vec4(1,1,1,0.5f), CUI::CORNER_T, 5.0f); + CUIRect t; + pRect->VSplitLeft(5.0f, 0, &t); +#if defined(__ANDROID__) + float TextH = min(20.0f, pRect->h); + UI()->DoLabel(&t, pText, TextH*ms_FontmodHeight, -1); +#else + UI()->DoLabel(&t, pText, pRect->h*ms_FontmodHeight, -1); +#endif + return UI()->DoButtonLogic(pID, pText, Checked, pRect); +} + +int CMenus::DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect) +//void CMenus::ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra) +{ + CUIRect c = *pRect; + CUIRect t = *pRect; + c.w = c.h; + 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; + UI()->DoLabel(&c, pBoxText, pRect->h*ms_FontmodHeight*0.6f, 0); + UI()->DoLabel(&t, pText, pRect->h*ms_FontmodHeight*0.8f, -1); + return UI()->DoButtonLogic(pID, pText, 0, pRect); +} + +int CMenus::DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + return DoButton_CheckBox_Common(pID, pText, Checked?"X":"", pRect); +} + + +int CMenus::DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Checked); + return DoButton_CheckBox_Common(pID, pText, aBuf, pRect); +} + +int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners, const char *pEmptyText) +{ + int Inside = UI()->MouseInside(pRect); + bool ReturnValue = false; + bool UpdateOffset = false; + static int s_AtIndex = 0; + static bool s_DoScroll = false; + static float s_ScrollStart = 0.0f; + + FontSize *= UI()->Scale(); + + if(UI()->LastActiveItem() == pID) + { + int Len = str_length(pStr); + if(Len == 0) + s_AtIndex = 0; + + if(Inside && UI()->MouseButton(0)) + { + s_DoScroll = true; + s_ScrollStart = UI()->MouseX(); + int MxRel = (int)(UI()->MouseX() - pRect->x); + + for(int i = 1; i <= Len; i++) + { + if(TextRender()->TextWidth(0, FontSize, pStr, i) - *Offset > MxRel) + { + s_AtIndex = i - 1; + break; + } + + if(i == Len) + s_AtIndex = Len; + } + } + else if(!UI()->MouseButton(0)) + s_DoScroll = false; + else if(s_DoScroll) + { + // do scrolling + if(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f) + { + s_AtIndex = max(0, s_AtIndex-1); + s_ScrollStart = UI()->MouseX(); + UpdateOffset = true; + } + else if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f) + { + s_AtIndex = min(Len, s_AtIndex+1); + s_ScrollStart = UI()->MouseX(); + UpdateOffset = true; + } + } + + for(int i = 0; i < m_NumInputEvents; i++) + { + Len = str_length(pStr); + int NumChars = Len; + ReturnValue |= CLineInput::Manipulate(m_aInputEvents[i], pStr, StrSize, StrSize, &Len, &s_AtIndex, &NumChars); + } + } + + bool JustGotActive = false; + + if(UI()->ActiveItem() == pID) + { + if(!UI()->MouseButton(0)) + { + s_AtIndex = min(s_AtIndex, str_length(pStr)); + s_DoScroll = false; + UI()->SetActiveItem(0); + } + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + if (UI()->LastActiveItem() != pID) + JustGotActive = true; + UI()->SetActiveItem(pID); + } + } + + if(Inside) + { + UI()->SetHotItem(pID); +#if defined(__ANDROID__) + if(UI()->ActiveItem() == pID && UI()->MouseButtonClicked(0)) + { + s_AtIndex = 0; + UI()->AndroidBlockAndGetTextInput(pStr, StrSize, ""); + } +#endif + } + + CUIRect Textbox = *pRect; + 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(pDisplayStr[0] == '\0') + { + pDisplayStr = pEmptyText; + TextRender()->TextColor(1, 1, 1, 0.75f); + } + + if(Hidden) + { + unsigned s = str_length(pDisplayStr); + if(s >= sizeof(aStars)) + s = sizeof(aStars)-1; + for(unsigned int i = 0; i < s; ++i) + aStars[i] = '*'; + aStars[s] = 0; + pDisplayStr = aStars; + } + + // check if the text has to be moved + if(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || m_NumInputEvents)) + { + float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); + if(w-*Offset > Textbox.w) + { + // move to the left + float wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1); + do + { + *Offset += min(wt-*Offset-Textbox.w, Textbox.w/3); + } + while(w-*Offset > Textbox.w); + } + else if(w-*Offset < 0.0f) + { + // move to the right + do + { + *Offset = max(0.0f, *Offset-Textbox.w/3); + } + while(w-*Offset < 0.0f); + } + } + UI()->ClipEnable(pRect); + Textbox.x -= *Offset; + + UI()->DoLabel(&Textbox, pDisplayStr, FontSize, -1); + + TextRender()->TextColor(1, 1, 1, 1); + + // render the cursor + if(UI()->LastActiveItem() == pID && !JustGotActive) + { + float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); + Textbox = *pRect; + Textbox.VSplitLeft(2.0f, 0, &Textbox); + Textbox.x += (w-*Offset-TextRender()->TextWidth(0, FontSize, "|", -1)/2); + + if((2*time_get()/time_freq()) % 2) // make it blink + UI()->DoLabel(&Textbox, "|", FontSize, -1); + } + UI()->ClipDisable(); + + return ReturnValue; +} + +float CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current) +{ + CUIRect Handle; + static float OffsetY; +#if defined(__ANDROID__) + pRect->HSplitTop(50, &Handle, 0); +#else + pRect->HSplitTop(33, &Handle, 0); +#endif + + Handle.y += (pRect->h-Handle.h)*Current; + + // logic + 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; + ReturnValue = (Cur-Min)/Max; + if(ReturnValue < 0.0f) ReturnValue = 0.0f; + if(ReturnValue > 1.0f) ReturnValue = 1.0f; + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + UI()->SetActiveItem(pID); + OffsetY = UI()->MouseY()-Handle.y; + } + } + + if(Inside) + UI()->SetHotItem(pID); + + // render + CUIRect Rail; + pRect->VMargin(5.0f, &Rail); + RenderTools()->DrawUIRect(&Rail, vec4(1,1,1,0.25f), 0, 0.0f); + + CUIRect Slider = Handle; + Slider.w = Rail.x-Slider.x; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_L, 2.5f); + Slider.x = Rail.x+Rail.w; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_R, 2.5f); + + 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; +} + + + +float CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current) +{ + CUIRect Handle; + static float OffsetX; + pRect->VSplitLeft(33, &Handle, 0); + + Handle.x += (pRect->w-Handle.w)*Current; + + // logic + 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; + ReturnValue = (Cur-Min)/Max; + if(ReturnValue < 0.0f) ReturnValue = 0.0f; + if(ReturnValue > 1.0f) ReturnValue = 1.0f; + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + UI()->SetActiveItem(pID); + OffsetX = UI()->MouseX()-Handle.x; + } + } + + if(Inside) + UI()->SetHotItem(pID); + + // render + CUIRect Rail; + pRect->HMargin(5.0f, &Rail); + RenderTools()->DrawUIRect(&Rail, vec4(1,1,1,0.25f), 0, 0.0f); + + CUIRect Slider = Handle; + Slider.h = Rail.y-Slider.y; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_T, 2.5f); + Slider.y = Rail.y+Rail.h; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_B, 2.5f); + + 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; +} + +int CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key) +{ + // process + static void *pGrabbedID = 0; + static bool MouseReleased = true; + static int ButtonUsed = 0; + int Inside = UI()->MouseInside(pRect); + int NewKey = Key; + + if(!UI()->MouseButton(0) && !UI()->MouseButton(1) && pGrabbedID == pID) + MouseReleased = true; + + if(UI()->ActiveItem() == pID) + { + if(m_Binder.m_GotKey) + { + // abort with escape key + if(m_Binder.m_Key.m_Key != KEY_ESCAPE) + NewKey = m_Binder.m_Key.m_Key; + m_Binder.m_GotKey = false; + UI()->SetActiveItem(0); + MouseReleased = false; + pGrabbedID = pID; + } + + if(ButtonUsed == 1 && !UI()->MouseButton(1)) + { + if(Inside) + NewKey = 0; + UI()->SetActiveItem(0); + } + } + else if(UI()->HotItem() == pID) + { + if(MouseReleased) + { + if(UI()->MouseButton(0)) + { + m_Binder.m_TakeKey = true; + m_Binder.m_GotKey = false; + UI()->SetActiveItem(pID); + ButtonUsed = 0; + } + + if(UI()->MouseButton(1)) + { + UI()->SetActiveItem(pID); + ButtonUsed = 1; + } + } + } + + if(Inside) + UI()->SetHotItem(pID); + + // draw + if (UI()->ActiveItem() == pID && ButtonUsed == 0) + DoButton_KeySelect(pID, "???", 0, pRect); + else + { + if(Key == 0) + DoButton_KeySelect(pID, "", 0, pRect); + else + DoButton_KeySelect(pID, Input()->KeyName(Key), 0, pRect); + } + return NewKey; +} + + +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 + Box.VSplitLeft(90.0f, &Button, &Box); + static int s_NewsButton=0; + if (DoButton_MenuTab(&s_NewsButton, Localize("News"), m_ActivePage==PAGE_NEWS, &Button, CUI::CORNER_T)) + { + NewPage = PAGE_NEWS; + m_DoubleClickIndex = -1; + } + Box.VSplitLeft(10.0f, 0, &Box); + + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_InternetButton=0; + if(DoButton_MenuTab(&s_InternetButton, Localize("Internet"), m_ActivePage==PAGE_INTERNET, &Button, CUI::CORNER_TL)) + { + if(ServerBrowser()->GetCurrentType() != IServerBrowser::TYPE_INTERNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); + NewPage = PAGE_INTERNET; + m_DoubleClickIndex = -1; + } + + //Box.VSplitLeft(4.0f, 0, &Box); + Box.VSplitLeft(60.0f, &Button, &Box); + static int s_LanButton=0; + if(DoButton_MenuTab(&s_LanButton, Localize("LAN"), m_ActivePage==PAGE_LAN, &Button, 0)) + { + if(ServerBrowser()->GetCurrentType() != IServerBrowser::TYPE_LAN) + ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); + NewPage = PAGE_LAN; + m_DoubleClickIndex = -1; + } + + //box.VSplitLeft(4.0f, 0, &box); + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_FavoritesButton=0; + if(DoButton_MenuTab(&s_FavoritesButton, Localize("Favorites"), m_ActivePage==PAGE_FAVORITES, &Button, 0)) + { + if(ServerBrowser()->GetCurrentType() != IServerBrowser::TYPE_FAVORITES) + ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); + NewPage = PAGE_FAVORITES; + m_DoubleClickIndex = -1; + } + + //box.VSplitLeft(4.0f, 0, &box); + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_DDNetButton=0; + if(DoButton_MenuTab(&s_DDNetButton, Localize("DDNet"), m_ActivePage==PAGE_DDNET, &Button, CUI::CORNER_TR)) + { + if(ServerBrowser()->GetCurrentType() != IServerBrowser::TYPE_DDNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + NewPage = PAGE_DDNET; + m_DoubleClickIndex = -1; + } + + Box.VSplitLeft(10.0f, 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; + m_DoubleClickIndex = -1; + } + } + else + { + // online menus + Box.VSplitLeft(90.0f, &Button, &Box); + static int s_GameButton=0; + if(DoButton_MenuTab(&s_GameButton, Localize("Game"), m_ActivePage==PAGE_GAME, &Button, CUI::CORNER_TL)) + NewPage = PAGE_GAME; + + Box.VSplitLeft(90.0f, &Button, &Box); + static int s_PlayersButton=0; + if(DoButton_MenuTab(&s_PlayersButton, Localize("Players"), m_ActivePage==PAGE_PLAYERS, &Button, 0)) + NewPage = PAGE_PLAYERS; + + Box.VSplitLeft(130.0f, &Button, &Box); + static int s_ServerInfoButton=0; + if(DoButton_MenuTab(&s_ServerInfoButton, Localize("Server info"), m_ActivePage==PAGE_SERVER_INFO, &Button, 0)) + NewPage = PAGE_SERVER_INFO; + + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_GhostButton=0; + if(DoButton_MenuTab(&s_GhostButton, "Network", m_ActivePage==PAGE_DDRace, &Button, 0)) + NewPage = PAGE_DDRace; + + Box.VSplitLeft(100.0f, &Button, &Box); + Box.VSplitLeft(4.0f, 0, &Box); + static int s_CallVoteButton=0; + 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(30.0f, &Box, &Button); + static int s_QuitButton=0; + if(DoButton_MenuTab(&s_QuitButton, "×", 0, &Button, CUI::CORNER_T)) + m_Popup = POPUP_QUIT; + + Box.VSplitRight(10.0f, &Box, &Button); + Box.VSplitRight(30.0f, &Box, &Button); + static int s_SettingsButton=0; + if(DoButton_MenuTab(&s_SettingsButton, "⚙", m_ActivePage==PAGE_SETTINGS, &Button, CUI::CORNER_T)) + NewPage = PAGE_SETTINGS; + + Box.VSplitRight(10.0f, &Box, &Button); + Box.VSplitRight(30.0f, &Box, &Button); + static int s_EditorButton=0; + if(DoButton_MenuTab(&s_EditorButton, Localize("✎"), 0, &Button, CUI::CORNER_T)) + { + g_Config.m_ClEditor = 1; + } + + if(NewPage != -1) + { + if(Client()->State() == IClient::STATE_OFFLINE) + g_Config.m_UiPage = NewPage; + else + m_GamePage = NewPage; + } + + return 0; +} + +void CMenus::RenderLoading() +{ + // TODO: not supported right now due to separate render thread + + static int64 LastLoadRender = 0; + float Percent = m_LoadCurrent++/(float)m_LoadTotal; + + // make sure that we don't render for each little thing we load + // 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(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + RenderBackground(); + + float w = 700; + float h = 200; + float x = Screen.w/2-w/2; + float y = Screen.h/2-h/2; + + Graphics()->BlendNormal(); + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.50f); + RenderTools()->DrawRoundRect(x, y, w, h, 40.0f); + Graphics()->QuadsEnd(); + + + const char *pCaption = Localize("Loading DDNet Client"); + + CUIRect r; + r.x = x; + r.y = y+20; + r.w = w; + r.h = h; + UI()->DoLabel(&r, pCaption, 48.0f, 0, -1); + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1,1,1,0.75f); + RenderTools()->DrawRoundRect(x+40, y+h-75, (w-80)*Percent, 25, 5.0f); + Graphics()->QuadsEnd(); + + Graphics()->Swap(); +} + +void CMenus::RenderNews(CUIRect MainView) +{ + // TODO: Like the settings with big fonts + // Make it work WITHOUT version updates + // Show news once after each version or news update + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + + MainView.HSplitTop(15.0f, 0, &MainView); + MainView.VSplitLeft(15.0f, 0, &MainView); + + CUIRect Label; + + std::istringstream f(Client()->m_aNews); + std::string line; + while (std::getline(f, line)) + { + if(line.size() > 0 && line.at(0) == '|' && line.at(line.size()-1) == '|') + { + MainView.HSplitTop(30.0f, &Label, &MainView); + UI()->DoLabelScaled(&Label, Localize(line.substr(1, line.size()-2).c_str()), 20.0f, -1); + } + else + { + MainView.HSplitTop(20.0f, &Label, &MainView); + UI()->DoLabelScaled(&Label, line.c_str(), 15.f, -1, MainView.w-30.0f); + } + } +} + +void CMenus::OnInit() +{ + + /* + array<string> my_strings; + array<string>::range r2; + my_strings.add("4"); + my_strings.add("6"); + my_strings.add("1"); + my_strings.add("3"); + my_strings.add("7"); + my_strings.add("5"); + my_strings.add("2"); + + 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); + myarray.add(1); + myarray.add(3); + myarray.add(7); + myarray.add(5); + myarray.add(2); + + 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; + str_copy(g_Config.m_BrFilterString, "Novice [DDraceNetwork]", sizeof(g_Config.m_BrFilterString)); + } + g_Config.m_ClShowWelcome = 0; + + Console()->Chain("add_favorite", ConchainServerbrowserUpdate, this); + Console()->Chain("remove_favorite", ConchainServerbrowserUpdate, this); + Console()->Chain("add_friend", ConchainFriendlistUpdate, this); + Console()->Chain("remove_friend", ConchainFriendlistUpdate, this); + + // setup load amount + m_LoadCurrent = 0; + m_LoadTotal = g_pData->m_NumImages; + if(!g_Config.m_ClThreadsoundloading) + m_LoadTotal += g_pData->m_NumSounds; +} + +void CMenus::PopupMessage(const char *pTopic, const char *pBody, const char *pButton) +{ + // reset active item + UI()->SetActiveItem(0); + + str_copy(m_aMessageTopic, pTopic, sizeof(m_aMessageTopic)); + str_copy(m_aMessageBody, pBody, sizeof(m_aMessageBody)); + str_copy(m_aMessageButton, pButton, sizeof(m_aMessageButton)); + m_Popup = POPUP_MESSAGE; +} + + +int CMenus::Render() +{ + CUIRect Screen = *UI()->Screen(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + static bool s_First = true; + if(s_First) + { + m_pClient->m_pSounds->Enqueue(CSounds::CHN_MUSIC, SOUND_MENU); + s_First = false; + m_DoubleClickIndex = -1; + + if(g_Config.m_UiPage == PAGE_INTERNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); + else if(g_Config.m_UiPage == PAGE_LAN) + ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); + else if(g_Config.m_UiPage == PAGE_FAVORITES) + ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); + else if(g_Config.m_UiPage == PAGE_DDNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + } + + if(Client()->State() == IClient::STATE_ONLINE) + { + ms_ColorTabbarInactive = ms_ColorTabbarInactiveIngame; + ms_ColorTabbarActive = ms_ColorTabbarActiveIngame; + } + else + { + RenderBackground(); + 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) + { + if(Client()->SoundInitFailed()) + m_Popup = POPUP_SOUNDERROR; + s_SoundCheck = true; + } + + if(m_Popup == POPUP_NONE) + { + // do tab bar +#if defined(__ANDROID__) + Screen.HSplitTop(100.0f, &TabBar, &MainView); +#else + Screen.HSplitTop(24.0f, &TabBar, &MainView); +#endif + 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; + m_DoubleClickIndex = -1; + } + + // render current page + if(Client()->State() != IClient::STATE_OFFLINE) + { + if(m_GamePage == PAGE_GAME) + RenderGame(MainView); + else if(m_GamePage == PAGE_PLAYERS) + RenderPlayers(MainView); + else if(m_GamePage == PAGE_SERVER_INFO) + RenderServerInfo(MainView); + else if(m_GamePage == PAGE_DDRace) + RenderInGameDDRace(MainView); + else if(m_GamePage == PAGE_CALLVOTE) + RenderServerControl(MainView); + else if(m_GamePage == PAGE_SETTINGS) + RenderSettings(MainView); + else if(m_GamePage == PAGE_GHOST) + RenderGhost(MainView); + else if(m_GamePage == PAGE_BROWSER) + RenderInGameBrowser(MainView); + } + else if(g_Config.m_UiPage == PAGE_NEWS) + RenderNews(MainView); + else if(g_Config.m_UiPage == PAGE_INTERNET) + RenderServerbrowser(MainView); + else if(g_Config.m_UiPage == PAGE_LAN) + RenderServerbrowser(MainView); + else if(g_Config.m_UiPage == PAGE_DEMOS) + RenderDemoList(MainView); + else if(g_Config.m_UiPage == PAGE_FAVORITES) + RenderServerbrowser(MainView); + else if(g_Config.m_UiPage == PAGE_DDNET) + RenderServerbrowser(MainView); + else if(g_Config.m_UiPage == PAGE_SETTINGS) + RenderSettings(MainView); + } + else + { + // make sure that other windows doesn't do anything funnay! + //UI()->SetHotItem(0); + //UI()->SetActiveItem(0); + char aBuf[128]; + const char *pTitle = ""; + const char *pExtraText = ""; + const char *pButtonText = ""; + int ExtraAlign = 0; + + if(m_Popup == POPUP_MESSAGE) + { + pTitle = m_aMessageTopic; + pExtraText = m_aMessageBody; + pButtonText = m_aMessageButton; + } + else if(m_Popup == POPUP_CONNECTING) + { + pTitle = Localize("Connecting to"); + pExtraText = g_Config.m_UiServerAddress; // TODO: query the client about the address + pButtonText = Localize("Abort"); + if(Client()->MapDownloadTotalsize() > 0) + { + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Downloading map"), Client()->MapDownloadName()); + pTitle = aBuf; + pExtraText = ""; + } + } + else if (m_Popup == POPUP_DISCONNECTED) + { + pTitle = Localize("Disconnected"); + pExtraText = Client()->ErrorString(); + pButtonText = Localize("Ok"); + if ((str_find_nocase(Client()->ErrorString(), "full")) || (str_find_nocase(Client()->ErrorString(), "reserved"))) + { + if (g_Config.m_ClReconnectFull) + { + if (_my_rtime == 0) + _my_rtime = time_get(); + str_format(aBuf, sizeof(aBuf), Localize("\n\nReconnect in %d sec"), ((_my_rtime - time_get()) / time_freq() + g_Config.m_ClReconnectFullTimeout)); + pTitle = Client()->ErrorString(); + pExtraText = aBuf; + pButtonText = Localize("Abort"); + } + } + else if (str_find_nocase(Client()->ErrorString(), "ban")) + { + if (g_Config.m_ClReconnectBan) + { + if (_my_rtime == 0) + _my_rtime = time_get(); + str_format(aBuf, sizeof(aBuf), Localize("\n\nReconnect in %d sec"), ((_my_rtime - time_get()) / time_freq() + g_Config.m_ClReconnectBanTimeout)); + pTitle = Client()->ErrorString(); + pExtraText = aBuf; + pButtonText = Localize("Abort"); + } + } + ExtraAlign = 0; + } + else if(m_Popup == POPUP_PURE) + { + pTitle = Localize("Disconnected"); + pExtraText = Localize("The server is running a non-standard tuning on a pure game type."); + pButtonText = Localize("Ok"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_DELETE_DEMO) + { + pTitle = Localize("Delete demo"); + pExtraText = Localize("Are you sure that you want to delete the demo?"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_RENAME_DEMO) + { + pTitle = Localize("Rename demo"); + pExtraText = ""; + ExtraAlign = -1; + } + else if(m_Popup == POPUP_REMOVE_FRIEND) + { + pTitle = Localize("Remove friend"); + pExtraText = Localize("Are you sure that you want to remove the player from your friends list?"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_SOUNDERROR) + { + pTitle = Localize("Sound error"); + pExtraText = Localize("The audio device couldn't be initialised."); + pButtonText = Localize("Ok"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_PASSWORD) + { + pTitle = Localize("Password incorrect"); + pExtraText = ""; + pButtonText = Localize("Try again"); + } + else if(m_Popup == POPUP_QUIT) + { + pTitle = Localize("Quit"); + pExtraText = Localize("Are you sure that you want to quit?"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_DISCONNECT) + { + pTitle = Localize("Disconnect"); + pExtraText = Localize("Are you sure that you want to disconnect?"); + ExtraAlign = -1; + } + else if(m_Popup == POPUP_FIRST_LAUNCH) + { + pTitle = Localize("Welcome to Teeworlds"); + pExtraText = Localize("As this is the first time you launch the game, please enter your nick name below. It's recommended that you check the settings to adjust them to your liking before joining a server."); + pButtonText = Localize("Ok"); + ExtraAlign = -1; + } + + CUIRect Box, Part; + Box = Screen; + Box.VMargin(150.0f/UI()->Scale(), &Box); +#if defined(__ANDROID__) + Box.HMargin(100.0f/UI()->Scale(), &Box); +#else + Box.HMargin(150.0f/UI()->Scale(), &Box); +#endif + + // 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); + Part.VMargin(20.f/UI()->Scale(), &Part); + if(TextRender()->TextWidth(0, 24.f, pTitle, -1) > Part.w) + UI()->DoLabelScaled(&Part, pTitle, 24.f, -1, (int)Part.w); + else + 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 + { + if(TextRender()->TextWidth(0, 20.f, pExtraText, -1) > Part.w) + UI()->DoLabelScaled(&Part, pExtraText, 20.f, -1, (int)Part.w); + else + UI()->DoLabelScaled(&Part, pExtraText, 20.f, 0, -1); + } + + if(m_Popup == POPUP_QUIT) + { + CUIRect Yes, No; + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + // additional info + Box.HSplitTop(10.0f, 0, &Box); + Box.VMargin(20.f/UI()->Scale(), &Box); + if(m_pClient->Editor()->HasUnsavedData()) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s\n%s", Localize("There's an unsaved map in the editor, you might want to save it before you quit the game."), Localize("Quit anyway?")); + UI()->DoLabelScaled(&Box, aBuf, 20.f, -1, Part.w-20.0f); + } + + // buttons + Part.VMargin(80.0f, &Part); + Part.VSplitMid(&No, &Yes); + Yes.VMargin(20.0f, &Yes); + No.VMargin(20.0f, &No); + + static int s_ButtonAbort = 0; + if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) + m_Popup = POPUP_NONE; + + static int s_ButtonTryAgain = 0; + if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), 0, &Yes) || m_EnterPressed) + Client()->Quit(); + } + else if(m_Popup == POPUP_DISCONNECT) + { + CUIRect Yes, No; + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + // buttons + Part.VMargin(80.0f, &Part); + Part.VSplitMid(&No, &Yes); + Yes.VMargin(20.0f, &Yes); + No.VMargin(20.0f, &No); + + static int s_ButtonAbort = 0; + if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) + m_Popup = POPUP_NONE; + + static int s_ButtonTryAgain = 0; + if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), 0, &Yes) || m_EnterPressed) + Client()->Disconnect(); + } + else if(m_Popup == POPUP_PASSWORD) + { + CUIRect Label, TextBox, TryAgain, Abort; + + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + 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; + + static int s_ButtonTryAgain = 0; + if(DoButton_Menu(&s_ButtonTryAgain, Localize("Try again"), 0, &TryAgain) || m_EnterPressed) + { + Client()->Connect(g_Config.m_UiServerAddress); + } + + Box.HSplitBottom(60.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + Part.VSplitLeft(60.0f, 0, &Label); + Label.VSplitLeft(100.0f, 0, &TextBox); + TextBox.VSplitLeft(20.0f, 0, &TextBox); + TextBox.VSplitRight(60.0f, &TextBox, 0); + UI()->DoLabel(&Label, Localize("Password"), 18.0f, -1); + static float Offset = 0.0f; + DoEditBox(&g_Config.m_Password, &TextBox, g_Config.m_Password, sizeof(g_Config.m_Password), 12.0f, &Offset, true); + } + else if(m_Popup == POPUP_CONNECTING) + { + Box = Screen; + Box.VMargin(150.0f, &Box); + Box.HMargin(150.0f, &Box); + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Part.VMargin(120.0f, &Part); + + static int s_Button = 0; + if(DoButton_Menu(&s_Button, pButtonText, 0, &Part) || m_EscapePressed || m_EnterPressed) + { + Client()->Disconnect(); + m_Popup = POPUP_NONE; + } + + if(Client()->MapDownloadTotalsize() > 0) + { + int64 Now = time_get(); + if(Now-m_DownloadLastCheckTime >= time_freq()) + { + if(m_DownloadLastCheckSize > Client()->MapDownloadAmount()) + { + // map downloaded restarted + m_DownloadLastCheckSize = 0; + } + + // update download speed + float Diff = (Client()->MapDownloadAmount()-m_DownloadLastCheckSize)/((int)((Now-m_DownloadLastCheckTime)/time_freq())); + float StartDiff = m_DownloadLastCheckSize-0.0f; + if(StartDiff+Diff > 0.0f) + m_DownloadSpeed = (Diff/(StartDiff+Diff))*(Diff/1.0f) + (StartDiff/(Diff+StartDiff))*m_DownloadSpeed; + else + m_DownloadSpeed = 0.0f; + m_DownloadLastCheckTime = Now; + m_DownloadLastCheckSize = Client()->MapDownloadAmount(); + } + + Box.HSplitTop(64.f, 0, &Box); + 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 = max(1, m_DownloadSpeed > 0.0f ? static_cast<int>((Client()->MapDownloadTotalsize()-Client()->MapDownloadAmount())/m_DownloadSpeed) : 1); + if(TimeLeft >= 60) + { + TimeLeft /= 60; + pTimeLeftString = TimeLeft == 1 ? Localize("%i minute left") : Localize("%i minutes left"); + } + else + pTimeLeftString = TimeLeft == 1 ? Localize("%i second left") : Localize("%i seconds left"); + Box.HSplitTop(20.f, 0, &Box); + Box.HSplitTop(24.f, &Part, &Box); + str_format(aBuf, sizeof(aBuf), pTimeLeftString, TimeLeft); + UI()->DoLabel(&Part, aBuf, 20.f, 0, -1); + + // progress bar + Box.HSplitTop(20.f, 0, &Box); + Box.HSplitTop(24.f, &Part, &Box); + Part.VMargin(40.0f, &Part); + RenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f); + Part.w = max(10.0f, (Part.w*Client()->MapDownloadAmount())/Client()->MapDownloadTotalsize()); + RenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 5.0f); + } + } + else if(m_Popup == POPUP_LANGUAGE) + { + Box = Screen; + Box.VMargin(150.0f, &Box); +#if defined(__ANDROID__) + Box.HMargin(20.0f, &Box); +#else + Box.HMargin(150.0f, &Box); +#endif + Box.HSplitTop(20.f, &Part, &Box); + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Box.HSplitBottom(20.f, &Box, 0); + Box.VMargin(20.0f, &Box); + RenderLanguageSelection(Box); + Part.VMargin(120.0f, &Part); + + static int s_Button = 0; + if(DoButton_Menu(&s_Button, Localize("Ok"), 0, &Part) || m_EscapePressed || m_EnterPressed) + m_Popup = POPUP_FIRST_LAUNCH; + } + else if(m_Popup == POPUP_COUNTRY) + { + Box = Screen; + Box.VMargin(150.0f, &Box); +#if defined(__ANDROID__) + Box.HMargin(20.0f, &Box); +#else + Box.HMargin(150.0f, &Box); +#endif + Box.HSplitTop(20.f, &Part, &Box); + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Box.HSplitBottom(20.f, &Box, 0); + Box.VMargin(20.0f, &Box); + + static int ActSelection = -2; + if(ActSelection == -2) + ActSelection = g_Config.m_BrFilterCountryIndex; + static float s_ScrollValue = 0.0f; + int OldSelected = -1; + UiDoListboxStart(&s_ScrollValue, &Box, 50.0f, Localize("Country"), "", m_pClient->m_pCountryFlags->Num(), 6, OldSelected, s_ScrollValue); + + for(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i) + { + const CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i); + if(pEntry->m_CountryCode == ActSelection) + OldSelected = i; + + CListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i); + if(Item.m_Visible) + { + CUIRect Label; + Item.m_Rect.Margin(5.0f, &Item.m_Rect); + Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label); + float OldWidth = Item.m_Rect.w; + Item.m_Rect.w = Item.m_Rect.h*2; + Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f; + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + m_pClient->m_pCountryFlags->Render(pEntry->m_CountryCode, &Color, Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h); + UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); + } + } + + const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); + if(OldSelected != NewSelected) + ActSelection = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode; + + Part.VMargin(120.0f, &Part); + + static int s_Button = 0; + if(DoButton_Menu(&s_Button, Localize("Ok"), 0, &Part) || m_EnterPressed) + { + g_Config.m_BrFilterCountryIndex = ActSelection; + Client()->ServerBrowserUpdate(); + m_Popup = POPUP_NONE; + } + + if(m_EscapePressed) + { + ActSelection = g_Config.m_BrFilterCountryIndex; + m_Popup = POPUP_NONE; + } + } + else if(m_Popup == POPUP_DELETE_DEMO) + { + CUIRect Yes, No; + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Part.VMargin(80.0f, &Part); + + Part.VSplitMid(&No, &Yes); + + Yes.VMargin(20.0f, &Yes); + No.VMargin(20.0f, &No); + + static int s_ButtonAbort = 0; + if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) + m_Popup = POPUP_NONE; + + static int s_ButtonTryAgain = 0; + if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), 0, &Yes) || m_EnterPressed) + { + m_Popup = POPUP_NONE; + // delete demo + if(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); + if(Storage()->RemoveFile(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType)) + { + DemolistPopulate(); + DemolistOnUpdate(false); + } + else + PopupMessage(Localize("Error"), Localize("Unable to delete the demo"), Localize("Ok")); + } + } + } + else if(m_Popup == POPUP_RENAME_DEMO) + { + CUIRect Label, TextBox, Ok, Abort; + + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + 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; + + static int s_ButtonOk = 0; + if(DoButton_Menu(&s_ButtonOk, Localize("Ok"), 0, &Ok) || m_EnterPressed) + { + m_Popup = POPUP_NONE; + // rename demo + if(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir) + { + char aBufOld[512]; + str_format(aBufOld, sizeof(aBufOld), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); + int Length = str_length(m_aCurrentDemoFile); + char aBufNew[512]; + if(Length <= 4 || m_aCurrentDemoFile[Length-5] != '.' || str_comp_nocase(m_aCurrentDemoFile+Length-4, "demo")) + str_format(aBufNew, sizeof(aBufNew), "%s/%s.demo", m_aCurrentDemoFolder, m_aCurrentDemoFile); + else + str_format(aBufNew, sizeof(aBufNew), "%s/%s", m_aCurrentDemoFolder, m_aCurrentDemoFile); + if(Storage()->RenameFile(aBufOld, aBufNew, m_lDemos[m_DemolistSelectedIndex].m_StorageType)) + { + DemolistPopulate(); + DemolistOnUpdate(false); + } + else + PopupMessage(Localize("Error"), Localize("Unable to rename the demo"), Localize("Ok")); + } + } + + Box.HSplitBottom(60.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + Part.VSplitLeft(60.0f, 0, &Label); + Label.VSplitLeft(120.0f, 0, &TextBox); + TextBox.VSplitLeft(20.0f, 0, &TextBox); + TextBox.VSplitRight(60.0f, &TextBox, 0); + UI()->DoLabel(&Label, Localize("New name:"), 18.0f, -1); + static float Offset = 0.0f; + DoEditBox(&Offset, &TextBox, m_aCurrentDemoFile, sizeof(m_aCurrentDemoFile), 12.0f, &Offset); + } + else if(m_Popup == POPUP_REMOVE_FRIEND) + { + CUIRect Yes, No; + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Part.VMargin(80.0f, &Part); + + Part.VSplitMid(&No, &Yes); + + Yes.VMargin(20.0f, &Yes); + No.VMargin(20.0f, &No); + + static int s_ButtonAbort = 0; + if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) + m_Popup = POPUP_NONE; + + static int s_ButtonTryAgain = 0; + if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), 0, &Yes) || m_EnterPressed) + { + m_Popup = POPUP_NONE; + // remove friend + if(m_FriendlistSelectedIndex >= 0) + { + m_pClient->Friends()->RemoveFriend(m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName, + m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aClan); + FriendlistOnUpdate(); + Client()->ServerBrowserUpdate(); + } + } + } + else if(m_Popup == POPUP_FIRST_LAUNCH) + { + CUIRect Label, TextBox; + + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + 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); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + Part.VSplitLeft(60.0f, 0, &Label); + Label.VSplitLeft(100.0f, 0, &TextBox); + TextBox.VSplitLeft(20.0f, 0, &TextBox); + TextBox.VSplitRight(60.0f, &TextBox, 0); + UI()->DoLabel(&Label, Localize("Nickname"), 18.0f, -1); + static float Offset = 0.0f; + DoEditBox(&g_Config.m_PlayerName, &TextBox, g_Config.m_PlayerName, sizeof(g_Config.m_PlayerName), 12.0f, &Offset); + } + else + { + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + Part.VMargin(120.0f, &Part); + + static int s_Button = 0; + if(DoButton_Menu(&s_Button, pButtonText, 0, &Part) || m_EscapePressed || m_EnterPressed) + m_Popup = POPUP_NONE; + } + + if(m_Popup == POPUP_NONE) + UI()->SetActiveItem(0); + } + + if (m_Popup == POPUP_DISCONNECTED) + { + if (str_find_nocase(Client()->ErrorString(), "full") || str_find_nocase(Client()->ErrorString(), "reserved")) + { + if (g_Config.m_ClReconnectFull && time_get() > _my_rtime + time_freq() * g_Config.m_ClReconnectFullTimeout) + Client()->Connect(g_Config.m_UiServerAddress); + } + else if (str_find_nocase(Client()->ErrorString(), "ban") || str_find_nocase(Client()->ErrorString(), "kick")) + { + if (g_Config.m_ClReconnectBan && time_get() > _my_rtime + time_freq() * g_Config.m_ClReconnectBanTimeout) + Client()->Connect(g_Config.m_UiServerAddress); + } + } + else if (_my_rtime != 0) { + _my_rtime = 0; + } + return 0; +} + + +void CMenus::SetActive(bool Active) +{ + m_MenuActive = Active; +#if defined(__ANDROID__) + UI()->AndroidShowScreenKeys(!m_MenuActive && !m_pClient->m_pControls->m_UsingGamepad); +#endif + if(!m_MenuActive) + { + if(m_NeedSendinfo) + { + m_pClient->SendInfo(false); + m_NeedSendinfo = false; + } + + if(m_NeedSendDummyinfo) + { + m_pClient->SendDummyInfo(false); + m_NeedSendDummyinfo = false; + } + + if(Client()->State() == IClient::STATE_ONLINE) + { + m_pClient->OnRelease(); + } + } + else if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + m_pClient->OnRelease(); + } +} + +void CMenus::OnReset() +{ +} + +bool CMenus::OnMouseMove(float x, float y) +{ + m_LastInput = time_get(); + + if(!m_MenuActive) + return false; + +#if defined(__ANDROID__) // No relative mouse on Android + m_MousePos.x = x; + m_MousePos.y = y; +#else + UI()->ConvertMouseMove(&x, &y); + m_MousePos.x += x; + m_MousePos.y += y; +#endif + 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) + { + if(e.m_Key == KEY_ESCAPE) + { + m_EscapePressed = true; + SetActive(!IsActive()); + return true; + } + } + + if(IsActive()) + { + if(e.m_Flags&IInput::FLAG_PRESS) + { + // special for popups + if(e.m_Key == KEY_RETURN || e.m_Key == KEY_KP_ENTER) + m_EnterPressed = true; + else if(e.m_Key == KEY_DELETE) + m_DeletePressed = true; + } + + if(m_NumInputEvents < MAX_INPUTEVENTS) + m_aInputEvents[m_NumInputEvents++] = e; + return true; + } + return false; +} + +void CMenus::OnStateChange(int NewState, int OldState) +{ + // reset active item + UI()->SetActiveItem(0); + + if(NewState == IClient::STATE_OFFLINE) + { + if(OldState >= IClient::STATE_ONLINE && NewState < IClient::STATE_QUITING) + m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); + m_Popup = POPUP_NONE; + if(Client()->ErrorString() && Client()->ErrorString()[0] != 0) + { + if(str_find(Client()->ErrorString(), "password")) + { + m_Popup = POPUP_PASSWORD; + UI()->SetHotItem(&g_Config.m_Password); + UI()->SetActiveItem(&g_Config.m_Password); + } + else + m_Popup = POPUP_DISCONNECTED; + } + } + else if(NewState == IClient::STATE_LOADING) + { + m_Popup = POPUP_CONNECTING; + m_DownloadLastCheckTime = time_get(); + m_DownloadLastCheckSize = 0; + m_DownloadSpeed = 0.0f; + //client_serverinfo_request(); + } + else if(NewState == IClient::STATE_CONNECTING) + m_Popup = POPUP_CONNECTING; + else if (NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK) + { + m_Popup = POPUP_NONE; + SetActive(false); + } +} + +extern "C" void font_debug_render(); + +void CMenus::OnRender() +{ + /* + // text rendering test stuff + render_background(); + + CTextCursor cursor; + TextRender()->SetCursor(&cursor, 10, 10, 20, TEXTFLAG_RENDER); + TextRender()->TextEx(&cursor, "ようこそ - ガイド", -1); + + 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); + + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + CUIRect Screen = *UI()->Screen(); + 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; + m_EnterPressed = false; + m_DeletePressed = false; + 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); + + ms_ColorTabbarInactiveOutgame = vec4(0,0,0,0.25f); + ms_ColorTabbarActiveOutgame = vec4(0,0,0,0.5f); + + float ColorIngameScaleI = 0.5f; + float ColorIngameAcaleA = 0.2f; + ms_ColorTabbarInactiveIngame = vec4( + ms_GuiColor.r*ColorIngameScaleI, + 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) + { + if(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1; + if(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2; + if(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4; + } + +#if defined(__ANDROID__) + static int ButtonsOneFrameDelay = 0; // For Android touch input + + UI()->Update(mx,my,mx*3.0f,my*3.0f,ButtonsOneFrameDelay); + ButtonsOneFrameDelay = Buttons; +#else + UI()->Update(mx,my,mx*3.0f,my*3.0f,Buttons); +#endif + + // render + if(Client()->State() != IClient::STATE_DEMOPLAYBACK) + Render(); + + // render cursor + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1,1,1,1); + IGraphics::CQuadItem QuadItem(mx, my, 24, 24); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + // render debug information + if(g_Config.m_Debug) + { + CUIRect Screen = *UI()->Screen(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%p %p %p", UI()->HotItem(), UI()->ActiveItem(), UI()->LastActiveItem()); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, 10, 10, 10, TEXTFLAG_RENDER); + TextRender()->TextEx(&Cursor, aBuf, -1); + } + + m_EscapePressed = false; + m_EnterPressed = false; + m_DeletePressed = false; + m_NumInputEvents = 0; +} + +static int gs_TextureBlob = -1; + +void CMenus::RenderBackground() +{ + //Graphics()->Clear(1,1,1); + //render_sunrays(0,0); + if(gs_TextureBlob == -1) + gs_TextureBlob = Graphics()->LoadTexture("blob.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + + + float sw = 300*Graphics()->ScreenAspect(); + float sh = 300; + Graphics()->MapScreen(0, 0, sw, sh); + + // render background color + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + //vec4 bottom(gui_color.r*0.3f, gui_color.g*0.3f, gui_color.b*0.3f, 1.0f); + //vec4 bottom(0, 0, 0, 1.0f); + vec4 Bottom(ms_GuiColor.r, ms_GuiColor.g, ms_GuiColor.b, 1.0f); + vec4 Top(ms_GuiColor.r, ms_GuiColor.g, ms_GuiColor.b, 1.0f); + IGraphics::CColorVertex Array[4] = { + IGraphics::CColorVertex(0, Top.r, Top.g, Top.b, Top.a), + IGraphics::CColorVertex(1, Top.r, Top.g, Top.b, Top.a), + IGraphics::CColorVertex(2, Bottom.r, Bottom.g, Bottom.b, Bottom.a), + IGraphics::CColorVertex(3, Bottom.r, Bottom.g, Bottom.b, Bottom.a)}; + Graphics()->SetColorVertex(Array, 4); + IGraphics::CQuadItem QuadItem(0, 0, sw, sh); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + // render the tiles + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + float Size = 15.0f; + float OffsetTime = fmod(Client()->LocalTime()*0.15f, 2.0f); + for(int y = -2; y < (int)(sw/Size); y++) + for(int x = -2; x < (int)(sh/Size); x++) + { + Graphics()->SetColor(0,0,0,0.045f); + IGraphics::CQuadItem QuadItem((x-OffsetTime)*Size*2+(y&1)*Size, (y+OffsetTime)*Size, Size, Size); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + Graphics()->QuadsEnd(); + + // render border fade + Graphics()->TextureSet(gs_TextureBlob); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.5f); + QuadItem = IGraphics::CQuadItem(-100, -100, sw+200, sh+200); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + // restore screen + {CUIRect Screen = *UI()->Screen(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);} +} + +int CMenus::DoButton_CheckBox_DontCare(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + switch(Checked) + { + case 0: + return DoButton_CheckBox_Common(pID, pText, "", pRect); + case 1: + return DoButton_CheckBox_Common(pID, pText, "X", pRect); + case 2: + return DoButton_CheckBox_Common(pID, pText, "O", pRect); + default: + return DoButton_CheckBox_Common(pID, pText, "", pRect); + } +} + +void CMenus::RenderUpdating(const char *pCaption, int current, int total) +{ + // make sure that we don't render for each little thing we load + // because that will slow down loading if we have vsync + static int64 LastLoadRender = 0; + 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(); + Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); + + RenderBackground(); + + float w = 700; + float h = 200; + float x = Screen.w/2-w/2; + float y = Screen.h/2-h/2; + + Graphics()->BlendNormal(); + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.50f); + RenderTools()->DrawRoundRect(0, y, Screen.w, h, 0.0f); + Graphics()->QuadsEnd(); + + CUIRect r; + r.x = x; + r.y = y+20; + r.w = w; + r.h = h; + UI()->DoLabel(&r, Localize(pCaption), 32.0f, 0, -1); + + if (total>0) + { + float Percent = current/(float)total; + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.15f,0.15f,0.15f,0.75f); + RenderTools()->DrawRoundRect(x+40, y+h-75, w-80, 30, 5.0f); + Graphics()->SetColor(1,1,1,0.75f); + RenderTools()->DrawRoundRect(x+45, y+h-70, (w-85)*Percent, 20, 5.0f); + Graphics()->QuadsEnd(); + } + + Graphics()->Swap(); +} diff --git a/src/game/client/components/menus.h b/src/game/client/components/menus.h new file mode 100644 index 0000000..316942f --- /dev/null +++ b/src/game/client/components/menus.h @@ -0,0 +1,389 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_MENUS_H +#define GAME_CLIENT_COMPONENTS_MENUS_H + +#include <base/vmath.h> +#include <base/tl/sorted_array.h> + +#include <engine/demo.h> +#include <engine/friends.h> + +#include <game/voting.h> +#include <game/client/component.h> +#include <game/client/ui.h> + + +// compnent to fetch keypresses, override all other input +class CMenusKeyBinder : public CComponent +{ +public: + bool m_TakeKey; + bool m_GotKey; + IInput::CEvent m_Key; + CMenusKeyBinder(); + virtual bool OnInput(IInput::CEvent Event); +}; + +class CMenus : public CComponent +{ + static vec4 ms_GuiColor; + static vec4 ms_ColorTabbarInactiveOutgame; + static vec4 ms_ColorTabbarActiveOutgame; + static vec4 ms_ColorTabbarInactiveIngame; + static vec4 ms_ColorTabbarActiveIngame; + static vec4 ms_ColorTabbarInactive; + static vec4 ms_ColorTabbarActive; + + vec4 ButtonColorMul(const void *pID); + + + int DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + int DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Checked, const CUIRect *pRect, int Corners); + int DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active); + int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + int DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners); + + int DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect); + int DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + int DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + + /*static void ui_draw_menu_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); + static void ui_draw_keyselect_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); + static void ui_draw_menu_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); + static void ui_draw_settings_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); + */ + + int DoButton_Icon(int ImageId, int SpriteId, const CUIRect *pRect); + int DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + + //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); + */ + int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden=false, int Corners=CUI::CORNER_ALL, const char *pEmptyText = ""); + //static int ui_do_edit_box(void *id, const CUIRect *rect, char *str, unsigned str_size, float font_size, bool hidden=false); + + float DoScrollbarV(const void *pID, const CUIRect *pRect, float Current); + float DoScrollbarH(const void *pID, const CUIRect *pRect, float Current); + void DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + int DoKeyReader(void *pID, const CUIRect *pRect, int Key); + + //static int ui_do_key_reader(void *id, const CUIRect *rect, int key); + void UiDoGetButtons(int Start, int Stop, CUIRect View); + + struct CListboxItem + { + int m_Visible; + int m_Selected; + 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); + 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); + + int m_GamePage; + int m_Popup; + int m_ActivePage; + 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 + 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_ListitemAdditionalHeight; + static float ms_FontmodHeight; + + // for settings + bool m_NeedRestartSkins; + bool m_NeedRestartGraphics; + bool m_NeedRestartSound; + bool m_NeedRestartUpdate; + bool m_NeedSendinfo; + bool m_NeedSendDummyinfo; + int m_SettingPlayerPage; + + // + bool m_EscapePressed; + bool m_EnterPressed; + bool m_DeletePressed; + + // for map download popup + int64 m_DownloadLastCheckTime; + int m_DownloadLastCheckSize; + float m_DownloadSpeed; + + // for call vote + int m_CallvoteSelectedOption; + int m_CallvoteSelectedPlayer; + char m_aCallvoteReason[VOTE_REASON_LENGTH]; + char m_aFilterString[25]; + + // demo + struct CDemoItem + { + char m_aFilename[128]; + char m_aName[128]; + bool m_IsDir; + int m_StorageType; + time_t m_Date; + + bool m_InfosLoaded; + bool m_Valid; + CDemoHeader m_Info; + + bool operator<(const CDemoItem &Other) + { + if (g_Config.m_BrDemoSort) + { + if (g_Config.m_BrDemoSortOrder) + { + return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : + m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : + m_Date < Other.m_Date; + } + else + { + return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : + m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : + m_Date > Other.m_Date; + } + } + else + { + if (g_Config.m_BrDemoSortOrder) + { + 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; + } + else + { + 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, time_t Date, int IsDir, int StorageType, void *pUser); + + // friends + struct CFriendItem + { + const CFriendInfo *m_pFriendInfo; + int m_NumFound; + + bool operator<(const CFriendItem &Other) + { + if(m_NumFound && !Other.m_NumFound) + return true; + else if(!m_NumFound && Other.m_NumFound) + return false; + else + { + int Result = str_comp(m_pFriendInfo->m_aName, Other.m_pFriendInfo->m_aName); + if(Result) + return Result < 0; + else + return str_comp(m_pFriendInfo->m_aClan, Other.m_pFriendInfo->m_aClan) < 0; + } + } + }; + + sorted_array<CFriendItem> m_lFriends; + int m_FriendlistSelectedIndex; + + void FriendlistOnUpdate(); + + // 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); + void RenderServerInfo(CUIRect MainView); + void RenderServerControl(CUIRect MainView); + void RenderServerControlKick(CUIRect MainView, bool FilterSpectators); + void RenderServerControlServer(CUIRect MainView); + + // found in menus_browser.cpp + int m_SelectedIndex; + int m_DoubleClickIndex; + int m_ScrollOffset; + void RenderServerbrowserServerList(CUIRect View); + void RenderServerbrowserServerDetail(CUIRect View); + void RenderServerbrowserFilters(CUIRect View); + void RenderServerbrowserFriends(CUIRect View); + void RenderServerbrowser(CUIRect MainView); + static void ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + 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); + void RenderSettingsPlayer(CUIRect MainView); + void RenderSettingsDummyPlayer(CUIRect MainView); + void RenderSettingsTee(CUIRect MainView); + void RenderSettingsControls(CUIRect MainView); + void RenderSettingsGraphics(CUIRect MainView); + void RenderSettingsSound(CUIRect MainView); + void RenderSettings(CUIRect MainView); + + void SetActive(bool Active); +public: + void RenderBackground(); + + void UseMouseButtons(bool Use) { m_UseMouseButtons = Use; } + + static CMenusKeyBinder m_Binder; + + CMenus(); + + void RenderLoading(); + void RenderUpdating(const char *pCaption, int current=0, int total=0); + + bool IsActive() const { return m_MenuActive; } + + virtual void OnInit(); + + virtual void OnStateChange(int NewState, int OldState); + virtual void OnReset(); + virtual void OnRender(); + virtual bool OnInput(IInput::CEvent Event); + virtual bool OnMouseMove(float x, float y); + + enum + { + PAGE_NEWS=1, + PAGE_GAME, + PAGE_PLAYERS, + PAGE_SERVER_INFO, + PAGE_CALLVOTE, + PAGE_INTERNET, + PAGE_LAN, + PAGE_FAVORITES, + PAGE_DDNET, + PAGE_DEMOS, + PAGE_SETTINGS, + PAGE_SYSTEM, + PAGE_DDRace, + PAGE_BROWSER, + PAGE_GHOST + }; + + // DDRace + int64 _my_rtime; // reconnect time + int DoButton_CheckBox_DontCare(const void *pID, const char *pText, int Checked, const CUIRect *pRect); + sorted_array<CDemoItem> m_lDemos; + void DemolistPopulate(); + bool m_Dummy; + + // Ghost + struct CGhostItem + { + char m_aFilename[256]; + char m_aPlayer[MAX_NAME_LENGTH]; + + float m_Time; + + bool m_Active; + int m_ID; + + bool operator<(const CGhostItem &Other) { return m_Time < Other.m_Time; } + bool operator==(const CGhostItem &Other) { return m_ID == Other.m_ID; } + }; + + sorted_array<CGhostItem> m_lGhosts; + CGhostItem *m_OwnGhost; + int m_DDRacePage; + void GhostlistPopulate(); + void setPopup(int Popup) { m_Popup = Popup; } + + int m_DemoPlayerState; + char m_aDemoPlayerPopupHint[256]; + + enum + { + POPUP_NONE=0, + POPUP_FIRST_LAUNCH, + POPUP_CONNECTING, + POPUP_MESSAGE, + POPUP_DISCONNECTED, + POPUP_PURE, + POPUP_LANGUAGE, + POPUP_COUNTRY, + POPUP_DELETE_DEMO, + POPUP_RENAME_DEMO, + POPUP_REMOVE_FRIEND, + POPUP_SOUNDERROR, + POPUP_PASSWORD, + POPUP_QUIT, + POPUP_DISCONNECT, + + // demo player states + DEMOPLAYER_NONE=0, + DEMOPLAYER_SLICE_SAVE, + }; + +private: + + static int GhostlistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser); + + // found in menus_ingame.cpp + void RenderInGameDDRace(CUIRect MainView); + void RenderGhost(CUIRect MainView); + void RenderInGameBrowser(CUIRect MainView); + + // found in menus_settings.cpp + void RenderSettingsDDRace(CUIRect MainView); + void RenderSettingsHUD(CUIRect MainView); +}; +#endif diff --git a/src/game/client/components/menus_browser.cpp b/src/game/client/components/menus_browser.cpp new file mode 100644 index 0000000..8601fd8 --- /dev/null +++ b/src/game/client/components/menus_browser.cpp @@ -0,0 +1,1391 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/config.h> +#include <engine/friends.h> +#include <engine/graphics.h> +#include <engine/keys.h> +#include <engine/serverbrowser.h> +#include <engine/textrender.h> +#include <engine/updater.h> +#include <engine/shared/config.h> + +#include <game/generated/client_data.h> +#include <game/generated/protocol.h> + +#include <game/localization.h> +#include <game/version.h> +#include <game/client/render.h> +#include <game/client/ui.h> +#include <game/client/components/countryflags.h> +#include <game/client/components/console.h> + +#include "menus.h" + + +void CMenus::RenderServerbrowserServerList(CUIRect View) +{ + CUIRect Headers; + CUIRect Status; + + View.HSplitTop(ms_ListheaderHeight, &Headers, &View); + View.HSplitBottom(28.0f, &View, &Status); + + // split of the scrollbar + RenderTools()->DrawUIRect(&Headers, vec4(1,1,1,0.25f), CUI::CORNER_T, 5.0f); + Headers.VSplitRight(20.0f, &Headers, 0); + + struct CColumn + { + int m_ID; + int m_Sort; + CLocConstString m_Caption; + int m_Direction; + float m_Width; + int m_Flags; + CUIRect m_Rect; + CUIRect m_Spacer; + }; + + enum + { + FIXED=1, + SPACER=2, + + COL_FLAG_LOCK=0, + COL_FLAG_FAV, + COL_NAME, + COL_GAMETYPE, + COL_MAP, + COL_PLAYERS, + COL_PING, + COL_VERSION, + }; + + static CColumn s_aCols[] = { + {-1, -1, " ", -1, 2.0f, 0, {0}, {0}}, + {COL_FLAG_LOCK, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_FLAG_FAV, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_NAME, IServerBrowser::SORT_NAME, "Name", 0, 50.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 + (Headers.w - 480) / 8, 0, {0}, {0}}, + {COL_PLAYERS, IServerBrowser::SORT_NUMPLAYERS, "Players", 1, 60.0f, 0, {0}, {0}}, + {-1, -1, " ", 1, 10.0f, 0, {0}, {0}}, + {COL_PING, IServerBrowser::SORT_PING, "Ping", 1, 40.0f, FIXED, {0}, {0}}, +#if defined(__ANDROID__) + {-1, -1, " ", 1, 50.0f, 0, {0}, {0}}, // Scrollbar +#endif + }; + // This is just for scripts/update_localization.py to work correctly (all other strings are already Localize()'d somewhere else). Don't remove! + // Localize("Type"); + + int NumCols = sizeof(s_aCols)/sizeof(CColumn); + + // do layout + for(int i = 0; i < NumCols; i++) + { + if(s_aCols[i].m_Direction == -1) + { + Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); + + if(i+1 < NumCols) + { + //Cols[i].flags |= SPACER; + Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); + } + } + } + + for(int i = NumCols-1; i >= 0; i--) + { + if(s_aCols[i].m_Direction == 1) + { + Headers.VSplitRight(s_aCols[i].m_Width, &Headers, &s_aCols[i].m_Rect); + Headers.VSplitRight(2, &Headers, &s_aCols[i].m_Spacer); + } + } + + for(int i = 0; i < NumCols; i++) + { + if(s_aCols[i].m_Direction == 0) + s_aCols[i].m_Rect = Headers; + } + + // do headers + for(int i = 0; i < NumCols; i++) + { + if(DoButton_GridHeader(s_aCols[i].m_Caption, s_aCols[i].m_Caption, g_Config.m_BrSort == s_aCols[i].m_Sort, &s_aCols[i].m_Rect)) + { + if(s_aCols[i].m_Sort != -1) + { + if(g_Config.m_BrSort == s_aCols[i].m_Sort) + g_Config.m_BrSortOrder ^= 1; + else + g_Config.m_BrSortOrder = 0; + g_Config.m_BrSort = s_aCols[i].m_Sort; + } + } + } + + RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.15f), 0, 0); + + CUIRect Scroll; +#if defined(__ANDROID__) + View.VSplitRight(50, &View, &Scroll); +#else + View.VSplitRight(15, &View, &Scroll); +#endif + + int NumServers = ServerBrowser()->NumSortedServers(); + + // display important messages in the middle of the screen so no + // users misses it + { + CUIRect MsgBox = View; + MsgBox.y += View.h/3; + + if(m_ActivePage == PAGE_INTERNET && ServerBrowser()->IsRefreshingMasters()) + UI()->DoLabelScaled(&MsgBox, Localize("Refreshing master servers"), 16.0f, 0); + else if(!ServerBrowser()->NumServers()) + UI()->DoLabelScaled(&MsgBox, Localize("No servers found"), 16.0f, 0); + else if(ServerBrowser()->NumServers() && !NumServers) + UI()->DoLabelScaled(&MsgBox, Localize("No servers match your filter criteria"), 16.0f, 0); + } + + int Num = (int)(View.h/s_aCols[0].m_Rect.h) + 1; + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + int ScrollNum = NumServers-Num+1; + if(ScrollNum > 0) + { + if(m_ScrollOffset >= 0) + { + s_ScrollValue = (float)(m_ScrollOffset)/ScrollNum; + m_ScrollOffset = -1; + } + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) + s_ScrollValue -= 3.0f/ScrollNum; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) + s_ScrollValue += 3.0f/ScrollNum; + } + else + ScrollNum = 0; + + if(Input()->KeyDown(KEY_TAB) && m_pClient->m_pGameConsole->IsClosed()) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + g_Config.m_UiToolboxPage = (g_Config.m_UiToolboxPage + 3 - 1) % 3; + else + g_Config.m_UiToolboxPage = (g_Config.m_UiToolboxPage + 3 + 1) % 3; + } + if(m_SelectedIndex > -1) + { + for(int i = 0; i < m_NumInputEvents; i++) + { + int NewIndex = -1; + if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + { + if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = m_SelectedIndex + 1; + if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = m_SelectedIndex - 1; + } + 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; + int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; + if(Scroll) + { + if(Scroll < 0) + { + int NumScrolls = (View.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + } + else + { + int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(View.y+View.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + } + } + + 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; + + // set clipping + UI()->ClipEnable(&View); + + CUIRect OriginalView = View; + View.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + + int NewSelected = -1; +#if defined(__ANDROID__) + int DoubleClicked = 0; +#endif + int NumPlayers = 0; + + m_SelectedIndex = -1; + + // reset friend counter + for(int i = 0; i < m_lFriends.size(); m_lFriends[i++].m_NumFound = 0); + + for (int i = 0; i < NumServers; i++) + { + int ItemIndex = i; + const CServerInfo *pItem = ServerBrowser()->SortedGet(ItemIndex); + NumPlayers += g_Config.m_BrFilterSpectators ? pItem->m_NumPlayers : pItem->m_NumClients; + CUIRect Row; + CUIRect SelectHitBox; + + int Selected = str_comp(pItem->m_aAddress, g_Config.m_UiServerAddress) == 0; //selected_index==ItemIndex; + + View.HSplitTop(ms_ListheaderHeight, &Row, &View); + SelectHitBox = Row; + + if(Selected) + m_SelectedIndex = i; + + // update friend counter + if(pItem->m_FriendState != IFriends::FRIEND_NO) + { + for(int j = 0; j < pItem->m_NumClients; ++j) + { + if(pItem->m_aClients[j].m_FriendState != IFriends::FRIEND_NO) + { + unsigned NameHash = str_quickhash(pItem->m_aClients[j].m_aName); + unsigned ClanHash = str_quickhash(pItem->m_aClients[j].m_aClan); + for(int f = 0; f < m_lFriends.size(); ++f) + { + if(((g_Config.m_ClFriendsIgnoreClan && m_lFriends[f].m_pFriendInfo->m_aName[0]) || ClanHash == m_lFriends[f].m_pFriendInfo->m_ClanHash) && + (!m_lFriends[f].m_pFriendInfo->m_aName[0] || NameHash == m_lFriends[f].m_pFriendInfo->m_NameHash)) + { + m_lFriends[f].m_NumFound++; + if(m_lFriends[f].m_pFriendInfo->m_aName[0]) + break; + } + } + } + } + } + + // make sure that only those in view can be selected + if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + { + if(Selected) + { + CUIRect r = Row; + r.Margin(1.5f, &r); + RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + } + + // clip the selection + if(SelectHitBox.y < OriginalView.y) // top + { + SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.y = OriginalView.y; + } + else if(SelectHitBox.y+SelectHitBox.h > OriginalView.y+OriginalView.h) // bottom + SelectHitBox.h = OriginalView.y+OriginalView.h-SelectHitBox.y; + + if(UI()->DoButtonLogic(pItem, "", Selected, &SelectHitBox)) + { + NewSelected = ItemIndex; +#if defined(__ANDROID__) + if(NewSelected == m_DoubleClickIndex) + DoubleClicked = 1; +#endif + m_DoubleClickIndex = NewSelected; + } + } + else + { + // reset active item, if not visible + if(UI()->ActiveItem() == pItem) + UI()->SetActiveItem(0); + + // don't render invisible items + continue; + } + + for(int c = 0; c < NumCols; c++) + { + CUIRect Button; + char aTemp[64]; + Button.x = s_aCols[c].m_Rect.x; + Button.y = Row.y; + Button.h = Row.h; + Button.w = s_aCols[c].m_Rect.w; + + int ID = s_aCols[c].m_ID; + + if(ID == COL_FLAG_LOCK) + { + if(pItem->m_Flags & SERVER_FLAG_PASSWORD) + DoButton_Icon(IMAGE_BROWSEICONS, SPRITE_BROWSE_LOCK, &Button); + } + else if(ID == COL_FLAG_FAV) + { + if(pItem->m_Favorite) + DoButton_Icon(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART, &Button); + } + else if(ID == COL_NAME) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_SERVERNAME)) + { + // highlight the parts that matches + const char *pStr = str_find_nocase(pItem->m_aName, g_Config.m_BrFilterString); + if(pStr) + { + TextRender()->TextEx(&Cursor, pItem->m_aName, (int)(pStr-pItem->m_aName)); + TextRender()->TextColor(0.4f,0.4f,1.0f,1); + TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); + TextRender()->TextColor(1,1,1,1); + TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); + } + else + TextRender()->TextEx(&Cursor, pItem->m_aName, -1); + } + else + TextRender()->TextEx(&Cursor, pItem->m_aName, -1); + } + else if(ID == COL_MAP) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_MAPNAME)) + { + // highlight the parts that matches + const char *pStr = str_find_nocase(pItem->m_aMap, g_Config.m_BrFilterString); + if(pStr) + { + TextRender()->TextEx(&Cursor, pItem->m_aMap, (int)(pStr-pItem->m_aMap)); + TextRender()->TextColor(0.4f,0.4f,1.0f,1); + TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); + TextRender()->TextColor(1,1,1,1); + TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); + } + else + TextRender()->TextEx(&Cursor, pItem->m_aMap, -1); + } + else + TextRender()->TextEx(&Cursor, pItem->m_aMap, -1); + } + else if(ID == COL_PLAYERS) + { + CUIRect Icon; + Button.VMargin(4.0f, &Button); + if(pItem->m_FriendState != IFriends::FRIEND_NO) + { + Button.VSplitLeft(Button.h, &Icon, &Button); + Icon.Margin(2.0f, &Icon); + DoButton_Icon(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART, &Icon); + } + + if(g_Config.m_BrFilterSpectators) + str_format(aTemp, sizeof(aTemp), "%i/%i", pItem->m_NumPlayers, pItem->m_MaxPlayers); + else + str_format(aTemp, sizeof(aTemp), "%i/%i", pItem->m_NumClients, pItem->m_MaxClients); + if(g_Config.m_BrFilterString[0] && (pItem->m_QuickSearchHit&IServerBrowser::QUICK_PLAYER)) + TextRender()->TextColor(0.4f,0.4f,1.0f,1); + UI()->DoLabelScaled(&Button, aTemp, 12.0f, 1); + TextRender()->TextColor(1,1,1,1); + } + else if(ID == COL_PING) + { + str_format(aTemp, sizeof(aTemp), "%i", pItem->m_Latency); + if (g_Config.m_UiColorizePing) + { + vec3 rgb = HslToRgb(vec3((300.0f - clamp(pItem->m_Latency, 0, 300)) / 1000.0f, 1.0f, 0.5f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + } + + UI()->DoLabelScaled(&Button, aTemp, 12.0f, 1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + else if(ID == COL_VERSION) + { + const char *pVersion = pItem->m_aVersion; + UI()->DoLabelScaled(&Button, pVersion, 12.0f, 1); + } + else if(ID == COL_GAMETYPE) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f*UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + if (g_Config.m_UiColorizeGametype) + { + vec3 hsl = vec3(1.0f, 1.0f, 1.0f); + + if (!str_comp(pItem->m_aGameType, "DM") + || !str_comp(pItem->m_aGameType, "TDM") + || !str_comp(pItem->m_aGameType, "CTF")) + hsl = vec3(0.33f, 1.0f, 0.75f); // Vanilla + else if (str_find_nocase(pItem->m_aGameType, "catch")) + hsl = vec3(0.17f, 1.0f, 0.75f); // Catch + else if (str_find_nocase(pItem->m_aGameType, "idm") + || str_find_nocase(pItem->m_aGameType, "itdm") + || str_find_nocase(pItem->m_aGameType, "ictf")) + hsl = vec3(0.00f, 1.0f, 0.75f); // Instagib + else if (str_find_nocase(pItem->m_aGameType, "fng")) + hsl = vec3(0.83f, 1.0f, 0.75f); // FNG + else if (IsDDNet(pItem)) + hsl = vec3(0.58f, 1.0f, 0.75f); // DDNet + else if (IsDDRace(pItem)) + hsl = vec3(0.75f, 1.0f, 0.75f); // DDRace + else if (IsRace(pItem)) + hsl = vec3(0.46f, 1.0f, 0.75f); // Race + + vec3 rgb = HslToRgb(hsl); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + TextRender()->TextEx(&Cursor, pItem->m_aGameType, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + else + TextRender()->TextEx(&Cursor, pItem->m_aGameType, -1); + } + } + } + + UI()->ClipDisable(); + + if(NewSelected != -1) + { + // select the new server + const CServerInfo *pItem = ServerBrowser()->SortedGet(NewSelected); + str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); +#if defined(__ANDROID__) + if(DoubleClicked) +#else + if(Input()->MouseDoubleClick()) +#endif + Client()->Connect(g_Config.m_UiServerAddress); + } + + RenderTools()->DrawUIRect(&Status, vec4(1,1,1,0.25f), CUI::CORNER_B, 5.0f); + Status.Margin(5.0f, &Status); + + CUIRect QuickSearch, QuickExclude, Button, Status2, Status3; + Status.VSplitRight(250.0f, &Status2, &Status3); + + Status2.VSplitMid(&QuickSearch, &QuickExclude); + QuickExclude.VSplitLeft(5.0f, 0, &QuickExclude); + // render quick search + { + const char *pLabel = "⚲"; + UI()->DoLabelScaled(&QuickSearch, pLabel, 12.0f, -1); + float w = TextRender()->TextWidth(0, 12.0f, pLabel, -1); + QuickSearch.VSplitLeft(w, 0, &QuickSearch); + QuickSearch.VSplitLeft(5.0f, 0, &QuickSearch); + QuickSearch.VSplitLeft(QuickSearch.w-15.0f, &QuickSearch, &Button); + static float Offset = 0.0f; + if(DoEditBox(&g_Config.m_BrFilterString, &QuickSearch, g_Config.m_BrFilterString, sizeof(g_Config.m_BrFilterString), 12.0f, &Offset, false, CUI::CORNER_L, Localize("Search"))) + Client()->ServerBrowserUpdate(); + } + + // clear button + { + static int s_ClearButton = 0; + RenderTools()->DrawUIRect(&Button, vec4(1,1,1,0.33f)*ButtonColorMul(&s_ClearButton), CUI::CORNER_R, 3.0f); + UI()->DoLabel(&Button, "×", Button.h*ms_FontmodHeight, 0); + if(UI()->DoButtonLogic(&s_ClearButton, "×", 0, &Button)) + { + g_Config.m_BrFilterString[0] = 0; + UI()->SetActiveItem(&g_Config.m_BrFilterString); + Client()->ServerBrowserUpdate(); + } + } + + // render quick exclude + { + const char *pLabel = Localize("✗"); + UI()->DoLabelScaled(&QuickExclude, pLabel, 12.0f, -1); + float w = TextRender()->TextWidth(0, 12.0f, pLabel, -1); + QuickExclude.VSplitLeft(w, 0, &QuickExclude); + QuickExclude.VSplitLeft(5.0f, 0, &QuickExclude); + QuickExclude.VSplitLeft(QuickExclude.w-15.0f, &QuickExclude, &Button); + static float Offset = 0.0f; + if(DoEditBox(&g_Config.m_BrExcludeString, &QuickExclude, g_Config.m_BrExcludeString, sizeof(g_Config.m_BrExcludeString), 12.0f, &Offset, false, CUI::CORNER_L, Localize("Exclude"))) + Client()->ServerBrowserUpdate(); + } + + // clear button + { + static int s_ClearButton = 0; + RenderTools()->DrawUIRect(&Button, vec4(1,1,1,0.33f)*ButtonColorMul(&s_ClearButton), CUI::CORNER_R, 3.0f); + UI()->DoLabel(&Button, "×", Button.h*ms_FontmodHeight, 0); + if(UI()->DoButtonLogic(&s_ClearButton, "×", 0, &Button)) + { + g_Config.m_BrExcludeString[0] = 0; + UI()->SetActiveItem(&g_Config.m_BrExcludeString); + Client()->ServerBrowserUpdate(); + } + } + + // render status + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), Localize("%d of %d servers, %d players"), ServerBrowser()->NumSortedServers(), ServerBrowser()->NumServers(), NumPlayers); + Status3.VSplitRight(TextRender()->TextWidth(0, 14.0f, aBuf, -1), 0, &Status3); + UI()->DoLabelScaled(&Status3, aBuf, 14.0f, -1); +} + +void CMenus::RenderServerbrowserFilters(CUIRect View) +{ + CUIRect ServerFilter = View, FilterHeader; + const float FontSize = 12.0f; + ServerFilter.HSplitBottom(0.0f, &ServerFilter, 0); + + // server filter + ServerFilter.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFilter); + RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); + RenderTools()->DrawUIRect(&ServerFilter, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); + UI()->DoLabelScaled(&FilterHeader, Localize("Server filter"), FontSize+2.0f, 0); + CUIRect Button, Button2; + + ServerFilter.VSplitLeft(5.0f, 0, &ServerFilter); + ServerFilter.Margin(3.0f, &ServerFilter); + ServerFilter.VMargin(5.0f, &ServerFilter); + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox(&g_Config.m_BrFilterEmpty, Localize("Has people playing"), g_Config.m_BrFilterEmpty, &Button)) + g_Config.m_BrFilterEmpty ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if(DoButton_CheckBox(&g_Config.m_BrFilterSpectators, Localize("Count players only"), g_Config.m_BrFilterSpectators, &Button)) + g_Config.m_BrFilterSpectators ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox(&g_Config.m_BrFilterFull, Localize("Server not full"), g_Config.m_BrFilterFull, &Button)) + g_Config.m_BrFilterFull ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox(&g_Config.m_BrFilterFriends, Localize("Show friends only"), g_Config.m_BrFilterFriends, &Button)) + g_Config.m_BrFilterFriends ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox(&g_Config.m_BrFilterPw, Localize("No password"), g_Config.m_BrFilterPw, &Button)) + g_Config.m_BrFilterPw ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox((char *)&g_Config.m_BrFilterCompatversion, Localize("Compatible version"), g_Config.m_BrFilterCompatversion, &Button)) + g_Config.m_BrFilterCompatversion ^= 1; + + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox((char *)&g_Config.m_BrFilterPure, Localize("Standard gametype"), g_Config.m_BrFilterPure, &Button)) + g_Config.m_BrFilterPure ^= 1; + + 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(20.0f, &Button, &ServerFilter); + if (DoButton_CheckBox((char *)&g_Config.m_BrFilterGametypeStrict, Localize("Strict gametype filter"), g_Config.m_BrFilterGametypeStrict, &Button)) + g_Config.m_BrFilterGametypeStrict ^= 1; + + ServerFilter.HSplitTop(5.0f, 0, &ServerFilter); + + ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); + UI()->DoLabelScaled(&Button, Localize("Game types:"), FontSize, -1); + Button.VSplitRight(60.0f, 0, &Button); + ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); + static float Offset = 0.0f; + if(DoEditBox(&g_Config.m_BrFilterGametype, &Button, g_Config.m_BrFilterGametype, sizeof(g_Config.m_BrFilterGametype), FontSize, &Offset)) + Client()->ServerBrowserUpdate(); + + { + 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; + DoEditBox(&g_Config.m_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset); + g_Config.m_BrFilterPing = clamp(str_toint(aBuf), 0, 999); + } + + // server address + 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); + 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(); + + // player country + { + CUIRect Rect; + ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); + ServerFilter.HSplitTop(26.0f, &Button, &ServerFilter); + Button.VSplitRight(60.0f, &Button, &Rect); + Button.HMargin(3.0f, &Button); + if(DoButton_CheckBox(&g_Config.m_BrFilterCountry, Localize("Player country:"), g_Config.m_BrFilterCountry, &Button)) + g_Config.m_BrFilterCountry ^= 1; + + float OldWidth = Rect.w; + Rect.w = Rect.h*2; + Rect.x += (OldWidth-Rect.w)/2.0f; + vec4 Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f); + m_pClient->m_pCountryFlags->Render(g_Config.m_BrFilterCountryIndex, &Color, Rect.x, Rect.y, Rect.w, Rect.h); + + if(g_Config.m_BrFilterCountry && UI()->DoButtonLogic(&g_Config.m_BrFilterCountryIndex, "", 0, &Rect)) + m_Popup = POPUP_COUNTRY; + } + + CUIRect ResetButton; + + //ServerFilter.HSplitBottom(5.0f, &ServerFilter, 0); + ServerFilter.HSplitBottom(ms_ButtonHeight-2.0f, &ServerFilter, &ResetButton); + + // ddnet country filters + if(g_Config.m_UiPage == PAGE_DDNET) + { + // add more space + ServerFilter.HSplitTop(10.0f, 0, &ServerFilter); + ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); + ServerFilter.HSplitTop(95.0f, &ServerFilter, 0); + + RenderTools()->DrawUIRect(&ServerFilter, ms_ColorTabbarActive, CUI::CORNER_B, 10.0f); + + Button.VSplitMid(&Button, &Button2); + + static int s_ActivePage = 0; + + static int s_CountriesButton = 0; + if(DoButton_MenuTab(&s_CountriesButton, Localize("Countries"), s_ActivePage == 0, &Button, CUI::CORNER_TL)) + { + s_ActivePage = 0; + } + + static int s_TypesButton = 0; + if(DoButton_MenuTab(&s_TypesButton, Localize("Types"), s_ActivePage == 1, &Button2, CUI::CORNER_TR)) + { + s_ActivePage = 1; + } + + if(s_ActivePage == 1) + { + int MaxTypes = ServerBrowser()->NumDDNetTypes(); + int NumTypes = ServerBrowser()->NumDDNetTypes(); + int PerLine = 3; + + if(MaxTypes <= 12) + ServerFilter.HSplitTop(8.0f, 0, &ServerFilter); + + const float TypesWidth = 40.0f; + const float TypesHeight = MaxTypes > 12 ? 15.0f : 20.0f; + + CUIRect TypesRect, Left, Right; + + static int s_aTypeButtons[64]; + + while(NumTypes > 0) + { + ServerFilter.HSplitTop(TypesHeight, &TypesRect, &ServerFilter); + TypesRect.VSplitMid(&Left, &Right); + + for(int i = 0; i < PerLine && NumTypes > 0; i++, NumTypes--) + { + int TypeIndex = MaxTypes - NumTypes; + const char *pName = ServerBrowser()->GetDDNetType(TypeIndex); + bool Active = !ServerBrowser()->DDNetFiltered(g_Config.m_BrFilterExcludeTypes, pName); + + vec2 Pos = vec2(TypesRect.x+TypesRect.w*((i+0.5f)/(float) PerLine), TypesRect.y); + + // correct pos + Pos.x -= TypesWidth / 2.0f; + + // create button logic + CUIRect Rect; + + Rect.x = Pos.x; + Rect.y = Pos.y; + Rect.w = TypesWidth; + Rect.h = TypesHeight; + + if (UI()->DoButtonLogic(&s_aTypeButtons[TypeIndex], "", 0, &Rect)) + { + // toggle flag filter + if (Active) + ServerBrowser()->DDNetFilterAdd(g_Config.m_BrFilterExcludeTypes, pName); + else + ServerBrowser()->DDNetFilterRem(g_Config.m_BrFilterExcludeTypes, pName); + + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + } + + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + + if (!Active) + Color.a = 0.2f; + TextRender()->TextColor(Color.r, Color.g, Color.b, Color.a); + UI()->DoLabelScaled(&Rect, pName, FontSize, 0); + TextRender()->TextColor(1.0, 1.0, 1.0, 1.0f); + } + } + } + else + { + ServerFilter.HSplitTop(17.0f, &ServerFilter, &ServerFilter); + + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + + const float FlagWidth = 40.0f; + const float FlagHeight = 20.0f; + + int MaxFlags = ServerBrowser()->NumDDNetCountries(); + int NumFlags = ServerBrowser()->NumDDNetCountries(); + int PerLine = MaxFlags > 9 ? 4 : 3; + + CUIRect FlagsRect; + + static int s_aFlagButtons[64]; + + while(NumFlags > 0) + { + ServerFilter.HSplitTop(30.0f, &FlagsRect, &ServerFilter); + + for(int i = 0; i < PerLine && NumFlags > 0; i++, NumFlags--) + { + int CountryIndex = MaxFlags - NumFlags; + const char *pName = ServerBrowser()->GetDDNetCountryName(CountryIndex); + bool Active = !ServerBrowser()->DDNetFiltered(g_Config.m_BrFilterExcludeCountries, pName); + int FlagID = ServerBrowser()->GetDDNetCountryFlag(CountryIndex); + + vec2 Pos = vec2(FlagsRect.x+FlagsRect.w*((i+0.5f)/(float) PerLine), FlagsRect.y); + + // correct pos + Pos.x -= FlagWidth / 2.0f; + Pos.y -= FlagHeight / 2.0f; + + // create button logic + CUIRect Rect; + + Rect.x = Pos.x; + Rect.y = Pos.y; + Rect.w = FlagWidth; + Rect.h = FlagHeight; + + if (UI()->DoButtonLogic(&s_aFlagButtons[CountryIndex], "", 0, &Rect)) + { + // toggle flag filter + if (Active) + ServerBrowser()->DDNetFilterAdd(g_Config.m_BrFilterExcludeCountries, pName); + else + ServerBrowser()->DDNetFilterRem(g_Config.m_BrFilterExcludeCountries, pName); + + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + } + + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + + if (!Active) + Color.a = 0.2f; + + m_pClient->m_pCountryFlags->Render(FlagID, &Color, Pos.x, Pos.y, FlagWidth, FlagHeight); + } + } + } + } + + static int s_ClearButton = 0; + if(DoButton_Menu(&s_ClearButton, Localize("Reset filter"), 0, &ResetButton)) + { + g_Config.m_BrFilterString[0] = 0; + g_Config.m_BrExcludeString[0] = 0; + g_Config.m_BrFilterFull = 0; + g_Config.m_BrFilterEmpty = 0; + g_Config.m_BrFilterSpectators = 0; + g_Config.m_BrFilterFriends = 0; + g_Config.m_BrFilterCountry = 0; + g_Config.m_BrFilterCountryIndex = -1; + g_Config.m_BrFilterPw = 0; + g_Config.m_BrFilterPing = 999; + g_Config.m_BrFilterGametype[0] = 0; + g_Config.m_BrFilterGametypeStrict = 0; + g_Config.m_BrFilterServerAddress[0] = 0; + g_Config.m_BrFilterPure = 0; + g_Config.m_BrFilterPureMap = 0; + g_Config.m_BrFilterCompatversion = 0; + g_Config.m_BrFilterExcludeCountries[0] = 0; + g_Config.m_BrFilterExcludeTypes[0] = 0; + Client()->ServerBrowserUpdate(); + } +} + +void CMenus::RenderServerbrowserServerDetail(CUIRect View) +{ + CUIRect ServerDetails = View; + CUIRect ServerScoreBoard, ServerHeader; + + const CServerInfo *pSelectedServer = ServerBrowser()->SortedGet(m_SelectedIndex); + + // split off a piece to use for scoreboard + ServerDetails.HSplitTop(90.0f, &ServerDetails, &ServerScoreBoard); + ServerDetails.HSplitBottom(2.5f, &ServerDetails, 0x0); + + // server details + CTextCursor Cursor; + const float FontSize = 12.0f; + ServerDetails.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerDetails); + RenderTools()->DrawUIRect(&ServerHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); + RenderTools()->DrawUIRect(&ServerDetails, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); + UI()->DoLabelScaled(&ServerHeader, Localize("Server details"), FontSize+2.0f, 0); + + if (pSelectedServer) + { + ServerDetails.VSplitLeft(5.0f, 0, &ServerDetails); + ServerDetails.Margin(3.0f, &ServerDetails); + + CUIRect Row; + static CLocConstString s_aLabels[] = { + "Version", // Localize - these strings are localized within CLocConstString + "Game type", + "Ping"}; + + CUIRect LeftColumn; + CUIRect RightColumn; + + // + { + CUIRect Button; + ServerDetails.HSplitBottom(20.0f, &ServerDetails, &Button); + Button.VSplitLeft(5.0f, 0, &Button); + static int s_AddFavButton = 0; + if(DoButton_CheckBox(&s_AddFavButton, Localize("Favorite"), pSelectedServer->m_Favorite, &Button)) + { + if(pSelectedServer->m_Favorite) + ServerBrowser()->RemoveFavorite(pSelectedServer->m_NetAddr); + else + ServerBrowser()->AddFavorite(pSelectedServer->m_NetAddr); + } + } + + ServerDetails.VSplitLeft(5.0f, 0x0, &ServerDetails); + ServerDetails.VSplitLeft(80.0f, &LeftColumn, &RightColumn); + + for (unsigned int i = 0; i < sizeof(s_aLabels) / sizeof(s_aLabels[0]); i++) + { + LeftColumn.HSplitTop(15.0f, &Row, &LeftColumn); + UI()->DoLabelScaled(&Row, s_aLabels[i], FontSize, -1); + } + + RightColumn.HSplitTop(15.0f, &Row, &RightColumn); + TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Row.w; + TextRender()->TextEx(&Cursor, pSelectedServer->m_aVersion, -1); + + RightColumn.HSplitTop(15.0f, &Row, &RightColumn); + TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Row.w; + TextRender()->TextEx(&Cursor, pSelectedServer->m_aGameType, -1); + + char aTemp[16]; + str_format(aTemp, sizeof(aTemp), "%d", pSelectedServer->m_Latency); + RightColumn.HSplitTop(15.0f, &Row, &RightColumn); + TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Row.w; + TextRender()->TextEx(&Cursor, aTemp, -1); + + } + + // server scoreboard + //ServerScoreBoard.HSplitBottom(20.0f, &ServerScoreBoard, 0x0); + + if(pSelectedServer) + { + static int s_VoteList = 0; + static float s_ScrollValue = 0; + UiDoListboxStart(&s_VoteList, &ServerScoreBoard, 26.0f, Localize("Scoreboard"), "", pSelectedServer->m_NumClients, 1, -1, s_ScrollValue); + + for (int i = 0; i < pSelectedServer->m_NumClients; i++) + { + CListboxItem Item = UiDoListboxNextItem(&i); + + if(!Item.m_Visible) + continue; + + CUIRect Name, Clan, Score, Flag; + Item.m_Rect.HSplitTop(25.0f, &Name, &Item.m_Rect); + if(UI()->DoButtonLogic(&pSelectedServer->m_aClients[i], "", 0, &Name)) + { + if(pSelectedServer->m_aClients[i].m_FriendState == IFriends::FRIEND_PLAYER) + m_pClient->Friends()->RemoveFriend(pSelectedServer->m_aClients[i].m_aName, pSelectedServer->m_aClients[i].m_aClan); + else + m_pClient->Friends()->AddFriend(pSelectedServer->m_aClients[i].m_aName, pSelectedServer->m_aClients[i].m_aClan); + FriendlistOnUpdate(); + Client()->ServerBrowserUpdate(); + } + + vec4 Colour = pSelectedServer->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? vec4(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) : + vec4(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f); + RenderTools()->DrawUIRect(&Name, Colour, CUI::CORNER_ALL, 4.0f); + Name.VSplitLeft(5.0f, 0, &Name); + Name.VSplitLeft(34.0f, &Score, &Name); + Name.VSplitRight(34.0f, &Name, &Flag); + Flag.HMargin(4.0f, &Flag); + Name.HSplitTop(11.0f, &Name, &Clan); + + // score + char aTemp[16]; + + if(!pSelectedServer->m_aClients[i].m_Player) + str_copy(aTemp, "SPEC", sizeof(aTemp)); + else if(IsRace(pSelectedServer)) + { + if(pSelectedServer->m_aClients[i].m_Score == -9999 || pSelectedServer->m_aClients[i].m_Score == 0) + aTemp[0] = 0; + else + { + int Time = abs(pSelectedServer->m_aClients[i].m_Score); + str_format(aTemp, sizeof(aTemp), "%02d:%02d", Time/60, Time%60); + } + } + else + str_format(aTemp, sizeof(aTemp), "%d", pSelectedServer->m_aClients[i].m_Score); + + TextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + 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; + const char *pName = pSelectedServer->m_aClients[i].m_aName; + if(g_Config.m_BrFilterString[0]) + { + // highlight the parts that matches + const char *s = str_find_nocase(pName, g_Config.m_BrFilterString); + if(s) + { + TextRender()->TextEx(&Cursor, pName, (int)(s-pName)); + TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); + TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); + } + else + TextRender()->TextEx(&Cursor, pName, -1); + } + else + TextRender()->TextEx(&Cursor, pName, -1); + + // clan + TextRender()->SetCursor(&Cursor, Clan.x, Clan.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Clan.w; + const char *pClan = pSelectedServer->m_aClients[i].m_aClan; + if(g_Config.m_BrFilterString[0]) + { + // highlight the parts that matches + const char *s = str_find_nocase(pClan, g_Config.m_BrFilterString); + if(s) + { + TextRender()->TextEx(&Cursor, pClan, (int)(s-pClan)); + TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); + TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); + } + else + TextRender()->TextEx(&Cursor, pClan, -1); + } + else + TextRender()->TextEx(&Cursor, pClan, -1); + + // flag + vec4 Color(1.0f, 1.0f, 1.0f, 0.5f); + m_pClient->m_pCountryFlags->Render(pSelectedServer->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h); + } + + UiDoListboxEnd(&s_ScrollValue, 0); + } +} + +void CMenus::FriendlistOnUpdate() +{ + m_lFriends.clear(); + for(int i = 0; i < m_pClient->Friends()->NumFriends(); ++i) + { + CFriendItem Item; + Item.m_pFriendInfo = m_pClient->Friends()->GetFriend(i); + Item.m_NumFound = 0; + m_lFriends.add_unsorted(Item); + } + m_lFriends.sort_range(); +} + +void CMenus::RenderServerbrowserFriends(CUIRect View) +{ + static int s_Inited = 0; + if(!s_Inited) + { + FriendlistOnUpdate(); + s_Inited = 1; + } + + CUIRect ServerFriends = View, FilterHeader; + const float FontSize = 10.0f; + + // header + ServerFriends.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFriends); + RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); + RenderTools()->DrawUIRect(&ServerFriends, vec4(0,0,0,0.15f), 0, 4.0f); + UI()->DoLabelScaled(&FilterHeader, Localize("Friends"), FontSize+4.0f, 0); + CUIRect Button, List; + + ServerFriends.Margin(3.0f, &ServerFriends); + ServerFriends.VMargin(3.0f, &ServerFriends); + ServerFriends.HSplitBottom(100.0f, &List, &ServerFriends); + + // friends list(remove friend) + static float s_ScrollValue = 0; + if(m_FriendlistSelectedIndex >= m_lFriends.size()) + m_FriendlistSelectedIndex = m_lFriends.size()-1; +#if defined(__ANDROID__) + UiDoListboxStart(&m_lFriends, &List, 50.0f, "", "", m_lFriends.size(), 1, m_FriendlistSelectedIndex, s_ScrollValue); +#else + UiDoListboxStart(&m_lFriends, &List, 30.0f, "", "", m_lFriends.size(), 1, m_FriendlistSelectedIndex, s_ScrollValue); +#endif + + m_lFriends.sort_range(); + for(int i = 0; i < m_lFriends.size(); ++i) + { + CListboxItem Item = UiDoListboxNextItem(&m_lFriends[i]); + + if(Item.m_Visible) + { + Item.m_Rect.Margin(1.5f, &Item.m_Rect); + CUIRect OnState; + Item.m_Rect.VSplitRight(30.0f, &Item.m_Rect, &OnState); + RenderTools()->DrawUIRect(&Item.m_Rect, vec4(1.0f, 1.0f, 1.0f, 0.1f), CUI::CORNER_L, 4.0f); + + Item.m_Rect.VMargin(2.5f, &Item.m_Rect); + Item.m_Rect.HSplitTop(12.0f, &Item.m_Rect, &Button); + UI()->DoLabelScaled(&Item.m_Rect, m_lFriends[i].m_pFriendInfo->m_aName, FontSize, -1); + UI()->DoLabelScaled(&Button, m_lFriends[i].m_pFriendInfo->m_aClan, FontSize, -1); + + RenderTools()->DrawUIRect(&OnState, m_lFriends[i].m_NumFound ? vec4(0.0f, 1.0f, 0.0f, 0.25f) : vec4(1.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_R, 4.0f); + OnState.HMargin((OnState.h-FontSize)/3, &OnState); + OnState.VMargin(5.0f, &OnState); + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%i", m_lFriends[i].m_NumFound); + UI()->DoLabelScaled(&OnState, aBuf, FontSize+2, 1); + } + } + + bool Activated = false; + m_FriendlistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated); + + // activate found server with friend + if(Activated && !m_EnterPressed && m_lFriends[m_FriendlistSelectedIndex].m_NumFound) + { + bool Found = false; + int NumServers = ServerBrowser()->NumSortedServers(); + for (int i = 0; i < NumServers && !Found; i++) + { + int ItemIndex = m_SelectedIndex != -1 ? (m_SelectedIndex+i+1)%NumServers : i; + const CServerInfo *pItem = ServerBrowser()->SortedGet(ItemIndex); + if(pItem->m_FriendState != IFriends::FRIEND_NO) + { + for(int j = 0; j < pItem->m_NumClients && !Found; ++j) + { + if(pItem->m_aClients[j].m_FriendState != IFriends::FRIEND_NO && + ((g_Config.m_ClFriendsIgnoreClan && m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0]) || str_quickhash(pItem->m_aClients[j].m_aClan) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_ClanHash) && + (!m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0] || + str_quickhash(pItem->m_aClients[j].m_aName) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_NameHash)) + { + str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); + m_ScrollOffset = ItemIndex; + m_SelectedIndex = ItemIndex; + Found = true; + } + } + } + } + } + + ServerFriends.HSplitTop(2.5f, 0, &ServerFriends); + ServerFriends.HSplitTop(20.0f, &Button, &ServerFriends); + if(m_FriendlistSelectedIndex != -1) + { + static int s_RemoveButton = 0; + if(DoButton_Menu(&s_RemoveButton, Localize("Remove"), 0, &Button)) + m_Popup = POPUP_REMOVE_FRIEND; + } + + // add friend + if(m_pClient->Friends()->NumFriends() < IFriends::MAX_FRIENDS) + { + ServerFriends.HSplitTop(10.0f, 0, &ServerFriends); + ServerFriends.HSplitTop(19.0f, &Button, &ServerFriends); + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Name")); + UI()->DoLabelScaled(&Button, aBuf, FontSize, -1); + Button.VSplitLeft(80.0f, 0, &Button); + static char s_aName[MAX_NAME_LENGTH] = {0}; + static float s_OffsetName = 0.0f; + DoEditBox(&s_aName, &Button, s_aName, sizeof(s_aName), FontSize, &s_OffsetName); + + ServerFriends.HSplitTop(3.0f, 0, &ServerFriends); + ServerFriends.HSplitTop(19.0f, &Button, &ServerFriends); + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Clan")); + UI()->DoLabelScaled(&Button, aBuf, FontSize, -1); + Button.VSplitLeft(80.0f, 0, &Button); + static char s_aClan[MAX_CLAN_LENGTH] = {0}; + static float s_OffsetClan = 0.0f; + DoEditBox(&s_aClan, &Button, s_aClan, sizeof(s_aClan), FontSize, &s_OffsetClan); + + ServerFriends.HSplitTop(3.0f, 0, &ServerFriends); + ServerFriends.HSplitTop(20.0f, &Button, &ServerFriends); + static int s_AddButton = 0; + if(DoButton_Menu(&s_AddButton, Localize("Add Friend"), 0, &Button)) + { + m_pClient->Friends()->AddFriend(s_aName, s_aClan); + FriendlistOnUpdate(); + Client()->ServerBrowserUpdate(); + } + } +} + +void CMenus::RenderServerbrowser(CUIRect MainView) +{ + /* + +-----------------+ +-------+ + | | | | + | | | tool | + | server list | | box | + | | | | + | | | | + +-----------------+ | | + status box tab +-------+ + */ + + CUIRect ServerList, ToolBox, StatusBox, TabBar; + + // background + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + MainView.Margin(10.0f, &MainView); + + // create server list, status box, tab bar and tool box area + MainView.VSplitRight(205.0f, &ServerList, &ToolBox); + ServerList.HSplitBottom(70.0f, &ServerList, &StatusBox); + StatusBox.VSplitRight(100.0f, &StatusBox, &TabBar); + ServerList.VSplitRight(5.0f, &ServerList, 0); + + // server list + { + RenderServerbrowserServerList(ServerList); + } + + int ToolboxPage = g_Config.m_UiToolboxPage; + + // tab bar + { + CUIRect TabButton0, TabButton1, TabButton2; + TabBar.HSplitTop(5.0f, 0, &TabBar); + TabBar.HSplitTop(20.0f, &TabButton0, &TabBar); + TabBar.HSplitTop(2.5f, 0, &TabBar); + TabBar.HSplitTop(20.0f, &TabButton1, &TabBar); + TabBar.HSplitTop(2.5f, 0, &TabBar); + TabBar.HSplitTop(20.0f, &TabButton2, 0); + vec4 Active = ms_ColorTabbarActive; + vec4 InActive = ms_ColorTabbarInactive; + ms_ColorTabbarActive = vec4(0.0f, 0.0f, 0.0f, 0.3f); + ms_ColorTabbarInactive = vec4(0.0f, 0.0f, 0.0f, 0.15f); + + static int s_FiltersTab = 0; + if (DoButton_MenuTab(&s_FiltersTab, Localize("Filter"), ToolboxPage==0, &TabButton0, CUI::CORNER_L)) + ToolboxPage = 0; + + static int s_InfoTab = 0; + if (DoButton_MenuTab(&s_InfoTab, Localize("Info"), ToolboxPage==1, &TabButton1, CUI::CORNER_L)) + ToolboxPage = 1; + + static int s_FriendsTab = 0; + if (DoButton_MenuTab(&s_FriendsTab, Localize("Friends"), ToolboxPage==2, &TabButton2, CUI::CORNER_L)) + ToolboxPage = 2; + + ms_ColorTabbarActive = Active; + ms_ColorTabbarInactive = InActive; + g_Config.m_UiToolboxPage = ToolboxPage; + } + + // tool box + { + RenderTools()->DrawUIRect(&ToolBox, vec4(0.0f, 0.0f, 0.0f, 0.15f), CUI::CORNER_T, 4.0f); + + + if(ToolboxPage == 0) + RenderServerbrowserFilters(ToolBox); + else if(ToolboxPage == 1) + RenderServerbrowserServerDetail(ToolBox); + else if(ToolboxPage == 2) + RenderServerbrowserFriends(ToolBox); + } + + // status box + { + CUIRect Button, ButtonArea; + StatusBox.HSplitTop(5.0f, 0, &StatusBox); + + // version note +#if defined(CONF_FAMILY_WINDOWS) || (defined(CONF_PLATFORM_LINUX) && !defined(__ANDROID__)) + CUIRect Part; + StatusBox.HSplitBottom(15.0f, &StatusBox, &Button); + char aBuf[64]; + int State = Updater()->GetCurrentState(); + bool NeedUpdate = str_comp(Client()->LatestVersion(), "0"); + if(State == IUpdater::CLEAN && NeedUpdate) + { + str_format(aBuf, sizeof(aBuf), "DDNet %s is out!", Client()->LatestVersion()); + TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); + } + else if(State == IUpdater::CLEAN) + str_format(aBuf, sizeof(aBuf), Localize("Current version: %s"), GAME_VERSION); + else if(State >= IUpdater::GETTING_MANIFEST && State < IUpdater::NEED_RESTART) + str_format(aBuf, sizeof(aBuf), "Downloading %s:", Updater()->GetCurrentFile()); + else if(State == IUpdater::FAIL) + { + str_format(aBuf, sizeof(aBuf), "Failed to download a file! Restart client to retry..."); + TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); + } + else if(State == IUpdater::NEED_RESTART) + { + str_format(aBuf, sizeof(aBuf), "DDNet Client updated!"); + TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); + } + UI()->DoLabelScaled(&Button, aBuf, 14.0f, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + + Button.VSplitLeft(TextRender()->TextWidth(0, 14.0f, aBuf, -1) + 10.0f, &Button, &Part); + + if(State == IUpdater::CLEAN && NeedUpdate) + { + CUIRect Update; + Part.VSplitLeft(100.0f, &Update, NULL); + + static int s_ButtonUpdate = 0; + if(DoButton_Menu(&s_ButtonUpdate, Localize("Update now"), 0, &Update)) + { + Updater()->InitiateUpdate(); + } + } + else if(State == IUpdater::NEED_RESTART) + { + CUIRect Restart; + Part.VSplitLeft(50.0f, &Restart, &Part); + + static int s_ButtonUpdate = 0; + if(DoButton_Menu(&s_ButtonUpdate, Localize("Restart"), 0, &Restart)) + { + Client()->Restart(); + } + } + else if(State >= IUpdater::GETTING_MANIFEST && State < IUpdater::NEED_RESTART) + { + CUIRect ProgressBar, Percent; + Part.VSplitLeft(100.0f, &ProgressBar, &Percent); + ProgressBar.y += 2.0f; + ProgressBar.HMargin(1.0f, &ProgressBar); + RenderTools()->DrawUIRect(&ProgressBar, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f); + ProgressBar.w = clamp((float)Updater()->GetCurrentPercent(), 10.0f, 100.0f); + RenderTools()->DrawUIRect(&ProgressBar, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 5.0f); + } +#else + StatusBox.HSplitBottom(15.0f, &StatusBox, &Button); + char aBuf[64]; + if(str_comp(Client()->LatestVersion(), "0") != 0) + { + str_format(aBuf, sizeof(aBuf), Localize("DDNet %s is out! Download it at ddnet.tw!"), Client()->LatestVersion()); + TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); + } + else + str_format(aBuf, sizeof(aBuf), Localize("Current version: %s"), GAME_VERSION); + UI()->DoLabelScaled(&Button, aBuf, 14.0f, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); +#endif + // button area + //StatusBox.VSplitRight(80.0f, &StatusBox, 0); + StatusBox.VSplitRight(170.0f, &StatusBox, &ButtonArea); + //ButtonArea.VSplitRight(150.0f, 0, &ButtonArea); + ButtonArea.HSplitTop(20.0f, &Button, &ButtonArea); + Button.VMargin(20.0f, &Button); + + static int s_RefreshButton = 0; + if(ServerBrowser()->IsRefreshing()) + str_format(aBuf, sizeof(aBuf), "%s (%d%%)", Localize("Refresh"), ServerBrowser()->LoadingProgression()); + else + str_copy(aBuf, Localize("Refresh"), sizeof(aBuf)); + + if(DoButton_Menu(&s_RefreshButton, aBuf, 0, &Button)) + { + if(g_Config.m_UiPage == PAGE_INTERNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); + else if(g_Config.m_UiPage == PAGE_LAN) + ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); + else if(g_Config.m_UiPage == PAGE_FAVORITES) + ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); + else if(g_Config.m_UiPage == PAGE_DDNET) + { + // start a new serverlist request + Client()->RequestDDNetSrvList(); + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + } + m_DoubleClickIndex = -1; + } + + ButtonArea.HSplitTop(5.0f, 0, &ButtonArea); + ButtonArea.HSplitTop(20.0f, &Button, &ButtonArea); + Button.VMargin(20.0f, &Button); + + static int s_JoinButton = 0; + if(DoButton_Menu(&s_JoinButton, Localize("Connect"), 0, &Button) || m_EnterPressed) + { + Client()->Connect(g_Config.m_UiServerAddress); + m_EnterPressed = false; + } + + // address info + StatusBox.VSplitLeft(20.0f, 0, &StatusBox); + StatusBox.HSplitTop(20.0f, &Button, &StatusBox); + UI()->DoLabelScaled(&Button, Localize("Host address"), 14.0f, -1); + StatusBox.HSplitTop(20.0f, &Button, 0); + static float Offset = 0.0f; + DoEditBox(&g_Config.m_UiServerAddress, &Button, g_Config.m_UiServerAddress, sizeof(g_Config.m_UiServerAddress), 14.0f, &Offset); + } +} + +void CMenus::ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() == 2 && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE) + { + ((CMenus *)pUserData)->FriendlistOnUpdate(); + ((CMenus *)pUserData)->Client()->ServerBrowserUpdate(); + } +} + +void CMenus::ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments() && (g_Config.m_UiPage == PAGE_FAVORITES || g_Config.m_UiPage == PAGE_DDNET) && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE) + ((CMenus *)pUserData)->ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); +} diff --git a/src/game/client/components/menus_demo.cpp b/src/game/client/components/menus_demo.cpp new file mode 100644 index 0000000..41e29ee --- /dev/null +++ b/src/game/client/components/menus_demo.cpp @@ -0,0 +1,1176 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/string.h> + +#include <base/math.h> + +#include <engine/demo.h> +#include <engine/keys.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/storage.h> + +#include <game/client/render.h> +#include <game/client/gameclient.h> +#include <game/localization.h> + +#include <game/client/ui.h> + +#include <game/generated/client_data.h> + +#include "maplayers.h" +#include "menus.h" + +int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect) +{ + RenderTools()->DrawUIRect(pRect, vec4(1,1,1, Checked ? 0.10f : 0.5f)*ButtonColorMul(pID), CUI::CORNER_ALL, 5.0f); + UI()->DoLabel(pRect, pText, 14.0f, 0); + return UI()->DoButtonLogic(pID, pText, Checked, pRect); +} + +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); + Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); + Graphics()->QuadsBegin(); + if(!Checked) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); + RenderTools()->SelectSprite(SpriteID); + 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; + static int64 LastSpeedChange = 0; + + // render popups + if (m_DemoPlayerState == DEMOPLAYER_SLICE_SAVE) + { + CUIRect Screen = *UI()->Screen(); + CUIRect Box, Part; + Box = Screen; + Box.VMargin(150.0f/UI()->Scale(), &Box); +#if defined(__ANDROID__) + Box.HMargin(100.0f/UI()->Scale(), &Box); +#else + Box.HMargin(150.0f/UI()->Scale(), &Box); +#endif + + // 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, Localize("Select a name"), 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); + UI()->DoLabelScaled(&Part, m_aDemoPlayerPopupHint, 24.f, 0); + + + CUIRect Label, TextBox, Ok, Abort; + + Box.HSplitBottom(20.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + 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_DemoPlayerState = DEMOPLAYER_NONE; + + static int s_ButtonOk = 0; + if(DoButton_Menu(&s_ButtonOk, Localize("Ok"), 0, &Ok) || m_EnterPressed) + { + if (str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, m_aCurrentDemoFile) == 0) + str_copy(m_aDemoPlayerPopupHint, Localize("Please use a different name"), sizeof(m_aDemoPlayerPopupHint)); + else + { + m_DemoPlayerState = DEMOPLAYER_NONE; + + int len = str_length(m_aCurrentDemoFile); + if(len < 5 || str_comp_nocase(&m_aCurrentDemoFile[len-5], ".demo")) + str_append(m_aCurrentDemoFile, ".demo", sizeof(m_aCurrentDemoFile)); + + char aPath[512]; + str_format(aPath, sizeof(aPath), "%s/%s", m_aCurrentDemoFolder, m_aCurrentDemoFile); + Client()->DemoSlice(aPath); + } + } + + Box.HSplitBottom(60.f, &Box, &Part); +#if defined(__ANDROID__) + Box.HSplitBottom(60.f, &Box, &Part); +#else + Box.HSplitBottom(24.f, &Box, &Part); +#endif + + Part.VSplitLeft(60.0f, 0, &Label); + Label.VSplitLeft(120.0f, 0, &TextBox); + TextBox.VSplitLeft(20.0f, 0, &TextBox); + TextBox.VSplitRight(60.0f, &TextBox, 0); + UI()->DoLabel(&Label, Localize("New name:"), 18.0f, -1); + static float Offset = 0.0f; + DoEditBox(&Offset, &TextBox, m_aCurrentDemoFile, sizeof(m_aCurrentDemoFile), 12.0f, &Offset); + + } + + // handle mousewheel independent of active menu + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + { + if(pInfo->m_Speed < 0.1f) DemoPlayer()->SetSpeed(0.1f); + else if(pInfo->m_Speed < 0.25f) DemoPlayer()->SetSpeed(0.25f); + else if(pInfo->m_Speed < 0.5f) DemoPlayer()->SetSpeed(0.5f); + else if(pInfo->m_Speed < 0.75f) DemoPlayer()->SetSpeed(0.75f); + else if(pInfo->m_Speed < 1.0f) DemoPlayer()->SetSpeed(1.0f); + else if(pInfo->m_Speed < 2.0f) DemoPlayer()->SetSpeed(2.0f); + else if(pInfo->m_Speed < 4.0f) DemoPlayer()->SetSpeed(4.0f); + else DemoPlayer()->SetSpeed(8.0f); + LastSpeedChange = time_get(); + } + else if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + { + if(pInfo->m_Speed > 4.0f) DemoPlayer()->SetSpeed(4.0f); + else if(pInfo->m_Speed > 2.0f) DemoPlayer()->SetSpeed(2.0f); + else if(pInfo->m_Speed > 1.0f) DemoPlayer()->SetSpeed(1.0f); + else if(pInfo->m_Speed > 0.75f) DemoPlayer()->SetSpeed(0.75f); + else if(pInfo->m_Speed > 0.5f) DemoPlayer()->SetSpeed(0.5f); + else if(pInfo->m_Speed > 0.25f) DemoPlayer()->SetSpeed(0.25f); + else if(pInfo->m_Speed > 0.1f) DemoPlayer()->SetSpeed(0.1f); + else DemoPlayer()->SetSpeed(0.05f); + LastSpeedChange = time_get(); + } + + TotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3; + + // render speed info + if (g_Config.m_ClDemoShowSpeed && time_get() - LastSpeedChange < time_freq() * 1) + { + CUIRect Screen = *UI()->Screen(); + + char aSpeedBuf[256]; + str_format(aSpeedBuf, sizeof(aSpeedBuf), "×%.2f", pInfo->m_Speed); + TextRender()->Text(0, 120.0f, Screen.y+Screen.h - 120.0f - TotalHeight, 60.0f, aSpeedBuf, -1); + } + + if(!m_MenuActive) + return; + + MainView.HSplitBottom(TotalHeight, 0, &MainView); + MainView.VSplitLeft(50.0f, 0, &MainView); + MainView.VSplitLeft(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; + + MainView.HSplitTop(SeekBarHeight, &SeekBar, &ButtonBar); + ButtonBar.HSplitTop(Margins, 0, &ButtonBar); + ButtonBar.HSplitBottom(NameBarHeight, &ButtonBar, &NameBar); + NameBar.HSplitTop(4.0f, 0, &NameBar); + + // do seekbar + { + static int s_SeekBarID = 0; + void *id = &s_SeekBarID; + char aBuffer[128]; + + // draw seek bar + RenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f); + + // draw filled bar + 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); + + // draw markers + for(int i = 0; i < pInfo->m_NumTimelineMarkers; i++) + { + float Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks; + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + // draw slice markers + // begin + if (g_Config.m_ClDemoSliceBegin != -1) + { + float Ratio = (g_Config.m_ClDemoSliceBegin-pInfo->m_FirstTick) / (float)TotalTicks; + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); + IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + // end + if (g_Config.m_ClDemoSliceEnd != -1) + { + float Ratio = (g_Config.m_ClDemoSliceEnd-pInfo->m_FirstTick) / (float)TotalTicks; + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); + IGraphics::CQuadItem QuadItem(10.0f + SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + // draw time + 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); + + if(UI()->ActiveItem() == id) + { + if(!UI()->MouseButton(0)) + UI()->SetActiveItem(0); + else + { + static float PrevAmount = 0.0f; + float Amount = (UI()->MouseX()-SeekBar.x)/(float)SeekBar.w; + + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + { + Amount = PrevAmount + (Amount-PrevAmount) * 0.05f; + + if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.0001f) + { + //PrevAmount = Amount; + m_pClient->OnReset(); + m_pClient->m_SuppressEvents = true; + DemoPlayer()->SetPos(Amount); + m_pClient->m_SuppressEvents = false; + m_pClient->m_pMapLayersBackGround->EnvelopeUpdate(); + m_pClient->m_pMapLayersForeGround->EnvelopeUpdate(); + } + } + else + { + if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.001f) + { + PrevAmount = Amount; + m_pClient->OnReset(); + m_pClient->m_SuppressEvents = true; + DemoPlayer()->SetPos(Amount); + m_pClient->m_SuppressEvents = false; + m_pClient->m_pMapLayersBackGround->EnvelopeUpdate(); + m_pClient->m_pMapLayersForeGround->EnvelopeUpdate(); + } + } + } + } + else if(UI()->HotItem() == id) + { + if(UI()->MouseButton(0)) + UI()->SetActiveItem(id); + } + + if(Inside) + UI()->SetHotItem(id); + } + + if(CurrentTick == TotalTicks) + { + m_pClient->OnReset(); + DemoPlayer()->Pause(); + DemoPlayer()->SetPos(0); + } + + bool IncreaseDemoSpeed = false, DecreaseDemoSpeed = false; + + // do buttons + CUIRect Button; + + // combined play and pause button + ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); + static int s_PlayPauseButton = 0; + if(!pInfo->m_Paused) + { + if(DoButton_Sprite(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PAUSE, false, &Button, CUI::CORNER_ALL)) + DemoPlayer()->Pause(); + } + else + { + 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()->SetPos(0); + } + + // slowdown + ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); + ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); + 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); + static int s_FastForwardButton = 0; + if(DoButton_Sprite(&s_FastForwardButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_FASTER, 0, &Button, CUI::CORNER_ALL)) + IncreaseDemoSpeed = true; + + // speed meter + ButtonBar.VSplitLeft(Margins*3, 0, &ButtonBar); + char aBuffer[64]; + if(pInfo->m_Speed >= 1.0f) + str_format(aBuffer, sizeof(aBuffer), "×%.0f", pInfo->m_Speed); + else + str_format(aBuffer, sizeof(aBuffer), "×%.2f", pInfo->m_Speed); + UI()->DoLabel(&ButtonBar, aBuffer, Button.h*0.7f, -1); + + // slice begin button + ButtonBar.VSplitLeft(Margins*10, 0, &ButtonBar); + ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); + static int s_SliceBeginButton = 0; + if(DoButton_Sprite(&s_SliceBeginButton, IMAGE_DEMOBUTTONS2, SPRITE_DEMOBUTTON_SLICE_BEGIN, 0, &Button, CUI::CORNER_ALL)) + Client()->DemoSliceBegin(); + + // slice end button + ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); + ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); + static int s_SliceEndButton = 0; + if(DoButton_Sprite(&s_SliceEndButton, IMAGE_DEMOBUTTONS2, SPRITE_DEMOBUTTON_SLICE_END, 0, &Button, CUI::CORNER_ALL)) + Client()->DemoSliceEnd(); + + // slice save button + ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); + ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); + static int s_SliceSaveButton = 0; + if(DoButton_Sprite(&s_SliceSaveButton, IMAGE_FILEICONS, SPRITE_FILE_DEMO2, 0, &Button, CUI::CORNER_ALL)) + { + str_copy(m_aCurrentDemoFile, m_lDemos[m_DemolistSelectedIndex].m_aFilename, sizeof(m_aCurrentDemoFile)); + m_aDemoPlayerPopupHint[0] = '\0'; + m_DemoPlayerState = DEMOPLAYER_SLICE_SAVE; + } + + // close button + ButtonBar.VSplitRight(ButtonbarHeight*3, &ButtonBar, &Button); + static int s_ExitButton = 0; + if(DoButton_DemoPlayer(&s_ExitButton, Localize("Close"), 0, &Button)) + { + Client()->Disconnect(); + DemolistPopulate(); + DemolistOnUpdate(false); + } + + // demo name + char aDemoName[64] = {0}; + DemoPlayer()->GetDemoName(aDemoName, sizeof(aDemoName)); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), Localize("Demofile: %s"), aDemoName); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y, Button.h*0.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = MainView.w; + TextRender()->TextEx(&Cursor, aBuf, -1); + + if(IncreaseDemoSpeed) + { + if(pInfo->m_Speed < 0.1f) DemoPlayer()->SetSpeed(0.1f); + else if(pInfo->m_Speed < 0.25f) DemoPlayer()->SetSpeed(0.25f); + else if(pInfo->m_Speed < 0.5f) DemoPlayer()->SetSpeed(0.5f); + else if(pInfo->m_Speed < 0.75f) DemoPlayer()->SetSpeed(0.75f); + else if(pInfo->m_Speed < 1.0f) DemoPlayer()->SetSpeed(1.0f); + else if(pInfo->m_Speed < 2.0f) DemoPlayer()->SetSpeed(2.0f); + else if(pInfo->m_Speed < 4.0f) DemoPlayer()->SetSpeed(4.0f); + else DemoPlayer()->SetSpeed(8.0f); + LastSpeedChange = time_get(); + } + else if(DecreaseDemoSpeed) + { + if(pInfo->m_Speed > 4.0f) DemoPlayer()->SetSpeed(4.0f); + else if(pInfo->m_Speed > 2.0f) DemoPlayer()->SetSpeed(2.0f); + else if(pInfo->m_Speed > 1.0f) DemoPlayer()->SetSpeed(1.0f); + else if(pInfo->m_Speed > 0.75f) DemoPlayer()->SetSpeed(0.75f); + else if(pInfo->m_Speed > 0.5f) DemoPlayer()->SetSpeed(0.5f); + else if(pInfo->m_Speed > 0.25f) DemoPlayer()->SetSpeed(0.25f); + else if(pInfo->m_Speed > 0.1f) DemoPlayer()->SetSpeed(0.1f); + else DemoPlayer()->SetSpeed(0.05f); + LastSpeedChange = time_get(); + } +} + +static CUIRect gs_ListBoxOriginalView; +static CUIRect gs_ListBoxView; +static float gs_ListBoxRowHeight; +static int gs_ListBoxItemIndex; +static int gs_ListBoxSelectedIndex; +static int gs_ListBoxNewSelected; +static int gs_ListBoxDoneEvents; +static int gs_ListBoxNumItems; +static int gs_ListBoxItemsPerRow; +static float gs_ListBoxScrollValue; +static bool gs_ListBoxItemActivated; + +void CMenus::UiDoListboxStart(const void *pID, const CUIRect *pRect, float RowHeight, const char *pTitle, const char *pBottomText, int NumItems, + int ItemsPerRow, int SelectedIndex, float ScrollValue) +{ + 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); + 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); + Footer.VSplitLeft(10.0f, 0, &Footer); + UI()->DoLabel(&Footer, pBottomText, Header.h*ms_FontmodHeight, 0); + + // background + RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.15f), 0, 0); + + // prepare the scroll +#if defined(__ANDROID__) + View.VSplitRight(50, &View, &Scroll); +#else + View.VSplitRight(15, &View, &Scroll); +#endif + + // setup the variables + gs_ListBoxOriginalView = View; + gs_ListBoxSelectedIndex = SelectedIndex; + gs_ListBoxNewSelected = SelectedIndex; + gs_ListBoxItemIndex = 0; + gs_ListBoxRowHeight = RowHeight; + gs_ListBoxNumItems = NumItems; + gs_ListBoxItemsPerRow = ItemsPerRow; + gs_ListBoxDoneEvents = 0; + gs_ListBoxScrollValue = ScrollValue; + gs_ListBoxItemActivated = false; + + // 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) + Num = 0; + if(Num > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) + gs_ListBoxScrollValue -= 3.0f/Num; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) + 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); + UI()->ClipEnable(&gs_ListBoxView); + gs_ListBoxView.y -= gs_ListBoxScrollValue*Num*Row.h; +} + +CMenus::CListboxItem CMenus::UiDoListboxNextRow() +{ + static CUIRect s_RowView; + CListboxItem Item = {0}; + if(gs_ListBoxItemIndex%gs_ListBoxItemsPerRow == 0) + gs_ListBoxView.HSplitTop(gs_ListBoxRowHeight /*-2.0f*/, &s_RowView, &gs_ListBoxView); + + s_RowView.VSplitLeft(s_RowView.w/(gs_ListBoxItemsPerRow-gs_ListBoxItemIndex%gs_ListBoxItemsPerRow)/(UI()->Scale()), &Item.m_Rect, &s_RowView); + + 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; + + // 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; +} + +CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected) +{ + int ThisItemIndex = gs_ListBoxItemIndex; + if(Selected) + { + if(gs_ListBoxSelectedIndex == gs_ListBoxNewSelected) + 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) + { + if(!gs_ListBoxDoneEvents) + { + gs_ListBoxDoneEvents = 1; + + if(m_EnterPressed || (UI()->ActiveItem() == pId && Input()->MouseDoubleClick())) + { + gs_ListBoxItemActivated = true; + UI()->SetActiveItem(0); + } + else + { + for(int i = 0; i < m_NumInputEvents; i++) + { + int NewIndex = -1; + if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + { + if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = gs_ListBoxNewSelected + 1; + if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = gs_ListBoxNewSelected - 1; + } + if(NewIndex > -1 && NewIndex < gs_ListBoxNumItems) + { + // scroll + float Offset = (NewIndex/gs_ListBoxItemsPerRow-gs_ListBoxNewSelected/gs_ListBoxItemsPerRow)*gs_ListBoxRowHeight; + int Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y+Offset ? -1 : + gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h < Item.m_Rect.y+Item.m_Rect.h+Offset ? 1 : 0; + if(Scroll) + { + int NumViewable = (int)(gs_ListBoxOriginalView.h/gs_ListBoxRowHeight) + 1; + int ScrollNum = (gs_ListBoxNumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; + if(Scroll < 0) + { + int Num = (gs_ListBoxOriginalView.y-Item.m_Rect.y-Offset+gs_ListBoxRowHeight-1.0f)/gs_ListBoxRowHeight; + gs_ListBoxScrollValue -= (1.0f/ScrollNum)*Num; + } + else + { + int Num = (Item.m_Rect.y+Item.m_Rect.h+Offset-(gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)+gs_ListBoxRowHeight-1.0f)/ + gs_ListBoxRowHeight; + gs_ListBoxScrollValue += (1.0f/ScrollNum)*Num; + } + 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; +} + +int CMenus::UiDoListboxEnd(float *pScrollValue, bool *pItemActivated) +{ + UI()->ClipDisable(); + if(pScrollValue) + *pScrollValue = gs_ListBoxScrollValue; + if(pItemActivated) + *pItemActivated = gs_ListBoxItemActivated; + return gs_ListBoxNewSelected; +} + +int CMenus::DemolistFetchCallback(const char *pName, time_t Date, int IsDir, int StorageType, void *pUser) +{ + CMenus *pSelf = (CMenus *)pUser; + int Length = str_length(pName); + if((pName[0] == '.' && (pName[1] == 0 || + (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) + { + str_format(Item.m_aName, sizeof(Item.m_aName), "%s/", pName); + Item.m_Valid = false; + } + else + { + str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-4)); + Item.m_InfosLoaded = false; + Item.m_Date = Date; + } + Item.m_IsDir = IsDir != 0; + Item.m_StorageType = StorageType; + pSelf->m_lDemos.add_unsorted(Item); + + return 0; +} + +void CMenus::DemolistPopulate() +{ + m_lDemos.clear(); + if(!str_comp(m_aCurrentDemoFolder, "demos")) + m_DemolistStorageType = IStorage::TYPE_ALL; + Storage()->ListDirectoryInfo(m_DemolistStorageType, m_aCurrentDemoFolder, DemolistFetchCallback, this); + m_lDemos.sort_range(); +} + +void CMenus::DemolistOnUpdate(bool Reset) +{ + if (Reset) + g_Config.m_UiDemoSelected[0] = '\0'; + else + { + bool Found = false; + int SelectedIndex = -1; + // search for selected index + for(sorted_array<CDemoItem>::range r = m_lDemos.all(); !r.empty(); r.pop_front()) + { + SelectedIndex++; + + if (str_comp(g_Config.m_UiDemoSelected, r.front().m_aName) == 0) + { + Found = true; + break; + } + } + + if (Found) + m_DemolistSelectedIndex = SelectedIndex; + } + + m_DemolistSelectedIndex = Reset ? m_lDemos.size() > 0 ? 0 : -1 : + m_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size()-1 : m_DemolistSelectedIndex; + m_DemolistSelectedIsDir = m_DemolistSelectedIndex < 0 ? false : m_lDemos[m_DemolistSelectedIndex].m_IsDir; +} + +void CMenus::RenderDemoList(CUIRect MainView) +{ + static int s_Inited = 0; + if(!s_Inited) + { + DemolistPopulate(); + DemolistOnUpdate(true); + s_Inited = 1; + } + + char aFooterLabel[128] = {0}; + if(m_DemolistSelectedIndex >= 0) + { + CDemoItem *Item = &m_lDemos[m_DemolistSelectedIndex]; + if(str_comp(Item->m_aFilename, "..") == 0) + str_copy(aFooterLabel, Localize("Parent Folder"), sizeof(aFooterLabel)); + else if(m_DemolistSelectedIsDir) + str_copy(aFooterLabel, Localize("Folder"), sizeof(aFooterLabel)); + else + { + if(!Item->m_InfosLoaded) + { + char aBuffer[512]; + str_format(aBuffer, sizeof(aBuffer), "%s/%s", m_aCurrentDemoFolder, Item->m_aFilename); + Item->m_Valid = DemoPlayer()->GetDemoInfo(Storage(), aBuffer, Item->m_StorageType, &Item->m_Info); + Item->m_InfosLoaded = true; + } + if(!Item->m_Valid) + str_copy(aFooterLabel, Localize("Invalid Demo"), sizeof(aFooterLabel)); + else + 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, ListBox; + MainView.HSplitBottom(ms_ButtonHeight+5.0f, &MainView, &ButtonBar); + ButtonBar.HSplitTop(5.0f, 0, &ButtonBar); + ButtonBar.VSplitRight(130.0f, &ButtonBar, &PlayRect); + ButtonBar.VSplitLeft(130.0f, &RefreshRect, &ButtonBar); + ButtonBar.VSplitLeft(10.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &DeleteRect, &ButtonBar); + ButtonBar.VSplitLeft(10.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &RenameRect, &ButtonBar); + MainView.HSplitBottom(140.0f, &ListBox, &MainView); + + // render demo info + MainView.VMargin(5.0f, &MainView); + MainView.HSplitBottom(5.0f, &MainView, 0); + RenderTools()->DrawUIRect(&MainView, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); + if(!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid) + { + CUIRect Left, Right, Labels; + MainView.Margin(20.0f, &MainView); + MainView.VSplitMid(&Labels, &MainView); + + // left side + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Created:"), 14.0f, -1); + + char aTimestamp[256]; + str_timestamp_ex(m_lDemos[m_DemolistSelectedIndex].m_Date, aTimestamp, sizeof(aTimestamp), "%Y-%m-%d %H:%M:%S"); + + UI()->DoLabelScaled(&Right, aTimestamp, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Type:"), 14.0f, -1); + UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aType, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Length:"), 14.0f, -1); + int Length = ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[0]<<24)&0xFF000000) | ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[1]<<16)&0xFF0000) | + ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[2]<<8)&0xFF00) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[3]&0xFF); + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%d:%02d", Length/60, Length%60); + UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Version:"), 14.0f, -1); + str_format(aBuf, sizeof(aBuf), "%d", m_lDemos[m_DemolistSelectedIndex].m_Info.m_Version); + UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); + + // right side + Labels = MainView; + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Map:"), 14.0f, -1); + UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapName, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(20.0f, 0, &Left); + Left.VSplitLeft(130.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Size:"), 14.0f, -1); + unsigned Size = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1]<<16) | + (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]); + if(Size > 1024*1024) + str_format(aBuf, sizeof(aBuf), Localize("%.2f MiB"), float(Size)/(1024*1024)); + else + str_format(aBuf, sizeof(aBuf), Localize("%.2f KiB"), float(Size)/1024); + UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(20.0f, 0, &Left); + Left.VSplitLeft(130.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Crc:"), 14.0f, -1); + unsigned Crc = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[1]<<16) | + (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[3]); + str_format(aBuf, sizeof(aBuf), "%08x", Crc); + UI()->DoLabelScaled(&Right, aBuf, 14.0f, -1); + Labels.HSplitTop(5.0f, 0, &Labels); + Labels.HSplitTop(20.0f, &Left, &Labels); + Left.VSplitLeft(150.0f, &Left, &Right); + UI()->DoLabelScaled(&Left, Localize("Netversion:"), 14.0f, -1); + UI()->DoLabelScaled(&Right, m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion, 14.0f, -1); + } + + + // demo list + + CUIRect Headers; + + ListBox.HSplitTop(ms_ListheaderHeight, &Headers, &ListBox); + + struct CColumn + { + int m_ID; + int m_Sort; + CLocConstString m_Caption; + int m_Direction; + float m_Width; + int m_Flags; + CUIRect m_Rect; + CUIRect m_Spacer; + }; + + enum + { + COL_ICON=0, + COL_DEMONAME, + COL_DATE, + + SORT_DEMONAME=0, + SORT_DATE, + }; + + static CColumn s_aCols[] = { + {COL_ICON, -1, " ", -1, 14.0f, 0, {0}, {0}}, + {COL_DEMONAME, SORT_DEMONAME, "Demo", 0, 0.0f, 0, {0}, {0}}, + {COL_DATE, SORT_DATE, "Date", 1, 300.0f, 0, {0}, {0}}, + }; + + RenderTools()->DrawUIRect(&Headers, vec4(0.0f,0,0,0.15f), 0, 0); + + int NumCols = sizeof(s_aCols)/sizeof(CColumn); + + // do layout + for(int i = 0; i < NumCols; i++) + { + if(s_aCols[i].m_Direction == -1) + { + Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); + + if(i+1 < NumCols) + { + //Cols[i].flags |= SPACER; + Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); + } + } + } + + for(int i = NumCols-1; i >= 0; i--) + { + if(s_aCols[i].m_Direction == 1) + { + Headers.VSplitRight(s_aCols[i].m_Width, &Headers, &s_aCols[i].m_Rect); + Headers.VSplitRight(2, &Headers, &s_aCols[i].m_Spacer); + } + } + + for(int i = 0; i < NumCols; i++) + { + if(s_aCols[i].m_Direction == 0) + s_aCols[i].m_Rect = Headers; + } + + // do headers + for(int i = 0; i < NumCols; i++) + { + if(DoButton_GridHeader(s_aCols[i].m_Caption, s_aCols[i].m_Caption, g_Config.m_BrDemoSort == s_aCols[i].m_Sort, &s_aCols[i].m_Rect)) + { + if(s_aCols[i].m_Sort != -1) + { + if(g_Config.m_BrDemoSort == s_aCols[i].m_Sort) + g_Config.m_BrDemoSortOrder ^= 1; + else + g_Config.m_BrDemoSortOrder = 0; + g_Config.m_BrDemoSort = s_aCols[i].m_Sort; + } + + DemolistPopulate(); + DemolistOnUpdate(false); + } + } + + // scrollbar + CUIRect Scroll; +#if defined(__ANDROID__) + ListBox.VSplitRight(50, &ListBox, &Scroll); +#else + ListBox.VSplitRight(15, &ListBox, &Scroll); +#endif + + int Num = (int)(ListBox.h/s_aCols[0].m_Rect.h) + 1; + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + int ScrollNum = m_lDemos.size()-Num+1; + if(ScrollNum > 0) + { + if(m_ScrollOffset) + { + s_ScrollValue = (float)(m_ScrollOffset)/ScrollNum; + m_ScrollOffset = 0; + } + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&ListBox)) + s_ScrollValue -= 3.0f/ScrollNum; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&ListBox)) + s_ScrollValue += 3.0f/ScrollNum; + } + else + ScrollNum = 0; + + if(m_DemolistSelectedIndex > -1) + { + for(int i = 0; i < m_NumInputEvents; i++) + { + int NewIndex = -1; + if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + { + if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = m_DemolistSelectedIndex + 1; + if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = m_DemolistSelectedIndex - 1; + } + if(NewIndex > -1 && NewIndex < m_lDemos.size()) + { + //scroll + float IndexY = ListBox.y - s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h + NewIndex*s_aCols[0].m_Rect.h; + int Scroll = ListBox.y > IndexY ? -1 : ListBox.y+ListBox.h < IndexY+s_aCols[0].m_Rect.h ? 1 : 0; + if(Scroll) + { + if(Scroll < 0) + { + int NumScrolls = (ListBox.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + } + else + { + int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(ListBox.y+ListBox.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + } + } + + m_DemolistSelectedIndex = NewIndex; + + str_copy(g_Config.m_UiDemoSelected, m_lDemos[NewIndex].m_aName, sizeof(g_Config.m_UiDemoSelected)); + DemolistOnUpdate(false); + } + } + } + + if(s_ScrollValue < 0) s_ScrollValue = 0; + if(s_ScrollValue > 1) s_ScrollValue = 1; + + // set clipping + UI()->ClipEnable(&ListBox); + + CUIRect OriginalView = ListBox; + ListBox.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + + int NewSelected = -1; +#if defined(__ANDROID__) + int DoubleClicked = 0; +#endif + int ItemIndex = -1; + + for(sorted_array<CDemoItem>::range r = m_lDemos.all(); !r.empty(); r.pop_front()) + { + ItemIndex++; + + CUIRect Row; + CUIRect SelectHitBox; + + ListBox.HSplitTop(ms_ListheaderHeight, &Row, &ListBox); + SelectHitBox = Row; + + int Selected = ItemIndex == m_DemolistSelectedIndex; + + // make sure that only those in view can be selected + if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + { + if(Selected) + { + CUIRect r = Row; + r.Margin(1.5f, &r); + RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + } + + // clip the selection + if(SelectHitBox.y < OriginalView.y) // top + { + SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.y = OriginalView.y; + } + else if(SelectHitBox.y+SelectHitBox.h > OriginalView.y+OriginalView.h) // bottom + SelectHitBox.h = OriginalView.y+OriginalView.h-SelectHitBox.y; + + if(UI()->DoButtonLogic(r.front().m_aName /* TODO: */, "", Selected, &SelectHitBox)) + { + NewSelected = ItemIndex; + str_copy(g_Config.m_UiDemoSelected, r.front().m_aName, sizeof(g_Config.m_UiDemoSelected)); + DemolistOnUpdate(false); +#if defined(__ANDROID__) + if(NewSelected == m_DoubleClickIndex) + DoubleClicked = 1; +#endif + + m_DoubleClickIndex = NewSelected; + } + } + else + { + // don't render invisible items + continue; + } + + for(int c = 0; c < NumCols; c++) + { + CUIRect Button; + Button.x = s_aCols[c].m_Rect.x; + Button.y = Row.y; + Button.h = Row.h; + Button.w = s_aCols[c].m_Rect.w; + + int ID = s_aCols[c].m_ID; + + if (ID == COL_ICON) + { + DoButton_Icon(IMAGE_FILEICONS, r.front().m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_DEMO1, &Button); + } + else if(ID == COL_DEMONAME) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + TextRender()->TextEx(&Cursor, r.front().m_aName, -1); + + } + else if (ID == COL_DATE && !r.front().m_IsDir) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + char aBuf[256]; + str_timestamp_ex(r.front().m_Date, aBuf, sizeof(aBuf), "%Y-%m-%d %H:%M:%S"); + TextRender()->TextEx(&Cursor, aBuf, -1); + } + } + } + + UI()->ClipDisable(); + + + bool Activated = false; + +#if defined(__ANDROID__) + if (m_EnterPressed || (DoubleClicked && UI()->ActiveItem() == m_lDemos[m_DemolistSelectedIndex].m_aName)) +#else + if (m_EnterPressed || (Input()->MouseDoubleClick() && UI()->ActiveItem() == m_lDemos[m_DemolistSelectedIndex].m_aName)) +#endif + { + UI()->SetActiveItem(0); + Activated = true; + } + + static int s_RefreshButton = 0; + if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &RefreshRect)) + { + DemolistPopulate(); + DemolistOnUpdate(false); + } + + static int s_PlayButton = 0; + if(DoButton_Menu(&s_PlayButton, m_DemolistSelectedIsDir?Localize("Open"):Localize("Play"), 0, &PlayRect) || Activated) + { + if(m_DemolistSelectedIndex >= 0) + { + if(m_DemolistSelectedIsDir) // folder + { + if(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, "..") == 0) // parent folder + fs_parent_dir(m_aCurrentDemoFolder); + else // sub folder + { + char aTemp[256]; + str_copy(aTemp, m_aCurrentDemoFolder, sizeof(aTemp)); + str_format(m_aCurrentDemoFolder, sizeof(m_aCurrentDemoFolder), "%s/%s", aTemp, m_lDemos[m_DemolistSelectedIndex].m_aFilename); + m_DemolistStorageType = m_lDemos[m_DemolistSelectedIndex].m_StorageType; + } + DemolistPopulate(); + DemolistOnUpdate(true); + } + else // file + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); + const char *pError = Client()->DemoPlayer_Play(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType); + if(pError) + PopupMessage(Localize("Error"), str_comp(pError, "error loading demo") ? pError : Localize("Error loading demo"), Localize("Ok")); + else + { + UI()->SetActiveItem(0); + return; + } + } + } + } + + if(!m_DemolistSelectedIsDir) + { + static int s_DeleteButton = 0; + if(DoButton_Menu(&s_DeleteButton, Localize("Delete"), 0, &DeleteRect) || m_DeletePressed) + { + if(m_DemolistSelectedIndex >= 0) + { + UI()->SetActiveItem(0); + m_Popup = POPUP_DELETE_DEMO; + return; + } + } + + static int s_RenameButton = 0; + if(DoButton_Menu(&s_RenameButton, Localize("Rename"), 0, &RenameRect)) + { + if(m_DemolistSelectedIndex >= 0) + { + UI()->SetActiveItem(0); + m_Popup = POPUP_RENAME_DEMO; + str_copy(m_aCurrentDemoFile, m_lDemos[m_DemolistSelectedIndex].m_aFilename, sizeof(m_aCurrentDemoFile)); + return; + } + } + } +} diff --git a/src/game/client/components/menus_ingame.cpp b/src/game/client/components/menus_ingame.cpp new file mode 100644 index 0000000..3552c83 --- /dev/null +++ b/src/game/client/components/menus_ingame.cpp @@ -0,0 +1,1129 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> + +#include <engine/config.h> +#include <engine/demo.h> +#include <engine/friends.h> +#include <engine/graphics.h> +#include <engine/serverbrowser.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/localization.h> +#include <game/client/components/countryflags.h> +#include <game/client/animstate.h> +#include <game/client/gameclient.h> +#include <game/client/render.h> +#include <game/client/ui.h> + +#include "menus.h" +#include "motd.h" +#include "voting.h" + +#include <base/tl/string.h> +#include <engine/keys.h> +#include <engine/graphics.h> +#include <engine/storage.h> +#include "ghost.h" + +void CMenus::RenderGame(CUIRect MainView) +{ + CUIRect Button, ButtonBar; +#if defined(__ANDROID__) + MainView.HSplitTop(100.0f, &ButtonBar, &MainView); +#else + MainView.HSplitTop(45.0f, &ButtonBar, &MainView); +#endif + RenderTools()->DrawUIRect(&ButtonBar, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + + // button bar + ButtonBar.HSplitTop(10.0f, 0, &ButtonBar); +#if defined(__ANDROID__) + ButtonBar.HSplitTop(80.0f, &ButtonBar, 0); +#else + ButtonBar.HSplitTop(25.0f, &ButtonBar, 0); +#endif + 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)) + { + if(g_Config.m_ClConfirmDisconnect) + m_Popup = POPUP_DISCONNECT; + else + Client()->Disconnect(); + } + + static int s_SpectateButton = 0; + static int s_JoinRedButton = 0; + static int s_JoinBlueButton = 0; + bool DummyConnecting = m_pClient->Client()->DummyConnecting(); + + if(m_pClient->m_Snap.m_pLocalInfo && m_pClient->m_Snap.m_pGameInfoObj) + { + if(m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_SPECTATORS) + { + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &Button, &ButtonBar); + if(!DummyConnecting && DoButton_Menu(&s_SpectateButton, Localize("Spectate"), 0, &Button)) + { + if(g_Config.m_ClDummy == 0 || m_pClient->Client()->DummyConnected()) + { + m_pClient->SendSwitchTeam(TEAM_SPECTATORS); + SetActive(false); + } + } + } + + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags & GAMEFLAG_TEAMS) + { + if(m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_RED) + { + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &Button, &ButtonBar); + if(!DummyConnecting && DoButton_Menu(&s_JoinRedButton, Localize("Join red"), 0, &Button)) + { + m_pClient->SendSwitchTeam(TEAM_RED); + SetActive(false); + } + } + + if(m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_BLUE) + { + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &Button, &ButtonBar); + if(!DummyConnecting && DoButton_Menu(&s_JoinBlueButton, Localize("Join blue"), 0, &Button)) + { + m_pClient->SendSwitchTeam(TEAM_BLUE); + SetActive(false); + } + } + } + else + { + if(m_pClient->m_Snap.m_pLocalInfo->m_Team != 0) + { + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(120.0f, &Button, &ButtonBar); + if(!DummyConnecting && DoButton_Menu(&s_SpectateButton, Localize("Join game"), 0, &Button)) + { + m_pClient->SendSwitchTeam(0); + SetActive(false); + } + } + } + } + + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(150.0f, &Button, &ButtonBar); + + static int s_DemoButton = 0; + bool Recording = DemoRecorder(RECORDER_MANUAL)->IsRecording(); + if(DoButton_Menu(&s_DemoButton, Localize(Recording ? "Stop record" : "Record demo"), 0, &Button)) // Localize("Stop record");Localize("Record demo"); + { + if(!Recording) + Client()->DemoRecorder_Start(Client()->GetCurrentMap(), true, RECORDER_MANUAL); + else + Client()->DemoRecorder_Stop(RECORDER_MANUAL); + } + + ButtonBar.VSplitLeft(5.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(170.0f, &Button, &ButtonBar); + + static int s_DummyButton = 0; + if(DummyConnecting) + { + DoButton_Menu(&s_DummyButton, Localize("Connecting dummy"), 1, &Button); + } + else if(DoButton_Menu(&s_DummyButton, Localize(Client()->DummyConnected() ? "Disconnect dummy" : "Connect dummy"), 0, &Button)) + { + if(!Client()->DummyConnected()) + { + Client()->DummyConnect(); + } + else + { + Client()->DummyDisconnect(0); + } + } +} + +void CMenus::RenderPlayers(CUIRect MainView) +{ + CUIRect Button, Button2, ButtonBar, Options, Player; + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + + // player options + MainView.Margin(10.0f, &Options); + RenderTools()->DrawUIRect(&Options, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); + Options.Margin(10.0f, &Options); + Options.HSplitTop(50.0f, &Button, &Options); + UI()->DoLabelScaled(&Button, Localize("Player options"), 34.0f, -1); + + // headline + Options.HSplitTop(34.0f, &ButtonBar, &Options); + ButtonBar.VSplitRight(220.0f, &Player, &ButtonBar); + UI()->DoLabelScaled(&Player, Localize("Player"), 24.0f, -1); + + ButtonBar.HMargin(1.0f, &ButtonBar); + float Width = ButtonBar.h*2.0f; + ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(SPRITE_GUIICON_MUTE); + IGraphics::CQuadItem QuadItem(Button.x, Button.y, Button.w, Button.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + ButtonBar.VSplitLeft(20.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(SPRITE_GUIICON_FRIEND); + QuadItem = IGraphics::CQuadItem(Button.x, Button.y, Button.w, Button.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + int TotalPlayers = 0; + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(!m_pClient->m_Snap.m_paInfoByName[i]) + continue; + + int Index = m_pClient->m_Snap.m_paInfoByName[i]->m_ClientID; + + if(Index == m_pClient->m_Snap.m_LocalClientID) + continue; + + TotalPlayers++; + } + + static int s_VoteList = 0; + static float s_ScrollValue = 0; + CUIRect List = Options; + //List.HSplitTop(28.0f, 0, &List); +#if defined(__ANDROID__) + UiDoListboxStart(&s_VoteList, &List, 50.0f, "", "", TotalPlayers, 1, -1, s_ScrollValue); +#else + UiDoListboxStart(&s_VoteList, &List, 24.0f, "", "", TotalPlayers, 1, -1, s_ScrollValue); +#endif + + // options + static int s_aPlayerIDs[MAX_CLIENTS][2] = {{0}}; + + for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i) + { + if(!m_pClient->m_Snap.m_paInfoByName[i]) + continue; + + int Index = m_pClient->m_Snap.m_paInfoByName[i]->m_ClientID; + + if(Index == m_pClient->m_Snap.m_LocalClientID) + continue; + + CListboxItem Item = UiDoListboxNextItem(&m_pClient->m_aClients[Index]); + + Count++; + + if(!Item.m_Visible) + continue; + + if(Count%2 == 1) + RenderTools()->DrawUIRect(&Item.m_Rect, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); + Item.m_Rect.VSplitRight(300.0f, &Player, &Item.m_Rect); + + // player info + Player.VSplitLeft(28.0f, &Button, &Player); + CTeeRenderInfo Info = m_pClient->m_aClients[Index].m_RenderInfo; + Info.m_Size = Button.h; + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x+Button.h/2, Button.y+Button.h/2)); + + Player.HSplitTop(1.5f, 0, &Player); + Player.VSplitMid(&Player, &Button); + Item.m_Rect.VSplitRight(200.0f, &Button2, &Item.m_Rect); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Player.x, Player.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Player.w; + TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aName, -1); + + TextRender()->SetCursor(&Cursor, Button.x,Button.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aClan, -1); + + //TextRender()->SetCursor(&Cursor, Button2.x,Button2.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + //Cursor.m_LineWidth = Button.w; + vec4 Color(1.0f, 1.0f, 1.0f, 0.5f); + m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[Index].m_Country, &Color, + Button2.x, Button2.y + Button2.h/2.0f - 0.75*Button2.h/2.0f, 1.5f*Button2.h, 0.75f*Button2.h); + + // ignore button + Item.m_Rect.HMargin(2.0f, &Item.m_Rect); + Item.m_Rect.VSplitLeft(Width, &Button, &Item.m_Rect); + Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); + Button.VSplitLeft(Button.h, &Button, 0); + if(g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[Index].m_Friend) + DoButton_Toggle(&s_aPlayerIDs[Index][0], 1, &Button, false); + else + if(DoButton_Toggle(&s_aPlayerIDs[Index][0], m_pClient->m_aClients[Index].m_ChatIgnore, &Button, true)) + m_pClient->m_aClients[Index].m_ChatIgnore ^= 1; + + // friend button + Item.m_Rect.VSplitLeft(20.0f, &Button, &Item.m_Rect); + Item.m_Rect.VSplitLeft(Width, &Button, &Item.m_Rect); + Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); + Button.VSplitLeft(Button.h, &Button, 0); + if(DoButton_Toggle(&s_aPlayerIDs[Index][1], m_pClient->m_aClients[Index].m_Friend, &Button, true)) + { + if(m_pClient->m_aClients[Index].m_Friend) + m_pClient->Friends()->RemoveFriend(m_pClient->m_aClients[Index].m_aName, m_pClient->m_aClients[Index].m_aClan); + else + m_pClient->Friends()->AddFriend(m_pClient->m_aClients[Index].m_aName, m_pClient->m_aClients[Index].m_aClan); + } + } + + UiDoListboxEnd(&s_ScrollValue, 0); + /* + CUIRect bars; + votearea.HSplitTop(10.0f, 0, &votearea); + votearea.HSplitTop(25.0f + 10.0f*3 + 25.0f, &votearea, &bars); + + RenderTools()->DrawUIRect(&votearea, color_tabbar_active, CUI::CORNER_ALL, 10.0f); + + votearea.VMargin(20.0f, &votearea); + votearea.HMargin(10.0f, &votearea); + + votearea.HSplitBottom(35.0f, &votearea, &bars); + + if(gameclient.voting->is_voting()) + { + // do yes button + votearea.VSplitLeft(50.0f, &button, &votearea); + static int yes_button = 0; + if(UI()->DoButton(&yes_button, "Yes", 0, &button, ui_draw_menu_button, 0)) + gameclient.voting->vote(1); + + // do no button + votearea.VSplitLeft(5.0f, 0, &votearea); + votearea.VSplitLeft(50.0f, &button, &votearea); + 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]; + str_format(buf, sizeof(buf), "%d", gameclient.voting->seconds_left()); + UI()->DoLabel(&button, buf, 24.0f, 0); + + // do description and command + votearea.VSplitLeft(5.0f, 0, &votearea); + UI()->DoLabel(&votearea, gameclient.voting->vote_description(), 14.0f, -1); + votearea.HSplitTop(16.0f, 0, &votearea); + UI()->DoLabel(&votearea, gameclient.voting->vote_command(), 10.0f, -1); + + // 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); + }*/ +} + +void CMenus::RenderServerInfo(CUIRect MainView) +{ + if(!m_pClient->m_Snap.m_pLocalInfo) + return; + + // 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, + sizeof(aBuf), + "%s\n\n" + "%s: %s\n" + "%s: %d\n" + "%s: %s\n" + "%s: %s\n", + CurrentServerInfo.m_aName, + Localize("Address"), CurrentServerInfo.m_aAddress, + Localize("Ping"), m_pClient->m_Snap.m_pLocalInfo->m_Latency, + 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); + ServerInfo.HSplitBottom(20.0f, &ServerInfo, &Button); + static int s_AddFavButton = 0; + if(DoButton_CheckBox(&s_AddFavButton, Localize("Favorite"), IsFavorite, &Button)) + { + if(IsFavorite) + ServerBrowser()->RemoveFavorite(CurrentServerInfo.m_NetAddr); + else + 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)); + str_format( + aBuf, + sizeof(aBuf), + "\n\n" + "%s: %s\n" + "%s: %s\n" + "%s: %d\n" + "%s: %d\n" + "\n" + "%s: %d/%d\n", + Localize("Game type"), CurrentServerInfo.m_aGameType, + Localize("Map"), CurrentServerInfo.m_aMap, + Localize("Score limit"), m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit, + Localize("Time limit"), m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit, + Localize("Players"), m_pClient->m_Snap.m_NumPlayers, CurrentServerInfo.m_MaxClients + ); + 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); + Motd.Margin(5.0f, &Motd); + y = 0.0f; + x = 5.0f; + TextRender()->Text(0, Motd.x+x, Motd.y+y, 32, Localize("MOTD"), -1); + y += 32.0f+5.0f; + TextRender()->Text(0, Motd.x+x, Motd.y+y, 16, m_pClient->m_pMotd->m_aServerMotd, (int)Motd.w); +} + +void CMenus::RenderServerControlServer(CUIRect MainView) +{ + static int s_VoteList = 0; + static float s_ScrollValue = 0; + CUIRect List = MainView; + int Total = m_pClient->m_pVoting->m_NumVoteOptions; + int NumVoteOptions = 0; + int aIndices[MAX_VOTE_OPTIONS]; + static int s_CurVoteOption = 0; + int TotalShown = 0; + + for(CVoteOptionClient *pOption = m_pClient->m_pVoting->m_pFirst; pOption; pOption = pOption->m_pNext) + { + if(m_aFilterString[0] != '\0' && !str_find_nocase(pOption->m_aDescription, m_aFilterString)) + continue; + TotalShown++; + } + +#if defined(__ANDROID__) + UiDoListboxStart(&s_VoteList, &List, 50.0f, "", "", TotalShown, 1, s_CurVoteOption, s_ScrollValue); +#else + UiDoListboxStart(&s_VoteList, &List, 24.0f, "", "", TotalShown, 1, s_CurVoteOption, s_ScrollValue); +#endif + + int i = -1; + for(CVoteOptionClient *pOption = m_pClient->m_pVoting->m_pFirst; pOption; pOption = pOption->m_pNext) + { + i++; + if(m_aFilterString[0] != '\0' && !str_find_nocase(pOption->m_aDescription, m_aFilterString)) + continue; + + CListboxItem Item = UiDoListboxNextItem(pOption); + + if(Item.m_Visible) + UI()->DoLabelScaled(&Item.m_Rect, pOption->m_aDescription, 16.0f, -1); + + if(NumVoteOptions < Total) + aIndices[NumVoteOptions] = i; + NumVoteOptions++; + } + + s_CurVoteOption = UiDoListboxEnd(&s_ScrollValue, 0); + if(s_CurVoteOption < Total) + m_CallvoteSelectedOption = aIndices[s_CurVoteOption]; +} + +void CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators) +{ + int NumOptions = 0; + int Selected = -1; + static int aPlayerIDs[MAX_CLIENTS]; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!m_pClient->m_Snap.m_paInfoByName[i]) + continue; + + int Index = m_pClient->m_Snap.m_paInfoByName[i]->m_ClientID; + if(Index == m_pClient->m_Snap.m_LocalClientID || (FilterSpectators && m_pClient->m_Snap.m_paInfoByName[i]->m_Team == TEAM_SPECTATORS)) + continue; + + if(!str_find_nocase(m_pClient->m_aClients[Index].m_aName, m_aFilterString)) + continue; + + if(m_CallvoteSelectedPlayer == Index) + Selected = NumOptions; + aPlayerIDs[NumOptions++] = Index; + } + + static int s_VoteList = 0; + static float s_ScrollValue = 0; + CUIRect List = MainView; +#if defined(__ANDROID__) + UiDoListboxStart(&s_VoteList, &List, 50.0f, "", "", NumOptions, 1, Selected, s_ScrollValue); +#else + UiDoListboxStart(&s_VoteList, &List, 24.0f, "", "", NumOptions, 1, Selected, s_ScrollValue); +#endif + + 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; + Info.m_Size = Item.m_Rect.h; + Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), vec2(Item.m_Rect.x+Item.m_Rect.h/2, Item.m_Rect.y+Item.m_Rect.h/2)); + Item.m_Rect.x +=Info.m_Size; + 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; +} + +void CMenus::RenderServerControl(CUIRect MainView) +{ + static int s_ControlPage = 0; + + // render background + CUIRect Bottom, Extended, TabBar, Button; +#if defined(__ANDROID__) + MainView.HSplitTop(50.0f, &Bottom, &MainView); +#else + MainView.HSplitTop(20.0f, &Bottom, &MainView); +#endif + RenderTools()->DrawUIRect(&Bottom, ms_ColorTabbarActive, CUI::CORNER_T, 10.0f); +#if defined(__ANDROID__) + MainView.HSplitTop(50.0f, &TabBar, &MainView); +#else + MainView.HSplitTop(20.0f, &TabBar, &MainView); +#endif + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_B, 10.0f); + MainView.Margin(10.0f, &MainView); +#if defined(__ANDROID__) + MainView.HSplitBottom(10.0f, &MainView, &Extended); +#else + MainView.HSplitBottom(90.0f, &MainView, &Extended); +#endif + + // tab bar + { + TabBar.VSplitLeft(TabBar.w/3, &Button, &TabBar); + static int s_Button0 = 0; + if(DoButton_MenuTab(&s_Button0, Localize("Change settings"), s_ControlPage == 0, &Button, 0)) + s_ControlPage = 0; + + TabBar.VSplitMid(&Button, &TabBar); + static int s_Button1 = 0; + if(DoButton_MenuTab(&s_Button1, Localize("Kick player"), s_ControlPage == 1, &Button, 0)) + s_ControlPage = 1; + + static int s_Button2 = 0; + if(DoButton_MenuTab(&s_Button2, Localize("Move player to spectators"), s_ControlPage == 2, &TabBar, 0)) + s_ControlPage = 2; + } + + // render page + MainView.HSplitBottom(ms_ButtonHeight + 5*2, &MainView, &Bottom); + Bottom.HMargin(5.0f, &Bottom); + + if(s_ControlPage == 0) + RenderServerControlServer(MainView); + else if(s_ControlPage == 1) + RenderServerControlKick(MainView, false); + else if(s_ControlPage == 2) + RenderServerControlKick(MainView, true); + + // vote menu + { + CUIRect Button, Button2, QuickSearch; + + // render quick search + { + Bottom.VSplitLeft(240.0f, &QuickSearch, &Bottom); + QuickSearch.HSplitTop(5.0f, 0, &QuickSearch); + const char *pSearchLabel = "⚲"; + UI()->DoLabelScaled(&QuickSearch, pSearchLabel, 14.0f, -1); + float wSearch = TextRender()->TextWidth(0, 14.0f, pSearchLabel, -1); + QuickSearch.VSplitLeft(wSearch, 0, &QuickSearch); + QuickSearch.VSplitLeft(5.0f, 0, &QuickSearch); + QuickSearch.VSplitLeft(QuickSearch.w-15.0f, &QuickSearch, &Button2); + static float Offset = 0.0f; + //static char aFilterString[25]; + if(DoEditBox(&m_aFilterString, &QuickSearch, m_aFilterString, sizeof(m_aFilterString), 14.0f, &Offset, false, CUI::CORNER_L, Localize("Search"))) { + // TODO: Implement here + } + + // clear button + { + static int s_ClearButton = 0; + RenderTools()->DrawUIRect(&Button2, vec4(1,1,1,0.33f)*ButtonColorMul(&s_ClearButton), CUI::CORNER_R, 3.0f); + UI()->DoLabel(&Button2, "×", Button2.h*ms_FontmodHeight, 0); + if(UI()->DoButtonLogic(&s_ClearButton, "×", 0, &Button2)) + { + m_aFilterString[0] = 0; + UI()->SetActiveItem(&m_aFilterString); + Client()->ServerBrowserUpdate(); + } + } + } + + Bottom.VSplitRight(120.0f, &Bottom, &Button); + + static int s_CallVoteButton = 0; + if(DoButton_Menu(&s_CallVoteButton, Localize("Call vote"), 0, &Button)) + { + if(s_ControlPage == 0) + m_pClient->m_pVoting->CallvoteOption(m_CallvoteSelectedOption, m_aCallvoteReason); + else if(s_ControlPage == 1) + { + if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && + m_pClient->m_Snap.m_paPlayerInfos[m_CallvoteSelectedPlayer]) + { + m_pClient->m_pVoting->CallvoteKick(m_CallvoteSelectedPlayer, m_aCallvoteReason); + SetActive(false); + } + } + else if(s_ControlPage == 2) + { + if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && + m_pClient->m_Snap.m_paPlayerInfos[m_CallvoteSelectedPlayer]) + { + m_pClient->m_pVoting->CallvoteSpectate(m_CallvoteSelectedPlayer, m_aCallvoteReason); + SetActive(false); + } + } + m_aCallvoteReason[0] = 0; + } + + // render kick reason + CUIRect Reason; + Bottom.VSplitRight(40.0f, &Bottom, 0); + Bottom.VSplitRight(160.0f, &Bottom, &Reason); + Reason.HSplitTop(5.0f, 0, &Reason); + const char *pLabel = Localize("Reason:"); + UI()->DoLabelScaled(&Reason, pLabel, 14.0f, -1); + float w = TextRender()->TextWidth(0, 14.0f, pLabel, -1); + 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()) + { + // background + Extended.Margin(10.0f, &Extended); + Extended.HSplitTop(20.0f, &Bottom, &Extended); + Extended.HSplitTop(5.0f, 0, &Extended); + + // force vote + Bottom.VSplitLeft(5.0f, 0, &Bottom); + Bottom.VSplitLeft(120.0f, &Button, &Bottom); + static int s_ForceVoteButton = 0; + if(DoButton_Menu(&s_ForceVoteButton, Localize("Force vote"), 0, &Button)) + { + if(s_ControlPage == 0) + m_pClient->m_pVoting->CallvoteOption(m_CallvoteSelectedOption, m_aCallvoteReason, true); + else if(s_ControlPage == 1) + { + if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && + m_pClient->m_Snap.m_paPlayerInfos[m_CallvoteSelectedPlayer]) + { + m_pClient->m_pVoting->CallvoteKick(m_CallvoteSelectedPlayer, m_aCallvoteReason, true); + SetActive(false); + } + } + else if(s_ControlPage == 2) + { + if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && + m_pClient->m_Snap.m_paPlayerInfos[m_CallvoteSelectedPlayer]) + { + m_pClient->m_pVoting->CallvoteSpectate(m_CallvoteSelectedPlayer, m_aCallvoteReason, true); + SetActive(false); + } + } + m_aCallvoteReason[0] = 0; + } + + if(s_ControlPage == 0) + { + // remove vote + Bottom.VSplitRight(10.0f, &Bottom, 0); + Bottom.VSplitRight(120.0f, 0, &Button); + 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); + Bottom.VSplitLeft(5.0f, 0, &Bottom); + Bottom.VSplitLeft(250.0f, &Button, &Bottom); + UI()->DoLabelScaled(&Button, Localize("Vote description:"), 14.0f, -1); + + Bottom.VSplitLeft(20.0f, 0, &Button); + UI()->DoLabelScaled(&Button, Localize("Vote command:"), 14.0f, -1); + + static char s_aVoteDescription[64] = {0}; + static char s_aVoteCommand[512] = {0}; + Extended.HSplitTop(20.0f, &Bottom, &Extended); + Bottom.VSplitRight(10.0f, &Bottom, 0); + Bottom.VSplitRight(120.0f, &Bottom, &Button); + static int s_AddVoteButton = 0; + if(DoButton_Menu(&s_AddVoteButton, Localize("Add"), 0, &Button)) + if(s_aVoteDescription[0] != 0 && s_aVoteCommand[0] != 0) + m_pClient->m_pVoting->AddvoteOption(s_aVoteDescription, s_aVoteCommand); + + Bottom.VSplitLeft(5.0f, 0, &Bottom); + Bottom.VSplitLeft(250.0f, &Button, &Bottom); + 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); + static float s_OffsetCmd = 0.0f; + DoEditBox(&s_aVoteCommand, &Button, s_aVoteCommand, sizeof(s_aVoteCommand), 14.0f, &s_OffsetCmd, false, CUI::CORNER_ALL); + } + } + } +} + +void CMenus::RenderInGameDDRace(CUIRect MainView) +{ + CUIRect Box = MainView; + CUIRect Button; + + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + + Box.HSplitTop(5.0f, &MainView, &MainView); + Box.HSplitTop(24.0f, &Box, &MainView); + Box.VMargin(20.0f, &Box); + + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_BrwoserButton=0; + if(DoButton_MenuTab(&s_BrwoserButton, Localize("Browser"), m_DDRacePage==PAGE_BROWSER, &Button, CUI::CORNER_TL)) + { + m_DDRacePage = PAGE_BROWSER; + } + + //Box.VSplitLeft(4.0f, 0, &Box); + Box.VSplitLeft(80.0f, &Button, &Box); + static int s_GhostButton=0; + if(DoButton_MenuTab(&s_GhostButton, Localize("Ghost"), m_DDRacePage==PAGE_GHOST, &Button, 0)) + { + m_DDRacePage = PAGE_GHOST; + } + + if(m_DDRacePage != -1) + { + if(m_DDRacePage == PAGE_GHOST) + RenderGhost(MainView); + else + RenderInGameBrowser(MainView); + } + + return; +} + +void CMenus::RenderInGameBrowser(CUIRect MainView) +{ + CUIRect Box = MainView; + CUIRect Button; + + int Page = g_Config.m_UiPage; + int NewPage = -1; + + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_ALL, 10.0f); + + Box.HSplitTop(5.0f, &MainView, &MainView); + Box.HSplitTop(24.0f, &Box, &MainView); + Box.VMargin(20.0f, &Box); + + Box.VSplitLeft(100.0f, &Button, &Box); + static int s_InternetButton=0; + if(DoButton_MenuTab(&s_InternetButton, Localize("Internet"), Page==PAGE_INTERNET, &Button, CUI::CORNER_TL)) + { + if (Page != PAGE_INTERNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); + NewPage = PAGE_INTERNET; + } + + Box.VSplitLeft(80.0f, &Button, &Box); + static int s_LanButton=0; + if(DoButton_MenuTab(&s_LanButton, Localize("LAN"), Page==PAGE_LAN, &Button, 0)) + { + if (Page != PAGE_LAN) + ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); + NewPage = PAGE_LAN; + } + + Box.VSplitLeft(110.0f, &Button, &Box); + static int s_FavoritesButton=0; + if(DoButton_MenuTab(&s_FavoritesButton, Localize("Favorites"), Page==PAGE_FAVORITES, &Button, 0)) + { + if (Page != PAGE_FAVORITES) + ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES); + NewPage = PAGE_FAVORITES; + } + + Box.VSplitLeft(110.0f, &Button, &Box); + static int s_DDNetButton=0; + if(DoButton_MenuTab(&s_DDNetButton, Localize("DDNet"), Page==PAGE_DDNET, &Button, CUI::CORNER_TR)) + { + if (Page != PAGE_DDNET) + ServerBrowser()->Refresh(IServerBrowser::TYPE_DDNET); + NewPage = PAGE_DDNET; + } + + if(NewPage != -1) + { + if(Client()->State() != IClient::STATE_OFFLINE) + g_Config.m_UiPage = NewPage; + } + + RenderServerbrowser(MainView); + return; +} + +// ghost stuff +int CMenus::GhostlistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser) +{ + CMenus *pSelf = (CMenus *)pUser; + int Length = str_length(pName); + if((pName[0] == '.' && (pName[1] == 0 || + (pName[1] == '.' && pName[2] == 0))) || + (!IsDir && (Length < 4 || str_comp(pName+Length-4, ".gho")))) + return 0; + + CGhost::CGhostHeader Header; + if(!pSelf->m_pClient->m_pGhost->GetInfo(pName, &Header)) + return 0; + + CGhostItem Item; + str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename)); + str_copy(Item.m_aPlayer, Header.m_aOwner, sizeof(Item.m_aPlayer)); + Item.m_Time = Header.m_Time; + Item.m_Active = false; + Item.m_ID = pSelf->m_lGhosts.add(Item); + + return 0; +} + +void CMenus::GhostlistPopulate() +{ + m_OwnGhost = 0; + m_lGhosts.clear(); + Storage()->ListDirectory(IStorage::TYPE_ALL, "ghosts", GhostlistFetchCallback, this); + + for(int i = 0; i < m_lGhosts.size(); i++) + { + if(str_comp(m_lGhosts[i].m_aPlayer, g_Config.m_PlayerName) == 0 && (!m_OwnGhost || m_lGhosts[i] < *m_OwnGhost)) + m_OwnGhost = &m_lGhosts[i]; + } + + if(m_OwnGhost) + { + m_OwnGhost->m_ID = -1; + m_OwnGhost->m_Active = true; + m_pClient->m_pGhost->Load(m_OwnGhost->m_aFilename, -1); + } +} + +void CMenus::RenderGhost(CUIRect MainView) +{ + // render background + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_B|CUI::CORNER_TL, 10.0f); + + MainView.HSplitTop(10.0f, 0, &MainView); + MainView.HSplitBottom(5.0f, &MainView, 0); + MainView.VSplitLeft(5.0f, 0, &MainView); + MainView.VSplitRight(5.0f, &MainView, 0); + + CUIRect Headers, Status; + CUIRect View = MainView; + + View.HSplitTop(17.0f, &Headers, &View); + View.HSplitBottom(28.0f, &View, &Status); + + // split of the scrollbar + RenderTools()->DrawUIRect(&Headers, vec4(1,1,1,0.25f), CUI::CORNER_T, 5.0f); + Headers.VSplitRight(20.0f, &Headers, 0); + + struct CColumn + { + int m_Id; + CLocConstString m_Caption; + float m_Width; + CUIRect m_Rect; + CUIRect m_Spacer; + }; + + enum + { + COL_ACTIVE=0, + COL_NAME, + COL_TIME, + }; + + static CColumn s_aCols[] = { + {-1, " ", 2.0f, {0}, {0}}, + {COL_ACTIVE, " ", 30.0f, {0}, {0}}, + {COL_NAME, "Name", 300.0f, {0}, {0}}, + {COL_TIME, "Time", 200.0f, {0}, {0}}, + }; + + int NumCols = sizeof(s_aCols)/sizeof(CColumn); + + // do layout + for(int i = 0; i < NumCols; i++) + { + Headers.VSplitLeft(s_aCols[i].m_Width, &s_aCols[i].m_Rect, &Headers); + + if(i+1 < NumCols) + Headers.VSplitLeft(2, &s_aCols[i].m_Spacer, &Headers); + } + + // do headers + for(int i = 0; i < NumCols; i++) + DoButton_GridHeader(s_aCols[i].m_Caption, s_aCols[i].m_Caption, 0, &s_aCols[i].m_Rect); + + RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.15f), 0, 0); + + CUIRect Scroll; + View.VSplitRight(15, &View, &Scroll); + + int NumGhosts = m_lGhosts.size(); + + int Num = (int)(View.h/s_aCols[0].m_Rect.h) + 1; + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + int ScrollNum = NumGhosts-Num+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue -= 1.0f/ScrollNum; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue += 1.0f/ScrollNum; + } + else + ScrollNum = 0; + + static int s_SelectedIndex = 0; + for(int i = 0; i < m_NumInputEvents; i++) + { + int NewIndex = -1; + if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) + { + if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = s_SelectedIndex + 1; + if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = s_SelectedIndex - 1; + } + if(NewIndex > -1 && NewIndex < NumGhosts) + { + //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 < 0) + { + int NumScrolls = (View.y-IndexY+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; + } + else + { + int NumScrolls = (IndexY+s_aCols[0].m_Rect.h-(View.y+View.h)+s_aCols[0].m_Rect.h-1.0f)/s_aCols[0].m_Rect.h; + s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; + } + } + + s_SelectedIndex = NewIndex; + } + } + + if(s_ScrollValue < 0) s_ScrollValue = 0; + if(s_ScrollValue > 1) s_ScrollValue = 1; + + // set clipping + UI()->ClipEnable(&View); + + CUIRect OriginalView = View; + View.y -= s_ScrollValue*ScrollNum*s_aCols[0].m_Rect.h; + + int NewSelected = -1; + + for (int i = 0; i < NumGhosts; i++) + { + const CGhostItem *pItem = &m_lGhosts[i]; + CUIRect Row; + CUIRect SelectHitBox; + + View.HSplitTop(17.0f, &Row, &View); + SelectHitBox = Row; + + // make sure that only those in view can be selected + if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) + { + if(i == s_SelectedIndex) + { + CUIRect r = Row; + r.Margin(1.5f, &r); + RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 4.0f); + } + + // clip the selection + if(SelectHitBox.y < OriginalView.y) // top + { + SelectHitBox.h -= OriginalView.y-SelectHitBox.y; + SelectHitBox.y = OriginalView.y; + } + else if(SelectHitBox.y+SelectHitBox.h > OriginalView.y+OriginalView.h) // bottom + SelectHitBox.h = OriginalView.y+OriginalView.h-SelectHitBox.y; + + if(UI()->DoButtonLogic(pItem, "", 0, &SelectHitBox)) + { + NewSelected = i; + } + } + + for(int c = 0; c < NumCols; c++) + { + CUIRect Button; + Button.x = s_aCols[c].m_Rect.x; + Button.y = Row.y; + Button.h = Row.h; + Button.w = s_aCols[c].m_Rect.w; + + int Id = s_aCols[c].m_Id; + + if(Id == COL_ACTIVE) + { + if(pItem->m_Active) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(SPRITE_OOP + 7); + IGraphics::CQuadItem QuadItem(Button.x+Button.w/2, Button.y+Button.h/2, 20.0f, 20.0f); + Graphics()->QuadsDraw(&QuadItem, 1); + + Graphics()->QuadsEnd(); + } + } + else if(Id == COL_NAME) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + char aBuf[128]; + bool Own = m_OwnGhost && pItem == m_OwnGhost; + str_format(aBuf, sizeof(aBuf), "%s%s", pItem->m_aPlayer, Own?" (own)":""); + TextRender()->TextEx(&Cursor, aBuf, -1); + } + else if(Id == COL_TIME) + { + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f * UI()->Scale(), TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = Button.w; + + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%02d:%06.3f", (int)pItem->m_Time/60, pItem->m_Time-((int)pItem->m_Time/60*60)); + TextRender()->TextEx(&Cursor, aBuf, -1); + } + } + } + + if(NewSelected != -1) + s_SelectedIndex = NewSelected; + + CGhostItem *pGhost = &m_lGhosts[s_SelectedIndex]; + + UI()->ClipDisable(); + + RenderTools()->DrawUIRect(&Status, vec4(1,1,1,0.25f), CUI::CORNER_B, 5.0f); + Status.Margin(5.0f, &Status); + + CUIRect Button; + Status.VSplitRight(120.0f, &Status, &Button); + + static int s_GhostButton = 0; + const char *pText = pGhost->m_Active ? "Deactivate" : "Activate"; + + if(DoButton_Menu(&s_GhostButton, Localize(pText), 0, &Button) || (NewSelected != -1 && Input()->MouseDoubleClick())) + { + if(pGhost->m_Active) + m_pClient->m_pGhost->Unload(pGhost->m_ID); + else + m_pClient->m_pGhost->Load(pGhost->m_aFilename, pGhost->m_ID); + pGhost->m_Active ^= 1; + } +} diff --git a/src/game/client/components/menus_settings.cpp b/src/game/client/components/menus_settings.cpp new file mode 100644 index 0000000..5b7967b --- /dev/null +++ b/src/game/client/components/menus_settings.cpp @@ -0,0 +1,1990 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/string.h> + +#include <base/math.h> + +#include <engine/engine.h> +#include <engine/graphics.h> +#include <engine/storage.h> +#include <engine/textrender.h> +#include <engine/updater.h> +#include <engine/shared/config.h> +#include <engine/shared/linereader.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/client/components/sounds.h> +#include <game/client/ui.h> +#include <game/client/render.h> +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include <game/localization.h> + +#include "binds.h" +#include "camera.h" +#include "countryflags.h" +#include "menus.h" +#include "skins.h" + +CMenusKeyBinder CMenus::m_Binder; + +CMenusKeyBinder::CMenusKeyBinder() +{ + m_TakeKey = false; + m_GotKey = false; +} + +bool CMenusKeyBinder::OnInput(IInput::CEvent Event) +{ + if(m_TakeKey) + { + if(Event.m_Flags&IInput::FLAG_PRESS) + { + m_Key = Event; + m_GotKey = true; + m_TakeKey = false; + } + return true; + } + + return false; +} + +void CMenus::RenderSettingsGeneral(CUIRect MainView) +{ + char aBuf[128]; + CUIRect Label, Button, Left, Right, Game, Client, AutoReconnect; + MainView.HSplitTop(180.0f, &Game, &Client); + Client.HSplitTop(160.0f, &Client, &AutoReconnect); + + // game + { + // headline + Game.HSplitTop(30.0f, &Label, &Game); + UI()->DoLabelScaled(&Label, Localize("Game"), 20.0f, -1); + Game.Margin(5.0f, &Game); + Game.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + // dynamic camera + Left.HSplitTop(20.0f, &Button, &Left); + static int s_DynamicCameraButton = 0; + if(DoButton_CheckBox(&s_DynamicCameraButton, Localize("Dynamic Camera"), g_Config.m_ClMouseDeadzone != 0, &Button)) + { + if(g_Config.m_ClMouseDeadzone) + { + g_Config.m_ClMouseFollowfactor = 0; + g_Config.m_ClMouseMaxDistance = 400; + g_Config.m_ClMouseDeadzone = 0; + } + else + { + g_Config.m_ClMouseFollowfactor = 60; + g_Config.m_ClMouseMaxDistance = 1000; + g_Config.m_ClMouseDeadzone = 300; + } + } + + // weapon pickup + Left.HSplitTop(5.0f, 0, &Left); + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClAutoswitchWeapons, Localize("Switch weapon on pickup"), g_Config.m_ClAutoswitchWeapons, &Button)) + g_Config.m_ClAutoswitchWeapons ^= 1; + + // weapon out of ammo autoswitch + Left.HSplitTop(5.0f, 0, &Left); + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClAutoswitchWeaponsOutOfAmmo, Localize("Switch weapon when out of ammo"), g_Config.m_ClAutoswitchWeaponsOutOfAmmo, &Button)) + g_Config.m_ClAutoswitchWeaponsOutOfAmmo ^= 1; + + // weapon reset on death + Left.HSplitTop(5.0f, 0, &Left); + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClResetWantedWeaponOnDeath, Localize("Reset wanted weapon on death"), g_Config.m_ClResetWantedWeaponOnDeath, &Button)) + g_Config.m_ClResetWantedWeaponOnDeath ^= 1; + + // chat messages + Right.HSplitTop(5.0f, 0, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClShowChatFriends, Localize("Show only chat messages from friends"), g_Config.m_ClShowChatFriends, &Button)) + g_Config.m_ClShowChatFriends ^= 1; + + // name plates + Right.HSplitTop(5.0f, 0, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClNameplates, Localize("Show name plates"), g_Config.m_ClNameplates, &Button)) + g_Config.m_ClNameplates ^= 1; + + if(g_Config.m_ClNameplates) + { + Right.HSplitTop(2.5f, 0, &Right); + Right.HSplitTop(20.0f, &Label, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Name plates size"), g_Config.m_ClNameplatesSize); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Button.HMargin(2.0f, &Button); + g_Config.m_ClNameplatesSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesSize, &Button, g_Config.m_ClNameplatesSize/100.0f)*100.0f+0.1f); + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClNameplatesTeamcolors, Localize("Use team colors for name plates"), g_Config.m_ClNameplatesTeamcolors, &Button)) + g_Config.m_ClNameplatesTeamcolors ^= 1; + + Right.HSplitTop(5.0f, 0, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClNameplatesClan, Localize("Show clan above name plates"), g_Config.m_ClNameplatesClan, &Button)) + g_Config.m_ClNameplatesClan ^= 1; + } + + if(g_Config.m_ClNameplatesClan) + { + Right.HSplitTop(2.5f, 0, &Right); + Right.HSplitTop(20.0f, &Label, &Right); + Right.HSplitTop(20.0f, &Button, &Right); + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Clan plates size"), g_Config.m_ClNameplatesClanSize); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Button.HMargin(2.0f, &Button); + g_Config.m_ClNameplatesClanSize = (int)(DoScrollbarH(&g_Config.m_ClNameplatesClanSize, &Button, g_Config.m_ClNameplatesClanSize/100.0f)*100.0f+0.1f); + } + } + + // client + { + // headline + Client.HSplitTop(30.0f, &Label, &Client); + UI()->DoLabelScaled(&Label, Localize("Client"), 20.0f, -1); + Client.Margin(5.0f, &Client); + Client.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + // auto demo settings + { + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClAutoDemoRecord, Localize("Automatically record demos"), g_Config.m_ClAutoDemoRecord, &Button)) + g_Config.m_ClAutoDemoRecord ^= 1; + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAutoScreenshot, Localize("Automatically take game over screenshot"), g_Config.m_ClAutoScreenshot, &Button)) + g_Config.m_ClAutoScreenshot ^= 1; + + Left.HSplitTop(10.0f, 0, &Left); + Left.HSplitTop(20.0f, &Label, &Left); + Button.VSplitRight(20.0f, &Button, 0); + char aBuf[64]; + if(g_Config.m_ClAutoDemoMax) + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Max demos"), g_Config.m_ClAutoDemoMax); + else + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Max demos"), Localize("no limit")); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Left.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClAutoDemoMax = static_cast<int>(DoScrollbarH(&g_Config.m_ClAutoDemoMax, &Button, g_Config.m_ClAutoDemoMax/1000.0f)*1000.0f+0.1f); + + Right.HSplitTop(10.0f, 0, &Right); + Right.HSplitTop(20.0f, &Label, &Right); + Button.VSplitRight(20.0f, &Button, 0); + if(g_Config.m_ClAutoScreenshotMax) + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Max Screenshots"), g_Config.m_ClAutoScreenshotMax); + else + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Max Screenshots"), Localize("no limit")); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Right.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClAutoScreenshotMax = static_cast<int>(DoScrollbarH(&g_Config.m_ClAutoScreenshotMax, &Button, g_Config.m_ClAutoScreenshotMax/1000.0f)*1000.0f+0.1f); + } + + Left.HSplitTop(20.0f, 0, &Left); + Left.HSplitTop(20.0f, &Label, &Left); + Button.VSplitRight(20.0f, &Button, 0); + char aBuf[64]; + if(g_Config.m_ClCpuThrottle) + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("CPU Throttle"), g_Config.m_ClCpuThrottle); + else + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("CPU Throttle"), Localize("none")); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Left.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClCpuThrottle= static_cast<int>(DoScrollbarH(&g_Config.m_ClCpuThrottle, &Button, g_Config.m_ClCpuThrottle/100.0f)*100.0f+0.1f); + +#if defined(CONF_FAMILY_WINDOWS) + Left.HSplitTop(20.0f, 0, &Left); + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClShowConsole, Localize("Show console window"), g_Config.m_ClShowConsole, &Button)) + g_Config.m_ClShowConsole ^= 1; +#endif + + // auto statboard screenshot + { + Right.HSplitTop(20.0f, 0, &Right); // + Right.HSplitTop(20.0f, 0, &Right); // Make some distance so it looks more natural + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAutoStatboardScreenshot, + Localize("Automatically take statboard screenshot"), + g_Config.m_ClAutoStatboardScreenshot, &Button)) + { + g_Config.m_ClAutoStatboardScreenshot ^= 1; + } + + Right.HSplitTop(10.0f, 0, &Right); + Right.HSplitTop(20.0f, &Label, &Right); + Button.VSplitRight(20.0f, &Button, 0); + if(g_Config.m_ClAutoStatboardScreenshotMax) + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Max Screenshots"), g_Config.m_ClAutoStatboardScreenshotMax); + else + str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Max Screenshots"), Localize("no limit")); + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Right.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClAutoStatboardScreenshotMax = + static_cast<int>(DoScrollbarH(&g_Config.m_ClAutoStatboardScreenshotMax, + &Button, + g_Config.m_ClAutoStatboardScreenshotMax/1000.0f)*1000.0f+0.1f); + } + } +} + +void CMenus::RenderSettingsPlayer(CUIRect MainView) +{ + CUIRect Button, Label, Dummy; + MainView.HSplitTop(10.0f, 0, &MainView); + + char *Name = g_Config.m_PlayerName; + char *Clan = g_Config.m_PlayerClan; + int *Country = &g_Config.m_PlayerCountry; + + if(m_Dummy) + { + Name = g_Config.m_ClDummyName; + Clan = g_Config.m_ClDummyClan; + Country = &g_Config.m_ClDummyCountry; + } + + // player name + MainView.HSplitTop(20.0f, &Button, &MainView); + Button.VSplitLeft(80.0f, &Label, &Button); + Button.VSplitLeft(200.0f, &Button, &Dummy); + Button.VSplitLeft(150.0f, &Button, 0); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Name")); + UI()->DoLabelScaled(&Label, aBuf, 14.0, -1); + static float s_OffsetName = 0.0f; + if(DoEditBox(Name, &Button, Name, sizeof(g_Config.m_PlayerName), 14.0f, &s_OffsetName)) + { + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } + + if(DoButton_CheckBox(&g_Config.m_ClShowKillMessages, Localize("Dummy settings"), m_Dummy, &Dummy)) + { + m_Dummy ^= 1; + } + + // player clan + MainView.HSplitTop(5.0f, 0, &MainView); + MainView.HSplitTop(20.0f, &Button, &MainView); + Button.VSplitLeft(80.0f, &Label, &Button); + Button.VSplitLeft(150.0f, &Button, 0); + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Clan")); + UI()->DoLabelScaled(&Label, aBuf, 14.0, -1); + static float s_OffsetClan = 0.0f; + if(DoEditBox(Clan, &Button, Clan, sizeof(g_Config.m_PlayerClan), 14.0f, &s_OffsetClan)) + { + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } + + // country flag selector + MainView.HSplitTop(20.0f, 0, &MainView); + static float s_ScrollValue = 0.0f; + int OldSelected = -1; + UiDoListboxStart(&s_ScrollValue, &MainView, 50.0f, Localize("Country"), "", m_pClient->m_pCountryFlags->Num(), 6, OldSelected, s_ScrollValue); + + for(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i) + { + const CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i); + if(pEntry->m_CountryCode == *Country) + OldSelected = i; + + CListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i); + if(Item.m_Visible) + { + CUIRect Label; + Item.m_Rect.Margin(5.0f, &Item.m_Rect); + Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label); + float OldWidth = Item.m_Rect.w; + Item.m_Rect.w = Item.m_Rect.h*2; + Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f; + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + m_pClient->m_pCountryFlags->Render(pEntry->m_CountryCode, &Color, Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h); + if(pEntry->m_Texture != -1) + UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); + } + } + + const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); + if(OldSelected != NewSelected) + { + *Country = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode; + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } +} + +void CMenus::RenderSettingsTee(CUIRect MainView) +{ + CUIRect Button, Label, Button2, Dummy, DummyLabel, SkinList, QuickSearch, QuickSearchClearButton; + static bool s_InitSkinlist = true; + MainView.HSplitTop(10.0f, 0, &MainView); + + char *Skin = g_Config.m_ClPlayerSkin; + int *UseCustomColor = &g_Config.m_ClPlayerUseCustomColor; + int *ColorBody = &g_Config.m_ClPlayerColorBody; + int *ColorFeet = &g_Config.m_ClPlayerColorFeet; + + if(m_Dummy) + { + Skin = g_Config.m_ClDummySkin; + UseCustomColor = &g_Config.m_ClDummyUseCustomColor; + ColorBody = &g_Config.m_ClDummyColorBody; + ColorFeet = &g_Config.m_ClDummyColorFeet; + } + + // skin info + const CSkins::CSkin *pOwnSkin = m_pClient->m_pSkins->Get(m_pClient->m_pSkins->Find(Skin)); + CTeeRenderInfo OwnSkinInfo; + if(*UseCustomColor) + { + OwnSkinInfo.m_Texture = pOwnSkin->m_ColorTexture; + OwnSkinInfo.m_ColorBody = m_pClient->m_pSkins->GetColorV4(*ColorBody); + OwnSkinInfo.m_ColorFeet = m_pClient->m_pSkins->GetColorV4(*ColorFeet); + } + else + { + OwnSkinInfo.m_Texture = pOwnSkin->m_OrgTexture; + OwnSkinInfo.m_ColorBody = vec4(1.0f, 1.0f, 1.0f, 1.0f); + OwnSkinInfo.m_ColorFeet = vec4(1.0f, 1.0f, 1.0f, 1.0f); + } + OwnSkinInfo.m_Size = 50.0f*UI()->Scale(); + + MainView.HSplitTop(20.0f, &Label, &MainView); + Label.VSplitLeft(280.0f, &Label, &Dummy); + Label.VSplitLeft(230.0f, &Label, 0); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Your skin")); + UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); + + Dummy.HSplitTop(20.0f, &DummyLabel, &Dummy); + + if(DoButton_CheckBox(&g_Config.m_ClShowKillMessages, Localize("Dummy settings"), m_Dummy, &DummyLabel)) + { + m_Dummy ^= 1; + } + + Dummy.HSplitTop(20.0f, &DummyLabel, &Dummy); + + if(DoButton_CheckBox(&g_Config.m_ClVanillaSkinsOnly, Localize("Vanilla Skins only"), g_Config.m_ClVanillaSkinsOnly, &DummyLabel)) + { + g_Config.m_ClVanillaSkinsOnly ^= 1; + m_NeedRestartSkins = true; + } + + Dummy.HSplitTop(20.0f, &DummyLabel, &Dummy); + + MainView.HSplitTop(50.0f, &Label, &MainView); + Label.VSplitLeft(230.0f, &Label, 0); + RenderTools()->DrawUIRect(&Label, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); + 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, Skin, 14.0f, -1, 150.0f); + + // custom colour selector + MainView.HSplitTop(20.0f, 0, &MainView); + MainView.HSplitTop(20.0f, &Button, &MainView); + Button.VSplitMid(&Button, &Button2); + if(DoButton_CheckBox(&ColorBody, Localize("Custom colors"), *UseCustomColor, &Button)) + { + *UseCustomColor = *UseCustomColor?0:1; + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } + + MainView.HSplitTop(5.0f, 0, &MainView); + MainView.HSplitTop(82.5f, &Label, &MainView); + if(*UseCustomColor) + { + CUIRect aRects[2]; + Label.VSplitMid(&aRects[0], &aRects[1]); + aRects[0].VSplitRight(10.0f, &aRects[0], 0); + aRects[1].VSplitLeft(10.0f, 0, &aRects[1]); + + int *paColors[2]; + paColors[0] = ColorBody; + paColors[1] = ColorFeet; + + const char *paParts[] = { + Localize("Body"), + Localize("Feet")}; + const char *paLabels[] = { + Localize("Hue"), + Localize("Sat."), + Localize("Lht.")}; + static int s_aColorSlider[2][3] = {{0}}; + + for(int i = 0; i < 2; i++) + { + aRects[i].HSplitTop(20.0f, &Label, &aRects[i]); + UI()->DoLabelScaled(&Label, paParts[i], 14.0f, -1); + aRects[i].VSplitLeft(20.0f, 0, &aRects[i]); + aRects[i].HSplitTop(2.5f, 0, &aRects[i]); + + int PrevColor = *paColors[i]; + int Color = 0; + for(int s = 0; s < 3; s++) + { + aRects[i].HSplitTop(20.0f, &Label, &aRects[i]); + Label.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + + 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); + UI()->DoLabelScaled(&Label, paLabels[s], 14.0f, -1); + } + + if(PrevColor != Color) + { + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } + + *paColors[i] = Color; + } + } + + // skin selector + MainView.HSplitTop(20.0f, 0, &MainView); + MainView.HSplitTop(230.0f, &SkinList, &MainView); + static sorted_array<const CSkins::CSkin *> s_paSkinList; + static float s_ScrollValue = 0.0f; + if(s_InitSkinlist) + { + s_paSkinList.clear(); + for(int i = 0; i < m_pClient->m_pSkins->Num(); ++i) + { + const CSkins::CSkin *s = m_pClient->m_pSkins->Get(i); + + // filter quick search + if(g_Config.m_ClSkinFilterString[0] != '\0' && !str_find_nocase(s->m_aName, g_Config.m_ClSkinFilterString)) + continue; + + // no special skins + if((s->m_aName[0] == 'x' && s->m_aName[1] == '_')) + continue; + + s_paSkinList.add(s); + } + s_InitSkinlist = false; + } + + int OldSelected = -1; + UiDoListboxStart(&s_InitSkinlist, &SkinList, 50.0f, Localize("Skins"), "", s_paSkinList.size(), 4, OldSelected, s_ScrollValue); + for(int i = 0; i < s_paSkinList.size(); ++i) + { + const CSkins::CSkin *s = s_paSkinList[i]; + if(s == 0) + continue; + + if(str_comp(s->m_aName, Skin) == 0) + OldSelected = i; + + CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i); + char aBuf[128]; + if(Item.m_Visible) + { + CTeeRenderInfo Info; + if(*UseCustomColor) + { + Info.m_Texture = s->m_ColorTexture; + Info.m_ColorBody = m_pClient->m_pSkins->GetColorV4(*ColorBody); + Info.m_ColorFeet = m_pClient->m_pSkins->GetColorV4(*ColorFeet); + } + else + { + Info.m_Texture = s->m_OrgTexture; + Info.m_ColorBody = vec4(1.0f, 1.0f, 1.0f, 1.0f); + Info.m_ColorFeet = vec4(1.0f, 1.0f, 1.0f, 1.0f); + } + + Info.m_Size = UI()->Scale()*50.0f; + Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top + RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+30, Item.m_Rect.y+Item.m_Rect.h/2)); + + + Item.m_Rect.VSplitLeft(60.0f, 0, &Item.m_Rect); + Item.m_Rect.HSplitTop(10.0f, 0, &Item.m_Rect); + str_format(aBuf, sizeof(aBuf), "%s", s->m_aName); + RenderTools()->UI()->DoLabelScaled(&Item.m_Rect, aBuf, 12.0f, -1,Item.m_Rect.w); + if(g_Config.m_Debug) + { + vec3 BloodColor = *UseCustomColor ? m_pClient->m_pSkins->GetColorV3(*ColorBody) : s->m_BloodColor; + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(BloodColor.r, BloodColor.g, BloodColor.b, 1.0f); + IGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, 12.0f, 12.0f); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + } + } + + const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); + if(OldSelected != NewSelected) + { + mem_copy(Skin, s_paSkinList[NewSelected]->m_aName, sizeof(g_Config.m_ClPlayerSkin)); + if(m_Dummy) + m_NeedSendDummyinfo = true; + else + m_NeedSendinfo = true; + } + + // render quick search + { + MainView.HSplitBottom(ms_ButtonHeight, &MainView, &QuickSearch); + QuickSearch.VSplitLeft(240.0f, &QuickSearch, 0); + QuickSearch.HSplitTop(5.0f, 0, &QuickSearch); + const char *pSearchLabel = "⚲"; + UI()->DoLabelScaled(&QuickSearch, pSearchLabel, 14.0f, -1); + float wSearch = TextRender()->TextWidth(0, 14.0f, pSearchLabel, -1); + QuickSearch.VSplitLeft(wSearch, 0, &QuickSearch); + QuickSearch.VSplitLeft(5.0f, 0, &QuickSearch); + QuickSearch.VSplitLeft(QuickSearch.w-15.0f, &QuickSearch, &QuickSearchClearButton); + static float Offset = 0.0f; + if(DoEditBox(&g_Config.m_ClSkinFilterString, &QuickSearch, g_Config.m_ClSkinFilterString, sizeof(g_Config.m_ClSkinFilterString), 14.0f, &Offset, false, CUI::CORNER_L, Localize("Search"))) + s_InitSkinlist = true; + + // clear button + { + static int s_ClearButton = 0; + RenderTools()->DrawUIRect(&QuickSearchClearButton, vec4(1,1,1,0.33f)*ButtonColorMul(&s_ClearButton), CUI::CORNER_R, 3.0f); + UI()->DoLabel(&QuickSearchClearButton, "×", QuickSearchClearButton.h*ms_FontmodHeight, 0); + if(UI()->DoButtonLogic(&s_ClearButton, "×", 0, &QuickSearchClearButton)) + { + g_Config.m_ClSkinFilterString[0] = 0; + UI()->SetActiveItem(&g_Config.m_ClSkinFilterString); + s_InitSkinlist = true; + } + } + } +} + + +typedef void (*pfnAssignFuncCallback)(CConfiguration *pConfig, int Value); + +typedef struct +{ + CLocConstString m_Name; + const char *m_pCommand; + int m_KeyId; +} CKeyInfo; + +static CKeyInfo gs_aKeys[] = +{ + { "Move left", "+left", 0}, // Localize - these strings are localized within CLocConstString + { "Move right", "+right", 0 }, + { "Jump", "+jump", 0 }, + { "Fire", "+fire", 0 }, + { "Hook", "+hook", 0 }, + { "Hook Collisions", "+showhookcoll", 0 }, + { "Toggle DynCam", "toggle cl_dyncam 0 1", 0 }, + { "Hammer", "+weapon1", 0 }, + { "Pistol", "+weapon2", 0 }, + { "Shotgun", "+weapon3", 0 }, + { "Grenade", "+weapon4", 0 }, + { "Rifle", "+weapon5", 0 }, + { "Next weapon", "+nextweapon", 0 }, + { "Prev. weapon", "+prevweapon", 0 }, + { "Vote yes", "vote yes", 0 }, + { "Vote no", "vote no", 0 }, + { "Chat", "+show_chat; chat all", 0 }, + { "Team chat", "+show_chat; chat team", 0 }, + { "Converse", "+show_chat; chat all /c ", 0 }, + { "Show chat", "+show_chat", 0 }, + { "Emoticon", "+emote", 0 }, + { "Spectator mode", "+spectate", 0 }, + { "Spectate next", "spectate_next", 0 }, + { "Spectate previous", "spectate_previous", 0 }, + { "Console", "toggle_local_console", 0 }, + { "Remote console", "toggle_remote_console", 0 }, + { "Screenshot", "screenshot", 0 }, + { "Scoreboard", "+scoreboard", 0 }, + { "Statboard", "+statboard", 0 }, + { "Respawn", "kill", 0 }, + { "Toggle Dummy", "toggle cl_dummy 0 1", 0 }, + { "Dummy Copy", "toggle cl_dummy_copy_moves 0 1", 0 }, + { "Hammerfly Dummy", "toggle cl_dummy_hammer 0 1", 0 }, +}; + +/* This is for scripts/update_localization.py to work, don't remove! + Localize("Move left");Localize("Move right");Localize("Jump");Localize("Fire");Localize("Hook");Localize("Hammer"); + Localize("Pistol");Localize("Shotgun");Localize("Grenade");Localize("Rifle");Localize("Next weapon");Localize("Prev. weapon"); + Localize("Vote yes");Localize("Vote no");Localize("Chat");Localize("Team chat");Localize("Show chat");Localize("Emoticon"); + Localize("Spectator mode");Localize("Spectate next");Localize("Spectate previous");Localize("Console");Localize("Remote console");Localize("Screenshot");Localize("Scoreboard");Localize("Respawn"); +*/ + +const int g_KeyCount = sizeof(gs_aKeys) / sizeof(CKeyInfo); + +void CMenus::UiDoGetButtons(int Start, int Stop, CUIRect View) +{ + for (int i = Start; i < Stop; i++) + { + CKeyInfo &Key = gs_aKeys[i]; + CUIRect Button, Label; + View.HSplitTop(20.0f, &Button, &View); + Button.VSplitLeft(135.0f, &Label, &Button); + + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%s:", (const char *)Key.m_Name); + + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + int OldId = Key.m_KeyId; + int NewId = DoKeyReader((void *)&gs_aKeys[i].m_Name, &Button, OldId); + if(NewId != OldId) + { + if(OldId != 0 || NewId == 0) + m_pClient->m_pBinds->Bind(OldId, ""); + if(NewId != 0) + m_pClient->m_pBinds->Bind(NewId, gs_aKeys[i].m_pCommand); + } + View.HSplitTop(2.0f, 0, &View); + } +} + +void CMenus::RenderSettingsControls(CUIRect MainView) +{ + // this is kinda slow, but whatever + for(int i = 0; i < g_KeyCount; i++) + gs_aKeys[i].m_KeyId = 0; + + for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) + { + const char *pBind = m_pClient->m_pBinds->Get(KeyId); + if(!pBind[0]) + continue; + + for(int i = 0; i < g_KeyCount; i++) + if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) + { + gs_aKeys[i].m_KeyId = KeyId; + break; + } + } + + CUIRect MovementSettings, WeaponSettings, VotingSettings, ChatSettings, MiscSettings, ResetButton; + MainView.VSplitMid(&MovementSettings, &VotingSettings); + + // movement settings + { + MovementSettings.VMargin(5.0f, &MovementSettings); + MovementSettings.HSplitTop(MainView.h/3+75.0f, &MovementSettings, &WeaponSettings); + RenderTools()->DrawUIRect(&MovementSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + MovementSettings.VMargin(10.0f, &MovementSettings); + + TextRender()->Text(0, MovementSettings.x, MovementSettings.y, 14.0f*UI()->Scale(), Localize("Movement"), -1); + + MovementSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &MovementSettings); + + { + CUIRect Button, Label; + MovementSettings.HSplitTop(20.0f, &Button, &MovementSettings); + Button.VSplitLeft(135.0f, &Label, &Button); + UI()->DoLabel(&Label, Localize("Mouse sens."), 14.0f*UI()->Scale(), -1); + Button.HMargin(2.0f, &Button); + g_Config.m_InpMousesens = (int)(DoScrollbarH(&g_Config.m_InpMousesens, &Button, (g_Config.m_InpMousesens-5)/500.0f)*500.0f)+5; + //*key.key = ui_do_key_reader(key.key, &Button, *key.key); + MovementSettings.HSplitTop(20.0f, 0, &MovementSettings); + } + + UiDoGetButtons(0, 7, MovementSettings); + + } + + // weapon settings + { + WeaponSettings.HSplitTop(10.0f, 0, &WeaponSettings); + WeaponSettings.HSplitTop(MainView.h/3+35.0f, &WeaponSettings, &ResetButton); + RenderTools()->DrawUIRect(&WeaponSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + WeaponSettings.VMargin(10.0f, &WeaponSettings); + + TextRender()->Text(0, WeaponSettings.x, WeaponSettings.y, 14.0f*UI()->Scale(), Localize("Weapon"), -1); + + WeaponSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &WeaponSettings); + UiDoGetButtons(7, 14, WeaponSettings); + } + + // defaults + { + ResetButton.HSplitTop(10.0f, 0, &ResetButton); + RenderTools()->DrawUIRect(&ResetButton, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + ResetButton.HMargin(10.0f, &ResetButton); + ResetButton.VMargin(30.0f, &ResetButton); + ResetButton.HSplitTop(20.0f, &ResetButton, 0); + static int s_DefaultButton = 0; + if(DoButton_Menu((void*)&s_DefaultButton, Localize("Reset to defaults"), 0, &ResetButton)) + m_pClient->m_pBinds->SetDefaults(); + } + + // voting settings + { + VotingSettings.VMargin(5.0f, &VotingSettings); + VotingSettings.HSplitTop(MainView.h/3-106.0f, &VotingSettings, &ChatSettings); + RenderTools()->DrawUIRect(&VotingSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + VotingSettings.VMargin(10.0f, &VotingSettings); + + TextRender()->Text(0, VotingSettings.x, VotingSettings.y, 14.0f*UI()->Scale(), Localize("Voting"), -1); + + VotingSettings.HSplitTop(14.0f+5.0f, 0, &VotingSettings); + UiDoGetButtons(14, 16, VotingSettings); + } + + // chat settings + { + ChatSettings.HSplitTop(10.0f, 0, &ChatSettings); + ChatSettings.HSplitTop(MainView.h/3-56.0f, &ChatSettings, &MiscSettings); + RenderTools()->DrawUIRect(&ChatSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + ChatSettings.VMargin(10.0f, &ChatSettings); + + TextRender()->Text(0, ChatSettings.x, ChatSettings.y, 14.0f*UI()->Scale(), Localize("Chat"), -1); + + ChatSettings.HSplitTop(14.0f+5.0f, 0, &ChatSettings); + UiDoGetButtons(16, 20, ChatSettings); + } + + // misc settings + { + MiscSettings.HSplitTop(10.0f, 0, &MiscSettings); + RenderTools()->DrawUIRect(&MiscSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); + MiscSettings.VMargin(10.0f, &MiscSettings); + + TextRender()->Text(0, MiscSettings.x, MiscSettings.y, 14.0f*UI()->Scale(), Localize("Miscellaneous"), -1); + + MiscSettings.HSplitTop(14.0f+5.0f, 0, &MiscSettings); + UiDoGetButtons(20, 33, MiscSettings); + } + +} + +void CMenus::RenderSettingsGraphics(CUIRect MainView) +{ + CUIRect Button; + char aBuf[128]; + bool CheckSettings = false; + + static const int MAX_RESOLUTIONS = 256; + static CVideoMode s_aModes[MAX_RESOLUTIONS]; + static int s_NumNodes = Graphics()->GetVideoModes(s_aModes, MAX_RESOLUTIONS); + static int s_GfxScreenWidth = g_Config.m_GfxScreenWidth; + static int s_GfxScreenHeight = g_Config.m_GfxScreenHeight; + static int s_GfxColorDepth = g_Config.m_GfxColorDepth; + static int s_GfxBorderless = g_Config.m_GfxBorderless; + static int s_GfxFullscreen = g_Config.m_GfxFullscreen; + static int s_GfxVsync = g_Config.m_GfxVsync; + static int s_GfxFsaaSamples = g_Config.m_GfxFsaaSamples; + static int s_GfxTextureQuality = g_Config.m_GfxTextureQuality; + static int s_GfxTextureCompression = g_Config.m_GfxTextureCompression; + + CUIRect ModeList; + MainView.VSplitLeft(300.0f, &MainView, &ModeList); + + // draw allmodes switch + ModeList.HSplitTop(20, &Button, &ModeList); + if(DoButton_CheckBox(&g_Config.m_GfxDisplayAllModes, Localize("Show only supported"), g_Config.m_GfxDisplayAllModes^1, &Button)) + { + g_Config.m_GfxDisplayAllModes ^= 1; + s_NumNodes = Graphics()->GetVideoModes(s_aModes, MAX_RESOLUTIONS); + } + + // display mode list + static float s_ScrollValue = 0; + int OldSelected = -1; + int G = gcd(s_GfxScreenWidth, s_GfxScreenHeight); + str_format(aBuf, sizeof(aBuf), "%s: %dx%d %d bit (%d:%d)", Localize("Current"), s_GfxScreenWidth, s_GfxScreenHeight, s_GfxColorDepth, s_GfxScreenWidth/G, s_GfxScreenHeight/G); + UiDoListboxStart(&s_NumNodes , &ModeList, 24.0f, Localize("Display Modes"), aBuf, s_NumNodes, 1, OldSelected, s_ScrollValue); + + for(int i = 0; i < s_NumNodes; ++i) + { + const int Depth = s_aModes[i].m_Red+s_aModes[i].m_Green+s_aModes[i].m_Blue > 16 ? 24 : 16; + if(g_Config.m_GfxColorDepth == Depth && + g_Config.m_GfxScreenWidth == s_aModes[i].m_Width && + g_Config.m_GfxScreenHeight == s_aModes[i].m_Height) + { + OldSelected = i; + } + + CListboxItem Item = UiDoListboxNextItem(&s_aModes[i], OldSelected == i); + if(Item.m_Visible) + { + int G = gcd(s_aModes[i].m_Width, s_aModes[i].m_Height); + str_format(aBuf, sizeof(aBuf), " %dx%d %d bit (%d:%d)", s_aModes[i].m_Width, s_aModes[i].m_Height, Depth, s_aModes[i].m_Width/G, s_aModes[i].m_Height/G); + UI()->DoLabelScaled(&Item.m_Rect, aBuf, 16.0f, -1); + } + } + + const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); + if(OldSelected != NewSelected) + { + const int Depth = s_aModes[NewSelected].m_Red+s_aModes[NewSelected].m_Green+s_aModes[NewSelected].m_Blue > 16 ? 24 : 16; + g_Config.m_GfxColorDepth = Depth; + g_Config.m_GfxScreenWidth = s_aModes[NewSelected].m_Width; + g_Config.m_GfxScreenHeight = s_aModes[NewSelected].m_Height; + CheckSettings = true; + } + + // switches + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxBorderless, Localize("Borderless window"), g_Config.m_GfxBorderless, &Button)) + { + g_Config.m_GfxBorderless ^= 1; + if(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen) + g_Config.m_GfxFullscreen = 0; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxFullscreen, Localize("Fullscreen"), g_Config.m_GfxFullscreen, &Button)) + { + g_Config.m_GfxFullscreen ^= 1; + if(g_Config.m_GfxFullscreen && g_Config.m_GfxBorderless) + g_Config.m_GfxBorderless = 0; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxVsync, Localize("V-Sync"), g_Config.m_GfxVsync, &Button)) + { + g_Config.m_GfxVsync ^= 1; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + int GfxFsaaSamples_MouseButton = DoButton_CheckBox_Number(&g_Config.m_GfxFsaaSamples, Localize("FSAA samples"), g_Config.m_GfxFsaaSamples, &Button); + if( GfxFsaaSamples_MouseButton == 1) //inc + { + g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples+1)%17; + CheckSettings = true; + } + else if(GfxFsaaSamples_MouseButton == 2) //dec + { + g_Config.m_GfxFsaaSamples = (g_Config.m_GfxFsaaSamples-1 +17)%17; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxTextureQuality, Localize("Quality Textures"), g_Config.m_GfxTextureQuality, &Button)) + { + g_Config.m_GfxTextureQuality ^= 1; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxTextureCompression, Localize("Texture Compression"), g_Config.m_GfxTextureCompression, &Button)) + { + g_Config.m_GfxTextureCompression ^= 1; + CheckSettings = true; + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_GfxHighDetail, Localize("High Detail"), g_Config.m_GfxHighDetail, &Button)) + g_Config.m_GfxHighDetail ^= 1; + + // check if the new settings require a restart + if(CheckSettings) + { + if(s_GfxScreenWidth == g_Config.m_GfxScreenWidth && + s_GfxScreenHeight == g_Config.m_GfxScreenHeight && + s_GfxColorDepth == g_Config.m_GfxColorDepth && + s_GfxBorderless == g_Config.m_GfxBorderless && + s_GfxFullscreen == g_Config.m_GfxFullscreen && + s_GfxVsync == g_Config.m_GfxVsync && + s_GfxFsaaSamples == g_Config.m_GfxFsaaSamples && + s_GfxTextureQuality == g_Config.m_GfxTextureQuality && + s_GfxTextureCompression == g_Config.m_GfxTextureCompression) + m_NeedRestartGraphics = false; + else + m_NeedRestartGraphics = true; + } + + // + + CUIRect Text; + MainView.HSplitTop(20.0f, 0, &MainView); + MainView.HSplitTop(20.0f, &Text, &MainView); + //text.VSplitLeft(15.0f, 0, &text); + UI()->DoLabelScaled(&Text, Localize("UI Color"), 14.0f, -1); + + const char *paLabels[] = { + Localize("Hue"), + Localize("Sat."), + Localize("Lht."), + Localize("Alpha")}; + int *pColorSlider[4] = {&g_Config.m_UiColorHue, &g_Config.m_UiColorSat, &g_Config.m_UiColorLht, &g_Config.m_UiColorAlpha}; + for(int s = 0; s < 4; s++) + { + CUIRect Text; + MainView.HSplitTop(19.0f, &Button, &MainView); + Button.VMargin(15.0f, &Button); + Button.VSplitLeft(100.0f, &Text, &Button); + //Button.VSplitRight(5.0f, &Button, 0); + Button.HSplitTop(4.0f, 0, &Button); + + float k = (*pColorSlider[s]) / 255.0f; + k = DoScrollbarH(pColorSlider[s], &Button, k); + *pColorSlider[s] = (int)(k*255.0f); + UI()->DoLabelScaled(&Text, paLabels[s], 15.0f, -1); + } +} + +void CMenus::RenderSettingsSound(CUIRect MainView) +{ + CUIRect Button; + MainView.VSplitMid(&MainView, 0); + static int s_SndEnable = g_Config.m_SndEnable; + static int s_SndRate = g_Config.m_SndRate; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndEnable, Localize("Use sounds"), g_Config.m_SndEnable, &Button)) + { + g_Config.m_SndEnable ^= 1; + if(g_Config.m_SndEnable) + { + if(g_Config.m_SndMusic && Client()->State() == IClient::STATE_OFFLINE) + m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); + } + else + m_pClient->m_pSounds->Stop(SOUND_MENU); + m_NeedRestartSound = g_Config.m_SndEnable && (!s_SndEnable || s_SndRate != g_Config.m_SndRate); + } + + if(!g_Config.m_SndEnable) + return; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndMusic, Localize("Play background music"), g_Config.m_SndMusic, &Button)) + { + g_Config.m_SndMusic ^= 1; + if(Client()->State() == IClient::STATE_OFFLINE) + { + if(g_Config.m_SndMusic) + m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); + else + m_pClient->m_pSounds->Stop(SOUND_MENU); + } + } + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndNonactiveMute, Localize("Mute when not active"), g_Config.m_SndNonactiveMute, &Button)) + g_Config.m_SndNonactiveMute ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndGame, Localize("Enable game sounds"), g_Config.m_SndGame, &Button)) + g_Config.m_SndGame ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndGun, Localize("Enable gun sound"), g_Config.m_SndGun, &Button)) + g_Config.m_SndGun ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndServerMessage, Localize("Enable server message sound"), g_Config.m_SndServerMessage, &Button)) + g_Config.m_SndServerMessage ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndChat, Localize("Enable regular chat sound"), g_Config.m_SndChat, &Button)) + g_Config.m_SndChat ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndTeamChat, Localize("Enable team chat sound"), g_Config.m_SndTeamChat, &Button)) + g_Config.m_SndTeamChat ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_SndHighlight, Localize("Enable highlighted chat sound"), g_Config.m_SndHighlight, &Button)) + g_Config.m_SndHighlight ^= 1; + + MainView.HSplitTop(20.0f, &Button, &MainView); + if(DoButton_CheckBox(&g_Config.m_ClThreadsoundloading, Localize("Threaded sound loading"), g_Config.m_ClThreadsoundloading, &Button)) + g_Config.m_ClThreadsoundloading ^= 1; + + // sample rate box + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%d", g_Config.m_SndRate); + MainView.HSplitTop(20.0f, &Button, &MainView); + UI()->DoLabelScaled(&Button, Localize("Sample rate"), 14.0f, -1); + Button.VSplitLeft(190.0f, 0, &Button); + static float Offset = 0.0f; + DoEditBox(&g_Config.m_SndRate, &Button, aBuf, sizeof(aBuf), 14.0f, &Offset); + g_Config.m_SndRate = max(1, str_toint(aBuf)); + m_NeedRestartSound = !s_SndEnable || s_SndRate != g_Config.m_SndRate; + } + + // volume slider + { + CUIRect Button, Label; + MainView.HSplitTop(5.0f, &Button, &MainView); + MainView.HSplitTop(20.0f, &Button, &MainView); + Button.VSplitLeft(190.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sound volume"), 14.0f, -1); + g_Config.m_SndVolume = (int)(DoScrollbarH(&g_Config.m_SndVolume, &Button, g_Config.m_SndVolume/100.0f)*100.0f); + } + + // volume slider map sounds + { + CUIRect Button, Label; + MainView.HSplitTop(5.0f, &Button, &MainView); + MainView.HSplitTop(20.0f, &Button, &MainView); + Button.VSplitLeft(190.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Map sound volume"), 14.0f, -1); + g_Config.m_SndMapSoundVolume = (int)(DoScrollbarH(&g_Config.m_SndMapSoundVolume, &Button, g_Config.m_SndMapSoundVolume/100.0f)*100.0f); + } +} + +class CLanguage +{ +public: + CLanguage() {} + CLanguage(const char *n, const char *f, int Code) : m_Name(n), m_FileName(f), m_CountryCode(Code) {} + + string m_Name; + string m_FileName; + int m_CountryCode; + + bool operator<(const CLanguage &Other) { return m_Name < Other.m_Name; } +}; + +void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array<CLanguage> *pLanguages) +{ + IOHANDLE File = pStorage->OpenFile("languages/index.txt", IOFLAG_READ, IStorage::TYPE_ALL); + if(!File) + { + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "couldn't open index file"); + return; + } + + char aOrigin[128]; + char aReplacement[128]; + CLineReader LineReader; + LineReader.Init(File); + char *pLine; + while((pLine = LineReader.Get())) + { + if(!str_length(pLine) || pLine[0] == '#') // skip empty lines and comments + continue; + + str_copy(aOrigin, pLine, sizeof(aOrigin)); + + pLine = LineReader.Get(); + if(!pLine) + { + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of index file"); + break; + } + + if(pLine[0] != '=' || pLine[1] != '=' || pLine[2] != ' ') + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "malform replacement for index '%s'", aOrigin); + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); + (void)LineReader.Get(); + continue; + } + str_copy(aReplacement, pLine+3, sizeof(aReplacement)); + + pLine = LineReader.Get(); + if(!pLine) + { + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of index file"); + break; + } + + if(pLine[0] != '=' || pLine[1] != '=' || pLine[2] != ' ') + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "malform replacement for index '%s'", aOrigin); + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); + continue; + } + + char aFileName[128]; + str_format(aFileName, sizeof(aFileName), "languages/%s.txt", aOrigin); + pLanguages->add(CLanguage(aReplacement, aFileName, str_toint(pLine+3))); + } + io_close(File); +} + +void CMenus::RenderLanguageSelection(CUIRect MainView) +{ + static int s_LanguageList = 0; + static int s_SelectedLanguage = 0; + static sorted_array<CLanguage> s_Languages; + static float s_ScrollValue = 0; + + if(s_Languages.size() == 0) + { + s_Languages.add(CLanguage("English", "", 826)); + LoadLanguageIndexfile(Storage(), Console(), &s_Languages); + for(int i = 0; i < s_Languages.size(); i++) + if(str_comp(s_Languages[i].m_FileName, g_Config.m_ClLanguagefile) == 0) + { + s_SelectedLanguage = i; + break; + } + } + + int OldSelected = s_SelectedLanguage; + +#if defined(__ANDROID__) + UiDoListboxStart(&s_LanguageList , &MainView, 50.0f, Localize("Language"), "", s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue); +#else + UiDoListboxStart(&s_LanguageList , &MainView, 24.0f, Localize("Language"), "", s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue); +#endif + + for(sorted_array<CLanguage>::range r = s_Languages.all(); !r.empty(); r.pop_front()) + { + CListboxItem Item = UiDoListboxNextItem(&r.front()); + + if(Item.m_Visible) + { + CUIRect Rect; + Item.m_Rect.VSplitLeft(Item.m_Rect.h*2.0f, &Rect, &Item.m_Rect); + Rect.VMargin(6.0f, &Rect); + Rect.HMargin(3.0f, &Rect); + vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); + m_pClient->m_pCountryFlags->Render(r.front().m_CountryCode, &Color, Rect.x, Rect.y, Rect.w, Rect.h); + Item.m_Rect.HSplitTop(2.0f, 0, &Item.m_Rect); + UI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, 16.0f, -1); + } + } + + s_SelectedLanguage = UiDoListboxEnd(&s_ScrollValue, 0); + + if(OldSelected != s_SelectedLanguage) + { + str_copy(g_Config.m_ClLanguagefile, s_Languages[s_SelectedLanguage].m_FileName, sizeof(g_Config.m_ClLanguagefile)); + g_Localization.Load(s_Languages[s_SelectedLanguage].m_FileName, Storage(), Console()); + + // Load Font + static CFont *pDefaultFont = 0; + char aFilename[512]; + const char *pFontFile = "fonts/DejaVuSansCJKName.ttf"; + if (str_find(g_Config.m_ClLanguagefile, "chinese") != NULL || str_find(g_Config.m_ClLanguagefile, "japanese") != NULL || + str_find(g_Config.m_ClLanguagefile, "korean") != NULL) + pFontFile = "fonts/DejavuWenQuanYiMicroHei.ttf"; + IOHANDLE File = Storage()->OpenFile(pFontFile, IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename)); + if(File) + { + io_close(File); + pDefaultFont = TextRender()->LoadFont(aFilename); + TextRender()->SetDefaultFont(pDefaultFont); + } + if(!pDefaultFont) + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load font. filename='%s'", pFontFile); + } +} + +void CMenus::RenderSettings(CUIRect MainView) +{ + static int s_SettingsPage = 0; + + // render background + CUIRect Temp, TabBar, RestartWarning; + MainView.VSplitRight(120.0f, &MainView, &TabBar); + RenderTools()->DrawUIRect(&MainView, ms_ColorTabbarActive, CUI::CORNER_B|CUI::CORNER_TL, 10.0f); + MainView.Margin(10.0f, &MainView); + MainView.HSplitBottom(15.0f, &MainView, &RestartWarning); + TabBar.HSplitTop(50.0f, &Temp, &TabBar); + RenderTools()->DrawUIRect(&Temp, ms_ColorTabbarActive, CUI::CORNER_R, 10.0f); + + MainView.HSplitTop(10.0f, 0, &MainView); + + CUIRect Button; + + const char *aTabs[] = { + Localize("Language"), + Localize("General"), + Localize("Player"), + ("Tee"), + Localize("HUD"), + Localize("Controls"), + Localize("Graphics"), + Localize("Sound"), + Localize("DDNet") + }; + + int NumTabs = (int)(sizeof(aTabs)/sizeof(*aTabs)); + + for(int i = 0; i < NumTabs; i++) + { + TabBar.HSplitTop(10, &Button, &TabBar); + TabBar.HSplitTop(26, &Button, &TabBar); + if(DoButton_MenuTab(aTabs[i], aTabs[i], s_SettingsPage == i, &Button, CUI::CORNER_R)) + s_SettingsPage = i; + } + + MainView.Margin(10.0f, &MainView); + + if(s_SettingsPage == 0) + RenderLanguageSelection(MainView); + else if(s_SettingsPage == 1) + RenderSettingsGeneral(MainView); + else if(s_SettingsPage == 2) + RenderSettingsPlayer(MainView); + else if(s_SettingsPage == 3) + RenderSettingsTee(MainView); + else if(s_SettingsPage == 4) + RenderSettingsHUD(MainView); + else if(s_SettingsPage == 5) + RenderSettingsControls(MainView); + else if(s_SettingsPage == 6) + RenderSettingsGraphics(MainView); + else if(s_SettingsPage == 7) + RenderSettingsSound(MainView); + else if(s_SettingsPage == 8) + RenderSettingsDDRace(MainView); + + if(m_NeedRestartUpdate) + { + TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); + UI()->DoLabelScaled(&RestartWarning, Localize("DDNet Client needs to be restarted to complete update!"), 14.0f, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + else if(m_NeedRestartSkins || m_NeedRestartGraphics || m_NeedRestartSound) + UI()->DoLabelScaled(&RestartWarning, Localize("You must restart the game for all settings to take effect."), 14.0f, -1); +} +void CMenus::RenderSettingsHUD(CUIRect MainView) +{ + CUIRect Left, Right, HUD, Messages, Button, Label, Weapon, Laser; + + MainView.HSplitTop(150.0f, &HUD, &MainView); + + HUD.HSplitTop(30.0f, &Label, &HUD); + UI()->DoLabelScaled(&Label, Localize("HUD"), 20.0f, -1); + HUD.Margin(5.0f, &HUD); + HUD.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + // show hud + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClShowhud, Localize("Show ingame HUD"), g_Config.m_ClShowhud, &Button)) + g_Config.m_ClShowhud ^= 1; + + + Left.HSplitTop(20.0f, &Button, &Left); + if (DoButton_CheckBox(&g_Config.m_ClDDRaceScoreBoard, Localize("Use DDRace Scoreboard"), g_Config.m_ClDDRaceScoreBoard, &Button)) + { + g_Config.m_ClDDRaceScoreBoard ^= 1; + } + + Left.HSplitTop(20.0f, &Button, &Left); + if (DoButton_CheckBox(&g_Config.m_ClShowIDs, Localize("Show client IDs in Scoreboard"), g_Config.m_ClShowIDs, &Button)) + { + g_Config.m_ClShowIDs ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if (DoButton_CheckBox(&g_Config.m_ClShowhudScore, Localize("Show score"), g_Config.m_ClShowhudScore, &Button)) + { + g_Config.m_ClShowhudScore ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if (DoButton_CheckBox(&g_Config.m_ClShowhudHealthAmmo, Localize("Show health + ammo"), g_Config.m_ClShowhudHealthAmmo, &Button)) + { + g_Config.m_ClShowhudHealthAmmo ^= 1; + } + + Left.HSplitTop(20.0f, &Button, &Left); + if (DoButton_CheckBox(&g_Config.m_ClShowChat, Localize("Show chat"), g_Config.m_ClShowChat, &Button)) + { + g_Config.m_ClShowChat ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if (DoButton_CheckBox(&g_Config.m_ClChatTeamColors, Localize("Show names in chat in team colors"), g_Config.m_ClChatTeamColors, &Button)) + { + g_Config.m_ClChatTeamColors ^= 1; + } + + Left.HSplitTop(20.0f, &Button, &Left); + if (DoButton_CheckBox(&g_Config.m_ClShowKillMessages, Localize("Show kill messages"), g_Config.m_ClShowKillMessages, &Button)) + { + g_Config.m_ClShowKillMessages ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if (DoButton_CheckBox(&g_Config.m_ClShowVotesAfterVoting, Localize("Show votes window after voting"), g_Config.m_ClShowVotesAfterVoting, &Button)) + { + g_Config.m_ClShowVotesAfterVoting ^= 1; + } + MainView.HSplitTop(170.0f, &Messages, &MainView); + Messages.HSplitTop(30.0f, &Label, &Messages); + Label.VSplitMid(&Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Messages"), 20.0f, -1); + Messages.Margin(5.0f, &Messages); + Messages.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + { + char aBuf[64]; + Left.HSplitTop(20.0f, &Label, &Left); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("System message"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(1.0f, 1.0f, 0.5f)); // default values + g_Config.m_ClMessageSystemHue = HSL.h; + g_Config.m_ClMessageSystemSat = HSL.s; + g_Config.m_ClMessageSystemLht = HSL.l; + } + } + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 14.0f, -1); + g_Config.m_ClMessageSystemHue = (int)(DoScrollbarH(&g_Config.m_ClMessageSystemHue, &Button, g_Config.m_ClMessageSystemHue / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 14.0f, -1); + g_Config.m_ClMessageSystemSat = (int)(DoScrollbarH(&g_Config.m_ClMessageSystemSat, &Button, g_Config.m_ClMessageSystemSat / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 14.0f, -1); + g_Config.m_ClMessageSystemLht = (int)(DoScrollbarH(&g_Config.m_ClMessageSystemLht, &Button, g_Config.m_ClMessageSystemLht / 255.0f)*255.0f); + + Left.HSplitTop(10.0f, &Label, &Left); + + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageSystemHue / 255.0f, g_Config.m_ClMessageSystemSat / 255.0f, g_Config.m_ClMessageSystemLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + + + char name[16]; + str_copy(name, g_Config.m_PlayerName, sizeof(name)); + str_format(aBuf, sizeof(aBuf), "*** '%s' entered and joined the spectators", name); + while (TextRender()->TextWidth(0, 12.0f, aBuf, -1) > Label.w) + { + name[str_length(name) - 1] = 0; + str_format(aBuf, sizeof(aBuf), "*** '%s' entered and joined the spectators", name); + } + UI()->DoLabelScaled(&Label, aBuf, 12.0f, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + Left.HSplitTop(20.0f, 0, &Left); + } + { + char aBuf[64]; + Right.HSplitTop(20.0f, &Label, &Right); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Highlighted message"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(1.0f, 0.5f, 0.5f)); // default values + g_Config.m_ClMessageHighlightHue = HSL.h; + g_Config.m_ClMessageHighlightSat = HSL.s; + g_Config.m_ClMessageHighlightLht = HSL.l; + } + } + Right.HSplitTop(20.0f, &Button, &Right); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 14.0f, -1); + g_Config.m_ClMessageHighlightHue = (int)(DoScrollbarH(&g_Config.m_ClMessageHighlightHue, &Button, g_Config.m_ClMessageHighlightHue / 255.0f)*255.0f); + + Right.HSplitTop(20.0f, &Button, &Right); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 14.0f, -1); + g_Config.m_ClMessageHighlightSat = (int)(DoScrollbarH(&g_Config.m_ClMessageHighlightSat, &Button, g_Config.m_ClMessageHighlightSat / 255.0f)*255.0f); + + Right.HSplitTop(20.0f, &Button, &Right); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 14.0f, -1); + g_Config.m_ClMessageHighlightLht = (int)(DoScrollbarH(&g_Config.m_ClMessageHighlightLht, &Button, g_Config.m_ClMessageHighlightLht / 255.0f)*255.0f); + + Right.HSplitTop(10.0f, &Label, &Right); + + TextRender()->TextColor(0.75f, 0.5f, 0.75f, 1.0f); + float tw = TextRender()->TextWidth(0, 12.0f, Localize("Spectator"), -1); + Label.VSplitLeft(tw, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Spectator"), 12.0f, -1); + + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHighlightHue / 255.0f, g_Config.m_ClMessageHighlightSat / 255.0f, g_Config.m_ClMessageHighlightLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + char name[16]; + str_copy(name, g_Config.m_PlayerName, sizeof(name)); + str_format(aBuf, sizeof(aBuf), ": %s: %s", name, Localize ("Look out!")); + while (TextRender()->TextWidth(0, 12.0f, aBuf, -1) > Button.w) + { + name[str_length(name) - 1] = 0; + str_format(aBuf, sizeof(aBuf), ": %s: %s", name, Localize("Look out!")); + } + UI()->DoLabelScaled(&Button, aBuf, 12.0f, -1); + + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + Right.HSplitTop(20.0f, 0, &Right); + } + { + char aBuf[64]; + Left.HSplitTop(20.0f, &Label, &Left); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Team message"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(0.65f, 1.0f, 0.65f)); // default values + g_Config.m_ClMessageTeamHue = HSL.h; + g_Config.m_ClMessageTeamSat = HSL.s; + g_Config.m_ClMessageTeamLht = HSL.l; + } + } + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 14.0f, -1); + g_Config.m_ClMessageTeamHue = (int)(DoScrollbarH(&g_Config.m_ClMessageTeamHue, &Button, g_Config.m_ClMessageTeamHue / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 14.0f, -1); + g_Config.m_ClMessageTeamSat = (int)(DoScrollbarH(&g_Config.m_ClMessageTeamSat, &Button, g_Config.m_ClMessageTeamSat / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 14.0f, -1); + g_Config.m_ClMessageTeamLht = (int)(DoScrollbarH(&g_Config.m_ClMessageTeamLht, &Button, g_Config.m_ClMessageTeamLht / 255.0f)*255.0f); + + Left.HSplitTop(10.0f, &Label, &Left); + + TextRender()->TextColor(0.45f, 0.9f, 0.45f, 1.0f); + float tw = TextRender()->TextWidth(0, 12.0f, Localize("Player"), -1); + Label.VSplitLeft(tw, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Player"), 12.0f, -1); + + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageTeamHue / 255.0f, g_Config.m_ClMessageTeamSat / 255.0f, g_Config.m_ClMessageTeamLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + str_format(aBuf, sizeof(aBuf), ": %s!", Localize("We will win")); + UI()->DoLabelScaled(&Button, aBuf, 12.0f, -1); + + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + Left.HSplitTop(20.0f, 0, &Left); + } + { + char aBuf[64]; + Left.HSplitTop(20.0f, &Label, &Left); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Normal message"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(1.0f, 1.0f, 1.0f)); // default values + g_Config.m_ClMessageHue = HSL.h; + g_Config.m_ClMessageSat = HSL.s; + g_Config.m_ClMessageLht = HSL.l; + } + } + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 14.0f, -1); + g_Config.m_ClMessageHue = (int)(DoScrollbarH(&g_Config.m_ClMessageHue, &Button, g_Config.m_ClMessageHue / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 14.0f, -1); + g_Config.m_ClMessageSat = (int)(DoScrollbarH(&g_Config.m_ClMessageSat, &Button, g_Config.m_ClMessageSat / 255.0f)*255.0f); + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 14.0f, -1); + g_Config.m_ClMessageLht = (int)(DoScrollbarH(&g_Config.m_ClMessageLht, &Button, g_Config.m_ClMessageLht / 255.0f)*255.0f); + + Left.HSplitTop(10.0f, &Label, &Left); + + TextRender()->TextColor(0.8f, 0.8f, 0.8f, 1.0f); + float tw = TextRender()->TextWidth(0, 12.0f, Localize("Player"), -1); + Label.VSplitLeft(tw, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Player"), 12.0f, -1); + + vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHue / 255.0f, g_Config.m_ClMessageSat / 255.0f, g_Config.m_ClMessageLht / 255.0f)); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1.0f); + str_format(aBuf, sizeof(aBuf), ": %s :D", Localize("Hello and welcome")); + UI()->DoLabelScaled(&Button, aBuf, 12.0f, -1); + + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + { + Right.HSplitTop(220.0f, &Laser, &Right); + RenderTools()->DrawUIRect(&Laser, vec4(1.0f, 1.0f, 1.0f, 0.1f), CUI::CORNER_ALL, 5.0f); + Laser.Margin(10.0f, &Laser); + Laser.HSplitTop(30.0f, &Label, &Laser); + Label.VSplitLeft(TextRender()->TextWidth(0, 20.0f, Localize("Laser"), -1) + 5.0f, &Label, &Weapon); + UI()->DoLabelScaled(&Label, Localize("Laser"), 20.0f, -1); + + Laser.HSplitTop(20.0f, &Label, &Laser); + Label.VSplitLeft(5.0f, 0, &Label); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Inner color"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(0.5f, 0.5f, 1.0f)); // default values + g_Config.m_ClLaserInnerHue = HSL.h; + g_Config.m_ClLaserInnerSat = HSL.s; + g_Config.m_ClLaserInnerLht = HSL.l; + } + } + + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(20.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 12.0f, -1); + g_Config.m_ClLaserInnerHue = (int)(DoScrollbarH(&g_Config.m_ClLaserInnerHue, &Button, g_Config.m_ClLaserInnerHue / 255.0f)*255.0f); + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(20.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 12.0f, -1); + g_Config.m_ClLaserInnerSat = (int)(DoScrollbarH(&g_Config.m_ClLaserInnerSat, &Button, g_Config.m_ClLaserInnerSat / 255.0f)*255.0f); + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(20.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 12.0f, -1); + g_Config.m_ClLaserInnerLht = (int)(DoScrollbarH(&g_Config.m_ClLaserInnerLht, &Button, g_Config.m_ClLaserInnerLht / 255.0f)*255.0f); + + Laser.HSplitTop(10.0f, 0, &Laser); + + Laser.HSplitTop(20.0f, &Label, &Laser); + Label.VSplitLeft(5.0f, 0, &Label); + Label.VSplitRight(50.0f, &Label, &Button); + UI()->DoLabelScaled(&Label, Localize("Outline color"), 16.0f, -1); + { + static int s_DefaultButton = 0; + if (DoButton_Menu(&s_DefaultButton, Localize("Reset"), 0, &Button)){ + vec3 HSL = RgbToHsl(vec3(0.075f, 0.075f, 0.25f)); // default values + g_Config.m_ClLaserOutlineHue = HSL.h; + g_Config.m_ClLaserOutlineSat = HSL.s; + g_Config.m_ClLaserOutlineLht = HSL.l; + } + } + + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Hue"), 12.0f, -1); + g_Config.m_ClLaserOutlineHue = (int)(DoScrollbarH(&g_Config.m_ClLaserOutlineHue, &Button, g_Config.m_ClLaserOutlineHue / 255.0f)*255.0f); + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Sat."), 12.0f, -1); + g_Config.m_ClLaserOutlineSat = (int)(DoScrollbarH(&g_Config.m_ClLaserOutlineSat, &Button, g_Config.m_ClLaserOutlineSat / 255.0f)*255.0f); + Laser.HSplitTop(20.0f, &Button, &Laser); + Button.VSplitLeft(15.0f, 0, &Button); + Button.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Lht."), 12.0f, -1); + g_Config.m_ClLaserOutlineLht = (int)(DoScrollbarH(&g_Config.m_ClLaserOutlineLht, &Button, g_Config.m_ClLaserOutlineLht / 255.0f)*255.0f); + + + //Laser.HSplitTop(8.0f, &Weapon, &Laser); + Weapon.VSplitLeft(30.0f, 0, &Weapon); + + vec3 RGB; + vec2 From = vec2(Weapon.x, Weapon.y + Weapon.h / 2.0f); + vec2 Pos = vec2(Weapon.x + Weapon.w - 10.0f, Weapon.y + Weapon.h / 2.0f); + + vec2 Out, Border; + + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + + // do outline + RGB = HslToRgb(vec3(g_Config.m_ClLaserOutlineHue / 255.0f, g_Config.m_ClLaserOutlineSat / 255.0f, g_Config.m_ClLaserOutlineLht / 255.0f)); + vec4 OuterColor(RGB.r, RGB.g, RGB.b, 1.0f); + Graphics()->SetColor(RGB.r, RGB.g, RGB.b, 1.0f); // outline + Out = vec2(0.0f, -1.0f) * (3.15f); + + IGraphics::CFreeformItem Freeform( + 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); + + // do inner + RGB = HslToRgb(vec3(g_Config.m_ClLaserInnerHue / 255.0f, g_Config.m_ClLaserInnerSat / 255.0f, g_Config.m_ClLaserInnerLht / 255.0f)); + vec4 InnerColor(RGB.r, RGB.g, RGB.b, 1.0f); + Out = vec2(0.0f, -1.0f) * (2.25f); + 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(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); + Graphics()->QuadsBegin(); + + int Sprites[] = { SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03 }; + RenderTools()->SelectSprite(Sprites[time_get() % 3]); + Graphics()->QuadsSetRotation(time_get()); + Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); + IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 24, 24); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); + QuadItem = IGraphics::CQuadItem(Pos.x, Pos.y, 20, 20); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + // draw laser weapon + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + + RenderTools()->SelectSprite(SPRITE_WEAPON_RIFLE_BODY); + RenderTools()->DrawSprite(Weapon.x, Weapon.y + Weapon.h / 2.0f, 60.0f); + + Graphics()->QuadsEnd(); + } + /* + Left.VSplitLeft(20.0f, 0, &Left); + Left.HSplitTop(20.0f, &Label, &Left); + Button.VSplitRight(20.0f, &Button, 0); + char aBuf[64]; + if (g_Config.m_ClReconnectBanTimeout == 1) + { + str_format(aBuf, sizeof(aBuf), "%s %i %s", Localize("Wait before try for"), g_Config.m_ClReconnectBanTimeout, Localize("second")); + } + else + { + str_format(aBuf, sizeof(aBuf), "%s %i %s", Localize("Wait before try for"), g_Config.m_ClReconnectBanTimeout, Localize("seconds")); + } + UI()->DoLabelScaled(&Label, aBuf, 13.0f, -1); + Left.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClReconnectBanTimeout = static_cast<int>(DoScrollbarH(&g_Config.m_ClReconnectBanTimeout, &Button, g_Config.m_ClReconnectBanTimeout / 120.0f) * 120.0f); + if (g_Config.m_ClReconnectBanTimeout < 5) + g_Config.m_ClReconnectBanTimeout = 5;*/ +} + +void CMenus::RenderSettingsDDRace(CUIRect MainView) +{ + CUIRect Button, Left, Right, LeftLeft, Demo, Gameplay, Miscellaneous, Label, Background; + + MainView.HSplitTop(100.0f, &Demo , &MainView); + + Demo.HSplitTop(30.0f, &Label, &Demo); + UI()->DoLabelScaled(&Label, Localize("Demo"), 20.0f, -1); + Demo.Margin(5.0f, &Demo); + Demo.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClAutoRaceRecord, Localize("Save the best demo of each race"), g_Config.m_ClAutoRaceRecord, &Button)) + { + g_Config.m_ClAutoRaceRecord ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClRaceGhost, Localize("Ghost"), g_Config.m_ClRaceGhost, &Button)) + { + g_Config.m_ClRaceGhost ^= 1; + } + + if(g_Config.m_ClRaceGhost) + { + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClRaceShowGhost, Localize("Show ghost"), g_Config.m_ClRaceShowGhost, &Button)) + { + g_Config.m_ClRaceShowGhost ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClRaceSaveGhost, Localize("Save ghost"), g_Config.m_ClRaceSaveGhost, &Button)) + { + g_Config.m_ClRaceSaveGhost ^= 1; + } + } + + MainView.HSplitTop(290.0f, &Gameplay , &MainView); + + Gameplay.HSplitTop(30.0f, &Label, &Gameplay); + UI()->DoLabelScaled(&Label, Localize("Gameplay"), 20.0f, -1); + Gameplay.Margin(5.0f, &Gameplay); + Gameplay.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + { + CUIRect Button, Label; + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitLeft(120.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Overlay entities"), 14.0f, -1); + g_Config.m_ClOverlayEntities = (int)(DoScrollbarH(&g_Config.m_ClOverlayEntities, &Button, g_Config.m_ClOverlayEntities/100.0f)*100.0f); + } + + { + CUIRect Button, Label; + Left.HSplitTop(20.0f, &Button, &Left); + Button.VSplitMid(&LeftLeft, &Button); + + Button.VSplitLeft(50.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + UI()->DoLabelScaled(&Label, Localize("Alpha"), 14.0f, -1); + g_Config.m_ClShowOthersAlpha = (int)(DoScrollbarH(&g_Config.m_ClShowOthersAlpha, &Button, g_Config.m_ClShowOthersAlpha /100.0f)*100.0f); + + if(DoButton_CheckBox(&g_Config.m_ClShowOthers, Localize("Show others"), g_Config.m_ClShowOthers, &LeftLeft)) + { + g_Config.m_ClShowOthers ^= 1; + } + } + + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClShowQuads, Localize("Show quads"), g_Config.m_ClShowQuads, &Button)) + { + g_Config.m_ClShowQuads ^= 1; + } + + Right.HSplitTop(20.0f, &Label, &Right); + Label.VSplitLeft(130.0f, &Label, &Button); + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("Default zoom"), g_Config.m_ClDefaultZoom); + UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); + //Right.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClDefaultZoom= static_cast<int>(DoScrollbarH(&g_Config.m_ClDefaultZoom, &Button, g_Config.m_ClDefaultZoom/20.0f)*20.0f+0.1f); + + Right.HSplitTop(20.0f, &Label, &Right); + Label.VSplitLeft(130.0f, &Label, &Button); + str_format(aBuf, sizeof(aBuf), "%s: %i", Localize("AntiPing limit"), g_Config.m_ClAntiPingLimit); + UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); + //Right.HSplitTop(20.0f, &Button, 0); + Button.HMargin(2.0f, &Button); + g_Config.m_ClAntiPingLimit= static_cast<int>(DoScrollbarH(&g_Config.m_ClAntiPingLimit, &Button, g_Config.m_ClAntiPingLimit/200.0f)*200.0f+0.1f); + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAntiPing, Localize("AntiPing"), g_Config.m_ClAntiPing, &Button)) + { + g_Config.m_ClAntiPing ^= 1; + } + + if(g_Config.m_ClAntiPing) + { + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAntiPingPlayers, Localize("AntiPing: predict other players"), g_Config.m_ClAntiPingPlayers, &Button)) + { + g_Config.m_ClAntiPingPlayers ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAntiPingWeapons, Localize("AntiPing: predict weapons"), g_Config.m_ClAntiPingWeapons, &Button)) + { + g_Config.m_ClAntiPingWeapons ^= 1; + } + + Right.HSplitTop(20.0f, &Button, &Right); + if(DoButton_CheckBox(&g_Config.m_ClAntiPingGrenade, Localize("AntiPing: predict grenade paths"), g_Config.m_ClAntiPingGrenade, &Button)) + { + g_Config.m_ClAntiPingGrenade ^= 1; + } + } + else + { + Right.HSplitTop(60.0f, 0, &Right); + } + + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClShowOtherHookColl, Localize("Show other players' hook collision lines"), g_Config.m_ClShowOtherHookColl, &Button)) + { + g_Config.m_ClShowOtherHookColl ^= 1; + } + + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClShowDirection, Localize("Show other players' key presses"), g_Config.m_ClShowDirection, &Button)) + { + g_Config.m_ClShowDirection ^= 1; + } + + Left.HSplitTop(20.0f, &Button, &Left); + + CUIRect aRects[2]; + Left.HSplitTop(5.0f, &Button, &Left); + Right.HSplitTop(5.0f, &Button, &Right); + aRects[0] = Left; + aRects[1] = Right; + aRects[0].VSplitRight(10.0f, &aRects[0], 0); + aRects[1].VSplitLeft(10.0f, 0, &aRects[1]); + + int *pColorSlider[2][3] = {{&g_Config.m_ClBackgroundHue, &g_Config.m_ClBackgroundSat, &g_Config.m_ClBackgroundLht}, {&g_Config.m_ClBackgroundEntitiesHue, &g_Config.m_ClBackgroundEntitiesSat, &g_Config.m_ClBackgroundEntitiesLht}}; + + const char *paParts[] = { + Localize("Background (regular)"), + Localize("Background (entities)")}; + const char *paLabels[] = { + Localize("Hue"), + Localize("Sat."), + Localize("Lht.")}; + + for(int i = 0; i < 2; i++) + { + aRects[i].HSplitTop(20.0f, &Label, &aRects[i]); + UI()->DoLabelScaled(&Label, paParts[i], 14.0f, -1); + aRects[i].VSplitLeft(20.0f, 0, &aRects[i]); + aRects[i].HSplitTop(2.5f, 0, &aRects[i]); + + for(int s = 0; s < 3; s++) + { + aRects[i].HSplitTop(20.0f, &Label, &aRects[i]); + Label.VSplitLeft(100.0f, &Label, &Button); + Button.HMargin(2.0f, &Button); + + float k = (*pColorSlider[i][s]) / 255.0f; + k = DoScrollbarH(pColorSlider[i][s], &Button, k); + *pColorSlider[i][s] = (int)(k*255.0f); + UI()->DoLabelScaled(&Label, paLabels[s], 15.0f, -1); + } + } + + { + static float s_Map = 0.0f; + aRects[1].HSplitTop(25.0f, &Background, &aRects[1]); + Background.HSplitTop(20.0f, &Background, 0); + Background.VSplitLeft(100.0f, &Label, &Left); + UI()->DoLabelScaled(&Label, Localize("Map"), 14.0f, -1); + DoEditBox(g_Config.m_ClBackgroundEntities, &Left, g_Config.m_ClBackgroundEntities, sizeof(g_Config.m_ClBackgroundEntities), 14.0f, &s_Map); + + aRects[1].HSplitTop(20.0f, &Button, 0); + if(DoButton_CheckBox(&g_Config.m_ClBackgroundShowTilesLayers, Localize("Show tiles layers from BG map"), g_Config.m_ClBackgroundShowTilesLayers, &Button)) + { + g_Config.m_ClBackgroundShowTilesLayers ^= 1; + } + } + + MainView.HSplitTop(30.0f, &Label, &Miscellaneous); + UI()->DoLabelScaled(&Label, Localize("Miscellaneous"), 20.0f, -1); + Miscellaneous.VMargin(5.0f, &Miscellaneous); + Miscellaneous.VSplitMid(&Left, &Right); + Left.VSplitRight(5.0f, &Left, 0); + Right.VMargin(5.0f, &Right); + + Left.HSplitTop(20.0f, &Button, &Left); + if(DoButton_CheckBox(&g_Config.m_ClHttpMapDownload, Localize("Try fast HTTP map download first"), g_Config.m_ClHttpMapDownload, &Button)) + { + g_Config.m_ClHttpMapDownload ^= 1; + } + + //Updater +#if defined(CONF_FAMILY_WINDOWS) || (defined(CONF_PLATFORM_LINUX) && !defined(__ANDROID__)) + { + Left.HSplitTop(20.0f, &Label, &Left); + bool NeedUpdate = str_comp(Client()->LatestVersion(), "0"); + char aBuf[256]; + int State = Updater()->GetCurrentState(); + + //Update Button + if(NeedUpdate && State <= IUpdater::CLEAN) + { + str_format(aBuf, sizeof(aBuf), Localize("DDNet %s is available:"), Client()->LatestVersion()); + Label.VSplitLeft(TextRender()->TextWidth(0, 14.0f, aBuf, -1) + 10.0f, &Label, &Button); + Button.VSplitLeft(100.0f, &Button, 0); + static int s_ButtonUpdate = 0; + if(DoButton_Menu(&s_ButtonUpdate, Localize("Update now"), 0, &Button)) + Updater()->InitiateUpdate(); + } + else if(State >= IUpdater::GETTING_MANIFEST && State < IUpdater::NEED_RESTART) + str_format(aBuf, sizeof(aBuf), Localize("Updating...")); + else if(State == IUpdater::NEED_RESTART){ + str_format(aBuf, sizeof(aBuf), Localize("DDNet Client updated!")); + m_NeedRestartUpdate = true; + } + else + { + str_format(aBuf, sizeof(aBuf), Localize("No updates available")); + Label.VSplitLeft(TextRender()->TextWidth(0, 14.0f, aBuf, -1) + 10.0f, &Label, &Button); + Button.VSplitLeft(100.0f, &Button, 0); + static int s_ButtonUpdate = 0; + if(DoButton_Menu(&s_ButtonUpdate, Localize("Check now"), 0, &Button)) + { + Client()->CheckVersionUpdate(); + } + } + UI()->DoLabelScaled(&Label, aBuf, 14.0f, -1); + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } +#endif + + { + Right.HSplitTop(20.0f, &Button, &Right); + Button.VSplitLeft(190.0f, &Label, &Button); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Timeout code")); + UI()->DoLabelScaled(&Label, aBuf, 14.0, -1); + static float s_OffsetCode = 0.0f; + DoEditBox(g_Config.m_ClTimeoutCode, &Button, g_Config.m_ClTimeoutCode, sizeof(g_Config.m_ClTimeoutCode), 14.0f, &s_OffsetCode); + } + + Right.HSplitTop(5.0f, &Button, &Right); + + { + Right.HSplitTop(20.0f, &Button, &Right); + Button.VSplitLeft(190.0f, &Label, &Button); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s:", Localize("Dummy Timeout code")); + UI()->DoLabelScaled(&Label, aBuf, 14.0, -1); + static float s_OffsetCode = 0.0f; + DoEditBox(g_Config.m_ClDummyTimeoutCode, &Button, g_Config.m_ClDummyTimeoutCode, sizeof(g_Config.m_ClDummyTimeoutCode), 14.0f, &s_OffsetCode); + } +} diff --git a/src/game/client/components/motd.cpp b/src/game/client/components/motd.cpp new file mode 100644 index 0000000..5f4249c --- /dev/null +++ b/src/game/client/components/motd.cpp @@ -0,0 +1,100 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/keys.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> +#include <game/client/gameclient.h> + +#include "motd.h" + +void CMotd::Clear() +{ + m_ServerMotdTime = 0; +} + +bool CMotd::IsActive() +{ + return time_get() < m_ServerMotdTime; +} + +void CMotd::OnStateChange(int NewState, int OldState) +{ + if(OldState == IClient::STATE_ONLINE || OldState == IClient::STATE_OFFLINE) + Clear(); +} + +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; + float y = 150.0f; + + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.5f); + RenderTools()->DrawRoundRect(x, y, w, h, 40.0f); + Graphics()->QuadsEnd(); + + TextRender()->Text(0, x+40.0f, y+40.0f, 32.0f, m_aServerMotd, (int)(w-80.0f)); +} + +void CMotd::OnMessage(int MsgType, void *pRawMsg) +{ + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + return; + + if(MsgType == NETMSGTYPE_SV_MOTD) + { + CNetMsg_Sv_Motd *pMsg = (CNetMsg_Sv_Motd *)pRawMsg; + + char* pLast = m_aServerMotd; + // process escaping + str_copy(m_aServerMotd, pMsg->m_pMessage, sizeof(m_aServerMotd)); + for(int i = 0; m_aServerMotd[i]; i++) + { + if(m_aServerMotd[i] == '\\') + { + if(m_aServerMotd[i+1] == 'n') + { + m_aServerMotd[i] = '\0'; + m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "motd", pLast, true); + m_aServerMotd[i] = ' '; + m_aServerMotd[i+1] = '\n'; + i++; + pLast = m_aServerMotd+i+1; + } + } + } + if(*pLast) + m_pClient->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "motd", pLast, true); + + if(m_aServerMotd[0] && g_Config.m_ClMotdTime) + m_ServerMotdTime = time_get()+time_freq()*g_Config.m_ClMotdTime; + else + m_ServerMotdTime = 0; + } +} + +bool CMotd::OnInput(IInput::CEvent Event) +{ + if(IsActive() && Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) + { + Clear(); + return true; + } + return false; +} diff --git a/src/game/client/components/motd.h b/src/game/client/components/motd.h new file mode 100644 index 0000000..f47adaf --- /dev/null +++ b/src/game/client/components/motd.h @@ -0,0 +1,23 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_MOTD_H +#define GAME_CLIENT_COMPONENTS_MOTD_H +#include <game/client/component.h> + +class CMotd : public CComponent +{ + // motd + int64 m_ServerMotdTime; +public: + char m_aServerMotd[900]; + + void Clear(); + bool IsActive(); + + virtual void OnRender(); + virtual void OnStateChange(int NewState, int OldState); + virtual void OnMessage(int MsgType, void *pRawMsg); + virtual bool OnInput(IInput::CEvent Event); +}; + +#endif diff --git a/src/game/client/components/nameplates.cpp b/src/game/client/components/nameplates.cpp new file mode 100644 index 0000000..d41bd9f --- /dev/null +++ b/src/game/client/components/nameplates.cpp @@ -0,0 +1,110 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/textrender.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include "nameplates.h" +#include "controls.h" + +void CNamePlates::RenderNameplate( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPlayerInfo + ) +{ + float IntraTick = Client()->IntraGameTick(); + + vec2 Position = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), IntraTick); + + bool OtherTeam; + + if (m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_Team == TEAM_SPECTATORS && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + OtherTeam = false; + else if (m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) + OtherTeam = m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID); + else + OtherTeam = m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_LocalClientID); + + float FontSize = 18.0f + 20.0f * g_Config.m_ClNameplatesSize / 100.0f; + float FontSizeClan = 18.0f + 20.0f * g_Config.m_ClNameplatesClanSize / 100.0f; + // render name plate + if(!pPlayerInfo->m_Local) + { + float a = 1; + if(g_Config.m_ClNameplatesAlways == 0) + a = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy], 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); + + vec3 rgb = vec3(1.0f, 1.0f, 1.0f); + if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID)) + rgb = HslToRgb(vec3(m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID) / 64.0f, 1.0f, 0.75f)); + + if (OtherTeam) + { + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.2f); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, g_Config.m_ClShowOthersAlpha / 100.0f); + } + else + { + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.5f*a); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, a); + } + if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + if(pPlayerInfo->m_Team == TEAM_RED) + TextRender()->TextColor(1.0f, 0.5f, 0.5f, a); + 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_ClNameplatesClan) + { + const char *pClan = m_pClient->m_aClients[pPlayerInfo->m_ClientID].m_aClan; + float tw_clan = TextRender()->TextWidth(0, FontSizeClan, pClan, -1); + TextRender()->Text(0, Position.x-tw_clan/2.0f, Position.y-FontSize-FontSizeClan-38.0f, FontSizeClan, pClan, -1); + } + + if(g_Config.m_Debug) // render client id when in debug aswell + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf),"%d", pPlayerInfo->m_ClientID); + float Offset = g_Config.m_ClNameplatesClan ? (FontSize * 2 + FontSizeClan) : (FontSize * 2); + float tw_id = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, Position.x-tw_id/2.0f, Position.y-Offset-38.0f, 28.0f, aBuf, -1); + } + + TextRender()->TextColor(1,1,1,1); + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); + } +} + +void CNamePlates::OnRender() +{ + if (!g_Config.m_ClNameplates || m_pClient->AntiPingPlayers()) + return; + + for(int i = 0; i < MAX_CLIENTS; i++) + { + // only render active characters + if(!m_pClient->m_Snap.m_aCharacters[i].m_Active) + continue; + + const void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i); + + if(pInfo) + { + RenderNameplate( + &m_pClient->m_Snap.m_aCharacters[i].m_Prev, + &m_pClient->m_Snap.m_aCharacters[i].m_Cur, + (const CNetObj_PlayerInfo *)pInfo); + } + } +} diff --git a/src/game/client/components/nameplates.h b/src/game/client/components/nameplates.h new file mode 100644 index 0000000..a3516a0 --- /dev/null +++ b/src/game/client/components/nameplates.h @@ -0,0 +1,19 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_NAMEPLATES_H +#define GAME_CLIENT_COMPONENTS_NAMEPLATES_H +#include <game/client/component.h> + +class CNamePlates : public CComponent +{ + void RenderNameplate( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPlayerInfo + ); + +public: + virtual void OnRender(); +}; + +#endif diff --git a/src/game/client/components/particles.cpp b/src/game/client/components/particles.cpp new file mode 100644 index 0000000..66a62f1 --- /dev/null +++ b/src/game/client/components/particles.cpp @@ -0,0 +1,188 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> +#include <engine/graphics.h> +#include <engine/demo.h> + +#include <game/generated/client_data.h> +#include <game/client/render.h> +#include <game/gamecore.h> +#include "particles.h" + +CParticles::CParticles() +{ + OnReset(); + m_RenderTrail.m_pParts = this; + m_RenderExplosions.m_pParts = this; + m_RenderGeneral.m_pParts = this; +} + + +void CParticles::OnReset() +{ + // reset particles + for(int i = 0; i < MAX_PARTICLES; i++) + { + 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; + + for(int i = 0; i < NUM_GROUPS; i++) + m_aFirstPart[i] = -1; +} + +void CParticles::Add(int Group, CParticle *pPart) +{ + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(pInfo->m_Paused) + return; + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_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; +} + +void CParticles::Update(float TimePassed) +{ + static float FrictionFraction = 0; + FrictionFraction += 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]; + while(i != -1) + { + 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; + + // check particle death + if(m_aParticles[i].m_Life > m_aParticles[i].m_LifeSpan) + { + // remove it from the group list + if(m_aParticles[i].m_PrevPart != -1) + 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; + m_aParticles[i].m_PrevPart = -1; + m_aParticles[i].m_NextPart = m_FirstFree; + m_FirstFree = i; + } + + i = Next; + } + } +} + +void CParticles::OnRender() +{ + if(Client()->State() < IClient::STATE_ONLINE) + return; + + static int64 LastTime = 0; + int64 t = time_get(); + + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(!pInfo->m_Paused) + Update((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed); + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + Update((float)((t-LastTime)/(double)time_freq())); + } + + LastTime = t; +} + +void CParticles::RenderGroup(int Group) +{ + Graphics()->BlendNormal(); + //gfx_blend_additive(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); + Graphics()->QuadsBegin(); + + int i = m_aFirstPart[Group]; + while(i != -1) + { + RenderTools()->SelectSprite(m_aParticles[i].m_Spr); + float a = m_aParticles[i].m_Life / m_aParticles[i].m_LifeSpan; + vec2 p = m_aParticles[i].m_Pos; + float Size = mix(m_aParticles[i].m_StartSize, m_aParticles[i].m_EndSize, a); + + Graphics()->QuadsSetRotation(m_aParticles[i].m_Rot); + + Graphics()->SetColor( + 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) * + + IGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size); + Graphics()->QuadsDraw(&QuadItem, 1); + + i = m_aParticles[i].m_NextPart; + } + Graphics()->QuadsEnd(); + Graphics()->BlendNormal(); +} diff --git a/src/game/client/components/particles.h b/src/game/client/components/particles.h new file mode 100644 index 0000000..176a2b0 --- /dev/null +++ b/src/game/client/components/particles.h @@ -0,0 +1,96 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_PARTICLES_H +#define GAME_CLIENT_COMPONENTS_PARTICLES_H +#include <base/vmath.h> +#include <game/client/component.h> + +// particles +struct CParticle +{ + void SetDefault() + { + m_Vel = vec2(0,0); + m_LifeSpan = 0; + m_StartSize = 32; + m_EndSize = 32; + m_Rot = 0; + m_Rotspeed = 0; + m_Gravity = 0; + m_Friction = 0; + m_FlowAffected = 1.0f; + m_Color = vec4(1,1,1,1); + } + + vec2 m_Pos; + vec2 m_Vel; + + int m_Spr; + + float m_FlowAffected; + + float m_LifeSpan; + + float m_StartSize; + float m_EndSize; + + float m_Rot; + float m_Rotspeed; + + float m_Gravity; + float m_Friction; + + vec4 m_Color; + + // set by the particle system + float m_Life; + int m_PrevPart; + int m_NextPart; +}; + +class CParticles : public CComponent +{ + friend class CGameClient; +public: + enum + { + GROUP_PROJECTILE_TRAIL=0, + GROUP_EXPLOSIONS, + GROUP_GENERAL, + NUM_GROUPS + }; + + CParticles(); + + void Add(int Group, CParticle *pPart); + + virtual void OnReset(); + virtual void OnRender(); + +private: + + enum + { + MAX_PARTICLES=1024*8, + }; + + CParticle m_aParticles[MAX_PARTICLES]; + int m_FirstFree; + int m_aFirstPart[NUM_GROUPS]; + + void RenderGroup(int Group); + void Update(float TimePassed); + + template<int TGROUP> + class CRenderGroup : public CComponent + { + public: + 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; +}; +#endif diff --git a/src/game/client/components/players.cpp b/src/game/client/components/players.cpp new file mode 100644 index 0000000..7350014 --- /dev/null +++ b/src/game/client/components/players.cpp @@ -0,0 +1,1071 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/sorted_array.h> + +#include <engine/demo.h> +#include <engine/engine.h> +#include <engine/graphics.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <game/gamecore.h> // get_angle +#include <game/client/animstate.h> +#include <game/client/gameclient.h> +#include <game/client/ui.h> +#include <game/client/render.h> + +#include <game/client/components/flow.h> +#include <game/client/components/skins.h> +#include <game/client/components/effects.h> +#include <game/client/components/sounds.h> +#include <game/client/components/controls.h> + +#include <engine/textrender.h> + +#include "players.h" +#include <stdio.h> + +void CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset) +{ + // for drawing hand + //const skin *s = skin_get(skin_id); + + float BaseSize = 10.0f; + //dir = normalize(hook_pos-pos); + + vec2 HandPos = CenterPos + Dir; + float Angle = GetAngle(Dir); + if (Dir.x < 0) + Angle -= AngleOffset; + else + Angle += AngleOffset; + + vec2 DirX = Dir; + vec2 DirY(-Dir.y,Dir.x); + + if (Dir.x < 0) + DirY = -DirY; + + HandPos += DirX * PostRotOffset.x; + HandPos += DirY * PostRotOffset.y; + + //Graphics()->TextureSet(data->m_aImages[IMAGE_CHAR_DEFAULT].id); + Graphics()->TextureSet(pInfo->m_Texture); + Graphics()->QuadsBegin(); + Graphics()->SetColor(pInfo->m_ColorBody.r, pInfo->m_ColorBody.g, pInfo->m_ColorBody.b, pInfo->m_ColorBody.a); + + // two passes + for (int i = 0; i < 2; i++) + { + bool OutLine = i == 0; + + RenderTools()->SelectSprite(OutLine?SPRITE_TEE_HAND_OUTLINE:SPRITE_TEE_HAND, 0, 0, 0); + Graphics()->QuadsSetRotation(Angle); + IGraphics::CQuadItem QuadItem(HandPos.x, HandPos.y, 2*BaseSize, 2*BaseSize); + Graphics()->QuadsDraw(&QuadItem, 1); + } + + Graphics()->QuadsSetRotation(0); + Graphics()->QuadsEnd(); +} + +inline float NormalizeAngular(float f) +{ + return fmod(f+pi*2, pi*2); +} + +inline float AngularMixDirection (float Src, float Dst) { return sinf(Dst-Src) >0?1:-1; } +inline float AngularDistance(float Src, float Dst) { return asinf(sinf(Dst-Src)); } + +inline float AngularApproach(float Src, float Dst, float Amount) +{ + float d = AngularMixDirection (Src, Dst); + float n = Src + Amount*d; + if(AngularMixDirection (n, Dst) != d) + return Dst; + return n; +} + +void CPlayers::Predict( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPrevInfo, + const CNetObj_PlayerInfo *pPlayerInfo, + vec2 &PrevPredPos, + vec2 &SmoothPos, + int &MoveCnt, + vec2 &Position + ) +{ + CNetObj_Character Prev; + CNetObj_Character Player; + Prev = *pPrevChar; + Player = *pPlayerChar; + + CNetObj_PlayerInfo pInfo = *pPlayerInfo; + + + // set size + + float IntraTick = Client()->IntraGameTick(); + + + //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 + } + else + { + /* + 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; + else + angle = angular_approach(current, target, fabs(delta-new_delta)); + + g_GameClient.m_aClients[info.cid].angle = angle;*/ + } + +vec2 NonPredPos = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); + + // use preditect players if needed + if(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + // apply predicted results + m_pClient->m_aClients[pInfo.m_ClientID].m_Predicted.Write(&Player); + m_pClient->m_aClients[pInfo.m_ClientID].m_PrevPredicted.Write(&Prev); + + IntraTick = Client()->PredIntraGameTick(); + } + } + + Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); + + + static double ping = 0; + + if(pInfo.m_Local) { + ping = mix(ping, (double)pInfo.m_Latency, 0.1); + } + + if(!pInfo.m_Local) + { + /* + for ping = 260, usual missprediction distances: + + move = 120-140 + jump = 130 + dj = 250 + + normalized: + move = 0.461 - 0.538 + jump = 0.5 + dj = .961 + + */ + //printf("%d\n", m_pClient->m_Snap.m_pLocalInfo->m_Latency); + + + if(m_pClient->m_Snap.m_pLocalInfo) + ping = mix(ping, (double)m_pClient->m_Snap.m_pLocalInfo->m_Latency, 0.1); + + double d = length(PrevPredPos - Position)/ping; + + if((d > 0.4) && (d < 5.)) + { +// if(MoveCnt == 0) +// printf("[\n"); + if(MoveCnt == 0) + SmoothPos = NonPredPos; + + MoveCnt = 10; +// SmoothPos = PrevPredPos; +// SmoothPos = mix(NonPredPos, Position, 0.6); + } + + PrevPredPos = Position; + + if(MoveCnt > 0) + { +// Position = mix(mix(NonPredPos, Position, 0.5), SmoothPos, (((float)MoveCnt))/15); +// Position = mix(mix(NonPredPos, Position, 0.5), SmoothPos, 0.5); + Position = mix(NonPredPos, Position, 0.5); + + SmoothPos = Position; + MoveCnt--; +// if(MoveCnt == 0) +// printf("]\n\n"); + } + } +} + +void CPlayers::RenderHook( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPrevInfo, + const CNetObj_PlayerInfo *pPlayerInfo, + const vec2 &parPosition, + const vec2 &PositionTo + ) +{ + CNetObj_Character Prev; + CNetObj_Character Player; + Prev = *pPrevChar; + Player = *pPlayerChar; + + CNetObj_PlayerInfo pInfo = *pPlayerInfo; + CTeeRenderInfo RenderInfo = m_aRenderInfo[pInfo.m_ClientID]; + + // don't render hooks to not active character cores + if (pPlayerChar->m_HookedPlayer != -1 && !m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Active) + return; + + float IntraTick = Client()->IntraGameTick(); + + bool OtherTeam; + + if (m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_Team == TEAM_SPECTATORS && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + OtherTeam = false; + else if (m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) + OtherTeam = m_pClient->m_Teams.Team(pInfo.m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID); + else + OtherTeam = m_pClient->m_Teams.Team(pInfo.m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_LocalClientID); + + if (OtherTeam) + { + RenderInfo.m_ColorBody.a = g_Config.m_ClShowOthersAlpha / 100.0f; + RenderInfo.m_ColorFeet.a = g_Config.m_ClShowOthersAlpha / 100.0f; + } + + // set size + RenderInfo.m_Size = 64.0f; + + if (!m_pClient->AntiPingPlayers()) + { + // use preditect players if needed + if(pInfo.m_Local && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(!m_pClient->m_Snap.m_pLocalCharacter || (m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + } + else + { + // apply predicted results + m_pClient->m_PredictedChar.Write(&Player); + m_pClient->m_PredictedPrevChar.Write(&Prev); + IntraTick = Client()->PredIntraGameTick(); + } + } + } + else + { + if(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + // apply predicted results + m_pClient->m_aClients[pInfo.m_ClientID].m_Predicted.Write(&Player); + m_pClient->m_aClients[pInfo.m_ClientID].m_PrevPredicted.Write(&Prev); + + IntraTick = Client()->PredIntraGameTick(); + } + } + } + + vec2 Position; + if (!m_pClient->AntiPingPlayers()) + Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); + else + Position = parPosition; + + // draw hook + if (Prev.m_HookState>0 && Player.m_HookState>0) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + //Graphics()->QuadsBegin(); + + vec2 Pos = Position; + vec2 HookPos; + + if (!m_pClient->AntiPingPlayers()) + { + if(pPlayerChar->m_HookedPlayer != -1) + { + if(m_pClient->m_Snap.m_pLocalInfo && pPlayerChar->m_HookedPlayer == m_pClient->m_Snap.m_pLocalInfo->m_ClientID) + { + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) // only use prediction if needed + HookPos = vec2(m_pClient->m_LocalCharacterPos.x, m_pClient->m_LocalCharacterPos.y); + else + HookPos = mix(vec2(m_pClient->m_PredictedPrevChar.m_Pos.x, m_pClient->m_PredictedPrevChar.m_Pos.y), + vec2(m_pClient->m_PredictedChar.m_Pos.x, m_pClient->m_PredictedChar.m_Pos.y), Client()->PredIntraGameTick()); + } + else if(pInfo.m_Local) + { + HookPos = mix(vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_X, + m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_Y), + vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_X, + m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_Y), + Client()->IntraGameTick()); + } + else + HookPos = mix(vec2(pPrevChar->m_HookX, pPrevChar->m_HookY), vec2(pPlayerChar->m_HookX, pPlayerChar->m_HookY), Client()->IntraGameTick()); + } + else + HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick); + } + else + { + if(pPrevChar->m_HookedPlayer != -1) + HookPos = PositionTo; + else + HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick); + } + + float d = distance(Pos, HookPos); + vec2 Dir = normalize(Pos-HookPos); + + Graphics()->QuadsSetRotation(GetAngle(Dir)+pi); + + // render head + RenderTools()->SelectSprite(SPRITE_HOOK_HEAD); + IGraphics::CQuadItem QuadItem(HookPos.x, HookPos.y, 24,16); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + Graphics()->QuadsDraw(&QuadItem, 1); + + // render chain + RenderTools()->SelectSprite(SPRITE_HOOK_CHAIN); + IGraphics::CQuadItem Array[1024]; + int i = 0; + for(float f = 24; f < d && i < 1024; f += 24, i++) + { + vec2 p = HookPos + Dir*f; + Array[i] = IGraphics::CQuadItem(p.x, p.y,24,16); + } + + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + Graphics()->QuadsDraw(Array, i); + Graphics()->QuadsSetRotation(0); + Graphics()->QuadsEnd(); + + RenderHand(&RenderInfo, Position, normalize(HookPos-Pos), -pi/2, vec2(20, 0)); + } +} + +void CPlayers::RenderPlayer( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPrevInfo, + const CNetObj_PlayerInfo *pPlayerInfo, + const vec2 &parPosition +/* vec2 &PrevPos, + vec2 &SmoothPos, + int &MoveCnt +*/ ) +{ + CNetObj_Character Prev; + CNetObj_Character Player; + Prev = *pPrevChar; + Player = *pPlayerChar; + + CNetObj_PlayerInfo pInfo = *pPlayerInfo; + CTeeRenderInfo RenderInfo = m_aRenderInfo[pInfo.m_ClientID]; + + bool NewTick = m_pClient->m_NewTick; + + bool OtherTeam; + + if (m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_Team == TEAM_SPECTATORS && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + OtherTeam = false; + else if (m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) + OtherTeam = m_pClient->m_Teams.Team(pInfo.m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID); + else + OtherTeam = m_pClient->m_Teams.Team(pInfo.m_ClientID) != m_pClient->m_Teams.Team(m_pClient->m_Snap.m_LocalClientID); + + // set size + RenderInfo.m_Size = 64.0f; + + float IntraTick = Client()->IntraGameTick(); + + float Angle; + if(pInfo.m_Local && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + // just use the direct input if it's the local player we are rendering + Angle = GetAngle(m_pClient->m_pControls->m_MousePos[g_Config.m_ClDummy]); + } + else + { + // If the player moves their weapon through top, then change + // the end angle by 2*Pi, so that the mix function will use the + // short path and not the long one. + if (Player.m_Angle > (256.0f * pi) && Prev.m_Angle < 0) + { + Player.m_Angle -= 256.0f * 2 * pi; + Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick) / 256.0f; + } + else if (Player.m_Angle < 0 && Prev.m_Angle > (256.0f * pi)) + { + Player.m_Angle += 256.0f * 2 * pi; + Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick) / 256.0f; + } + else + { + // No special cases? Just use mix(): + Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f; + } + } + + + // use preditect players if needed + if (!m_pClient->AntiPingPlayers()) + { + if(pInfo.m_Local && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(!m_pClient->m_Snap.m_pLocalCharacter || (m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + } + else + { + // apply predicted results + m_pClient->m_PredictedChar.Write(&Player); + m_pClient->m_PredictedPrevChar.Write(&Prev); + IntraTick = Client()->PredIntraGameTick(); + NewTick = m_pClient->m_NewPredictedTick; + } + } + } + else + { + if(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + // apply predicted results + m_pClient->m_aClients[pInfo.m_ClientID].m_Predicted.Write(&Player); + m_pClient->m_aClients[pInfo.m_ClientID].m_PrevPredicted.Write(&Prev); + + IntraTick = Client()->PredIntraGameTick(); + NewTick = m_pClient->m_NewPredictedTick; + } + } + } + + vec2 Direction = GetDirection((int)(Angle*256.0f)); + vec2 Position; + if (!m_pClient->AntiPingPlayers()) + Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); + else + Position = parPosition; + 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) + { + // detect air jump + if(!RenderInfo.m_GotAirJump && !(Prev.m_Jumped&2)) + m_pClient->m_pEffects->AirJump(Position); + } + + bool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1; + bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16); + bool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0); + + // evaluate animation + float WalkTime = fmod(absolute(Position.x), 100.0f)/100.0f; + CAnimState State; + State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); + + if(InAir) + State.Add(&g_pData->m_aAnimations[ANIM_INAIR], 0, 1.0f); // TODO: some sort of time here + else if(Stationary) + State.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); // TODO: some sort of time here + else if(!WantOtherDir) + State.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f); + + static float s_LastGameTickTime = Client()->GameTickTime(); + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + s_LastGameTickTime = Client()->GameTickTime(); + if (Player.m_Weapon == WEAPON_HAMMER) + { + float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; + State.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(ct*5.0f,0.0f,1.0f), 1.0f); + } + if (Player.m_Weapon == WEAPON_NINJA) + { + float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; + 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) + { + static int64 SkidSoundTime = 0; + if(time_get()-SkidSoundTime > time_freq()/10) + { + if(g_Config.m_SndGame) + m_pClient->m_pSounds->PlayAt(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) + ); + } + + // draw gun + { + if (Player.m_PlayerFlags&PLAYERFLAG_AIM && (g_Config.m_ClShowOtherHookColl || pPlayerInfo->m_Local)) + { + float Alpha = 1.0f; + if (OtherTeam) + Alpha = g_Config.m_ClShowOthersAlpha / 100.0f; + + vec2 ExDirection = Direction; + + if (pPlayerInfo->m_Local && Client()->State() != IClient::STATE_DEMOPLAYBACK) + ExDirection = normalize(vec2(m_pClient->m_pControls->m_InputData[g_Config.m_ClDummy].m_TargetX, m_pClient->m_pControls->m_InputData[g_Config.m_ClDummy].m_TargetY)); + + Graphics()->TextureSet(-1); + vec2 initPos = Position; + vec2 finishPos = initPos + ExDirection * (m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength-42.0f); + + Graphics()->LinesBegin(); + Graphics()->SetColor(1.00f, 0.0f, 0.0f, Alpha); + + float PhysSize = 28.0f; + + vec2 OldPos = initPos + ExDirection * PhysSize * 1.5f;; + vec2 NewPos = OldPos; + + bool doBreak = false; + int Hit = 0; + + do { + OldPos = NewPos; + NewPos = OldPos + ExDirection * m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookFireSpeed; + + if (distance(initPos, NewPos) > m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength) + { + NewPos = initPos + normalize(NewPos-initPos) * m_pClient->m_Tuning[g_Config.m_ClDummy].m_HookLength; + doBreak = true; + } + + int teleNr = 0; + Hit = Collision()->IntersectLineTeleHook(OldPos, NewPos, &finishPos, 0x0, &teleNr, true); + + if(!doBreak && Hit) { + if (!(Hit&CCollision::COLFLAG_NOHOOK)) + Graphics()->SetColor(130.0f/255.0f, 232.0f/255.0f, 160.0f/255.0f, Alpha); + } + + if(m_pClient->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking && m_pClient->IntersectCharacter(OldPos, finishPos, finishPos, pPlayerInfo->m_ClientID) != -1) + { + Graphics()->SetColor(1.0f, 1.0f, 0.0f, Alpha); + break; + } + + if(Hit) + break; + + NewPos.x = round_to_int(NewPos.x); + NewPos.y = round_to_int(NewPos.y); + + if (OldPos == NewPos) + break; + + ExDirection.x = round_to_int(ExDirection.x*256.0f) / 256.0f; + ExDirection.y = round_to_int(ExDirection.y*256.0f) / 256.0f; + } while (!doBreak); + + IGraphics::CLineItem LineItem(initPos.x, initPos.y, finishPos.x, finishPos.y); + Graphics()->LinesDraw(&LineItem, 1); + Graphics()->LinesEnd(); + } + + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + Graphics()->QuadsSetRotation(State.GetAttach()->m_Angle*pi*2+Angle); + + // normal weapons + int iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS-1); + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_pSpriteBody, Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0); + + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + + vec2 Dir = Direction; + float Recoil = 0.0f; + vec2 p; + if (Player.m_Weapon == WEAPON_HAMMER) + { + // Static position for hammer + p = Position + vec2(State.GetAttach()->m_X, State.GetAttach()->m_Y); + p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; + // if attack is under way, bash stuffs + if(Direction.x < 0) + { + Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); + p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; + } + else + { + Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); + } + RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); + } + else if (Player.m_Weapon == WEAPON_NINJA) + { + p = Position; + p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; + + if(Direction.x < 0) + { + Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); + p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; + m_pClient->m_pEffects->PowerupShine(p+vec2(32,0), vec2(32,12)); + } + else + { + Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); + m_pClient->m_pEffects->PowerupShine(p-vec2(32,0), vec2(32,12)); + } + RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); + + // HADOKEN + if ((Client()->GameTick()-Player.m_AttackTick) <= (SERVER_TICK_SPEED / 6) && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles) + { + int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; + static int s_LastIteX = IteX; + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(pInfo->m_Paused) + IteX = s_LastIteX; + else + s_LastIteX = IteX; + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + IteX = s_LastIteX; + else + s_LastIteX = IteX; + } + if(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX]) + { + vec2 Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y); + Dir = normalize(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); + vec2 DirY(-Dir.y,Dir.x); + p = Position; + float OffsetX = g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx; + p -= Dir * OffsetX; + RenderTools()->DrawSprite(p.x, p.y, 160.0f); + } + } + } + else + { + // TODO: should be an animation + Recoil = 0; + static float s_LastIntraTick = IntraTick; + if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) + s_LastIntraTick = IntraTick; + + float a = (Client()->GameTick()-Player.m_AttackTick+s_LastIntraTick)/5.0f; + if(a < 1) + Recoil = sinf(a*pi); + p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir*Recoil*10.0f; + p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; + if (Player.m_Weapon == WEAPON_GUN && g_Config.m_ClOldGunPosition) + p.y -= 8; + RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); + } + + if (Player.m_Weapon == WEAPON_GUN || Player.m_Weapon == WEAPON_SHOTGUN) + { + // check if we're firing stuff + if(g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)//prev.attackticks) + { + float Alpha = 0.0f; + int Phase1Tick = (Client()->GameTick() - Player.m_AttackTick); + if (Phase1Tick < (g_pData->m_Weapons.m_aId[iw].m_Muzzleduration + 3)) + { + float t = ((((float)Phase1Tick) + IntraTick)/(float)g_pData->m_Weapons.m_aId[iw].m_Muzzleduration); + Alpha = mix(2.0f, 0.0f, min(1.0f,max(0.0f,t))); + } + + int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; + static int s_LastIteX = IteX; + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); + if(pInfo->m_Paused) + IteX = s_LastIteX; + else + s_LastIteX = IteX; + } + else + { + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) + IteX = s_LastIteX; + else + s_LastIteX = IteX; + } + if (Alpha > 0.0f && g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX]) + { + float OffsetY = -g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsety; + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0); + if(Direction.x < 0) + OffsetY = -OffsetY; + + vec2 DirY(-Dir.y,Dir.x); + vec2 MuzzlePos = p + Dir * g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx + DirY * OffsetY; + + RenderTools()->DrawSprite(MuzzlePos.x, MuzzlePos.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); + } + } + } + Graphics()->QuadsEnd(); + + if (OtherTeam) + { + RenderInfo.m_ColorBody.a = g_Config.m_ClShowOthersAlpha / 100.0f; + RenderInfo.m_ColorFeet.a = g_Config.m_ClShowOthersAlpha / 100.0f; + } + + switch (Player.m_Weapon) + { + case WEAPON_GUN: RenderHand(&RenderInfo, p, Direction, -3*pi/4, vec2(-15, 4)); break; + case WEAPON_SHOTGUN: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-5, 4)); break; + case WEAPON_GRENADE: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-4, 7)); break; + } + + } + + // render the "shadow" tee + if(pInfo.m_Local && (g_Config.m_Debug || g_Config.m_ClUnpredictedShadow)) + { + vec2 GhostPosition = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), Client()->IntraGameTick()); + CTeeRenderInfo Ghost = RenderInfo; + Ghost.m_ColorBody.a = 0.5f; + Ghost.m_ColorFeet.a = 0.5f; + RenderTools()->RenderTee(&State, &Ghost, Player.m_Emote, Direction, GhostPosition, true); // render ghost + } + + RenderInfo.m_Size = 64.0f; // force some settings + + if (OtherTeam) + { + RenderInfo.m_ColorBody.a = g_Config.m_ClShowOthersAlpha / 100.0f; + RenderInfo.m_ColorFeet.a = g_Config.m_ClShowOthersAlpha / 100.0f; + } + + if (g_Config.m_ClShowDirection && (!pInfo.m_Local || DemoPlayer()->IsPlaying())) + { + if (Player.m_Direction == -1) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_ARROW].m_Id); + Graphics()->QuadsBegin(); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + IGraphics::CQuadItem QuadItem(Position.x-30, Position.y - 70, 22, 22); + Graphics()->QuadsSetRotation(GetAngle(vec2(1,0))+pi); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + else if (Player.m_Direction == 1) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_ARROW].m_Id); + Graphics()->QuadsBegin(); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + IGraphics::CQuadItem QuadItem(Position.x+30, Position.y - 70, 22, 22); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + if (Player.m_Jumped&1) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_ARROW].m_Id); + Graphics()->QuadsBegin(); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + IGraphics::CQuadItem QuadItem(Position.x, Position.y - 70, 22, 22); + Graphics()->QuadsSetRotation(GetAngle(vec2(0,1))+pi); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + } + + RenderTools()->RenderTee(&State, &RenderInfo, Player.m_Emote, Direction, Position, OtherTeam); + + if(Player.m_PlayerFlags&PLAYERFLAG_CHATTING) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(SPRITE_DOTDOT); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_ClShowOthersAlpha / 100.0f); + IGraphics::CQuadItem QuadItem(Position.x + 24, Position.y - 40, 64,64); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + if (m_pClient->m_aClients[pInfo.m_ClientID].m_EmoticonStart != -1 && m_pClient->m_aClients[pInfo.m_ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() > Client()->GameTick()) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); + Graphics()->QuadsBegin(); + + int SinceStart = Client()->GameTick() - m_pClient->m_aClients[pInfo.m_ClientID].m_EmoticonStart; + int FromEnd = m_pClient->m_aClients[pInfo.m_ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() - Client()->GameTick(); + + float a = 1; + + if (FromEnd < Client()->GameTickSpeed() / 5) + a = FromEnd / (Client()->GameTickSpeed() / 5.0); + + float h = 1; + if (SinceStart < Client()->GameTickSpeed() / 10) + h = SinceStart / (Client()->GameTickSpeed() / 10.0); + + float Wiggle = 0; + if (SinceStart < Client()->GameTickSpeed() / 5) + Wiggle = SinceStart / (Client()->GameTickSpeed() / 5.0); + + float WiggleAngle = sinf(5*Wiggle); + + Graphics()->QuadsSetRotation(pi/6*WiggleAngle); + + Graphics()->SetColor(1.0f,1.0f,1.0f,a); + if (OtherTeam) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, a * (float) g_Config.m_ClShowOthersAlpha / 100.0f); + // client_datas::emoticon is an offset from the first emoticon + RenderTools()->SelectSprite(SPRITE_OOP + m_pClient->m_aClients[pInfo.m_ClientID].m_Emoticon); + IGraphics::CQuadItem QuadItem(Position.x, Position.y - 23 - 32*h, 64, 64*h); + Graphics()->QuadsDraw(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + if(g_Config.m_ClNameplates && m_pClient->AntiPingPlayers()) + { + float FontSize = 18.0f + 20.0f * g_Config.m_ClNameplatesSize / 100.0f; + float FontSizeClan = 18.0f + 20.0f * g_Config.m_ClNameplatesClanSize / 100.0f; + // render name plate + if(!pPlayerInfo->m_Local) + { + float a = 1; + if(g_Config.m_ClNameplatesAlways == 0) + a = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos[g_Config.m_ClDummy], 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); + + vec3 rgb = vec3(1.0f, 1.0f, 1.0f); + if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID)) + rgb = HslToRgb(vec3(m_pClient->m_Teams.Team(pPlayerInfo->m_ClientID) / 64.0f, 1.0f, 0.75f)); + + if (OtherTeam) + { + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.2f); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, g_Config.m_ClShowOthersAlpha / 100.0f); + } + else + { + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.5f*a); + TextRender()->TextColor(rgb.r, rgb.g, rgb.b, a); + } + if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + if(pPlayerInfo->m_Team == TEAM_RED) + TextRender()->TextColor(1.0f, 0.5f, 0.5f, a); + 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_ClNameplatesClan) + { + const char *pClan = m_pClient->m_aClients[pPlayerInfo->m_ClientID].m_aClan; + float tw_clan = TextRender()->TextWidth(0, FontSizeClan, pClan, -1); + TextRender()->Text(0, Position.x-tw_clan/2.0f, Position.y-FontSize-FontSizeClan-38.0f, FontSizeClan, pClan, -1); + } + + if(g_Config.m_Debug) // render client id when in debug aswell + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf),"%d", pPlayerInfo->m_ClientID); + float Offset = g_Config.m_ClNameplatesClan ? (FontSize * 2 + FontSizeClan) : (FontSize * 2); + float tw_id = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, Position.x-tw_id/2.0f, Position.y-Offset-38.0f, 28.0f, aBuf, -1); + } + + TextRender()->TextColor(1,1,1,1); + TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); + } + } +} + +void CPlayers::OnRender() +{ + // update RenderInfo for ninja + bool IsTeamplay = false; + if(m_pClient->m_Snap.m_pGameInfoObj) + IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + m_aRenderInfo[i] = m_pClient->m_aClients[i].m_RenderInfo; + if(m_pClient->m_Snap.m_aCharacters[i].m_Cur.m_Weapon == WEAPON_NINJA && g_Config.m_ClShowNinja) + { + // change the skin for the player to the ninja + int Skin = m_pClient->m_pSkins->Find("x_ninja"); + if(Skin != -1) + { + if(IsTeamplay) + m_aRenderInfo[i].m_Texture = m_pClient->m_pSkins->Get(Skin)->m_ColorTexture; + else + { + m_aRenderInfo[i].m_Texture = m_pClient->m_pSkins->Get(Skin)->m_OrgTexture; + m_aRenderInfo[i].m_ColorBody = vec4(1,1,1,1); + m_aRenderInfo[i].m_ColorFeet = vec4(1,1,1,1); + } + } + } + } + + static vec2 PrevPos[MAX_CLIENTS]; + static vec2 SmoothPos[MAX_CLIENTS]; + static int MoveCnt[MAX_CLIENTS] = {0}; + static vec2 PredictedPos[MAX_CLIENTS]; + + static int predcnt = 0; + + if (m_pClient->AntiPingPlayers()) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!m_pClient->m_Snap.m_aCharacters[i].m_Active) + continue; + const void *pPrevInfo = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_PLAYERINFO, i); + const void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i); + + if(pPrevInfo && pInfo) + { + CNetObj_Character PrevChar = m_pClient->m_Snap.m_aCharacters[i].m_Prev; + CNetObj_Character CurChar = m_pClient->m_Snap.m_aCharacters[i].m_Cur; + + Predict( + &PrevChar, + &CurChar, + (const CNetObj_PlayerInfo *)pPrevInfo, + (const CNetObj_PlayerInfo *)pInfo, + PrevPos[i], + SmoothPos[i], + MoveCnt[i], + PredictedPos[i] + ); + } + } + + if(m_pClient->AntiPingPlayers() && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + // double ping = m_pClient->m_Snap.m_pLocalInfo->m_Latency; + // static double fps; + // fps = mix(fps, (1. / Client()->RenderFrameTime()), 0.1); + + // int predmax = (fps * ping / 1000.); + + int predmax = 19; + // if( 0 <= predmax && predmax <= 100) + predcnt = (predcnt + 1) % predmax; + // else + // predcnt = (predcnt + 1) % 2; + } + } + + // render other players in two passes, first pass we render the other, second pass we render our self + for(int p = 0; p < 4; p++) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + // only render active characters + if(!m_pClient->m_Snap.m_aCharacters[i].m_Active) + continue; + + const void *pPrevInfo = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_PLAYERINFO, i); + const void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i); + + if(pPrevInfo && pInfo) + { + // + 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; + + if(p<2) + { + if(PrevChar.m_HookedPlayer != -1) + RenderHook( + &PrevChar, + &CurChar, + (const CNetObj_PlayerInfo *)pPrevInfo, + (const CNetObj_PlayerInfo *)pInfo, + PredictedPos[i], + PredictedPos[PrevChar.m_HookedPlayer] + ); + else + RenderHook( + &PrevChar, + &CurChar, + (const CNetObj_PlayerInfo *)pPrevInfo, + (const CNetObj_PlayerInfo *)pInfo, + PredictedPos[i], + PredictedPos[i] + ); + } + else + { + RenderPlayer( + &PrevChar, + &CurChar, + (const CNetObj_PlayerInfo *)pPrevInfo, + (const CNetObj_PlayerInfo *)pInfo, + PredictedPos[i] + ); + } + } + } + } +} diff --git a/src/game/client/components/players.h b/src/game/client/components/players.h new file mode 100644 index 0000000..d5073d8 --- /dev/null +++ b/src/game/client/components/players.h @@ -0,0 +1,46 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_PLAYERS_H +#define GAME_CLIENT_COMPONENTS_PLAYERS_H +#include <game/client/component.h> + +class CPlayers : public CComponent +{ + CTeeRenderInfo m_aRenderInfo[MAX_CLIENTS]; + 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, + const vec2 &Position +/* vec2 &PrevPredPos, + vec2 &SmoothPos, + int &MoveCnt +*/ + ); + void RenderHook( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPrevInfo, + const CNetObj_PlayerInfo *pPlayerInfo, + const vec2 &Position, + const vec2 &PositionTo + ); + + void Predict( + const CNetObj_Character *pPrevChar, + const CNetObj_Character *pPlayerChar, + const CNetObj_PlayerInfo *pPrevInfo, + const CNetObj_PlayerInfo *pPlayerInfo, + vec2 &PrevPredPos, + vec2 &SmoothPos, + int &MoveCnt, + vec2 &Position + ); + +public: + virtual void OnRender(); +}; + +#endif diff --git a/src/game/client/components/race_demo.cpp b/src/game/client/components/race_demo.cpp new file mode 100644 index 0000000..fa62361 --- /dev/null +++ b/src/game/client/components/race_demo.cpp @@ -0,0 +1,214 @@ +/* (c) Redix and Sushi */ + +#include <stdio.h> + +#include <base/system.h> +#include <engine/shared/config.h> +#include <engine/serverbrowser.h> +#include <engine/storage.h> + +#include "menus.h" +#include "race_demo.h" + +CRaceDemo::CRaceDemo() +{ + m_RaceState = RACE_NONE; + m_RecordStopTime = 0; + m_Time = 0; + m_DemoStartTick = 0; +} + +void CRaceDemo::Stop() +{ + if(Client()->RaceRecordIsRecording()) + Client()->RaceRecordStop(); + + char aFilename[512]; + str_format(aFilename, sizeof(aFilename), "demos/%s_tmp_%d.demo", m_pMap, pid()); + Storage()->RemoveFile(aFilename, IStorage::TYPE_SAVE); + + m_Time = 0; + m_RaceState = RACE_NONE; + m_RecordStopTime = 0; + m_DemoStartTick = 0; +} + +void CRaceDemo::OnStateChange(int NewState, int OldState) +{ + if(OldState == IClient::STATE_ONLINE) + Stop(); +} + +void CRaceDemo::OnRender() +{ + if(!g_Config.m_ClAutoRaceRecord || !m_pClient->m_Snap.m_pGameInfoObj || m_pClient->m_Snap.m_SpecInfo.m_Active || Client()->State() != IClient::STATE_ONLINE) + return; + + // start the demo + if(m_DemoStartTick < Client()->GameTick()) + { + bool start = false; + std::list < int > Indices = m_pClient->Collision()->GetMapIndices(m_pClient->m_PredictedPrevChar.m_Pos, m_pClient->m_LocalCharacterPos); + if(!Indices.empty()) + for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + { + if(m_pClient->Collision()->GetTileIndex(*i) == TILE_BEGIN) start = true; + if(m_pClient->Collision()->GetFTileIndex(*i) == TILE_BEGIN) start = true; + } + else + { + if(m_pClient->Collision()->GetTileIndex(m_pClient->Collision()->GetPureMapIndex(m_pClient->m_LocalCharacterPos)) == TILE_BEGIN) start = true; + if(m_pClient->Collision()->GetFTileIndex(m_pClient->Collision()->GetPureMapIndex(m_pClient->m_LocalCharacterPos)) == TILE_BEGIN) start = true; + } + + if(start) + { + OnReset(); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "tmp_%d", pid()); + m_pMap = Client()->RaceRecordStart(aBuf); + m_DemoStartTick = Client()->GameTick() + Client()->GameTickSpeed(); + m_RaceState = RACE_STARTED; + } + } + + // stop the demo + if(m_RaceState == RACE_FINISHED && m_RecordStopTime < Client()->GameTick() && m_Time > 0) + { + CheckDemo(); + OnReset(); + } +} + +void CRaceDemo::OnReset() +{ + if(Client()->State() == IClient::STATE_ONLINE) + Stop(); +} + +void CRaceDemo::OnShutdown() +{ + Stop(); +} + +void CRaceDemo::OnMessage(int MsgType, void *pRawMsg) +{ + if(!g_Config.m_ClAutoRaceRecord || Client()->State() != IClient::STATE_ONLINE || m_pClient->m_Snap.m_SpecInfo.m_Active) + return; + + // check for messages from server + if(MsgType == NETMSGTYPE_SV_KILLMSG) + { + CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; + if(pMsg->m_Victim == m_pClient->m_Snap.m_LocalClientID && m_RaceState == RACE_FINISHED) + { + // check for new record + CheckDemo(); + OnReset(); + } + } + else if(MsgType == NETMSGTYPE_SV_CHAT) + { + CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; + if(pMsg->m_ClientID == -1 && m_RaceState == RACE_STARTED) + { + const char* pMessage = pMsg->m_pMessage; + + int Num = 0; + while(str_comp_num(pMessage, " finished in: ", 14)) + { + pMessage++; + Num++; + if(!pMessage[0]) + return; + } + + // store the name + char aName[64]; + str_copy(aName, pMsg->m_pMessage, Num+1); + + // prepare values and state for saving + int Minutes; + float Seconds; + if(!str_comp(aName, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName) && sscanf(pMessage, " finished in: %d minute(s) %f", &Minutes, &Seconds) == 2) + { + m_RaceState = RACE_FINISHED; + m_RecordStopTime = Client()->GameTick() + Client()->GameTickSpeed(); + m_Time = Minutes*60 + Seconds; + } + } + } +} + +void CRaceDemo::CheckDemo() +{ + // stop the demo recording + Client()->RaceRecordStop(); + + char aTmpDemoName[128]; + str_format(aTmpDemoName, sizeof(aTmpDemoName), "%s_tmp_%d", m_pMap, pid()); + + // loop through demo files + m_pClient->m_pMenus->DemolistPopulate(); + for(int i = 0; i < m_pClient->m_pMenus->m_lDemos.size(); i++) + { + if(!str_comp_num(m_pClient->m_pMenus->m_lDemos[i].m_aName, m_pMap, str_length(m_pMap)) && str_comp_num(m_pClient->m_pMenus->m_lDemos[i].m_aName, aTmpDemoName, str_length(aTmpDemoName)) && str_length(m_pClient->m_pMenus->m_lDemos[i].m_aName) > str_length(m_pMap) && m_pClient->m_pMenus->m_lDemos[i].m_aName[str_length(m_pMap)] == '_') + { + const char *pDemo = m_pClient->m_pMenus->m_lDemos[i].m_aName; + + // set cursor + pDemo += str_length(m_pMap)+1; + float DemoTime = str_tofloat(pDemo); + if(m_Time < DemoTime) + { + // save new record + SaveDemo(m_pMap); + + // delete old demo + char aFilename[512]; + str_format(aFilename, sizeof(aFilename), "demos/%s.demo", m_pClient->m_pMenus->m_lDemos[i].m_aName); + Storage()->RemoveFile(aFilename, IStorage::TYPE_SAVE); + } + + m_Time = 0; + + return; + } + } + + // save demo if there is none + SaveDemo(m_pMap); + + m_Time = 0; +} + +void CRaceDemo::SaveDemo(const char* pDemo) +{ + char aNewFilename[512]; + char aOldFilename[512]; + if(g_Config.m_ClDemoName) + { + char aPlayerName[MAX_NAME_LENGTH]; + str_copy(aPlayerName, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName, sizeof(aPlayerName)); + + // check the player name + for(int i = 0; i < MAX_NAME_LENGTH; i++) + { + if(!aPlayerName[i]) + break; + + if(aPlayerName[i] == '\\' || aPlayerName[i] == '/' || aPlayerName[i] == '|' || aPlayerName[i] == ':' || aPlayerName[i] == '*' || aPlayerName[i] == '?' || aPlayerName[i] == '<' || aPlayerName[i] == '>' || aPlayerName[i] == '"') + aPlayerName[i] = '%'; + + str_format(aNewFilename, sizeof(aNewFilename), "demos/%s_%5.2f_%s.demo", pDemo, m_Time, aPlayerName); + } + } + else + str_format(aNewFilename, sizeof(aNewFilename), "demos/%s_%5.2f.demo", pDemo, m_Time); + + str_format(aOldFilename, sizeof(aOldFilename), "demos/%s_tmp_%d.demo", m_pMap, pid()); + + Storage()->RenameFile(aOldFilename, aNewFilename, IStorage::TYPE_SAVE); + + dbg_msg("racedemo", "Saved better demo"); +} diff --git a/src/game/client/components/race_demo.h b/src/game/client/components/race_demo.h new file mode 100644 index 0000000..45bba4d --- /dev/null +++ b/src/game/client/components/race_demo.h @@ -0,0 +1,41 @@ +/* (c) Redix and Sushi */ + +#ifndef GAME_CLIENT_COMPONENTS_RACE_DEMO_H +#define GAME_CLIENT_COMPONENTS_RACE_DEMO_H + +#include <game/client/gameclient.h> + +#include <game/client/component.h> + +class CRaceDemo : public CComponent +{ + int m_RecordStopTime; + int m_DemoStartTick; + float m_Time; + const char *m_pMap; + + void Stop(); + +public: + + int m_RaceState; + + enum + { + RACE_NONE = 0, + RACE_STARTED, + RACE_FINISHED, + }; + + CRaceDemo(); + + virtual void OnReset(); + virtual void OnStateChange(int NewState, int OldState); + virtual void OnRender(); + virtual void OnShutdown(); + virtual void OnMessage(int MsgType, void *pRawMsg); + + void CheckDemo(); + void SaveDemo(const char* pDemo); +}; +#endif diff --git a/src/game/client/components/scoreboard.cpp b/src/game/client/components/scoreboard.cpp new file mode 100644 index 0000000..ea9df58 --- /dev/null +++ b/src/game/client/components/scoreboard.cpp @@ -0,0 +1,697 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/demo.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> + +#include <game/generated/client_data.h> +#include <game/generated/protocol.h> + +#include <game/localization.h> +#include <game/client/animstate.h> +#include <game/client/gameclient.h> +#include <game/client/render.h> +#include <game/client/components/countryflags.h> +#include <game/client/components/motd.h> +#include <game/client/components/statboard.h> + +#include "scoreboard.h" + +#include <time.h> +#include <base/tl/string.h> +#include <engine/serverbrowser.h> + +CScoreboard::CScoreboard() +{ + OnReset(); +} + +void CScoreboard::ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData) +{ + CScoreboard *pSelf = (CScoreboard *)pUserData; + CServerInfo Info; + + pSelf->Client()->GetServerInfo(&Info); + pSelf->m_IsGameTypeRace = IsRace(&Info); + pSelf->m_Active = pResult->GetInteger(0) != 0; +} + +void CScoreboard::OnReset() +{ + m_Active = false; + m_ServerRecord = -1.0f; +} + +void CScoreboard::OnRelease() +{ + m_Active = false; +} + +void CScoreboard::OnMessage(int MsgType, void *pRawMsg) +{ + if(MsgType == NETMSGTYPE_SV_RECORD) + { + CNetMsg_Sv_Record *pMsg = (CNetMsg_Sv_Record *)pRawMsg; + m_ServerRecord = (float)pMsg->m_ServerTimeBest/100; + //m_PlayerRecord = (float)pMsg->m_PlayerTimeBest/100; + } +} + +void CScoreboard::OnConsoleInit() +{ + Console()->Register("+scoreboard", "", CFGFLAG_CLIENT, ConKeyScoreboard, this, "Show scoreboard"); +} + +void CScoreboard::RenderGoals(float x, float y, float w) +{ + float h = 50.0f; + + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.5f); + RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); + Graphics()->QuadsEnd(); + + // render goals + y += 10.0f; + if(m_pClient->m_Snap.m_pGameInfoObj) + { + if(m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Score limit"), m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit); + TextRender()->Text(0, x+10.0f, y, 20.0f, aBuf, -1); + } + if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), Localize("Time limit: %d min"), m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit); + TextRender()->Text(0, x+230.0f, y, 20.0f, aBuf, -1); + } + if(m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum && m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%s %d/%d", Localize("Round"), m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent, m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum); + float tw = TextRender()->TextWidth(0, 20.0f, aBuf, -1); + TextRender()->Text(0, x+w-tw-10.0f, y, 20.0f, aBuf, -1); + } + } +} + +void CScoreboard::RenderSpectators(float x, float y, float w) +{ + float h = 140.0f; + + // background + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.5f); + RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); + Graphics()->QuadsEnd(); + + // Headline + y += 10.0f; + TextRender()->Text(0, x+10.0f, y, 28.0f, Localize("Spectators"), w-20.0f); + + // spectator names + y += 30.0f; + char aBuffer[1024*4]; + aBuffer[0] = 0; + bool Multiple = false; + for(int i = 0; i < MAX_CLIENTS; ++i) + { + const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByName[i]; + if(!pInfo || pInfo->m_Team != TEAM_SPECTATORS) + continue; + + if(Multiple) + str_append(aBuffer, ", ", sizeof(aBuffer)); + if(g_Config.m_ClShowIDs) + { + char aId[5]; + str_format(aId,sizeof(aId),"%d: ",pInfo->m_ClientID); + str_append(aBuffer, aId, sizeof(aBuffer)); + } + str_append(aBuffer, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, sizeof(aBuffer)); + Multiple = true; + } + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, x+10.0f, y, 22.0f, TEXTFLAG_RENDER); + Cursor.m_LineWidth = w-20.0f; + Cursor.m_MaxLines = 4; + TextRender()->TextEx(&Cursor, aBuffer, -1); +} + +void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const char *pTitle) +{ + if(Team == TEAM_SPECTATORS) + return; + + bool lower16 = false; + bool upper16 = false; + bool lower24 = false; + bool upper24 = false; + bool lower32 = false; + bool upper32 = false; + + if(Team == -3) + upper16 = true; + else if(Team == -4) + lower32 = true; + else if(Team == -5) + upper32 = true; + else if(Team == -6) + lower16 = true; + else if(Team == -7) + lower24 = true; + else if(Team == -8) + upper24 = true; + + if(Team < -1) + Team = 0; + + float h = 760.0f; + + // background + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.5f); + if(upper16 || upper32 || upper24) + RenderTools()->DrawRoundRectExt(x, y, w, h, 17.0f, 10); + else if(lower16 || lower32 || lower24) + RenderTools()->DrawRoundRectExt(x, y, w, h, 17.0f, 5); + else + RenderTools()->DrawRoundRect(x, y, w, h, 17.0f); + Graphics()->QuadsEnd(); + + // render title + float TitleFontsize = 40.0f; + if(!pTitle) + { + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + pTitle = Localize("Game over"); + else + pTitle = Localize("Score board"); + } + TextRender()->Text(0, x+20.0f, y, TitleFontsize, pTitle, -1); + + char aBuf[128] = {0}; + + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + if(m_pClient->m_Snap.m_pGameDataObj) + { + int Score = Team == TEAM_RED ? m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed : m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue; + str_format(aBuf, sizeof(aBuf), "%d", Score); + } + } + else + { + if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW && + m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]) + { + int Score = m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]->m_Score; + str_format(aBuf, sizeof(aBuf), "%d", Score); + } + else if(m_pClient->m_Snap.m_pLocalInfo) + { + int Score = m_pClient->m_Snap.m_pLocalInfo->m_Score; + str_format(aBuf, sizeof(aBuf), "%d", Score); + } + } + + if(m_IsGameTypeRace && g_Config.m_ClDDRaceScoreBoard) + { + if (m_ServerRecord > 0) + { + str_format(aBuf, sizeof(aBuf), "%02d:%02d", ((int) m_ServerRecord)/60, ((int) m_ServerRecord)%60); + } + else + aBuf[0] = 0; + } + + float tw; + + if (!lower16 && !lower32 && !lower24) + { + tw = TextRender()->TextWidth(0, TitleFontsize, aBuf, -1); + TextRender()->Text(0, x+w-tw-20.0f, y, TitleFontsize, aBuf, -1); + } + + // calculate measurements + x += 10.0f; + float LineHeight = 60.0f; + float TeeSizeMod = 1.0f; + float Spacing = 16.0f; + float RoundRadius = 15.0f; + if(m_pClient->m_Snap.m_aTeamSize[Team] > 48) + { + LineHeight = 20.0f; + TeeSizeMod = 0.4f; + Spacing = 0.0f; + RoundRadius = 5.0f; + } + else if(m_pClient->m_Snap.m_aTeamSize[Team] > 32) + { + LineHeight = 27.0f; + TeeSizeMod = 0.6f; + Spacing = 0.0f; + RoundRadius = 5.0f; + } + else if(m_pClient->m_Snap.m_aTeamSize[Team] > 12) + { + LineHeight = 40.0f; + TeeSizeMod = 0.8f; + Spacing = 0.0f; + RoundRadius = 15.0f; + } + else if(m_pClient->m_Snap.m_aTeamSize[Team] > 8) + { + LineHeight = 50.0f; + TeeSizeMod = 0.9f; + Spacing = 5.0f; + RoundRadius = 15.0f; + } + + float ScoreOffset = x+10.0f, ScoreLength = TextRender()->TextWidth(0, 22.0f/*HeadlineFontsize*/, "00:00:0", -1); + float TeeOffset = ScoreOffset+ScoreLength, TeeLength = 60*TeeSizeMod; + 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; + + // render headlines + y += 50.0f; + float HeadlineFontsize = 22.0f; + float ScoreWidth = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Score"), -1); + tw = ScoreLength > ScoreWidth ? ScoreLength : ScoreWidth; + 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); + + // render player entries + y += HeadlineFontsize*2.0f; + float FontSize = 24.0f; + if(m_pClient->m_Snap.m_aTeamSize[Team] > 48) + FontSize = 16.0f; + else if(m_pClient->m_Snap.m_aTeamSize[Team] > 32) + FontSize = 20.0f; + CTextCursor Cursor; + + int rendered = 0; + if (upper16) + rendered = -16; + if (upper32) + rendered = -32; + if (upper24) + rendered = -24; + + int OldDDTeam = -1; + + for(int i = 0; i < MAX_CLIENTS; i++) + { + // make sure that we render the correct team + const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByDDTeam[i]; + if(!pInfo || pInfo->m_Team != Team) + continue; + + if (rendered++ < 0) continue; + + int DDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo->m_ClientID); + int NextDDTeam = 0; + + for(int j = i + 1; j < MAX_CLIENTS; j++) + { + const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeam[j]; + + if(!pInfo2 || pInfo2->m_Team != Team) + continue; + + NextDDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo2->m_ClientID); + break; + } + + if (OldDDTeam == -1) + { + for (int j = i - 1; j >= 0; j--) + { + const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeam[j]; + + if(!pInfo2 || pInfo2->m_Team != Team) + continue; + + OldDDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo2->m_ClientID); + break; + } + } + + if (DDTeam != TEAM_FLOCK) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + vec3 rgb = HslToRgb(vec3(DDTeam / 64.0f, 1.0f, 0.5f)); + Graphics()->SetColor(rgb.r, rgb.g, rgb.b, 0.5f); + + int Corners = 0; + + if (OldDDTeam != DDTeam) + Corners |= CUI::CORNER_TL | CUI::CORNER_TR; + if (NextDDTeam != DDTeam) + Corners |= CUI::CORNER_BL | CUI::CORNER_BR; + + RenderTools()->DrawRoundRectExt(x - 10.0f, y, w, LineHeight + Spacing, RoundRadius, Corners); + + Graphics()->QuadsEnd(); + + if (NextDDTeam != DDTeam) + { + char aBuf[64]; + if(m_pClient->m_Snap.m_aTeamSize[0] > 8) + { + str_format(aBuf, sizeof(aBuf),"%d", DDTeam); + TextRender()->SetCursor(&Cursor, x - 10.0f, y + Spacing + FontSize - (FontSize/1.5f), FontSize/1.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NameLength+3; + } + else + { + str_format(aBuf, sizeof(aBuf),"Team %d", DDTeam); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->SetCursor(&Cursor, ScoreOffset+w/2.0f-tw/2.0f, y + LineHeight - Spacing/3.0f, FontSize/1.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NameLength+3; + } + TextRender()->TextEx(&Cursor, aBuf, -1); + } + } + + OldDDTeam = DDTeam; + + // background so it's easy to find the local player or the followed one in spectator mode + if(pInfo->m_Local || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); + RenderTools()->DrawRoundRect(x, y, w-20.0f, LineHeight, RoundRadius); + Graphics()->QuadsEnd(); + } + + // score + if(m_IsGameTypeRace && g_Config.m_ClDDRaceScoreBoard) + { + if (pInfo->m_Score == -9999) + aBuf[0] = 0; + else + { + int Time = abs(pInfo->m_Score); + str_format(aBuf, sizeof(aBuf), "%02d:%02d", Time/60, Time%60); + } + } + else + str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Score, -999, 999)); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->SetCursor(&Cursor, ScoreOffset+ScoreLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER); + TextRender()->TextEx(&Cursor, aBuf, -1); + + // flag + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS && + m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == pInfo->m_ClientID || + m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == pInfo->m_ClientID)) + { + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + 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; + RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset+TeeLength/2, y+LineHeight/2)); + + // name + TextRender()->SetCursor(&Cursor, NameOffset, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + if(g_Config.m_ClShowIDs) + { + char aId[64] = ""; + if (pInfo->m_ClientID >= 10) + str_format(aId, sizeof(aId),"%d: ", pInfo->m_ClientID); + else + str_format(aId, sizeof(aId)," %d: ", pInfo->m_ClientID); + str_append(aId, m_pClient->m_aClients[pInfo->m_ClientID].m_aName,sizeof(aId)); + Cursor.m_LineWidth = NameLength+3; + TextRender()->TextEx(&Cursor, aId, -1); + } + else + { + Cursor.m_LineWidth = NameLength; + TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1); + } + + // clan + tw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1); + TextRender()->SetCursor(&Cursor, ClanOffset+ClanLength/2-tw/2, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = ClanLength; + TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1); + + // country flag + vec4 Color(1.0f, 1.0f, 1.0f, 0.5f); + m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color, + CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f); + + // ping + str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Latency, 0, 1000)); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->SetCursor(&Cursor, PingOffset+PingLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = PingLength; + TextRender()->TextEx(&Cursor, aBuf, -1); + + y += LineHeight+Spacing; + if (lower32 || upper32) { + if (rendered == 32) break; + } else if (lower24 || upper24) { + if (rendered == 24) break; + } else { + if (rendered == 16) break; + } + } +} + +void CScoreboard::RenderLocalTime(float x) +{ + //draw the box + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); + RenderTools()->DrawRoundRectExt(x-120.0f, 0.0f, 100.0f, 50.0f, 15.0f, CUI::CORNER_B); + Graphics()->QuadsEnd(); + + time_t rawtime; + struct tm *timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + //draw the text + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min); + TextRender()->Text(0, x-100.0f, 10.0f, 20.0f, aBuf, -1); +} + +void CScoreboard::RenderRecordingNotification(float x) +{ + if(!m_pClient->DemoRecorder(RECORDER_MANUAL)->IsRecording() && + !m_pClient->DemoRecorder(RECORDER_AUTO)->IsRecording() && + !m_pClient->DemoRecorder(RECORDER_RACE)->IsRecording()) + { + return; + } + + //draw the text + char aBuf[64] = "\0"; + char aBuf2[64]; + int Seconds; + + if(m_pClient->DemoRecorder(RECORDER_MANUAL)->IsRecording()) + { + Seconds = m_pClient->DemoRecorder(RECORDER_MANUAL)->Length(); + str_format(aBuf2, sizeof(aBuf2), Localize("Manual %3d:%02d "), Seconds/60, Seconds%60); + str_append(aBuf, aBuf2, sizeof(aBuf)); + } + if(m_pClient->DemoRecorder(RECORDER_RACE)->IsRecording()) + { + Seconds = m_pClient->DemoRecorder(RECORDER_RACE)->Length(); + str_format(aBuf2, sizeof(aBuf2), Localize("Race %3d:%02d "), Seconds/60, Seconds%60); + str_append(aBuf, aBuf2, sizeof(aBuf)); + } + if(m_pClient->DemoRecorder(RECORDER_AUTO)->IsRecording()) + { + Seconds = m_pClient->DemoRecorder(RECORDER_AUTO)->Length(); + str_format(aBuf2, sizeof(aBuf2), Localize("Auto %3d:%02d "), Seconds/60, Seconds%60); + str_append(aBuf, aBuf2, sizeof(aBuf)); + } + + float w = TextRender()->TextWidth(0, 20.0f, aBuf, -1); + + //draw the box + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); + RenderTools()->DrawRoundRectExt(x, 0.0f, w+60.0f, 50.0f, 15.0f, CUI::CORNER_B); + Graphics()->QuadsEnd(); + + //draw the red dot + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); + RenderTools()->DrawRoundRect(x+20, 15.0f, 20.0f, 20.0f, 10.0f); + Graphics()->QuadsEnd(); + + TextRender()->Text(0, x+50.0f, 10.0f, 20.0f, aBuf, -1); +} + +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; + + if(m_pClient->m_Snap.m_pGameInfoObj) + { + if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS)) + { + if(m_pClient->m_Snap.m_aTeamSize[0] > 48) + { + RenderScoreboard(Width/2-w, 150.0f, w, -4, 0); + RenderScoreboard(Width/2, 150.0f, w, -5, ""); + } else if(m_pClient->m_Snap.m_aTeamSize[0] > 32) + { + RenderScoreboard(Width/2-w, 150.0f, w, -7, 0); + RenderScoreboard(Width/2, 150.0f, w, -8, ""); + } else if(m_pClient->m_Snap.m_aTeamSize[0] > 16) + { + RenderScoreboard(Width/2-w, 150.0f, w, -6, 0); + RenderScoreboard(Width/2, 150.0f, w, -3, ""); + } else + { + RenderScoreboard(Width/2-w/2, 150.0f, w, 0, 0); + } + } + else + { + 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) + str_format(aText, sizeof(aText), Localize("%s wins!"), pRedClanName); + else + str_copy(aText, Localize("Red team wins!"), sizeof(aText)); + } + else if(m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue > m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed) + { + if(pBlueClanName) + str_format(aText, sizeof(aText), Localize("%s wins!"), pBlueClanName); + 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")); + } + } + + RenderGoals(Width/2-w/2, 150+760+10, w); + RenderSpectators(Width/2-w/2, 150+760+10+50+10, w); + RenderRecordingNotification((Width/7)*4); + RenderLocalTime((Width/7)*3); +} + +bool CScoreboard::Active() +{ + // if statboard is active dont show scoreboard + if(m_pClient->m_pStatboard->IsActive()) + return false; + + 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 + if(!m_pClient->m_Snap.m_pLocalCharacter && g_Config.m_ClScoreboardOnDeath) + return true; + } + + // if the game is over + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + return true; + + return false; +} + +const char *CScoreboard::GetClanName(int Team) +{ + int ClanPlayers = 0; + const char *pClanName = 0; + for(int i = 0; i < MAX_CLIENTS; i++) + { + 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; + ClanPlayers++; + } + else + { + if(str_comp(m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, pClanName) == 0) + ClanPlayers++; + else + return 0; + } + } + + if(ClanPlayers > 1 && pClanName[0]) + return pClanName; + else + return 0; +} diff --git a/src/game/client/components/scoreboard.h b/src/game/client/components/scoreboard.h new file mode 100644 index 0000000..cccc929 --- /dev/null +++ b/src/game/client/components/scoreboard.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_SCOREBOARD_H +#define GAME_CLIENT_COMPONENTS_SCOREBOARD_H +#include <game/client/component.h> + +class CScoreboard : public CComponent +{ + void RenderGoals(float x, float y, float w); + void RenderSpectators(float x, float y, float w); + void RenderScoreboard(float x, float y, float w, int Team, const char *pTitle); + void RenderRecordingNotification(float x); + void RenderLocalTime(float x); + + static void ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData); + + const char *GetClanName(int Team); + + bool m_Active; + +public: + CScoreboard(); + virtual void OnReset(); + virtual void OnConsoleInit(); + virtual void OnRender(); + virtual void OnRelease(); + + bool Active(); + + // DDRace + + virtual void OnMessage(int MsgType, void *pRawMsg); + +private: + + bool m_IsGameTypeRace; + float m_ServerRecord; +}; + +#endif diff --git a/src/game/client/components/skins.cpp b/src/game/client/components/skins.cpp new file mode 100644 index 0000000..1647b97 --- /dev/null +++ b/src/game/client/components/skins.cpp @@ -0,0 +1,196 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <math.h> + +#include <base/system.h> +#include <base/math.h> + +#include <engine/graphics.h> +#include <engine/storage.h> +#include <engine/shared/config.h> + +#include "skins.h" + +const char* vanillaSkins[] = {"bluekitty.png", "bluestripe.png", "brownbear.png", + "cammo.png", "cammostripes.png", "coala.png", "default.png", "limekitty.png", + "pinky.png", "redbopp.png", "redstripe.png", "saddo.png", "toptri.png", + "twinbop.png", "twintri.png", "warpaint.png", "x_ninja.png"}; + +int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) +{ + if(g_Config.m_ClVanillaSkinsOnly) + { + bool found = false; + for(unsigned int i = 0; i < sizeof(vanillaSkins) / sizeof(vanillaSkins[0]); i++) + { + if(str_comp(pName, vanillaSkins[i]) == 0) + { + found = true; + break; + } + } + if(!found) + return 0; + } + + CSkins *pSelf = (CSkins *)pUser; + + int l = str_length(pName); + if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0) + return 0; + + // Don't add duplicate skins (one from user's config directory, other from + // client itself) + for(int i = 0; i < pSelf->Num(); i++) + { + const char* pExName = pSelf->Get(i)->m_aName; + if(str_comp_num(pExName, pName, l-4) == 0 && str_length(pExName) == l-4) + return 0; + } + + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "skins/%s", pName); + CImageInfo Info; + if(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType)) + { + str_format(aBuf, sizeof(aBuf), "failed to load skin from %s", pName); + 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 + if (BodySize > Info.m_Height) + return 0; + unsigned char *d = (unsigned char *)Info.m_pData; + int Pitch = Info.m_Width*4; + + // dig out blood color + { + int aColors[3] = {0}; + for(int y = 0; y < BodySize; y++) + for(int x = 0; x < BodySize; x++) + { + if(d[y*Pitch+x*4+3] > 128) + { + aColors[0] += d[y*Pitch+x*4+0]; + aColors[1] += d[y*Pitch+x*4+1]; + 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; + + // make the texture gray scale + for(int i = 0; i < Info.m_Width*Info.m_Height; i++) + { + int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3; + d[i*Step] = v; + d[i*Step+1] = v; + 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++) + { + 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]) + OrgWeight = i; + } + + // reorder + int InvOrgWeight = 255-OrgWeight; + int InvNewWeight = 255-NewWeight; + for(int y = 0; y < BodySize; y++) + for(int x = 0; x < BodySize; x++) + { + int v = d[y*Pitch+x*4]; + if(v <= OrgWeight) + v = (int)(((v/(float)OrgWeight) * NewWeight)); + else + v = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight); + d[y*Pitch+x*4] = v; + 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 + str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-3)); + if(g_Config.m_Debug) + { + str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); + } + pSelf->m_aSkins.add(Skin); + + return 0; +} + + +void CSkins::OnInit() +{ + // load skins + m_aSkins.clear(); + Storage()->ListDirectory(IStorage::TYPE_ALL, "skins", SkinScan, this); + if(!m_aSkins.size()) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load skins. folder='skins/'"); + CSkin DummySkin; + DummySkin.m_OrgTexture = -1; + DummySkin.m_ColorTexture = -1; + str_copy(DummySkin.m_aName, "dummy", sizeof(DummySkin.m_aName)); + DummySkin.m_BloodColor = vec3(1.0f, 1.0f, 1.0f); + m_aSkins.add(DummySkin); + } +} + +int CSkins::Num() +{ + return m_aSkins.size(); +} + +const CSkins::CSkin *CSkins::Get(int Index) +{ + return &m_aSkins[max(0, Index%m_aSkins.size())]; +} + +int CSkins::Find(const char *pName) +{ + for(int i = 0; i < m_aSkins.size(); i++) + { + if(str_comp(m_aSkins[i].m_aName, pName) == 0) + return i; + } + return -1; +} + +vec3 CSkins::GetColorV3(int v) +{ + return HslToRgb(vec3(((v>>16)&0xff)/255.0f, ((v>>8)&0xff)/255.0f, 0.5f+(v&0xff)/255.0f*0.5f)); +} + +vec4 CSkins::GetColorV4(int v) +{ + vec3 r = GetColorV3(v); + return vec4(r.r, r.g, r.b, 1.0f); +} diff --git a/src/game/client/components/skins.h b/src/game/client/components/skins.h new file mode 100644 index 0000000..519f452 --- /dev/null +++ b/src/game/client/components/skins.h @@ -0,0 +1,36 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_SKINS_H +#define GAME_CLIENT_COMPONENTS_SKINS_H +#include <base/vmath.h> +#include <base/tl/sorted_array.h> +#include <game/client/component.h> + +class CSkins : public CComponent +{ +public: + // do this better and nicer + struct CSkin + { + int m_OrgTexture; + int m_ColorTexture; + char m_aName[24]; + vec3 m_BloodColor; + + 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; + + static int SkinScan(const char *pName, int IsDir, int DirType, void *pUser); +}; +#endif diff --git a/src/game/client/components/sounds.cpp b/src/game/client/components/sounds.cpp new file mode 100644 index 0000000..7fdb5e2 --- /dev/null +++ b/src/game/client/components/sounds.cpp @@ -0,0 +1,239 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/array.h> + +#include <engine/engine.h> +#include <engine/sound.h> +#include <engine/shared/config.h> +#include <game/generated/client_data.h> +#include <game/client/gameclient.h> +#include <game/client/components/camera.h> +#include <game/client/components/menus.h> +#include "sounds.h" + + +struct CUserData +{ + CGameClient *m_pGameClient; + bool m_Render; +} g_UserData; + +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++) + { + int Id = pData->m_pGameClient->Sound()->LoadWV(g_pData->m_aSounds[s].m_aSounds[i].m_pFilename); + g_pData->m_aSounds[s].m_aSounds[i].m_Id = Id; + } + + if(pData->m_Render) + pData->m_pGameClient->m_pMenus->RenderLoading(); + } + + return 0; +} + +int CSounds::GetSampleId(int SetId) +{ + if(!g_Config.m_SndEnable || !Sound()->IsSoundEnabled() || m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds) + return -1; + + CDataSoundset *pSet = &g_pData->m_aSounds[SetId]; + if(!pSet->m_NumSounds) + return -1; + + if(pSet->m_NumSounds == 1) + return pSet->m_aSounds[0].m_Id; + + // return random one + int Id; + do + { + Id = rand() % pSet->m_NumSounds; + } + while(Id == pSet->m_Last); + pSet->m_Last = Id; + return pSet->m_aSounds[Id].m_Id; +} + +void CSounds::OnInit() +{ + // setup sound channels + m_MapSoundVolume = g_Config.m_SndMapSoundVolume/100.0f; + + Sound()->SetChannel(CSounds::CHN_GUI, 1.0f, 0.0f); + Sound()->SetChannel(CSounds::CHN_MUSIC, 1.0f, 0.0f); + Sound()->SetChannel(CSounds::CHN_WORLD, 0.9f, 1.0f); + Sound()->SetChannel(CSounds::CHN_GLOBAL, 1.0f, 0.0f); + Sound()->SetChannel(CSounds::CHN_MAPSOUND, m_MapSoundVolume, 1.0f); + + Sound()->SetListenerPos(0.0f, 0.0f); + + ClearQueue(); + + // load sounds + if(g_Config.m_ClThreadsoundloading) + { + g_UserData.m_pGameClient = m_pClient; + g_UserData.m_Render = false; + m_pClient->Engine()->AddJob(&m_SoundJob, LoadSoundsThread, &g_UserData); + m_WaitForSoundJob = true; + } + else + { + g_UserData.m_pGameClient = m_pClient; + g_UserData.m_Render = true; + LoadSoundsThread(&g_UserData); + m_WaitForSoundJob = false; + } +} + +void CSounds::OnReset() +{ + if(Client()->State() >= IClient::STATE_ONLINE) + { + Sound()->StopAll(); + ClearQueue(); + } +} + +void CSounds::OnStateChange(int NewState, int OldState) +{ + if(NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK) + OnReset(); +} + +void CSounds::OnRender() +{ + // check for sound initialisation + if(m_WaitForSoundJob) + { + if(m_SoundJob.Status() == CJob::STATE_DONE) + m_WaitForSoundJob = false; + else + return; + } + + // set listner pos + Sound()->SetListenerPos(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y); + + // update volume + float NewMapSoundVol = g_Config.m_SndMapSoundVolume/100.0f; + if(NewMapSoundVol != m_MapSoundVolume) + { + m_MapSoundVolume = NewMapSoundVol; + Sound()->SetChannel(CSounds::CHN_MAPSOUND, m_MapSoundVolume, 1.0f); + } + + // play sound from queue + if(m_QueuePos > 0) + { + int64 Now = time_get(); + if(m_QueueWaitTime <= Now) + { + Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f); + m_QueueWaitTime = Now+time_freq()*3/10; // wait 300ms before playing the next one + if(--m_QueuePos > 0) + mem_move(m_aQueue, m_aQueue+1, m_QueuePos*sizeof(QueueEntry)); + } + } +} + +void CSounds::ClearQueue() +{ + mem_zero(m_aQueue, sizeof(m_aQueue)); + m_QueuePos = 0; + m_QueueWaitTime = time_get(); +} + +void CSounds::Enqueue(int Channel, int SetId) +{ + // add sound to the queue + if(m_QueuePos < QUEUE_SIZE) + { + if(Channel == CHN_MUSIC || !g_Config.m_ClEditor) + { + m_aQueue[m_QueuePos].m_Channel = Channel; + m_aQueue[m_QueuePos++].m_SetId = SetId; + } + } +} + +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); +} + +void CSounds::Play(int Chn, int SetId, float Vol) +{ + if(Chn == CHN_MUSIC && !g_Config.m_SndMusic) + return; + + int SampleId = GetSampleId(SetId); + if(SampleId == -1) + return; + + int Flags = 0; + if(Chn == CHN_MUSIC) + Flags = ISound::FLAG_LOOP; + + Sound()->Play(Chn, SampleId, Flags); +} + +void CSounds::PlayAt(int Chn, int SetId, float Vol, vec2 Pos) +{ + if(Chn == CHN_MUSIC && !g_Config.m_SndMusic) + return; + + int SampleId = GetSampleId(SetId); + if(SampleId == -1) + return; + + int Flags = 0; + if(Chn == CHN_MUSIC) + Flags = ISound::FLAG_LOOP; + + Sound()->PlayAt(Chn, SampleId, Flags, Pos.x, Pos.y); +} + +void CSounds::Stop(int SetId) +{ + if(m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds) + return; + + CDataSoundset *pSet = &g_pData->m_aSounds[SetId]; + + for(int i = 0; i < pSet->m_NumSounds; i++) + Sound()->Stop(pSet->m_aSounds[i].m_Id); +} + +ISound::CVoiceHandle CSounds::PlaySample(int Chn, int SampleId, float Vol, int Flags) +{ + if((Chn == CHN_MUSIC && !g_Config.m_SndMusic) || SampleId == -1) + return ISound::CVoiceHandle(); + + if(Chn == CHN_MUSIC) + Flags |= ISound::FLAG_LOOP; + + return Sound()->Play(Chn, SampleId, Flags); +} + +ISound::CVoiceHandle CSounds::PlaySampleAt(int Chn, int SampleId, float Vol, vec2 Pos, int Flags) +{ + if((Chn == CHN_MUSIC && !g_Config.m_SndMusic) || SampleId == -1) + return ISound::CVoiceHandle(); + + if(Chn == CHN_MUSIC) + Flags |= ISound::FLAG_LOOP; + + return Sound()->PlayAt(Chn, SampleId, Flags, Pos.x, Pos.y); +} diff --git a/src/game/client/components/sounds.h b/src/game/client/components/sounds.h new file mode 100644 index 0000000..b8f7a86 --- /dev/null +++ b/src/game/client/components/sounds.h @@ -0,0 +1,56 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_SOUNDS_H +#define GAME_CLIENT_COMPONENTS_SOUNDS_H +#include <engine/sound.h> +#include <game/client/component.h> + +class CSounds : public CComponent +{ + enum + { + QUEUE_SIZE = 32, + }; + struct QueueEntry + { + int m_Channel; + int m_SetId; + } m_aQueue[QUEUE_SIZE]; + int m_QueuePos; + int64 m_QueueWaitTime; + class CJob m_SoundJob; + bool m_WaitForSoundJob; + + int GetSampleId(int SetId); + + float m_MapSoundVolume; + +public: + // sound channels + enum + { + CHN_GUI=0, + CHN_MUSIC, + CHN_WORLD, + CHN_GLOBAL, + CHN_MAPSOUND, + }; + + virtual void OnInit(); + virtual void OnReset(); + virtual void OnStateChange(int NewState, int OldState); + virtual void OnRender(); + + void ClearQueue(); + void Enqueue(int Channel, int SetId); + void Play(int Channel, int SetId, float Vol); + void PlayAt(int Channel, int SetId, float Vol, vec2 Pos); + void PlayAndRecord(int Channel, int SetId, float Vol, vec2 Pos); + void Stop(int SetId); + + ISound::CVoiceHandle PlaySample(int Channel, int SampleId, float Vol, int Flags = 0); + ISound::CVoiceHandle PlaySampleAt(int Channel, int SampleId, float Vol, vec2 Pos, int Flags = 0); +}; + + +#endif diff --git a/src/game/client/components/spectator.cpp b/src/game/client/components/spectator.cpp new file mode 100644 index 0000000..b573cb7 --- /dev/null +++ b/src/game/client/components/spectator.cpp @@ -0,0 +1,445 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/demo.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/shared/config.h> + +#include <game/generated/client_data.h> +#include <game/generated/protocol.h> + +#include <game/client/animstate.h> +#include <game/client/render.h> + +#include "spectator.h" + + +void CSpectator::ConKeySpectator(IConsole::IResult *pResult, void *pUserData) +{ + CSpectator *pSelf = (CSpectator *)pUserData; + + if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active || pSelf->Client()->State() == IClient::STATE_DEMOPLAYBACK) + pSelf->m_Active = pResult->GetInteger(0) != 0; + else + pSelf->m_Active = false; +} + +void CSpectator::ConSpectate(IConsole::IResult *pResult, void *pUserData) +{ + ((CSpectator *)pUserData)->Spectate(pResult->GetInteger(0)); +} + +void CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData) +{ + CSpectator *pSelf = (CSpectator *)pUserData; + int NewSpectatorID; + bool GotNewSpectatorID = false; + + int CurPos = -1; + for (int i = 0; i < MAX_CLIENTS; i++) + if (pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] && pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID == pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID) + CurPos = i; + + if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + } + else + { + for(int i = CurPos + 1; i < MAX_CLIENTS; i++) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + + if(!GotNewSpectatorID) + { + for(int i = 0; i < CurPos; i++) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + } + } + if(GotNewSpectatorID) + pSelf->Spectate(NewSpectatorID); +} + +void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData) +{ + CSpectator *pSelf = (CSpectator *)pUserData; + int NewSpectatorID; + bool GotNewSpectatorID = false; + + int CurPos = -1; + for (int i = 0; i < MAX_CLIENTS; i++) + if (pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] && pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID == pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID) + CurPos = i; + + if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + { + for(int i = MAX_CLIENTS -1; i > -1; i--) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + } + else + { + for(int i = CurPos - 1; i > -1; i--) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + + if(!GotNewSpectatorID) + { + for(int i = MAX_CLIENTS - 1; i > CurPos; i--) + { + if(!pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i] || pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + NewSpectatorID = pSelf->m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + GotNewSpectatorID = true; + break; + } + } + } + if(GotNewSpectatorID) + pSelf->Spectate(NewSpectatorID); +} + +CSpectator::CSpectator() +{ + OnReset(); + m_OldMouseX = m_OldMouseY = 0.0f; +} + +void CSpectator::OnConsoleInit() +{ + Console()->Register("+spectate", "", CFGFLAG_CLIENT, ConKeySpectator, this, "Open spectator mode selector"); + Console()->Register("spectate", "i[spectator-id]", CFGFLAG_CLIENT, ConSpectate, this, "Switch spectator mode"); + Console()->Register("spectate_next", "", CFGFLAG_CLIENT, ConSpectateNext, this, "Spectate the next player"); + Console()->Register("spectate_previous", "", CFGFLAG_CLIENT, ConSpectatePrevious, this, "Spectate the previous player"); +} + +bool CSpectator::OnMouseMove(float x, float y) +{ + if(!m_Active) + return false; + +#if defined(__ANDROID__) // No relative mouse on Android + m_SelectorMouse = vec2(x,y); + if( m_OldMouseX != x || m_OldMouseY != y ) + { + m_OldMouseX = x; + m_OldMouseY = y; + m_SelectorMouse = vec2((x - g_Config.m_GfxScreenWidth/2), (y - g_Config.m_GfxScreenHeight/2)); + } +#else + UI()->ConvertMouseMove(&x, &y); + m_SelectorMouse += vec2(x,y); +#endif + return true; +} + +void CSpectator::OnRelease() +{ + OnReset(); +} + +void CSpectator::OnRender() +{ + if(!m_Active) + { + if(m_WasActive) + { + if(m_SelectedSpectatorID != NO_SELECTION) + Spectate(m_SelectedSpectatorID); + m_WasActive = false; + } + return; + } + + if(!m_pClient->m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + m_Active = false; + m_WasActive = false; + return; + } + + m_WasActive = true; + m_SelectedSpectatorID = NO_SELECTION; + + // draw background + float Width = 400*3.0f*Graphics()->ScreenAspect(); + float Height = 400*3.0f; + float ObjWidth = 300.0f; + float FontSize = 20.0f; + float BigFontSize = 20.0f; + float StartY = -190.0f; + float LineHeight = 60.0f; + float TeeSizeMod = 1.0f; + float RoundRadius = 30.0f; + bool Selected = false; + int TotalPlayers = 0; + int PerLine = 8; + float BoxMove = -10.0f; + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(!m_pClient->m_Snap.m_paInfoByDDTeam[i] || m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + ++TotalPlayers; + } + + if (TotalPlayers > 32) + { + FontSize = 18.0f; + LineHeight = 30.0f; + TeeSizeMod = 0.7f; + PerLine = 16; + RoundRadius = 10.0f; + BoxMove = 3.0f; + } + if (TotalPlayers > 16) + { + ObjWidth = 600.0f; + } + + Graphics()->MapScreen(0, 0, Width, Height); + + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.3f); + RenderTools()->DrawRoundRect(Width/2.0f-ObjWidth, Height/2.0f-300.0f, ObjWidth*2, 600.0f, 20.0f); + Graphics()->QuadsEnd(); + + // clamp mouse position to selector area + m_SelectorMouse.x = clamp(m_SelectorMouse.x, -(ObjWidth - 20.0f), ObjWidth - 20.0f); + m_SelectorMouse.y = clamp(m_SelectorMouse.y, -280.0f, 280.0f); + + // draw selections + if((Client()->State() == IClient::STATE_DEMOPLAYBACK && m_pClient->m_DemoSpecID == SPEC_FREEVIEW) || + m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); + RenderTools()->DrawRoundRect(Width/2.0f-(ObjWidth - 20.0f), Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); + Graphics()->QuadsEnd(); + } + + if(Client()->State() == IClient::STATE_DEMOPLAYBACK && m_pClient->m_DemoSpecID == SPEC_FOLLOW) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); + RenderTools()->DrawRoundRect(Width/2.0f-(ObjWidth - 310.0f), Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); + Graphics()->QuadsEnd(); + } + + if(m_SelectorMouse.x >= -(ObjWidth-20.0f) && m_SelectorMouse.x <= -(ObjWidth-290+10.0f) && + m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) + { + m_SelectedSpectatorID = SPEC_FREEVIEW; + Selected = true; + } + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); + TextRender()->Text(0, Width/2.0f-(ObjWidth-60.0f), Height/2.0f-265.0f, BigFontSize, Localize("Free-View"), -1); + + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + Selected = false; + if(m_SelectorMouse.x > -(ObjWidth-290.0f) && m_SelectorMouse.x <= -(ObjWidth-590.0f) && + m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) + { + m_SelectedSpectatorID = SPEC_FOLLOW; + Selected = true; + } + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); + TextRender()->Text(0, Width/2.0f-(ObjWidth-350.0f), Height/2.0f-265.0f, BigFontSize, Localize("Follow"), -1); + } + + float x = -(ObjWidth - 30.0f), y = StartY; + + int OldDDTeam = -1; + + for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i) + { + if(!m_pClient->m_Snap.m_paInfoByDDTeam[i] || m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team == TEAM_SPECTATORS) + continue; + + ++Count; + + if(Count == PerLine + 1 || (Count > PerLine + 1 && (Count-1)%PerLine == 0)) + { + x += 290.0f; + y = StartY; + } + + const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByDDTeam[i]; + int DDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo->m_ClientID); + int NextDDTeam = 0; + + for(int j = i + 1; j < MAX_CLIENTS; j++) + { + const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeam[j]; + + if(!pInfo2 || pInfo2->m_Team == TEAM_SPECTATORS) + continue; + + NextDDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo2->m_ClientID); + break; + } + + if (OldDDTeam == -1) + { + for (int j = i - 1; j >= 0; j--) + { + const CNetObj_PlayerInfo *pInfo2 = m_pClient->m_Snap.m_paInfoByDDTeam[j]; + + if(!pInfo2 || pInfo2->m_Team == TEAM_SPECTATORS) + continue; + + OldDDTeam = ((CGameClient *) m_pClient)->m_Teams.Team(pInfo2->m_ClientID); + break; + } + } + + if (DDTeam != TEAM_FLOCK) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + vec3 rgb = HslToRgb(vec3(DDTeam / 64.0f, 1.0f, 0.5f)); + Graphics()->SetColor(rgb.r, rgb.g, rgb.b, 0.5f); + + int Corners = 0; + + if (OldDDTeam != DDTeam) + Corners |= CUI::CORNER_TL | CUI::CORNER_TR; + if (NextDDTeam != DDTeam) + Corners |= CUI::CORNER_BL | CUI::CORNER_BR; + + RenderTools()->DrawRoundRectExt(Width/2.0f+x-10.0f, Height/2.0f+y+BoxMove, 270.0f, LineHeight, RoundRadius, Corners); + + Graphics()->QuadsEnd(); + } + + OldDDTeam = DDTeam; + + if((Client()->State() == IClient::STATE_DEMOPLAYBACK && m_pClient->m_DemoSpecID == m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID) + || (Client()->State() != IClient::STATE_DEMOPLAYBACK && m_pClient ->m_Snap.m_SpecInfo.m_SpectatorID == m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID)) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); + RenderTools()->DrawRoundRect(Width/2.0f+x-10.0f, Height/2.0f+y+BoxMove, 270.0f, LineHeight, RoundRadius); + Graphics()->QuadsEnd(); + } + + Selected = false; + if(m_SelectorMouse.x >= x-10.0f && m_SelectorMouse.x < x+260.0f && + m_SelectorMouse.y >= y-(LineHeight/6.0f) && m_SelectorMouse.y < y+(LineHeight*5.0f/6.0f)) + { + m_SelectedSpectatorID = m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID; + Selected = true; + } + float TeeAlpha; + if(Client()->State() == IClient::STATE_DEMOPLAYBACK && + !m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID].m_Active) + { + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.25f); + TeeAlpha = 0.5f; + } + else + { + TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); + TeeAlpha = 1.0f; + } + TextRender()->Text(0, Width/2.0f+x+50.0f, Height/2.0f+y+5.0f, FontSize, m_pClient->m_aClients[m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID].m_aName, 220.0f); + + // flag + if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS && + m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID || + m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID)) + { + Graphics()->BlendNormal(); + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + + RenderTools()->SelectSprite(m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); + + float Size = LineHeight; + IGraphics::CQuadItem QuadItem(Width/2.0f+x-LineHeight/5.0f, Height/2.0f+y-LineHeight/3.0f, Size/2.0f, Size); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + + CTeeRenderInfo TeeInfo = m_pClient->m_aClients[m_pClient->m_Snap.m_paInfoByDDTeam[i]->m_ClientID].m_RenderInfo; + TeeInfo.m_ColorBody.a = TeeAlpha; + TeeInfo.m_ColorFeet.a = TeeAlpha; + TeeInfo.m_Size *= TeeSizeMod; + 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), true); + + y += LineHeight; + } + TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + + // draw cursor + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Width/2.0f, m_SelectorMouse.y+Height/2.0f, 48.0f, 48.0f); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); +} + +void CSpectator::OnReset() +{ + m_WasActive = false; + m_Active = false; + m_SelectedSpectatorID = NO_SELECTION; +} + +void CSpectator::Spectate(int SpectatorID) +{ + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + m_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FOLLOW, MAX_CLIENTS-1); + return; + } + + if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SpectatorID) + return; + + CNetMsg_Cl_SetSpectatorMode Msg; + Msg.m_SpectatorID = SpectatorID; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); +} diff --git a/src/game/client/components/spectator.h b/src/game/client/components/spectator.h new file mode 100644 index 0000000..e041008 --- /dev/null +++ b/src/game/client/components/spectator.h @@ -0,0 +1,42 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_SPECTATOR_H +#define GAME_CLIENT_COMPONENTS_SPECTATOR_H +#include <base/vmath.h> + +#include <game/client/component.h> + +class CSpectator : public CComponent +{ + enum + { + NO_SELECTION=-3, + }; + + bool m_Active; + bool m_WasActive; + + int m_SelectedSpectatorID; + vec2 m_SelectorMouse; + + float m_OldMouseX; + float m_OldMouseY; + + static void ConKeySpectator(IConsole::IResult *pResult, void *pUserData); + 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(); + virtual void OnRelease(); + virtual void OnReset(); + + void Spectate(int SpectatorID); +}; + +#endif diff --git a/src/game/client/components/statboard.cpp b/src/game/client/components/statboard.cpp new file mode 100644 index 0000000..78d7adc --- /dev/null +++ b/src/game/client/components/statboard.cpp @@ -0,0 +1,404 @@ +#include <engine/shared/config.h> +#include <engine/textrender.h> +#include <engine/graphics.h> +#include <engine/serverbrowser.h> +#include <game/generated/client_data.h> +#include <game/client/gameclient.h> +#include <game/client/animstate.h> +#include <game/client/components/motd.h> +#include <game/client/components/statboard.h> + +CStatboard::CStatboard() +{ + m_Active = false; + m_ScreenshotTaken = false; + m_ScreenshotTime = -1; +} + +void CStatboard::OnReset() +{ + for(int i=0; i<MAX_CLIENTS; i++) + m_pClient->m_aStats[i].Reset(); + m_Active = false; + m_ScreenshotTaken = false; + m_ScreenshotTime = -1; +} + +void CStatboard::OnRelease() +{ + m_Active = false; +} + +void CStatboard::ConKeyStats(IConsole::IResult *pResult, void *pUserData) +{ + ((CStatboard *)pUserData)->m_Active = pResult->GetInteger(0) != 0; +} + +void CStatboard::OnConsoleInit() +{ + Console()->Register("+statboard", "", CFGFLAG_CLIENT, ConKeyStats, this, "Show stats"); +} + +bool CStatboard::IsActive() +{ + return m_Active; +} + +void CStatboard::OnMessage(int MsgType, void *pRawMsg) +{ + if(MsgType == NETMSGTYPE_SV_KILLMSG) + { + CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; + CGameClient::CClientStats *pStats = m_pClient->m_aStats; + + pStats[pMsg->m_Victim].m_Deaths++; + pStats[pMsg->m_Victim].m_CurrentSpree = 0; + if(pMsg->m_Weapon >= 0) + pStats[pMsg->m_Victim].m_aDeathsFrom[pMsg->m_Weapon]++; + if(pMsg->m_Victim != pMsg->m_Killer) + { + pStats[pMsg->m_Killer].m_Frags++; + pStats[pMsg->m_Killer].m_CurrentSpree++; + + if(pStats[pMsg->m_Killer].m_CurrentSpree > pStats[pMsg->m_Killer].m_BestSpree) + pStats[pMsg->m_Killer].m_BestSpree = pStats[pMsg->m_Killer].m_CurrentSpree; + if(pMsg->m_Weapon >= 0) + pStats[pMsg->m_Killer].m_aFragsWith[pMsg->m_Weapon]++; + } + else + pStats[pMsg->m_Victim].m_Suicides++; + } + else if(MsgType == NETMSGTYPE_SV_CHAT) + { + CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; + if(pMsg->m_ClientID < 0) + { + const char *p; + const char *pLookFor = "flag was captured by '"; + if(str_find(pMsg->m_pMessage, pLookFor) != 0) + { + // server info + CServerInfo CurrentServerInfo; + Client()->GetServerInfo(&CurrentServerInfo); + + p = str_find(pMsg->m_pMessage, pLookFor); + char aName[64]; + p += str_length(pLookFor); + str_copy(aName, p, sizeof(aName)); + // remove capture time + if(str_comp(aName+str_length(aName)-9, " seconds)") == 0) + { + char *c = aName+str_length(aName)-10; + while(c > aName) + { + c--; + if(*c == '(') + { + *(c-1) = 0; + break; + } + } + } + // remove the ' at the end + aName[str_length(aName)-1] = 0; + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!m_pClient->m_aStats[i].m_Active) + continue; + + if(str_comp(m_pClient->m_aClients[i].m_aName, aName) == 0) + { + m_pClient->m_aStats[i].m_FlagCaptures++; + break; + } + } + } + } + } +} + +void CStatboard::OnRender() +{ + if(g_Config.m_ClAutoStatboardScreenshot && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(m_ScreenshotTime < 0 && m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) + m_ScreenshotTime = time_get() + time_freq() * 3; + if(m_ScreenshotTime > -1 && m_ScreenshotTime < time_get()) + m_Active = true; + if(!m_ScreenshotTaken && m_ScreenshotTime > -1 && m_ScreenshotTime + time_freq() / 5 < time_get()) + { + AutoStatScreenshot(); + m_ScreenshotTaken = true; + } + } + + if(IsActive()) + RenderGlobalStats(); +} + +void CStatboard::RenderGlobalStats() +{ + const float StatboardWidth = 400*3.0f*Graphics()->ScreenAspect(); + const float StatboardHeight = 400*3.0f; + float StatboardContentWidth = 260.0f; + float StatboardContentHeight = 750.0f; + + const CNetObj_PlayerInfo *apPlayers[MAX_CLIENTS] = {0}; + int NumPlayers = 0; + + // sort red or dm players by score + for(int i = 0; i < MAX_CLIENTS; i++) + { + const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i]; + if(!pInfo || !m_pClient->m_aStats[pInfo->m_ClientID].m_Active || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != TEAM_RED) + continue; + apPlayers[NumPlayers] = pInfo; + NumPlayers++; + } + + // sort blue players by score after + if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i]; + if(!pInfo || !m_pClient->m_aStats[pInfo->m_ClientID].m_Active || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != TEAM_BLUE) + continue; + apPlayers[NumPlayers] = pInfo; + NumPlayers++; + } + } + + // Dirty hack. Do not show scoreboard if there are more than 16 players + // remove as soon as support of more than 16 players is required + if(NumPlayers > 16) + return; + + //clear motd if it is active + if(m_pClient->m_pMotd->IsActive()) + m_pClient->m_pMotd->Clear(); + + bool gameWithFlags = m_pClient->m_Snap.m_pGameInfoObj && + m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS; + + StatboardContentWidth += 7 * 85 + 95; // Suicides 95; other labels 85 + + if(gameWithFlags) + StatboardContentWidth += 150; // Grabs & Flags + + bool aDisplayWeapon[NUM_WEAPONS] = {false}; + for(int i = 0; i < NumPlayers; i++) + { + const CGameClient::CClientStats pStats = m_pClient->m_aStats[apPlayers[i]->m_ClientID]; + for(int j=0; j<NUM_WEAPONS; j++) + aDisplayWeapon[j] = aDisplayWeapon[j] || pStats.m_aFragsWith[j] || pStats.m_aDeathsFrom[j]; + } + for(int i = 0; i < NUM_WEAPONS; i++) + if(aDisplayWeapon[i]) + StatboardContentWidth += 80; + + float x = StatboardWidth/2-StatboardContentWidth/2; + float y = 200.0f; + + Graphics()->MapScreen(0, 0, StatboardWidth, StatboardHeight); + + Graphics()->BlendNormal(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(0,0,0,0.5f); + RenderTools()->DrawRoundRect(x-10.f, y-10.f, StatboardContentWidth, StatboardContentHeight, 17.0f); + Graphics()->QuadsEnd(); + + float tw; + int px = 325; + + TextRender()->Text(0, x+10, y-5, 22.0f, Localize("Name"), -1); + const char *apHeaders[] = { + Localize("Frags"), Localize("Deaths"), Localize("Suicides"), + Localize("Ratio"), Localize("Net"), Localize("FPM"), + Localize("Spree"), Localize("Best"), Localize("Grabs") + }; + for(int i = 0; i < 9; i++) + { + if(i == 2) + px += 10.0f; // Suicides + if(i == 8 && !gameWithFlags) // Don't draw "Grabs" in game with no flag + continue; + tw = TextRender()->TextWidth(0, 22.0f, apHeaders[i], -1); + TextRender()->Text(0, x+px-tw, y-5, 22.0f, apHeaders[i], -1); + px += 85; + } + + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + px -= 40; + for(int i = 0; i < NUM_WEAPONS; i++) + { + if(!aDisplayWeapon[i]) + continue; + RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[i].m_pSpriteBody); + if(i == 0) + RenderTools()->DrawSprite(x+px, y+10, g_pData->m_Weapons.m_aId[i].m_VisualSize*0.8); + else + RenderTools()->DrawSprite(x+px, y+10, g_pData->m_Weapons.m_aId[i].m_VisualSize); + px += 80; + } + Graphics()->QuadsEnd(); + + if(gameWithFlags) + { + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); + Graphics()->QuadsBegin(); + Graphics()->QuadsSetRotation(0.78f); + RenderTools()->SelectSprite(SPRITE_FLAG_RED); + RenderTools()->DrawSprite(x+px, y+15, 48); + Graphics()->QuadsEnd(); + } + else + { + px += 40; + } + + y += 29.0f; + + float FontSize = 24.0f; + float LineHeight = 50.0f; + float TeeSizemod = 0.8f; + float TeeOffset = 0.0f; + + if(NumPlayers > 14) + { + FontSize = 24.0f; + LineHeight = 40.0f; + TeeSizemod = 0.7f; + TeeOffset = -5.0f; + } + + for(int j = 0; j < NumPlayers; j++) + { + const CNetObj_PlayerInfo *pInfo = apPlayers[j]; + const CGameClient::CClientStats Stats = m_pClient->m_aStats[pInfo->m_ClientID]; + + if(m_pClient->m_Snap.m_LocalClientID == pInfo->m_ClientID + || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)) + { + // background so it's easy to find the local player + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + Graphics()->SetColor(1,1,1,0.25f); + RenderTools()->DrawRoundRect(x, y, StatboardContentWidth-20, LineHeight*0.95f, 17.0f); + Graphics()->QuadsEnd(); + } + + CTeeRenderInfo Teeinfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo; + Teeinfo.m_Size *= TeeSizemod; + RenderTools()->RenderTee(CAnimState::GetIdle(), &Teeinfo, EMOTE_NORMAL, vec2(1,0), vec2(x+28, y+28+TeeOffset)); + + char aBuf[128]; + CTextCursor Cursor; + tw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1); + TextRender()->SetCursor(&Cursor, x+64, y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = 220; + TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1); + + px = 325; + + // FRAGS + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_Frags); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // DEATHS + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_Deaths); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // SUICIDES + { + px += 10; + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_Suicides); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // RATIO + { + if(Stats.m_Deaths == 0) + str_format(aBuf, sizeof(aBuf), "--"); + else + str_format(aBuf, sizeof(aBuf), "%.2f", (float)(Stats.m_Frags)/Stats.m_Deaths); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // NET + { + str_format(aBuf, sizeof(aBuf), "%+d", Stats.m_Frags-Stats.m_Deaths); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // FPM + { + float Fpm = (float)(Stats.m_Frags*60)/((float)(Client()->GameTick()-Stats.m_JoinDate)/Client()->GameTickSpeed()); + str_format(aBuf, sizeof(aBuf), "%.1f", Fpm); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // SPREE + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_CurrentSpree); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // BEST SPREE + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_BestSpree); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // GRABS + if(gameWithFlags) + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_FlagGrabs); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + // WEAPONS + px -= 40; + for(int i = 0; i < NUM_WEAPONS; i++) + { + if(!aDisplayWeapon[i]) + continue; + + str_format(aBuf, sizeof(aBuf), "%d/%d", Stats.m_aFragsWith[i], Stats.m_aDeathsFrom[i]); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x+px-tw/2, y, FontSize, aBuf, -1); + px += 80; + } + // FLAGS + if(gameWithFlags) + { + str_format(aBuf, sizeof(aBuf), "%d", Stats.m_FlagCaptures); + tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); + TextRender()->Text(0, x-tw+px, y, FontSize, aBuf, -1); + px += 85; + } + y += LineHeight; + } +} + +void CStatboard::AutoStatScreenshot() +{ + if(Client()->State() != IClient::STATE_DEMOPLAYBACK) + Client()->AutoStatScreenshot_Start(); +} diff --git a/src/game/client/components/statboard.h b/src/game/client/components/statboard.h new file mode 100644 index 0000000..f2426a1 --- /dev/null +++ b/src/game/client/components/statboard.h @@ -0,0 +1,21 @@ +#include <game/client/component.h> + +class CStatboard: public CComponent +{ + private: + bool m_Active; + bool m_ScreenshotTaken; + int64 m_ScreenshotTime; + static void ConKeyStats(IConsole::IResult *pResult, void *pUserData); + void RenderGlobalStats(); + void AutoStatScreenshot(); + + public: + CStatboard(); + virtual void OnReset(); + virtual void OnConsoleInit(); + virtual void OnRender(); + virtual void OnRelease(); + virtual void OnMessage(int MsgType, void *pRawMsg); + bool IsActive(); +}; diff --git a/src/game/client/components/voting.cpp b/src/game/client/components/voting.cpp new file mode 100644 index 0000000..92a19bc --- /dev/null +++ b/src/game/client/components/voting.cpp @@ -0,0 +1,337 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/shared/config.h> + +#include <game/generated/protocol.h> +#include <base/vmath.h> +#include <game/client/render.h> +#include "voting.h" + +void CVoting::ConCallvote(IConsole::IResult *pResult, void *pUserData) +{ + CVoting *pSelf = (CVoting*)pUserData; + pSelf->Callvote(pResult->GetString(0), pResult->GetString(1), pResult->NumArguments() > 2 ? pResult->GetString(2) : ""); +} + +void CVoting::ConVote(IConsole::IResult *pResult, void *pUserData) +{ + CVoting *pSelf = (CVoting *)pUserData; + if(str_comp_nocase(pResult->GetString(0), "yes") == 0) + pSelf->Vote(1); + else if(str_comp_nocase(pResult->GetString(0), "no") == 0) + pSelf->Vote(-1); +} + +void CVoting::Callvote(const char *pType, const char *pValue, const char *pReason) +{ + CNetMsg_Cl_CallVote Msg = {0}; + Msg.m_Type = pType; + Msg.m_Value = pValue; + Msg.m_Reason = pReason; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); +} + +void CVoting::CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote) +{ + if(ForceVote) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "set_team %d -1", ClientID); + Client()->Rcon(aBuf); + } + else + { + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "%d", ClientID); + Callvote("spectate", aBuf, pReason); + } +} + +void CVoting::CallvoteKick(int ClientID, const char *pReason, bool ForceVote) +{ + if(ForceVote) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "force_vote kick %d %s", ClientID, pReason); + Client()->Rcon(aBuf); + } + else + { + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "%d", ClientID); + Callvote("kick", aBuf, pReason); + } +} + +void CVoting::CallvoteOption(int OptionID, const char *pReason, bool ForceVote) +{ + CVoteOptionClient *pOption = m_pFirst; + while(pOption && OptionID >= 0) + { + if(OptionID == 0) + { + if(ForceVote) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "force_vote option \"%s\" %s", pOption->m_aDescription, pReason); + Client()->Rcon(aBuf); + } + else + Callvote("option", pOption->m_aDescription, pReason); + break; + } + + OptionID--; + pOption = pOption->m_pNext; + } +} + +void CVoting::RemovevoteOption(int OptionID) +{ + CVoteOptionClient *pOption = m_pFirst; + while(pOption && OptionID >= 0) + { + if(OptionID == 0) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "remove_vote \"%s\"", pOption->m_aDescription); + Client()->Rcon(aBuf); + break; + } + + OptionID--; + pOption = pOption->m_pNext; + } +} + +void CVoting::AddvoteOption(const char *pDescription, const char *pCommand) +{ + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "add_vote \"%s\" %s", pDescription, pCommand); + Client()->Rcon(aBuf); +} + +void CVoting::Vote(int v) +{ + m_Voted = v; + CNetMsg_Cl_Vote Msg = {v}; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); +} + +CVoting::CVoting() +{ + ClearOptions(); + + m_Closetime = 0; + m_aDescription[0] = 0; + m_aReason[0] = 0; + m_Yes = m_No = m_Pass = m_Total = 0; + m_Voted = 0; +} + +void CVoting::AddOption(const char *pDescription) +{ + CVoteOptionClient *pOption; + if(m_pRecycleFirst) + { + pOption = m_pRecycleFirst; + m_pRecycleFirst = m_pRecycleFirst->m_pNext; + if(m_pRecycleFirst) + m_pRecycleFirst->m_pPrev = 0; + else + m_pRecycleLast = 0; + } + else + pOption = (CVoteOptionClient *)m_Heap.Allocate(sizeof(CVoteOptionClient)); + + pOption->m_pNext = 0; + pOption->m_pPrev = m_pLast; + if(pOption->m_pPrev) + pOption->m_pPrev->m_pNext = pOption; + m_pLast = pOption; + if(!m_pFirst) + m_pFirst = pOption; + + str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); + ++m_NumVoteOptions; +} + +void CVoting::ClearOptions() +{ + m_Heap.Reset(); + + m_NumVoteOptions = 0; + m_pFirst = 0; + m_pLast = 0; + + m_pRecycleFirst = 0; + m_pRecycleLast = 0; +} + +void CVoting::OnReset() +{ + m_Closetime = 0; + m_aDescription[0] = 0; + m_aReason[0] = 0; + m_Yes = m_No = m_Pass = m_Total = 0; + m_Voted = 0; +} + +void CVoting::OnConsoleInit() +{ + Console()->Register("callvote", "s[name] s[command] ?r[reason]", CFGFLAG_CLIENT, ConCallvote, this, "Call vote"); + Console()->Register("vote", "r['yes'|'no']", CFGFLAG_CLIENT, ConVote, this, "Vote yes/no"); +} + +void CVoting::OnMessage(int MsgType, void *pRawMsg) +{ + if(MsgType == NETMSGTYPE_SV_VOTESET) + { + CNetMsg_Sv_VoteSet *pMsg = (CNetMsg_Sv_VoteSet *)pRawMsg; + if(pMsg->m_Timeout) + { + OnReset(); + str_copy(m_aDescription, pMsg->m_pDescription, sizeof(m_aDescription)); + str_copy(m_aReason, pMsg->m_pReason, sizeof(m_aReason)); + m_Closetime = time_get() + time_freq() * pMsg->m_Timeout; + } + else + OnReset(); + } + else if(MsgType == NETMSGTYPE_SV_VOTESTATUS) + { + CNetMsg_Sv_VoteStatus *pMsg = (CNetMsg_Sv_VoteStatus *)pRawMsg; + m_Yes = pMsg->m_Yes; + m_No = pMsg->m_No; + m_Pass = pMsg->m_Pass; + m_Total = pMsg->m_Total; + } + else if(MsgType == NETMSGTYPE_SV_VOTECLEAROPTIONS) + { + ClearOptions(); + } + else if(MsgType == NETMSGTYPE_SV_VOTEOPTIONLISTADD) + { + CNetMsg_Sv_VoteOptionListAdd *pMsg = (CNetMsg_Sv_VoteOptionListAdd *)pRawMsg; + int NumOptions = pMsg->m_NumOptions; + for(int i = 0; i < NumOptions; ++i) + { + switch(i) + { + case 0: AddOption(pMsg->m_pDescription0); break; + case 1: AddOption(pMsg->m_pDescription1); break; + case 2: AddOption(pMsg->m_pDescription2); break; + case 3: AddOption(pMsg->m_pDescription3); break; + case 4: AddOption(pMsg->m_pDescription4); break; + case 5: AddOption(pMsg->m_pDescription5); break; + case 6: AddOption(pMsg->m_pDescription6); break; + case 7: AddOption(pMsg->m_pDescription7); break; + case 8: AddOption(pMsg->m_pDescription8); break; + case 9: AddOption(pMsg->m_pDescription9); break; + case 10: AddOption(pMsg->m_pDescription10); break; + case 11: AddOption(pMsg->m_pDescription11); break; + case 12: AddOption(pMsg->m_pDescription12); break; + case 13: AddOption(pMsg->m_pDescription13); break; + case 14: AddOption(pMsg->m_pDescription14); + } + } + } + else if(MsgType == NETMSGTYPE_SV_VOTEOPTIONADD) + { + CNetMsg_Sv_VoteOptionAdd *pMsg = (CNetMsg_Sv_VoteOptionAdd *)pRawMsg; + AddOption(pMsg->m_pDescription); + } + 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) + { + // remove it from the list + if(m_pFirst == pOption) + m_pFirst = m_pFirst->m_pNext; + if(m_pLast == pOption) + m_pLast = m_pLast->m_pPrev; + if(pOption->m_pPrev) + pOption->m_pPrev->m_pNext = pOption->m_pNext; + if(pOption->m_pNext) + pOption->m_pNext->m_pPrev = pOption->m_pPrev; + --m_NumVoteOptions; + + // add it to recycle list + pOption->m_pNext = 0; + pOption->m_pPrev = m_pRecycleLast; + if(pOption->m_pPrev) + pOption->m_pPrev->m_pNext = pOption; + m_pRecycleLast = pOption; + if(!m_pRecycleFirst) + m_pRecycleLast = pOption; + + break; + } + } + } +} + +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; + if(m_Yes) + { + 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]; + str_format(Buf, sizeof(Buf), "%d", m_No); + UI()->DoLabel(&NoArea, Buf, Bars.h*0.75f, 0); + } + + PassArea.w -= NoArea.w; + } + + if(Text && m_Pass) + { + char Buf[256]; + 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 new file mode 100644 index 0000000..8a3d824 --- /dev/null +++ b/src/game/client/components/voting.h @@ -0,0 +1,60 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_COMPONENTS_VOTING_H +#define GAME_CLIENT_COMPONENTS_VOTING_H + +#include <engine/shared/memheap.h> + +#include <game/voting.h> +#include <game/client/component.h> +#include <game/client/ui.h> + +class CVoting : public CComponent +{ + CHeap m_Heap; + + 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; + CVoteOptionClient *m_pFirst; + CVoteOptionClient *m_pLast; + + CVoteOptionClient *m_pRecycleFirst; + CVoteOptionClient *m_pRecycleLast; + + CVoting(); + virtual void OnReset(); + 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; } + const char *VoteDescription() const { return m_aDescription; } + const char *VoteReason() const { return m_aReason; } +}; + +#endif diff --git a/src/game/client/gameclient.cpp b/src/game/client/gameclient.cpp new file mode 100644 index 0000000..4d57767 --- /dev/null +++ b/src/game/client/gameclient.cpp @@ -0,0 +1,2268 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/editor.h> +#include <engine/engine.h> +#include <engine/friends.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include <engine/demo.h> +#include <engine/map.h> +#include <engine/storage.h> +#include <engine/sound.h> +#include <engine/serverbrowser.h> +#include <engine/updater.h> +#include <engine/shared/demo.h> +#include <engine/shared/config.h> + +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +#include <base/math.h> +#include <base/vmath.h> + +#include <game/localization.h> +#include <game/version.h> +#include "render.h" + +#include "gameclient.h" + +#include "components/background.h" +#include "components/binds.h" +#include "components/broadcast.h" +#include "components/camera.h" +#include "components/chat.h" +#include "components/console.h" +#include "components/controls.h" +#include "components/countryflags.h" +#include "components/damageind.h" +#include "components/debughud.h" +#include "components/effects.h" +#include "components/emoticon.h" +#include "components/flow.h" +#include "components/hud.h" +#include "components/items.h" +#include "components/killmessages.h" +#include "components/mapimages.h" +#include "components/maplayers.h" +#include "components/mapsounds.h" +#include "components/menus.h" +#include "components/motd.h" +#include "components/particles.h" +#include "components/players.h" +#include "components/nameplates.h" +#include "components/scoreboard.h" +#include "components/skins.h" +#include "components/sounds.h" +#include "components/spectator.h" +#include "components/statboard.h" +#include "components/voting.h" + +#include <base/system.h> +#include "components/race_demo.h" +#include "components/ghost.h" +#include <base/tl/sorted_array.h> + +CGameClient g_GameClient; + +// instanciate all systems +static CKillMessages gs_KillMessages; +static CCamera gs_Camera; +static CChat gs_Chat; +static CMotd gs_Motd; +static CBroadcast gs_Broadcast; +static CGameConsole gs_GameConsole; +static CBinds gs_Binds; +static CParticles gs_Particles; +static CMenus gs_Menus; +static CSkins gs_Skins; +static CCountryFlags gs_CountryFlags; +static CFlow gs_Flow; +static CHud gs_Hud; +static CDebugHud gs_DebugHud; +static CControls gs_Controls; +static CEffects gs_Effects; +static CScoreboard gs_Scoreboard; +static CStatboard gs_Statboard; +static CSounds gs_Sounds; +static CEmoticon gs_Emoticon; +static CDamageInd gsDamageInd; +static CVoting gs_Voting; +static CSpectator gs_Spectator; + +static CPlayers gs_Players; +static CNamePlates gs_NamePlates; +static CItems gs_Items; +static CMapImages gs_MapImages; + +static CMapLayers gs_MapLayersBackGround(CMapLayers::TYPE_BACKGROUND); +static CMapLayers gs_MapLayersForeGround(CMapLayers::TYPE_FOREGROUND); +static CBackground gs_BackGround; + +static CMapSounds gs_MapSounds; + +static CRaceDemo gs_RaceDemo; +static CGhost gs_Ghost; + +CGameClient::CStack::CStack() { m_Num = 0; } +void CGameClient::CStack::Add(class CComponent *pComponent) { m_paComponents[m_Num++] = pComponent; } + +const char *CGameClient::Version() { return GAME_VERSION; } +const char *CGameClient::NetVersion() { return GAME_NETVERSION; } +const char *CGameClient::GetItemName(int Type) { return m_NetObjHandler.GetObjName(Type); } + +const CNetObj_PlayerInput &CGameClient::getPlayerInput(int dummy) +{ + return m_pControls->m_InputData[dummy]; +} + +void CGameClient::ResetDummyInput() +{ + m_pControls->ResetInput(!g_Config.m_ClDummy); +} + +void CGameClient::OnConsoleInit() +{ + m_pEngine = Kernel()->RequestInterface<IEngine>(); + m_pClient = Kernel()->RequestInterface<IClient>(); + m_pTextRender = Kernel()->RequestInterface<ITextRender>(); + m_pSound = Kernel()->RequestInterface<ISound>(); + m_pInput = Kernel()->RequestInterface<IInput>(); + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + m_pDemoPlayer = Kernel()->RequestInterface<IDemoPlayer>(); + m_pServerBrowser = Kernel()->RequestInterface<IServerBrowser>(); + m_pEditor = Kernel()->RequestInterface<IEditor>(); + m_pFriends = Kernel()->RequestInterface<IFriends>(); + m_pFoes = Client()->Foes(); +#if defined(CONF_FAMILY_WINDOWS) || (defined(CONF_PLATFORM_LINUX) && !defined(__ANDROID__)) + m_pUpdater = Kernel()->RequestInterface<IUpdater>(); +#endif + + // setup pointers + m_pBinds = &::gs_Binds; + m_pGameConsole = &::gs_GameConsole; + m_pParticles = &::gs_Particles; + m_pMenus = &::gs_Menus; + m_pSkins = &::gs_Skins; + m_pCountryFlags = &::gs_CountryFlags; + m_pChat = &::gs_Chat; + m_pFlow = &::gs_Flow; + m_pCamera = &::gs_Camera; + m_pControls = &::gs_Controls; + m_pEffects = &::gs_Effects; + m_pSounds = &::gs_Sounds; + m_pMotd = &::gs_Motd; + m_pDamageind = &::gsDamageInd; + m_pMapimages = &::gs_MapImages; + m_pVoting = &::gs_Voting; + m_pScoreboard = &::gs_Scoreboard; + m_pStatboard = &::gs_Statboard; + m_pItems = &::gs_Items; + m_pMapLayersBackGround = &::gs_MapLayersBackGround; + m_pMapLayersForeGround = &::gs_MapLayersForeGround; + m_pBackGround = &::gs_BackGround; + + m_pMapSounds = &::gs_MapSounds; + + m_pRaceDemo = &::gs_RaceDemo; + m_pGhost = &::gs_Ghost; + + // make a list of all the systems, make sure to add them in the correct render order + m_All.Add(m_pSkins); + m_All.Add(m_pCountryFlags); + m_All.Add(m_pMapimages); + m_All.Add(m_pEffects); // doesn't render anything, just updates effects + m_All.Add(m_pParticles); + m_All.Add(m_pBinds); + m_All.Add(m_pControls); + m_All.Add(m_pCamera); + 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(m_pRaceDemo); + m_All.Add(m_pMapSounds); + + m_All.Add(&gs_BackGround); //render instead of gs_MapLayersBackGround when g_Config.m_ClOverlayEntities == 100 + m_All.Add(&gs_MapLayersBackGround); // first to render + m_All.Add(&m_pParticles->m_RenderTrail); + m_All.Add(m_pItems); + m_All.Add(&gs_Players); + m_All.Add(m_pGhost); + m_All.Add(&gs_MapLayersForeGround); + m_All.Add(&m_pParticles->m_RenderExplosions); + m_All.Add(&gs_NamePlates); + m_All.Add(&m_pParticles->m_RenderGeneral); + m_All.Add(m_pDamageind); + m_All.Add(&gs_Hud); + m_All.Add(&gs_Spectator); + m_All.Add(&gs_Emoticon); + m_All.Add(&gs_KillMessages); + m_All.Add(m_pChat); + m_All.Add(&gs_Broadcast); + m_All.Add(&gs_DebugHud); + m_All.Add(&gs_Scoreboard); + m_All.Add(&gs_Statboard); + 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); + m_Input.Add(m_pGameConsole); + m_Input.Add(m_pChat); // chat has higher prio due to tha you can quit it by pressing esc + m_Input.Add(m_pMotd); // for pressing esc to remove it + m_Input.Add(m_pMenus); + m_Input.Add(&gs_Spectator); + m_Input.Add(&gs_Emoticon); + m_Input.Add(m_pControls); + m_Input.Add(m_pBinds); + + // add the some console commands + Console()->Register("team", "i[team-id]", 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", "s[tuning] i[value]", CFGFLAG_SERVER, 0, 0, "Tune variable to value"); + Console()->Register("tune_reset", "", CFGFLAG_SERVER, 0, 0, "Reset tuning"); + Console()->Register("tune_dump", "", CFGFLAG_SERVER, 0, 0, "Dump tuning"); + Console()->Register("change_map", "?r[map]", CFGFLAG_SERVER, 0, 0, "Change map"); + Console()->Register("restart", "?i[seconds]", CFGFLAG_SERVER, 0, 0, "Restart in x seconds"); + Console()->Register("broadcast", "r[message]", CFGFLAG_SERVER, 0, 0, "Broadcast message"); + Console()->Register("say", "r[message]", CFGFLAG_SERVER, 0, 0, "Say in chat"); + Console()->Register("set_team", "i[id] i[team-id] ?i[delay in minutes]", CFGFLAG_SERVER, 0, 0, "Set team of player to team"); + Console()->Register("set_team_all", "i[team-id]", CFGFLAG_SERVER, 0, 0, "Set team of all players to team"); + Console()->Register("add_vote", "s[name] r[command]", CFGFLAG_SERVER, 0, 0, "Add a voting option"); + Console()->Register("remove_vote", "s[name]", CFGFLAG_SERVER, 0, 0, "remove a voting option"); + Console()->Register("force_vote", "s[name] s[command] ?r[reason]", CFGFLAG_SERVER, 0, 0, "Force a voting option"); + Console()->Register("clear_votes", "", CFGFLAG_SERVER, 0, 0, "Clears the voting options"); + Console()->Register("vote", "r['yes'|'no']", CFGFLAG_SERVER, 0, 0, "Force a vote to yes/no"); + Console()->Register("swap_teams", "", CFGFLAG_SERVER, 0, 0, "Swap the current teams"); + Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, 0, 0, "Shuffle the current teams"); + + + 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); + Console()->Chain("player_country", ConchainSpecialInfoupdate, this); + Console()->Chain("player_use_custom_color", ConchainSpecialInfoupdate, this); + Console()->Chain("player_color_body", ConchainSpecialInfoupdate, this); + Console()->Chain("player_color_feet", ConchainSpecialInfoupdate, this); + Console()->Chain("player_skin", ConchainSpecialInfoupdate, this); + + Console()->Chain("dummy_name", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_clan", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_country", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_use_custom_color", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_color_body", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_color_feet", ConchainSpecialDummyInfoupdate, this); + Console()->Chain("dummy_skin", ConchainSpecialDummyInfoupdate, this); + + Console()->Chain("cl_dummy", ConchainSpecialDummy, this); + + // + m_SuppressEvents = false; +} + +void CGameClient::OnInit() +{ + m_pGraphics = Kernel()->RequestInterface<IGraphics>(); + + // propagate pointers + m_UI.SetGraphics(Graphics(), TextRender()); + m_RenderTools.m_pGraphics = Graphics(); + m_RenderTools.m_pUI = UI(); + + int64 Start = time_get(); + + // set the language + g_Localization.Load(g_Config.m_ClLanguagefile, Storage(), Console()); + + // TODO: this should be different + // setup item sizes + for(int i = 0; i < NUM_NETOBJTYPES; i++) + Client()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); + + // load default font + static CFont *pDefaultFont = 0; + char aFilename[512]; + const char *pFontFile = "fonts/DejaVuSansCJKName.ttf"; + if (str_find(g_Config.m_ClLanguagefile, "chinese") != NULL || str_find(g_Config.m_ClLanguagefile, "japanese") != NULL || + str_find(g_Config.m_ClLanguagefile, "korean") != NULL) + pFontFile = "fonts/DejavuWenQuanYiMicroHei.ttf"; + IOHANDLE File = Storage()->OpenFile(pFontFile, IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename)); + if(File) + { + io_close(File); + pDefaultFont = TextRender()->LoadFont(aFilename); + TextRender()->SetDefaultFont(pDefaultFont); + } + if(!pDefaultFont) + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", "failed to load font. filename='%s'", pFontFile); + + // init all components + for(int i = m_All.m_Num-1; i >= 0; --i) + m_All.m_paComponents[i]->OnInit(); + + char aBuf[256]; + + // setup load amount// load textures + for(int i = 0; i < g_pData->m_NumImages; i++) + { + g_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(g_pData->m_aImages[i].m_pFilename, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + g_GameClient.m_pMenus->RenderLoading(); + } + +#if defined(__ANDROID__) + m_pMapimages->OnMapLoad(); // Reload map textures on Android +#endif + + for(int i = 0; i < m_All.m_Num; i++) + m_All.m_paComponents[i]->OnReset(); + + int64 End = time_get(); + 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; + + m_DDRaceMsgSent[0] = false; + m_DDRaceMsgSent[1] = false; + m_ShowOthers[0] = -1; + m_ShowOthers[1] = -1; + + // Set free binds to DDRace binds if it's active + if(!g_Config.m_ClDDRaceBindsSet && g_Config.m_ClDDRaceBinds) + gs_Binds.SetDDRaceBinds(true); + + if(g_Config.m_ClTimeoutCode[0] == '\0' || str_comp(g_Config.m_ClTimeoutCode, "hGuEYnfxicsXGwFq") == 0) + { + for(unsigned int i = 0; i < 16; i++) + { + if (rand() % 2) + g_Config.m_ClTimeoutCode[i] = (rand() % 26) + 97; + else + g_Config.m_ClTimeoutCode[i] = (rand() % 26) + 65; + } + } + + if(g_Config.m_ClDummyTimeoutCode[0] == '\0' || str_comp(g_Config.m_ClDummyTimeoutCode, "hGuEYnfxicsXGwFq") == 0) + { + for(unsigned int i = 0; i < 16; i++) + { + if (rand() % 2) + g_Config.m_ClDummyTimeoutCode[i] = (rand() % 26) + 97; + else + g_Config.m_ClDummyTimeoutCode[i] = (rand() % 26) + 65; + } + } +} + +void CGameClient::DispatchInput() +{ + // handle mouse movement + float x = 0.0f, y = 0.0f; + Input()->MouseRelative(&x, &y); +#if !defined(__ANDROID__) // No relative mouse on Android + if(x != 0.0f || y != 0.0f) +#endif + { + for(int h = 0; h < m_Input.m_Num; h++) + { + if(m_Input.m_paComponents[h]->OnMouseMove(x, y)) + 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)) + { + //dbg_msg("", "%d char=%d key=%d flags=%d", h, e.ch, e.key, e.flags); + break; + } + } + } + + // clear all events for this frame + Input()->ClearEvents(); +} + + +int CGameClient::OnSnapInput(int *pData) +{ + return m_pControls->SnapInput(pData); +} + +void CGameClient::OnConnected() +{ + m_Layers.Init(Kernel()); + m_Collision.Init(Layers()); + + RenderTools()->RenderTilemapGenerateSkip(Layers()); + + for(int i = 0; i < m_All.m_Num; i++) + { + m_All.m_paComponents[i]->OnMapLoad(); + m_All.m_paComponents[i]->OnReset(); + } + + CServerInfo CurrentServerInfo; + Client()->GetServerInfo(&CurrentServerInfo); + + m_ServerMode = SERVERMODE_PURE; + + // send the inital info + SendInfo(true); + // we should keep this in for now, because otherwise you can't spectate + // people at start as the other info 64 packet is only sent after the first + // snap + Client()->Rcon("crashmeplx"); +} + +void CGameClient::OnReset() +{ + // clear out the invalid pointers + m_LastNewPredictedTick[0] = -1; + m_LastNewPredictedTick[1] = -1; + mem_zero(&g_GameClient.m_Snap, sizeof(g_GameClient.m_Snap)); + + 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(); + + m_DemoSpecID = SPEC_FOLLOW; + m_FlagDropTick[TEAM_RED] = 0; + m_FlagDropTick[TEAM_BLUE] = 0; + m_LastRoundStartTick = -1; + m_LastFlagCarrierRed = -4; + m_LastFlagCarrierBlue = -4; + m_Tuning[g_Config.m_ClDummy] = CTuningParams(); + + m_Teams.Reset(); + m_DDRaceMsgSent[0] = false; + m_DDRaceMsgSent[1] = false; + m_ShowOthers[0] = -1; + m_ShowOthers[1] = -1; + + for(int i = 0; i < 150; i++) + m_aWeaponData[i].m_Tick = -1; +} + + +void CGameClient::UpdatePositions() +{ + // local character position + if(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) + { + if(!AntiPingPlayers()) + { + if(!m_Snap.m_pLocalCharacter || (m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + // don't use predicted + } + else + m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick()); + } + else + { + if(!(m_Snap.m_pGameInfoObj && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) + { + if (m_Snap.m_pLocalCharacter) + m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick()); + } + // else + // m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick()); + } + } + else if(m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter) + { + m_LocalCharacterPos = mix( + vec2(m_Snap.m_pLocalPrevCharacter->m_X, m_Snap.m_pLocalPrevCharacter->m_Y), + vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y), Client()->IntraGameTick()); + } + + if (AntiPingPlayers()) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (!m_Snap.m_aCharacters[i].m_Active) + continue; + + if (m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter && g_Config.m_ClPredict /* && g_Config.m_AntiPing */ && !(m_Snap.m_LocalClientID == -1 || !m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Active)) + m_Snap.m_aCharacters[i].m_Position = mix(m_aClients[i].m_PrevPredicted.m_Pos, m_aClients[i].m_Predicted.m_Pos, Client()->PredIntraGameTick()); + else + m_Snap.m_aCharacters[i].m_Position = mix(vec2(m_Snap.m_aCharacters[i].m_Prev.m_X, m_Snap.m_aCharacters[i].m_Prev.m_Y), vec2(m_Snap.m_aCharacters[i].m_Cur.m_X, m_Snap.m_aCharacters[i].m_Cur.m_Y), Client()->IntraGameTick()); + } + } + + // spectator position + if(m_Snap.m_SpecInfo.m_Active) + { + if(Client()->State() == IClient::STATE_DEMOPLAYBACK && m_DemoSpecID != SPEC_FOLLOW && m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) + { + m_Snap.m_SpecInfo.m_Position = mix( + vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_Y), + vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_Y), + Client()->IntraGameTick()); + m_Snap.m_SpecInfo.m_UsePosition = true; + } + else if(m_Snap.m_pSpectatorInfo && ((Client()->State() == IClient::STATE_DEMOPLAYBACK && m_DemoSpecID == SPEC_FOLLOW) || (Client()->State() != IClient::STATE_DEMOPLAYBACK && m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW))) + { + if(m_Snap.m_pPrevSpectatorInfo) + m_Snap.m_SpecInfo.m_Position = mix(vec2(m_Snap.m_pPrevSpectatorInfo->m_X, m_Snap.m_pPrevSpectatorInfo->m_Y), + vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), Client()->IntraGameTick()); + else + m_Snap.m_SpecInfo.m_Position = vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y); + m_Snap.m_SpecInfo.m_UsePosition = true; + } + } +} + + +static void Evolve(CNetObj_Character *pCharacter, int Tick) +{ + CWorldCore TempWorld; + CCharacterCore TempCore; + CTeamsCore TempTeams; + mem_zero(&TempCore, sizeof(TempCore)); + mem_zero(&TempTeams, sizeof(TempTeams)); + TempCore.Init(&TempWorld, g_GameClient.Collision(), &TempTeams); + TempCore.Read(pCharacter); + TempCore.m_ActiveWeapon = pCharacter->m_Weapon; + + while(pCharacter->m_Tick < Tick) + { + pCharacter->m_Tick++; + TempCore.Tick(false, true); + TempCore.Move(); + TempCore.Quantize(); + } + + TempCore.Write(pCharacter); +} + +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; + + if(g_Config.m_ClDummy && !Client()->DummyConnected()) + g_Config.m_ClDummy = 0; + + // resend player and dummy info if it was filtered by server + if(Client()->State() == IClient::STATE_ONLINE && !m_pMenus->IsActive()) { + if(m_CheckInfo[0] == 0) { + if( + str_comp(m_aClients[Client()->m_LocalIDs[0]].m_aName, g_Config.m_PlayerName) || + str_comp(m_aClients[Client()->m_LocalIDs[0]].m_aClan, g_Config.m_PlayerClan) || + m_aClients[Client()->m_LocalIDs[0]].m_Country != g_Config.m_PlayerCountry || + str_comp(m_aClients[Client()->m_LocalIDs[0]].m_aSkinName, g_Config.m_ClPlayerSkin) || + m_aClients[Client()->m_LocalIDs[0]].m_UseCustomColor != g_Config.m_ClPlayerUseCustomColor || + m_aClients[Client()->m_LocalIDs[0]].m_ColorBody != g_Config.m_ClPlayerColorBody || + m_aClients[Client()->m_LocalIDs[0]].m_ColorFeet != g_Config.m_ClPlayerColorFeet + ) + SendInfo(false); + else + m_CheckInfo[0] = -1; + } + + if(m_CheckInfo[0] > 0) + m_CheckInfo[0]--; + + if(Client()->DummyConnected()) { + if(m_CheckInfo[1] == 0) { + if( + str_comp(m_aClients[Client()->m_LocalIDs[1]].m_aName, g_Config.m_ClDummyName) || + str_comp(m_aClients[Client()->m_LocalIDs[1]].m_aClan, g_Config.m_ClDummyClan) || + m_aClients[Client()->m_LocalIDs[1]].m_Country != g_Config.m_ClDummyCountry || + str_comp(m_aClients[Client()->m_LocalIDs[1]].m_aSkinName, g_Config.m_ClDummySkin) || + m_aClients[Client()->m_LocalIDs[1]].m_UseCustomColor != g_Config.m_ClDummyUseCustomColor || + m_aClients[Client()->m_LocalIDs[1]].m_ColorBody != g_Config.m_ClDummyColorBody || + m_aClients[Client()->m_LocalIDs[1]].m_ColorFeet != g_Config.m_ClDummyColorFeet + ) + SendDummyInfo(false); + else + m_CheckInfo[1] = -1; + } + + if(m_CheckInfo[1] > 0) + m_CheckInfo[1]--; + } + } +} + +void CGameClient::OnDummyDisconnect() +{ + m_DDRaceMsgSent[1] = false; + m_ShowOthers[1] = -1; + m_LastNewPredictedTick[1] = -1; +} + +void CGameClient::OnRelease() +{ + // release all systems + for(int i = 0; i < m_All.m_Num; i++) + m_All.m_paComponents[i]->OnRelease(); +} + +void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker, bool IsDummy) +{ + // special messages + if(MsgId == NETMSGTYPE_SV_EXTRAPROJECTILE && !IsDummy) + { + 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); + + if(AntiPingWeapons() && Proj.m_Type == WEAPON_GRENADE && !UseExtraInfo(&Proj)) + { + vec2 StartPos; + vec2 Direction; + ExtractInfo(&Proj, &StartPos, &Direction, 1); + if(CWeaponData *pCurrentData = GetWeaponData(Proj.m_StartTick)) + { + if(CWeaponData *pMatchingData = FindWeaponData(Proj.m_StartTick)) + { + if(distance(pMatchingData->m_Direction, Direction) < 0.015) + Direction = pMatchingData->m_Direction; + else if(int *pData = Client()->GetInput(Proj.m_StartTick+2)) + { + CNetObj_PlayerInput *pNextInput = (CNetObj_PlayerInput*) pData; + vec2 NextDirection = normalize(vec2(pNextInput->m_TargetX, pNextInput->m_TargetY)); + if(distance(NextDirection, Direction) < 0.015) + Direction = NextDirection; + } + if(distance(pMatchingData->StartPos(), StartPos) < 1) + StartPos = pMatchingData->StartPos(); + } + pCurrentData->m_Tick = Proj.m_StartTick; + pCurrentData->m_Direction = Direction; + pCurrentData->m_Pos = StartPos - Direction * 28.0f * 0.75f; + } + } + } + + return; + } + else if(MsgId == NETMSGTYPE_SV_TUNEPARAMS) + { + // unpack the new tuning + CTuningParams NewTuning; + int *pParams = (int *)&NewTuning; + // No jetpack on DDNet incompatible servers: + NewTuning.m_JetpackStrength = 0; + for(unsigned i = 0; i < sizeof(CTuningParams)/sizeof(int); i++) + { + int value = pUnpacker->GetInt(); + + // check for unpacking errors + if(pUnpacker->Error()) + break; + + pParams[i] = value; + } + + m_ServerMode = SERVERMODE_PURE; + + // apply new tuning + m_Tuning[IsDummy ? !g_Config.m_ClDummy : g_Config.m_ClDummy] = NewTuning; + return; + } + + void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgId, pUnpacker); + if(!pRawMsg) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "dropped weird message '%s' (%d), failed on '%s'", m_NetObjHandler.GetMsgName(MsgId), MsgId, m_NetObjHandler.FailedMsgOn()); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); + return; + } + + if(IsDummy) + { + if(MsgId == NETMSGTYPE_SV_CHAT + && Client()->m_LocalIDs[0] >= 0 + && Client()->m_LocalIDs[1] >= 0) + { + CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; + + if((pMsg->m_Team == 1 + && (m_aClients[Client()->m_LocalIDs[0]].m_Team != m_aClients[Client()->m_LocalIDs[1]].m_Team + || m_Teams.Team(Client()->m_LocalIDs[0]) != m_Teams.Team(Client()->m_LocalIDs[1]))) + || pMsg->m_Team > 1) + { + m_pChat->OnMessage(MsgId, pRawMsg); + } + } + return; // no need of all that stuff for the dummy + } + + // 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(); + } + else if (MsgId == NETMSGTYPE_SV_EMOTICON) + { + CNetMsg_Sv_Emoticon *pMsg = (CNetMsg_Sv_Emoticon *)pRawMsg; + + // apply + m_aClients[pMsg->m_ClientID].m_Emoticon = pMsg->m_Emoticon; + m_aClients[pMsg->m_ClientID].m_EmoticonStart = Client()->GameTick(); + } + else if(MsgId == NETMSGTYPE_SV_SOUNDGLOBAL) + { + 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 || + pMsg->m_SoundID == SOUND_CTF_CAPTURE || pMsg->m_SoundID == SOUND_CTF_GRAB_EN || + pMsg->m_SoundID == SOUND_CTF_GRAB_PL) + { + if(g_Config.m_SndGame) + g_GameClient.m_pSounds->Enqueue(CSounds::CHN_GLOBAL, pMsg->m_SoundID); + } + else + { + if(g_Config.m_SndGame) + g_GameClient.m_pSounds->Play(CSounds::CHN_GLOBAL, pMsg->m_SoundID, 1.0f); + } + } + else if(MsgId == NETMSGTYPE_SV_TEAMSSTATE) + { + unsigned int i; + + for(i = 0; i < MAX_CLIENTS; i++) + { + int Team = pUnpacker->GetInt(); + bool WentWrong = false; + + if(pUnpacker->Error()) + WentWrong = true; + + if(!WentWrong && Team >= 0 && Team < MAX_CLIENTS) + m_Teams.Team(i, Team); + else if (Team != MAX_CLIENTS) + WentWrong = true; + + if(WentWrong) + { + m_Teams.Team(i, 0); + break; + } + } + + if (i <= 16) + m_Teams.m_IsDDRace16 = true; + } + else if(MsgId == NETMSGTYPE_SV_PLAYERTIME) + { + CNetMsg_Sv_PlayerTime *pMsg = (CNetMsg_Sv_PlayerTime *)pRawMsg; + m_aClients[pMsg->m_ClientID].m_Score = pMsg->m_Time; + } +} + +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); +} + +void CGameClient::OnShutdown() +{ + m_pRaceDemo->OnShutdown(); +} + +void CGameClient::OnEnterGame() +{ + g_GameClient.m_pEffects->ResetDamageIndicator(); +} + +void CGameClient::OnGameOver() +{ + if(Client()->State() != IClient::STATE_DEMOPLAYBACK && g_Config.m_ClEditor == 0) + Client()->AutoScreenshot_Start(); +} + +void CGameClient::OnStartGame() +{ + if(Client()->State() != IClient::STATE_DEMOPLAYBACK) + Client()->DemoRecorder_HandleAutoStart(); + m_pStatboard->OnReset(); +} + +void CGameClient::OnFlagGrab(int TeamID) +{ + if(TeamID == TEAM_RED) + m_aStats[m_Snap.m_pGameDataObj->m_FlagCarrierRed].m_FlagGrabs++; + else + m_aStats[m_Snap.m_pGameDataObj->m_FlagCarrierBlue].m_FlagGrabs++; +} + +void CGameClient::OnRconLine(const char *pLine) +{ + m_pGameConsole->PrintLine(CGameConsole::CONSOLETYPE_REMOTE, pLine); +} + +void CGameClient::ProcessEvents() +{ + if(m_SuppressEvents) + return; + + int SnapType = IClient::SNAP_CURRENT; + int Num = Client()->SnapNumItems(SnapType); + for(int Index = 0; Index < Num; Index++) + { + IClient::CSnapItem Item; + const void *pData = Client()->SnapGetItem(SnapType, Index, &Item); + + if(Item.m_Type == NETEVENTTYPE_DAMAGEIND) + { + CNetEvent_DamageInd *ev = (CNetEvent_DamageInd *)pData; + g_GameClient.m_pEffects->DamageIndicator(vec2(ev->m_X, ev->m_Y), GetDirection(ev->m_Angle)); + } + else if(Item.m_Type == NETEVENTTYPE_EXPLOSION) + { + CNetEvent_Explosion *ev = (CNetEvent_Explosion *)pData; + g_GameClient.m_pEffects->Explosion(vec2(ev->m_X, ev->m_Y)); + } + else if(Item.m_Type == NETEVENTTYPE_HAMMERHIT) + { + CNetEvent_HammerHit *ev = (CNetEvent_HammerHit *)pData; + g_GameClient.m_pEffects->HammerHit(vec2(ev->m_X, ev->m_Y)); + } + else if(Item.m_Type == NETEVENTTYPE_SPAWN) + { + CNetEvent_Spawn *ev = (CNetEvent_Spawn *)pData; + g_GameClient.m_pEffects->PlayerSpawn(vec2(ev->m_X, ev->m_Y)); + } + else if(Item.m_Type == NETEVENTTYPE_DEATH) + { + CNetEvent_Death *ev = (CNetEvent_Death *)pData; + g_GameClient.m_pEffects->PlayerDeath(vec2(ev->m_X, ev->m_Y), ev->m_ClientID); + } + else if(Item.m_Type == NETEVENTTYPE_SOUNDWORLD) + { + CNetEvent_SoundWorld *ev = (CNetEvent_SoundWorld *)pData; + if(g_Config.m_SndGame && (ev->m_SoundID != SOUND_GUN_FIRE || g_Config.m_SndGun)) + g_GameClient.m_pSounds->PlayAt(CSounds::CHN_WORLD, ev->m_SoundID, 1.0f, vec2(ev->m_X, ev->m_Y)); + } + } +} + +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; + + // secure snapshot + { + int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); + for(int Index = 0; Index < Num; Index++) + { + IClient::CSnapItem Item; + void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item); + if(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0) + { + if(g_Config.m_Debug) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "invalidated index=%d type=%d (%s) size=%d id=%d", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_ID); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + } + Client()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index); + } + } + } + + ProcessEvents(); + + if(g_Config.m_DbgStress) + { + if((Client()->GameTick()%100) == 0) + { + char aMessage[64]; + int MsgLen = rand()%(sizeof(aMessage)-1); + 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; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + } + } + + // 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; + + for(int i = 0; i < MAX_CLIENTS; i++) + m_aStats[i].m_Active = false; + + int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); + for(int i = 0; i < Num; i++) + { + IClient::CSnapItem Item; + const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); + + if(Item.m_Type == NETOBJTYPE_CLIENTINFO) + { + const CNetObj_ClientInfo *pInfo = (const CNetObj_ClientInfo *)pData; + int ClientID = Item.m_ID; + IntsToStr(&pInfo->m_Name0, 4, m_aClients[ClientID].m_aName); + IntsToStr(&pInfo->m_Clan0, 3, m_aClients[ClientID].m_aClan); + m_aClients[ClientID].m_Country = 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) + { + m_aClients[ClientID].m_SkinID = g_GameClient.m_pSkins->Find("default"); + 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 + { + m_aClients[ClientID].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[ClientID].m_SkinID)->m_OrgTexture; + m_aClients[ClientID].m_SkinInfo.m_ColorBody = vec4(1,1,1,1); + m_aClients[ClientID].m_SkinInfo.m_ColorFeet = vec4(1,1,1,1); + } + + 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]++; + m_aStats[pInfo->m_ClientID].m_Active = true; + } + + } + else if(Item.m_Type == NETOBJTYPE_CHARACTER) + { + const void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_ID); + m_Snap.m_aCharacters[Item.m_ID].m_Cur = *((const CNetObj_Character *)pData); + if(pOld) + { + m_Snap.m_aCharacters[Item.m_ID].m_Active = true; + m_Snap.m_aCharacters[Item.m_ID].m_Prev = *((const CNetObj_Character *)pOld); + + if(m_Snap.m_aCharacters[Item.m_ID].m_Prev.m_Tick) + Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Prev, Client()->PrevGameTick()); + if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Tick) + Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Cur, Client()->GameTick()); + } + } + else if(Item.m_Type == NETOBJTYPE_SPECTATORINFO) + { + m_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)pData; + m_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_SPECTATORINFO, Item.m_ID); + + m_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_pSpectatorInfo->m_SpectatorID; + } + else if(Item.m_Type == NETOBJTYPE_GAMEINFO) + { + static bool s_GameOver = 0; + static bool s_GamePaused = 0; + m_Snap.m_pGameInfoObj = (const CNetObj_GameInfo *)pData; + bool CurrentTickGameOver = m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER; + if(!s_GameOver && CurrentTickGameOver) + OnGameOver(); + else if(s_GameOver && !CurrentTickGameOver) + OnStartGame(); + // Reset statboard when new round is started (RoundStartTick changed) + // New round is usually started after `restart` on server + if(m_Snap.m_pGameInfoObj->m_RoundStartTick != m_LastRoundStartTick + // In GamePaused or GameOver state RoundStartTick is updated on each tick + // hence no need to reset stats until player leaves GameOver + // and it would be a mistake to reset stats after or during the pause + && !(CurrentTickGameOver || m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED || s_GamePaused)) + m_pStatboard->OnReset(); + m_LastRoundStartTick = m_Snap.m_pGameInfoObj->m_RoundStartTick; + s_GameOver = CurrentTickGameOver; + s_GamePaused = m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED; + } + else if(Item.m_Type == NETOBJTYPE_GAMEDATA) + { + m_Snap.m_pGameDataObj = (const CNetObj_GameData *)pData; + m_Snap.m_GameDataSnapID = Item.m_ID; + if(m_Snap.m_pGameDataObj->m_FlagCarrierRed == FLAG_TAKEN) + { + if(m_FlagDropTick[TEAM_RED] == 0) + m_FlagDropTick[TEAM_RED] = Client()->GameTick(); + } + else if(m_FlagDropTick[TEAM_RED] != 0) + m_FlagDropTick[TEAM_RED] = 0; + if(m_Snap.m_pGameDataObj->m_FlagCarrierBlue == FLAG_TAKEN) + { + if(m_FlagDropTick[TEAM_BLUE] == 0) + m_FlagDropTick[TEAM_BLUE] = Client()->GameTick(); + } + else if(m_FlagDropTick[TEAM_BLUE] != 0) + m_FlagDropTick[TEAM_BLUE] = 0; + if(m_LastFlagCarrierRed == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierRed >= 0) + OnFlagGrab(TEAM_RED); + else if(m_LastFlagCarrierBlue == FLAG_ATSTAND && m_Snap.m_pGameDataObj->m_FlagCarrierBlue >= 0) + OnFlagGrab(TEAM_BLUE); + + m_LastFlagCarrierRed = m_Snap.m_pGameDataObj->m_FlagCarrierRed; + m_LastFlagCarrierBlue = m_Snap.m_pGameDataObj->m_FlagCarrierBlue; + } + else if(Item.m_Type == NETOBJTYPE_FLAG) + m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData; + } + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_aStats[i].m_Active && !m_aStats[i].m_WasActive) + { + m_aStats[i].m_Active = true; + m_aStats[i].m_JoinDate = Client()->GameTick(); + } + m_aStats[i].m_WasActive = m_aStats[i].m_Active; + } + } + + // setup local pointers + if(m_Snap.m_LocalClientID >= 0) + { + CSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_Snap.m_LocalClientID]; + if(c->m_Active) + { + m_Snap.m_pLocalCharacter = &c->m_Cur; + m_Snap.m_pLocalPrevCharacter = &c->m_Prev; + m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y); + } + else if(Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, m_Snap.m_LocalClientID)) + { + // player died + m_pControls->OnPlayerDeath(); + } + } + if(Client()->State() == IClient::STATE_DEMOPLAYBACK) + { + if(m_DemoSpecID != SPEC_FOLLOW) + { + m_Snap.m_SpecInfo.m_Active = true; + m_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_LocalClientID; + if(m_DemoSpecID > SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecID].m_Active) + m_Snap.m_SpecInfo.m_SpectatorID = m_DemoSpecID; + else + m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; + } + } + + // clear out unneeded client data + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(!m_Snap.m_paPlayerInfos[i] && m_aClients[i].m_Active) + m_aClients[i].Reset(); + } + + // update friend state + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Friends()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)) + m_aClients[i].m_Friend = false; + else + m_aClients[i].m_Friend = true; + } + + // update foe state + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Foes()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)) + m_aClients[i].m_Foe = false; + else + m_aClients[i].m_Foe = true; + } + + // sort player infos by name + mem_copy(m_Snap.m_paInfoByName, m_Snap.m_paPlayerInfos, sizeof(m_Snap.m_paInfoByName)); + for(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort + { + for(int i = 0; i < MAX_CLIENTS-k-1; i++) + { + if(m_Snap.m_paInfoByName[i+1] && (!m_Snap.m_paInfoByName[i] || str_comp_nocase(m_aClients[m_Snap.m_paInfoByName[i]->m_ClientID].m_aName, m_aClients[m_Snap.m_paInfoByName[i+1]->m_ClientID].m_aName) > 0)) + { + const CNetObj_PlayerInfo *pTmp = m_Snap.m_paInfoByName[i]; + m_Snap.m_paInfoByName[i] = m_Snap.m_paInfoByName[i+1]; + m_Snap.m_paInfoByName[i+1] = pTmp; + } + } + } + + // sort player infos by score + mem_copy(m_Snap.m_paInfoByScore, m_Snap.m_paInfoByName, sizeof(m_Snap.m_paInfoByScore)); + for(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort + { + for(int i = 0; i < MAX_CLIENTS-k-1; i++) + { + if(m_Snap.m_paInfoByScore[i+1] && (!m_Snap.m_paInfoByScore[i] || m_Snap.m_paInfoByScore[i]->m_Score < m_Snap.m_paInfoByScore[i+1]->m_Score)) + { + const CNetObj_PlayerInfo *pTmp = m_Snap.m_paInfoByScore[i]; + m_Snap.m_paInfoByScore[i] = m_Snap.m_paInfoByScore[i+1]; + m_Snap.m_paInfoByScore[i+1] = pTmp; + } + } + } + + // sort player infos by team + //int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS }; + int Index = 0; + //for(int Team = 0; Team < 3; ++Team) + //{ + // for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i) + // { + // if(m_Snap.m_paPlayerInfos[i] && m_Snap.m_paPlayerInfos[i]->m_Team == Teams[Team]) + // m_Snap.m_paInfoByTeam[Index++] = m_Snap.m_paPlayerInfos[i]; + // } + //} + + // sort player infos by DDRace Team (and score inbetween) + Index = 0; + for(int Team = 0; Team <= MAX_CLIENTS; ++Team) + { + for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i) + { + if(m_Snap.m_paInfoByScore[i] && m_Teams.Team(m_Snap.m_paInfoByScore[i]->m_ClientID) == Team) + m_Snap.m_paInfoByDDTeam[Index++] = m_Snap.m_paInfoByScore[i]; + } + } + + CTuningParams StandardTuning; + CServerInfo CurrentServerInfo; + Client()->GetServerInfo(&CurrentServerInfo); + if(CurrentServerInfo.m_aGameType[0] != '0') + { + if(str_comp(CurrentServerInfo.m_aGameType, "DM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "TDM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "CTF") != 0) + m_ServerMode = SERVERMODE_MOD; + else if(mem_comp(&StandardTuning, &m_Tuning[g_Config.m_ClDummy], 33) == 0) + m_ServerMode = SERVERMODE_PURE; + else + m_ServerMode = SERVERMODE_PUREMOD; + } + + // add tuning to demo + bool AnyRecording = false; + for(int i = 0; i < RECORDER_MAX; i++) + if(DemoRecorder(i)->IsRecording()) + { + AnyRecording = true; + break; + } + if(AnyRecording && mem_comp(&StandardTuning, &m_Tuning[g_Config.m_ClDummy], sizeof(CTuningParams)) != 0) + { + CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); + int *pParams = (int *)&m_Tuning[g_Config.m_ClDummy]; + for(unsigned i = 0; i < sizeof(m_Tuning[0])/sizeof(int); i++) + Msg.AddInt(pParams[i]); + Client()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND); + } + + if((!m_DDRaceMsgSent[0] && m_Snap.m_pLocalInfo) or g_Config.m_ClSpamVersion) + { + CMsgPacker Msg(NETMSGTYPE_CL_ISDDNET); + Msg.AddInt(g_Config.m_ClClientVersionNr); + Client()->SendMsgExY(&Msg, MSGFLAG_VITAL,false, 0); + m_DDRaceMsgSent[0] = true; + } + + if(!m_DDRaceMsgSent[1] && m_Snap.m_pLocalInfo && Client()->DummyConnected()) + { + CMsgPacker Msg(NETMSGTYPE_CL_ISDDNET); + Msg.AddInt(g_Config.m_ClClientVersionNr); + Client()->SendMsgExY(&Msg, MSGFLAG_VITAL,false, 1); + m_DDRaceMsgSent[1] = true; + } + + if(m_ShowOthers[g_Config.m_ClDummy] == -1 || (m_ShowOthers[g_Config.m_ClDummy] != -1 && m_ShowOthers[g_Config.m_ClDummy] != g_Config.m_ClShowOthers)) + { + // no need to send, default settings + //if(!(m_ShowOthers == -1 && g_Config.m_ClShowOthers)) + { + CNetMsg_Cl_ShowOthers Msg; + Msg.m_Show = g_Config.m_ClShowOthers; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + } + + // update state + m_ShowOthers[g_Config.m_ClDummy] = g_Config.m_ClShowOthers; + } +} + +void CGameClient::OnPredict() +{ + + // store the previous values so we can detect prediction errors + CCharacterCore BeforePrevChar = m_PredictedPrevChar; + CCharacterCore BeforeChar = m_PredictedChar; + + // 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) + { + if(m_Snap.m_pLocalCharacter) + { + m_PredictedChar.Read(m_Snap.m_pLocalCharacter); + m_PredictedChar.m_ActiveWeapon = m_Snap.m_pLocalCharacter->m_Weapon; + } + if(m_Snap.m_pLocalPrevCharacter) + { + m_PredictedPrevChar.Read(m_Snap.m_pLocalPrevCharacter); + m_PredictedPrevChar.m_ActiveWeapon = m_Snap.m_pLocalPrevCharacter->m_Weapon; + } + return; + } + + static bool IsWeaker[2][MAX_CLIENTS] = {{0}}; + if(AntiPingPlayers()) + FindWeaker(IsWeaker); + + // repredict character + CWorldCore World; + World.m_Tuning[g_Config.m_ClDummy] = m_Tuning[g_Config.m_ClDummy]; + + // search for players + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!m_Snap.m_aCharacters[i].m_Active || !m_Snap.m_paPlayerInfos[i]) + continue; + + g_GameClient.m_aClients[i].m_Predicted.Init(&World, Collision(), &m_Teams); + World.m_apCharacters[i] = &g_GameClient.m_aClients[i].m_Predicted; + World.m_apCharacters[i]->m_Id = m_Snap.m_paPlayerInfos[i]->m_ClientID; + g_GameClient.m_aClients[i].m_Predicted.Read(&m_Snap.m_aCharacters[i].m_Cur); + g_GameClient.m_aClients[i].m_Predicted.m_ActiveWeapon = m_Snap.m_aCharacters[i].m_Cur.m_Weapon; + } + + CServerInfo Info; + Client()->GetServerInfo(&Info); + const int MaxProjectiles = 128; + class CLocalProjectile PredictedProjectiles[MaxProjectiles]; + int NumProjectiles = 0; + int ReloadTimer = 0; + vec2 PrevPos; + + if(AntiPingWeapons()) + { + for(int Index = 0; Index < MaxProjectiles; Index++) + PredictedProjectiles[Index].Deactivate(); + + int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); + for(int Index = 0; Index < Num && NumProjectiles < MaxProjectiles; Index++) + { + IClient::CSnapItem Item; + const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item); + if(Item.m_Type == NETOBJTYPE_PROJECTILE) + { + CNetObj_Projectile* pProj = (CNetObj_Projectile*) pData; + if(pProj->m_Type == WEAPON_GRENADE || (pProj->m_Type == WEAPON_SHOTGUN && UseExtraInfo(pProj))) + { + CLocalProjectile NewProj; + NewProj.Init(this, &World, Collision(), pProj); + if(fabs(1.0f - length(NewProj.m_Direction)) < 0.015) + { + if(!NewProj.m_ExtraInfo) + { + if(CWeaponData *pData = FindWeaponData(NewProj.m_StartTick)) + { + NewProj.m_Pos = pData->StartPos(); + NewProj.m_Direction = pData->m_Direction; + NewProj.m_Owner = m_Snap.m_LocalClientID; + } + } + PredictedProjectiles[NumProjectiles] = NewProj; + NumProjectiles++; + } + } + } + } + + int AttackTick = m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Cur.m_AttackTick; + if(World.m_apCharacters[m_Snap.m_LocalClientID]->m_ActiveWeapon == WEAPON_HAMMER) + { + CWeaponData *pWeaponData = GetWeaponData(AttackTick); + if(pWeaponData && pWeaponData->m_Tick == AttackTick) + ReloadTimer = SERVER_TICK_SPEED / 3 - (Client()->GameTick() - AttackTick); + else + ReloadTimer = 0; + } + else + ReloadTimer = g_pData->m_Weapons.m_aId[World.m_apCharacters[m_Snap.m_LocalClientID]->m_ActiveWeapon].m_Firedelay * SERVER_TICK_SPEED / 1000 - (Client()->GameTick() - AttackTick); + ReloadTimer = max(ReloadTimer, 0); + } + + // 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]; + + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(!World.m_apCharacters[c]) + continue; + + if(AntiPingPlayers() && Tick == Client()->PredGameTick()) + g_GameClient.m_aClients[c].m_PrevPredicted = *World.m_apCharacters[c]; + } + + // input + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(!World.m_apCharacters[c]) + continue; + + mem_zero(&World.m_apCharacters[c]->m_Input, sizeof(World.m_apCharacters[c]->m_Input)); + if(m_Snap.m_LocalClientID == c) + { + // apply player input + int *pInput = Client()->GetInput(Tick); + if(pInput) + World.m_apCharacters[c]->m_Input = *((CNetObj_PlayerInput*)pInput); + } + } + + if(AntiPingWeapons()) + { + const float ProximityRadius = 28.0f; + CNetObj_PlayerInput Input; + CNetObj_PlayerInput PrevInput; + mem_zero(&Input, sizeof(Input)); + mem_zero(&PrevInput, sizeof(PrevInput)); + int *pInput = Client()->GetInput(Tick); + if(pInput) + Input = *((CNetObj_PlayerInput*)pInput); + int *pPrevInput = Client()->GetInput(Tick-1); + if(pPrevInput) + PrevInput = *((CNetObj_PlayerInput*)pPrevInput); + + CCharacterCore *Local = World.m_apCharacters[m_Snap.m_LocalClientID]; + vec2 Direction = normalize(vec2(Input.m_TargetX, Input.m_TargetY)); + vec2 Pos = Local->m_Pos; + vec2 ProjStartPos = Pos + Direction * ProximityRadius * 0.75f; + + bool WeaponFired = false; + bool NewPresses = false; + // handle weapons + do + { + if(ReloadTimer) + break; + if(!World.m_apCharacters[m_Snap.m_LocalClientID]) + break; + if(!pInput || !pPrevInput) + break; + + bool FullAuto = false; + if(Local->m_ActiveWeapon == WEAPON_GRENADE || Local->m_ActiveWeapon == WEAPON_SHOTGUN || Local->m_ActiveWeapon == WEAPON_RIFLE) + FullAuto = true; + + bool WillFire = false; + + if(CountInput(PrevInput.m_Fire, Input.m_Fire).m_Presses) + { + WillFire = true; + NewPresses = true; + } + if(FullAuto && (Input.m_Fire&1)) + WillFire = true; + if(!WillFire) + break; + if(!IsRace(&Info) && !m_Snap.m_pLocalCharacter->m_AmmoCount && Local->m_ActiveWeapon != WEAPON_HAMMER) + break; + + int ExpectedStartTick = Tick-1; + ReloadTimer = g_pData->m_Weapons.m_aId[Local->m_ActiveWeapon].m_Firedelay * SERVER_TICK_SPEED / 1000; + + bool DirectInput = Client()->InputExists(Tick); + if(!DirectInput) + { + ReloadTimer++; + ExpectedStartTick++; + } + + switch(Local->m_ActiveWeapon) + { + case WEAPON_RIFLE: + case WEAPON_SHOTGUN: + case WEAPON_GUN: + { + WeaponFired = true; + } break; + case WEAPON_GRENADE: + { + if(NumProjectiles >= MaxProjectiles) + break; + PredictedProjectiles[NumProjectiles].Init( + this, &World, Collision(), + Direction, //StartDir + ProjStartPos, //StartPos + ExpectedStartTick, //StartTick + WEAPON_GRENADE, //Type + m_Snap.m_LocalClientID, //Owner + WEAPON_GRENADE, //Weapon + 1, 0, 0, 1); //Explosive, Bouncing, Freeze, ExtraInfo + NumProjectiles++; + WeaponFired = true; + } break; + case WEAPON_HAMMER: + { + vec2 ProjPos = ProjStartPos; + float Radius = ProximityRadius*0.5f; + + int Hits = 0; + bool OwnerCanProbablyHitOthers = (m_Tuning[g_Config.m_ClDummy].m_PlayerCollision || m_Tuning[g_Config.m_ClDummy].m_PlayerHooking); + if(!OwnerCanProbablyHitOthers) + break; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!World.m_apCharacters[i]) + continue; + if(i == m_Snap.m_LocalClientID) + continue; + if(!(distance(World.m_apCharacters[i]->m_Pos, ProjPos) < Radius+ProximityRadius)) + continue;; + + CCharacterCore *pTarget = World.m_apCharacters[i]; + + if(m_aClients[i].m_Active && !m_Teams.CanCollide(i, m_Snap.m_LocalClientID)) + continue; + + vec2 Dir; + if (length(pTarget->m_Pos - Pos) > 0.0f) + Dir = normalize(pTarget->m_Pos - Pos); + else + Dir = vec2(0.f, -1.f); + + float Strength; + Strength = World.m_Tuning[g_Config.m_ClDummy].m_HammerStrength; + + vec2 Temp = pTarget->m_Vel + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f; + + pTarget->LimitForce(&Temp); + + Temp -= pTarget->m_Vel; + pTarget->ApplyForce((vec2(0.f, -1.0f) + Temp) * Strength); + Hits++; + } + // if we Hit anything, we have to wait for the reload + if(Hits) + { + ReloadTimer = SERVER_TICK_SPEED/3; + WeaponFired = true; + } + } break; + } + if(!ReloadTimer) + { + ReloadTimer = g_pData->m_Weapons.m_aId[Local->m_ActiveWeapon].m_Firedelay * SERVER_TICK_SPEED / 1000; + if(!DirectInput) + ReloadTimer++; + } + } while(false); + + if(ReloadTimer) + ReloadTimer--; + + if(Tick > Client()->GameTick()+1) + if(CWeaponData *pWeaponData = GetWeaponData(Tick-1)) + pWeaponData->m_Pos = Pos; + if(WeaponFired) + { + if(CWeaponData *pWeaponData = GetWeaponData(Tick-1)) + { + pWeaponData->m_Direction = Direction; + pWeaponData->m_Tick = Tick-1; + } + if(NewPresses) + { + if(CWeaponData *pWeaponData = GetWeaponData(Tick-2)) + { + pWeaponData->m_Direction = Direction; + pWeaponData->m_Tick = Tick-2; + } + if(CWeaponData *pWeaponData = GetWeaponData(Tick)) + { + pWeaponData->m_Direction = Direction; + pWeaponData->m_Tick = Tick; + } + } + } + + // projectiles + for(int g = 0; g < MaxProjectiles; g++) + if(PredictedProjectiles[g].m_Active) + PredictedProjectiles[g].Tick(Tick, Client()->GameTickSpeed(), m_Snap.m_LocalClientID); + } + + // calculate where everyone should move + if(AntiPingPlayers()) + { + //first apply Tick to weaker players (players that the local client has strong hook against), then local, then stronger players + for(int h = 0; h < 3; h++) + { + if(h == 1) + { + if(World.m_apCharacters[m_Snap.m_LocalClientID]) + World.m_apCharacters[m_Snap.m_LocalClientID]->Tick(true, true); + } + else + for(int c = 0; c < MAX_CLIENTS; c++) + if(c != m_Snap.m_LocalClientID && World.m_apCharacters[c] && ((h == 0 && IsWeaker[g_Config.m_ClDummy][c]) || (h == 2 && !IsWeaker[g_Config.m_ClDummy][c]))) + World.m_apCharacters[c]->Tick(false, true); + } + } + else + { + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(!World.m_apCharacters[c]) + continue; + if(m_Snap.m_LocalClientID == c) + World.m_apCharacters[c]->Tick(true, true); + else + World.m_apCharacters[c]->Tick(false, true); + } + } + + // move all players and quantize their data + if(AntiPingPlayers()) + { + // Everyone with weaker hook + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(c != m_Snap.m_LocalClientID && World.m_apCharacters[c] && IsWeaker[g_Config.m_ClDummy][c]) + { + World.m_apCharacters[c]->Move(); + World.m_apCharacters[c]->Quantize(); + } + } + + // Us + if(World.m_apCharacters[m_Snap.m_LocalClientID]) + { + World.m_apCharacters[m_Snap.m_LocalClientID]->Move(); + World.m_apCharacters[m_Snap.m_LocalClientID]->Quantize(); + } + + // Everyone with stronger hook + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(c != m_Snap.m_LocalClientID && World.m_apCharacters[c] && !IsWeaker[g_Config.m_ClDummy][c]) + { + World.m_apCharacters[c]->Move(); + World.m_apCharacters[c]->Quantize(); + } + } + } + else + { + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(!World.m_apCharacters[c]) + continue; + World.m_apCharacters[c]->Move(); + World.m_apCharacters[c]->Quantize(); + } + } + + // check if we want to trigger effects + if(Tick > m_LastNewPredictedTick[g_Config.m_ClDummy]) + { + m_LastNewPredictedTick[g_Config.m_ClDummy] = 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) + if(g_Config.m_SndGame) + 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) + if(g_Config.m_SndGame) + g_GameClient.m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_GROUND, 1.0f, Pos); + if(Events&COREEVENT_HOOK_HIT_NOHOOK) + if(g_Config.m_SndGame) + g_GameClient.m_pSounds->PlayAndRecord(CSounds::CHN_WORLD, SOUND_HOOK_NOATTACH, 1.0f, Pos); + //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 (AntiPingPlayers()) + { + for (int c = 0; c < MAX_CLIENTS; c++) + { + if(!World.m_apCharacters[c]) + continue; + + g_GameClient.m_aClients[c].m_Predicted = *World.m_apCharacters[c]; + } + } + } + } + + if(g_Config.m_Debug && g_Config.m_ClPredict && m_PredictedTick == Client()->PredGameTick()) + { + CNetObj_CharacterCore Before = {0}, Now = {0}, BeforePrev = {0}, NowPrev = {0}; + BeforeChar.Write(&Before); + BeforePrevChar.Write(&BeforePrev); + m_PredictedChar.Write(&Now); + m_PredictedPrevChar.Write(&NowPrev); + + if(mem_comp(&Before, &Now, sizeof(CNetObj_CharacterCore)) != 0) + { + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "prediction error"); + for(unsigned i = 0; i < sizeof(CNetObj_CharacterCore)/sizeof(int); i++) + 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]); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); + } + } + } + + m_PredictedTick = Client()->PredGameTick(); +} + +void CGameClient::OnActivateEditor() +{ + OnRelease(); +} + +CGameClient::CClientStats::CClientStats() +{ + m_JoinDate = 0; + m_Active = false; + m_WasActive = false; + m_Frags = 0; + m_Deaths = 0; + m_Suicides = 0; + for(int j = 0; j < NUM_WEAPONS; j++) + { + m_aFragsWith[j] = 0; + m_aDeathsFrom[j] = 0; + } + m_FlagGrabs = 0; + m_FlagCaptures = 0; +} + +void CGameClient::CClientStats::Reset() +{ + m_JoinDate = 0; + m_Active = false; + m_WasActive = false; + m_Frags = 0; + m_Deaths = 0; + m_Suicides = 0; + m_BestSpree = 0; + m_CurrentSpree = 0; + for(int j = 0; j < NUM_WEAPONS; j++) + { + m_aFragsWith[j] = 0; + m_aDeathsFrom[j] = 0; + } + m_FlagGrabs = 0; + m_FlagCaptures = 0; +} + +void CGameClient::CClientData::UpdateRenderInfo() +{ + m_RenderInfo = m_SkinInfo; + + // force team colors + if(g_GameClient.m_Snap.m_pGameInfoObj && g_GameClient.m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) + { + m_RenderInfo.m_Texture = g_GameClient.m_pSkins->Get(m_SkinID)->m_ColorTexture; + const int TeamColors[2] = {65387, 10223467}; + if(m_Team >= TEAM_RED && m_Team <= TEAM_BLUE) + { + m_RenderInfo.m_ColorBody = g_GameClient.m_pSkins->GetColorV4(TeamColors[m_Team]); + m_RenderInfo.m_ColorFeet = g_GameClient.m_pSkins->GetColorV4(TeamColors[m_Team]); + } + else + { + m_RenderInfo.m_ColorBody = g_GameClient.m_pSkins->GetColorV4(12895054); + m_RenderInfo.m_ColorFeet = g_GameClient.m_pSkins->GetColorV4(12895054); + } + } +} + +void CGameClient::CClientData::Reset() +{ + m_aName[0] = 0; + m_aClan[0] = 0; + m_Country = -1; + m_SkinID = 0; + m_Team = 0; + m_Angle = 0; + m_Emoticon = 0; + m_EmoticonStart = -1; + m_Active = false; + m_ChatIgnore = false; + m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(0)->m_ColorTexture; + m_SkinInfo.m_ColorBody = vec4(1,1,1,1); + m_SkinInfo.m_ColorFeet = vec4(1,1,1,1); + UpdateRenderInfo(); +} + +void CGameClient::SendSwitchTeam(int Team) +{ + CNetMsg_Cl_SetTeam Msg; + Msg.m_Team = Team; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + + if (Team != TEAM_SPECTATORS) + m_pCamera->OnReset(); +} + +void CGameClient::SendInfo(bool Start) +{ + if(Start) + { + CNetMsg_Cl_StartInfo Msg; + Msg.m_pName = g_Config.m_PlayerName; + Msg.m_pClan = g_Config.m_PlayerClan; + Msg.m_Country = g_Config.m_PlayerCountry; + Msg.m_pSkin = g_Config.m_ClPlayerSkin; + Msg.m_UseCustomColor = g_Config.m_ClPlayerUseCustomColor; + Msg.m_ColorBody = g_Config.m_ClPlayerColorBody; + Msg.m_ColorFeet = g_Config.m_ClPlayerColorFeet; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + Client()->SendMsgExY(&Packer, MSGFLAG_VITAL, false, 0); + m_CheckInfo[0] = -1; + } + else + { + CNetMsg_Cl_ChangeInfo Msg; + Msg.m_pName = g_Config.m_PlayerName; + Msg.m_pClan = g_Config.m_PlayerClan; + Msg.m_Country = g_Config.m_PlayerCountry; + Msg.m_pSkin = g_Config.m_ClPlayerSkin; + Msg.m_UseCustomColor = g_Config.m_ClPlayerUseCustomColor; + Msg.m_ColorBody = g_Config.m_ClPlayerColorBody; + Msg.m_ColorFeet = g_Config.m_ClPlayerColorFeet; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + Client()->SendMsgExY(&Packer, MSGFLAG_VITAL, false, 0); + m_CheckInfo[0] = Client()->GameTickSpeed(); + } +} + +void CGameClient::SendDummyInfo(bool Start) +{ + if(Start) + { + CNetMsg_Cl_StartInfo Msg; + Msg.m_pName = g_Config.m_ClDummyName; + Msg.m_pClan = g_Config.m_ClDummyClan; + Msg.m_Country = g_Config.m_ClDummyCountry; + Msg.m_pSkin = g_Config.m_ClDummySkin; + Msg.m_UseCustomColor = g_Config.m_ClDummyUseCustomColor; + Msg.m_ColorBody = g_Config.m_ClDummyColorBody; + Msg.m_ColorFeet = g_Config.m_ClDummyColorFeet; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + Client()->SendMsgExY(&Packer, MSGFLAG_VITAL, false, 1); + m_CheckInfo[1] = -1; + } + else + { + CNetMsg_Cl_ChangeInfo Msg; + Msg.m_pName = g_Config.m_ClDummyName; + Msg.m_pClan = g_Config.m_ClDummyClan; + Msg.m_Country = g_Config.m_ClDummyCountry; + Msg.m_pSkin = g_Config.m_ClDummySkin; + Msg.m_UseCustomColor = g_Config.m_ClDummyUseCustomColor; + Msg.m_ColorBody = g_Config.m_ClDummyColorBody; + Msg.m_ColorFeet = g_Config.m_ClDummyColorFeet; + CMsgPacker Packer(Msg.MsgID()); + Msg.Pack(&Packer); + Client()->SendMsgExY(&Packer, MSGFLAG_VITAL,false, 1); + m_CheckInfo[1] = Client()->GameTickSpeed(); + } +} + +void CGameClient::SendKill(int ClientID) +{ + CNetMsg_Cl_Kill Msg; + Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); + + if(g_Config.m_ClDummyCopyMoves) + { + CMsgPacker Msg(NETMSGTYPE_CL_KILL); + Client()->SendMsgExY(&Msg, MSGFLAG_VITAL, false, !g_Config.m_ClDummy); + } +} + +void CGameClient::ConTeam(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameClient*)pUserData)->SendSwitchTeam(pResult->GetInteger(0)); +} + +void CGameClient::ConKill(IConsole::IResult *pResult, void *pUserData) +{ + ((CGameClient*)pUserData)->SendKill(-1); +} + +void CGameClient::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CGameClient*)pUserData)->SendInfo(false); +} + +void CGameClient::ConchainSpecialDummyInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + ((CGameClient*)pUserData)->SendDummyInfo(false); +} + +void CGameClient::ConchainSpecialDummy(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + if(g_Config.m_ClDummy && !((CGameClient*)pUserData)->Client()->DummyConnected()) + g_Config.m_ClDummy = 0; +} + +IGameClient *CreateGameClient() +{ + return &g_GameClient; +} + +int CGameClient::IntersectCharacter(vec2 HookPos, vec2 NewPos, vec2& NewPos2, int ownID) +{ + float PhysSize = 28.0f; + float Distance = 0.0f; + int ClosestID = -1; + + if (!m_Tuning[g_Config.m_ClDummy].m_PlayerHooking) + return ClosestID; + + for (int i=0; i<MAX_CLIENTS; i++) + { + CClientData cData = m_aClients[i]; + CNetObj_Character Prev = m_Snap.m_aCharacters[i].m_Prev; + CNetObj_Character Player = m_Snap.m_aCharacters[i].m_Cur; + + vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), Client()->IntraGameTick()); + + if (!cData.m_Active || i == ownID || !m_Teams.SameTeam(i, ownID)) + continue; + + vec2 ClosestPoint = closest_point_on_line(HookPos, NewPos, Position); + if(distance(Position, ClosestPoint) < PhysSize+2.0f) + { + if(ClosestID == -1 || distance(HookPos, Position) < Distance) + { + NewPos2 = ClosestPoint; + ClosestID = i; + Distance = distance(HookPos, Position); + } + } + } + + return ClosestID; +} + + +int CGameClient::IntersectCharacter(vec2 OldPos, vec2 NewPos, float Radius, vec2 *NewPos2, int ownID, CWorldCore *World) +{ + float PhysSize = 28.0f; + float Distance = 0.0f; + int ClosestID = -1; + + if(!World) + return ClosestID; + + for (int i=0; i<MAX_CLIENTS; i++) + { + if(!World->m_apCharacters[i]) + continue; + CClientData cData = m_aClients[i]; + + if(!cData.m_Active || i == ownID || !m_Teams.CanCollide(i, ownID)) + continue; + vec2 Position = World->m_apCharacters[i]->m_Pos; + vec2 ClosestPoint = closest_point_on_line(OldPos, NewPos, Position); + if(distance(Position, ClosestPoint) < PhysSize+Radius) + { + if(ClosestID == -1 || distance(OldPos, Position) < Distance) + { + *NewPos2 = ClosestPoint; + ClosestID = i; + Distance = distance(OldPos, Position); + } + } + } + return ClosestID; +} + +void CLocalProjectile::Init(CGameClient *pGameClient, CWorldCore *pWorld, CCollision *pCollision, const CNetObj_Projectile *pProj) +{ + m_Active = 1; + m_pGameClient = pGameClient; + m_pWorld = pWorld; + m_pCollision = pCollision; + m_StartTick = pProj->m_StartTick; + m_Type = pProj->m_Type; + m_Weapon = m_Type; + + ExtractInfo(pProj, &m_Pos, &m_Direction, 1); + + if(UseExtraInfo(pProj)) + { + ExtractExtraInfo(pProj, &m_Owner, &m_Explosive, &m_Bouncing, &m_Freeze); + m_ExtraInfo = true; + } + else + { + bool StandardVel = (fabs(1.0f - length(m_Direction)) < 0.015); + m_Owner = -1; + m_Explosive = ((m_Type == WEAPON_GRENADE && StandardVel) ? true : false); + m_Bouncing = 0; + m_Freeze = 0; + m_ExtraInfo = false; + } +} + +void CLocalProjectile::Init(CGameClient *pGameClient, CWorldCore *pWorld, CCollision *pCollision, vec2 Direction, vec2 Pos, int StartTick, int Type, int Owner, int Weapon, bool Explosive, int Bouncing, bool Freeze, bool ExtraInfo) +{ + m_Active = 1; + m_pGameClient = pGameClient; + m_pWorld = pWorld; + m_pCollision = pCollision; + m_Direction = Direction; + m_Pos = Pos; + m_StartTick = StartTick; + m_Type = Type; + m_Weapon = Weapon; + m_Owner = Owner; + m_Explosive = Explosive; + m_Bouncing = Bouncing; + m_Freeze = Freeze; + m_ExtraInfo = ExtraInfo; +} + +vec2 CLocalProjectile::GetPos(float Time) +{ + float Curvature = 0; + float Speed = 0; + + switch(m_Type) + { + case WEAPON_GRENADE: + Curvature = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GrenadeCurvature; + Speed = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GrenadeSpeed; + break; + + case WEAPON_SHOTGUN: + Curvature = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_ShotgunCurvature; + Speed = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_ShotgunSpeed; + break; + + case WEAPON_GUN: + Curvature = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GunCurvature; + Speed = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GunSpeed; + break; + } + return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); +} + +bool CLocalProjectile::GameLayerClipped(vec2 CheckPos) +{ + return round_to_int(CheckPos.x)/32 < -200 || round_to_int(CheckPos.x)/32 > m_pCollision->GetWidth()+200 || + round_to_int(CheckPos.y)/32 < -200 || round_to_int(CheckPos.y)/32 > m_pCollision->GetHeight()+200 ? true : false; +} + +void CLocalProjectile::Tick(int CurrentTick, int GameTickSpeed, int LocalClientID) +{ + if(!m_pWorld) + return; + if(CurrentTick <= m_StartTick) + return; + float Pt = (CurrentTick-m_StartTick-1)/(float)GameTickSpeed; + float Ct = (CurrentTick-m_StartTick)/(float)GameTickSpeed; + + vec2 PrevPos = GetPos(Pt); + vec2 CurPos = GetPos(Ct); + vec2 ColPos; + vec2 NewPos; + int Collide = 0; + if(m_pCollision) + Collide = m_pCollision->IntersectLine(PrevPos, CurPos, &ColPos, &NewPos, false); + int Target = m_pGameClient->IntersectCharacter(PrevPos, ColPos, m_Freeze ? 1.0f : 6.0f, &ColPos, m_Owner, m_pWorld); + + bool isWeaponCollide = false; + if(m_Owner >= 0 && Target >= 0 && m_pGameClient->m_aClients[m_Owner].m_Active && m_pGameClient->m_aClients[Target].m_Active && !m_pGameClient->m_Teams.CanCollide(m_Owner, Target)) + isWeaponCollide = true; + + bool OwnerCanProbablyHitOthers = (m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision || m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking); + + if(((Target >= 0 && (m_Owner >= 0 ? OwnerCanProbablyHitOthers : 1 || Target == m_Owner)) || Collide || GameLayerClipped(CurPos)) && !isWeaponCollide) + { + if(m_Explosive && (Target < 0 || (Target >= 0 && (!m_Freeze || (m_Weapon == WEAPON_SHOTGUN && Collide))))) + CreateExplosion(ColPos, m_Owner); + if(Collide && m_Bouncing != 0) + { + m_StartTick = CurrentTick; + m_Pos = NewPos+(-(m_Direction*4)); + if (m_Bouncing == 1) + m_Direction.x = -m_Direction.x; + else if(m_Bouncing == 2) + m_Direction.y = -m_Direction.y; + if (fabs(m_Direction.x) < 1e-6) + m_Direction.x = 0; + if (fabs(m_Direction.y) < 1e-6) + m_Direction.y = 0; + m_Pos += m_Direction; + } + else if(!m_Bouncing) + Deactivate(); + } + + if(!m_Bouncing) + { + int Lifetime = 0; + if(m_Weapon == WEAPON_GRENADE) + Lifetime = m_pGameClient->m_Tuning[g_Config.m_ClDummy].m_GrenadeLifetime * SERVER_TICK_SPEED; + else if(m_Weapon == WEAPON_GUN) + Lifetime = m_pGameClient->m_Tuning[g_Config.m_ClDummy].m_GrenadeLifetime * SERVER_TICK_SPEED; + else if(m_Weapon == WEAPON_SHOTGUN) + Lifetime = m_pGameClient->m_Tuning[g_Config.m_ClDummy].m_ShotgunLifetime * SERVER_TICK_SPEED; + int LifeSpan = Lifetime - (CurrentTick - m_StartTick); + if(LifeSpan == -1) + { + if(m_Explosive) + CreateExplosion(ColPos, LocalClientID); + Deactivate(); + } + } +} + +void CLocalProjectile::CreateExplosion(vec2 Pos, int LocalClientID) +{ + if(!m_pWorld) + return; + float Radius = 135.0f; + float InnerRadius = 48.0f; + + bool OwnerCanProbablyHitOthers = (m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision || m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking); + + for(int c = 0; c < MAX_CLIENTS; c++) + { + if(!m_pWorld->m_apCharacters[c]) + continue; + if(m_Owner >= 0 && c >= 0) + if(m_pGameClient->m_aClients[c].m_Active && !m_pGameClient->m_Teams.CanCollide(c, m_Owner)) + continue; + if(c != LocalClientID && !OwnerCanProbablyHitOthers) + continue; + vec2 Diff = m_pWorld->m_apCharacters[c]->m_Pos - Pos; + vec2 ForceDir(0,1); + float l = length(Diff); + if(l) + ForceDir = normalize(Diff); + l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); + + float Strength = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_ExplosionStrength; + float Dmg = Strength * l; + + if((int)Dmg) + m_pWorld->m_apCharacters[c]->ApplyForce(ForceDir*Dmg*2); + } +} + +CWeaponData *CGameClient::FindWeaponData(int TargetTick) +{ + CWeaponData *pData; + int TickDiff[3] = {0, -1, 1}; + for(unsigned int i = 0; i < sizeof(TickDiff)/sizeof(int); i++) + if((pData = GetWeaponData(TargetTick + TickDiff[i]))) + if(pData->m_Tick == TargetTick + TickDiff[i]) + return GetWeaponData(TargetTick + TickDiff[i]); + return NULL; +} + +void CGameClient::FindWeaker(bool IsWeaker[2][MAX_CLIENTS]) +{ + // attempts to detect strong/weak against the player we are hooking + static int DirAccumulated[2][MAX_CLIENTS] = {{0}}; + if(!m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Active || !m_Snap.m_paPlayerInfos[m_Snap.m_LocalClientID]) + return; + int HookedPlayer = m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Prev.m_HookedPlayer; + if(HookedPlayer >= 0 && m_Snap.m_aCharacters[HookedPlayer].m_Active && m_Snap.m_paPlayerInfos[HookedPlayer]) + { + CCharacterCore OtherCharCur; + OtherCharCur.Read(&m_Snap.m_aCharacters[HookedPlayer].m_Cur); + float PredictErr[2]; + for(int dir = 0; dir < 2; dir++) + { + CWorldCore World; + World.m_Tuning[g_Config.m_ClDummy] = m_Tuning[g_Config.m_ClDummy]; + + CCharacterCore OtherChar; + OtherChar.Init(&World, Collision(), &m_Teams); + World.m_apCharacters[HookedPlayer] = &OtherChar; + OtherChar.Read(&m_Snap.m_aCharacters[HookedPlayer].m_Prev); + + CCharacterCore LocalChar; + LocalChar.Init(&World, Collision(), &m_Teams); + World.m_apCharacters[m_Snap.m_LocalClientID] = &LocalChar; + LocalChar.Read(&m_Snap.m_aCharacters[m_Snap.m_LocalClientID].m_Prev); + + for(int Tick = Client()->PrevGameTick(); Tick < Client()->GameTick(); Tick++) + { + if(dir == 0) + { + LocalChar.Tick(false, true); + OtherChar.Tick(false, true); + } + else + { + OtherChar.Tick(false, true); + LocalChar.Tick(false, true); + } + LocalChar.Move(); + LocalChar.Quantize(); + OtherChar.Move(); + OtherChar.Quantize(); + } + PredictErr[dir] = distance(OtherChar.m_Vel, OtherCharCur.m_Vel); + } + const float Low = 0.0001, High = 0.07; + if(PredictErr[1] < Low && PredictErr[0] > High) + DirAccumulated[g_Config.m_ClDummy][HookedPlayer] = SaturatedAdd(-1, 2, DirAccumulated[g_Config.m_ClDummy][HookedPlayer], 1); + else if(PredictErr[0] < Low && PredictErr[1] > High) + DirAccumulated[g_Config.m_ClDummy][HookedPlayer] = SaturatedAdd(-1, 2, DirAccumulated[g_Config.m_ClDummy][HookedPlayer], -1); + IsWeaker[g_Config.m_ClDummy][HookedPlayer] = (DirAccumulated[g_Config.m_ClDummy][HookedPlayer] > 0); + } +} diff --git a/src/game/client/gameclient.h b/src/game/client/gameclient.h new file mode 100644 index 0000000..b29eb1c --- /dev/null +++ b/src/game/client/gameclient.h @@ -0,0 +1,438 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_GAMECLIENT_H +#define GAME_CLIENT_GAMECLIENT_H + +#include <base/vmath.h> +#include <engine/client.h> +#include <engine/console.h> +#include <game/layers.h> +#include <game/gamecore.h> +#include "render.h" + +#include <game/teamscore.h> + +#define MIN3(x,y,z) ((y) <= (z) ? \ + ((x) <= (y) ? (x) : (y)) \ + : \ + ((x) <= (z) ? (x) : (z))) + +#define MAX3(x,y,z) ((y) >= (z) ? \ + ((x) >= (y) ? (x) : (y)) \ + : \ + ((x) >= (z) ? (x) : (z))) + +class CGameClient; + +class CWeaponData +{ +public: + int m_Tick; + vec2 m_Pos; + vec2 m_Direction; + vec2 StartPos() { return m_Pos + m_Direction * 28.0f * 0.75f; } +}; + +class CLocalProjectile +{ +public: + int m_Active; + CGameClient *m_pGameClient; + CWorldCore *m_pWorld; + CCollision *m_pCollision; + + vec2 m_Direction; + vec2 m_Pos; + int m_StartTick; + int m_Type; + + int m_Owner; + int m_Weapon; + bool m_Explosive; + int m_Bouncing; + bool m_Freeze; + bool m_ExtraInfo; + + vec2 GetPos(float Time); + void CreateExplosion(vec2 Pos, int LocalClientID); + void Tick(int CurrentTick, int GameTickSpeed, int LocalClientID); + void Init(CGameClient *pGameClient, CWorldCore *pWorld, CCollision *pCollision, const CNetObj_Projectile *pProj); + void Init(CGameClient *pGameClient, CWorldCore *pWorld, CCollision *pCollision, vec2 Vel, vec2 Pos, int StartTick, int Type, int Owner, int Weapon, bool Explosive, int Bouncing, bool Freeze, bool ExtraInfo); + bool GameLayerClipped(vec2 CheckPos); + void Deactivate() { m_Active = 0; } +}; + +class CGameClient : public IGameClient +{ + class CStack + { + public: + enum + { + 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; + class ITextRender *m_pTextRender; + class IClient *m_pClient; + class ISound *m_pSound; + class IConsole *m_pConsole; + class IStorage *m_pStorage; + class IDemoPlayer *m_pDemoPlayer; + class IServerBrowser *m_pServerBrowser; + class IEditor *m_pEditor; + class IFriends *m_pFriends; + class IFriends *m_pFoes; + class IUpdater *m_pUpdater; + + CLayers m_Layers; + class CCollision m_Collision; + CUI m_UI; + + void DispatchInput(); + void ProcessEvents(); + void UpdatePositions(); + + int m_PredictedTick; + int m_LastNewPredictedTick[2]; + + int m_LastRoundStartTick; + + int m_LastFlagCarrierRed; + int m_LastFlagCarrierBlue; + + int m_CheckInfo[2]; + + 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); + static void ConchainSpecialDummyInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + static void ConchainSpecialDummy(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + +public: + IKernel *Kernel() { return IInterface::Kernel(); } + IEngine *Engine() const { return m_pEngine; } + class IGraphics *Graphics() const { return m_pGraphics; } + class IClient *Client() const { return m_pClient; } + class CUI *UI() { return &m_UI; } + class ISound *Sound() const { return m_pSound; } + class IInput *Input() const { return m_pInput; } + class IStorage *Storage() const { return m_pStorage; } + class IConsole *Console() { return m_pConsole; } + class ITextRender *TextRender() const { return m_pTextRender; } + class IDemoPlayer *DemoPlayer() const { return m_pDemoPlayer; } + class IDemoRecorder *DemoRecorder(int Recorder) const { return Client()->DemoRecorder(Recorder); } + class IServerBrowser *ServerBrowser() const { return m_pServerBrowser; } + class CRenderTools *RenderTools() { return &m_RenderTools; } + class CLayers *Layers() { return &m_Layers; }; + class CCollision *Collision() { return &m_Collision; }; + class IEditor *Editor() { return m_pEditor; } + class IFriends *Friends() { return m_pFriends; } + class IFriends *Foes() { return m_pFoes; } + class IUpdater *Updater() { return m_pUpdater; } + + int NetobjNumCorrections() { return m_NetObjHandler.NumObjCorrections(); } + const char *NetobjCorrectedOn() { return m_NetObjHandler.CorrectedObjOn(); } + + bool m_SuppressEvents; + bool m_NewTick; + bool m_NewPredictedTick; + int m_FlagDropTick[2]; + + // TODO: move this + CTuningParams m_Tuning[2]; + + enum + { + SERVERMODE_PURE=0, + SERVERMODE_MOD, + SERVERMODE_PUREMOD, + }; + int m_ServerMode; + + int m_DemoSpecID; + + vec2 m_LocalCharacterPos; + + // predicted players + CCharacterCore m_PredictedPrevChar; + CCharacterCore m_PredictedChar; + + // snap pointers + struct CSnapState + { + const CNetObj_Character *m_pLocalCharacter; + const CNetObj_Character *m_pLocalPrevCharacter; + const CNetObj_PlayerInfo *m_pLocalInfo; + const CNetObj_SpectatorInfo *m_pSpectatorInfo; + const CNetObj_SpectatorInfo *m_pPrevSpectatorInfo; + const CNetObj_Flag *m_paFlags[2]; + const CNetObj_GameInfo *m_pGameInfoObj; + const CNetObj_GameData *m_pGameDataObj; + int m_GameDataSnapID; + + const CNetObj_PlayerInfo *m_paPlayerInfos[MAX_CLIENTS]; + const CNetObj_PlayerInfo *m_paInfoByScore[MAX_CLIENTS]; + const CNetObj_PlayerInfo *m_paInfoByName[MAX_CLIENTS]; + //const CNetObj_PlayerInfo *m_paInfoByTeam[MAX_CLIENTS]; + const CNetObj_PlayerInfo *m_paInfoByDDTeam[MAX_CLIENTS]; + + int m_LocalClientID; + int m_NumPlayers; + int m_aTeamSize[2]; + + // spectate data + struct CSpectateInfo + { + bool m_Active; + int m_SpectatorID; + 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; + char m_aSkinName[64]; + int m_SkinID; + int m_SkinColor; + int m_Team; + int m_Emoticon; + int m_EmoticonStart; + CCharacterCore m_Predicted; + CCharacterCore m_PrevPredicted; + + 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; + bool m_Foe; + + void UpdateRenderInfo(); + void Reset(); + + // DDRace + + int m_Score; + }; + + CClientData m_aClients[MAX_CLIENTS]; + + class CClientStats + { + public: + CClientStats(); + + int m_JoinDate; + bool m_Active; + bool m_WasActive; + + int m_aFragsWith[NUM_WEAPONS]; + int m_aDeathsFrom[NUM_WEAPONS]; + int m_Frags; + int m_Deaths; + int m_Suicides; + int m_BestSpree; + int m_CurrentSpree; + + int m_FlagGrabs; + int m_FlagCaptures; + + void Reset(); + }; + + CClientStats m_aStats[MAX_CLIENTS]; + + CRenderTools m_RenderTools; + + void OnReset(); + + // hooks + virtual void OnConnected(); + virtual void OnRender(); + virtual void OnDummyDisconnect(); + virtual void OnRelease(); + virtual void OnInit(); + virtual void OnConsoleInit(); + virtual void OnStateChange(int NewState, int OldState); + virtual void OnMessage(int MsgId, CUnpacker *pUnpacker, bool IsDummy = 0); + virtual void OnNewSnapshot(); + virtual void OnPredict(); + virtual void OnActivateEditor(); + virtual int OnSnapInput(int *pData); + virtual void OnShutdown(); + virtual void OnEnterGame(); + virtual void OnRconLine(const char *pLine); + virtual void OnGameOver(); + virtual void OnStartGame(); + virtual void OnFlagGrab(int TeamID); + + virtual void ResetDummyInput(); + virtual const char *GetItemName(int Type); + virtual const char *Version(); + virtual const char *NetVersion(); + + virtual const CNetObj_PlayerInput &getPlayerInput(int dummy); + + + // actions + // TODO: move these + void SendSwitchTeam(int Team); + void SendInfo(bool Start); + virtual void SendDummyInfo(bool Start); + void SendKill(int ClientID); + + // pointers to all systems + class CGameConsole *m_pGameConsole; + class CBinds *m_pBinds; + class CParticles *m_pParticles; + class CMenus *m_pMenus; + class CSkins *m_pSkins; + class CCountryFlags *m_pCountryFlags; + class CFlow *m_pFlow; + class CChat *m_pChat; + class CDamageInd *m_pDamageind; + class CCamera *m_pCamera; + class CControls *m_pControls; + class CEffects *m_pEffects; + class CSounds *m_pSounds; + class CMotd *m_pMotd; + class CMapImages *m_pMapimages; + class CVoting *m_pVoting; + class CScoreboard *m_pScoreboard; + class CStatboard *m_pStatboard; + class CItems *m_pItems; + class CMapLayers *m_pMapLayersBackGround; + class CMapLayers *m_pMapLayersForeGround; + class CBackground *m_pBackGround; + + class CMapSounds *m_pMapSounds; + + // DDRace + + class CRaceDemo *m_pRaceDemo; + class CGhost *m_pGhost; + class CTeamsCore m_Teams; + + int IntersectCharacter(vec2 Pos0, vec2 Pos1, vec2& NewPos, int ownID); + int IntersectCharacter(vec2 OldPos, vec2 NewPos, float Radius, vec2* NewPos2, int ownID, CWorldCore *World); + + CWeaponData m_aWeaponData[150]; + CWeaponData *GetWeaponData(int Tick) { return &m_aWeaponData[((Tick%150)+150)%150]; } + CWeaponData *FindWeaponData(int TargetTick); + + void FindWeaker(bool IsWeaker[2][MAX_CLIENTS]); + + bool AntiPingPlayers() { return g_Config.m_ClAntiPing && g_Config.m_ClAntiPingPlayers && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK; } + bool AntiPingGrenade() { return g_Config.m_ClAntiPing && g_Config.m_ClAntiPingGrenade && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK; } + bool AntiPingWeapons() { return g_Config.m_ClAntiPing && g_Config.m_ClAntiPingWeapons && !m_Snap.m_SpecInfo.m_Active && Client()->State() != IClient::STATE_DEMOPLAYBACK; } + +private: + bool m_DDRaceMsgSent[2]; + int m_ShowOthers[2]; +}; + + +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; +} + +inline vec3 HslToRgb(vec3 HSL) +{ + if(HSL.s == 0.0f) + return vec3(HSL.l, HSL.l, HSL.l); + else + { + float v2 = HSL.l < 0.5f ? HSL.l * (1.0f + HSL.s) : (HSL.l+HSL.s) - (HSL.s*HSL.l); + float v1 = 2.0f * HSL.l - v2; + + return vec3(HueToRgb(v1, v2, HSL.h + (1.0f/3.0f)), HueToRgb(v1, v2, HSL.h), HueToRgb(v1, v2, HSL.h - (1.0f/3.0f))); + } +} + +inline vec3 RgbToHsl(vec3 RGB) +{ + vec3 HSL; + float maxColor = MAX3(RGB.r, RGB.g, RGB.b); + float minColor = MIN3(RGB.r, RGB.g, RGB.b); + if (minColor == maxColor) + return vec3(0.0f, 0.0f, RGB.g * 255.0f); + else + { + HSL.l = (minColor + maxColor) / 2; + + if (HSL.l < 0.5) + HSL.s = (maxColor - minColor) / (maxColor + minColor); + else + HSL.s = (maxColor - minColor) / (2.0 - maxColor - minColor); + + if (RGB.r == maxColor) + HSL.h = (RGB.g - RGB.b) / (maxColor - minColor); + else if (RGB.g == maxColor) + HSL.h = 2.0 + (RGB.b - RGB.r) / (maxColor - minColor); + else + HSL.h = 4.0 + (RGB.r - RGB.g) / (maxColor - minColor); + + HSL.h /= 6; //to bring it to a number between 0 and 1 + if (HSL.h < 0) HSL.h++; + } + HSL.h = int(HSL.h * 255.0); + HSL.s = int(HSL.s * 255.0); + HSL.l = int(HSL.l * 255.0); + return HSL; + +} + + +extern const char *Localize(const char *Str); + + +#endif diff --git a/src/game/client/lineinput.cpp b/src/game/client/lineinput.cpp new file mode 100644 index 0000000..11fae57 --- /dev/null +++ b/src/game/client/lineinput.cpp @@ -0,0 +1,108 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/keys.h> +#include "lineinput.h" + +CLineInput::CLineInput() +{ + Clear(); +} + +void CLineInput::Clear() +{ + mem_zero(m_Str, sizeof(m_Str)); + m_Len = 0; + m_CursorPos = 0; + m_NumChars = 0; +} + +void CLineInput::Set(const char *pString) +{ + str_copy(m_Str, pString, sizeof(m_Str)); + m_Len = str_length(m_Str); + m_CursorPos = m_Len; + m_NumChars = 0; + int Offset = 0; + while(pString[Offset]) + { + Offset = str_utf8_forward(pString, Offset); + ++m_NumChars; + } +} + +bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int StrMaxChars, int *pStrLenPtr, int *pCursorPosPtr, int *pNumCharsPtr) +{ + int NumChars = *pNumCharsPtr; + 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 && NumChars < StrMaxChars) + { + mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len-CursorPos+1); // +1 == null term + for(int i = 0; i < CharSize; i++) + pStr[CursorPos+i] = Tmp[i]; + CursorPos += CharSize; + Len += CharSize; + if(CharSize > 0) + ++NumChars; + Changes = true; + } + } + + if(e.m_Flags&IInput::FLAG_PRESS) + { + if (k == KEY_BACKSPACE && CursorPos > 0) + { + int NewCursorPos = str_utf8_rewind(pStr, CursorPos); + int CharSize = CursorPos-NewCursorPos; + mem_move(pStr+NewCursorPos, pStr+CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term + CursorPos = NewCursorPos; + Len -= CharSize; + if(CharSize > 0) + --NumChars; + Changes = true; + } + else if (k == KEY_DELETE && CursorPos < Len) + { + int p = str_utf8_forward(pStr, CursorPos); + int CharSize = p-CursorPos; + mem_move(pStr + CursorPos, pStr + CursorPos + CharSize, Len - CursorPos - CharSize + 1); // +1 == null term + Len -= CharSize; + if(CharSize > 0) + --NumChars; + Changes = true; + } + else if (k == KEY_LEFT && CursorPos > 0) + CursorPos = str_utf8_rewind(pStr, CursorPos); + else if (k == KEY_RIGHT && CursorPos < Len) + CursorPos = str_utf8_forward(pStr, CursorPos); + else if (k == KEY_HOME) + CursorPos = 0; + else if (k == KEY_END) + CursorPos = Len; + } + + *pNumCharsPtr = NumChars; + *pCursorPosPtr = CursorPos; + *pStrLenPtr = Len; + + return Changes; +} + +void CLineInput::ProcessInput(IInput::CEvent e) +{ + Manipulate(e, m_Str, MAX_SIZE, MAX_CHARS, &m_Len, &m_CursorPos, &m_NumChars); +} diff --git a/src/game/client/lineinput.h b/src/game/client/lineinput.h new file mode 100644 index 0000000..d70805b --- /dev/null +++ b/src/game/client/lineinput.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_LINEINPUT_H +#define GAME_CLIENT_LINEINPUT_H + +#include <engine/input.h> + +// line input helter +class CLineInput +{ + enum + { + MAX_SIZE=512, + MAX_CHARS=MAX_SIZE/2, + }; + char m_Str[MAX_SIZE]; + int m_Len; + int m_CursorPos; + int m_NumChars; +public: + static bool Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int StrMaxChars, int *pStrLenPtr, int *pCursorPosPtr, int *pNumCharsPtr); + + class CCallback + { + public: + virtual ~CCallback() {} + virtual bool Event(IInput::CEvent e) = 0; + }; + + CLineInput(); + void Clear(); + void ProcessInput(IInput::CEvent e); + void Set(const char *pString); + const char *GetString() const { return m_Str; } + int GetLength() const { return m_Len; } + int GetCursorOffset() const { return m_CursorPos; } + void SetCursorOffset(int Offset) { m_CursorPos = Offset > m_Len ? m_Len : Offset < 0 ? 0 : Offset; } +}; + +#endif diff --git a/src/game/client/render.cpp b/src/game/client/render.cpp new file mode 100644 index 0000000..f1c8fc4 --- /dev/null +++ b/src/game/client/render.cpp @@ -0,0 +1,372 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <math.h> + +#include <base/math.h> + +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/map.h> +#include <game/generated/client_data.h> +#include <game/generated/protocol.h> +#include <game/layers.h> +#include "animstate.h" +#include "render.h" + +static float gs_SpriteWScale; +static float gs_SpriteHScale; + + +/* +static void layershot_begin() +{ + if(!config.cl_layershot) + return; + + Graphics()->Clear(0,0,0); +} + +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); + config.cl_layershot++; +}*/ + +void CRenderTools::SelectSprite(CDataSprite *pSpr, int Flags, int sx, int sy) +{ + int x = pSpr->m_X+sx; + int y = pSpr->m_Y+sy; + int w = pSpr->m_W; + int h = pSpr->m_H; + int cx = pSpr->m_pSet->m_Gridx; + int cy = pSpr->m_pSet->m_Gridy; + + 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; + float y2 = (y+h)/(float)cy; + float Temp = 0; + + if(Flags&SPRITE_FLAG_FLIP_Y) + { + Temp = y1; + y1 = y2; + y2 = Temp; + } + + if(Flags&SPRITE_FLAG_FLIP_X) + { + Temp = x1; + x1 = x2; + x2 = Temp; + } + + Graphics()->QuadsSetSubset(x1, y1, x2, y2); +} + +void CRenderTools::SelectSprite(int Id, int Flags, int sx, int sy) +{ + if(Id < 0 || Id >= g_pData->m_NumSprites) + return; + SelectSprite(&g_pData->m_aSprites[Id], Flags, sx, sy); +} + +void CRenderTools::DrawSprite(float x, float y, float Size) +{ + IGraphics::CQuadItem QuadItem(x, y, Size*gs_SpriteWScale, Size*gs_SpriteHScale); + Graphics()->QuadsDraw(&QuadItem, 1); +} + +void CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners) +{ + IGraphics::CFreeformItem ArrayF[32]; + int NumItems = 0; + int Num = 8; + for(int i = 0; i < Num; i+=2) + { + float a1 = i/(float)Num * pi/2; + float a2 = (i+1)/(float)Num * pi/2; + float a3 = (i+2)/(float)Num * pi/2; + float Ca1 = cosf(a1); + float Ca2 = cosf(a2); + float Ca3 = cosf(a3); + float Sa1 = sinf(a1); + float Sa2 = sinf(a2); + float Sa3 = sinf(a3); + + if(Corners&1) // TL + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x+r, y+r, + x+(1-Ca1)*r, y+(1-Sa1)*r, + x+(1-Ca3)*r, y+(1-Sa3)*r, + x+(1-Ca2)*r, y+(1-Sa2)*r); + + if(Corners&2) // TR + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x+w-r, y+r, + x+w-r+Ca1*r, y+(1-Sa1)*r, + x+w-r+Ca3*r, y+(1-Sa3)*r, + x+w-r+Ca2*r, y+(1-Sa2)*r); + + if(Corners&4) // BL + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x+r, y+h-r, + x+(1-Ca1)*r, y+h-r+Sa1*r, + x+(1-Ca3)*r, y+h-r+Sa3*r, + x+(1-Ca2)*r, y+h-r+Sa2*r); + + if(Corners&8) // BR + ArrayF[NumItems++] = IGraphics::CFreeformItem( + x+w-r, y+h-r, + x+w-r+Ca1*r, y+h-r+Sa1*r, + x+w-r+Ca3*r, y+h-r+Sa3*r, + x+w-r+Ca2*r, y+h-r+Sa2*r); + } + Graphics()->QuadsDrawFreeform(ArrayF, NumItems); + + IGraphics::CQuadItem ArrayQ[9]; + NumItems = 0; + ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center + ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top + 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 + if(!(Corners&8)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR + + Graphics()->QuadsDrawTL(ArrayQ, NumItems); +} + +void CRenderTools::DrawRoundRect(float x, float y, float w, float h, float r) +{ + DrawRoundRectExt(x,y,w,h,r,0xf); +} + +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); + DrawRoundRectExt(r->x,r->y,r->w,r->h,Rounding*UI()->Scale(), Corners); + Graphics()->QuadsEnd(); +} + +void CRenderTools::DrawCircle(float x, float y, float r, int Segments) +{ + IGraphics::CFreeformItem Array[32]; + int NumItems = 0; + float FSegments = (float)Segments; + for(int i = 0; i < Segments; i+=2) + { + float a1 = i/FSegments * 2*pi; + float a2 = (i+1)/FSegments * 2*pi; + float a3 = (i+2)/FSegments * 2*pi; + float Ca1 = cosf(a1); + float Ca2 = cosf(a2); + float Ca3 = cosf(a3); + float Sa1 = sinf(a1); + float Sa2 = sinf(a2); + float Sa3 = sinf(a3); + + Array[NumItems++] = IGraphics::CFreeformItem( + x, y, + x+Ca1*r, y+Sa1*r, + x+Ca3*r, y+Sa3*r, + x+Ca2*r, y+Sa2*r); + if(NumItems == 32) + { + Graphics()->QuadsDrawFreeform(Array, 32); + NumItems = 0; + } + } + if(NumItems) + Graphics()->QuadsDrawFreeform(Array, NumItems); +} + +void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos, bool Alpha) +{ + vec2 Direction = Dir; + vec2 Position = Pos; + + //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); + + // first pass we draw the outline + // second pass we draw the filling + for(int p = 0; p < 2; p++) + { + int OutLine = p==0 ? 1 : 0; + + for(int f = 0; f < 2; f++) + { + float AnimScale = pInfo->m_Size * 1.0f/64.0f; + float BaseSize = pInfo->m_Size; + if(f == 1) + { + Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); + + // draw body + if(Alpha) + Graphics()->SetColor(pInfo->m_ColorBody.r, pInfo->m_ColorBody.g, pInfo->m_ColorBody.b, pInfo->m_ColorBody.a); + else + Graphics()->SetColor(pInfo->m_ColorBody.r, pInfo->m_ColorBody.g, pInfo->m_ColorBody.b, 1.0f); + + vec2 BodyPos = Position + vec2(pAnim->GetBody()->m_X, pAnim->GetBody()->m_Y)*AnimScale; + SelectSprite(OutLine?SPRITE_TEE_BODY_OUTLINE:SPRITE_TEE_BODY, 0, 0, 0); + IGraphics::CQuadItem QuadItem(BodyPos.x, BodyPos.y, BaseSize, BaseSize); + Graphics()->QuadsDraw(&QuadItem, 1); + + // draw eyes + if(p == 1) + { + switch (Emote) + { + case EMOTE_PAIN: + SelectSprite(SPRITE_TEE_EYE_PAIN, 0, 0, 0); + break; + case EMOTE_HAPPY: + SelectSprite(SPRITE_TEE_EYE_HAPPY, 0, 0, 0); + break; + case EMOTE_SURPRISE: + SelectSprite(SPRITE_TEE_EYE_SURPRISE, 0, 0, 0); + break; + case EMOTE_ANGRY: + SelectSprite(SPRITE_TEE_EYE_ANGRY, 0, 0, 0); + break; + default: + 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; + vec2 Offset = vec2(Direction.x*0.125f, -0.05f+Direction.y*0.10f)*BaseSize; + IGraphics::CQuadItem Array[2] = { + IGraphics::CQuadItem(BodyPos.x-EyeSeparation+Offset.x, BodyPos.y+Offset.y, EyeScale, h), + IGraphics::CQuadItem(BodyPos.x+EyeSeparation+Offset.x, BodyPos.y+Offset.y, -EyeScale, h)}; + Graphics()->QuadsDraw(Array, 2); + } + } + + // draw feet + CAnimKeyframe *pFoot = f ? pAnim->GetFrontFoot() : pAnim->GetBackFoot(); + + float w = BaseSize; + 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 + { + SelectSprite(SPRITE_TEE_FOOT, 0, 0, 0); + if(Indicate) + cs = 0.5f; + } + + + if(Alpha) + Graphics()->SetColor(pInfo->m_ColorFeet.r*cs, pInfo->m_ColorFeet.g*cs, pInfo->m_ColorFeet.b*cs, pInfo->m_ColorFeet.a*cs); + else + Graphics()->SetColor(pInfo->m_ColorFeet.r*cs, pInfo->m_ColorFeet.g*cs, pInfo->m_ColorFeet.b*cs, 1.0f); + IGraphics::CQuadItem QuadItem(Position.x+pFoot->m_X*AnimScale, Position.y+pFoot->m_Y*AnimScale, w, h); + Graphics()->QuadsDraw(&QuadItem, 1); + } + } + + Graphics()->QuadsEnd(); + + +} + +static void CalcScreenParams(float Amount, float WMax, float HMax, float Aspect, float *w, float *h) +{ + 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; + *w = *h*Aspect; + } +} + +void CRenderTools::MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY, + float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints) +{ + float Width, Height; + CalcScreenParams(1150*1000, 1500, 1050, Aspect, &Width, &Height); + CenterX *= ParallaxX; + CenterY *= ParallaxY; + Width *= Zoom; + Height *= Zoom; + pPoints[0] = OffsetX+CenterX-Width/2; + pPoints[1] = OffsetY+CenterY-Height/2; + pPoints[2] = pPoints[0]+Width; + pPoints[3] = pPoints[1]+Height; +} + +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); + + if(pLayer->m_Type == LAYERTYPE_TILES) + { + CMapItemLayerTilemap *pTmap = (CMapItemLayerTilemap *)pLayer; + CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTmap->m_Data); + for(int y = 0; y < pTmap->m_Height; y++) + { + for(int x = 1; x < pTmap->m_Width;) + { + int sx; + for(sx = 1; x+sx < pTmap->m_Width && sx < 255; sx++) + { + if(pTiles[y*pTmap->m_Width+x+sx].m_Index) + break; + } + + pTiles[y*pTmap->m_Width+x].m_Skip = sx-1; + x += sx; + } + } + } + } + } +} diff --git a/src/game/client/render.h b/src/game/client/render.h new file mode 100644 index 0000000..8be2e6c --- /dev/null +++ b/src/game/client/render.h @@ -0,0 +1,96 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_RENDER_H +#define GAME_CLIENT_RENDER_H + +#include <base/vmath.h> +#include <game/mapitems.h> +#include "ui.h" + + +class CTeeRenderInfo +{ +public: + CTeeRenderInfo() + { + m_Texture = -1; + m_ColorBody = vec4(1,1,1,1); + m_ColorFeet = vec4(1,1,1,1); + m_Size = 1.0f; + m_GotAirJump = 1; + }; + + int m_Texture; + vec4 m_ColorBody; + vec4 m_ColorFeet; + float m_Size; + int m_GotAirJump; +}; + +// sprite renderings +enum +{ + SPRITE_FLAG_FLIP_Y=1, + SPRITE_FLAG_FLIP_X=2, + + LAYERRENDERFLAG_OPAQUE=1, + LAYERRENDERFLAG_TRANSPARENT=2, + + TILERENDERFLAG_EXTEND=4, +}; + +typedef void (*ENVELOPE_EVAL)(float TimeOffset, int Env, float *pChannels, void *pUser); + +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; } + + //typedef struct SPRITE; + + void SelectSprite(struct CDataSprite *pSprite, int Flags=0, int sx=0, int sy=0); + void SelectSprite(int id, int Flags=0, int sx=0, int sy=0); + + void DrawSprite(float x, float y, float size); + + // 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); + + void DrawCircle(float x, float y, float r, int Segments); + + // larger rendering methods + void RenderTilemapGenerateSkip(class CLayers *pLayers); + + // object render methods (gc_render_obj.cpp) + void RenderTee(class CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos, bool Alpha = false); + + // map render methods (gc_render_map.cpp) + static void RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult); + void RenderQuads(CQuad *pQuads, int NumQuads, int Flags, ENVELOPE_EVAL pfnEval, void *pUser); + void ForceRenderQuads(CQuad *pQuads, int NumQuads, int Flags, ENVELOPE_EVAL pfnEval, void *pUser, float Alpha = 1.0f); + void RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset); + + // helpers + void MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY, + float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints); + + // DDRace + + void RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale, float Alpha=1.0f); + void RenderSpeedupOverlay(CSpeedupTile *pTele, int w, int h, float Scale, float Alpha=1.0f); + void RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float Scale, float Alpha=1.0f); + void RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale, float Alpha=1.0f); + void RenderTelemap(CTeleTile *pTele, int w, int h, float Scale, vec4 Color, int RenderFlags); + void RenderSpeedupmap(CSpeedupTile *pTele, int w, int h, float Scale, vec4 Color, int RenderFlags); + void RenderSwitchmap(CSwitchTile *pSwitch, int w, int h, float Scale, vec4 Color, int RenderFlags); + void RenderTunemap(CTuneTile *pTune, int w, int h, float Scale, vec4 Color, int RenderFlags); +}; + +#endif diff --git a/src/game/client/render_map.cpp b/src/game/client/render_map.cpp new file mode 100644 index 0000000..0ba0d8a --- /dev/null +++ b/src/game/client/render_map.cpp @@ -0,0 +1,954 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <math.h> +#include <base/math.h> +#include <engine/graphics.h> + +#include "render.h" + +#include <engine/textrender.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/generated/client_data.h> + +void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult) +{ + if(NumPoints == 0) + { + pResult[0] = 0; + pResult[1] = 0; + pResult[2] = 0; + pResult[3] = 0; + return; + } + + if(NumPoints == 1) + { + pResult[0] = fx2f(pPoints[0].m_aValues[0]); + pResult[1] = fx2f(pPoints[0].m_aValues[1]); + pResult[2] = fx2f(pPoints[0].m_aValues[2]); + 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++) + { + if(Time >= pPoints[i].m_Time && Time <= pPoints[i+1].m_Time) + { + float Delta = pPoints[i+1].m_Time-pPoints[i].m_Time; + float a = (Time-pPoints[i].m_Time)/Delta; + + + if(pPoints[i].m_Curvetype == CURVETYPE_SMOOTH) + a = -2*a*a*a + 3*a*a; // second hermite basis + else if(pPoints[i].m_Curvetype == CURVETYPE_SLOW) + a = a*a*a; + else if(pPoints[i].m_Curvetype == CURVETYPE_FAST) + { + a = 1-a; + a = 1-a*a*a; + } + else if (pPoints[i].m_Curvetype == CURVETYPE_STEP) + a = 0; + else + { + // 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]); + pResult[3] = fx2f(pPoints[NumPoints-1].m_aValues[3]); + return; +} + + +static void Rotate(CPoint *pCenter, CPoint *pPoint, float Rotation) +{ + int x = pPoint->x - pCenter->x; + int y = pPoint->y - pCenter->y; + pPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x); + pPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y); +} + +void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser) +{ + if(!g_Config.m_ClShowQuads || g_Config.m_ClOverlayEntities == 100) + return; + + ForceRenderQuads(pQuads, NumQuads, RenderFlags, pfnEval, pUser, (100-g_Config.m_ClOverlayEntities)/100.0f); +} + +void CRenderTools::ForceRenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, float Alpha) +{ + Graphics()->QuadsBegin(); + float Conv = 1/255.0f; + 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) + { + float aChannels[4]; + pfnEval(q->m_ColorEnvOffset/1000.0f, q->m_ColorEnv, aChannels, pUser); + r = aChannels[0]; + g = aChannels[1]; + b = aChannels[2]; + a = aChannels[3]; + } + + bool Opaque = false; + /* TODO: Analyze quadtexture + 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), + fx2f(q->m_aTexcoords[2].x), fx2f(q->m_aTexcoords[2].y), + fx2f(q->m_aTexcoords[3].x), fx2f(q->m_aTexcoords[3].y) + ); + + float OffsetX = 0; + float OffsetY = 0; + float Rot = 0; + + // TODO: fix this + if(q->m_PosEnv >= 0) + { + float aChannels[4]; + pfnEval(q->m_PosEnvOffset/1000.0f, q->m_PosEnv, aChannels, pUser); + OffsetX = aChannels[0]; + 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*Alpha), + 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*Alpha), + IGraphics::CColorVertex(2, q->m_aColors[2].r*Conv*r, q->m_aColors[2].g*Conv*g, q->m_aColors[2].b*Conv*b, q->m_aColors[2].a*Conv*a*Alpha), + IGraphics::CColorVertex(3, q->m_aColors[3].r*Conv*r, q->m_aColors[3].g*Conv*g, q->m_aColors[3].b*Conv*b, q->m_aColors[3].a*Conv*a*Alpha)}; + Graphics()->SetColorVertex(Array, 4); + + CPoint *pPoints = q->m_aPoints; + + if(Rot != 0) + { + static CPoint aRotated[4]; + aRotated[0] = q->m_aPoints[0]; + aRotated[1] = q->m_aPoints[1]; + 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, + fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, + fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); + Graphics()->QuadsDrawFreeform(&Freeform, 1); + } + Graphics()->QuadsEnd(); +} + +void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags, + ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset) +{ + //Graphics()->TextureSet(img_get(tmap->image)); + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + 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 + float TilePixelSize = 1024/32.0f; + float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); + float FinalTilesetScale = FinalTileSize/TilePixelSize; + + float r=1, g=1, b=1, a=1; + if(ColorEnv >= 0) + { + float aChannels[4]; + pfnEval(ColorEnvOffset/1000.0f, ColorEnv, aChannels, pUser); + r = aChannels[0]; + g = aChannels[1]; + b = aChannels[2]; + a = aChannels[3]; + } + + Graphics()->QuadsBegin(); + Graphics()->SetColor(Color.r*r, Color.g*g, Color.b*b, Color.a*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); + float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(RenderFlags&TILERENDERFLAG_EXTEND) + { + if(mx<0) + mx = 0; + if(mx>=w) + mx = w-1; + if(my<0) + my = 0; + if(my>=h) + my = h-1; + } + else + { + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + 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 && Color.a*a > 254.0f/255.0f) + { + if(RenderFlags&LAYERRENDERFLAG_OPAQUE) + Render = true; + } + else + { + 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; + float y1 = Nudge + Py0/TexSize+Frac; + float x2 = Nudge + Px1/TexSize-Frac; + float y2 = Nudge + Py1/TexSize-Frac; + float x3 = Nudge + Px0/TexSize+Frac; + float y3 = Nudge + Py1/TexSize-Frac; + + if(Flags&TILEFLAG_VFLIP) + { + x0 = x2; + x1 = x3; + x2 = x3; + x3 = x0; + } + + if(Flags&TILEFLAG_HFLIP) + { + y0 = y3; + y2 = y1; + y3 = y1; + y1 = y0; + } + + if(Flags&TILEFLAG_ROTATE) + { + float Tmp = x0; + x0 = x3; + x3 = x2; + x2 = x1; + x1 = Tmp; + Tmp = y0; + y0 = y3; + y3 = y2; + y2 = y1; + y1 = Tmp; + } + + Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); + IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + x += pTiles[c].m_Skip; + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderTeleOverlay(CTeleTile *pTele, int w, int h, float Scale, float Alpha) +{ + if(!g_Config.m_ClTextEntities) + return; + + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + int StartY = (int)(ScreenY0/Scale)-1; + int StartX = (int)(ScreenX0/Scale)-1; + int EndY = (int)(ScreenY1/Scale)+1; + int EndX = (int)(ScreenX1/Scale)+1; + + if(EndX - StartX > g_Config.m_GfxScreenWidth / g_Config.m_GfxTextOverlay || EndY - StartY > g_Config.m_GfxScreenHeight / g_Config.m_GfxTextOverlay) + return; // its useless to render text at this distance + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + + int c = mx + my*w; + + unsigned char Index = pTele[c].m_Number; + if(Index && pTele[c].m_Type != TILE_TELECHECKIN && pTele[c].m_Type != TILE_TELECHECKINEVIL) + { + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Index); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale-2, my*Scale-4, Scale-5, aBuf, -1); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + } + + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderSpeedupOverlay(CSpeedupTile *pSpeedup, int w, int h, float Scale, float Alpha) +{ + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + int StartY = (int)(ScreenY0/Scale)-1; + int StartX = (int)(ScreenX0/Scale)-1; + int EndY = (int)(ScreenY1/Scale)+1; + int EndX = (int)(ScreenX1/Scale)+1; + + if(EndX - StartX > g_Config.m_GfxScreenWidth / g_Config.m_GfxTextOverlay || EndY - StartY > g_Config.m_GfxScreenHeight / g_Config.m_GfxTextOverlay) + return; // its useless to render text at this distance + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + + int c = mx + my*w; + + int Force = (int)pSpeedup[c].m_Force; + int MaxSpeed = (int)pSpeedup[c].m_MaxSpeed; + if(Force) + { + // draw arrow + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_SPEEDUP_ARROW].m_Id); + Graphics()->QuadsBegin(); + Graphics()->SetColor(255.0f, 255.0f, 255.0f, Alpha); + + SelectSprite(SPRITE_SPEEDUP_ARROW); + Graphics()->QuadsSetRotation(pSpeedup[c].m_Angle*(3.14159265f/180.0f)); + DrawSprite(mx*Scale+16, my*Scale+16, 35.0f); + + Graphics()->QuadsEnd(); + + if(g_Config.m_ClTextEntities) + { + // draw force + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Force); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale, my*Scale+16, Scale-20, aBuf, -1); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + if(MaxSpeed) + { + str_format(aBuf, sizeof(aBuf), "%d", MaxSpeed); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale, my*Scale-2, Scale-20, aBuf, -1); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + } + } + } + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderSwitchOverlay(CSwitchTile *pSwitch, int w, int h, float Scale, float Alpha) +{ + if(!g_Config.m_ClTextEntities) + return; + + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + int StartY = (int)(ScreenY0/Scale)-1; + int StartX = (int)(ScreenX0/Scale)-1; + int EndY = (int)(ScreenY1/Scale)+1; + int EndX = (int)(ScreenX1/Scale)+1; + + if(EndX - StartX > g_Config.m_GfxScreenWidth / g_Config.m_GfxTextOverlay || EndY - StartY > g_Config.m_GfxScreenHeight / g_Config.m_GfxTextOverlay) + return; // its useless to render text at this distance + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + + int c = mx + my*w; + + unsigned char Index = pSwitch[c].m_Number; + if(Index) + { + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Index); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale, my*Scale+16, Scale-20, aBuf, -1); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + + unsigned char Delay = pSwitch[c].m_Delay; + if(Delay) + { + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Delay); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale, my*Scale-2, Scale-20, aBuf, -1); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + } + + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderTuneOverlay(CTuneTile *pTune, int w, int h, float Scale, float Alpha) +{ + if(!g_Config.m_ClTextEntities) + return; + + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + int StartY = (int)(ScreenY0/Scale)-1; + int StartX = (int)(ScreenX0/Scale)-1; + int EndY = (int)(ScreenY1/Scale)+1; + int EndX = (int)(ScreenX1/Scale)+1; + + if(EndX - StartX > g_Config.m_GfxScreenWidth / g_Config.m_GfxTextOverlay || EndY - StartY > g_Config.m_GfxScreenHeight / g_Config.m_GfxTextOverlay) + return; // its useless to render text at this distance + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + + int c = mx + my*w; + + unsigned char Index = pTune[c].m_Number; + if(Index) + { + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d", Index); + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, Alpha); + UI()->TextRender()->Text(0, mx*Scale+11.f, my*Scale+6.f, Scale/1.5f-5.f, aBuf, -1); // numbers shouldnt be too big and in the center of the tile + UI()->TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); + } + } + + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderTelemap(CTeleTile *pTele, int w, int h, float Scale, vec4 Color, int RenderFlags) +{ + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + // 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); + float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(RenderFlags&TILERENDERFLAG_EXTEND) + { + if(mx<0) + mx = 0; + if(mx>=w) + mx = w-1; + if(my<0) + my = 0; + if(my>=h) + my = h-1; + } + else + { + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + } + + int c = mx + my*w; + + unsigned char Index = pTele[c].m_Type; + if(Index) + { + bool Render = false; + 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; + float y1 = Nudge + Py0/TexSize+Frac; + float x2 = Nudge + Px1/TexSize-Frac; + float y2 = Nudge + Py1/TexSize-Frac; + float x3 = Nudge + Px0/TexSize+Frac; + float y3 = Nudge + Py1/TexSize-Frac; + + Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); + IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderSpeedupmap(CSpeedupTile *pSpeedupTile, int w, int h, float Scale, vec4 Color, int RenderFlags) +{ + //Graphics()->TextureSet(img_get(tmap->image)); + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + 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 + 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); + float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(RenderFlags&TILERENDERFLAG_EXTEND) + { + if(mx<0) + mx = 0; + if(mx>=w) + mx = w-1; + if(my<0) + my = 0; + if(my>=h) + my = h-1; + } + else + { + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + } + + int c = mx + my*w; + + unsigned char Index = pSpeedupTile[c].m_Type; + if(Index) + { + bool Render = false; + 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; + float y1 = Nudge + Py0/TexSize+Frac; + float x2 = Nudge + Px1/TexSize-Frac; + float y2 = Nudge + Py1/TexSize-Frac; + float x3 = Nudge + Px0/TexSize+Frac; + float y3 = Nudge + Py1/TexSize-Frac; + + Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); + IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderSwitchmap(CSwitchTile *pSwitchTile, int w, int h, float Scale, vec4 Color, int RenderFlags) +{ + //Graphics()->TextureSet(img_get(tmap->image)); + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + 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 + 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); + float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(RenderFlags&TILERENDERFLAG_EXTEND) + { + if(mx<0) + mx = 0; + if(mx>=w) + mx = w-1; + if(my<0) + my = 0; + if(my>=h) + my = h-1; + } + else + { + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + } + + int c = mx + my*w; + + unsigned char Index = pSwitchTile[c].m_Type; + if(Index) + { + if(Index == TILE_SWITCHTIMEDOPEN) + Index = 8; + + unsigned char Flags = pSwitchTile[c].m_Flags; + + bool Render = false; + if(Flags&TILEFLAG_OPAQUE) + { + if(RenderFlags&LAYERRENDERFLAG_OPAQUE) + Render = true; + } + else + { + 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; + float y1 = Nudge + Py0/TexSize+Frac; + float x2 = Nudge + Px1/TexSize-Frac; + float y2 = Nudge + Py1/TexSize-Frac; + float x3 = Nudge + Px0/TexSize+Frac; + float y3 = Nudge + Py1/TexSize-Frac; + + if(Flags&TILEFLAG_VFLIP) + { + x0 = x2; + x1 = x3; + x2 = x3; + x3 = x0; + } + + if(Flags&TILEFLAG_HFLIP) + { + y0 = y3; + y2 = y1; + y3 = y1; + y1 = y0; + } + + if(Flags&TILEFLAG_ROTATE) + { + float Tmp = x0; + x0 = x3; + x3 = x2; + x2 = x1; + x1 = Tmp; + Tmp = y0; + y0 = y3; + y3 = y2; + y2 = y1; + y1 = Tmp; + } + + Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); + IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +void CRenderTools::RenderTunemap(CTuneTile *pTune, int w, int h, float Scale, vec4 Color, int RenderFlags) +{ + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + + // 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); + float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); + + for(int y = StartY; y < EndY; y++) + for(int x = StartX; x < EndX; x++) + { + int mx = x; + int my = y; + + if(RenderFlags&TILERENDERFLAG_EXTEND) + { + if(mx<0) + mx = 0; + if(mx>=w) + mx = w-1; + if(my<0) + my = 0; + if(my>=h) + my = h-1; + } + else + { + if(mx<0) + continue; // mx = 0; + if(mx>=w) + continue; // mx = w-1; + if(my<0) + continue; // my = 0; + if(my>=h) + continue; // my = h-1; + } + + int c = mx + my*w; + + unsigned char Index = pTune[c].m_Type; + if(Index) + { + bool Render = false; + 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; + float y1 = Nudge + Py0/TexSize+Frac; + float x2 = Nudge + Px1/TexSize-Frac; + float y2 = Nudge + Py1/TexSize-Frac; + float x3 = Nudge + Px0/TexSize+Frac; + float y3 = Nudge + Py1/TexSize-Frac; + + Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); + IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} diff --git a/src/game/client/ui.cpp b/src/game/client/ui.cpp new file mode 100644 index 0000000..db9959f --- /dev/null +++ b/src/game/client/ui.cpp @@ -0,0 +1,531 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <base/math.h> + +#include <engine/shared/config.h> +#include <engine/graphics.h> +#include <engine/textrender.h> +#include "ui.h" + +#if defined(__ANDROID__) +#include <SDL_screenkeyboard.h> +#endif + +/******************************************************** + UI +*********************************************************/ + +CUI::CUI() +{ + m_pHotItem = 0; + 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_Screen.x = 0; + m_Screen.y = 0; + m_Screen.w = 848.0f; + m_Screen.h = 480.0f; +} + +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; +} + +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; +} + +void CUI::ConvertMouseMove(float *x, float *y) +{ +#if defined(__ANDROID__) + //*x = *x * 500 / g_Config.m_GfxScreenWidth; + //*y = *y * 500 / g_Config.m_GfxScreenHeight; +#else + float Fac = (float)(g_Config.m_UiMousesens)/g_Config.m_InpMousesens; + *x = *x*Fac; + *y = *y*Fac; +#endif +} + +void CUI::AndroidShowScreenKeys(bool shown) +{ +#if defined(__ANDROID__) + static bool ScreenKeyboardInitialized = false; + static bool ScreenKeyboardShown = true; + static SDL_Rect Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_NUM]; + static SDL_Rect ButtonHidden = { 0, 0, 0, 0 }; + if( !ScreenKeyboardInitialized ) + { + //dbg_msg("dbg", "CUI::AndroidShowScreenKeys: ScreenKeyboardInitialized"); + ScreenKeyboardInitialized = true; + + for( int i = 0; i < SDL_ANDROID_SCREENKEYBOARD_BUTTON_NUM; i++ ) + SDL_ANDROID_GetScreenKeyboardButtonPos( i, &Buttons[i] ); + + if( !SDL_ANDROID_GetScreenKeyboardRedefinedByUser() ) + { + int ScreenW = Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].x + + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].w; + int ScreenH = Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].y + + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].h; + // Hide Hook button(it was above Weapnext) + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].x = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].x; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].h; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].w = 0; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].h = 0; + // Hide Weapprev button + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_2].x = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_0].x; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_2].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_2].h; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_2].w = 0; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_2].h = 0; + // Scores button above left joystick + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].x = 0; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].h * 2.0f; + // Text input button above scores + //Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_TEXT].w = + // Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].w; + //Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_TEXT].h = + // Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].h; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_TEXT].x = 0; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_TEXT].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_3].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_TEXT].h; + // Spec next button + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].x = + ScreenW - Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_4].w; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].h; + // Spec prev button + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_4].x = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].x - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_4].w; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_4].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].y; + // Weap next button + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].x = + ScreenW - Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].w; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].y = + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_5].y - + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_1].h; + // Bigger joysticks + /* + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD].w *= 1.25; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD].h *= 1.25; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD].y = + ScreenH - Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD].h; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].w *= 1.25; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].h *= 1.25; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].x = + ScreenW - Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].w; + Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].y = + ScreenH - Buttons[SDL_ANDROID_SCREENKEYBOARD_BUTTON_DPAD2].h; + */ + } + } + + if( ScreenKeyboardShown == shown ) + return; + ScreenKeyboardShown = shown; + //dbg_msg("dbg", "CUI::AndroidShowScreenKeys: shown %d", shown); + for( int i = 0; i < SDL_ANDROID_SCREENKEYBOARD_BUTTON_NUM; i++ ) + SDL_ANDROID_SetScreenKeyboardButtonPos( i, shown ? &Buttons[i] : &ButtonHidden ); +#endif +} + +void CUI::AndroidShowTextInput(const char *text, const char *hintText) +{ +#if defined(__ANDROID__) + SDL_ANDROID_SetScreenKeyboardHintMesage(hintText); + SDL_ANDROID_ToggleScreenKeyboardTextInput(text); +#endif +} + +void CUI::AndroidBlockAndGetTextInput(char *text, int textLength, const char *hintText) +{ +#if defined(__ANDROID__) + SDL_ANDROID_SetScreenKeyboardHintMesage(hintText); + SDL_ANDROID_GetScreenKeyboardTextInput(text, textLength); +#endif +} + +bool CUI::AndroidTextInputShown() +{ +#if defined(__ANDROID__) + return SDL_IsScreenKeyboardShown(NULL); +#else + return false; +#endif +} + +CUIRect *CUI::Screen() +{ + float Aspect = Graphics()->ScreenAspect(); + float w, h; + + h = 600; + w = Aspect*h; + + m_Screen.w = w; + m_Screen.h = h; + + return &m_Screen; +} + +float CUI::PixelSize() +{ + return Screen()->w/Graphics()->ScreenWidth(); +} + +void CUI::SetScale(float s) +{ + g_Config.m_UiScale = (int)(s*100.0f); +} + +float CUI::Scale() +{ + return g_Config.m_UiScale/100.0f; +} + +float CUIRect::Scale() const +{ + return g_Config.m_UiScale/100.0f; +} + +void CUI::ClipEnable(const CUIRect *r) +{ + float XScale = Graphics()->ScreenWidth()/Screen()->w; + float YScale = Graphics()->ScreenHeight()/Screen()->h; + Graphics()->ClipEnable((int)(r->x*XScale), (int)(r->y*YScale), (int)(r->w*XScale), (int)(r->h*YScale)); +} + +void CUI::ClipDisable() +{ + Graphics()->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; + } +} + +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; + } +} + +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; + } +} + + +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; + } +} + +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; + } +} + +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; + } +} + +void CUIRect::Margin(float Cut, CUIRect *pOtherRect) const +{ + 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; +} + +void CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const +{ + CUIRect r = *this; + Cut *= Scale(); + + 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; + Cut *= Scale(); + + 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); + static int ButtonUsed = 0; + + if(ActiveItem() == pID) + { + if(!MouseButton(ButtonUsed)) + { + if(Inside && Checked >= 0) + ReturnValue = 1+ButtonUsed; + SetActiveItem(0); + } + } + else if(HotItem() == pID) + { + if(MouseButton(0)) + { + SetActiveItem(pID); + ButtonUsed = 0; + } + + if(MouseButton(1)) + { + SetActiveItem(pID); + ButtonUsed = 1; + } + } + + if(Inside) + SetHotItem(pID); + + return ReturnValue; +} + +int CUI::DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY) +{ + int Inside = MouseInside(pRect); + + if(ActiveItem() == pID) + { + if(!MouseButton(0)) + SetActiveItem(0); + } + else if(HotItem() == pID) + { + if(MouseButton(0)) + SetActiveItem(pID); + } + else if(Inside) + SetHotItem(pID); + + if(!Inside || !MouseButton(0)) + return 0; + + if(pX) + *pX = clamp(m_MouseX - pRect->x, 0.0f, pRect->w) / Scale(); + if(pY) + *pY = clamp(m_MouseY - pRect->y, 0.0f, pRect->h) / Scale(); + + return 1; +} + +/* +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); + static int button_used = 0; + + if(ui_ActiveItem() == id) + { + if(!ui_MouseButton(button_used)) + { + if(inside && checked >= 0) + ret = 1+button_used; + ui_SetActiveItem(0); + } + } + else if(ui_HotItem() == id) + { + if(ui_MouseButton(0)) + { + 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; +}*/ + +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); + } + else if(Align < 0) + 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); + } +} + +void CUI::DoLabelScaled(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) +{ + DoLabel(r, pText, Size*Scale(), Align, MaxWidth); +} diff --git a/src/game/client/ui.h b/src/game/client/ui.h new file mode 100644 index 0000000..8720a35 --- /dev/null +++ b/src/game/client/ui.h @@ -0,0 +1,107 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_CLIENT_UI_H +#define GAME_CLIENT_UI_H + +class CUIRect +{ + // TODO: Refactor: Redo UI scaling + float Scale() const; +public: + 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; + void VSplitMid(CUIRect *pLeft, CUIRect *pRight) const; + void VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const; + void VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const; + + void Margin(float Cut, CUIRect *pOtherRect) const; + void VMargin(float Cut, CUIRect *pOtherRect) const; + void HMargin(float Cut, CUIRect *pOtherRect) const; + +}; + +class CUI +{ + const void *m_pHotItem; + const void *m_pActiveItem; + const void *m_pLastActiveItem; + const void *m_pBecommingHotItem; + float m_MouseX, m_MouseY; // in gui space + 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;} + class IGraphics *Graphics() { return m_pGraphics; } + class ITextRender *TextRender() { return m_pTextRender; } + + CUI(); + + enum + { + CORNER_TL=1, + 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 + }; + + int Update(float mx, float my, float Mwx, float Mwy, int m_Buttons); + + float MouseX() const { return m_MouseX; } + float MouseY() const { return m_MouseY; } + float MouseWorldX() const { return m_MouseWorldX; } + float MouseWorldY() const { return m_MouseWorldY; } + int MouseButton(int Index) const { return (m_MouseButtons>>Index)&1; } + int MouseButtonClicked(int Index) { return MouseButton(Index) && !((m_LastMouseButtons>>Index)&1) ; } + + void SetHotItem(const void *pID) { m_pBecommingHotItem = pID; } + void SetActiveItem(const void *pID) { m_pActiveItem = pID; if (pID) m_pLastActiveItem = pID; } + void ClearLastActiveItem() { m_pLastActiveItem = 0; } + const void *HotItem() const { return m_pHotItem; } + const void *NextHotItem() const { return m_pBecommingHotItem; } + const void *ActiveItem() const { return m_pActiveItem; } + const void *LastActiveItem() const { return m_pLastActiveItem; } + + int MouseInside(const CUIRect *pRect); + void ConvertMouseMove(float *x, float *y); + + CUIRect *Screen(); + float PixelSize(); + 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); + int DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY); + + // 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); + + void AndroidShowScreenKeys(bool shown); + void AndroidShowTextInput(const char *text, const char *hintText); + void AndroidBlockAndGetTextInput(char *text, int textLength, const char *hintText); + bool AndroidTextInputShown(); +}; + + +#endif diff --git a/src/game/collision.cpp b/src/game/collision.cpp new file mode 100644 index 0000000..b2bbf5e --- /dev/null +++ b/src/game/collision.cpp @@ -0,0 +1,1314 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/system.h> +#include <base/math.h> +#include <base/vmath.h> + +#include <math.h> +#include <engine/map.h> +#include <engine/kernel.h> + +#include <game/mapitems.h> +#include <game/layers.h> +#include <game/collision.h> + +#include <game/gamecore.h> +#include <game/animation.h> + +#include <engine/shared/config.h> + +CCollision::CCollision() +{ + m_pTiles = 0; + m_Width = 0; + m_Height = 0; + m_pLayers = 0; + + m_pTele = 0; + m_pSpeedup = 0; + m_pFront = 0; + m_pSwitch = 0; + m_pDoor = 0; + m_pSwitchers = 0; + m_pTune = 0; + + m_Time = 0.0; +} + +void CCollision::Init(class CLayers *pLayers) +{ + if(m_pLayers) m_pLayers->Dest(); + Dest(); + m_NumSwitchers = 0; + m_pLayers = 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)); + + if(m_pLayers->TeleLayer()) + { + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(m_pLayers->TeleLayer()->m_Tele); + if (Size >= m_Width*m_Height*sizeof(CTeleTile)) + m_pTele = static_cast<CTeleTile *>(m_pLayers->Map()->GetData(m_pLayers->TeleLayer()->m_Tele)); + } + + if(m_pLayers->SpeedupLayer()) + { + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(m_pLayers->SpeedupLayer()->m_Speedup); + if (Size >= m_Width*m_Height*sizeof(CSpeedupTile)) + m_pSpeedup = static_cast<CSpeedupTile *>(m_pLayers->Map()->GetData(m_pLayers->SpeedupLayer()->m_Speedup)); + } + + if(m_pLayers->SwitchLayer()) + { + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(m_pLayers->SwitchLayer()->m_Switch); + if (Size >= m_Width*m_Height*sizeof(CSwitchTile)) + m_pSwitch = static_cast<CSwitchTile *>(m_pLayers->Map()->GetData(m_pLayers->SwitchLayer()->m_Switch)); + + m_pDoor = new CDoorTile[m_Width*m_Height]; + mem_zero(m_pDoor, m_Width * m_Height * sizeof(CDoorTile)); + } + else + { + m_pDoor = 0; + m_pSwitchers = 0; + } + + if(m_pLayers->TuneLayer()) + { + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(m_pLayers->TuneLayer()->m_Tune); + if (Size >= m_Width*m_Height*sizeof(CTuneTile)) + m_pTune = static_cast<CTuneTile *>(m_pLayers->Map()->GetData(m_pLayers->TuneLayer()->m_Tune)); + } + + if(m_pLayers->FrontLayer()) + { + unsigned int Size = m_pLayers->Map()->GetUncompressedDataSize(m_pLayers->FrontLayer()->m_Front); + if (Size >= m_Width*m_Height*sizeof(CTile)) + m_pFront = static_cast<CTile *>(m_pLayers->Map()->GetData(m_pLayers->FrontLayer()->m_Front)); + } + + for(int i = 0; i < m_Width*m_Height; i++) + { + int Index; + if(m_pSwitch) + { + if(m_pSwitch[i].m_Number > m_NumSwitchers) + m_NumSwitchers = m_pSwitch[i].m_Number; + + if(m_pSwitch[i].m_Number) + m_pDoor[i].m_Number = m_pSwitch[i].m_Number; + else + m_pDoor[i].m_Number = 0; + + Index = m_pSwitch[i].m_Type; + + if(Index < TILE_MAX_ENTITIES) + { + if(Index >= TILE_JUMP && Index <= TILE_BONUS) + m_pSwitch[i].m_Type = Index; + else + m_pSwitch[i].m_Type = 0; + } + } + if(m_pFront) + { + Index = m_pFront[i].m_Index; + + if(Index < TILE_MAX_ENTITIES) + { + switch(Index) + { + case TILE_DEATH: + m_pFront[i].m_Index = COLFLAG_DEATH; + break; + case TILE_SOLID: + m_pFront[i].m_Index = 0; + break; + case TILE_NOHOOK: + m_pFront[i].m_Index = 0; + break; + case TILE_NOLASER: + m_pFront[i].m_Index = TILE_NOLASER; + break; + default: + m_pFront[i].m_Index = 0; + } + + // DDRace tiles + if(Index == TILE_THROUGH || Index == TILE_FREEZE || (Index >= TILE_UNFREEZE && Index <= TILE_DUNFREEZE) || (Index >= TILE_WALLJUMP && Index <= TILE_SOLO_END) || (Index >= TILE_REFILL_JUMPS && Index <= TILE_STOPA) || Index == TILE_CP || Index == TILE_CP_F || (Index >= TILE_OLDLASER && Index <= TILE_UNLOCK_TEAM) || (Index >= TILE_NPC_END && Index <= TILE_NPH_END) || (Index >= TILE_NPC_START && Index < TILE_MAX_ENTITIES)) + m_pFront[i].m_Index = Index; + } + } + Index = m_pTiles[i].m_Index; + if(Index < TILE_MAX_ENTITIES) + { + switch(Index) + { + case TILE_DEATH: + m_pTiles[i].m_Index = COLFLAG_DEATH; + break; + case TILE_SOLID: + m_pTiles[i].m_Index = COLFLAG_SOLID; + break; + case TILE_NOHOOK: + m_pTiles[i].m_Index = COLFLAG_SOLID|COLFLAG_NOHOOK; + break; + case TILE_NOLASER: + m_pTiles[i].m_Index = TILE_NOLASER; + break; + default: + m_pTiles[i].m_Index = 0; + } + + // DDRace tiles + if(Index == TILE_THROUGH || Index == TILE_FREEZE || (Index >= TILE_UNFREEZE && Index <= TILE_DUNFREEZE) || (Index >= TILE_WALLJUMP && Index <= TILE_SOLO_END) || (Index >= TILE_REFILL_JUMPS && Index <= TILE_STOPA) || Index == TILE_CP || Index == TILE_CP_F || (Index >= TILE_OLDLASER && Index <= TILE_UNLOCK_TEAM) || (Index >= TILE_NPC_END && Index <= TILE_NPH_END) || (Index >= TILE_NPC_START && Index < TILE_MAX_ENTITIES)) + m_pTiles[i].m_Index = Index; + } + } + if(m_NumSwitchers) + { + m_pSwitchers = new SSwitchers[m_NumSwitchers+1]; + + for (int i = 0; i < m_NumSwitchers+1; ++i) + { + m_pSwitchers[i].m_Initial = true; + for (int j = 0; j < MAX_CLIENTS; ++j) + { + m_pSwitchers[i].m_Status[j] = true; + m_pSwitchers[i].m_EndTick[j] = 0; + m_pSwitchers[i].m_Type[j] = 0; + } + } + } +} + +int CCollision::GetTile(int x, int y) +{ + if(!m_pTiles) + return 0; + + int Nx = clamp(x/32, 0, m_Width-1); + int Ny = clamp(y/32, 0, m_Height-1); + int pos = Ny * m_Width + Nx; + + if(m_pTiles[pos].m_Index == COLFLAG_SOLID + || m_pTiles[pos].m_Index == (COLFLAG_SOLID|COLFLAG_NOHOOK) + || m_pTiles[pos].m_Index == COLFLAG_DEATH + || m_pTiles[pos].m_Index == TILE_NOLASER) + return m_pTiles[pos].m_Index; + return 0; +} +/* +bool CCollision::IsTileSolid(int x, int y) +{ + return GetTile(x, y)&COLFLAG_SOLID; +} +*/ +// TODO: rewrite this smarter! +int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, bool AllowThrough) +{ + float Distance = distance(Pos0, Pos1); + int End(Distance+1); + vec2 Last = Pos0; + int ix = 0, iy = 0; // Temporary position for checking collision + int dx = 0, dy = 0; // Offset for checking the "through" tile + if (AllowThrough) + { + ThroughOffset(Pos0, Pos1, &dx, &dy); + } + for(int i = 0; i <= End; i++) + { + float a = i/(float)End; + vec2 Pos = mix(Pos0, Pos1, a); + ix = round_to_int(Pos.x); + iy = round_to_int(Pos.y); + + if((CheckPoint(ix, iy) && !(AllowThrough && IsThrough(ix + dx, iy + dy)))) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return GetCollisionAt(ix, iy); + } + + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +int CCollision::IntersectLineTeleHook(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr, bool AllowThrough) +{ + float Distance = distance(Pos0, Pos1); + int End(Distance+1); + vec2 Last = Pos0; + int ix = 0, iy = 0; // Temporary position for checking collision + int dx = 0, dy = 0; // Offset for checking the "through" tile + if (AllowThrough) + { + ThroughOffset(Pos0, Pos1, &dx, &dy); + } + for(int i = 0; i <= End; i++) + { + float a = i/(float)End; + vec2 Pos = mix(Pos0, Pos1, a); + ix = round_to_int(Pos.x); + iy = round_to_int(Pos.y); + + int Nx = clamp(ix/32, 0, m_Width-1); + int Ny = clamp(iy/32, 0, m_Height-1); + if (g_Config.m_SvOldTeleportHook) + *pTeleNr = IsTeleport(Ny*m_Width+Nx); + else + *pTeleNr = IsTeleportHook(Ny*m_Width+Nx); + if(*pTeleNr) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return COLFLAG_TELE; + } + + if((CheckPoint(ix, iy) && !(AllowThrough && IsThrough(ix + dx, iy + dy)))) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return GetCollisionAt(ix, iy); + } + + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +int CCollision::IntersectLineTeleWeapon(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr, bool AllowThrough) +{ + float Distance = distance(Pos0, Pos1); + int End(Distance+1); + vec2 Last = Pos0; + int ix = 0, iy = 0; // Temporary position for checking collision + int dx = 0, dy = 0; // Offset for checking the "through" tile + if (AllowThrough) + { + ThroughOffset(Pos0, Pos1, &dx, &dy); + } + for(int i = 0; i <= End; i++) + { + float a = i/(float)End; + vec2 Pos = mix(Pos0, Pos1, a); + ix = round_to_int(Pos.x); + iy = round_to_int(Pos.y); + + int Nx = clamp(ix/32, 0, m_Width-1); + int Ny = clamp(iy/32, 0, m_Height-1); + if (g_Config.m_SvOldTeleportWeapons) + *pTeleNr = IsTeleport(Ny*m_Width+Nx); + else + *pTeleNr = IsTeleportWeapon(Ny*m_Width+Nx); + if(*pTeleNr) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return COLFLAG_TELE; + } + + if((CheckPoint(ix, iy) && !(AllowThrough && IsThrough(ix + dx, iy + dy)))) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + return GetCollisionAt(ix, iy); + } + + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +// TODO: OPT: rewrite this smarter! +void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces) +{ + if(pBounces) + *pBounces = 0; + + vec2 Pos = *pInoutPos; + vec2 Vel = *pInoutVel; + if(CheckPoint(Pos + Vel)) + { + int Affected = 0; + if(CheckPoint(Pos.x + Vel.x, Pos.y)) + { + pInoutVel->x *= -Elasticity; + if(pBounces) + (*pBounces)++; + Affected++; + } + + if(CheckPoint(Pos.x, Pos.y + Vel.y)) + { + pInoutVel->y *= -Elasticity; + if(pBounces) + (*pBounces)++; + Affected++; + } + + if(Affected == 0) + { + pInoutVel->x *= -Elasticity; + pInoutVel->y *= -Elasticity; + } + } + else + { + *pInoutPos = Pos + Vel; + } +} + +bool CCollision::TestBox(vec2 Pos, vec2 Size) +{ + Size *= 0.5f; + if(CheckPoint(Pos.x-Size.x, Pos.y-Size.y)) + return true; + if(CheckPoint(Pos.x+Size.x, Pos.y-Size.y)) + return true; + if(CheckPoint(Pos.x-Size.x, Pos.y+Size.y)) + return true; + if(CheckPoint(Pos.x+Size.x, Pos.y+Size.y)) + return true; + return false; +} + +void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity) +{ + // 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; + float Fraction = 1.0f/(float)(Max+1); + for(int i = 0; i <= Max; i++) + { + //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) + { + NewPos.y = Pos.y; + Vel.y *= -Elasticity; + NewPos.x = Pos.x; + Vel.x *= -Elasticity; + } + } + + Pos = NewPos; + } + } + + *pInoutPos = Pos; + *pInoutVel = Vel; +} + +// DDRace + +void CCollision::Dest() +{ + if(m_pDoor) + delete[] m_pDoor; + if(m_pSwitchers) + delete[] m_pSwitchers; + m_pTiles = 0; + m_Width = 0; + m_Height = 0; + m_pLayers = 0; + m_pTele = 0; + m_pSpeedup = 0; + m_pFront = 0; + m_pSwitch = 0; + m_pTune = 0; + m_pDoor = 0; + m_pSwitchers = 0; +} + +int CCollision::IsSolid(int x, int y) +{ + return (GetTile(x,y)&COLFLAG_SOLID); +} + +int CCollision::IsThrough(int x, int y) +{ + int Nx = clamp(x/32, 0, m_Width-1); + int Ny = clamp(y/32, 0, m_Height-1); + int Index = m_pTiles[Ny*m_Width+Nx].m_Index; + int Findex = 0; + if (m_pFront) + Findex = m_pFront[Ny*m_Width+Nx].m_Index; + if (Index == TILE_THROUGH) + return Index; + if (Findex == TILE_THROUGH) + return Findex; + return 0; +} + +int CCollision::IsWallJump(int Index) +{ + if(Index < 0) + return 0; + + return m_pTiles[Index].m_Index == TILE_WALLJUMP; +} + +int CCollision::IsNoLaser(int x, int y) +{ + return (CCollision::GetTile(x,y) == TILE_NOLASER); +} + +int CCollision::IsFNoLaser(int x, int y) +{ + return (CCollision::GetFTile(x,y) == TILE_NOLASER); +} + +int CCollision::IsTeleport(int Index) +{ + if(Index < 0 || !m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELEIN) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsEvilTeleport(int Index) +{ + if(Index < 0) + return 0; + if(!m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELEINEVIL) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsCheckTeleport(int Index) +{ + if(Index < 0) + return 0; + if(!m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELECHECKIN) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsCheckEvilTeleport(int Index) +{ + if(Index < 0) + return 0; + if(!m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELECHECKINEVIL) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsTCheckpoint(int Index) +{ + if(Index < 0) + return 0; + + if(!m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELECHECK) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsTeleportWeapon(int Index) +{ + if(Index < 0 || !m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELEINWEAPON) + return m_pTele[Index].m_Number; + + return 0; +} + +int CCollision::IsTeleportHook(int Index) +{ + if(Index < 0 || !m_pTele) + return 0; + + if(m_pTele[Index].m_Type == TILE_TELEINHOOK) + return m_pTele[Index].m_Number; + + return 0; +} + + +int CCollision::IsSpeedup(int Index) +{ + if(Index < 0 || !m_pSpeedup) + return 0; + + if(m_pSpeedup[Index].m_Force > 0) + return Index; + + return 0; +} + +int CCollision::IsTune(int Index) +{ + if(Index < 0 || !m_pTune) + return 0; + + if(m_pTune[Index].m_Type) + return m_pTune[Index].m_Number; + + return 0; +} + +void CCollision::GetSpeedup(int Index, vec2 *Dir, int *Force, int *MaxSpeed) +{ + if(Index < 0 || !m_pSpeedup) + return; + float Angle = m_pSpeedup[Index].m_Angle * (pi / 180.0f); + *Force = m_pSpeedup[Index].m_Force; + *Dir = vec2(cos(Angle), sin(Angle)); + if(MaxSpeed) + *MaxSpeed = m_pSpeedup[Index].m_MaxSpeed; +} + +int CCollision::IsSwitch(int Index) +{ + //dbg_msg("IsSwitch","Index %d, pSwitch %d, m_Type %d, m_Number %d", Index, m_pSwitch, (m_pSwitch)?m_pSwitch[Index].m_Type:0, (m_pSwitch)?m_pSwitch[Index].m_Number:0); + if(Index < 0 || !m_pSwitch) + return 0; + + if(m_pSwitch[Index].m_Type > 0) + return m_pSwitch[Index].m_Type; + + return 0; +} + +int CCollision::GetSwitchNumber(int Index) +{ + //dbg_msg("GetSwitchNumber","Index %d, pSwitch %d, m_Type %d, m_Number %d", Index, m_pSwitch, (m_pSwitch)?m_pSwitch[Index].m_Type:0, (m_pSwitch)?m_pSwitch[Index].m_Number:0); + if(Index < 0 || !m_pSwitch) + return 0; + + if(m_pSwitch[Index].m_Type > 0 && m_pSwitch[Index].m_Number > 0) + return m_pSwitch[Index].m_Number; + + return 0; +} + +int CCollision::GetSwitchDelay(int Index) +{ + //dbg_msg("GetSwitchNumber","Index %d, pSwitch %d, m_Type %d, m_Number %d", Index, m_pSwitch, (m_pSwitch)?m_pSwitch[Index].m_Type:0, (m_pSwitch)?m_pSwitch[Index].m_Number:0); + if(Index < 0 || !m_pSwitch) + return 0; + + if(m_pSwitch[Index].m_Type > 0) + return m_pSwitch[Index].m_Delay; + + return 0; +} + +int CCollision::IsMover(int x, int y, int* Flags) +{ + int Nx = clamp(x/32, 0, m_Width-1); + int Ny = clamp(y/32, 0, m_Height-1); + int Index = m_pTiles[Ny*m_Width+Nx].m_Index; + *Flags = m_pTiles[Ny*m_Width+Nx].m_Flags; + if(Index < 0) + return 0; + if (Index == TILE_CP || Index == TILE_CP_F) + return Index; + else + return 0; +} + +vec2 CCollision::CpSpeed(int Index, int Flags) +{ + if(Index < 0) + return vec2(0,0); + vec2 target; + if(Index == TILE_CP || Index == TILE_CP_F) + switch(Flags) + { + case ROTATION_0: + target.x=0; + target.y=-4; + break; + case ROTATION_90: + target.x=4; + target.y=0; + break; + case ROTATION_180: + target.x=0; + target.y=4; + break; + case ROTATION_270: + target.x=-4; + target.y=0; + break; + default: + target=vec2(0,0); + break; + } + if(Index == TILE_CP_F) + target*=4; + return target; +} + +int CCollision::GetPureMapIndex(vec2 Pos) +{ + int Nx = clamp((int)Pos.x/32, 0, m_Width-1); + int Ny = clamp((int)Pos.y/32, 0, m_Height-1); + return Ny*m_Width+Nx; +} + +bool CCollision::TileExists(int Index) +{ + if(Index < 0) + return false; + + if(m_pTiles[Index].m_Index >= TILE_FREEZE && m_pTiles[Index].m_Index < TILE_MAX_ENTITIES) + return true; + if(m_pFront && m_pFront[Index].m_Index >= TILE_FREEZE && m_pFront[Index].m_Index < TILE_MAX_ENTITIES) + return true; + if(m_pTele && (m_pTele[Index].m_Type == TILE_TELEIN || m_pTele[Index].m_Type == TILE_TELEINEVIL || m_pTele[Index].m_Type == TILE_TELECHECKINEVIL ||m_pTele[Index].m_Type == TILE_TELECHECK || m_pTele[Index].m_Type == TILE_TELECHECKIN)) + return true; + if(m_pSpeedup && m_pSpeedup[Index].m_Force > 0) + return true; + if(m_pDoor && m_pDoor[Index].m_Index) + return true; + if(m_pSwitch && m_pSwitch[Index].m_Type) + return true; + if(m_pTune && m_pTune[Index].m_Type) + return true; + return TileExistsNext(Index); +} + +bool CCollision::TileExistsNext(int Index) +{ + if(Index < 0) + return false; + int TileOnTheLeft = (Index - 1 > 0) ? Index - 1 : Index; + int TileOnTheRight = (Index + 1 < m_Width * m_Height) ? Index + 1 : Index; + int TileBelow = (Index + m_Width < m_Width * m_Height) ? Index + m_Width : Index; + int TileAbove = (Index - m_Width > 0) ? Index - m_Width : Index; + + if((m_pTiles[TileOnTheRight].m_Index == TILE_STOP && m_pTiles[TileOnTheRight].m_Flags == ROTATION_270) || (m_pTiles[TileOnTheLeft].m_Index == TILE_STOP && m_pTiles[TileOnTheLeft].m_Flags == ROTATION_90)) + return true; + if((m_pTiles[TileBelow].m_Index == TILE_STOP && m_pTiles[TileBelow].m_Flags == ROTATION_0) || (m_pTiles[TileAbove].m_Index == TILE_STOP && m_pTiles[TileAbove].m_Flags == ROTATION_180)) + return true; + if(m_pTiles[TileOnTheRight].m_Index == TILE_STOPA || m_pTiles[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pTiles[TileOnTheRight].m_Index == TILE_STOPS || m_pTiles[TileOnTheLeft].m_Index == TILE_STOPS) && m_pTiles[TileOnTheRight].m_Flags|ROTATION_270|ROTATION_90)) + return true; + if(m_pTiles[TileBelow].m_Index == TILE_STOPA || m_pTiles[TileAbove].m_Index == TILE_STOPA || ((m_pTiles[TileBelow].m_Index == TILE_STOPS || m_pTiles[TileAbove].m_Index == TILE_STOPS) && m_pTiles[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + return true; + if(m_pFront) + { + if(m_pFront[TileOnTheRight].m_Index == TILE_STOPA || m_pFront[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pFront[TileOnTheRight].m_Index == TILE_STOPS || m_pFront[TileOnTheLeft].m_Index == TILE_STOPS) && m_pFront[TileOnTheRight].m_Flags|ROTATION_270|ROTATION_90)) + return true; + if(m_pFront[TileBelow].m_Index == TILE_STOPA || m_pFront[TileAbove].m_Index == TILE_STOPA || ((m_pFront[TileBelow].m_Index == TILE_STOPS || m_pFront[TileAbove].m_Index == TILE_STOPS) && m_pFront[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + return true; + if((m_pFront[TileOnTheRight].m_Index == TILE_STOP && m_pFront[TileOnTheRight].m_Flags == ROTATION_270) || (m_pFront[TileOnTheLeft].m_Index == TILE_STOP && m_pFront[TileOnTheLeft].m_Flags == ROTATION_90)) + return true; + if((m_pFront[TileBelow].m_Index == TILE_STOP && m_pFront[TileBelow].m_Flags == ROTATION_0) || (m_pFront[TileAbove].m_Index == TILE_STOP && m_pFront[TileAbove].m_Flags == ROTATION_180)) + return true; + } + if(m_pDoor) + { + if(m_pDoor[TileOnTheRight].m_Index == TILE_STOPA || m_pDoor[TileOnTheLeft].m_Index == TILE_STOPA || ((m_pDoor[TileOnTheRight].m_Index == TILE_STOPS || m_pDoor[TileOnTheLeft].m_Index == TILE_STOPS) && m_pDoor[TileOnTheRight].m_Flags|ROTATION_270|ROTATION_90)) + return true; + if(m_pDoor[TileBelow].m_Index == TILE_STOPA || m_pDoor[TileAbove].m_Index == TILE_STOPA || ((m_pDoor[TileBelow].m_Index == TILE_STOPS || m_pDoor[TileAbove].m_Index == TILE_STOPS) && m_pDoor[TileBelow].m_Flags|ROTATION_180|ROTATION_0)) + return true; + if((m_pDoor[TileOnTheRight].m_Index == TILE_STOP && m_pDoor[TileOnTheRight].m_Flags == ROTATION_270) || (m_pDoor[TileOnTheLeft].m_Index == TILE_STOP && m_pDoor[TileOnTheLeft].m_Flags == ROTATION_90)) + return true; + if((m_pDoor[TileBelow].m_Index == TILE_STOP && m_pDoor[TileBelow].m_Flags == ROTATION_0) || (m_pDoor[TileAbove].m_Index == TILE_STOP && m_pDoor[TileAbove].m_Flags == ROTATION_180)) + return true; + } + return false; +} + +int CCollision::GetMapIndex(vec2 Pos) +{ + int Nx = clamp((int)Pos.x / 32, 0, m_Width - 1); + int Ny = clamp((int)Pos.y / 32, 0, m_Height - 1); + int Index = Ny*m_Width+Nx; + /*if (m_pTele && (m_pTele[Index].m_Type == TILE_TELEIN)) dbg_msg("m_pTele && TELEIN","Index %d",Index); + else if (m_pTele && m_pTele[Index].m_Type==TILE_TELEOUT) dbg_msg("TELEOUT","Index %d",Index); + else dbg_msg("GetMapIndex(","Index %d",Index);//REMOVE */ + + if(TileExists(Index)) + return Index; + else + return -1; +} + +std::list<int> CCollision::GetMapIndices(vec2 PrevPos, vec2 Pos, unsigned MaxIndices) +{ + std::list< int > Indices; + float d = distance(PrevPos, Pos); + int End(d + 1); + if(!d) + { + int Nx = clamp((int)Pos.x / 32, 0, m_Width - 1); + int Ny = clamp((int)Pos.y / 32, 0, m_Height - 1); + int Index = Ny * m_Width + Nx; + /*if (m_pTele && (m_pTele[Index].m_Type == TILE_TELEIN)) dbg_msg("m_pTele && TELEIN","Index %d",Index); + else if (m_pTele && m_pTele[Index].m_Type==TILE_TELEOUT) dbg_msg("TELEOUT","Index %d",Index); + else dbg_msg("GetMapIndex(","Index %d",Index);//REMOVE */ + + if(TileExists(Index)) + { + Indices.push_back(Index); + return Indices; + } + else + return Indices; + } + else + { + float a = 0.0f; + vec2 Tmp = vec2(0, 0); + int Nx = 0; + int Ny = 0; + int Index,LastIndex = 0; + for(int i = 0; i < End; i++) + { + a = i/d; + Tmp = mix(PrevPos, Pos, a); + Nx = clamp((int)Tmp.x / 32, 0, m_Width - 1); + Ny = clamp((int)Tmp.y / 32, 0, m_Height - 1); + Index = Ny * m_Width + Nx; + //dbg_msg("lastindex","%d",LastIndex); + //dbg_msg("index","%d",Index); + if(TileExists(Index) && LastIndex != Index) + { + if(MaxIndices && Indices.size() > MaxIndices) + return Indices; + Indices.push_back(Index); + LastIndex = Index; + //dbg_msg("pushed","%d",Index); + } + } + + return Indices; + } +} + +vec2 CCollision::GetPos(int Index) +{ + if(Index < 0) + return vec2(0,0); + + int x = Index%m_Width; + int y = Index/m_Width; + return vec2(x*32+16, y*32+16); +} + +int CCollision::GetTileIndex(int Index) +{ + /*dbg_msg("GetTileIndex","m_pTiles[%d].m_Index = %d",Index,m_pTiles[Index].m_Index);//Remove*/ + if(Index < 0) + return 0; + return m_pTiles[Index].m_Index; +} + +int CCollision::GetFTileIndex(int Index) +{ + /*dbg_msg("GetFTileIndex","m_pFront[%d].m_Index = %d",Index,m_pFront[Index].m_Index);//Remove*/ + + if(Index < 0 || !m_pFront) + return 0; + return m_pFront[Index].m_Index; +} + +int CCollision::GetTileFlags(int Index) +{ + /*dbg_msg("GetTileIndex","m_pTiles[%d].m_Index = %d",Index,m_pTiles[Index].m_Index);//Remove*/ + if(Index < 0) + return 0; + return m_pTiles[Index].m_Flags; +} + +int CCollision::GetFTileFlags(int Index) +{ + /*dbg_msg("GetFTileIndex","m_pFront[%d].m_Index = %d",Index,m_pFront[Index].m_Index);//Remove*/ + + if(Index < 0 || !m_pFront) + return 0; + return m_pFront[Index].m_Flags; +} + +int CCollision::GetIndex(int Nx, int Ny) +{ + return m_pTiles[Ny*m_Width+Nx].m_Index; +} + +int CCollision::GetIndex(vec2 Pos) +{ + int nx = clamp((int)Pos.x/32, 0, m_Width-1); + int ny = clamp((int)Pos.y/32, 0, m_Height-1); + + return ny*m_Width+nx; +} + +int CCollision::GetIndex(vec2 PrevPos, vec2 Pos) +{ + float Distance = distance(PrevPos, Pos); + + if(!Distance) + { + int Nx = clamp((int)Pos.x/32, 0, m_Width-1); + int Ny = clamp((int)Pos.y/32, 0, m_Height-1); + + if ((m_pTele) || + (m_pSpeedup && m_pSpeedup[Ny*m_Width+Nx].m_Force > 0)) + { + return Ny*m_Width+Nx; + } + } + + float a = 0.0f; + vec2 Tmp = vec2(0, 0); + int Nx = 0; + int Ny = 0; + + for(float f = 0; f < Distance; f++) + { + a = f/Distance; + Tmp = mix(PrevPos, Pos, a); + Nx = clamp((int)Tmp.x/32, 0, m_Width-1); + Ny = clamp((int)Tmp.y/32, 0, m_Height-1); + if ((m_pTele) || + (m_pSpeedup && m_pSpeedup[Ny*m_Width+Nx].m_Force > 0)) + { + return Ny*m_Width+Nx; + } + } + + return -1; +} + +int CCollision::GetFIndex(int Nx, int Ny) +{ + if(!m_pFront) return 0; + return m_pFront[Ny*m_Width+Nx].m_Index; +} + +int CCollision::GetFTile(int x, int y) +{ + if(!m_pFront) + return 0; + int Nx = clamp(x/32, 0, m_Width-1); + int Ny = clamp(y/32, 0, m_Height-1); + /*dbg_msg("GetFTile","m_Index %d",m_pFront[Ny*m_Width+Nx].m_Index);//Remove */ + if(m_pFront[Ny*m_Width+Nx].m_Index == COLFLAG_DEATH + || m_pFront[Ny*m_Width+Nx].m_Index == TILE_NOLASER) + return m_pFront[Ny*m_Width+Nx].m_Index; + else + return 0; +} + +int CCollision::Entity(int x, int y, int Layer) +{ + if((0 > x || x >= m_Width) || (0 > y || y >= m_Height)) + { + char aBuf[12]; + switch (Layer) + { + case LAYER_GAME: + str_format(aBuf,sizeof(aBuf), "Game"); + break; + case LAYER_FRONT: + str_format(aBuf,sizeof(aBuf), "Front"); + break; + case LAYER_SWITCH: + str_format(aBuf,sizeof(aBuf), "Switch"); + break; + case LAYER_TELE: + str_format(aBuf,sizeof(aBuf), "Tele"); + break; + case LAYER_SPEEDUP: + str_format(aBuf,sizeof(aBuf), "Speedup"); + break; + case LAYER_TUNE: + str_format(aBuf,sizeof(aBuf), "Tune"); + break; + default: + str_format(aBuf,sizeof(aBuf), "Unknown"); + } + dbg_msg("CCollision::Entity","Something is VERY wrong with the %s layer please report this at https://github.com/ddnet/ddnet, you will need to post the map as well and any steps that u think may have led to this", aBuf); + return 0; + } + switch (Layer) + { + case LAYER_GAME: + return m_pTiles[y*m_Width+x].m_Index - ENTITY_OFFSET; + case LAYER_FRONT: + return m_pFront[y*m_Width+x].m_Index - ENTITY_OFFSET; + case LAYER_SWITCH: + return m_pSwitch[y*m_Width+x].m_Type - ENTITY_OFFSET; + case LAYER_TELE: + return m_pTele[y*m_Width+x].m_Type - ENTITY_OFFSET; + case LAYER_SPEEDUP: + return m_pSpeedup[y*m_Width+x].m_Type - ENTITY_OFFSET; + case LAYER_TUNE: + return m_pTune[y*m_Width+x].m_Type - ENTITY_OFFSET; + default: + return 0; + break; + } +} + +void CCollision::SetCollisionAt(float x, float y, int flag) +{ + int Nx = clamp(round_to_int(x)/32, 0, m_Width-1); + int Ny = clamp(round_to_int(y)/32, 0, m_Height-1); + + m_pTiles[Ny * m_Width + Nx].m_Index = flag; +} + +void CCollision::SetDCollisionAt(float x, float y, int Type, int Flags, int Number) +{ + if(!m_pDoor) + return; + int Nx = clamp(round_to_int(x)/32, 0, m_Width-1); + int Ny = clamp(round_to_int(y)/32, 0, m_Height-1); + + m_pDoor[Ny * m_Width + Nx].m_Index = Type; + m_pDoor[Ny * m_Width + Nx].m_Flags = Flags; + m_pDoor[Ny * m_Width + Nx].m_Number = Number; +} + +int CCollision::GetDTileIndex(int Index) +{ + if(!m_pDoor || Index < 0 || !m_pDoor[Index].m_Index) + return 0; + return m_pDoor[Index].m_Index; +} + +int CCollision::GetDTileNumber(int Index) +{ + if(!m_pDoor || Index < 0 || !m_pDoor[Index].m_Index) + return 0; + if(m_pDoor[Index].m_Number) return m_pDoor[Index].m_Number; + return 0; +} + +int CCollision::GetDTileFlags(int Index) +{ + if(!m_pDoor || Index < 0 || !m_pDoor[Index].m_Index) + return 0; + return m_pDoor[Index].m_Flags; +} + +void ThroughOffset(vec2 Pos0, vec2 Pos1, int *Ox, int *Oy) +{ + float x = Pos0.x - Pos1.x; + float y = Pos0.y - Pos1.y; + if (fabs(x) > fabs(y)) + { + if (x < 0) + { + *Ox = -32; + *Oy = 0; + } + else + { + *Ox = 32; + *Oy = 0; + } + } + else + { + if (y < 0) + { + *Ox = 0; + *Oy = -32; + } + else + { + *Ox = 0; + *Oy = 32; + } + } +} + +int CCollision::IntersectNoLaser(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) +{ + float d = distance(Pos0, Pos1); + vec2 Last = Pos0; + + for(float f = 0; f < d; f++) + { + float a = f/d; + vec2 Pos = mix(Pos0, Pos1, a); + int Nx = clamp(round_to_int(Pos.x)/32, 0, m_Width-1); + int Ny = clamp(round_to_int(Pos.y)/32, 0, m_Height-1); + if(GetIndex(Nx, Ny) == COLFLAG_SOLID + || GetIndex(Nx, Ny) == (COLFLAG_SOLID|COLFLAG_NOHOOK) + || GetIndex(Nx, Ny) == TILE_NOLASER + || GetFIndex(Nx, Ny) == TILE_NOLASER) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + if (GetFIndex(Nx, Ny) == TILE_NOLASER) return GetFCollisionAt(Pos.x, Pos.y); + else return GetCollisionAt(Pos.x, Pos.y); + + } + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +int CCollision::IntersectNoLaserNW(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) +{ + float d = distance(Pos0, Pos1); + vec2 Last = Pos0; + + for(float f = 0; f < d; f++) + { + float a = f/d; + vec2 Pos = mix(Pos0, Pos1, a); + if(IsNoLaser(round_to_int(Pos.x), round_to_int(Pos.y)) || IsFNoLaser(round_to_int(Pos.x), round_to_int(Pos.y))) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + if(IsNoLaser(round_to_int(Pos.x), round_to_int(Pos.y))) return GetCollisionAt(Pos.x, Pos.y); + else return GetFCollisionAt(Pos.x, Pos.y); + } + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +int CCollision::IntersectAir(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) +{ + float d = distance(Pos0, Pos1); + vec2 Last = Pos0; + + for(float f = 0; f < d; f++) + { + float a = f/d; + vec2 Pos = mix(Pos0, Pos1, a); + if(IsSolid(round_to_int(Pos.x), round_to_int(Pos.y)) || (!GetTile(round_to_int(Pos.x), round_to_int(Pos.y)) && !GetFTile(round_to_int(Pos.x), round_to_int(Pos.y)))) + { + if(pOutCollision) + *pOutCollision = Pos; + if(pOutBeforeCollision) + *pOutBeforeCollision = Last; + if(!GetTile(round_to_int(Pos.x), round_to_int(Pos.y)) && !GetFTile(round_to_int(Pos.x), round_to_int(Pos.y))) + return -1; + else + if (!GetTile(round_to_int(Pos.x), round_to_int(Pos.y))) return GetTile(round_to_int(Pos.x), round_to_int(Pos.y)); + else return GetFTile(round_to_int(Pos.x), round_to_int(Pos.y)); + } + Last = Pos; + } + if(pOutCollision) + *pOutCollision = Pos1; + if(pOutBeforeCollision) + *pOutBeforeCollision = Pos1; + return 0; +} + +int CCollision::IsCheckpoint(int Index) +{ + if(Index < 0) + return -1; + + int z = m_pTiles[Index].m_Index; + if(z >= 35 && z <= 59) + return z-35; + return -1; +} + +int CCollision::IsFCheckpoint(int Index) +{ + if(Index < 0 || !m_pFront) + return -1; + + int z = m_pFront[Index].m_Index; + if(z >= 35 && z <= 59) + return z-35; + return -1; +} + +inline bool SameSide(const vec2& l0, const vec2& l1, const vec2& p0, const vec2& p1) +{ + vec2 l0l1 = l1-l0; + vec2 l0p0 = p0-l0; + vec2 l0p1 = p1-l0; + + return sign(l0l1.x*l0p0.y - l0l1.y*l0p0.x) == sign(l0l1.x*l0p1.y - l0l1.y*l0p1.x); +} + + +// ptum + +//t0, t1 and t2 are position of triangle vertices +inline vec3 BarycentricCoordinates(const vec2& t0, const vec2& t1, const vec2& t2, const vec2& p) +{ + vec2 e0 = t1 - t0; + vec2 e1 = t2 - t0; + vec2 e2 = p - t0; + + float d00 = dot(e0, e0); + float d01 = dot(e0, e1); + float d11 = dot(e1, e1); + float d20 = dot(e2, e0); + float d21 = dot(e2, e1); + float denom = d00 * d11 - d01 * d01; + + vec3 bary; + bary.x = (d11 * d20 - d01 * d21) / denom; + bary.y = (d00 * d21 - d01 * d20) / denom; + bary.z = 1.0f - bary.x - bary.y; + + return bary; +} + +//t0, t1 and t2 are position of triangle vertices +inline bool InsideTriangle(const vec2& t0, const vec2& t1, const vec2& t2, const vec2& p) +{ + vec3 bary = BarycentricCoordinates(t0, t1, t2, p); + return (bary.x >= 0.0f && bary.y >= 0.0f && bary.x + bary.y < 1.0f); +} + +//t0, t1 and t2 are position of quad vertices +inline bool InsideQuad(const vec2& q0, const vec2& q1, const vec2& q2, const vec2& q3, const vec2& p) +{ + if(SameSide(q1, q2, p, q0)) + return InsideTriangle(q0, q1, q2, p); + else + return InsideTriangle(q1, q2, q3, p); +} + +static void Rotate(vec2 *pCenter, vec2 *pPoint, float Rotation) +{ + float x = pPoint->x - pCenter->x; + float y = pPoint->y - pCenter->y; + pPoint->x = (x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x); + pPoint->y = (x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y); +} + +bool CCollision::GetQuadAt(const char *name, float x, float y) +{ + for(int i = 0; i < m_pLayers->NumGroups(); i++) + { + CMapItemGroup *pGroup = m_pLayers->GetGroup(i); + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = m_pLayers->GetLayer(pGroup->m_StartLayer+l); + + if(pLayer->m_Type == LAYERTYPE_QUADS) + { + CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; + + const CQuad *pQuads = (const CQuad *) m_pLayers->Map()->GetDataSwapped(pQLayer->m_Data); + + for(int q = 0; q < pQLayer->m_NumQuads; q++) + { + vec2 Position(0.0f, 0.0f); + float Angle = 0.0f; + if(pQuads[q].m_PosEnv >= 0) + { + GetAnimationTransform(m_Time + (static_cast<double>(pQuads->m_PosEnvOffset)/1000.), pQuads[q].m_PosEnv, m_pLayers, Position, Angle); + } + + vec2 p0 = Position + vec2(fx2f(pQuads[q].m_aPoints[0].x), fx2f(pQuads[q].m_aPoints[0].y)); + vec2 p1 = Position + vec2(fx2f(pQuads[q].m_aPoints[1].x), fx2f(pQuads[q].m_aPoints[1].y)); + vec2 p2 = Position + vec2(fx2f(pQuads[q].m_aPoints[2].x), fx2f(pQuads[q].m_aPoints[2].y)); + vec2 p3 = Position + vec2(fx2f(pQuads[q].m_aPoints[3].x), fx2f(pQuads[q].m_aPoints[3].y)); + + if(Angle != 0) + { + vec2 center(fx2f(pQuads[q].m_aPoints[4].x), fx2f(pQuads[q].m_aPoints[4].y)); + Rotate(¢er, &p0, Angle); + Rotate(¢er, &p1, Angle); + Rotate(¢er, &p2, Angle); + Rotate(¢er, &p3, Angle); + } + + char aName[12]; + IntsToStr(pQLayer->m_aName, 3, aName); + + if(!str_comp(name, aName)) return InsideQuad(p0, p1, p2, p3, vec2(x, y)); + } + } + } + } + return false; +} \ No newline at end of file diff --git a/src/game/collision.h b/src/game/collision.h new file mode 100644 index 0000000..6d86f5f --- /dev/null +++ b/src/game/collision.h @@ -0,0 +1,141 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_COLLISION_H +#define GAME_COLLISION_H + +#include <base/vmath.h> +#include <engine/shared/protocol.h> + +#include <list> + +class CCollision +{ + class CTile *m_pTiles; + int m_Width; + int m_Height; + class CLayers *m_pLayers; + + //bool IsTileSolid(int x, int y); + //int GetTile(int x, int y); + +public: + enum + { + COLFLAG_SOLID=1, + COLFLAG_DEATH=2, + COLFLAG_NOHOOK=4, + // DDRace + //COLFLAG_NOLASER=8, // Unused, now used for TimedSwitchActivation + //COLFLAG_THROUGH=16, // Unused, now used for WallJump + COLFLAG_TELE=32 + }; + + CCollision(); + void Init(class CLayers *pLayers); + bool CheckPoint(float x, float y) { return IsSolid(round_to_int(x), round_to_int(y)); } + bool CheckPoint(vec2 Pos) { return CheckPoint(Pos.x, Pos.y); } + int GetCollisionAt(float x, float y) { return GetTile(round_to_int(x), round_to_int(y)); } + int GetWidth() { return m_Width; }; + int GetHeight() { return m_Height; }; + int IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, bool AllowThrough); + int IntersectLineTeleWeapon(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr, bool AllowThrough); + int IntersectLineTeleHook(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision, int *pTeleNr, bool AllowThrough); + void MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces); + void MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity); + bool TestBox(vec2 Pos, vec2 Size); + + // DDRace + + void Dest(); + void SetCollisionAt(float x, float y, int Flag); + void SetDTile(float x, float y, bool State); + void SetDCollisionAt(float x, float y, int Type, int Flags, int Number); + int GetDTileIndex(int Index); + int GetDTileFlags(int Index); + int GetDTileNumber(int Index); + int GetFCollisionAt(float x, float y) { return GetFTile(round_to_int(x), round_to_int(y)); } + int IntersectNoLaser(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision); + int IntersectNoLaserNW(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision); + int IntersectAir(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision); + int GetIndex(int x, int y); + int GetIndex(vec2 Pos); + int GetIndex(vec2 PrevPos, vec2 Pos); + int GetFIndex(int x, int y); + + int GetTile(int x, int y); + int GetFTile(int x, int y); + int Entity(int x, int y, int Layer); + int GetPureMapIndex(vec2 Pos); + std::list<int> GetMapIndices(vec2 PrevPos, vec2 Pos, unsigned MaxIndices = 0); + int GetMapIndex(vec2 Pos); + bool TileExists(int Index); + bool TileExistsNext(int Index); + vec2 GetPos(int Index); + int GetTileIndex(int Index); + int GetFTileIndex(int Index); + int GetTileFlags(int Index); + int GetFTileFlags(int Index); + int IsTeleport(int Index); + int IsEvilTeleport(int Index); + int IsCheckTeleport(int Index); + int IsCheckEvilTeleport(int Index); + int IsTeleportWeapon(int Index); + int IsTeleportHook(int Index); + int IsTCheckpoint(int Index); + //int IsCheckpoint(int Index); + int IsSpeedup(int Index); + int IsTune(int Index); + void GetSpeedup(int Index, vec2 *Dir, int *Force, int *MaxSpeed); + int IsSwitch(int Index); + int GetSwitchNumber(int Index); + int GetSwitchDelay(int Index); + + int IsSolid(int x, int y); + int IsThrough(int x, int y); + int IsWallJump(int Index); + int IsNoLaser(int x, int y); + int IsFNoLaser(int x, int y); + + int IsCheckpoint(int Index); + int IsFCheckpoint(int Index); + + // headbot + bool GetQuadAt(const char *name, float x, float y); + void SetTime(double time) { m_Time = time; } + + int IsMover(int x, int y, int* Flags); + + vec2 CpSpeed(int index, int Flags = 0); + + class CTeleTile *TeleLayer() { return m_pTele; } + class CSwitchTile *SwitchLayer() { return m_pSwitch; } + class CTuneTile *TuneLayer() { return m_pTune; } + class CLayers *Layers() { return m_pLayers; } + int m_NumSwitchers; + +private: + + class CTeleTile *m_pTele; + class CSpeedupTile *m_pSpeedup; + class CTile *m_pFront; + class CSwitchTile *m_pSwitch; + class CTuneTile *m_pTune; + class CDoorTile *m_pDoor; + struct SSwitchers + { + bool m_Status[MAX_CLIENTS]; + bool m_Initial; + int m_EndTick[MAX_CLIENTS]; + int m_Type[MAX_CLIENTS]; + }; + + // headbot + double m_Time; + +public: + + SSwitchers* m_pSwitchers; +}; + +void ThroughOffset(vec2 Pos0, vec2 Pos1, int *Ox, int *Oy); +#endif diff --git a/src/game/ddracecommands.h b/src/game/ddracecommands.h new file mode 100644 index 0000000..5a822ea --- /dev/null +++ b/src/game/ddracecommands.h @@ -0,0 +1,52 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_DDRACECOMMANDS_H +#define GAME_SERVER_DDRACECOMMANDS_H +#undef GAME_SERVER_DDRACECOMMANDS_H // this file can be included several times +#ifndef CONSOLE_COMMAND +#define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) +#endif + +CONSOLE_COMMAND("kill_pl", "v[id]", CFGFLAG_SERVER, ConKillPlayer, this, "Kills player v and announces the kill") +CONSOLE_COMMAND("totele", "i[number]", CFGFLAG_SERVER|CMDFLAG_TEST, ConToTeleporter, this, "Teleports you to teleporter v") +CONSOLE_COMMAND("totelecp", "i[number]", CFGFLAG_SERVER|CMDFLAG_TEST, ConToCheckTeleporter, this, "Teleports you to checkpoint teleporter v") +CONSOLE_COMMAND("tele", "v[id] ?i[number]", CFGFLAG_SERVER|CMDFLAG_TEST, ConTeleport, this, "Teleports you (or player v) to player i") +CONSOLE_COMMAND("addweapon", "i[weapon-id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConAddWeapon, this, "Gives weapon with id i to you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, rifle = 4, ninja = 5)") +CONSOLE_COMMAND("removeweapon", "i[weapon-id]", CFGFLAG_SERVER|CMDFLAG_TEST, ConRemoveWeapon, this, "removes weapon with id i from you (all = -1, hammer = 0, gun = 1, shotgun = 2, grenade = 3, rifle = 4)") +CONSOLE_COMMAND("shotgun", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConShotgun, this, "Gives a shotgun to you") +CONSOLE_COMMAND("grenade", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGrenade, this, "Gives a grenade launcher to you") +CONSOLE_COMMAND("rifle", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConRifle, this, "Gives a rifle to you") +CONSOLE_COMMAND("weapons", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConWeapons, this, "Gives all weapons to you") +CONSOLE_COMMAND("unshotgun", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnShotgun, this, "Takes the shotgun from you") +CONSOLE_COMMAND("ungrenade", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnGrenade, this, "Takes the grenade launcher you") +CONSOLE_COMMAND("unrifle", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnRifle, this, "Takes the rifle from you") +CONSOLE_COMMAND("unweapons", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnWeapons, this, "Takes all weapons from you") +CONSOLE_COMMAND("ninja", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConNinja, this, "Makes you a ninja") +CONSOLE_COMMAND("super", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConSuper, this, "Makes you super") +CONSOLE_COMMAND("unsuper", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnSuper, this, "Removes super from you") +CONSOLE_COMMAND("unsolo", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnSolo, this, "Puts you out of solo part") +CONSOLE_COMMAND("undeep", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConUnDeep, this, "Puts you out of deep freeze") +CONSOLE_COMMAND("left", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoLeft, this, "Makes you move 1 tile left") +CONSOLE_COMMAND("right", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoRight, this, "Makes you move 1 tile right") +CONSOLE_COMMAND("up", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoUp, this, "Makes you move 1 tile up") +CONSOLE_COMMAND("down", "", CFGFLAG_SERVER|CMDFLAG_TEST, ConGoDown, this, "Makes you move 1 tile down") + +CONSOLE_COMMAND("move", "i[x] i[y]", CFGFLAG_SERVER|CMDFLAG_TEST, ConMove, this, "Moves to the tile with x/y-number ii") +CONSOLE_COMMAND("move_raw", "i[x] i[y]", CFGFLAG_SERVER|CMDFLAG_TEST, ConMoveRaw, this, "Moves to the point with x/y-coordinates ii") +CONSOLE_COMMAND("force_pause", "i[id] i[seconds]", CFGFLAG_SERVER, ConForcePause, this, "Force i to pause for i seconds") +CONSOLE_COMMAND("force_unpause", "i[id]", CFGFLAG_SERVER, ConForcePause, this, "Set force-pause timer of i to 0.") +CONSOLE_COMMAND("showothers", "?i['0'|'1']", CFGFLAG_CHAT, ConShowOthers, this, "Whether to show players from other teams or not (off by default), optional i = 0 for off else for on") +CONSOLE_COMMAND("showall", "?i['0'|'1']", CFGFLAG_CHAT, ConShowAll, this, "Whether to show players at any distance (off by default), optional i = 0 for off else for on") + +CONSOLE_COMMAND("list", "?s[filter]", CFGFLAG_CHAT, ConList, this, "List connected players with optional case-insensitive substring matching filter") + +CONSOLE_COMMAND("mute", "", CFGFLAG_SERVER, ConMute, this, ""); +CONSOLE_COMMAND("muteid", "v[id] i[seconds]", CFGFLAG_SERVER, ConMuteID, this, ""); +CONSOLE_COMMAND("muteip", "s[ip] i[seconds]", CFGFLAG_SERVER, ConMuteIP, this, ""); +CONSOLE_COMMAND("unmute", "v[id]", CFGFLAG_SERVER, ConUnmute, this, ""); +CONSOLE_COMMAND("mutes", "", CFGFLAG_SERVER, ConMutes, this, ""); + +CONSOLE_COMMAND("freezehammer", "v[id]", CFGFLAG_SERVER, ConFreezeHammer, this, "Gives a player Freeze Hammer") +CONSOLE_COMMAND("unfreezehammer", "v[id]", CFGFLAG_SERVER, ConUnFreezeHammer, this, "Removes Freeze Hammer from a player") +#undef CONSOLE_COMMAND + +#endif diff --git a/src/game/editor/auto_map.cpp b/src/game/editor/auto_map.cpp new file mode 100644 index 0000000..b3ef808 --- /dev/null +++ b/src/game/editor/auto_map.cpp @@ -0,0 +1,365 @@ +#include <stdio.h> // sscanf + +#include <engine/console.h> +#include <engine/storage.h> +#include <engine/shared/linereader.h> + +#include "auto_map.h" +#include "editor.h" + +CAutoMapper::CAutoMapper(CEditor *pEditor) +{ + m_pEditor = pEditor; + m_FileLoaded = false; +} + +void CAutoMapper::Load(const char* pTileName) +{ + char aPath[256]; + str_format(aPath, sizeof(aPath), "editor/%s.rules", pTileName); + IOHANDLE RulesFile = m_pEditor->Storage()->OpenFile(aPath, IOFLAG_READ, IStorage::TYPE_ALL); + if(!RulesFile) + return; + + CLineReader LineReader; + LineReader.Init(RulesFile); + + CConfiguration *pCurrentConf = 0; + CRun *pCurrentRun = 0; + CIndexRule *pCurrentIndex = 0; + + char aBuf[256]; + + // read each line + while(char *pLine = LineReader.Get()) + { + // skip blank/empty lines as well as comments + if(str_length(pLine) > 0 && pLine[0] != '#' && pLine[0] != '\n' && pLine[0] != '\r' + && pLine[0] != '\t' && pLine[0] != '\v' && pLine[0] != ' ') + { + if(pLine[0]== '[') + { + // new configuration, get the name + pLine++; + CConfiguration NewConf; + int ConfigurationID = m_lConfigs.add(NewConf); + pCurrentConf = &m_lConfigs[ConfigurationID]; + str_copy(pCurrentConf->m_aName, pLine, str_length(pLine)); + + // add start run + CRun NewRun; + int RunID = pCurrentConf->m_aRuns.add(NewRun); + pCurrentRun = &pCurrentConf->m_aRuns[RunID]; + } + else if(!str_comp_num(pLine, "NewRun", 6)) + { + // add new run + CRun NewRun; + int RunID = pCurrentConf->m_aRuns.add(NewRun); + pCurrentRun = &pCurrentConf->m_aRuns[RunID]; + } + else if(!str_comp_num(pLine, "Index", 5)) + { + // new index + int ID = 0; + char aOrientation1[128] = ""; + char aOrientation2[128] = ""; + char aOrientation3[128] = ""; + + sscanf(pLine, "Index %d %127s %127s %127s", &ID, aOrientation1, aOrientation2, aOrientation3); + + CIndexRule NewIndexRule; + NewIndexRule.m_ID = ID; + NewIndexRule.m_Flag = 0; + NewIndexRule.m_RandomValue = 0; + NewIndexRule.m_DefaultRule = true; + + if(str_length(aOrientation1) > 0) + { + if(!str_comp(aOrientation1, "XFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation1, "YFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation1, "ROTATE")) + NewIndexRule.m_Flag |= TILEFLAG_ROTATE; + } + + if(str_length(aOrientation2) > 0) + { + if(!str_comp(aOrientation2, "XFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation2, "YFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation2, "ROTATE")) + NewIndexRule.m_Flag |= TILEFLAG_ROTATE; + } + + if(str_length(aOrientation3) > 0) + { + if(!str_comp(aOrientation3, "XFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation3, "YFLIP")) + NewIndexRule.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation3, "ROTATE")) + NewIndexRule.m_Flag |= TILEFLAG_ROTATE; + } + + // add the index rule object and make it current + int IndexRuleID = pCurrentRun->m_aIndexRules.add(NewIndexRule); + pCurrentIndex = &pCurrentRun->m_aIndexRules[IndexRuleID]; + } + else if(!str_comp_num(pLine, "Pos", 3) && pCurrentIndex) + { + int x = 0, y = 0; + char aValue[128]; + int Value = CPosRule::NORULE; + array<CIndexInfo> NewIndexList; + + sscanf(pLine, "Pos %d %d %127s", &x, &y, aValue); + + if(!str_comp(aValue, "EMPTY")) + { + Value = CPosRule::INDEX; + CIndexInfo NewIndexInfo = {0, 0}; + NewIndexList.add(NewIndexInfo); + } + else if(!str_comp(aValue, "FULL")) + { + Value = CPosRule::NOTINDEX; + CIndexInfo NewIndexInfo1 = {0, 0}; + //CIndexInfo NewIndexInfo2 = {-1, 0}; + NewIndexList.add(NewIndexInfo1); + //NewIndexList.add(NewIndexInfo2); + } + else if(!str_comp(aValue, "INDEX") || !str_comp(aValue, "NOTINDEX")) + { + if(!str_comp(aValue, "INDEX")) + Value = CPosRule::INDEX; + else + Value = CPosRule::NOTINDEX; + + int pWord = 4; + while(true) { + int ID = 0; + char aOrientation1[128] = ""; + char aOrientation2[128] = ""; + char aOrientation3[128] = ""; + char aOrientation4[128] = ""; + sscanf(str_trim_words(pLine, pWord), "%d %127s %127s %127s %127s", &ID, aOrientation1, aOrientation2, aOrientation3, aOrientation4); + + CIndexInfo NewIndexInfo; + NewIndexInfo.m_ID = ID; + NewIndexInfo.m_Flag = 0; + + if(!str_comp(aOrientation1, "OR")) { + NewIndexList.add(NewIndexInfo); + pWord += 2; + continue; + } else if(str_length(aOrientation1) > 0) { + if(!str_comp(aOrientation1, "XFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation1, "YFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation1, "ROTATE")) + NewIndexInfo.m_Flag |= TILEFLAG_ROTATE; + } else { + NewIndexList.add(NewIndexInfo); + break; + } + + if(!str_comp(aOrientation2, "OR")) { + NewIndexList.add(NewIndexInfo); + pWord += 3; + continue; + } else if(str_length(aOrientation2) > 0) { + if(!str_comp(aOrientation2, "XFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation2, "YFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation2, "ROTATE")) + NewIndexInfo.m_Flag |= TILEFLAG_ROTATE; + } else { + NewIndexList.add(NewIndexInfo); + break; + } + + if(!str_comp(aOrientation3, "OR")) { + NewIndexList.add(NewIndexInfo); + pWord += 4; + continue; + } else if(str_length(aOrientation3) > 0) { + if(!str_comp(aOrientation3, "XFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_VFLIP; + else if(!str_comp(aOrientation3, "YFLIP")) + NewIndexInfo.m_Flag |= TILEFLAG_HFLIP; + else if(!str_comp(aOrientation3, "ROTATE")) + NewIndexInfo.m_Flag |= TILEFLAG_ROTATE; + } else { + NewIndexList.add(NewIndexInfo); + break; + } + + if(!str_comp(aOrientation4, "OR")) { + NewIndexList.add(NewIndexInfo); + pWord += 5; + continue; + } else { + NewIndexList.add(NewIndexInfo); + break; + } + } + } + + if(Value != CPosRule::NORULE) { + CPosRule NewPosRule = {x, y, Value, NewIndexList}; + pCurrentIndex->m_aRules.add(NewPosRule); + } + } + else if(!str_comp_num(pLine, "Random", 6) && pCurrentIndex) + { + sscanf(pLine, "Random %d", &pCurrentIndex->m_RandomValue); + } + else if(!str_comp_num(pLine, "NoDefaultRule", 13) && pCurrentIndex) + { + pCurrentIndex->m_DefaultRule = false; + } + } + } + + // add default rule for Pos 0 0 if there is none + for (int g = 0; g < m_lConfigs.size(); ++g) + { + for (int h = 0; h < m_lConfigs[g].m_aRuns.size(); ++h) + { + for(int i = 0; i < m_lConfigs[g].m_aRuns[h].m_aIndexRules.size(); ++i) + { + bool Found = false; + for(int j = 0; j < m_lConfigs[g].m_aRuns[h].m_aIndexRules[i].m_aRules.size(); ++j) + { + CPosRule *pRule = &m_lConfigs[g].m_aRuns[h].m_aIndexRules[i].m_aRules[j]; + if(pRule && pRule->m_X == 0 && pRule->m_Y == 0) + { + Found = true; + break; + } + } + if(!Found && m_lConfigs[g].m_aRuns[h].m_aIndexRules[i].m_DefaultRule) + { + array<CIndexInfo> NewIndexList; + CIndexInfo NewIndexInfo = {0, 0}; + NewIndexList.add(NewIndexInfo); + CPosRule NewPosRule = {0, 0, CPosRule::NOTINDEX, NewIndexList}; + m_lConfigs[g].m_aRuns[h].m_aIndexRules[i].m_aRules.add(NewPosRule); + } + } + } + } + + io_close(RulesFile); + + str_format(aBuf, sizeof(aBuf),"loaded %s", aPath); + m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); + + m_FileLoaded = true; +} + +const char* CAutoMapper::GetConfigName(int Index) +{ + if(Index < 0 || Index >= m_lConfigs.size()) + return ""; + + return m_lConfigs[Index].m_aName; +} + +void CAutoMapper::Proceed(CLayerTiles *pLayer, int ConfigID) +{ + if(!m_FileLoaded || pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_lConfigs.size()) + return; + + CConfiguration *pConf = &m_lConfigs[ConfigID]; + + // for every run: copy tiles, automap, overwrite tiles + for(int h = 0; h < pConf->m_aRuns.size(); ++h) { + CRun *pRun = &pConf->m_aRuns[h]; + CLayerTiles newLayer(pLayer->m_Width, pLayer->m_Height); + + // copy tiles + for(int y = 0; y < pLayer->m_Height; y++) { + for(int x = 0; x < pLayer->m_Width; x++) + { + CTile *in = &pLayer->m_pTiles[y*pLayer->m_Width+x]; + CTile *out = &newLayer.m_pTiles[y*pLayer->m_Width+x]; + out->m_Index = in->m_Index; + out->m_Flags = in->m_Flags; + } + } + + // auto map + for(int y = 0; y < pLayer->m_Height; y++) + for(int x = 0; x < pLayer->m_Width; x++) + { + CTile *pTile = &(newLayer.m_pTiles[y*pLayer->m_Width+x]); + m_pEditor->m_Map.m_Modified = true; + + for(int i = 0; i < pRun->m_aIndexRules.size(); ++i) + { + bool RespectRules = true; + for(int j = 0; j < pRun->m_aIndexRules[i].m_aRules.size() && RespectRules; ++j) + { + CPosRule *pRule = &pRun->m_aIndexRules[i].m_aRules[j]; + + int CheckIndex, CheckFlags; + int CheckX = x + pRule->m_X; + int CheckY = y + pRule->m_Y; + if(CheckX >= 0 && CheckX < pLayer->m_Width && CheckY >= 0 && CheckY < pLayer->m_Height) { + int CheckTile = CheckY * pLayer->m_Width + CheckX; + CheckIndex = pLayer->m_pTiles[CheckTile].m_Index; + CheckFlags = pLayer->m_pTiles[CheckTile].m_Flags; + } else { + CheckIndex = -1; + CheckFlags = 0; + } + + if(pRule->m_Value == CPosRule::INDEX) + { + bool PosRuleTest = false; + for(int i = 0; i < pRule->m_aIndexList.size(); ++i) { + if(CheckIndex == pRule->m_aIndexList[i].m_ID && (!pRule->m_aIndexList[i].m_Flag || CheckFlags == pRule->m_aIndexList[i].m_Flag)) + PosRuleTest = true; + } + if(!PosRuleTest) + RespectRules = false; + } + else if(pRule->m_Value == CPosRule::NOTINDEX) + { + bool PosRuleTest = true; + for(int i = 0; i < pRule->m_aIndexList.size(); ++i) { + if(CheckIndex == pRule->m_aIndexList[i].m_ID && (!pRule->m_aIndexList[i].m_Flag || CheckFlags == pRule->m_aIndexList[i].m_Flag)) + PosRuleTest = false; + } + if(!PosRuleTest) + RespectRules = false; + } + } + + if(RespectRules && + (pRun->m_aIndexRules[i].m_RandomValue <= 1 || (int)((float)rand() / ((float)RAND_MAX + 1) * pRun->m_aIndexRules[i].m_RandomValue) == 1)) + { + pTile->m_Index = pRun->m_aIndexRules[i].m_ID; + pTile->m_Flags = pRun->m_aIndexRules[i].m_Flag; + } + } + } + + // overwrite tiles + for(int y = 0; y < pLayer->m_Height; y++) { + for(int x = 0; x < pLayer->m_Width; x++) + { + CTile *in = &newLayer.m_pTiles[y*pLayer->m_Width+x]; + CTile *out = &pLayer->m_pTiles[y*pLayer->m_Width+x]; + out->m_Index = in->m_Index; + out->m_Flags = in->m_Flags; + } + } + } +} diff --git a/src/game/editor/auto_map.h b/src/game/editor/auto_map.h new file mode 100644 index 0000000..2f5a00a --- /dev/null +++ b/src/game/editor/auto_map.h @@ -0,0 +1,66 @@ +#ifndef GAME_EDITOR_AUTO_MAP_H +#define GAME_EDITOR_AUTO_MAP_H + +#include <base/tl/array.h> + +class CAutoMapper +{ + struct CIndexInfo + { + int m_ID; + int m_Flag; + }; + + struct CPosRule + { + int m_X; + int m_Y; + int m_Value; + array<CIndexInfo> m_aIndexList; + + enum + { + NORULE=0, + INDEX, + NOTINDEX + }; + }; + + struct CIndexRule + { + int m_ID; + array<CPosRule> m_aRules; + int m_Flag; + int m_RandomValue; + bool m_DefaultRule; + }; + + struct CRun + { + array<CIndexRule> m_aIndexRules; + }; + + struct CConfiguration + { + array<CRun> m_aRuns; + char m_aName[128]; + }; + +public: + CAutoMapper(class CEditor *pEditor); + + void Load(const char* pTileName); + void Proceed(class CLayerTiles *pLayer, int ConfigID); + + int ConfigNamesNum() { return m_lConfigs.size(); } + const char* GetConfigName(int Index); + + const bool IsLoaded() { return m_FileLoaded; } +private: + array<CConfiguration> m_lConfigs; + class CEditor *m_pEditor; + bool m_FileLoaded; +}; + + +#endif diff --git a/src/game/editor/editor.cpp b/src/game/editor/editor.cpp new file mode 100644 index 0000000..676cde8 --- /dev/null +++ b/src/game/editor/editor.cpp @@ -0,0 +1,5649 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/tl/array.h> +#include <base/system.h> +#include <base/color.h> +#include <time.h> + +#if defined(CONF_FAMILY_UNIX) +#include <pthread.h> +#endif + +#include <engine/shared/datafile.h> +#include <engine/shared/config.h> +#include <engine/client.h> +#include <engine/console.h> +#include <engine/graphics.h> +#include <engine/input.h> +#include <engine/keys.h> +#include <engine/storage.h> +#include <engine/textrender.h> + +#include <game/gamecore.h> +#include <game/localization.h> +#include <game/client/lineinput.h> +#include <game/client/render.h> +#include <game/client/ui.h> +#include <game/generated/client_data.h> + +#include "auto_map.h" +#include "editor.h" + +const char* vanillaImages[] = {"bg_cloud1", "bg_cloud2", "bg_cloud3", + "desert_doodads", "desert_main", "desert_mountains", "desert_mountains2", + "desert_sun", "generic_deathtiles", "generic_unhookable", "grass_doodads", + "grass_main", "jungle_background", "jungle_deathtiles", "jungle_doodads", + "jungle_main", "jungle_midground", "jungle_unhookables", "moon", "mountains", + "snow", "stars", "sun", "winter_doodads", "winter_main", "winter_mountains", + "winter_mountains2", "winter_mountains3"}; + +int CEditor::ms_CheckerTexture; +int CEditor::ms_BackgroundTexture; +int CEditor::ms_CursorTexture; +int CEditor::ms_EntitiesTexture; +const void* CEditor::ms_pUiGotContext; + +int CEditor::ms_FrontTexture; +int CEditor::ms_TeleTexture; +int CEditor::ms_SpeedupTexture; +int CEditor::ms_SwitchTexture; +int CEditor::ms_TuneTexture; + +vec3 CEditor::ms_PickerColor; +int CEditor::ms_SVPicker; +int CEditor::ms_HuePicker; + + +enum +{ + BUTTON_CONTEXT=1, +}; + +CEditorImage::~CEditorImage() +{ + m_pEditor->Graphics()->UnloadTexture(m_TexID); + if(m_pData) + { + mem_free(m_pData); + m_pData = 0; + } +} + +CEditorSound::~CEditorSound() +{ + m_pEditor->Sound()->UnloadSample(m_SoundID); + if(m_pData) + { + mem_free(m_pData); + m_pData = 0x0; + } +} + +CLayerGroup::CLayerGroup() +{ + m_aName[0] = 0; + m_Visible = true; + m_SaveToMap = true; + m_Collapse = false; + m_GameGroup = false; + m_OffsetX = 0; + m_OffsetY = 0; + m_ParallaxX = 100; + m_ParallaxY = 100; + + m_UseClipping = 0; + m_ClipX = 0; + m_ClipY = 0; + m_ClipW = 0; + m_ClipH = 0; +} + +CLayerGroup::~CLayerGroup() +{ + Clear(); +} + +void CLayerGroup::Convert(CUIRect *pRect) +{ + pRect->x += m_OffsetX; + pRect->y += m_OffsetY; +} + +void CLayerGroup::Mapping(float *pPoints) +{ + m_pMap->m_pEditor->RenderTools()->MapscreenToWorld( + m_pMap->m_pEditor->m_WorldOffsetX, m_pMap->m_pEditor->m_WorldOffsetY, + m_ParallaxX/100.0f, m_ParallaxY/100.0f, + m_OffsetX, m_OffsetY, + m_pMap->m_pEditor->Graphics()->ScreenAspect(), m_pMap->m_pEditor->m_WorldZoom, pPoints); + + pPoints[0] += m_pMap->m_pEditor->m_EditorOffsetX; + pPoints[1] += m_pMap->m_pEditor->m_EditorOffsetY; + pPoints[2] += m_pMap->m_pEditor->m_EditorOffsetX; + pPoints[3] += m_pMap->m_pEditor->m_EditorOffsetY; +} + +void CLayerGroup::MapScreen() +{ + float aPoints[4]; + Mapping(aPoints); + m_pMap->m_pEditor->Graphics()->MapScreen(aPoints[0], aPoints[1], aPoints[2], aPoints[3]); +} + +void CLayerGroup::Render() +{ + MapScreen(); + IGraphics *pGraphics = m_pMap->m_pEditor->Graphics(); + + if(m_UseClipping) + { + float aPoints[4]; + m_pMap->m_pGameGroup->Mapping(aPoints); + float x0 = (m_ClipX - aPoints[0]) / (aPoints[2]-aPoints[0]); + float y0 = (m_ClipY - aPoints[1]) / (aPoints[3]-aPoints[1]); + float x1 = ((m_ClipX+m_ClipW) - aPoints[0]) / (aPoints[2]-aPoints[0]); + float y1 = ((m_ClipY+m_ClipH) - aPoints[1]) / (aPoints[3]-aPoints[1]); + + pGraphics->ClipEnable((int)(x0*pGraphics->ScreenWidth()), (int)(y0*pGraphics->ScreenHeight()), + (int)((x1-x0)*pGraphics->ScreenWidth()), (int)((y1-y0)*pGraphics->ScreenHeight())); + } + + for(int i = 0; i < m_lLayers.size(); i++) + { + if(m_lLayers[i]->m_Visible && m_lLayers[i] != m_pMap->m_pGameLayer + && m_lLayers[i] != m_pMap->m_pFrontLayer && m_lLayers[i] != m_pMap->m_pTeleLayer + && m_lLayers[i] != m_pMap->m_pSpeedupLayer && m_lLayers[i] != m_pMap->m_pSwitchLayer && m_lLayers[i] != m_pMap->m_pTuneLayer) + { + if(m_pMap->m_pEditor->m_ShowDetail || !(m_lLayers[i]->m_Flags&LAYERFLAG_DETAIL)) + m_lLayers[i]->Render(); + } + } + + pGraphics->ClipDisable(); +} + +void CLayerGroup::AddLayer(CLayer *l) +{ + m_pMap->m_Modified = true; + m_lLayers.add(l); +} + +void CLayerGroup::DeleteLayer(int Index) +{ + if(Index < 0 || Index >= m_lLayers.size()) return; + delete m_lLayers[Index]; + m_lLayers.remove_index(Index); + m_pMap->m_Modified = true; + m_pMap->m_UndoModified++; +} + +void CLayerGroup::GetSize(float *w, float *h) +{ + *w = 0; *h = 0; + for(int i = 0; i < m_lLayers.size(); i++) + { + float lw, lh; + m_lLayers[i]->GetSize(&lw, &lh); + *w = max(*w, lw); + *h = max(*h, lh); + } +} + +int CLayerGroup::SwapLayers(int Index0, int Index1) +{ + if(Index0 < 0 || Index0 >= m_lLayers.size()) return Index0; + if(Index1 < 0 || Index1 >= m_lLayers.size()) return Index0; + if(Index0 == Index1) return Index0; + m_pMap->m_Modified = true; + m_pMap->m_UndoModified++; + swap(m_lLayers[Index0], m_lLayers[Index1]); + return Index1; +} + +void CEditorImage::AnalyseTileFlags() +{ + mem_zero(m_aTileFlags, sizeof(m_aTileFlags)); + + int tw = m_Width/16; // tilesizes + int th = m_Height/16; + if ( tw == th && m_Format == CImageInfo::FORMAT_RGBA ) + { + unsigned char *pPixelData = (unsigned char *)m_pData; + + int TileID = 0; + for(int ty = 0; ty < 16; ty++) + for(int tx = 0; tx < 16; tx++, TileID++) + { + bool Opaque = true; + for(int x = 0; x < tw; x++) + for(int y = 0; y < th; y++) + { + int p = (ty*tw+y)*m_Width + tx*tw+x; + if(pPixelData[p*4+3] < 250) + { + Opaque = false; + break; + } + } + + if(Opaque) + m_aTileFlags[TileID] |= TILEFLAG_OPAQUE; + } + } + +} + +void CEditor::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser) +{ + CEditor *pThis = (CEditor *)pUser; + if(Env < 0 || Env >= pThis->m_Map.m_lEnvelopes.size()) + { + pChannels[0] = 0; + pChannels[1] = 0; + pChannels[2] = 0; + pChannels[3] = 0; + return; + } + + CEnvelope *e = pThis->m_Map.m_lEnvelopes[Env]; + float t = pThis->m_AnimateTime+TimeOffset; + t *= pThis->m_AnimateSpeed; + e->Eval(t, pChannels); +} + +/******************************************************** + OTHER +*********************************************************/ + +// copied from gc_menu.cpp, should be more generalized +//extern int ui_do_edit_box(void *id, const CUIRect *rect, char *str, int str_size, float font_size, bool hidden=false); +int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners) +{ + int Inside = UI()->MouseInside(pRect); + bool ReturnValue = false; + bool UpdateOffset = false; + static int s_AtIndex = 0; + static bool s_DoScroll = false; + static float s_ScrollStart = 0.0f; + + FontSize *= UI()->Scale(); + + if(UI()->LastActiveItem() == pID) + { + m_EditBoxActive = 2; + int Len = str_length(pStr); + if(Len == 0) + s_AtIndex = 0; + + if(Inside && UI()->MouseButton(0)) + { + s_DoScroll = true; + s_ScrollStart = UI()->MouseX(); + int MxRel = (int)(UI()->MouseX() - pRect->x); + + for(int i = 1; i <= Len; i++) + { + if(TextRender()->TextWidth(0, FontSize, pStr, i) - *Offset > MxRel) + { + s_AtIndex = i - 1; + break; + } + + if(i == Len) + s_AtIndex = Len; + } + } + else if(!UI()->MouseButton(0)) + s_DoScroll = false; + else if(s_DoScroll) + { + // do scrolling + if(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f) + { + s_AtIndex = max(0, s_AtIndex-1); + s_ScrollStart = UI()->MouseX(); + UpdateOffset = true; + } + else if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f) + { + s_AtIndex = min(Len, s_AtIndex+1); + s_ScrollStart = UI()->MouseX(); + UpdateOffset = true; + } + } + + for(int i = 0; i < Input()->NumEvents(); i++) + { + Len = str_length(pStr); + int NumChars = Len; + ReturnValue |= CLineInput::Manipulate(Input()->GetEvent(i), pStr, StrSize, StrSize, &Len, &s_AtIndex, &NumChars); + } + } + + bool JustGotActive = false; + + if(UI()->ActiveItem() == pID) + { + if(!UI()->MouseButton(0)) + { + s_AtIndex = min(s_AtIndex, str_length(pStr)); + s_DoScroll = false; + UI()->SetActiveItem(0); + } + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + if (UI()->LastActiveItem() != pID) + JustGotActive = true; + UI()->SetActiveItem(pID); + } + } + + if(Inside) + UI()->SetHotItem(pID); + + CUIRect Textbox = *pRect; + RenderTools()->DrawUIRect(&Textbox, vec4(1, 1, 1, 0.5f), Corners, 3.0f); + Textbox.VMargin(2.0f, &Textbox); + + const char *pDisplayStr = pStr; + char aStars[128]; + + if(Hidden) + { + unsigned s = str_length(pStr); + if(s >= sizeof(aStars)) + s = sizeof(aStars)-1; + for(unsigned int i = 0; i < s; ++i) + aStars[i] = '*'; + aStars[s] = 0; + pDisplayStr = aStars; + } + + // check if the text has to be moved + if(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || Input()->NumEvents())) + { + float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); + if(w-*Offset > Textbox.w) + { + // move to the left + float wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1); + do + { + *Offset += min(wt-*Offset-Textbox.w, Textbox.w/3); + } + while(w-*Offset > Textbox.w); + } + else if(w-*Offset < 0.0f) + { + // move to the right + do + { + *Offset = max(0.0f, *Offset-Textbox.w/3); + } + while(w-*Offset < 0.0f); + } + } + UI()->ClipEnable(pRect); + Textbox.x -= *Offset; + + UI()->DoLabel(&Textbox, pDisplayStr, FontSize, -1); + + // render the cursor + if(UI()->LastActiveItem() == pID && !JustGotActive) + { + float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); + Textbox = *pRect; + Textbox.VSplitLeft(2.0f, 0, &Textbox); + Textbox.x += (w-*Offset-TextRender()->TextWidth(0, FontSize, "|", -1)/2); + + if((2*time_get()/time_freq()) % 2) // make it blink + UI()->DoLabel(&Textbox, "|", FontSize, -1); + } + UI()->ClipDisable(); + + return ReturnValue; +} + +vec4 CEditor::ButtonColorMul(const void *pID) +{ + if(UI()->ActiveItem() == pID) + return vec4(1,1,1,0.5f); + else if(UI()->HotItem() == pID) + return vec4(1,1,1,1.5f); + return vec4(1,1,1,1); +} + +float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current) +{ + CUIRect Handle; + static float s_OffsetY; + pRect->HSplitTop(33, &Handle, 0); + + Handle.y += (pRect->h-Handle.h)*Current; + + // logic + float Ret = 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()-s_OffsetY; + Ret = (Cur-Min)/Max; + if(Ret < 0.0f) Ret = 0.0f; + if(Ret > 1.0f) Ret = 1.0f; + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + UI()->SetActiveItem(pID); + s_OffsetY = UI()->MouseY()-Handle.y; + } + } + + if(Inside) + UI()->SetHotItem(pID); + + // render + CUIRect Rail; + pRect->VMargin(5.0f, &Rail); + RenderTools()->DrawUIRect(&Rail, vec4(1,1,1,0.25f), 0, 0.0f); + + CUIRect Slider = Handle; + Slider.w = Rail.x-Slider.x; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_L, 2.5f); + Slider.x = Rail.x+Rail.w; + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_R, 2.5f); + + Slider = Handle; + Slider.Margin(5.0f, &Slider); + RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f); + + return Ret; +} + +vec4 CEditor::GetButtonColor(const void *pID, int Checked) +{ + if(Checked < 0) + return vec4(0,0,0,0.5f); + + switch(Checked) + { + case 7: // selected + game layers + if(UI()->HotItem() == pID) + return vec4(1,0,0,0.4f); + return vec4(1,0,0,0.2f); + + case 6: // game layers + if(UI()->HotItem() == pID) + return vec4(1,1,1,0.4f); + return vec4(1,1,1,0.2f); + + case 5: // selected + image/sound should be embedded + if(UI()->HotItem() == pID) + return vec4(1,0,0,0.75f); + return vec4(1,0,0,0.5f); + + case 4: // image/sound should be embedded + if(UI()->HotItem() == pID) + return vec4(1,0,0,1.0f); + return vec4(1,0,0,0.875f); + + case 3: // selected + unused image/sound + if(UI()->HotItem() == pID) + return vec4(1,0,1,0.75f); + return vec4(1,0,1,0.5f); + + case 2: // unused image/sound + if(UI()->HotItem() == pID) + return vec4(0,0,1,0.75f); + return vec4(0,0,1,0.5f); + + case 1: // selected + if(UI()->HotItem() == pID) + return vec4(1,0,0,0.75f); + return vec4(1,0,0,0.5f); + + default: // regular + if(UI()->HotItem() == pID) + return vec4(1,1,1,0.75f); + return vec4(1,1,1,0.5f); + } +} + +int CEditor::DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + if(UI()->MouseInside(pRect)) + { + if(Flags&BUTTON_CONTEXT) + ms_pUiGotContext = pID; + if(m_pTooltip) + m_pTooltip = pToolTip; + } + + if(UI()->HotItem() == pID && pToolTip) + m_pTooltip = (const char *)pToolTip; + + return UI()->DoButtonLogic(pID, pText, Checked, pRect); + + // Draw here + //return UI()->DoButton(id, text, checked, r, draw_func, 0); +} + + +int CEditor::DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); + CUIRect NewRect = *pRect; + NewRect.y += NewRect.h/2.0f-7.0f; + float tw = min(TextRender()->TextWidth(0, 10.0f, pText, -1), NewRect.w); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, NewRect.x + NewRect.w/2-tw/2, NewRect.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NewRect.w; + TextRender()->TextEx(&Cursor, pText, -1); + Checked %= 2; + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_Env(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pToolTip, vec3 BaseColor) +{ + float bright = Checked ? 1.0f : 0.5f; + float alpha = UI()->HotItem() == pID ? 1.0f : 0.75f; + vec4 color = vec4(BaseColor.r*bright, BaseColor.g*bright, BaseColor.b*bright, alpha); + + RenderTools()->DrawUIRect(pRect, color, CUI::CORNER_ALL, 3.0f); + CUIRect NewRect = *pRect; + NewRect.y += NewRect.h/2.0f-7.0f; + float tw = min(TextRender()->TextWidth(0, 10.0f, pText, -1), NewRect.w); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, NewRect.x + NewRect.w/2-tw/2, NewRect.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = NewRect.w; + TextRender()->TextEx(&Cursor, pText, -1); + Checked %= 2; + return DoButton_Editor_Common(pID, pText, Checked, pRect, 0, pToolTip); +} + +int CEditor::DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + if(Checked) + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); + + CUIRect t = *pRect; + t.VMargin(5.0f, &t); + UI()->DoLabel(&t, pText, 10, -1, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + CUIRect r = *pRect; + RenderTools()->DrawUIRect(&r, vec4(0.5f, 0.5f, 0.5f, 1.0f), CUI::CORNER_T, 3.0f); + + r = *pRect; + r.VMargin(5.0f, &r); + UI()->DoLabel(&r, pText, 10, -1, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + if(UI()->HotItem() == pID || Checked) + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); + + CUIRect t = *pRect; + t.VMargin(5.0f, &t); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, t.x, t.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); + Cursor.m_LineWidth = t.w; + TextRender()->TextEx(&Cursor, pText, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_T, 5.0f); + CUIRect NewRect = *pRect; + NewRect.y += NewRect.h/2.0f-7.0f; + UI()->DoLabel(&NewRect, pText, 10, 0, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize) +{ + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), Corners, 3.0f); + CUIRect NewRect = *pRect; + NewRect.HMargin(NewRect.h/2.0f-FontSize/2.0f-1.0f, &NewRect); + UI()->DoLabel(&NewRect, pText, FontSize, 0, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_R, 3.0f); + UI()->DoLabel(pRect, pText?pText:"+", 10, 0, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) +{ + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_L, 3.0f); + UI()->DoLabel(pRect, pText?pText:"-", 10, 0, -1); + return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); +} + +int CEditor::DoButton_ColorPicker(const void *pID, const CUIRect *pRect, vec4 *pColor, const char *pToolTip) +{ + RenderTools()->DrawUIRect(pRect, *pColor, 0, 0.0f); + return DoButton_Editor_Common(pID, 0x0, 0, pRect, 0, pToolTip); +} + +void CEditor::RenderGrid(CLayerGroup *pGroup) +{ + if(!m_GridActive) + return; + + float aGroupPoints[4]; + pGroup->Mapping(aGroupPoints); + + float w = UI()->Screen()->w; + float h = UI()->Screen()->h; + + int LineDistance = GetLineDistance(); + + int XOffset = aGroupPoints[0]/LineDistance; + int YOffset = aGroupPoints[1]/LineDistance; + int XGridOffset = XOffset % m_GridFactor; + int YGridOffset = YOffset % m_GridFactor; + + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + + for(int i = 0; i < (int)w; i++) + { + if((i+YGridOffset) % m_GridFactor == 0) + Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); + else + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); + + IGraphics::CLineItem Line = IGraphics::CLineItem(LineDistance*XOffset, LineDistance*i+LineDistance*YOffset, w+aGroupPoints[2], LineDistance*i+LineDistance*YOffset); + Graphics()->LinesDraw(&Line, 1); + + if((i+XGridOffset) % m_GridFactor == 0) + Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); + else + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); + + Line = IGraphics::CLineItem(LineDistance*i+LineDistance*XOffset, LineDistance*YOffset, LineDistance*i+LineDistance*XOffset, h+aGroupPoints[3]); + Graphics()->LinesDraw(&Line, 1); + } + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + Graphics()->LinesEnd(); +} + +void CEditor::RenderBackground(CUIRect View, int Texture, float Size, float Brightness) +{ + Graphics()->TextureSet(Texture); + Graphics()->BlendNormal(); + Graphics()->QuadsBegin(); + Graphics()->SetColor(Brightness, Brightness, Brightness, 1.0f); + Graphics()->QuadsSetSubset(0,0, View.w/Size, View.h/Size); + IGraphics::CQuadItem QuadItem(View.x, View.y, View.w, View.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); +} + +int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip, bool isDegree, bool isHex) +{ + // logic + static float s_Value; + static char s_NumStr[64]; + static bool s_TextMode = false; + static void* s_LastTextpID = pID; + int Inside = UI()->MouseInside(pRect); + + if(UI()->MouseButton(1) && UI()->HotItem() == pID) + { + s_LastTextpID = pID; + s_TextMode = true; + if(isHex) + str_format(s_NumStr, sizeof(s_NumStr), "%06X", Current); + else + str_format(s_NumStr, sizeof(s_NumStr), "%d", Current); + } + + if(UI()->ActiveItem() == pID) + { + if(!UI()->MouseButton(0)) + { + m_LockMouse = false; + UI()->SetActiveItem(0); + s_TextMode = false; + } + } + + if(s_TextMode && s_LastTextpID == pID) + { + m_pTooltip = "Type your number"; + + static float s_NumberBoxID = 0; + DoEditBox(&s_NumberBoxID, pRect, s_NumStr, sizeof(s_NumStr), 10.0f, &s_NumberBoxID); + + UI()->SetActiveItem(&s_NumberBoxID); + + if(Input()->KeyPressed(KEY_RETURN) || Input()->KeyPressed(KEY_KP_ENTER) || + ((UI()->MouseButton(1) || UI()->MouseButton(0)) && !Inside)) + { + if(isHex) + Current = clamp(str_toint_base(s_NumStr, 16), Min, Max); + else + Current = clamp(str_toint(s_NumStr), Min, Max); + m_LockMouse = false; + UI()->SetActiveItem(0); + s_TextMode = false; + } + + if(Input()->KeyPressed(KEY_ESCAPE)) + { + m_LockMouse = false; + UI()->SetActiveItem(0); + s_TextMode = false; + } + } + else + { + if(UI()->ActiveItem() == pID) + { + if(UI()->MouseButton(0)) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + s_Value += m_MouseDeltaX*0.05f; + else + s_Value += m_MouseDeltaX; + + if(absolute(s_Value) > Scale) + { + int Count = (int)(s_Value/Scale); + s_Value = fmod(s_Value, Scale); + Current += Step*Count; + Current = clamp(Current, Min, Max); + } + } + if(pToolTip && !s_TextMode) + m_pTooltip = pToolTip; + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + m_LockMouse = true; + s_Value = 0; + UI()->SetActiveItem(pID); + } + if(pToolTip && !s_TextMode) + m_pTooltip = pToolTip; + } + + if(Inside) + UI()->SetHotItem(pID); + + // render + char aBuf[128]; + if(pLabel[0] != '\0') + str_format(aBuf, sizeof(aBuf),"%s %d", pLabel, Current); + else if(isDegree) + str_format(aBuf, sizeof(aBuf),"%d°", Current); + else if(isHex) + str_format(aBuf, sizeof(aBuf),"#%06X", Current); + else + str_format(aBuf, sizeof(aBuf),"%d", Current); + RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, 0), CUI::CORNER_ALL, 5.0f); + pRect->y += pRect->h/2.0f-7.0f; + UI()->DoLabel(pRect, aBuf, 10, 0, -1); + } + + return Current; +} + +CLayerGroup *CEditor::GetSelectedGroup() +{ + if(m_SelectedGroup >= 0 && m_SelectedGroup < m_Map.m_lGroups.size()) + return m_Map.m_lGroups[m_SelectedGroup]; + return 0x0; +} + +CLayer *CEditor::GetSelectedLayer(int Index) +{ + CLayerGroup *pGroup = GetSelectedGroup(); + if(!pGroup) + return 0x0; + + if(m_SelectedLayer >= 0 && m_SelectedLayer < m_Map.m_lGroups[m_SelectedGroup]->m_lLayers.size()) + return pGroup->m_lLayers[m_SelectedLayer]; + return 0x0; +} + +CLayer *CEditor::GetSelectedLayerType(int Index, int Type) +{ + CLayer *p = GetSelectedLayer(Index); + if(p && p->m_Type == Type) + return p; + return 0x0; +} + +CQuad *CEditor::GetSelectedQuad() +{ + CLayerQuads *ql = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); + if(!ql) + return 0; + if(m_SelectedQuad >= 0 && m_SelectedQuad < ql->m_lQuads.size()) + return &ql->m_lQuads[m_SelectedQuad]; + return 0; +} + +CSoundSource *CEditor::GetSelectedSource() +{ + CLayerSounds *pSounds = (CLayerSounds *)GetSelectedLayerType(0, LAYERTYPE_SOUNDS); + if(!pSounds) + return 0; + if(m_SelectedSource >= 0 && m_SelectedSource < pSounds->m_lSources.size()) + return &pSounds->m_lSources[m_SelectedSource]; + return 0; +} + +void CEditor::CallbackOpenMap(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor*)pUser; + if(pEditor->Load(pFileName, StorageType)) + { + str_copy(pEditor->m_aFileName, pFileName, 512); + pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder; + pEditor->SortImages(); + pEditor->m_Dialog = DIALOG_NONE; + pEditor->m_Map.m_Modified = false; + pEditor->m_Map.m_UndoModified = 0; + pEditor->m_LastUndoUpdateTime = time_get(); + } + else + { + pEditor->Reset(); + pEditor->m_aFileName[0] = 0; + } +} + +void CEditor::CallbackAppendMap(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor*)pUser; + if(pEditor->Append(pFileName, StorageType)) + pEditor->m_aFileName[0] = 0; + else + pEditor->SortImages(); + + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = static_cast<CEditor*>(pUser); + char aBuf[1024]; + const int Length = str_length(pFileName); + // add map extension + if(Length <= 4 || pFileName[Length-4] != '.' || str_comp_nocase(pFileName+Length-3, "map")) + { + str_format(aBuf, sizeof(aBuf), "%s.map", pFileName); + pFileName = aBuf; + } + + if(pEditor->Save(pFileName)) + { + str_copy(pEditor->m_aFileName, pFileName, sizeof(pEditor->m_aFileName)); + pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder; + pEditor->m_Map.m_Modified = false; + pEditor->m_Map.m_UndoModified = 0; + pEditor->m_LastUndoUpdateTime = time_get(); + } + + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::CallbackSaveCopyMap(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = static_cast<CEditor*>(pUser); + char aBuf[1024]; + const int Length = str_length(pFileName); + // add map extension + if(Length <= 4 || pFileName[Length-4] != '.' || str_comp_nocase(pFileName+Length-3, "map")) + { + str_format(aBuf, sizeof(aBuf), "%s.map", pFileName); + pFileName = aBuf; + } + + if(pEditor->Save(pFileName)) + { + pEditor->m_Map.m_Modified = false; + pEditor->m_Map.m_UndoModified = 0; + pEditor->m_LastUndoUpdateTime = time_get(); + } + + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::DoToolbar(CUIRect ToolBar) +{ + CUIRect TB_Top, TB_Bottom; + CUIRect Button; + + ToolBar.HSplitTop(ToolBar.h/2.0f, &TB_Top, &TB_Bottom); + + TB_Top.HSplitBottom(2.5f, &TB_Top, 0); + TB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom); + + // ctrl+o to open + if(Input()->KeyDown('o') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE) + { + if(HasUnsavedData()) + { + if(!m_PopupEventWasActivated) + { + m_PopupEventType = POPEVENT_LOAD; + m_PopupEventActivated = true; + } + } + else + InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", CallbackOpenMap, this); + } + + // ctrl+s to save + if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE) + { + if(m_aFileName[0] && m_ValidSaveFilename) + { + if(!m_PopupEventWasActivated) + { + str_copy(m_aFileSaveName, m_aFileName, sizeof(m_aFileSaveName)); + CallbackSaveMap(m_aFileSaveName, IStorage::TYPE_SAVE, this); + } + } + else + InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", CallbackSaveMap, this); + } + + // ctrl+shift+s to save as + if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && (Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && m_Dialog == DIALOG_NONE) + InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", CallbackSaveMap, this); + + // ctrl+shift+alt+s to save as + if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && (Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && (Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) && m_Dialog == DIALOG_NONE) + InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", CallbackSaveCopyMap, this); + + // detail button + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_HqButton = 0; + if(DoButton_Editor(&s_HqButton, "HD", m_ShowDetail, &Button, 0, "[ctrl+h] Toggle High Detail") || + (Input()->KeyDown('h') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) + { + m_ShowDetail = !m_ShowDetail; + } + + TB_Top.VSplitLeft(5.0f, 0, &TB_Top); + + // animation button + TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); + static int s_AnimateButton = 0; + if(DoButton_Editor(&s_AnimateButton, "Anim", m_Animate, &Button, 0, "[ctrl+m] Toggle animation") || + (Input()->KeyDown('m') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) + { + m_AnimateStart = time_get(); + m_Animate = !m_Animate; + } + + TB_Top.VSplitLeft(5.0f, 0, &TB_Top); + + // proof button + TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); + static int s_ProofButton = 0; + if(DoButton_Editor(&s_ProofButton, "Proof", m_ProofBorders, &Button, 0, "[ctrl+p] Toggles proof borders. These borders represent what a player maximum can see.") || + (Input()->KeyDown('p') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) + { + m_ProofBorders = !m_ProofBorders; + } + + TB_Top.VSplitLeft(5.0f, 0, &TB_Top); + + // tile info button + TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); + static int s_TileInfoButton = 0; + if(DoButton_Editor(&s_TileInfoButton, "Info", m_ShowTileInfo, &Button, 0, "[ctrl+i] Show tile informations") || + (Input()->KeyDown('i') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) + { + m_ShowTileInfo = !m_ShowTileInfo; + m_ShowEnvelopePreview = 0; + } + + TB_Top.VSplitLeft(15.0f, 0, &TB_Top); + + // zoom group + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_ZoomOutButton = 0; + if(DoButton_Ex(&s_ZoomOutButton, "ZO", 0, &Button, 0, "[NumPad-] Zoom out", CUI::CORNER_L)) + m_ZoomLevel += 50; + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_ZoomNormalButton = 0; + if(DoButton_Ex(&s_ZoomNormalButton, "1:1", 0, &Button, 0, "[NumPad*] Zoom to normal and remove editor offset", 0)) + { + m_EditorOffsetX = 0; + m_EditorOffsetY = 0; + m_ZoomLevel = 100; + } + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_ZoomInButton = 0; + if(DoButton_Ex(&s_ZoomInButton, "ZI", 0, &Button, 0, "[NumPad+] Zoom in", CUI::CORNER_R)) + m_ZoomLevel -= 50; + + TB_Top.VSplitLeft(10.0f, 0, &TB_Top); + + // animation speed + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_AnimFasterButton = 0; + if(DoButton_Ex(&s_AnimFasterButton, "A+", 0, &Button, 0, "Increase animation speed", CUI::CORNER_L)) + m_AnimateSpeed += 0.5f; + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_AnimNormalButton = 0; + if(DoButton_Ex(&s_AnimNormalButton, "1", 0, &Button, 0, "Normal animation speed", 0)) + m_AnimateSpeed = 1.0f; + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_AnimSlowerButton = 0; + if(DoButton_Ex(&s_AnimSlowerButton, "A-", 0, &Button, 0, "Decrease animation speed", CUI::CORNER_R)) + { + if(m_AnimateSpeed > 0.5f) + m_AnimateSpeed -= 0.5f; + } + + TB_Top.VSplitLeft(10.0f, &Button, &TB_Top); + + + // brush manipulation + { + int Enabled = m_Brush.IsEmpty()?-1:0; + + // flip buttons + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_FlipXButton = 0; + if(DoButton_Ex(&s_FlipXButton, "X/X", Enabled, &Button, 0, "[N] Flip brush horizontal", CUI::CORNER_L) || (Input()->KeyDown('n') && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) + { + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + m_Brush.m_lLayers[i]->BrushFlipX(); + } + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_FlipyButton = 0; + if(DoButton_Ex(&s_FlipyButton, "Y/Y", Enabled, &Button, 0, "[M] Flip brush vertical", CUI::CORNER_R) || (Input()->KeyDown('m') && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) + { + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + m_Brush.m_lLayers[i]->BrushFlipY(); + } + + // rotate buttons + TB_Top.VSplitLeft(15.0f, &Button, &TB_Top); + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_RotationAmount = 90; + bool TileLayer = false; + // check for tile layers in brush selection + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) + { + TileLayer = true; + s_RotationAmount = max(90, (s_RotationAmount/90)*90); + break; + } + s_RotationAmount = UiDoValueSelector(&s_RotationAmount, &Button, "", s_RotationAmount, TileLayer?90:1, 359, TileLayer?90:1, TileLayer?10.0f:2.0f, "Rotation of the brush in degrees. Use left mouse button to drag and change the value. Hold shift to be more precise.", true); + + TB_Top.VSplitLeft(5.0f, &Button, &TB_Top); + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_CcwButton = 0; + if(DoButton_Ex(&s_CcwButton, "CCW", Enabled, &Button, 0, "[R] Rotates the brush counter clockwise", CUI::CORNER_L) || (Input()->KeyDown('r') && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) + { + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + m_Brush.m_lLayers[i]->BrushRotate(-s_RotationAmount/360.0f*pi*2); + } + + TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); + static int s_CwButton = 0; + if(DoButton_Ex(&s_CwButton, "CW", Enabled, &Button, 0, "[T] Rotates the brush clockwise", CUI::CORNER_R) || (Input()->KeyDown('t') && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0)) + { + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + m_Brush.m_lLayers[i]->BrushRotate(s_RotationAmount/360.0f*pi*2); + } + } + + // quad manipulation + { + // do add button + TB_Top.VSplitLeft(10.0f, &Button, &TB_Top); + TB_Top.VSplitLeft(60.0f, &Button, &TB_Top); + static int s_NewButton = 0; + + CLayerQuads *pQLayer = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); + //CLayerTiles *tlayer = (CLayerTiles *)get_selected_layer_type(0, LAYERTYPE_TILES); + if(DoButton_Editor(&s_NewButton, "Add Quad", pQLayer?0:-1, &Button, 0, "Adds a new quad")) + { + if(pQLayer) + { + float Mapping[4]; + CLayerGroup *g = GetSelectedGroup(); + g->Mapping(Mapping); + int AddX = f2fx(Mapping[0] + (Mapping[2]-Mapping[0])/2); + int AddY = f2fx(Mapping[1] + (Mapping[3]-Mapping[1])/2); + + CQuad *q = pQLayer->NewQuad(); + for(int i = 0; i < 5; i++) + { + q->m_aPoints[i].x += AddX; + q->m_aPoints[i].y += AddY; + } + } + } + } + + // tile manipulation + { + TB_Bottom.VSplitLeft(40.0f, &Button, &TB_Bottom); + static int s_BorderBut = 0; + CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); + + // no border for tele layer, speedup, front and switch + if(pT && (pT->m_Tele || pT->m_Speedup || pT->m_Switch || pT->m_Front || pT->m_Tune)) + pT = 0; + + if(DoButton_Editor(&s_BorderBut, "Border", pT?0:-1, &Button, 0, "Adds border tiles")) + { + if(pT) + DoMapBorder(); + } + // do tele button + TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); + TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); + static int s_TeleButton = 0; + CLayerTiles *pS = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); + + if(DoButton_Ex(&s_TeleButton, "Teleporter", (pS && pS->m_Tele)?0:-1, &Button, 0, "Teleporter", CUI::CORNER_ALL)) + { + static int s_TelePopupID = 0; + UiInvokePopupMenu(&s_TelePopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 23, PopupTele); + } + // do speedup button + TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); + TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); + static int s_SpeedupButton = 0; + if(DoButton_Ex(&s_SpeedupButton, "Speedup", (pS && pS->m_Speedup)?0:-1, &Button, 0, "Speedup", CUI::CORNER_ALL)) + { + static int s_SpeedupPopupID = 0; + UiInvokePopupMenu(&s_SpeedupPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 53, PopupSpeedup); + } + // do switch button + TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); + TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); + static int s_SwitchButton = 0; + if(DoButton_Ex(&s_SwitchButton, "Switcher", (pS && pS->m_Switch)?0:-1, &Button, 0, "Switcher", CUI::CORNER_ALL)) + { + static int s_SwitchPopupID = 0; + UiInvokePopupMenu(&s_SwitchPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 36, PopupSwitch); + } + // do tuning button + TB_Bottom.VSplitLeft(5.0f, &Button, &TB_Bottom); + TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); + static int s_TuneButton = 0; + if(DoButton_Ex(&s_TuneButton, "Tune", (pS && pS->m_Tune)?0:-1, &Button, 0, "Tune", CUI::CORNER_ALL)) + { + static int s_TunePopupID = 0; + UiInvokePopupMenu(&s_TunePopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 90, PopupTune); + } + } + + TB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom); + + // refocus button + TB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom); + static int s_RefocusButton = 0; + if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX&&m_WorldOffsetY?0:-1, &Button, 0, "[HOME] Restore map focus") || (m_EditBoxActive == 0 && Input()->KeyDown(KEY_HOME))) + { + m_WorldOffsetX = 0; + m_WorldOffsetY = 0; + } + + TB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom); + + // grid button + TB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom); + static int s_GridButton = 0; + if(DoButton_Editor(&s_GridButton, "Grid", m_GridActive, &Button, 0, "Toggle Grid")) + { + m_GridActive = !m_GridActive; + } + + TB_Bottom.VSplitLeft(30.0f, 0, &TB_Bottom); + + // grid zoom + TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); + static int s_GridIncreaseButton = 0; + if(DoButton_Ex(&s_GridIncreaseButton, "G-", 0, &Button, 0, "Decrease grid", CUI::CORNER_L)) + { + if(m_GridFactor > 1) + m_GridFactor--; + } + + TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); + static int s_GridNormalButton = 0; + if(DoButton_Ex(&s_GridNormalButton, "1", 0, &Button, 0, "Normal grid", 0)) + m_GridFactor = 1; + + TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); + + static int s_GridDecreaseButton = 0; + if(DoButton_Ex(&s_GridDecreaseButton, "G+", 0, &Button, 0, "Increase grid", CUI::CORNER_R)) + { + if(m_GridFactor < 15) + m_GridFactor++; + } + + // sound source manipulation + { + // do add button + TB_Bottom.VSplitLeft(10.0f, &Button, &TB_Bottom); + TB_Bottom.VSplitLeft(60.0f, &Button, &TB_Bottom); + static int s_NewButton = 0; + + CLayerSounds *pSoundLayer = (CLayerSounds *)GetSelectedLayerType(0, LAYERTYPE_SOUNDS); + if(DoButton_Editor(&s_NewButton, "Add Sound", pSoundLayer?0:-1, &Button, 0, "Adds a new sound source")) + { + if(pSoundLayer) + { + float Mapping[4]; + CLayerGroup *g = GetSelectedGroup(); + g->Mapping(Mapping); + int AddX = f2fx(Mapping[0] + (Mapping[2]-Mapping[0])/2); + int AddY = f2fx(Mapping[1] + (Mapping[3]-Mapping[1])/2); + + CSoundSource *pSource = pSoundLayer->NewSource(); + pSource->m_Position.x += AddX; + pSource->m_Position.y += AddY; + } + } + } + +} + +static void Rotate(const CPoint *pCenter, CPoint *pPoint, float Rotation) +{ + int x = pPoint->x - pCenter->x; + int y = pPoint->y - pCenter->y; + pPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x); + pPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y); +} + +void CEditor::DoSoundSource(CSoundSource *pSource, int Index) +{ + enum + { + OP_NONE=0, + OP_MOVE, + OP_CONTEXT_MENU, + }; + + void *pID = &pSource->m_Position; + + static float s_LastWx; + static float s_LastWy; + static int s_Operation = OP_NONE; + + float wx = UI()->MouseWorldX(); + float wy = UI()->MouseWorldY(); + + float CenterX = fx2f(pSource->m_Position.x); + float CenterY = fx2f(pSource->m_Position.y); + + float dx = (CenterX - wx)/m_WorldZoom; + float dy = (CenterY - wy)/m_WorldZoom; + if(dx*dx+dy*dy < 50) + UI()->SetHotItem(pID); + + bool IgnoreGrid; + if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) + IgnoreGrid = true; + else + IgnoreGrid = false; + + if(UI()->ActiveItem() == pID) + { + if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.5f) + { + if(s_Operation == OP_MOVE) + { + if(m_GridActive && !IgnoreGrid) + { + int LineDistance = GetLineDistance(); + + float x = 0.0f; + float y = 0.0f; + if(wx >= 0) + x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + if(wy >= 0) + y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + + pSource->m_Position.x = f2fx(x); + pSource->m_Position.y = f2fx(y); + } + else + { + pSource->m_Position.x += f2fx(wx-s_LastWx); + pSource->m_Position.y += f2fx(wy-s_LastWy); + } + } + } + + s_LastWx = wx; + s_LastWy = wy; + + if(s_Operation == OP_CONTEXT_MENU) + { + if(!UI()->MouseButton(1)) + { + m_Map.m_UndoModified++; + + static int s_SourcePopupID = 0; + UiInvokePopupMenu(&s_SourcePopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 200, PopupSource); + m_LockMouse = false; + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + else + { + if(!UI()->MouseButton(0)) + { + if(s_Operation == OP_MOVE) + { + m_Map.m_UndoModified++; + } + + m_LockMouse = false; + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + + Graphics()->SetColor(1,1,1,1); + } + else if(UI()->HotItem() == pID) + { + ms_pUiGotContext = pID; + + Graphics()->SetColor(1,1,1,1); + m_pTooltip = "Left mouse button to move. Hold alt to ignore grid."; + + if(UI()->MouseButton(0)) + { + s_Operation = OP_MOVE; + + UI()->SetActiveItem(pID); + m_SelectedSource = Index; + s_LastWx = wx; + s_LastWy = wy; + } + + if(UI()->MouseButton(1)) + { + m_SelectedSource = Index; + s_Operation = OP_CONTEXT_MENU; + UI()->SetActiveItem(pID); + } + } + else + { + Graphics()->SetColor(0,1,0,1); + } + + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); +} + +void CEditor::DoQuad(CQuad *q, int Index) +{ + enum + { + OP_NONE=0, + OP_MOVE_ALL, + OP_MOVE_PIVOT, + OP_ROTATE, + OP_CONTEXT_MENU, + OP_DELETE, + }; + + // some basic values + void *pID = &q->m_aPoints[4]; // use pivot addr as id + static CPoint s_RotatePoints[4]; + static float s_LastWx; + static float s_LastWy; + static int s_Operation = OP_NONE; + static float s_RotateAngle = 0; + float wx = UI()->MouseWorldX(); + float wy = UI()->MouseWorldY(); + + // get pivot + float CenterX = fx2f(q->m_aPoints[4].x); + float CenterY = fx2f(q->m_aPoints[4].y); + + float dx = (CenterX - wx)/m_WorldZoom; + float dy = (CenterY - wy)/m_WorldZoom; + if(dx*dx+dy*dy < 50) + UI()->SetHotItem(pID); + + bool IgnoreGrid; + if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) + IgnoreGrid = true; + else + IgnoreGrid = false; + + // draw selection background + if(m_SelectedQuad == Index) + { + Graphics()->SetColor(0,0,0,1); + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 7.0f*m_WorldZoom, 7.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); + } + + if(UI()->ActiveItem() == pID) + { + if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.5f) + { + // check if we only should move pivot + if(s_Operation == OP_MOVE_PIVOT) + { + if(m_GridActive && !IgnoreGrid) + { + int LineDistance = GetLineDistance(); + + float x = 0.0f; + float y = 0.0f; + if(wx >= 0) + x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + if(wy >= 0) + y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + + q->m_aPoints[4].x = f2fx(x); + q->m_aPoints[4].y = f2fx(y); + } + else + { + q->m_aPoints[4].x += f2fx(wx-s_LastWx); + q->m_aPoints[4].y += f2fx(wy-s_LastWy); + } + } + else if(s_Operation == OP_MOVE_ALL) + { + // move all points including pivot + if(m_GridActive && !IgnoreGrid) + { + int LineDistance = GetLineDistance(); + + float x = 0.0f; + float y = 0.0f; + if(wx >= 0) + x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + if(wy >= 0) + y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + + int OldX = q->m_aPoints[4].x; + int OldY = q->m_aPoints[4].y; + q->m_aPoints[4].x = f2fx(x); + q->m_aPoints[4].y = f2fx(y); + int DiffX = q->m_aPoints[4].x - OldX; + int DiffY = q->m_aPoints[4].y - OldY; + + for(int v = 0; v < 4; v++) + { + q->m_aPoints[v].x += DiffX; + q->m_aPoints[v].y += DiffY; + } + } + else + { + for(int v = 0; v < 5; v++) + { + q->m_aPoints[v].x += f2fx(wx-s_LastWx); + q->m_aPoints[v].y += f2fx(wy-s_LastWy); + } + } + } + else if(s_Operation == OP_ROTATE) + { + for(int v = 0; v < 4; v++) + { + q->m_aPoints[v] = s_RotatePoints[v]; + Rotate(&q->m_aPoints[4], &q->m_aPoints[v], s_RotateAngle); + } + } + } + + s_RotateAngle += (m_MouseDeltaX) * 0.002f; + s_LastWx = wx; + s_LastWy = wy; + + if(s_Operation == OP_CONTEXT_MENU) + { + if(!UI()->MouseButton(1)) + { + m_Map.m_UndoModified++; + + static int s_QuadPopupID = 0; + UiInvokePopupMenu(&s_QuadPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 180, PopupQuad); + m_LockMouse = false; + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + else if(s_Operation == OP_DELETE) + { + if(!UI()->MouseButton(1)) + { + m_Map.m_UndoModified++; + m_LockMouse = false; + m_Map.m_Modified = true; + CLayerQuads *pLayer = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); + if(pLayer) + pLayer->m_lQuads.remove_index(m_SelectedQuad); + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + else + { + if(!UI()->MouseButton(0)) + { + if(s_Operation == OP_ROTATE || s_Operation == OP_MOVE_ALL || s_Operation == OP_MOVE_PIVOT) + { + m_Map.m_UndoModified++; + } + + m_LockMouse = false; + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + + Graphics()->SetColor(1,1,1,1); + } + else if(UI()->HotItem() == pID) + { + ms_pUiGotContext = pID; + + Graphics()->SetColor(1,1,1,1); + m_pTooltip = "Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate. Hold alt to ignore grid. Hold shift and right click to delete."; + + if(UI()->MouseButton(0)) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + s_Operation = OP_MOVE_PIVOT; + else if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) + { + m_LockMouse = true; + s_Operation = OP_ROTATE; + s_RotateAngle = 0; + s_RotatePoints[0] = q->m_aPoints[0]; + s_RotatePoints[1] = q->m_aPoints[1]; + s_RotatePoints[2] = q->m_aPoints[2]; + s_RotatePoints[3] = q->m_aPoints[3]; + } + else + s_Operation = OP_MOVE_ALL; + + UI()->SetActiveItem(pID); + if(m_SelectedQuad != Index) + m_SelectedPoints = 0; + m_SelectedQuad = Index; + s_LastWx = wx; + s_LastWy = wy; + } + + if(UI()->MouseButton(1)) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + { + if(m_SelectedQuad != Index) + m_SelectedPoints = 0; + m_SelectedQuad = Index; + s_Operation = OP_DELETE; + UI()->SetActiveItem(pID); + } + else + { + if(m_SelectedQuad != Index) + m_SelectedPoints = 0; + m_SelectedQuad = Index; + s_Operation = OP_CONTEXT_MENU; + UI()->SetActiveItem(pID); + } + } + } + else + Graphics()->SetColor(0,1,0,1); + + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); +} + +void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) +{ + void *pID = &pQuad->m_aPoints[V]; + + float wx = UI()->MouseWorldX(); + float wy = UI()->MouseWorldY(); + + float px = fx2f(pQuad->m_aPoints[V].x); + float py = fx2f(pQuad->m_aPoints[V].y); + + float dx = (px - wx)/m_WorldZoom; + float dy = (py - wy)/m_WorldZoom; + if(dx*dx+dy*dy < 50) + UI()->SetHotItem(pID); + + // draw selection background + if(m_SelectedQuad == QuadIndex && m_SelectedPoints&(1<<V)) + { + Graphics()->SetColor(0,0,0,1); + IGraphics::CQuadItem QuadItem(px, py, 7.0f*m_WorldZoom, 7.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); + } + + enum + { + OP_NONE=0, + OP_MOVEPOINT, + OP_MOVEUV, + OP_CONTEXT_MENU + }; + + static bool s_Moved; + static int s_Operation = OP_NONE; + + bool IgnoreGrid; + if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) + IgnoreGrid = true; + else + IgnoreGrid = false; + + if(UI()->ActiveItem() == pID) + { + float dx = m_MouseDeltaWx; + float dy = m_MouseDeltaWy; + if(!s_Moved) + { + if(dx*dx+dy*dy > 0.5f) + s_Moved = true; + } + + if(s_Moved) + { + if(s_Operation == OP_MOVEPOINT) + { + if(m_GridActive && !IgnoreGrid) + { + for(int m = 0; m < 4; m++) + if(m_SelectedPoints&(1<<m)) + { + int LineDistance = GetLineDistance(); + + float x = 0.0f; + float y = 0.0f; + if(wx >= 0) + x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + if(wy >= 0) + y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + + pQuad->m_aPoints[m].x = f2fx(x); + pQuad->m_aPoints[m].y = f2fx(y); + } + } + else + { + for(int m = 0; m < 4; m++) + if(m_SelectedPoints&(1<<m)) + { + pQuad->m_aPoints[m].x += f2fx(dx); + pQuad->m_aPoints[m].y += f2fx(dy); + } + } + } + else if(s_Operation == OP_MOVEUV) + { + for(int m = 0; m < 4; m++) + if(m_SelectedPoints&(1<<m)) + { + // 0,2;1,3 - line x + // 0,1;2,3 - line y + + pQuad->m_aTexcoords[m].x += f2fx(dx*0.001f); + pQuad->m_aTexcoords[(m+2)%4].x += f2fx(dx*0.001f); + + pQuad->m_aTexcoords[m].y += f2fx(dy*0.001f); + pQuad->m_aTexcoords[m^1].y += f2fx(dy*0.001f); + } + } + } + + if(s_Operation == OP_CONTEXT_MENU) + { + if(!UI()->MouseButton(1)) + { + m_Map.m_UndoModified++; + + static int s_PointPopupID = 0; + UiInvokePopupMenu(&s_PointPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 150, PopupPoint); + UI()->SetActiveItem(0); + } + } + else + { + if(!UI()->MouseButton(0)) + { + if(!s_Moved) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + m_SelectedPoints ^= 1<<V; + else + m_SelectedPoints = 1<<V; + } + + if(s_Operation == OP_MOVEPOINT || s_Operation == OP_MOVEUV) + m_Map.m_UndoModified++; + + m_LockMouse = false; + UI()->SetActiveItem(0); + } + } + + Graphics()->SetColor(1,1,1,1); + } + else if(UI()->HotItem() == pID) + { + ms_pUiGotContext = pID; + + Graphics()->SetColor(1,1,1,1); + m_pTooltip = "Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid."; + + if(UI()->MouseButton(0)) + { + UI()->SetActiveItem(pID); + s_Moved = false; + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + { + s_Operation = OP_MOVEUV; + m_LockMouse = true; + } + else + s_Operation = OP_MOVEPOINT; + + if(!(m_SelectedPoints&(1<<V))) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + m_SelectedPoints |= 1<<V; + else + m_SelectedPoints = 1<<V; + s_Moved = true; + } + + m_SelectedQuad = QuadIndex; + } + else if(UI()->MouseButton(1)) + { + s_Operation = OP_CONTEXT_MENU; + m_SelectedQuad = QuadIndex; + UI()->SetActiveItem(pID); + if(!(m_SelectedPoints&(1<<V))) + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + m_SelectedPoints |= 1<<V; + else + m_SelectedPoints = 1<<V; + s_Moved = true; + } + } + } + else + Graphics()->SetColor(1,0,0,1); + + IGraphics::CQuadItem QuadItem(px, py, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); +} + +void CEditor::DoQuadEnvelopes(const array<CQuad> &lQuads, int TexID) +{ + int Num = lQuads.size(); + CEnvelope **apEnvelope = new CEnvelope*[Num]; + mem_zero(apEnvelope, sizeof(CEnvelope*)*Num); + for(int i = 0; i < Num; i++) + { + if((m_ShowEnvelopePreview == 1 && lQuads[i].m_PosEnv == m_SelectedEnvelope) || m_ShowEnvelopePreview == 2) + if(lQuads[i].m_PosEnv >= 0 && lQuads[i].m_PosEnv < m_Map.m_lEnvelopes.size()) + apEnvelope[i] = m_Map.m_lEnvelopes[lQuads[i].m_PosEnv]; + } + + //Draw Lines + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->SetColor(80.0f/255, 150.0f/255, 230.f/255, 0.5f); + for(int j = 0; j < Num; j++) + { + if(!apEnvelope[j]) + continue; + + //QuadParams + const CPoint *pPoints = lQuads[j].m_aPoints; + for(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++) + { + float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); + float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); + vec2 Pos0 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); + + OffsetX = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[0]); + OffsetY = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[1]); + vec2 Pos1 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); + + IGraphics::CLineItem Line = IGraphics::CLineItem(Pos0.x, Pos0.y, Pos1.x, Pos1.y); + Graphics()->LinesDraw(&Line, 1); + } + } + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + Graphics()->LinesEnd(); + + //Draw Quads + Graphics()->TextureSet(TexID); + Graphics()->QuadsBegin(); + + for(int j = 0; j < Num; j++) + { + if(!apEnvelope[j]) + continue; + + //QuadParams + const CPoint *pPoints = lQuads[j].m_aPoints; + + for(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++) + { + //Calc Env Position + float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); + float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); + float Rot = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[2])/360.0f*pi*2; + + //Set Colours + float Alpha = (m_SelectedQuadEnvelope == lQuads[j].m_PosEnv && m_SelectedEnvelopePoint == i) ? 0.65f : 0.35f; + IGraphics::CColorVertex aArray[4] = { + IGraphics::CColorVertex(0, lQuads[j].m_aColors[0].r, lQuads[j].m_aColors[0].g, lQuads[j].m_aColors[0].b, Alpha), + IGraphics::CColorVertex(1, lQuads[j].m_aColors[1].r, lQuads[j].m_aColors[1].g, lQuads[j].m_aColors[1].b, Alpha), + IGraphics::CColorVertex(2, lQuads[j].m_aColors[2].r, lQuads[j].m_aColors[2].g, lQuads[j].m_aColors[2].b, Alpha), + IGraphics::CColorVertex(3, lQuads[j].m_aColors[3].r, lQuads[j].m_aColors[3].g, lQuads[j].m_aColors[3].b, Alpha)}; + Graphics()->SetColorVertex(aArray, 4); + + //Rotation + if(Rot != 0) + { + static CPoint aRotated[4]; + aRotated[0] = lQuads[j].m_aPoints[0]; + aRotated[1] = lQuads[j].m_aPoints[1]; + aRotated[2] = lQuads[j].m_aPoints[2]; + aRotated[3] = lQuads[j].m_aPoints[3]; + pPoints = aRotated; + + Rotate(&lQuads[j].m_aPoints[4], &aRotated[0], Rot); + Rotate(&lQuads[j].m_aPoints[4], &aRotated[1], Rot); + Rotate(&lQuads[j].m_aPoints[4], &aRotated[2], Rot); + Rotate(&lQuads[j].m_aPoints[4], &aRotated[3], Rot); + } + + //Set Texture Coords + Graphics()->QuadsSetSubsetFree( + fx2f(lQuads[j].m_aTexcoords[0].x), fx2f(lQuads[j].m_aTexcoords[0].y), + fx2f(lQuads[j].m_aTexcoords[1].x), fx2f(lQuads[j].m_aTexcoords[1].y), + fx2f(lQuads[j].m_aTexcoords[2].x), fx2f(lQuads[j].m_aTexcoords[2].y), + fx2f(lQuads[j].m_aTexcoords[3].x), fx2f(lQuads[j].m_aTexcoords[3].y) + ); + + //Set Quad Coords & Draw + IGraphics::CFreeformItem Freeform( + fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, + fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, + fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, + fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); + Graphics()->QuadsDrawFreeform(&Freeform, 1); + } + } + Graphics()->QuadsEnd(); + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + + // Draw QuadPoints + for(int j = 0; j < Num; j++) + { + if(!apEnvelope[j]) + continue; + + //QuadParams + for(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++) + DoQuadEnvPoint(&lQuads[j], j, i); + } + Graphics()->QuadsEnd(); + delete[] apEnvelope; +} + +void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) +{ + enum + { + OP_NONE=0, + OP_MOVE, + OP_ROTATE, + }; + + // some basic values + static float s_LastWx; + static float s_LastWy; + static int s_Operation = OP_NONE; + float wx = UI()->MouseWorldX(); + float wy = UI()->MouseWorldY(); + CEnvelope *pEnvelope = m_Map.m_lEnvelopes[pQuad->m_PosEnv]; + void *pID = &pEnvelope->m_lPoints[PIndex]; + static int s_ActQIndex = -1; + + // get pivot + float CenterX = fx2f(pQuad->m_aPoints[4].x)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]); + float CenterY = fx2f(pQuad->m_aPoints[4].y)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]); + + float dx = (CenterX - wx)/m_WorldZoom; + float dy = (CenterY - wy)/m_WorldZoom; + if(dx*dx+dy*dy < 50.0f && UI()->ActiveItem() == 0) + { + UI()->SetHotItem(pID); + s_ActQIndex = QIndex; + } + + bool IgnoreGrid; + if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) + IgnoreGrid = true; + else + IgnoreGrid = false; + + if(UI()->ActiveItem() == pID && s_ActQIndex == QIndex) + { + if(s_Operation == OP_MOVE) + { + if(m_GridActive && !IgnoreGrid) + { + int LineDistance = GetLineDistance(); + + float x = 0.0f; + float y = 0.0f; + if(wx >= 0) + x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + if(wy >= 0) + y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + else + y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); + + pEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x)-pQuad->m_aPoints[4].x; + pEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y)-pQuad->m_aPoints[4].y; + } + else + { + pEnvelope->m_lPoints[PIndex].m_aValues[0] += f2fx(wx-s_LastWx); + pEnvelope->m_lPoints[PIndex].m_aValues[1] += f2fx(wy-s_LastWy); + } + } + else if(s_Operation == OP_ROTATE) + pEnvelope->m_lPoints[PIndex].m_aValues[2] += 10*m_MouseDeltaX; + + s_LastWx = wx; + s_LastWy = wy; + + if(!UI()->MouseButton(0)) + { + m_LockMouse = false; + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + } + else if(UI()->HotItem() == pID && s_ActQIndex == QIndex) + { + ms_pUiGotContext = pID; + + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + m_pTooltip = "Left mouse button to move. Hold ctrl to rotate. Hold alt to ignore grid."; + + if(UI()->MouseButton(0)) + { + if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) + { + m_LockMouse = true; + s_Operation = OP_ROTATE; + } + else + s_Operation = OP_MOVE; + + m_SelectedEnvelopePoint = PIndex; + m_SelectedQuadEnvelope = pQuad->m_PosEnv; + + UI()->SetActiveItem(pID); + if(m_SelectedQuad != QIndex) + m_SelectedPoints = 0; + m_SelectedQuad = QIndex; + s_LastWx = wx; + s_LastWy = wy; + } + else + { + m_SelectedEnvelopePoint = -1; + m_SelectedQuadEnvelope = -1; + } + } + else + Graphics()->SetColor(0.0f, 1.0f, 0.0f, 1.0f); + + IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); + Graphics()->QuadsDraw(&QuadItem, 1); +} + +void CEditor::DoMapEditor(CUIRect View, CUIRect ToolBar) +{ + // render all good stuff + if(!m_ShowPicker) + { + for(int g = 0; g < m_Map.m_lGroups.size(); g++) + {// don't render the front, tele, speedup and switch layer now we will do it later to make them on top of others + if( + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pFrontLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTeleLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSpeedupLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pSwitchLayer || + m_Map.m_lGroups[g] == (CLayerGroup *)m_Map.m_pTuneLayer + ) + continue; + if(m_Map.m_lGroups[g]->m_Visible) + m_Map.m_lGroups[g]->Render(); + //UI()->ClipEnable(&view); + } + + // render the game, tele, speedup, front, tune and switch above everything else + if(m_Map.m_pGameGroup->m_Visible) + { + m_Map.m_pGameGroup->MapScreen(); + for(int i = 0; i < m_Map.m_pGameGroup->m_lLayers.size(); i++) + { + if + ( + m_Map.m_pGameGroup->m_lLayers[i]->m_Visible && + ( + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pGameLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pFrontLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTeleLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSpeedupLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pSwitchLayer || + m_Map.m_pGameGroup->m_lLayers[i] == m_Map.m_pTuneLayer + ) + ) + m_Map.m_pGameGroup->m_lLayers[i]->Render(); + } + } + + CLayerTiles *pT = static_cast<CLayerTiles *>(GetSelectedLayerType(0, LAYERTYPE_TILES)); + if(m_ShowTileInfo && pT && pT->m_Visible && m_ZoomLevel <= 300) + { + GetSelectedGroup()->MapScreen(); + pT->ShowInfo(); + } + } + else + { + // fix aspect ratio of the image in the picker + float Max = min(View.w, View.h); + View.w = View.h = Max; + } + + static void *s_pEditorID = (void *)&s_pEditorID; + int Inside = UI()->MouseInside(&View); + + // fetch mouse position + float wx = UI()->MouseWorldX(); + float wy = UI()->MouseWorldY(); + float mx = UI()->MouseX(); + float my = UI()->MouseY(); + + static float s_StartWx = 0; + static float s_StartWy = 0; + + enum + { + OP_NONE=0, + OP_BRUSH_GRAB, + OP_BRUSH_DRAW, + OP_BRUSH_PAINT, + OP_PAN_WORLD, + OP_PAN_EDITOR, + }; + + // remap the screen so it can display the whole tileset + if(m_ShowPicker) + { + CUIRect Screen = *UI()->Screen(); + float Size = 32.0*16.0f; + float w = Size*(Screen.w/View.w); + float h = Size*(Screen.h/View.h); + float x = -(View.x/Screen.w)*w; + float y = -(View.y/Screen.h)*h; + wx = x+w*mx/Screen.w; + wy = y+h*my/Screen.h; + CLayerTiles *t = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); + if(t) + { + Graphics()->MapScreen(x, y, x+w, y+h); + m_TilesetPicker.m_Image = t->m_Image; + m_TilesetPicker.m_TexID = t->m_TexID; + m_TilesetPicker.Render(); + if(m_ShowTileInfo) + m_TilesetPicker.ShowInfo(); + } + else + { + CLayerQuads *t = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); + if(t) + { + m_QuadsetPicker.m_Image = t->m_Image; + m_QuadsetPicker.m_lQuads[0].m_aPoints[0].x = (int) View.x << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[0].y = (int) View.y << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[1].x = (int) (View.x+View.w) << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[1].y = (int) View.y << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[2].x = (int) View.x << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[2].y = (int) (View.y+View.h) << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[3].x = (int) (View.x+View.w) << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[3].y = (int) (View.y+View.h) << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[4].x = (int) (View.x+View.w/2) << 10; + m_QuadsetPicker.m_lQuads[0].m_aPoints[4].y = (int) (View.y+View.h/2) << 10; + m_QuadsetPicker.Render(); + } + } + } + + static int s_Operation = OP_NONE; + + // draw layer borders + CLayer *pEditLayers[16]; + int NumEditLayers = 0; + NumEditLayers = 0; + + if(m_ShowPicker && GetSelectedLayer(0) && GetSelectedLayer(0)->m_Type == LAYERTYPE_TILES) + { + pEditLayers[0] = &m_TilesetPicker; + NumEditLayers++; + } + else if (m_ShowPicker) + { + pEditLayers[0] = &m_QuadsetPicker; + NumEditLayers++; + } + else + { + pEditLayers[0] = GetSelectedLayer(0); + if(pEditLayers[0]) + NumEditLayers++; + + CLayerGroup *g = GetSelectedGroup(); + if(g) + { + g->MapScreen(); + + RenderGrid(g); + + for(int i = 0; i < NumEditLayers; i++) + { + if(pEditLayers[i]->m_Type != LAYERTYPE_TILES) + continue; + + float w, h; + pEditLayers[i]->GetSize(&w, &h); + + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(0, 0, w, 0), + IGraphics::CLineItem(w, 0, w, h), + IGraphics::CLineItem(w, h, 0, h), + IGraphics::CLineItem(0, h, 0, 0)}; + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(Array, 4); + Graphics()->LinesEnd(); + } + } + } + + if(Inside) + { + UI()->SetHotItem(s_pEditorID); + + // do global operations like pan and zoom + if(UI()->ActiveItem() == 0 && (UI()->MouseButton(0) || UI()->MouseButton(2))) + { + s_StartWx = wx; + s_StartWy = wy; + + if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL) || UI()->MouseButton(2)) + { + if(Input()->KeyPressed(KEY_LSHIFT)) + s_Operation = OP_PAN_EDITOR; + else + s_Operation = OP_PAN_WORLD; + UI()->SetActiveItem(s_pEditorID); + } + else + s_Operation = OP_NONE; + } + + // brush editing + if(UI()->HotItem() == s_pEditorID) + { + if(m_Brush.IsEmpty()) + m_pTooltip = "Use left mouse button to drag and create a brush."; + else + m_pTooltip = "Use left mouse button to paint with the brush. Right button clears the brush."; + + if(UI()->ActiveItem() == s_pEditorID) + { + CUIRect r; + r.x = s_StartWx; + r.y = s_StartWy; + r.w = wx-s_StartWx; + r.h = wy-s_StartWy; + if(r.w < 0) + { + r.x += r.w; + r.w = -r.w; + } + + if(r.h < 0) + { + r.y += r.h; + r.h = -r.h; + } + + if(s_Operation == OP_BRUSH_DRAW) + { + if(!m_Brush.IsEmpty()) + { + // draw with brush + for(int k = 0; k < NumEditLayers; k++) + { + if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type) + pEditLayers[k]->BrushDraw(m_Brush.m_lLayers[0], wx, wy); + } + } + } + else if(s_Operation == OP_BRUSH_GRAB) + { + if(!UI()->MouseButton(0)) + { + // grab brush + char aBuf[256]; + str_format(aBuf, sizeof(aBuf),"grabbing %f %f %f %f", r.x, r.y, r.w, r.h); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); + + // TODO: do all layers + int Grabs = 0; + for(int k = 0; k < NumEditLayers; k++) + Grabs += pEditLayers[k]->BrushGrab(&m_Brush, r); + if(Grabs == 0) + m_Brush.Clear(); + } + else + { + //editor.map.groups[selected_group]->mapscreen(); + for(int k = 0; k < NumEditLayers; k++) + pEditLayers[k]->BrushSelecting(r); + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + } + } + else if(s_Operation == OP_BRUSH_PAINT) + { + if(!UI()->MouseButton(0)) + { + for(int k = 0; k < NumEditLayers; k++) + pEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[0], r); + } + else + { + //editor.map.groups[selected_group]->mapscreen(); + for(int k = 0; k < NumEditLayers; k++) + pEditLayers[k]->BrushSelecting(r); + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + } + } + } + else + { + if(UI()->MouseButton(1)) + m_Brush.Clear(); + + if(UI()->MouseButton(0) && s_Operation == OP_NONE) + { + UI()->SetActiveItem(s_pEditorID); + + if(m_Brush.IsEmpty()) + s_Operation = OP_BRUSH_GRAB; + else + { + s_Operation = OP_BRUSH_DRAW; + for(int k = 0; k < NumEditLayers; k++) + { + if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type) + pEditLayers[k]->BrushPlace(m_Brush.m_lLayers[0], wx, wy); + } + + } + + CLayerTiles *pLayer = (CLayerTiles*)GetSelectedLayerType(0, LAYERTYPE_TILES); + if((Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && pLayer) + s_Operation = OP_BRUSH_PAINT; + } + + if(!m_Brush.IsEmpty()) + { + m_Brush.m_OffsetX = -(int)wx; + m_Brush.m_OffsetY = -(int)wy; + for(int i = 0; i < m_Brush.m_lLayers.size(); i++) + { + if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) + { + m_Brush.m_OffsetX = -(int)(wx/32.0f)*32; + m_Brush.m_OffsetY = -(int)(wy/32.0f)*32; + break; + } + } + + CLayerGroup *g = GetSelectedGroup(); + if(g) + { + m_Brush.m_OffsetX += g->m_OffsetX; + m_Brush.m_OffsetY += g->m_OffsetY; + m_Brush.m_ParallaxX = g->m_ParallaxX; + m_Brush.m_ParallaxY = g->m_ParallaxY; + m_Brush.Render(); + float w, h; + m_Brush.GetSize(&w, &h); + + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(0, 0, w, 0), + IGraphics::CLineItem(w, 0, w, h), + IGraphics::CLineItem(w, h, 0, h), + IGraphics::CLineItem(0, h, 0, 0)}; + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(Array, 4); + Graphics()->LinesEnd(); + } + } + } + } + + // quad & sound editing + { + if(!m_ShowPicker && m_Brush.IsEmpty()) + { + // fetch layers + CLayerGroup *g = GetSelectedGroup(); + if(g) + g->MapScreen(); + + for(int k = 0; k < NumEditLayers; k++) + { + if(pEditLayers[k]->m_Type == LAYERTYPE_QUADS) + { + CLayerQuads *pLayer = (CLayerQuads *)pEditLayers[k]; + + if(!m_ShowEnvelopePreview) + m_ShowEnvelopePreview = 2; + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + for(int i = 0; i < pLayer->m_lQuads.size(); i++) + { + for(int v = 0; v < 4; v++) + DoQuadPoint(&pLayer->m_lQuads[i], i, v); + + DoQuad(&pLayer->m_lQuads[i], i); + } + Graphics()->QuadsEnd(); + } + + if(pEditLayers[k]->m_Type == LAYERTYPE_SOUNDS) + { + CLayerSounds *pLayer = (CLayerSounds *)pEditLayers[k]; + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + for(int i = 0; i < pLayer->m_lSources.size(); i++) + { + DoSoundSource(&pLayer->m_lSources[i], i); + } + Graphics()->QuadsEnd(); + } + } + + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + } + } + + // do panning + if(UI()->ActiveItem() == s_pEditorID) + { + if(s_Operation == OP_PAN_WORLD) + { + m_WorldOffsetX -= m_MouseDeltaX*m_WorldZoom; + m_WorldOffsetY -= m_MouseDeltaY*m_WorldZoom; + } + else if(s_Operation == OP_PAN_EDITOR) + { + m_EditorOffsetX -= m_MouseDeltaX*m_WorldZoom; + m_EditorOffsetY -= m_MouseDeltaY*m_WorldZoom; + } + + // release mouse + if(!UI()->MouseButton(0)) + { + if(s_Operation == OP_BRUSH_DRAW || s_Operation == OP_BRUSH_PAINT) + m_Map.m_UndoModified++; + + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + + + } + else if(UI()->ActiveItem() == s_pEditorID) + { + // release mouse + if(!UI()->MouseButton(0)) + { + s_Operation = OP_NONE; + UI()->SetActiveItem(0); + } + } + + if(!m_ShowPicker && GetSelectedGroup() && GetSelectedGroup()->m_UseClipping) + { + CLayerGroup *g = m_Map.m_pGameGroup; + g->MapScreen(); + + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + + CUIRect r; + r.x = GetSelectedGroup()->m_ClipX; + r.y = GetSelectedGroup()->m_ClipY; + r.w = GetSelectedGroup()->m_ClipW; + r.h = GetSelectedGroup()->m_ClipH; + + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), + IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), + IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), + IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; + Graphics()->SetColor(1,0,0,1); + Graphics()->LinesDraw(Array, 4); + + Graphics()->LinesEnd(); + } + + // render screen sizes + if(m_ProofBorders && !m_ShowPicker) + { + CLayerGroup *g = m_Map.m_pGameGroup; + g->MapScreen(); + + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + + float aLastPoints[4]; + float Start = 1.0f; //9.0f/16.0f; + float End = 16.0f/9.0f; + const int NumSteps = 20; + for(int i = 0; i <= NumSteps; i++) + { + float aPoints[4]; + float Aspect = Start + (End-Start)*(i/(float)NumSteps); + + RenderTools()->MapscreenToWorld( + m_WorldOffsetX, m_WorldOffsetY, + 1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints); + + if(i == 0) + { + IGraphics::CLineItem Array[2] = { + IGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[2], aPoints[1]), + IGraphics::CLineItem(aPoints[0], aPoints[3], aPoints[2], aPoints[3])}; + Graphics()->LinesDraw(Array, 2); + } + + if(i != 0) + { + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(aPoints[0], aPoints[1], aLastPoints[0], aLastPoints[1]), + IGraphics::CLineItem(aPoints[2], aPoints[1], aLastPoints[2], aLastPoints[1]), + IGraphics::CLineItem(aPoints[0], aPoints[3], aLastPoints[0], aLastPoints[3]), + IGraphics::CLineItem(aPoints[2], aPoints[3], aLastPoints[2], aLastPoints[3])}; + Graphics()->LinesDraw(Array, 4); + } + + if(i == NumSteps) + { + IGraphics::CLineItem Array[2] = { + IGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[0], aPoints[3]), + IGraphics::CLineItem(aPoints[2], aPoints[1], aPoints[2], aPoints[3])}; + Graphics()->LinesDraw(Array, 2); + } + + mem_copy(aLastPoints, aPoints, sizeof(aPoints)); + } + + if(1) + { + Graphics()->SetColor(1,0,0,1); + for(int i = 0; i < 2; i++) + { + float aPoints[4]; + float aAspects[] = {4.0f/3.0f, 16.0f/10.0f, 5.0f/4.0f, 16.0f/9.0f}; + float Aspect = aAspects[i]; + + RenderTools()->MapscreenToWorld( + m_WorldOffsetX, m_WorldOffsetY, + 1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints); + + CUIRect r; + r.x = aPoints[0]; + r.y = aPoints[1]; + r.w = aPoints[2]-aPoints[0]; + r.h = aPoints[3]-aPoints[1]; + + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), + IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), + IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), + IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; + Graphics()->LinesDraw(Array, 4); + Graphics()->SetColor(0,1,0,1); + } + } + + Graphics()->LinesEnd(); + } + + if (!m_ShowPicker && m_ShowTileInfo && m_ShowEnvelopePreview != 0 && GetSelectedLayer(0) && GetSelectedLayer(0)->m_Type == LAYERTYPE_QUADS) + { + GetSelectedGroup()->MapScreen(); + + CLayerQuads *pLayer = (CLayerQuads*)GetSelectedLayer(0); + int TexID = -1; + if(pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size()) + TexID = m_Map.m_lImages[pLayer->m_Image]->m_TexID; + + DoQuadEnvelopes(pLayer->m_lQuads, TexID); + m_ShowEnvelopePreview = 0; + } + + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + //UI()->ClipDisable(); +} + + +int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int *pNewVal, vec4 color) +{ + int Change = -1; + + for(int i = 0; pProps[i].m_pName; i++) + { + CUIRect Slot; + pToolBox->HSplitTop(13.0f, &Slot, pToolBox); + CUIRect Label, Shifter; + Slot.VSplitMid(&Label, &Shifter); + Shifter.HMargin(1.0f, &Shifter); + UI()->DoLabel(&Label, pProps[i].m_pName, 10.0f, -1, -1); + + if(pProps[i].m_Type == PROPTYPE_INT_STEP) + { + CUIRect Inc, Dec; + char aBuf[64]; + + Shifter.VSplitRight(10.0f, &Shifter, &Inc); + Shifter.VSplitLeft(10.0f, &Dec, &Shifter); + str_format(aBuf, sizeof(aBuf),"%d", pProps[i].m_Value); + RenderTools()->DrawUIRect(&Shifter, color, 0, 0.0f); + UI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1); + + if(DoButton_ButtonDec(&pIDs[i], 0, 0, &Dec, 0, "Decrease")) + { + *pNewVal = pProps[i].m_Value-1; + Change = i; + } + if(DoButton_ButtonInc(((char *)&pIDs[i])+1, 0, 0, &Inc, 0, "Increase")) + { + *pNewVal = pProps[i].m_Value+1; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_BOOL) + { + CUIRect No, Yes; + Shifter.VSplitMid(&No, &Yes); + if(DoButton_ButtonDec(&pIDs[i], "No", !pProps[i].m_Value, &No, 0, "")) + { + *pNewVal = 0; + Change = i; + } + if(DoButton_ButtonInc(((char *)&pIDs[i])+1, "Yes", pProps[i].m_Value, &Yes, 0, "")) + { + *pNewVal = 1; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_INT_SCROLL) + { + int NewValue = UiDoValueSelector(&pIDs[i], &Shifter, "", pProps[i].m_Value, pProps[i].m_Min, pProps[i].m_Max, 1, 1.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise. Rightclick to edit as text."); + if(NewValue != pProps[i].m_Value) + { + *pNewVal = NewValue; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_ANGLE_SCROLL) + { + bool Shift = Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT); + int Value = pProps[i].m_Value; + if (!Shift && UI()->MouseButton(0) && UI()->ActiveItem() == &pIDs[i]) + Value = (Value / 45) * 45; + int NewValue = UiDoValueSelector(&pIDs[i], &Shifter, "", Value, pProps[i].m_Min, Shift ? pProps[i].m_Max : 315, Shift ? 1 : 45, Shift ? 1.0f : 10.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise. Rightclick to edit as text."); + if(NewValue != pProps[i].m_Value) + { + *pNewVal = NewValue; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_COLOR) + { + static const char *s_paTexts[4] = {"R", "G", "B", "A"}; + static int s_aShift[] = {24, 16, 8, 0}; + int NewColor = 0; + + // extra space + CUIRect ColorBox, ColorSlots; + + pToolBox->HSplitTop(3.0f*13.0f, &Slot, pToolBox); + Slot.VSplitMid(&ColorBox, &ColorSlots); + ColorBox.HMargin(1.0f, &ColorBox); + ColorBox.VMargin(6.0f, &ColorBox); + + for(int c = 0; c < 4; c++) + { + int v = (pProps[i].m_Value >> s_aShift[c])&0xff; + NewColor |= UiDoValueSelector(((char *)&pIDs[i])+c, &Shifter, s_paTexts[c], v, 0, 255, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.")<<s_aShift[c]; + + if(c != 3) + { + ColorSlots.HSplitTop(13.0f, &Shifter, &ColorSlots); + Shifter.HMargin(1.0f, &Shifter); + } + } + + // hex + pToolBox->HSplitTop(13.0f, &Slot, pToolBox); + Slot.VSplitMid(0x0, &Shifter); + Shifter.HMargin(1.0f, &Shifter); + + int NewColorHex = pProps[i].m_Value&0xff; + NewColorHex |= UiDoValueSelector(((char *)&pIDs[i]-1), &Shifter, "", (pProps[i].m_Value >> 8)&0xFFFFFF, 0, 0xFFFFFF, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise. Rightclick to edit as text.", false, true) << 8; + + // color picker + vec4 Color = vec4( + ((pProps[i].m_Value >> s_aShift[0])&0xff)/255.0f, + ((pProps[i].m_Value >> s_aShift[1])&0xff)/255.0f, + ((pProps[i].m_Value >> s_aShift[2])&0xff)/255.0f, + 1.0f); + + static int s_ColorPicker, s_ColorPickerID; + if(DoButton_ColorPicker(&s_ColorPicker, &ColorBox, &Color)) + { + ms_PickerColor = RgbToHsv(vec3(Color.r, Color.g, Color.b)); + UiInvokePopupMenu(&s_ColorPickerID, 0, UI()->MouseX(), UI()->MouseY(), 180, 150, PopupColorPicker); + } + + if(UI()->HotItem() == &ms_SVPicker || UI()->HotItem() == &ms_HuePicker) + { + vec3 c = HsvToRgb(ms_PickerColor); + NewColor = ((int)(c.r * 255.0f)&0xff) << 24 | ((int)(c.g * 255.0f)&0xff) << 16 | ((int)(c.b * 255.0f)&0xff) << 8 | (pProps[i].m_Value&0xff); + } + + // + if(NewColor != pProps[i].m_Value) + { + *pNewVal = NewColor; + Change = i; + } + else if(NewColorHex != pProps[i].m_Value) + { + *pNewVal = NewColorHex; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_IMAGE) + { + char aBuf[64]; + if(pProps[i].m_Value < 0) + str_copy(aBuf, "None", sizeof(aBuf)); + else + str_format(aBuf, sizeof(aBuf),"%s", m_Map.m_lImages[pProps[i].m_Value]->m_aName); + + if(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0)) + PopupSelectImageInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY()); + + int r = PopupSelectImageResult(); + if(r >= -1) + { + *pNewVal = r; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_SHIFT) + { + CUIRect Left, Right, Up, Down; + Shifter.VSplitMid(&Left, &Up); + Left.VSplitRight(1.0f, &Left, 0); + Up.VSplitLeft(1.0f, 0, &Up); + Left.VSplitLeft(10.0f, &Left, &Shifter); + Shifter.VSplitRight(10.0f, &Shifter, &Right); + RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); + UI()->DoLabel(&Shifter, "X", 10.0f, 0, -1); + Up.VSplitLeft(10.0f, &Up, &Shifter); + Shifter.VSplitRight(10.0f, &Shifter, &Down); + RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); + UI()->DoLabel(&Shifter, "Y", 10.0f, 0, -1); + if(DoButton_ButtonDec(&pIDs[i], "-", 0, &Left, 0, "Left")) + { + *pNewVal = 1; + Change = i; + } + if(DoButton_ButtonInc(((char *)&pIDs[i])+3, "+", 0, &Right, 0, "Right")) + { + *pNewVal = 2; + Change = i; + } + if(DoButton_ButtonDec(((char *)&pIDs[i])+1, "-", 0, &Up, 0, "Up")) + { + *pNewVal = 4; + Change = i; + } + if(DoButton_ButtonInc(((char *)&pIDs[i])+2, "+", 0, &Down, 0, "Down")) + { + *pNewVal = 8; + Change = i; + } + } + else if(pProps[i].m_Type == PROPTYPE_SOUND) + { + char aBuf[64]; + if(pProps[i].m_Value < 0) + str_copy(aBuf, "None", sizeof(aBuf)); + else + str_format(aBuf, sizeof(aBuf),"%s", m_Map.m_lSounds[pProps[i].m_Value]->m_aName); + + if(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0)) + PopupSelectSoundInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY()); + + int r = PopupSelectSoundResult(); + if(r >= -1) + { + *pNewVal = r; + Change = i; + } + } + } + + return Change; +} + +void CEditor::RenderLayers(CUIRect ToolBox, CUIRect ToolBar, CUIRect View) +{ + CUIRect LayersBox = ToolBox; + + if(!m_GuiActive) + return; + + CUIRect Slot, Button; + char aBuf[64]; + + float LayersHeight = 12.0f; // Height of AddGroup button + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + + for(int g = 0; g < m_Map.m_lGroups.size(); g++) + { + // Each group is 19.0f + // Each layer is 14.0f + LayersHeight += 19.0f; + if(!m_Map.m_lGroups[g]->m_Collapse) + LayersHeight += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f; + } + + float ScrollDifference = LayersHeight - LayersBox.h; + + if(LayersHeight > LayersBox.h) // Do we even need a scrollbar? + { + CUIRect Scroll; + LayersBox.VSplitRight(15.0f, &LayersBox, &Scroll); + LayersBox.VSplitRight(3.0f, &LayersBox, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&LayersBox)) + { + int ScrollNum = (int)((LayersHeight-LayersBox.h)/15.0f)+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + } + } + + float LayerStartAt = ScrollDifference * s_ScrollValue; + if(LayerStartAt < 0.0f) + LayerStartAt = 0.0f; + + float LayerStopAt = LayersHeight - ScrollDifference * (1 - s_ScrollValue); + float LayerCur = 0; + + // render layers + { + for(int g = 0; g < m_Map.m_lGroups.size(); g++) + { + if(LayerCur > LayerStopAt) + break; + else if(LayerCur + m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f < LayerStartAt) + { + LayerCur += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f; + continue; + } + + CUIRect VisibleToggle, SaveCheck; + if(LayerCur >= LayerStartAt) + { + LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); + Slot.VSplitLeft(12, &VisibleToggle, &Slot); + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_Visible, m_Map.m_lGroups[g]->m_Visible?"V":"H", m_Map.m_lGroups[g]->m_Collapse ? 1 : 0, &VisibleToggle, 0, "Toggle group visibility", CUI::CORNER_L)) + m_Map.m_lGroups[g]->m_Visible = !m_Map.m_lGroups[g]->m_Visible; + + Slot.VSplitRight(12.0f, &Slot, &SaveCheck); + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_SaveToMap, "S", m_Map.m_lGroups[g]->m_SaveToMap, &SaveCheck, 0, "Enable/disable group for saving", CUI::CORNER_R)) + if(!m_Map.m_lGroups[g]->m_GameGroup) + m_Map.m_lGroups[g]->m_SaveToMap = !m_Map.m_lGroups[g]->m_SaveToMap; + + str_format(aBuf, sizeof(aBuf),"#%d %s", g, m_Map.m_lGroups[g]->m_aName); + float FontSize = 10.0f; + while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Slot.w) + FontSize--; + if(int Result = DoButton_Ex(&m_Map.m_lGroups[g], aBuf, g==m_SelectedGroup, &Slot, + BUTTON_CONTEXT, m_Map.m_lGroups[g]->m_Collapse ? "Select group. Double click to expand." : "Select group. Double click to collapse.", 0, FontSize)) + { + m_SelectedGroup = g; + m_SelectedLayer = 0; + + static int s_GroupPopupId = 0; + if(Result == 2) + UiInvokePopupMenu(&s_GroupPopupId, 0, UI()->MouseX(), UI()->MouseY(), 145, 230, PopupGroup); + + if(m_Map.m_lGroups[g]->m_lLayers.size() && Input()->MouseDoubleClick()) + m_Map.m_lGroups[g]->m_Collapse ^= 1; + } + LayersBox.HSplitTop(2.0f, &Slot, &LayersBox); + } + LayerCur += 14.0f; + + for(int i = 0; i < m_Map.m_lGroups[g]->m_lLayers.size(); i++) + { + if(LayerCur > LayerStopAt) + break; + else if(LayerCur < LayerStartAt) + { + LayerCur += 14.0f; + continue; + } + + if(m_Map.m_lGroups[g]->m_Collapse) + continue; + + //visible + LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); + Slot.VSplitLeft(12.0f, 0, &Button); + Button.VSplitLeft(15, &VisibleToggle, &Button); + + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible, m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible?"V":"H", 0, &VisibleToggle, 0, "Toggle layer visibility", CUI::CORNER_L)) + m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible = !m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible; + + Button.VSplitRight(12.0f, &Button, &SaveCheck); + if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, "S", m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, &SaveCheck, 0, "Enable/disable layer for saving", CUI::CORNER_R)) + if(m_Map.m_lGroups[g]->m_lLayers[i] != m_Map.m_pGameLayer) + m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap = !m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap; + + if(m_Map.m_lGroups[g]->m_lLayers[i]->m_aName[0]) + str_format(aBuf, sizeof(aBuf), "%s", m_Map.m_lGroups[g]->m_lLayers[i]->m_aName); + else if(m_Map.m_lGroups[g]->m_lLayers[i]->m_Type == LAYERTYPE_TILES) + str_copy(aBuf, "Tiles", sizeof(aBuf)); + else + str_copy(aBuf, "Quads", sizeof(aBuf)); + + float FontSize = 10.0f; + while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Button.w) + FontSize--; + int Checked = g == m_SelectedGroup && i == m_SelectedLayer; + if(m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pGameLayer || + m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pFrontLayer || + m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pSwitchLayer || + m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pTuneLayer || + m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pSpeedupLayer || + m_Map.m_lGroups[g]->m_lLayers[i] == m_Map.m_pTeleLayer) + { + Checked += 6; + } + if(int Result = DoButton_Ex(m_Map.m_lGroups[g]->m_lLayers[i], aBuf, Checked, &Button, + BUTTON_CONTEXT, "Select layer.", 0, FontSize)) + { + m_SelectedLayer = i; + m_SelectedGroup = g; + static int s_LayerPopupID = 0; + if(Result == 2) + UiInvokePopupMenu(&s_LayerPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 260, PopupLayer); + } + + LayerCur += 14.0f; + LayersBox.HSplitTop(2.0f, &Slot, &LayersBox); + } + if(LayerCur > LayerStartAt && LayerCur < LayerStopAt) + LayersBox.HSplitTop(5.0f, &Slot, &LayersBox); + LayerCur += 5.0f; + } + } + + if(LayerCur <= LayerStopAt) + { + LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); + + static int s_NewGroupButton = 0; + if(DoButton_Editor(&s_NewGroupButton, "Add group", 0, &Slot, 0, "Adds a new group")) + { + m_Map.NewGroup(); + m_SelectedGroup = m_Map.m_lGroups.size()-1; + } + } +} + +void CEditor::ReplaceImage(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + CEditorImage ImgInfo(pEditor); + if(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType)) + return; + + CEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage]; + int External = pImg->m_External; + pEditor->Graphics()->UnloadTexture(pImg->m_TexID); + if(pImg->m_pData) + { + mem_free(pImg->m_pData); + pImg->m_pData = 0; + } + *pImg = ImgInfo; + pImg->m_External = External; + pEditor->ExtractName(pFileName, pImg->m_aName, sizeof(pImg->m_aName)); + pImg->m_AutoMapper.Load(pImg->m_aName); + pImg->m_TexID = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); + ImgInfo.m_pData = 0; + pEditor->SortImages(); + for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i) + { + if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, pImg->m_aName)) + pEditor->m_SelectedImage = i; + } + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::AddImage(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + CEditorImage ImgInfo(pEditor); + if(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType)) + return; + + // check if we have that image already + char aBuf[128]; + ExtractName(pFileName, aBuf, sizeof(aBuf)); + for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i) + { + if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf)) + return; + } + + CEditorImage *pImg = new CEditorImage(pEditor); + *pImg = ImgInfo; + pImg->m_TexID = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); + ImgInfo.m_pData = 0; + pImg->m_External = 1; // external by default + str_copy(pImg->m_aName, aBuf, sizeof(pImg->m_aName)); + pImg->m_AutoMapper.Load(pImg->m_aName); + pEditor->m_Map.m_lImages.add(pImg); + pEditor->SortImages(); + if(pEditor->m_SelectedImage > -1 && pEditor->m_SelectedImage < pEditor->m_Map.m_lImages.size()) + { + for(int i = 0; i <= pEditor->m_SelectedImage; ++i) + if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf)) + { + pEditor->m_SelectedImage++; + break; + } + } + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::AddSound(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + + // check if we have that sound already + char aBuf[128]; + ExtractName(pFileName, aBuf, sizeof(aBuf)); + for(int i = 0; i < pEditor->m_Map.m_lSounds.size(); ++i) + { + if(!str_comp(pEditor->m_Map.m_lSounds[i]->m_aName, aBuf)) + return; + } + + // load external + IOHANDLE SoundFile = pEditor->Storage()->OpenFile(pFileName, IOFLAG_READ, StorageType); + if(!SoundFile) + { + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFileName); + return; + } + + // read the whole file into memory + int DataSize = io_length(SoundFile); + + if(DataSize <= 0) + { + io_close(SoundFile); + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFileName); + return; + } + + void *pData = mem_alloc((unsigned) DataSize, 1); + io_read(SoundFile, pData, (unsigned) DataSize); + io_close(SoundFile); + + // load sound + int SoundId = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned) DataSize, true); + if(SoundId == -1) + return; + + // add sound + CEditorSound *pSound = new CEditorSound(pEditor); + pSound->m_SoundID = SoundId; + pSound->m_External = 1; // external by default + pSound->m_DataSize = (unsigned) DataSize; + pSound->m_pData = pData; + str_copy(pSound->m_aName, aBuf, sizeof(pSound->m_aName)); + pEditor->m_Map.m_lSounds.add(pSound); + + if(pEditor->m_SelectedSound > -1 && pEditor->m_SelectedSound < pEditor->m_Map.m_lSounds.size()) + { + for(int i = 0; i <= pEditor->m_SelectedSound; ++i) + if(!str_comp(pEditor->m_Map.m_lSounds[i]->m_aName, aBuf)) + { + pEditor->m_SelectedSound++; + break; + } + } + + pEditor->m_Dialog = DIALOG_NONE; +} + +void CEditor::ReplaceSound(const char *pFileName, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + + // load external + IOHANDLE SoundFile = pEditor->Storage()->OpenFile(pFileName, IOFLAG_READ, StorageType); + if(!SoundFile) + { + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFileName); + return; + } + + // read the whole file into memory + int DataSize = io_length(SoundFile); + + if(DataSize <= 0) + { + io_close(SoundFile); + dbg_msg("sound/opus", "failed to open file. filename='%s'", pFileName); + return; + } + + void *pData = mem_alloc((unsigned) DataSize, 1); + io_read(SoundFile, pData, (unsigned) DataSize); + io_close(SoundFile); + + // + CEditorSound *pSound = pEditor->m_Map.m_lSounds[pEditor->m_SelectedSound]; + int External = pSound->m_External; + + // unload sample + pEditor->Sound()->UnloadSample(pSound->m_SoundID); + if(pSound->m_pData) + { + mem_free(pSound->m_pData); + pSound->m_pData = 0x0; + } + + // replace sound + pSound->m_External = External; + pEditor->ExtractName(pFileName, pSound->m_aName, sizeof(pSound->m_aName)); + pSound->m_SoundID = pEditor->Sound()->LoadOpusFromMem(pData, (unsigned) DataSize, true); + pSound->m_pData = pData; + pSound->m_DataSize = DataSize; + + pEditor->m_Dialog = DIALOG_NONE; +} + + +static int gs_ModifyIndexDeletedIndex; +static void ModifyIndexDeleted(int *pIndex) +{ + if(*pIndex == gs_ModifyIndexDeletedIndex) + *pIndex = -1; + else if(*pIndex > gs_ModifyIndexDeletedIndex) + *pIndex = *pIndex - 1; +} + +int CEditor::PopupImage(CEditor *pEditor, CUIRect View) +{ + static int s_ReplaceButton = 0; + static int s_RemoveButton = 0; + + CUIRect Slot; + View.HSplitTop(2.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + CEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage]; + + static int s_ExternalButton = 0; + if(pImg->m_External) + { + if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Embed", 0, &Slot, 0, "Embeds the image into the map file.")) + { + pImg->m_External = 0; + return 1; + } + } + else + { + if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Make external", 0, &Slot, 0, "Removes the image from the map file.")) + { + pImg->m_External = 1; + return 1; + } + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_ReplaceButton, "Replace", 0, &Slot, 0, "Replaces the image with a new one")) + { + pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, "Replace Image", "Replace", "mapres", "", ReplaceImage, pEditor); + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_RemoveButton, "Remove", 0, &Slot, 0, "Removes the image from the map")) + { + delete pImg; + pEditor->m_Map.m_lImages.remove_index(pEditor->m_SelectedImage); + gs_ModifyIndexDeletedIndex = pEditor->m_SelectedImage; + pEditor->m_Map.ModifyImageIndex(ModifyIndexDeleted); + return 1; + } + + return 0; +} + +int CEditor::PopupSound(CEditor *pEditor, CUIRect View) +{ + static int s_ReplaceButton = 0; + static int s_RemoveButton = 0; + + CUIRect Slot; + View.HSplitTop(2.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + CEditorSound *pSound = pEditor->m_Map.m_lSounds[pEditor->m_SelectedSound]; + + static int s_ExternalButton = 0; + if(pSound->m_External) + { + if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Embed", 0, &Slot, 0, "Embeds the sound into the map file.")) + { + pSound->m_External = 0; + return 1; + } + } + else + { + if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Make external", 0, &Slot, 0, "Removes the sound from the map file.")) + { + pSound->m_External = 1; + return 1; + } + } + + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_ReplaceButton, "Replace", 0, &Slot, 0, "Replaces the sound with a new one")) + { + pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_SOUND, "Replace sound", "Replace", "mapres", "", ReplaceSound, pEditor); + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_RemoveButton, "Remove", 0, &Slot, 0, "Removes the sound from the map")) + { + delete pSound; + pEditor->m_Map.m_lSounds.remove_index(pEditor->m_SelectedSound); + gs_ModifyIndexDeletedIndex = pEditor->m_SelectedSound; + pEditor->m_Map.ModifySoundIndex(ModifyIndexDeleted); + return 1; + } + + return 0; +} + +static int CompareImageName(const void *pObject1, const void *pObject2) +{ + CEditorImage *pImage1 = *(CEditorImage**)pObject1; + CEditorImage *pImage2 = *(CEditorImage**)pObject2; + + return str_comp(pImage1->m_aName, pImage2->m_aName); +} + +static int *gs_pSortedIndex = 0; +static void ModifySortedIndex(int *pIndex) +{ + if(*pIndex > -1) + *pIndex = gs_pSortedIndex[*pIndex]; +} + +void CEditor::SortImages() +{ + bool Sorted = true; + for(int i = 1; i < m_Map.m_lImages.size(); i++) + if( str_comp(m_Map.m_lImages[i]->m_aName, m_Map.m_lImages[i-1]->m_aName) < 0 ) + { + Sorted = false; + break; + } + + if(!Sorted) + { + array<CEditorImage*> lTemp = array<CEditorImage*>(m_Map.m_lImages); + gs_pSortedIndex = new int[lTemp.size()]; + + qsort(m_Map.m_lImages.base_ptr(), m_Map.m_lImages.size(), sizeof(CEditorImage*), CompareImageName); + + for(int OldIndex = 0; OldIndex < lTemp.size(); OldIndex++) + for(int NewIndex = 0; NewIndex < m_Map.m_lImages.size(); NewIndex++) + if(lTemp[OldIndex] == m_Map.m_lImages[NewIndex]) + gs_pSortedIndex[OldIndex] = NewIndex; + + m_Map.ModifyImageIndex(ModifySortedIndex); + + delete [] gs_pSortedIndex; + gs_pSortedIndex = 0; + } +} + + +void CEditor::RenderImages(CUIRect ToolBox, CUIRect ToolBar, CUIRect View) +{ + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + float ImagesHeight = 30.0f + 14.0f * m_Map.m_lImages.size() + 27.0f; + float ScrollDifference = ImagesHeight - ToolBox.h; + + if(!m_GuiActive) + return; + + if(ImagesHeight > ToolBox.h) // Do we even need a scrollbar? + { + CUIRect Scroll; + ToolBox.VSplitRight(15.0f, &ToolBox, &Scroll); + ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox)) + { + int ScrollNum = (int)((ImagesHeight-ToolBox.h)/14.0f)+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + } + } + + float ImageStartAt = ScrollDifference * s_ScrollValue; + if(ImageStartAt < 0.0f) + ImageStartAt = 0.0f; + + float ImageStopAt = ImagesHeight - ScrollDifference * (1 - s_ScrollValue); + float ImageCur = 0.0f; + + for(int e = 0; e < 2; e++) // two passes, first embedded, then external + { + CUIRect Slot; + + if(ImageCur > ImageStopAt) + break; + else if(ImageCur >= ImageStartAt) + { + + ToolBox.HSplitTop(15.0f, &Slot, &ToolBox); + if(e == 0) + UI()->DoLabel(&Slot, "Embedded", 12.0f, 0); + else + UI()->DoLabel(&Slot, "External", 12.0f, 0); + } + ImageCur += 15.0f; + + for(int i = 0; i < m_Map.m_lImages.size(); i++) + { + if((e && !m_Map.m_lImages[i]->m_External) || + (!e && m_Map.m_lImages[i]->m_External)) + { + continue; + } + + if(ImageCur > ImageStopAt) + break; + else if(ImageCur < ImageStartAt) + { + ImageCur += 14.0f; + continue; + } + ImageCur += 14.0f; + + char aBuf[128]; + str_copy(aBuf, m_Map.m_lImages[i]->m_aName, sizeof(aBuf)); + ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); + + int Selected = m_SelectedImage == i; + + for(int x = 0; x < m_Map.m_lGroups.size(); ++x) + for(int j = 0; j < m_Map.m_lGroups[x]->m_lLayers.size(); ++j) + if(m_Map.m_lGroups[x]->m_lLayers[j]->m_Type == LAYERTYPE_QUADS) + { + CLayerQuads *pLayer = static_cast<CLayerQuads *>(m_Map.m_lGroups[x]->m_lLayers[j]); + if(pLayer->m_Image == i) + goto done; + } + else if(m_Map.m_lGroups[x]->m_lLayers[j]->m_Type == LAYERTYPE_TILES) + { + CLayerTiles *pLayer = static_cast<CLayerTiles *>(m_Map.m_lGroups[x]->m_lLayers[j]); + if(pLayer->m_Image == i) + goto done; + } + + Selected += 2; // Image is unused + done: + if(Selected < 2 && e == 1) + { + bool found = false; + for(unsigned int k = 0; k < sizeof(vanillaImages) / sizeof(vanillaImages[0]); k++) + { + if(str_comp(m_Map.m_lImages[i]->m_aName, vanillaImages[k]) == 0) + { + found = true; + break; + } + } + if(!found) + Selected += 4; // Image should be embedded + } + + float FontSize = 10.0f; + while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Slot.w) + FontSize--; + + if(int Result = DoButton_Ex(&m_Map.m_lImages[i], aBuf, Selected, &Slot, + BUTTON_CONTEXT, "Select image", 0, FontSize)) + { + m_SelectedImage = i; + + static int s_PopupImageID = 0; + if(Result == 2) + UiInvokePopupMenu(&s_PopupImageID, 0, UI()->MouseX(), UI()->MouseY(), 120, 80, PopupImage); + } + + ToolBox.HSplitTop(2.0f, 0, &ToolBox); + } + + // separator + ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); + ImageCur += 5.0f; + IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2); + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(&LineItem, 1); + Graphics()->LinesEnd(); + } + + // render image + int i = m_SelectedImage; + if(i < m_Map.m_lImages.size()) + { + CUIRect r; + View.Margin(10.0f, &r); + if(r.h < r.w) + r.w = r.h; + else + r.h = r.w; + float Max = (float)(max(m_Map.m_lImages[i]->m_Width, m_Map.m_lImages[i]->m_Height)); + r.w *= m_Map.m_lImages[i]->m_Width/Max; + r.h *= m_Map.m_lImages[i]->m_Height/Max; + Graphics()->TextureSet(m_Map.m_lImages[i]->m_TexID); + Graphics()->BlendNormal(); + Graphics()->WrapClamp(); + Graphics()->QuadsBegin(); + IGraphics::CQuadItem QuadItem(r.x, r.y, r.w, r.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + Graphics()->WrapNormal(); + } + //if(ImageCur + 27.0f > ImageStopAt) + // return; + + CUIRect Slot; + ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); + + // new image + static int s_NewImageButton = 0; + ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); + if(DoButton_Editor(&s_NewImageButton, "Add", 0, &Slot, 0, "Load a new image to use in the map")) + InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, "Add Image", "Add", "mapres", "", AddImage, this); +} + +void CEditor::RenderSounds(CUIRect ToolBox, CUIRect ToolBar, CUIRect View) +{ + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + float SoundsHeight = 30.0f + 14.0f * m_Map.m_lSounds.size() + 27.0f; + float ScrollDifference = SoundsHeight - ToolBox.h; + + if(!m_GuiActive) + return; + + if(SoundsHeight > ToolBox.h) // Do we even need a scrollbar? + { + CUIRect Scroll; + ToolBox.VSplitRight(15.0f, &ToolBox, &Scroll); + ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox)) + { + int ScrollNum = (int)((SoundsHeight-ToolBox.h)/14.0f)+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + } + } + + float SoundStartAt = ScrollDifference * s_ScrollValue; + if(SoundStartAt < 0.0f) + SoundStartAt = 0.0f; + + float SoundStopAt = SoundsHeight - ScrollDifference * (1 - s_ScrollValue); + float SoundCur = 0.0f; + + for(int e = 0; e < 2; e++) // two passes, first embedded, then external + { + CUIRect Slot; + + if(SoundCur > SoundStopAt) + break; + else if(SoundCur >= SoundStartAt) + { + + ToolBox.HSplitTop(15.0f, &Slot, &ToolBox); + if(e == 0) + UI()->DoLabel(&Slot, "Embedded", 12.0f, 0); + else + UI()->DoLabel(&Slot, "External", 12.0f, 0); + } + SoundCur += 15.0f; + + for(int i = 0; i < m_Map.m_lSounds.size(); i++) + { + if((e && !m_Map.m_lSounds[i]->m_External) || + (!e && m_Map.m_lSounds[i]->m_External)) + { + continue; + } + + if(SoundCur > SoundStopAt) + break; + else if(SoundCur < SoundStartAt) + { + SoundCur += 14.0f; + continue; + } + SoundCur += 14.0f; + + char aBuf[128]; + str_copy(aBuf, m_Map.m_lSounds[i]->m_aName, sizeof(aBuf)); + ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); + + + int Selected = m_SelectedSound == i; + for(int x = 0; x < m_Map.m_lGroups.size(); ++x) + for(int j = 0; j < m_Map.m_lGroups[x]->m_lLayers.size(); ++j) + if(m_Map.m_lGroups[x]->m_lLayers[j]->m_Type == LAYERTYPE_SOUNDS) + { + CLayerSounds *pLayer = static_cast<CLayerSounds *>(m_Map.m_lGroups[x]->m_lLayers[j]); + if(pLayer->m_Sound == i) + goto done; + } + + Selected += 2; // Sound is unused + done: + if(Selected < 2 && e == 1) + Selected += 4; // Sound should be embedded + + float FontSize = 10.0f; + while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Slot.w) + FontSize--; + + if(int Result = DoButton_Ex(&m_Map.m_lSounds[i], aBuf, Selected, &Slot, + BUTTON_CONTEXT, "Select sound", 0, FontSize)) + { + m_SelectedSound = i; + + static int s_PopupSoundID = 0; + if(Result == 2) + UiInvokePopupMenu(&s_PopupSoundID, 0, UI()->MouseX(), UI()->MouseY(), 120, 80, PopupSound); + } + + ToolBox.HSplitTop(2.0f, 0, &ToolBox); + } + + // separator + ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); + SoundCur += 5.0f; + IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2); + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(&LineItem, 1); + Graphics()->LinesEnd(); + } + + CUIRect Slot; + ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); + + // new Sound + static int s_NewSoundButton = 0; + ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); + if(DoButton_Editor(&s_NewSoundButton, "Add", 0, &Slot, 0, "Load a new sound to use in the map")) + InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_SOUND, "Add Sound", "Add", "mapres", "", AddSound, this); +} + + +static int EditorListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) +{ + CEditor *pEditor = (CEditor*)pUser; + int Length = str_length(pName); + if((pName[0] == '.' && (pName[1] == 0 || + (pName[1] == '.' && pName[2] == 0 && (!str_comp(pEditor->m_pFileDialogPath, "maps") || !str_comp(pEditor->m_pFileDialogPath, "mapres"))))) || + (!IsDir && ((pEditor->m_FileDialogFileType == CEditor::FILETYPE_MAP && (Length < 4 || str_comp(pName+Length-4, ".map"))) || + (pEditor->m_FileDialogFileType == CEditor::FILETYPE_IMG && (Length < 4 || str_comp(pName+Length-4, ".png"))) || + (pEditor->m_FileDialogFileType == CEditor::FILETYPE_SOUND && (Length < 5 || str_comp(pName+Length-5, ".opus")))))) + return 0; + + CEditor::CFilelistItem Item; + str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename)); + if(IsDir) + str_format(Item.m_aName, sizeof(Item.m_aName), "%s/", pName); + else + { + if(pEditor->m_FileDialogFileType == CEditor::FILETYPE_SOUND) + str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-4)); + else + str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-3)); + } + Item.m_IsDir = IsDir != 0; + Item.m_IsLink = false; + Item.m_StorageType = StorageType; + pEditor->m_FileList.add(Item); + + return 0; +} + +void CEditor::AddFileDialogEntry(int Index, CUIRect *pView) +{ + m_FilesCur++; + if(m_FilesCur-1 < m_FilesStartAt || m_FilesCur >= m_FilesStopAt) + return; + + CUIRect Button, FileIcon; + pView->HSplitTop(15.0f, &Button, pView); + pView->HSplitTop(2.0f, 0, pView); + Button.VSplitLeft(Button.h, &FileIcon, &Button); + Button.VSplitLeft(5.0f, 0, &Button); + + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_FILEICONS].m_Id); + Graphics()->QuadsBegin(); + RenderTools()->SelectSprite(m_FileList[Index].m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_MAP2); + IGraphics::CQuadItem QuadItem(FileIcon.x, FileIcon.y, FileIcon.w, FileIcon.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + + if(DoButton_File(&m_FileList[Index], m_FileList[Index].m_aName, m_FilesSelectedIndex == Index, &Button, 0, 0)) + { + if(!m_FileList[Index].m_IsDir) + str_copy(m_aFileDialogFileName, m_FileList[Index].m_aFilename, sizeof(m_aFileDialogFileName)); + else + m_aFileDialogFileName[0] = 0; + m_FilesSelectedIndex = Index; + m_FilePreviewImage = 0; + + if(Input()->MouseDoubleClick()) + m_aFileDialogActivate = true; + } +} + +void CEditor::RenderFileDialog() +{ + // GUI coordsys + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + CUIRect View = *UI()->Screen(); + CUIRect Preview; + float Width = View.w, Height = View.h; + + RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.25f), 0, 0); + View.VMargin(150.0f, &View); + View.HMargin(50.0f, &View); + RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.75f), CUI::CORNER_ALL, 5.0f); + View.Margin(10.0f, &View); + + CUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll, PathBox; + View.HSplitTop(18.0f, &Title, &View); + View.HSplitTop(5.0f, 0, &View); // some spacing + View.HSplitBottom(14.0f, &View, &ButtonBar); + View.HSplitBottom(10.0f, &View, 0); // some spacing + View.HSplitBottom(14.0f, &View, &PathBox); + View.HSplitBottom(5.0f, &View, 0); // some spacing + View.HSplitBottom(14.0f, &View, &FileBox); + FileBox.VSplitLeft(55.0f, &FileBoxLabel, &FileBox); + View.HSplitBottom(10.0f, &View, 0); // some spacing + if (m_FileDialogFileType == CEditor::FILETYPE_IMG) + View.VSplitMid(&View, &Preview); + View.VSplitRight(15.0f, &View, &Scroll); + + // title + RenderTools()->DrawUIRect(&Title, vec4(1, 1, 1, 0.25f), CUI::CORNER_ALL, 4.0f); + Title.VMargin(10.0f, &Title); + UI()->DoLabel(&Title, m_pFileDialogTitle, 12.0f, -1, -1); + + // pathbox + char aPath[128], aBuf[128]; + if(m_FilesSelectedIndex != -1) + Storage()->GetCompletePath(m_FileList[m_FilesSelectedIndex].m_StorageType, m_pFileDialogPath, aPath, sizeof(aPath)); + else + aPath[0] = 0; + str_format(aBuf, sizeof(aBuf), "Current path: %s", aPath); + UI()->DoLabel(&PathBox, aBuf, 10.0f, -1, -1); + + // filebox + if(m_FileDialogStorageType == IStorage::TYPE_SAVE) + { + static float s_FileBoxID = 0; + UI()->DoLabel(&FileBoxLabel, "Filename:", 10.0f, -1, -1); + if(DoEditBox(&s_FileBoxID, &FileBox, m_aFileDialogFileName, sizeof(m_aFileDialogFileName), 10.0f, &s_FileBoxID)) + { + // remove '/' and '\' + for(int i = 0; m_aFileDialogFileName[i]; ++i) + if(m_aFileDialogFileName[i] == '/' || m_aFileDialogFileName[i] == '\\') + str_copy(&m_aFileDialogFileName[i], &m_aFileDialogFileName[i+1], (int)(sizeof(m_aFileDialogFileName))-i); + m_FilesSelectedIndex = -1; + } + } + + int Num = (int)(View.h/17.0f)+1; + static int ScrollBar = 0; + Scroll.HMargin(5.0f, &Scroll); + m_FileDialogScrollValue = UiDoScrollbarV(&ScrollBar, &Scroll, m_FileDialogScrollValue); + + int ScrollNum = m_FileList.size()-Num+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + m_FileDialogScrollValue -= 3.0f/ScrollNum; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + m_FileDialogScrollValue += 3.0f/ScrollNum; + } + else + ScrollNum = 0; + + if(m_FilesSelectedIndex > -1) + { + for(int i = 0; i < Input()->NumEvents(); i++) + { + int NewIndex = -1; + if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) + { + if(Input()->GetEvent(i).m_Key == KEY_DOWN) NewIndex = m_FilesSelectedIndex + 1; + if(Input()->GetEvent(i).m_Key == KEY_UP) NewIndex = m_FilesSelectedIndex - 1; + } + if(NewIndex > -1 && NewIndex < m_FileList.size()) + { + //scroll + float IndexY = View.y - m_FileDialogScrollValue*ScrollNum*17.0f + NewIndex*17.0f; + int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+17.0f ? 1 : 0; + if(Scroll) + { + if(Scroll < 0) + m_FileDialogScrollValue = ((float)(NewIndex)+0.5f)/ScrollNum; + else + m_FileDialogScrollValue = ((float)(NewIndex-Num)+2.5f)/ScrollNum; + } + + if(!m_FileList[NewIndex].m_IsDir) + str_copy(m_aFileDialogFileName, m_FileList[NewIndex].m_aFilename, sizeof(m_aFileDialogFileName)); + else + m_aFileDialogFileName[0] = 0; + m_FilesSelectedIndex = NewIndex; + m_FilePreviewImage = 0; + } + } + + if (m_FileDialogFileType == CEditor::FILETYPE_IMG && m_FilePreviewImage == 0 && m_FilesSelectedIndex > -1) + { + int Length = str_length(m_FileList[m_FilesSelectedIndex].m_aFilename); + if (Length >= 4 && !str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename+Length-4, ".png")) + { + char aBuffer[1024]; + str_format(aBuffer, sizeof(aBuffer), "%s/%s", m_pFileDialogPath, m_FileList[m_FilesSelectedIndex].m_aFilename); + + if(Graphics()->LoadPNG(&m_FilePreviewImageInfo, aBuffer, IStorage::TYPE_ALL)) + { + m_FilePreviewImage = Graphics()->LoadTextureRaw(m_FilePreviewImageInfo.m_Width, m_FilePreviewImageInfo.m_Height, m_FilePreviewImageInfo.m_Format, m_FilePreviewImageInfo.m_pData, m_FilePreviewImageInfo.m_Format, IGraphics::TEXLOAD_NORESAMPLE); + mem_free(m_FilePreviewImageInfo.m_pData); + } + } + } + if (m_FilePreviewImage) + { + int w = m_FilePreviewImageInfo.m_Width; + int h = m_FilePreviewImageInfo.m_Height; + if (m_FilePreviewImageInfo.m_Width > Preview.w) + { + h = m_FilePreviewImageInfo.m_Height * Preview.w / m_FilePreviewImageInfo.m_Width; + w = Preview.w; + } + if (h > Preview.h) + { + w = w * Preview.h / h, + h = Preview.h; + } + + Graphics()->TextureSet(m_FilePreviewImage); + Graphics()->BlendNormal(); + Graphics()->QuadsBegin(); + IGraphics::CQuadItem QuadItem(Preview.x, Preview.y, w, h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + } + + for(int i = 0; i < Input()->NumEvents(); i++) + { + if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) + { + if(Input()->GetEvent(i).m_Key == KEY_RETURN || Input()->GetEvent(i).m_Key == KEY_KP_ENTER) + m_aFileDialogActivate = true; + } + } + + if(m_FileDialogScrollValue < 0) m_FileDialogScrollValue = 0; + if(m_FileDialogScrollValue > 1) m_FileDialogScrollValue = 1; + + m_FilesStartAt = (int)(ScrollNum*m_FileDialogScrollValue); + if(m_FilesStartAt < 0) + m_FilesStartAt = 0; + + m_FilesStopAt = m_FilesStartAt+Num; + + m_FilesCur = 0; + + // set clipping + UI()->ClipEnable(&View); + + for(int i = 0; i < m_FileList.size(); i++) + AddFileDialogEntry(i, &View); + + // disable clipping again + UI()->ClipDisable(); + + // the buttons + static int s_OkButton = 0; + static int s_CancelButton = 0; + static int s_NewFolderButton = 0; + static int s_MapInfoButton = 0; + + CUIRect Button; + ButtonBar.VSplitRight(50.0f, &ButtonBar, &Button); + bool IsDir = m_FilesSelectedIndex >= 0 && m_FileList[m_FilesSelectedIndex].m_IsDir; + if(DoButton_Editor(&s_OkButton, IsDir ? "Open" : m_pFileDialogButtonText, 0, &Button, 0, 0) || m_aFileDialogActivate) + { + m_aFileDialogActivate = false; + if(IsDir) // folder + { + if(str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename, "..") == 0) // parent folder + { + if(fs_parent_dir(m_pFileDialogPath)) + m_pFileDialogPath = m_aFileDialogCurrentFolder; // leave the link + } + else // sub folder + { + if(m_FileList[m_FilesSelectedIndex].m_IsLink) + { + m_pFileDialogPath = m_aFileDialogCurrentLink; // follow the link + str_copy(m_aFileDialogCurrentLink, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogCurrentLink)); + } + else + { + char aTemp[MAX_PATH_LENGTH]; + str_copy(aTemp, m_pFileDialogPath, sizeof(aTemp)); + str_format(m_pFileDialogPath, MAX_PATH_LENGTH, "%s/%s", aTemp, m_FileList[m_FilesSelectedIndex].m_aFilename); + } + } + FilelistPopulate(!str_comp(m_pFileDialogPath, "maps") || !str_comp(m_pFileDialogPath, "mapres") ? m_FileDialogStorageType : + m_FileList[m_FilesSelectedIndex].m_StorageType); + if(m_FilesSelectedIndex >= 0 && !m_FileList[m_FilesSelectedIndex].m_IsDir) + str_copy(m_aFileDialogFileName, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogFileName)); + else + m_aFileDialogFileName[0] = 0; + } + else // file + { + str_format(m_aFileSaveName, sizeof(m_aFileSaveName), "%s/%s", m_pFileDialogPath, m_aFileDialogFileName); + if(!str_comp(m_pFileDialogButtonText, "Save")) + { + IOHANDLE File = Storage()->OpenFile(m_aFileSaveName, IOFLAG_READ, IStorage::TYPE_SAVE); + if(File) + { + io_close(File); + m_PopupEventType = POPEVENT_SAVE; + m_PopupEventActivated = true; + } + else + if(m_pfnFileDialogFunc) + m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); + } + else + if(m_pfnFileDialogFunc) + m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); + } + } + + ButtonBar.VSplitRight(40.0f, &ButtonBar, &Button); + ButtonBar.VSplitRight(50.0f, &ButtonBar, &Button); + if(DoButton_Editor(&s_CancelButton, "Cancel", 0, &Button, 0, 0) || Input()->KeyPressed(KEY_ESCAPE)) + m_Dialog = DIALOG_NONE; + + if(m_FileDialogStorageType == IStorage::TYPE_SAVE) + { + ButtonBar.VSplitLeft(40.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar); + if(DoButton_Editor(&s_NewFolderButton, "New folder", 0, &Button, 0, 0)) + { + m_FileDialogNewFolderName[0] = 0; + m_FileDialogErrString[0] = 0; + static int s_NewFolderPopupID = 0; + UiInvokePopupMenu(&s_NewFolderPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupNewFolder); + UI()->SetActiveItem(0); + } + } + + if(m_FileDialogStorageType == IStorage::TYPE_SAVE) + { + ButtonBar.VSplitLeft(40.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar); + if(DoButton_Editor(&s_MapInfoButton, "Map details", 0, &Button, 0, 0)) + { + str_copy(m_Map.m_MapInfo.m_aAuthorTmp, m_Map.m_MapInfo.m_aAuthor, sizeof(m_Map.m_MapInfo.m_aAuthorTmp)); + str_copy(m_Map.m_MapInfo.m_aVersionTmp, m_Map.m_MapInfo.m_aVersion, sizeof(m_Map.m_MapInfo.m_aVersionTmp)); + str_copy(m_Map.m_MapInfo.m_aCreditsTmp, m_Map.m_MapInfo.m_aCredits, sizeof(m_Map.m_MapInfo.m_aCreditsTmp)); + str_copy(m_Map.m_MapInfo.m_aLicenseTmp, m_Map.m_MapInfo.m_aLicense, sizeof(m_Map.m_MapInfo.m_aLicenseTmp)); + static int s_MapInfoPopupID = 0; + UiInvokePopupMenu(&s_MapInfoPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupMapInfo); + UI()->SetActiveItem(0); + } + } +} + +void CEditor::FilelistPopulate(int StorageType) +{ + m_FileList.clear(); + if(m_FileDialogStorageType != IStorage::TYPE_SAVE && !str_comp(m_pFileDialogPath, "maps")) + { + CFilelistItem Item; + str_copy(Item.m_aFilename, "downloadedmaps", sizeof(Item.m_aFilename)); + str_copy(Item.m_aName, "downloadedmaps/", sizeof(Item.m_aName)); + Item.m_IsDir = true; + Item.m_IsLink = true; + Item.m_StorageType = IStorage::TYPE_SAVE; + m_FileList.add(Item); + } + Storage()->ListDirectory(StorageType, m_pFileDialogPath, EditorListdirCallback, this); + m_FilesSelectedIndex = m_FileList.size() ? 0 : -1; + m_FilePreviewImage = 0; + m_aFileDialogActivate = false; + + if(m_FilesSelectedIndex >= 0) + str_copy(m_aFileDialogFileName, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogFileName)); + else + m_aFileDialogFileName[0] = 0; +} + +void CEditor::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) +{ + m_FileDialogStorageType = StorageType; + m_pFileDialogTitle = pTitle; + m_pFileDialogButtonText = pButtonText; + m_pfnFileDialogFunc = pfnFunc; + m_pFileDialogUser = pUser; + m_aFileDialogFileName[0] = 0; + m_aFileDialogCurrentFolder[0] = 0; + m_aFileDialogCurrentLink[0] = 0; + m_pFileDialogPath = m_aFileDialogCurrentFolder; + m_FileDialogFileType = FileType; + m_FileDialogScrollValue = 0.0f; + m_FilePreviewImage = 0; + + if(pDefaultName) + str_copy(m_aFileDialogFileName, pDefaultName, sizeof(m_aFileDialogFileName)); + if(pBasePath) + str_copy(m_aFileDialogCurrentFolder, pBasePath, sizeof(m_aFileDialogCurrentFolder)); + + FilelistPopulate(m_FileDialogStorageType); + + m_Dialog = DIALOG_FILE; +} + + + +void CEditor::RenderModebar(CUIRect View) +{ + CUIRect Button; + + // mode buttons + { + View.VSplitLeft(65.0f, &Button, &View); + Button.HSplitTop(30.0f, 0, &Button); + static int s_Button = 0; + const char *pButName = ""; + + if(m_Mode == MODE_LAYERS) + pButName = "Layers"; + else if(m_Mode == MODE_IMAGES) + pButName = "Images"; + else if(m_Mode == MODE_SOUNDS) + pButName = "Sounds"; + + int MouseButton = DoButton_Tab(&s_Button, pButName, 0, &Button, 0, "Switch between images, sounds and layers managment."); + if(MouseButton == 2) + { + if (m_Mode == MODE_LAYERS) + m_Mode = MODE_SOUNDS; + else if(m_Mode == MODE_IMAGES) + m_Mode = MODE_LAYERS; + else + m_Mode = MODE_IMAGES; + } + else if(MouseButton == 1) + { + if (m_Mode == MODE_LAYERS) + m_Mode = MODE_IMAGES; + else if(m_Mode == MODE_IMAGES) + m_Mode = MODE_SOUNDS; + else + m_Mode = MODE_LAYERS; + } + } + + View.VSplitLeft(5.0f, 0, &View); +} + +void CEditor::RenderStatusbar(CUIRect View) +{ + CUIRect Button; + View.VSplitRight(60.0f, &View, &Button); + static int s_EnvelopeButton = 0; + int MouseButton = DoButton_Editor(&s_EnvelopeButton, "Envelopes", m_ShowEnvelopeEditor, &Button, 0, "Toggles the envelope editor."); + if(MouseButton == 2) + m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+3)%4; + else if(MouseButton == 1) + m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+1)%4; + + if(MouseButton) + { + m_ShowServerSettingsEditor = false; + } + + View.VSplitRight(100.0f, &View, &Button); + Button.VSplitRight(10.0f, &Button, 0); + static int s_SettingsButton = 0; + if(DoButton_Editor(&s_SettingsButton, "Server settings", m_ShowServerSettingsEditor, &Button, 0, "Toggles the server settings editor.")) + { + m_ShowEnvelopeEditor = 0; + m_ShowServerSettingsEditor ^= 1; + } + + if (g_Config.m_ClEditorUndo) + { + View.VSplitRight(5.0f, &View, &Button); + View.VSplitRight(60.0f, &View, &Button); + static int s_UndolistButton = 0; + if(DoButton_Editor(&s_UndolistButton, "Undolist", m_ShowUndo, &Button, 0, "Toggles the undo list.")) + m_ShowUndo = (m_ShowUndo + 1) % 2; + } + + if(m_pTooltip) + { + if(ms_pUiGotContext && ms_pUiGotContext == UI()->HotItem()) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s Right click for context menu.", m_pTooltip); + UI()->DoLabel(&View, aBuf, 10.0f, -1, -1); + } + else + UI()->DoLabel(&View, m_pTooltip, 10.0f, -1, -1); + } +} + +void CEditor::RenderUndoList(CUIRect View) +{ + CUIRect List, Preview, Scroll, Button; + View.VSplitMid(&List, &Preview); + List.VSplitRight(15.0f, &List, &Scroll); + //int Num = (int)(List.h/17.0f)+1; + static int ScrollBar = 0; + Scroll.HMargin(5.0f, &Scroll); + m_UndoScrollValue = UiDoScrollbarV(&ScrollBar, &Scroll, m_UndoScrollValue); + + float TopY = List.y; + float Height = List.h; + UI()->ClipEnable(&List); + int ClickedIndex = -1; + int HoveredIndex = -1; + int ScrollNum = m_lUndoSteps.size() - List.h / 17.0f; + if (ScrollNum < 0) + ScrollNum = 0; + List.y -= m_UndoScrollValue*ScrollNum*17.0f; + for (int i = 0; i < m_lUndoSteps.size(); i++) + { + List.HSplitTop(17.0f, &Button, &List); + if (List.y < TopY) + continue; + if (List.y - 17.0f > TopY + Height) + break; + if(DoButton_Editor(&m_lUndoSteps[i].m_ButtonId, m_lUndoSteps[i].m_aName, 0, &Button, 0, "Undo to this step")) + ClickedIndex = i; + if (UI()->HotItem() == &m_lUndoSteps[i].m_ButtonId) + HoveredIndex = i; + } + UI()->ClipDisable(); + if (ClickedIndex != -1) + { + char aBuffer[1024]; + str_format(aBuffer, sizeof(aBuffer), "editor/undo_%i", m_lUndoSteps[HoveredIndex].m_FileNum); + m_Map.Load(m_pStorage, aBuffer, IStorage::TYPE_SAVE); + m_Map.m_UndoModified = 0; + m_LastUndoUpdateTime = time_get(); + } + if (HoveredIndex != -1) + { + if (m_lUndoSteps[HoveredIndex].m_PreviewImage == 0) + { + char aBuffer[1024]; + str_format(aBuffer, sizeof(aBuffer), "editor/undo_%i.png", m_lUndoSteps[HoveredIndex].m_FileNum); + m_lUndoSteps[HoveredIndex].m_PreviewImage = Graphics()->LoadTexture(aBuffer, IStorage::TYPE_SAVE, CImageInfo::FORMAT_RGB, IGraphics::TEXLOAD_NORESAMPLE); + } + if (m_lUndoSteps[HoveredIndex].m_PreviewImage) + { + Graphics()->TextureSet(m_lUndoSteps[HoveredIndex].m_PreviewImage); + Graphics()->BlendNormal(); + Graphics()->QuadsBegin(); + IGraphics::CQuadItem QuadItem(Preview.x, Preview.y, Preview.w, Preview.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } + } +} + +void CEditor::RenderEnvelopeEditor(CUIRect View) +{ + if(m_SelectedEnvelope < 0) m_SelectedEnvelope = 0; + if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; + + CEnvelope *pEnvelope = 0; + if(m_SelectedEnvelope >= 0 && m_SelectedEnvelope < m_Map.m_lEnvelopes.size()) + pEnvelope = m_Map.m_lEnvelopes[m_SelectedEnvelope]; + + CUIRect ToolBar, CurveBar, ColorBar; + View.HSplitTop(15.0f, &ToolBar, &View); + View.HSplitTop(15.0f, &CurveBar, &View); + ToolBar.Margin(2.0f, &ToolBar); + CurveBar.Margin(2.0f, &CurveBar); + + bool CurrentEnvelopeSwitched = false; + + // do the toolbar + { + CUIRect Button; + CEnvelope *pNewEnv = 0; + + + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + static int s_NewSoundButton = 0; + if(DoButton_Editor(&s_NewSoundButton, "Sound+", 0, &Button, 0, "Creates a new sound envelope")) + { + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + pNewEnv = m_Map.NewEnvelope(1); + } + + ToolBar.VSplitRight(5.0f, &ToolBar, &Button); + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + static int s_New4dButton = 0; + if(DoButton_Editor(&s_New4dButton, "Color+", 0, &Button, 0, "Creates a new color envelope")) + { + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + pNewEnv = m_Map.NewEnvelope(4); + } + + ToolBar.VSplitRight(5.0f, &ToolBar, &Button); + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + static int s_New2dButton = 0; + if(DoButton_Editor(&s_New2dButton, "Pos.+", 0, &Button, 0, "Creates a new position envelope")) + { + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + pNewEnv = m_Map.NewEnvelope(3); + } + + // Delete button + if(m_SelectedEnvelope >= 0) + { + ToolBar.VSplitRight(10.0f, &ToolBar, &Button); + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + static int s_DelButton = 0; + if(DoButton_Editor(&s_DelButton, "Delete", 0, &Button, 0, "Delete this envelope")) + { + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + m_Map.DeleteEnvelope(m_SelectedEnvelope); + if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) + m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; + pEnvelope = m_SelectedEnvelope >= 0 ? m_Map.m_lEnvelopes[m_SelectedEnvelope] : 0; + } + } + + if(pNewEnv) // add the default points + { + if(pNewEnv->m_Channels == 4) + { + pNewEnv->AddPoint(0, f2fx(1.0f), f2fx(1.0f), f2fx(1.0f), f2fx(1.0f)); + pNewEnv->AddPoint(1000, f2fx(1.0f), f2fx(1.0f), f2fx(1.0f), f2fx(1.0f)); + } + else + { + pNewEnv->AddPoint(0, 0); + pNewEnv->AddPoint(1000, 0); + } + } + + CUIRect Shifter, Inc, Dec; + ToolBar.VSplitLeft(60.0f, &Shifter, &ToolBar); + Shifter.VSplitRight(15.0f, &Shifter, &Inc); + Shifter.VSplitLeft(15.0f, &Dec, &Shifter); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf),"%d/%d", m_SelectedEnvelope+1, m_Map.m_lEnvelopes.size()); + RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); + UI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1); + + static int s_PrevButton = 0; + if(DoButton_ButtonDec(&s_PrevButton, 0, 0, &Dec, 0, "Previous Envelope")) + { + m_SelectedEnvelope--; + if(m_SelectedEnvelope < 0) + m_SelectedEnvelope = m_Map.m_lEnvelopes.size() - 1; + CurrentEnvelopeSwitched = true; + } + + static int s_NextButton = 0; + if(DoButton_ButtonInc(&s_NextButton, 0, 0, &Inc, 0, "Next Envelope")) + { + m_SelectedEnvelope++; + if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) + m_SelectedEnvelope = 0; + CurrentEnvelopeSwitched = true; + } + + if(pEnvelope) + { + ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); + ToolBar.VSplitLeft(35.0f, &Button, &ToolBar); + UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); + + ToolBar.VSplitLeft(80.0f, &Button, &ToolBar); + + static float s_NameBox = 0; + if(DoEditBox(&s_NameBox, &Button, pEnvelope->m_aName, sizeof(pEnvelope->m_aName), 10.0f, &s_NameBox)) + { + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + } + } + } + + bool ShowColorBar = false; + if(pEnvelope && pEnvelope->m_Channels == 4) + { + ShowColorBar = true; + View.HSplitTop(20.0f, &ColorBar, &View); + ColorBar.Margin(2.0f, &ColorBar); + RenderBackground(ColorBar, ms_CheckerTexture, 16.0f, 1.0f); + } + + RenderBackground(View, ms_CheckerTexture, 32.0f, 0.1f); + + if(pEnvelope) + { + static array<int> Selection; + static int sEnvelopeEditorID = 0; + static int s_ActiveChannels = 0xf; + + vec3 aColors[] = {vec3(1,0.2f,0.2f), vec3(0.2f,1,0.2f), vec3(0.2f,0.2f,1), vec3(1,1,0.2f)}; + + if(pEnvelope) + { + CUIRect Button; + + ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); + + static const char *s_paNames[4][4] = { + {"V", "", "", ""}, + {"", "", "", ""}, + {"X", "Y", "R", ""}, + {"R", "G", "B", "A"}, + }; + + const char *paDescriptions[4][4] = { + {"Volume of the envelope", "", "", ""}, + {"", "", "", ""}, + {"X-axis of the envelope", "Y-axis of the envelope", "Rotation of the envelope", ""}, + {"Red value of the envelope", "Green value of the envelope", "Blue value of the envelope", "Alpha value of the envelope"}, + }; + + static int s_aChannelButtons[4] = {0}; + int Bit = 1; + //ui_draw_button_func draw_func; + + for(int i = 0; i < pEnvelope->m_Channels; i++, Bit<<=1) + { + ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); + + /*if(i == 0) draw_func = draw_editor_button_l; + else if(i == envelope->channels-1) draw_func = draw_editor_button_r; + else draw_func = draw_editor_button_m;*/ + if(DoButton_Env(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels-1][i], s_ActiveChannels&Bit, &Button, paDescriptions[pEnvelope->m_Channels-1][i], aColors[i])) + s_ActiveChannels ^= Bit; + } + + // sync checkbox + ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); + ToolBar.VSplitLeft(12.0f, &Button, &ToolBar); + static int s_SyncButton; + if(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized?"X":"", 0, &Button, 0, "Enable envelope synchronization between clients")) + pEnvelope->m_Synchronized = !pEnvelope->m_Synchronized; + + ToolBar.VSplitLeft(4.0f, &Button, &ToolBar); + ToolBar.VSplitLeft(80.0f, &Button, &ToolBar); + UI()->DoLabel(&Button, "Synchronized", 10.0f, -1, -1); + } + + float EndTime = pEnvelope->EndTime(); + if(EndTime < 1) + EndTime = 1; + + pEnvelope->FindTopBottom(s_ActiveChannels); + float Top = pEnvelope->m_Top; + float Bottom = pEnvelope->m_Bottom; + + if(Top < 1) + Top = 1; + if(Bottom >= 0) + Bottom = 0; + + float TimeScale = EndTime/View.w; + float ValueScale = (Top-Bottom)/View.h; + + if(UI()->MouseInside(&View)) + UI()->SetHotItem(&sEnvelopeEditorID); + + if(UI()->HotItem() == &sEnvelopeEditorID) + { + // do stuff + if(pEnvelope) + { + if(UI()->MouseButtonClicked(1)) + { + // add point + int Time = (int)(((UI()->MouseX()-View.x)*TimeScale)*1000.0f); + //float env_y = (UI()->MouseY()-view.y)/TimeScale; + float aChannels[4]; + pEnvelope->Eval(Time / 1000.0f, aChannels); + pEnvelope->AddPoint(Time, + f2fx(aChannels[0]), f2fx(aChannels[1]), + f2fx(aChannels[2]), f2fx(aChannels[3])); + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + } + + m_ShowEnvelopePreview = 1; + m_pTooltip = "Press right mouse button to create a new point"; + } + } + + // render lines + { + UI()->ClipEnable(&View); + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + for(int c = 0; c < pEnvelope->m_Channels; c++) + { + if(s_ActiveChannels&(1<<c)) + Graphics()->SetColor(aColors[c].r,aColors[c].g,aColors[c].b,1); + else + Graphics()->SetColor(aColors[c].r*0.5f,aColors[c].g*0.5f,aColors[c].b*0.5f,1); + + float PrevX = 0; + float aResults[4]; + pEnvelope->Eval(0.000001f, aResults); + float PrevValue = aResults[c]; + + int Steps = (int)((View.w/UI()->Screen()->w) * Graphics()->ScreenWidth()); + for(int i = 1; i <= Steps; i++) + { + float a = i/(float)Steps; + pEnvelope->Eval(a*EndTime, aResults); + float v = aResults[c]; + v = (v-Bottom)/(Top-Bottom); + + IGraphics::CLineItem LineItem(View.x + PrevX*View.w, View.y+View.h - PrevValue*View.h, View.x + a*View.w, View.y+View.h - v*View.h); + Graphics()->LinesDraw(&LineItem, 1); + PrevX = a; + PrevValue = v; + } + } + Graphics()->LinesEnd(); + UI()->ClipDisable(); + } + + // render curve options + { + for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) + { + float t0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; + float t1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; + + //dbg_msg("", "%f", end_time); + + CUIRect v; + v.x = CurveBar.x + (t0+(t1-t0)*0.5f) * CurveBar.w; + v.y = CurveBar.y; + v.h = CurveBar.h; + v.w = CurveBar.h; + v.x -= v.w/2; + void *pID = &pEnvelope->m_lPoints[i].m_Curvetype; + const char *paTypeName[] = { + "N", "L", "S", "F", "M" + }; + + if(DoButton_Editor(pID, paTypeName[pEnvelope->m_lPoints[i].m_Curvetype], 0, &v, 0, "Switch curve type")) + pEnvelope->m_lPoints[i].m_Curvetype = (pEnvelope->m_lPoints[i].m_Curvetype+1)%NUM_CURVETYPES; + } + } + + // render colorbar + if(ShowColorBar) + { + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) + { + float r0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[0]); + float g0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]); + float b0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[2]); + float a0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[3]); + float r1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[0]); + float g1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[1]); + float b1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[2]); + float a1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[3]); + + IGraphics::CColorVertex Array[4] = {IGraphics::CColorVertex(0, r0, g0, b0, a0), + IGraphics::CColorVertex(1, r1, g1, b1, a1), + IGraphics::CColorVertex(2, r1, g1, b1, a1), + IGraphics::CColorVertex(3, r0, g0, b0, a0)}; + Graphics()->SetColorVertex(Array, 4); + + float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; +// float y0 = (fx2f(envelope->points[i].values[c])-bottom)/(top-bottom); + float x1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; + //float y1 = (fx2f(envelope->points[i+1].values[c])-bottom)/(top-bottom); + CUIRect v; + v.x = ColorBar.x + x0*ColorBar.w; + v.y = ColorBar.y; + v.w = (x1-x0)*ColorBar.w; + v.h = ColorBar.h; + + IGraphics::CQuadItem QuadItem(v.x, v.y, v.w, v.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + Graphics()->QuadsEnd(); + } + + // render handles + + // keep track of last Env + static void* s_pID = 0; + + // chars for textinput + static char s_aStrCurTime[32] = "0.000"; + static char s_aStrCurValue[32] = "0.000"; + + if(CurrentEnvelopeSwitched) + { + s_pID = 0; + + // update displayed text + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "0.000"); + str_format(s_aStrCurValue, sizeof(s_aStrCurValue), "0.000"); + } + + { + int CurrentValue = 0, CurrentTime = 0; + + Graphics()->TextureSet(-1); + Graphics()->QuadsBegin(); + for(int c = 0; c < pEnvelope->m_Channels; c++) + { + if(!(s_ActiveChannels&(1<<c))) + continue; + + for(int i = 0; i < pEnvelope->m_lPoints.size(); i++) + { + float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; + float y0 = (fx2f(pEnvelope->m_lPoints[i].m_aValues[c])-Bottom)/(Top-Bottom); + CUIRect Final; + Final.x = View.x + x0*View.w; + Final.y = View.y+View.h - y0*View.h; + Final.x -= 2.0f; + Final.y -= 2.0f; + Final.w = 4.0f; + Final.h = 4.0f; + + void *pID = &pEnvelope->m_lPoints[i].m_aValues[c]; + + if(UI()->MouseInside(&Final)) + UI()->SetHotItem(pID); + + float ColorMod = 1.0f; + + if(UI()->ActiveItem() == pID) + { + if(!UI()->MouseButton(0)) + { + m_SelectedQuadEnvelope = -1; + m_SelectedEnvelopePoint = -1; + + UI()->SetActiveItem(0); + } + else + { + if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) + { + if(i != 0) + { + if((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))) + pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX)); + else + pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX*TimeScale)*1000.0f); + if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1; + if(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1; + } + } + else + { + if((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))) + pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*0.001f); + else + pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*ValueScale); + } + + if (m_SelectedEnvelopePoint != i) + m_Map.m_UndoModified++; + + m_SelectedQuadEnvelope = m_SelectedEnvelope; + m_ShowEnvelopePreview = 1; + m_SelectedEnvelopePoint = i; + m_Map.m_Modified = true; + } + + ColorMod = 100.0f; + Graphics()->SetColor(1,1,1,1); + } + else if(UI()->HotItem() == pID) + { + if(UI()->MouseButton(0)) + { + Selection.clear(); + Selection.add(i); + UI()->SetActiveItem(pID); + // track it + s_pID = pID; + } + + // remove point + if(UI()->MouseButtonClicked(1)) + { + if(s_pID == pID) + { + s_pID = 0; + + // update displayed text + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "0.000"); + str_format(s_aStrCurValue, sizeof(s_aStrCurValue), "0.000"); + } + + pEnvelope->m_lPoints.remove_index(i); + m_Map.m_Modified = true; + m_Map.m_UndoModified++; + } + + m_ShowEnvelopePreview = 1; + ColorMod = 100.0f; + Graphics()->SetColor(1,0.75f,0.75f,1); + m_pTooltip = "Left mouse to drag. Hold ctrl to be more precise. Hold shift to alter time point aswell. Right click to delete."; + } + + if(pID == s_pID && (Input()->KeyPressed(KEY_RETURN) || Input()->KeyPressed(KEY_KP_ENTER))) + { + if(i != 0) + { + pEnvelope->m_lPoints[i].m_Time = str_tofloat(s_aStrCurTime) * 1000.0f; + + if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1; + if(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time) + pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1; + } + else + pEnvelope->m_lPoints[i].m_Time = 0.0f; + + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", pEnvelope->m_lPoints[i].m_Time/1000.0f); + + pEnvelope->m_lPoints[i].m_aValues[c] = f2fx(str_tofloat(s_aStrCurValue)); + } + + if(UI()->ActiveItem() == pID/* || UI()->HotItem() == pID*/) + { + CurrentTime = pEnvelope->m_lPoints[i].m_Time; + CurrentValue = pEnvelope->m_lPoints[i].m_aValues[c]; + + // update displayed text + str_format(s_aStrCurTime, sizeof(s_aStrCurTime), "%.3f", CurrentTime/1000.0f); + str_format(s_aStrCurValue, sizeof(s_aStrCurValue), "%.3f", fx2f(CurrentValue)); + } + + if (m_SelectedQuadEnvelope == m_SelectedEnvelope && m_SelectedEnvelopePoint == i) + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + else + Graphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f); + IGraphics::CQuadItem QuadItem(Final.x, Final.y, Final.w, Final.h); + Graphics()->QuadsDrawTL(&QuadItem, 1); + } + } + Graphics()->QuadsEnd(); + + static float s_ValNumber = 0; + static float s_TimeNumber = 0; + + CUIRect ToolBar1; + CUIRect ToolBar2; + + ToolBar.VSplitMid(&ToolBar1, &ToolBar2); + if (ToolBar.w > ToolBar.h * 21) + { + ToolBar1.VMargin(3.0f, &ToolBar1); + ToolBar2.VMargin(3.0f, &ToolBar2); + + CUIRect Label1; + CUIRect Label2; + + ToolBar1.VSplitMid(&Label1, &ToolBar1); + ToolBar2.VSplitMid(&Label2, &ToolBar2); + + UI()->DoLabel(&Label1, "Value:", 10.0f, -1, -1); + UI()->DoLabel(&Label2, "Time (in s):", 10.0f, -1, -1); + } + + DoEditBox(&s_ValNumber, &ToolBar1, s_aStrCurValue, sizeof(s_aStrCurValue), 10.0f, &s_ValNumber); + DoEditBox(&s_TimeNumber, &ToolBar2, s_aStrCurTime, sizeof(s_aStrCurTime), 10.0f, &s_TimeNumber); + } + } +} + +void CEditor::RenderServerSettingsEditor(CUIRect View) +{ + static int s_CommandSelectedIndex = -1; + + CUIRect ToolBar; + View.HSplitTop(20.0f, &ToolBar, &View); + ToolBar.Margin(2.0f, &ToolBar); + + // do the toolbar + { + CUIRect Button; + + // command line + ToolBar.VSplitLeft(5.0f, 0, &Button); + UI()->DoLabel(&Button, "Command:", 12.0f, -1); + + Button.VSplitLeft(70.0f, 0, &Button); + Button.VSplitLeft(180.0f, &Button, 0); + DoEditBox(&m_CommandBox, &Button, m_aSettingsCommand, sizeof(m_aSettingsCommand), 12.0f, &m_CommandBox); + + // buttons + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + static int s_AddButton = 0; + if(DoButton_Editor(&s_AddButton, "Add", 0, &Button, 0, "Add a command to command list.") + || ((Input()->KeyDown(KEY_RETURN) || Input()->KeyDown(KEY_KP_ENTER)) && UI()->LastActiveItem() == &m_CommandBox)) + { + if(m_aSettingsCommand[0] != 0 && str_find(m_aSettingsCommand, " ")) + { + bool Found = false; + for(int i = 0; i < m_Map.m_lSettings.size(); i++) + if(!str_comp(m_Map.m_lSettings[i].m_aCommand, m_aSettingsCommand)) + { + Found = true; + break; + } + + if(!Found) + { + CEditorMap::CSetting Setting; + str_copy(Setting.m_aCommand, m_aSettingsCommand, sizeof(Setting.m_aCommand)); + m_Map.m_lSettings.add(Setting); + } + } + } + + if(m_Map.m_lSettings.size()) + { + ToolBar.VSplitRight(50.0f, &ToolBar, &Button); + Button.VSplitRight(5.0f, &Button, 0); + static int s_AddButton = 0; + if(DoButton_Editor(&s_AddButton, "Del", 0, &Button, 0, "Delete a command from the command list.") + || Input()->KeyDown(KEY_DELETE)) + if(s_CommandSelectedIndex > -1 && s_CommandSelectedIndex < m_Map.m_lSettings.size()) + m_Map.m_lSettings.remove_index(s_CommandSelectedIndex); + } + } + + View.HSplitTop(2.0f, 0, &View); + RenderBackground(View, ms_CheckerTexture, 32.0f, 0.1f); + + CUIRect ListBox; + View.Margin(1.0f, &ListBox); + + float ListHeight = 17.0f * m_Map.m_lSettings.size(); + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + + float ScrollDifference = ListHeight - ListBox.h; + + if(ListHeight > ListBox.h) // Do we even need a scrollbar? + { + CUIRect Scroll; + ListBox.VSplitRight(15.0f, &ListBox, &Scroll); + ListBox.VSplitRight(3.0f, &ListBox, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ListBox)) + { + int ScrollNum = (int)((ListHeight-ListBox.h)/17.0f)+1; + if(ScrollNum > 0) + { + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + else + ScrollNum = 0; + } + } + + float ListStartAt = ScrollDifference * s_ScrollValue; + if(ListStartAt < 0.0f) + ListStartAt = 0.0f; + + float ListStopAt = ListHeight - ScrollDifference * (1 - s_ScrollValue); + float ListCur = 0; + + UI()->ClipEnable(&ListBox); + for(int i = 0; i < m_Map.m_lSettings.size(); i++) + { + if(ListCur > ListStopAt) + break; + + if(ListCur >= ListStartAt) + { + CUIRect Button; + ListBox.HSplitTop(15.0f, &Button, &ListBox); + ListBox.HSplitTop(2.0f, 0, &ListBox); + Button.VSplitLeft(5.0f, 0, &Button); + + if(DoButton_MenuItem(&m_Map.m_lSettings[i], m_Map.m_lSettings[i].m_aCommand, s_CommandSelectedIndex == i, &Button, 0, 0)) + s_CommandSelectedIndex = i; + } + ListCur += 17.0f; + } + UI()->ClipDisable(); +} + +int CEditor::PopupMenuFile(CEditor *pEditor, CUIRect View) +{ + static int s_NewMapButton = 0; + static int s_SaveButton = 0; + static int s_SaveAsButton = 0; + static int s_SaveCopyButton = 0; + static int s_OpenButton = 0; + static int s_AppendButton = 0; + static int s_ExitButton = 0; + + CUIRect Slot; + View.HSplitTop(2.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_NewMapButton, "New", 0, &Slot, 0, "Creates a new map")) + { + if(pEditor->HasUnsavedData()) + { + pEditor->m_PopupEventType = POPEVENT_NEW; + pEditor->m_PopupEventActivated = true; + } + else + { + pEditor->Reset(); + pEditor->m_aFileName[0] = 0; + } + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_OpenButton, "Load", 0, &Slot, 0, "Opens a map for editing")) + { + if(pEditor->HasUnsavedData()) + { + pEditor->m_PopupEventType = POPEVENT_LOAD; + pEditor->m_PopupEventActivated = true; + } + else + pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", pEditor->CallbackOpenMap, pEditor); + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_AppendButton, "Append", 0, &Slot, 0, "Opens a map and adds everything from that map to the current one")) + { + pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Append map", "Append", "maps", "", pEditor->CallbackAppendMap, pEditor); + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_SaveButton, "Save", 0, &Slot, 0, "Saves the current map (ctrl+s)")) + { + if(pEditor->m_aFileName[0] && pEditor->m_ValidSaveFilename) + { + str_copy(pEditor->m_aFileSaveName, pEditor->m_aFileName, sizeof(pEditor->m_aFileSaveName)); + pEditor->m_PopupEventType = POPEVENT_SAVE; + pEditor->m_PopupEventActivated = true; + } + else + pEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", pEditor->CallbackSaveMap, pEditor); + return 1; + } + + View.HSplitTop(2.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_SaveAsButton, "Save As", 0, &Slot, 0, "Saves the current map under a new name (ctrl+shift+s)")) + { + pEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", pEditor->CallbackSaveMap, pEditor); + return 1; + } + + View.HSplitTop(2.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_SaveCopyButton, "Save Copy", 0, &Slot, 0, "Saves a copy of the current map under a new name (ctrl+shift+alt+s)")) + { + pEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", pEditor->CallbackSaveCopyMap, pEditor); + return 1; + } + + View.HSplitTop(10.0f, &Slot, &View); + View.HSplitTop(12.0f, &Slot, &View); + if(pEditor->DoButton_MenuItem(&s_ExitButton, "Exit", 0, &Slot, 0, "Exits from the editor")) + { + if(pEditor->HasUnsavedData()) + { + pEditor->m_PopupEventType = POPEVENT_EXIT; + pEditor->m_PopupEventActivated = true; + } + else + g_Config.m_ClEditor = 0; + return 1; + } + + return 0; +} + +void CEditor::RenderMenubar(CUIRect MenuBar) +{ + static CUIRect s_File /*, view, help*/; + + MenuBar.VSplitLeft(60.0f, &s_File, &MenuBar); + if(DoButton_Menu(&s_File, "File", 0, &s_File, 0, 0)) + UiInvokePopupMenu(&s_File, 1, s_File.x, s_File.y+s_File.h-1.0f, 120, 150, PopupMenuFile, this); + + /* + menubar.VSplitLeft(5.0f, 0, &menubar); + menubar.VSplitLeft(60.0f, &view, &menubar); + if(do_editor_button(&view, "View", 0, &view, draw_editor_button_menu, 0, 0)) + (void)0; + + menubar.VSplitLeft(5.0f, 0, &menubar); + menubar.VSplitLeft(60.0f, &help, &menubar); + if(do_editor_button(&help, "Help", 0, &help, draw_editor_button_menu, 0, 0)) + (void)0; + */ + + CUIRect Info, Close; + MenuBar.VSplitLeft(40.0f, 0, &MenuBar); + MenuBar.VSplitRight(20.0f, &MenuBar, &Close); + Close.VSplitLeft(5.0f, 0, &Close); + MenuBar.VSplitLeft(MenuBar.w*0.75f, &MenuBar, &Info); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "File: %s", m_aFileName); + UI()->DoLabel(&MenuBar, aBuf, 10.0f, -1, -1); + + time_t rawtime; + struct tm *timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + str_format(aBuf, sizeof(aBuf), "Z: %i, A: %.1f, G: %i %02d:%02d", m_ZoomLevel, m_AnimateSpeed, m_GridFactor, timeinfo->tm_hour, timeinfo->tm_min); + UI()->DoLabel(&Info, aBuf, 10.0f, 1, -1); + + static int s_CloseButton = 0; + if(DoButton_Editor(&s_CloseButton, "×", 0, &Close, 0, "Exits from the editor")) + { + if(HasUnsavedData()) + { + m_PopupEventType = POPEVENT_EXIT; + m_PopupEventActivated = true; + } + else + g_Config.m_ClEditor = 0; + } +} + +void CEditor::Render() +{ + // basic start + Graphics()->Clear(1.0f, 0.0f, 1.0f); + CUIRect View = *UI()->Screen(); + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + + float Width = View.w; + float Height = View.h; + + // reset tip + m_pTooltip = 0; + + if(m_EditBoxActive) + --m_EditBoxActive; + + // render checker + RenderBackground(View, ms_CheckerTexture, 32.0f, 1.0f); + + CUIRect MenuBar, CModeBar, ToolBar, StatusBar, ExtraEditor, UndoList, ToolBox; + m_ShowPicker = Input()->KeyPressed(KEY_SPACE) != 0 && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0 && UI()->LastActiveItem() != &m_CommandBox; + + if(m_GuiActive) + { + + View.HSplitTop(16.0f, &MenuBar, &View); + View.HSplitTop(53.0f, &ToolBar, &View); + View.VSplitLeft(100.0f, &ToolBox, &View); + View.HSplitBottom(16.0f, &View, &StatusBar); + + if(m_ShowEnvelopeEditor && !m_ShowPicker) + { + float size = 125.0f; + if(m_ShowEnvelopeEditor == 2) + size *= 2.0f; + else if(m_ShowEnvelopeEditor == 3) + size *= 3.0f; + View.HSplitBottom(size, &View, &ExtraEditor); + } + if (m_ShowUndo && !m_ShowPicker) + { + View.HSplitBottom(250.0f, &View, &UndoList); + } + + if(m_ShowServerSettingsEditor && !m_ShowPicker) + View.HSplitBottom(250.0f, &View, &ExtraEditor); + } + + // a little hack for now + if(m_Mode == MODE_LAYERS) + DoMapEditor(View, ToolBar); + + // do zooming + if(Input()->KeyPresses(KEY_KP_MINUS) && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0) + m_ZoomLevel += 50; + if(Input()->KeyPresses(KEY_KP_PLUS) && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0) + m_ZoomLevel -= 50; + if(Input()->KeyDown(KEY_KP_MULTIPLY) && m_Dialog == DIALOG_NONE && m_EditBoxActive == 0) + { + m_EditorOffsetX = 0; + m_EditorOffsetY = 0; + m_ZoomLevel = 100; + } + if(m_Dialog == DIALOG_NONE && UI()->MouseInside(&View)) + { + // Determines in which direction to zoom. + int Zoom = 0; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + Zoom--; + if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + Zoom++; + + if(Zoom != 0) + { + float OldLevel = m_ZoomLevel; + m_ZoomLevel = clamp(m_ZoomLevel + Zoom * 20, 50, 2000); + if(g_Config.m_EdZoomTarget) + ZoomMouseTarget((float)m_ZoomLevel / OldLevel); + } + } + + m_ZoomLevel = clamp(m_ZoomLevel, 50, 2000); + m_WorldZoom = m_ZoomLevel/100.0f; + float Brightness = 0.25f; + + if(m_GuiActive) + { + RenderBackground(MenuBar, ms_BackgroundTexture, 128.0f, Brightness*0); + MenuBar.Margin(2.0f, &MenuBar); + + RenderBackground(ToolBox, ms_BackgroundTexture, 128.0f, Brightness); + ToolBox.Margin(2.0f, &ToolBox); + + RenderBackground(ToolBar, ms_BackgroundTexture, 128.0f, Brightness); + ToolBar.Margin(2.0f, &ToolBar); + ToolBar.VSplitLeft(100.0f, &CModeBar, &ToolBar); + + RenderBackground(StatusBar, ms_BackgroundTexture, 128.0f, Brightness); + StatusBar.Margin(2.0f, &StatusBar); + } + else + { + ToolBar.y = -300; + } + + // do the toolbar + if(m_Mode == MODE_LAYERS) + DoToolbar(ToolBar); + + if(m_GuiActive) + { + if(m_ShowEnvelopeEditor || m_ShowServerSettingsEditor) + { + RenderBackground(ExtraEditor, ms_BackgroundTexture, 128.0f, Brightness); + ExtraEditor.Margin(2.0f, &ExtraEditor); + } + if(m_ShowUndo) + { + RenderBackground(UndoList, ms_BackgroundTexture, 128.0f, Brightness); + UndoList.Margin(2.0f, &UndoList); + } + } + + + if(m_Mode == MODE_LAYERS) + RenderLayers(ToolBox, ToolBar, View); + else if(m_Mode == MODE_IMAGES) + RenderImages(ToolBox, ToolBar, View); + else if(m_Mode == MODE_SOUNDS) + RenderSounds(ToolBox, ToolBar, View); + + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + + if(m_GuiActive) + { + RenderMenubar(MenuBar); + + RenderModebar(CModeBar); + if(m_ShowEnvelopeEditor && !m_ShowPicker) + RenderEnvelopeEditor(ExtraEditor); + if(m_ShowUndo) + RenderUndoList(UndoList); + if(m_ShowServerSettingsEditor) + RenderServerSettingsEditor(ExtraEditor); + } + + if(m_Dialog == DIALOG_FILE) + { + static int s_NullUiTarget = 0; + UI()->SetHotItem(&s_NullUiTarget); + RenderFileDialog(); + } + + if(m_PopupEventActivated) + { + static int s_PopupID = 0; + UiInvokePopupMenu(&s_PopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupEvent); + m_PopupEventActivated = false; + m_PopupEventWasActivated = true; + } + + + UiDoPopupMenu(); + + if(m_GuiActive) + RenderStatusbar(StatusBar); + + // + if(g_Config.m_EdShowkeys) + { + Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); + CTextCursor Cursor; + TextRender()->SetCursor(&Cursor, View.x+10, View.y+View.h-24-10, 24.0f, TEXTFLAG_RENDER); + + int NKeys = 0; + for(int i = 0; i < KEY_LAST; i++) + { + if(Input()->KeyPressed(i)) + { + if(NKeys) + TextRender()->TextEx(&Cursor, " + ", -1); + TextRender()->TextEx(&Cursor, Input()->KeyName(i), -1); + NKeys++; + } + } + } + + if(m_ShowMousePointer) + { + // render butt ugly mouse cursor + float mx = UI()->MouseX(); + float my = UI()->MouseY(); + Graphics()->TextureSet(ms_CursorTexture); + Graphics()->QuadsBegin(); + if(ms_pUiGotContext == UI()->HotItem()) + Graphics()->SetColor(1,0,0,1); + IGraphics::CQuadItem QuadItem(mx,my, 16.0f, 16.0f); + Graphics()->QuadsDrawTL(&QuadItem, 1); + Graphics()->QuadsEnd(); + } +} + +static int UndoStepsListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) +{ + IStorage *pStorage = (IStorage *)pUser; + if (str_comp_nocase_num(pName, "undo_", 5) == 0) + { + char aBuffer[1024]; + pStorage->GetCompletePath(IStorage::TYPE_SAVE, "editor/", aBuffer, sizeof(aBuffer)); + str_append(aBuffer, pName, sizeof(aBuffer)); + fs_remove(aBuffer); + } + return 0; +} + +void CEditor::Reset(bool CreateDefault) +{ + m_Map.Clean(); + + //delete undo file + char aBuffer[1024]; + m_pStorage->GetCompletePath(IStorage::TYPE_SAVE, "editor/", aBuffer, sizeof(aBuffer)); + fs_listdir(aBuffer, UndoStepsListdirCallback, 0, m_pStorage); + m_lUndoSteps.clear(); + + // create default layers + if(CreateDefault) + m_Map.CreateDefault(ms_EntitiesTexture); + + /* + { + }*/ + + m_SelectedLayer = 0; + m_SelectedGroup = 0; + m_SelectedQuad = -1; + m_SelectedPoints = 0; + m_SelectedEnvelope = 0; + m_SelectedImage = 0; + m_SelectedSound = 0; + m_SelectedSource = -1; + + m_WorldOffsetX = 0; + m_WorldOffsetY = 0; + m_EditorOffsetX = 0.0f; + m_EditorOffsetY = 0.0f; + + m_WorldZoom = 1.0f; + m_ZoomLevel = 200; + + m_MouseDeltaX = 0; + m_MouseDeltaY = 0; + m_MouseDeltaWx = 0; + m_MouseDeltaWy = 0; + + m_Map.m_Modified = false; + m_Map.m_UndoModified = 0; + m_LastUndoUpdateTime = time_get(); + m_UndoRunning = false; + + m_ShowEnvelopePreview = 0; + m_ShiftBy = 1; +} + +int CEditor::GetLineDistance() +{ + int LineDistance = 512; + + if(m_ZoomLevel <= 100) + LineDistance = 16; + else if(m_ZoomLevel <= 250) + LineDistance = 32; + else if(m_ZoomLevel <= 450) + LineDistance = 64; + else if(m_ZoomLevel <= 850) + LineDistance = 128; + else if(m_ZoomLevel <= 1550) + LineDistance = 256; + + return LineDistance; +} + +void CEditor::ZoomMouseTarget(float ZoomFactor) +{ + // zoom to the current mouse position + // get absolute mouse position + float aPoints[4]; + RenderTools()->MapscreenToWorld( + m_WorldOffsetX, m_WorldOffsetY, + 1.0f, 1.0f, 0.0f, 0.0f, Graphics()->ScreenAspect(), m_WorldZoom, aPoints); + + float WorldWidth = aPoints[2]-aPoints[0]; + float WorldHeight = aPoints[3]-aPoints[1]; + + float Mwx = aPoints[0] + WorldWidth * (UI()->MouseX()/UI()->Screen()->w); + float Mwy = aPoints[1] + WorldHeight * (UI()->MouseY()/UI()->Screen()->h); + + // adjust camera + m_WorldOffsetX += (Mwx-m_WorldOffsetX) * (1-ZoomFactor); + m_WorldOffsetY += (Mwy-m_WorldOffsetY) * (1-ZoomFactor); +} + +void CEditorMap::DeleteEnvelope(int Index) +{ + if(Index < 0 || Index >= m_lEnvelopes.size()) + return; + + m_Modified = true; + m_UndoModified++; + + // fix links between envelopes and quads + for(int i = 0; i < m_lGroups.size(); ++i) + for(int j = 0; j < m_lGroups[i]->m_lLayers.size(); ++j) + if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_QUADS) + { + CLayerQuads *pLayer = static_cast<CLayerQuads *>(m_lGroups[i]->m_lLayers[j]); + for(int k = 0; k < pLayer->m_lQuads.size(); ++k) + { + if(pLayer->m_lQuads[k].m_PosEnv == Index) + pLayer->m_lQuads[k].m_PosEnv = -1; + else if(pLayer->m_lQuads[k].m_PosEnv > Index) + pLayer->m_lQuads[k].m_PosEnv--; + if(pLayer->m_lQuads[k].m_ColorEnv == Index) + pLayer->m_lQuads[k].m_ColorEnv = -1; + else if(pLayer->m_lQuads[k].m_ColorEnv > Index) + pLayer->m_lQuads[k].m_ColorEnv--; + } + } + else if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_TILES) + { + CLayerTiles *pLayer = static_cast<CLayerTiles *>(m_lGroups[i]->m_lLayers[j]); + if(pLayer->m_ColorEnv == Index) + pLayer->m_ColorEnv = -1; + if(pLayer->m_ColorEnv > Index) + pLayer->m_ColorEnv--; + } + + m_lEnvelopes.remove_index(Index); +} + +void CEditorMap::MakeGameLayer(CLayer *pLayer) +{ + m_pGameLayer = (CLayerGame *)pLayer; + m_pGameLayer->m_pEditor = m_pEditor; + m_pGameLayer->m_TexID = m_pEditor->ms_EntitiesTexture; +} + +void CEditorMap::MakeGameGroup(CLayerGroup *pGroup) +{ + m_pGameGroup = pGroup; + m_pGameGroup->m_GameGroup = true; + str_copy(m_pGameGroup->m_aName, "Game", sizeof(m_pGameGroup->m_aName)); +} + + + +void CEditorMap::Clean() +{ + m_lGroups.delete_all(); + m_lEnvelopes.delete_all(); + m_lImages.delete_all(); + m_lSounds.delete_all(); + + m_MapInfo.Reset(); + + m_lSettings.clear(); + + m_pGameLayer = 0x0; + m_pGameGroup = 0x0; + + m_Modified = false; + + m_pTeleLayer = 0x0; + m_pSpeedupLayer = 0x0; + m_pFrontLayer = 0x0; + m_pSwitchLayer = 0x0; + m_pTuneLayer = 0x0; +} + +void CEditorMap::CreateDefault(int EntitiesTexture) +{ + // add background + CLayerGroup *pGroup = NewGroup(); + pGroup->m_ParallaxX = 0; + pGroup->m_ParallaxY = 0; + CLayerQuads *pLayer = new CLayerQuads; + pLayer->m_pEditor = m_pEditor; + CQuad *pQuad = pLayer->NewQuad(); + const int Width = 800000; + const int Height = 600000; + pQuad->m_aPoints[0].x = pQuad->m_aPoints[2].x = -Width; + pQuad->m_aPoints[1].x = pQuad->m_aPoints[3].x = Width; + pQuad->m_aPoints[0].y = pQuad->m_aPoints[1].y = -Height; + pQuad->m_aPoints[2].y = pQuad->m_aPoints[3].y = Height; + pQuad->m_aColors[0].r = pQuad->m_aColors[1].r = 94; + pQuad->m_aColors[0].g = pQuad->m_aColors[1].g = 132; + pQuad->m_aColors[0].b = pQuad->m_aColors[1].b = 174; + pQuad->m_aColors[2].r = pQuad->m_aColors[3].r = 204; + pQuad->m_aColors[2].g = pQuad->m_aColors[3].g = 232; + pQuad->m_aColors[2].b = pQuad->m_aColors[3].b = 255; + pGroup->AddLayer(pLayer); + + // add game layer and reset front, tele, speedup, tune and switch layer pointers + MakeGameGroup(NewGroup()); + MakeGameLayer(new CLayerGame(50, 50)); + m_pGameGroup->AddLayer(m_pGameLayer); + + m_pFrontLayer = 0x0; + m_pTeleLayer = 0x0; + m_pSpeedupLayer = 0x0; + m_pSwitchLayer = 0x0; + m_pTuneLayer = 0x0; +} + +void CEditor::Init() +{ + m_pInput = Kernel()->RequestInterface<IInput>(); + m_pClient = Kernel()->RequestInterface<IClient>(); + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_pGraphics = Kernel()->RequestInterface<IGraphics>(); + m_pTextRender = Kernel()->RequestInterface<ITextRender>(); + m_pStorage = Kernel()->RequestInterface<IStorage>(); + m_pSound = Kernel()->RequestInterface<ISound>(); + m_RenderTools.m_pGraphics = m_pGraphics; + m_RenderTools.m_pUI = &m_UI; + m_UI.SetGraphics(m_pGraphics, m_pTextRender); + m_Map.m_pEditor = this; + + ms_CheckerTexture = Graphics()->LoadTexture("editor/checker.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_BackgroundTexture = Graphics()->LoadTexture("editor/background.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_CursorTexture = Graphics()->LoadTexture("editor/cursor.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_EntitiesTexture = Graphics()->LoadTexture("editor/entities.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + + ms_FrontTexture = Graphics()->LoadTexture("editor/front.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_TeleTexture = Graphics()->LoadTexture("editor/tele.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_SpeedupTexture = Graphics()->LoadTexture("editor/speedup.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_SwitchTexture = Graphics()->LoadTexture("editor/switch.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + ms_TuneTexture = Graphics()->LoadTexture("editor/tune.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); + + m_TilesetPicker.m_pEditor = this; + m_TilesetPicker.MakePalette(); + m_TilesetPicker.m_Readonly = true; + + m_QuadsetPicker.m_pEditor = this; + m_QuadsetPicker.NewQuad(); + m_QuadsetPicker.m_Readonly = true; + + m_Brush.m_pMap = &m_Map; + + Reset(); + m_Map.m_Modified = false; + m_Map.m_UndoModified = 0; + m_LastUndoUpdateTime = time_get(); + + ms_PickerColor = vec3(1.0f, 0.0f, 0.0f); +} + +void CEditor::DoMapBorder() +{ + CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); + + for(int i = 0; i < pT->m_Width*2; ++i) + pT->m_pTiles[i].m_Index = 1; + + for(int i = 0; i < pT->m_Width*pT->m_Height; ++i) + { + if(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3) + pT->m_pTiles[i].m_Index = 1; + } + + for(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i) + pT->m_pTiles[i].m_Index = 1; +} + +void CEditor::CreateUndoStep() +{ + void *CreateThread = thread_init(CreateUndoStepThread, this); + thread_detach(CreateThread); +} + +void CEditor::CreateUndoStepThread(void *pUser) +{ + CEditor *pEditor = (CEditor *)pUser; + + CUndo NewStep; + str_timestamp(NewStep.m_aName, sizeof(NewStep.m_aName)); + if (pEditor->m_lUndoSteps.size()) + NewStep.m_FileNum = pEditor->m_lUndoSteps[pEditor->m_lUndoSteps.size() - 1].m_FileNum + 1; + else + NewStep.m_FileNum = 0; + NewStep.m_PreviewImage = 0; + + char aBuffer[1024]; + str_format(aBuffer, sizeof(aBuffer), "editor/undo_%i.png", NewStep.m_FileNum); + pEditor->Graphics()->TakeCustomScreenshot(aBuffer); + + str_format(aBuffer, sizeof(aBuffer), "editor/undo_%i", NewStep.m_FileNum); + pEditor->Save(aBuffer); + + pEditor->m_lUndoSteps.add(NewStep); + pEditor->m_UndoRunning = false; +} + +void CEditor::UpdateAndRender() +{ + static float s_MouseX = 0.0f; + static float s_MouseY = 0.0f; + + if(m_Animate) + m_AnimateTime = (time_get()-m_AnimateStart)/(float)time_freq(); + else + m_AnimateTime = 0; + ms_pUiGotContext = 0; + + // handle mouse movement + float mx, my, Mwx, Mwy; + float rx, ry; + { + Input()->MouseRelative(&rx, &ry); +#if defined(__ANDROID__) + float tx, ty; + tx = s_MouseX; + ty = s_MouseY; + + s_MouseX = (rx / (float)g_Config.m_GfxScreenWidth) * UI()->Screen()->w; + s_MouseY = (ry / (float)g_Config.m_GfxScreenHeight) * UI()->Screen()->h; + + s_MouseX = clamp(s_MouseX, 0.0f, UI()->Screen()->w); + s_MouseY = clamp(s_MouseY, 0.0f, UI()->Screen()->h); + + m_MouseDeltaX = s_MouseX - m_OldMouseX; + m_MouseDeltaY = s_MouseY - m_OldMouseY; + m_OldMouseX = tx; + m_OldMouseY = ty; +#else + UI()->ConvertMouseMove(&rx, &ry); + m_MouseDeltaX = rx; + m_MouseDeltaY = ry; + + if(!m_LockMouse) + { + s_MouseX += rx; + s_MouseY += ry; + } + + s_MouseX = clamp(s_MouseX, 0.0f, UI()->Screen()->w); + s_MouseY = clamp(s_MouseY, 0.0f, UI()->Screen()->h); +#endif + + // update the ui + mx = s_MouseX; + my = s_MouseY; + Mwx = 0; + Mwy = 0; + + // fix correct world x and y + CLayerGroup *g = GetSelectedGroup(); + if(g) + { + float aPoints[4]; + g->Mapping(aPoints); + + float WorldWidth = aPoints[2]-aPoints[0]; + float WorldHeight = aPoints[3]-aPoints[1]; + + Mwx = aPoints[0] + WorldWidth * (s_MouseX/UI()->Screen()->w); + Mwy = aPoints[1] + WorldHeight * (s_MouseY/UI()->Screen()->h); + m_MouseDeltaWx = m_MouseDeltaX*(WorldWidth / UI()->Screen()->w); + m_MouseDeltaWy = m_MouseDeltaY*(WorldHeight / UI()->Screen()->h); + } + + int Buttons = 0; + if(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1; + if(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2; + if(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4; + +#if defined(__ANDROID__) + static int ButtonsOneFrameDelay = 0; // For Android touch input + + UI()->Update(mx,my,Mwx,Mwy,ButtonsOneFrameDelay); + ButtonsOneFrameDelay = Buttons; +#else + UI()->Update(mx,my,Mwx,Mwy,Buttons); +#endif + } + + // toggle gui + if(Input()->KeyDown(KEY_TAB)) + m_GuiActive = !m_GuiActive; + + if(Input()->KeyDown(KEY_F10)) + m_ShowMousePointer = false; + + if (g_Config.m_ClEditorUndo) + { + // Screenshot at most every 5 seconds, at least every 60 + if ((m_LastUndoUpdateTime + time_freq() * 60 < time_get() && m_Map.m_UndoModified) + || (m_LastUndoUpdateTime + time_freq() * 5 < time_get() && m_Map.m_UndoModified >= 10)) + { + m_Map.m_UndoModified = 0; + m_LastUndoUpdateTime = time_get(); + + if (!m_UndoRunning) + { + m_UndoRunning = true; + CreateUndoStep(); + } + } + } + Render(); + + if(Input()->KeyDown(KEY_F10)) + { + Graphics()->TakeScreenshot(0); + m_ShowMousePointer = true; + } + + Input()->ClearEvents(); +} + +IEditor *CreateEditor() { return new CEditor; } + +// DDRace + +void CEditorMap::MakeTeleLayer(CLayer *pLayer) +{ + m_pTeleLayer = (CLayerTele *)pLayer; + m_pTeleLayer->m_pEditor = m_pEditor; + m_pTeleLayer->m_TexID = m_pEditor->ms_TeleTexture; +} + +void CEditorMap::MakeSpeedupLayer(CLayer *pLayer) +{ + m_pSpeedupLayer = (CLayerSpeedup *)pLayer; + m_pSpeedupLayer->m_pEditor = m_pEditor; + m_pSpeedupLayer->m_TexID = m_pEditor->ms_SpeedupTexture; +} + +void CEditorMap::MakeFrontLayer(CLayer *pLayer) +{ + m_pFrontLayer = (CLayerFront *)pLayer; + m_pFrontLayer->m_pEditor = m_pEditor; + m_pFrontLayer->m_TexID = m_pEditor->ms_FrontTexture; +} + +void CEditorMap::MakeSwitchLayer(CLayer *pLayer) +{ + m_pSwitchLayer = (CLayerSwitch *)pLayer; + m_pSwitchLayer->m_pEditor = m_pEditor; + m_pSwitchLayer->m_TexID = m_pEditor->ms_SwitchTexture; +} + +void CEditorMap::MakeTuneLayer(CLayer *pLayer) +{ + m_pTuneLayer = (CLayerTune *)pLayer; + m_pTuneLayer->m_pEditor = m_pEditor; + m_pTuneLayer->m_TexID = m_pEditor->ms_TuneTexture; +} diff --git a/src/game/editor/editor.h b/src/game/editor/editor.h new file mode 100644 index 0000000..f0162d2 --- /dev/null +++ b/src/game/editor/editor.h @@ -0,0 +1,1140 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_EDITOR_EDITOR_H +#define GAME_EDITOR_EDITOR_H + +#include <math.h> + +#include <base/math.h> +#include <base/system.h> + +#include <base/tl/algorithm.h> +#include <base/tl/array.h> +#include <base/tl/sorted_array.h> +#include <base/tl/string.h> + +#include <game/client/ui.h> +#include <game/mapitems.h> +#include <game/client/render.h> + +#include <engine/shared/config.h> +#include <engine/shared/datafile.h> +#include <engine/editor.h> +#include <engine/graphics.h> +#include <engine/sound.h> + +#include "auto_map.h" + +typedef void (*INDEX_MODIFY_FUNC)(int *pIndex); + +//CRenderTools m_RenderTools; + +// CEditor SPECIFIC +enum +{ + MODE_LAYERS=0, + MODE_IMAGES, + MODE_SOUNDS, + + DIALOG_NONE=0, + DIALOG_FILE, +}; + +struct CEntity +{ + CPoint m_Position; + int m_Type; +}; + +class CEnvelope +{ +public: + int m_Channels; + array<CEnvPoint> m_lPoints; + char m_aName[32]; + float m_Bottom, m_Top; + bool m_Synchronized; + + CEnvelope(int Chan) + { + m_Channels = Chan; + m_aName[0] = 0; + m_Bottom = 0; + m_Top = 0; + m_Synchronized = true; + } + + void Resort() + { + sort(m_lPoints.all()); + FindTopBottom(0xf); + } + + void FindTopBottom(int ChannelMask) + { + m_Top = -1000000000.0f; + m_Bottom = 1000000000.0f; + for(int i = 0; i < m_lPoints.size(); i++) + { + for(int c = 0; c < m_Channels; c++) + { + if(ChannelMask&(1<<c)) + { + float v = fx2f(m_lPoints[i].m_aValues[c]); + if(v > m_Top) m_Top = v; + if(v < m_Bottom) m_Bottom = v; + } + } + } + } + + 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; + p.m_Time = Time; + p.m_aValues[0] = v0; + p.m_aValues[1] = v1; + p.m_aValues[2] = v2; + p.m_aValues[3] = v3; + p.m_Curvetype = CURVETYPE_LINEAR; + m_lPoints.add(p); + Resort(); + } + + float EndTime() + { + if(m_lPoints.size()) + return m_lPoints[m_lPoints.size()-1].m_Time*(1.0f/1000.0f); + return 0; + } +}; + + +class CLayer; +class CLayerGroup; +class CEditorMap; + +class CLayer +{ +public: + class CEditor *m_pEditor; + class IGraphics *Graphics(); + class ITextRender *TextRender(); + + CLayer() + { + m_Type = LAYERTYPE_INVALID; + str_copy(m_aName, "(invalid)", sizeof(m_aName)); + m_Visible = true; + m_Readonly = false; + m_SaveToMap = true; + 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) {} + virtual void BrushDraw(CLayer *pBrush, float x, float y) {} + virtual void BrushPlace(CLayer *pBrush, float x, float y) {} + 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 ModifySoundIndex(INDEX_MODIFY_FUNC pfnFunc) {} + + virtual void GetSize(float *w, float *h) { *w = 0; *h = 0;} + + char m_aName[12]; + int m_Type; + int m_Flags; + + bool m_Readonly; + bool m_Visible; + bool m_SaveToMap; +}; + +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; + + char m_aName[12]; + bool m_GameGroup; + bool m_Visible; + bool m_SaveToMap; + bool m_Collapse; + + 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 + { + return m_lLayers.size() == 0; // stupid function, since its bad for Fillselection: TODO add a function for Fillselection that returns whether a specific tile is used in the given layer + } + + /*bool IsUsedInThisLayer(int Layer, int Index) // <--------- this is what i meant but cause i dont know which Indexes belongs to which layers i cant finish yet + { + switch Layer + { + case LAYERTYPE_GAME: // security + return true; + case LAYERTYPE_FRONT: + return true; + case LAYERTYPE_TELE: + { + if (Index ==) // you could add an 2D array into mapitems.h which defines which Indexes belong to which layer(s) + } + case LAYERTYPE_SPEEDUP: + { + if (Index == TILE_BOOST) + return true; + else + return false; + } + case LAYERTYPE_SWITCH: + { + + } + case LAYERTYPE_TUNE: + { + if (Index == TILE_TUNE1) + return true; + else + return false; + } + default: + return false; + } + }*/ + + void Clear() + { + m_lLayers.delete_all(); + } + + void AddLayer(CLayer *l); + + void ModifyImageIndex(INDEX_MODIFY_FUNC Func) + { + 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++) + m_lLayers[i]->ModifyEnvelopeIndex(Func); + } + + void ModifySoundIndex(INDEX_MODIFY_FUNC Func) + { + for(int i = 0; i < m_lLayers.size(); i++) + m_lLayers[i]->ModifySoundIndex(Func); + } +}; + +class CEditorImage : public CImageInfo +{ +public: + CEditor *m_pEditor; + + CEditorImage(CEditor *pEditor) + : m_AutoMapper(pEditor) + { + m_pEditor = pEditor; + m_TexID = -1; + m_aName[0] = 0; + m_External = 0; + m_Width = 0; + m_Height = 0; + m_pData = 0; + m_Format = 0; + } + + ~CEditorImage(); + + void AnalyseTileFlags(); + + int m_TexID; + int m_External; + char m_aName[128]; + unsigned char m_aTileFlags[256]; + class CAutoMapper m_AutoMapper; +}; + +class CEditorSound +{ +public: + CEditor *m_pEditor; + + CEditorSound(CEditor *pEditor) + { + m_pEditor = pEditor; + m_aName[0] = 0; + m_External = 0; + m_SoundID = 0; + + m_pData = 0x0; + m_DataSize = 0; + } + + ~CEditorSound(); + + int m_SoundID; + int m_External; + char m_aName[128]; + + void *m_pData; + unsigned m_DataSize; +}; + +class CEditorMap +{ + void MakeGameGroup(CLayerGroup *pGroup); + void MakeGameLayer(CLayer *pLayer); +public: + CEditor *m_pEditor; + bool m_Modified; + int m_UndoModified; + + CEditorMap() + { + Clean(); + } + + array<CLayerGroup*> m_lGroups; + array<CEditorImage*> m_lImages; + array<CEnvelope*> m_lEnvelopes; + array<CEditorSound*> m_lSounds; + + class CMapInfo + { + public: + char m_aAuthorTmp[32]; + char m_aVersionTmp[16]; + char m_aCreditsTmp[128]; + char m_aLicenseTmp[32]; + + char m_aAuthor[32]; + char m_aVersion[16]; + char m_aCredits[128]; + char m_aLicense[32]; + + void Reset() + { + m_aAuthorTmp[0] = 0; + m_aVersionTmp[0] = 0; + m_aCreditsTmp[0] = 0; + m_aLicenseTmp[0] = 0; + + m_aAuthor[0] = 0; + m_aVersion[0] = 0; + m_aCredits[0] = 0; + m_aLicense[0] = 0; + } + }; + CMapInfo m_MapInfo; + + struct CSetting + { + char m_aCommand[64]; + }; + array<CSetting> m_lSettings; + + class CLayerGame *m_pGameLayer; + CLayerGroup *m_pGameGroup; + + CEnvelope *NewEnvelope(int Channels) + { + m_Modified = true; + m_UndoModified++; + CEnvelope *e = new CEnvelope(Channels); + m_lEnvelopes.add(e); + return e; + } + + void DeleteEnvelope(int Index); + + CLayerGroup *NewGroup() + { + m_Modified = true; + m_UndoModified++; + CLayerGroup *g = new CLayerGroup; + g->m_pMap = this; + m_lGroups.add(g); + return g; + } + + int SwapGroups(int Index0, int Index1) + { + if(Index0 < 0 || Index0 >= m_lGroups.size()) return Index0; + if(Index1 < 0 || Index1 >= m_lGroups.size()) return Index0; + if(Index0 == Index1) return Index0; + m_Modified = true; + m_UndoModified++; + swap(m_lGroups[Index0], m_lGroups[Index1]); + return Index1; + } + + void DeleteGroup(int Index) + { + if(Index < 0 || Index >= m_lGroups.size()) return; + m_Modified = true; + m_UndoModified++; + delete m_lGroups[Index]; + m_lGroups.remove_index(Index); + } + + void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) + { + m_Modified = true; + m_UndoModified++; + for(int i = 0; i < m_lGroups.size(); i++) + m_lGroups[i]->ModifyImageIndex(pfnFunc); + } + + void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) + { + m_Modified = true; + m_UndoModified++; + for(int i = 0; i < m_lGroups.size(); i++) + m_lGroups[i]->ModifyEnvelopeIndex(pfnFunc); + } + + void ModifySoundIndex(INDEX_MODIFY_FUNC pfnFunc) + { + m_Modified = true; + m_UndoModified++; + for(int i = 0; i < m_lGroups.size(); i++) + m_lGroups[i]->ModifySoundIndex(pfnFunc); + } + + void Clean(); + void CreateDefault(int EntitiesTexture); + + // io + int Save(class IStorage *pStorage, const char *pFilename); + int Load(class IStorage *pStorage, const char *pFilename, int StorageType); + + // DDRace + + class CLayerTele *m_pTeleLayer; + class CLayerSpeedup *m_pSpeedupLayer; + class CLayerFront *m_pFrontLayer; + class CLayerSwitch *m_pSwitchLayer; + class CLayerTune *m_pTuneLayer; + void MakeTeleLayer(CLayer *pLayer); + void MakeSpeedupLayer(CLayer *pLayer); + void MakeFrontLayer(CLayer *pLayer); + void MakeSwitchLayer(CLayer *pLayer); + void MakeTuneLayer(CLayer *pLayer); +}; + + +struct CProperty +{ + const char *m_pName; + int m_Value; + int m_Type; + int m_Min; + int m_Max; +}; + +enum +{ + PROPTYPE_NULL=0, + PROPTYPE_BOOL, + PROPTYPE_INT_STEP, + PROPTYPE_INT_SCROLL, + PROPTYPE_ANGLE_SCROLL, + PROPTYPE_COLOR, + PROPTYPE_IMAGE, + PROPTYPE_ENVELOPE, + PROPTYPE_SHIFT, + PROPTYPE_SOUND, +}; + +typedef struct +{ + int x, y; + int w, h; +} RECTi; + +class CLayerTiles : public CLayer +{ +public: + CLayerTiles(int w, int h); + ~CLayerTiles(); + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + + void MakePalette(); + virtual void Render(); + + int ConvertX(float x) const; + int ConvertY(float y) const; + void Convert(CUIRect Rect, RECTi *pOut); + void Snap(CUIRect *pRect); + void Clamp(RECTi *pRect); + + virtual void BrushSelecting(CUIRect Rect); + virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect); + virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); + 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; } + + int m_TexID; + int m_Game; + int m_Image; + int m_Width; + int m_Height; + CColor m_Color; + int m_ColorEnv; + int m_ColorEnvOffset; + CTile *m_pTiles; + + // DDRace + + int m_Tele; + int m_Speedup; + int m_Front; + int m_Switch; + int m_Tune; + char m_aFileName[512]; +}; + +class CLayerQuads : public CLayer +{ +public: + CLayerQuads(); + ~CLayerQuads(); + + virtual void Render(); + CQuad *NewQuad(); + + virtual void BrushSelecting(CUIRect Rect); + virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect); + virtual void BrushPlace(CLayer *pBrush, float wx, float wy); + 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; +}; + +class CLayerGame : public CLayerTiles +{ +public: + CLayerGame(int w, int h); + ~CLayerGame(); + + virtual int RenderProperties(CUIRect *pToolbox); +}; + +class CEditor : public IEditor +{ + class IInput *m_pInput; + class IClient *m_pClient; + class IConsole *m_pConsole; + class IGraphics *m_pGraphics; + class ITextRender *m_pTextRender; + class ISound *m_pSound; + class IStorage *m_pStorage; + CRenderTools m_RenderTools; + CUI m_UI; +public: + class IInput *Input() { return m_pInput; }; + class IClient *Client() { return m_pClient; }; + class IConsole *Console() { return m_pConsole; }; + class IGraphics *Graphics() { return m_pGraphics; }; + class ISound *Sound() { return m_pSound; } + class ITextRender *TextRender() { return m_pTextRender; }; + class IStorage *Storage() { return m_pStorage; }; + CUI *UI() { return &m_UI; } + CRenderTools *RenderTools() { return &m_RenderTools; } + + CEditor() : m_TilesetPicker(16, 16) + { + m_pInput = 0; + m_pClient = 0; + m_pGraphics = 0; + m_pTextRender = 0; + m_pSound = 0; + + m_Mode = MODE_LAYERS; + m_Dialog = 0; + m_EditBoxActive = 0; + m_pTooltip = 0; + + m_GridActive = false; + m_GridFactor = 1; + + m_aFileName[0] = 0; + m_aFileSaveName[0] = 0; + m_ValidSaveFilename = false; + + m_PopupEventActivated = false; + m_PopupEventWasActivated = false; + + m_FileDialogStorageType = 0; + m_pFileDialogTitle = 0; + m_pFileDialogButtonText = 0; + m_pFileDialogUser = 0; + m_aFileDialogFileName[0] = 0; + m_aFileDialogCurrentFolder[0] = 0; + m_aFileDialogCurrentLink[0] = 0; + m_pFileDialogPath = m_aFileDialogCurrentFolder; + m_aFileDialogActivate = false; + m_FileDialogScrollValue = 0.0f; + m_FilesSelectedIndex = -1; + m_FilesStartAt = 0; + m_FilesCur = 0; + m_FilesStopAt = 999; + + m_WorldOffsetX = 0; + m_WorldOffsetY = 0; + m_EditorOffsetX = 0.0f; + m_EditorOffsetY = 0.0f; + + m_WorldZoom = 1.0f; + m_ZoomLevel = 200; + m_LockMouse = false; + m_ShowMousePointer = true; + m_MouseDeltaX = 0; + m_MouseDeltaY = 0; + m_MouseDeltaWx = 0; + m_MouseDeltaWy = 0; +#if defined(__ANDROID__) + m_OldMouseX = 0; + m_OldMouseY = 0; +#endif + + 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; + m_ShowUndo = 0; + m_UndoScrollValue = 0.0f; + m_ShowServerSettingsEditor = false; + + m_ShowEnvelopePreview = 0; + m_SelectedQuadEnvelope = -1; + m_SelectedEnvelopePoint = -1; + + m_CommandBox = 0.0f; + m_aSettingsCommand[0] = 0; + + ms_CheckerTexture = 0; + ms_BackgroundTexture = 0; + ms_CursorTexture = 0; + ms_EntitiesTexture = 0; + + ms_pUiGotContext = 0; + + // DDRace + + ms_FrontTexture = 0; + ms_TeleTexture = 0; + ms_SpeedupTexture = 0; + ms_SwitchTexture = 0; + ms_TuneTexture = 0; + m_TeleNumber = 1; + m_SwitchNum = 1; + m_TuningNum = 1; + m_SwitchDelay = 0; + m_SpeedupForce = 50; + m_SpeedupMaxSpeed = 0; + m_SpeedupAngle = 0; + } + + virtual void Init(); + virtual void UpdateAndRender(); + virtual bool HasUnsavedData() { return m_Map.m_Modified; } + + int64 m_LastUndoUpdateTime; + bool m_UndoRunning; + void CreateUndoStep(); + static void CreateUndoStepThread(void *pUser); + int UndoStep(); + struct CUndo + { + int m_FileNum; + int m_ButtonId; + char m_aName[128]; + int m_PreviewImage; + }; + array<CUndo> m_lUndoSteps; + bool m_Undo; + int m_ShowUndo; + float m_UndoScrollValue; + 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); + int Append(const char *pFilename, int StorageType); + void Render(); + + CQuad *GetSelectedQuad(); + CLayer *GetSelectedLayerType(int Index, int Type); + CLayer *GetSelectedLayer(int Index); + CLayerGroup *GetSelectedGroup(); + CSoundSource *GetSelectedSource(); + + int DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal, vec4 color = vec4(1,1,1,0.5f)); + + int m_Mode; + int m_Dialog; + int m_EditBoxActive; + const char *m_pTooltip; + + bool m_GridActive; + int m_GridFactor; + + char m_aFileName[512]; + char m_aFileSaveName[512]; + bool m_ValidSaveFilename; + + enum + { + POPEVENT_EXIT=0, + POPEVENT_LOAD, + POPEVENT_NEW, + POPEVENT_SAVE, + }; + + int m_PopupEventType; + int m_PopupEventActivated; + int m_PopupEventWasActivated; + + enum + { + FILETYPE_MAP, + FILETYPE_IMG, + FILETYPE_SOUND, + + MAX_PATH_LENGTH = 512 + }; + + int m_FileDialogStorageType; + const char *m_pFileDialogTitle; + const char *m_pFileDialogButtonText; + void (*m_pfnFileDialogFunc)(const char *pFileName, int StorageType, void *pUser); + void *m_pFileDialogUser; + char m_aFileDialogFileName[MAX_PATH_LENGTH]; + char m_aFileDialogCurrentFolder[MAX_PATH_LENGTH]; + char m_aFileDialogCurrentLink[MAX_PATH_LENGTH]; + char *m_pFileDialogPath; + bool m_aFileDialogActivate; + int m_FileDialogFileType; + float m_FileDialogScrollValue; + int m_FilesSelectedIndex; + char m_FileDialogNewFolderName[64]; + char m_FileDialogErrString[64]; + int m_FilePreviewImage; + CImageInfo m_FilePreviewImageInfo; + + + struct CFilelistItem + { + char m_aFilename[128]; + char m_aName[128]; + 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; } + }; + sorted_array<CFilelistItem> m_FileList; + int m_FilesStartAt; + int m_FilesCur; + int m_FilesStopAt; + + float m_WorldOffsetX; + float m_WorldOffsetY; + float m_EditorOffsetX; + float m_EditorOffsetY; + float m_WorldZoom; + int m_ZoomLevel; + bool m_LockMouse; + bool m_ShowMousePointer; + bool m_GuiActive; + bool m_ProofBorders; + float m_MouseDeltaX; + float m_MouseDeltaY; + float m_MouseDeltaWx; + float m_MouseDeltaWy; +#if defined(__ANDROID__) + float m_OldMouseX; + float m_OldMouseY; +#endif + + bool m_ShowTileInfo; + bool m_ShowDetail; + bool m_Animate; + int64 m_AnimateStart; + float m_AnimateTime; + float m_AnimateSpeed; + + int m_ShowEnvelopeEditor; + int m_ShowEnvelopePreview; //Values: 0-Off|1-Selected Envelope|2-All + bool m_ShowServerSettingsEditor; + bool m_ShowPicker; + + int m_SelectedLayer; + int m_SelectedGroup; + int m_SelectedQuad; + int m_SelectedPoints; + int m_SelectedEnvelope; + int m_SelectedEnvelopePoint; + int m_SelectedQuadEnvelope; + int m_SelectedImage; + int m_SelectedSound; + int m_SelectedSource; + + static int ms_CheckerTexture; + static int ms_BackgroundTexture; + static int ms_CursorTexture; + static int ms_EntitiesTexture; + + CLayerGroup m_Brush; + CLayerTiles m_TilesetPicker; + CLayerQuads m_QuadsetPicker; + + static const void *ms_pUiGotContext; + + CEditorMap m_Map; + int m_ShiftBy; + + static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser); + + float m_CommandBox; + char m_aSettingsCommand[64]; + + 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); + int DoButton_Env(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pToolTip, vec3 Color); + + int DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); + int DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize=10.0f); + int DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); + 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 DoButton_ColorPicker(const void *pID, const CUIRect *pRect, vec4 *pColor, const char *pToolTip=0); + + int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden=false, int Corners=CUI::CORNER_ALL); + + void RenderBackground(CUIRect View, int Texture, float Size, float Brightness); + + void RenderGrid(CLayerGroup *pGroup); + + 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, bool isDegree=false, bool isHex=false); + + static int PopupGroup(CEditor *pEditor, CUIRect View); + static int PopupLayer(CEditor *pEditor, CUIRect View); + static int PopupQuad(CEditor *pEditor, CUIRect View); + static int PopupPoint(CEditor *pEditor, CUIRect View); + static int PopupNewFolder(CEditor *pEditor, CUIRect View); + static int PopupMapInfo(CEditor *pEditor, CUIRect View); + static int PopupEvent(CEditor *pEditor, CUIRect View); + static int PopupSelectImage(CEditor *pEditor, CUIRect View); + static int PopupSelectSound(CEditor *pEditor, CUIRect View); + static int PopupSelectGametileOp(CEditor *pEditor, CUIRect View); + static int PopupImage(CEditor *pEditor, CUIRect View); + static int PopupMenuFile(CEditor *pEditor, CUIRect View); + static int PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View); + static int PopupSound(CEditor *pEditor, CUIRect View); + static int PopupSource(CEditor *pEditor, CUIRect View); + static int PopupColorPicker(CEditor *pEditor, CUIRect View); + + static void CallbackOpenMap(const char *pFileName, int StorageType, void *pUser); + static void CallbackAppendMap(const char *pFileName, int StorageType, void *pUser); + static void CallbackSaveMap(const char *pFileName, int StorageType, void *pUser); + static void CallbackSaveCopyMap(const char *pFileName, int StorageType, void *pUser); + + void PopupSelectImageInvoke(int Current, float x, float y); + int PopupSelectImageResult(); + + void PopupSelectGametileOpInvoke(float x, float y); + int PopupSelectGameTileOpResult(); + + void PopupSelectConfigAutoMapInvoke(float x, float y); + int PopupSelectConfigAutoMapResult(); + + void PopupSelectSoundInvoke(int Current, float x, float y); + int PopupSelectSoundResult(); + + vec4 ButtonColorMul(const void *pID); + + void DoQuadEnvelopes(const array<CQuad> &m_lQuads, int TexID = -1); + void DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int pIndex); + void DoQuadPoint(CQuad *pQuad, int QuadIndex, int v); + + void DoSoundSource(CSoundSource *pSource, int Index); + + void DoMapEditor(CUIRect View, CUIRect Toolbar); + void DoToolbar(CUIRect Toolbar); + 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 ReplaceSound(const char *pFileName, int StorageType, void *pUser); + static void AddImage(const char *pFilename, int StorageType, void *pUser); + static void AddSound(const char *pFileName, int StorageType, void *pUser); + + void RenderImages(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); + void RenderLayers(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); + void RenderSounds(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); + void RenderModebar(CUIRect View); + void RenderStatusbar(CUIRect View); + void RenderEnvelopeEditor(CUIRect View); + void RenderUndoList(CUIRect View); + void RenderServerSettingsEditor(CUIRect View); + + void RenderMenubar(CUIRect Menubar); + void RenderFileDialog(); + + void AddFileDialogEntry(int Index, CUIRect *pView); + void SortImages(); + static void ExtractName(const char *pFileName, char *pName, int BufferSize) + { + const char *pExtractedName = pFileName; + const char *pEnd = 0; + for(; *pFileName; ++pFileName) + { + if(*pFileName == '/' || *pFileName == '\\') + pExtractedName = pFileName+1; + else if(*pFileName == '.') + pEnd = pFileName; + } + + int Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; + str_copy(pName, pExtractedName, Length); + } + + int GetLineDistance(); + void ZoomMouseTarget(float ZoomFactor); + + static vec3 ms_PickerColor; + static int ms_SVPicker; + static int ms_HuePicker; + + // DDRace + + static int ms_FrontTexture; + static int ms_TeleTexture; + static int ms_SpeedupTexture; + static int ms_SwitchTexture; + static int ms_TuneTexture; + static int PopupTele(CEditor *pEditor, CUIRect View); + static int PopupSpeedup(CEditor *pEditor, CUIRect View); + static int PopupSwitch(CEditor *pEditor, CUIRect View); + static int PopupTune(CEditor *pEditor, CUIRect View); + unsigned char m_TeleNumber; + + unsigned char m_TuningNum; + + unsigned char m_SpeedupForce; + unsigned char m_SpeedupMaxSpeed; + short m_SpeedupAngle; + + unsigned char m_SwitchNum; + unsigned char m_SwitchDelay; +}; + +// make sure to inline this function +inline class IGraphics *CLayer::Graphics() { return m_pEditor->Graphics(); } +inline class ITextRender *CLayer::TextRender() { return m_pEditor->TextRender(); } + +// DDRace + +class CLayerTele : public CLayerTiles +{ +public: + CLayerTele(int w, int h); + ~CLayerTele(); + + CTeleTile *m_pTeleTile; + unsigned char m_TeleNum; + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); + virtual void BrushFlipX(); + virtual void BrushFlipY(); + virtual void BrushRotate(float Amount); + virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); +}; + +class CLayerSpeedup : public CLayerTiles +{ +public: + CLayerSpeedup(int w, int h); + ~CLayerSpeedup(); + + CSpeedupTile *m_pSpeedupTile; + unsigned char m_SpeedupForce; + unsigned char m_SpeedupMaxSpeed; + unsigned char m_SpeedupAngle; + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); + virtual void BrushFlipX(); + virtual void BrushFlipY(); + virtual void BrushRotate(float Amount); + virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); +}; + +class CLayerFront : public CLayerTiles +{ +public: + CLayerFront(int w, int h); + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); +}; + +class CLayerSwitch : public CLayerTiles +{ +public: + CLayerSwitch(int w, int h); + ~CLayerSwitch(); + + CSwitchTile *m_pSwitchTile; + unsigned char m_SwitchNumber; + unsigned char m_SwitchDelay; + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); + virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); +}; + +class CLayerTune : public CLayerTiles +{ +public: + CLayerTune(int w, int h); + ~CLayerTune(); + + CTuneTile *m_pTuneTile; + unsigned char m_TuningNumber; + + virtual void Resize(int NewW, int NewH); + virtual void Shift(int Direction); + virtual void BrushDraw(CLayer *pBrush, float wx, float wy); + virtual void BrushFlipX(); + virtual void BrushFlipY(); + virtual void BrushRotate(float Amount); + virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); +}; + +class CLayerSounds : public CLayer +{ +public: + CLayerSounds(); + ~CLayerSounds(); + + virtual void Render(); + CSoundSource *NewSource(); + + virtual void BrushSelecting(CUIRect Rect); + virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect); + virtual void BrushPlace(CLayer *pBrush, float wx, float wy); + + virtual int RenderProperties(CUIRect *pToolbox); + + virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc); + virtual void ModifySoundIndex(INDEX_MODIFY_FUNC pfnFunc); + + int m_Sound; + array<CSoundSource> m_lSources; +}; + + +#endif diff --git a/src/game/editor/io.cpp b/src/game/editor/io.cpp new file mode 100644 index 0000000..e1797da --- /dev/null +++ b/src/game/editor/io.cpp @@ -0,0 +1,1270 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/tl/array.h> + +#include <engine/client.h> +#include <engine/console.h> +#include <engine/graphics.h> +#include <engine/serverbrowser.h> +#include <engine/storage.h> +#include <game/gamecore.h> +#include "editor.h" + +template<typename T> +static int MakeVersion(int i, const T &v) +{ return (i<<16)+sizeof(T); } + +// backwards compatiblity +/* +void editor_load_old(DATAFILE *df, MAP *map) +{ + class mapres_image + { + public: + int width; + int height; + int image_data; + }; + + struct mapres_tilemap + { + int image; + int width; + int height; + int x, y; + int scale; + int data; + int main; + }; + + struct mapres_entity + { + int x, y; + int data[1]; + }; + + struct mapres_spawnpoint + { + int x, y; + }; + + struct mapres_item + { + int x, y; + int type; + }; + + struct mapres_flagstand + { + int x, y; + }; + + enum + { + MAPRES_ENTS_START=1, + MAPRES_SPAWNPOINT=1, + MAPRES_ITEM=2, + MAPRES_SPAWNPOINT_RED=3, + MAPRES_SPAWNPOINT_BLUE=4, + MAPRES_FLAGSTAND_RED=5, + MAPRES_FLAGSTAND_BLUE=6, + MAPRES_ENTS_END, + + ITEM_NULL=0, + ITEM_WEAPON_GUN=0x00010001, + ITEM_WEAPON_SHOTGUN=0x00010002, + ITEM_WEAPON_ROCKET=0x00010003, + ITEM_WEAPON_SNIPER=0x00010004, + ITEM_WEAPON_HAMMER=0x00010005, + ITEM_HEALTH =0x00020001, + ITEM_ARMOR=0x00030001, + ITEM_NINJA=0x00040001, + }; + + enum + { + MAPRES_REGISTERED=0x8000, + MAPRES_IMAGE=0x8001, + MAPRES_TILEMAP=0x8002, + MAPRES_COLLISIONMAP=0x8003, + MAPRES_TEMP_THEME=0x8fff, + }; + + // load tilemaps + int game_width = 0; + int game_height = 0; + { + int start, num; + datafile_get_type(df, MAPRES_TILEMAP, &start, &num); + 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 + for(int i = 0; i < map->groups[0]->layers.len()-1; i++) + { + 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; + } + + // add new layer + map->groups[0]->add_layer(l); + + // 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; + datafile_get_type(df, MAPRES_IMAGE, &start, &count); + for(int i = 0; i < count; i++) + { + mapres_image *imgres = (mapres_image *)datafile_get_item(df, start+i, 0, 0); + void *data = datafile_get_data(df, imgres->image_data); + + EDITOR_IMAGE *img = new EDITOR_IMAGE; + 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; + g->resize(game_width, game_height); + for(int t = MAPRES_ENTS_START; t < MAPRES_ENTS_END; t++) + { + // fetch entities of this class + int start, num; + datafile_get_type(df, t, &start, &num); + + + for(int i = 0; i < num; i++) + { + mapres_entity *e = (mapres_entity *)datafile_get_item(df, start+i,0,0); + 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; + else if(t == MAPRES_FLAGSTAND_RED) id = ENTITY_FLAGSTAND_RED; + else if(t == MAPRES_FLAGSTAND_BLUE) id = ENTITY_FLAGSTAND_BLUE; + else if(t == MAPRES_ITEM) + { + if(e->data[0] == ITEM_WEAPON_SHOTGUN) id = ENTITY_WEAPON_SHOTGUN; + else if(e->data[0] == ITEM_WEAPON_ROCKET) id = ENTITY_WEAPON_GRENADE; + else if(e->data[0] == ITEM_NINJA) id = ENTITY_POWERUP_NINJA; + 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; + } + } + } +}*/ + +// compatibility with old sound layers +struct CSoundSource_DEPRECATED +{ + CPoint m_Position; + int m_Loop; + int m_TimeDelay; // in s + int m_FalloffDistance; + int m_PosEnv; + int m_PosEnvOffset; + int m_SoundEnv; + int m_SoundEnvOffset; +}; + +int CEditor::Save(const char *pFilename) +{ + return m_Map.Save(Kernel()->RequestInterface<IStorage>(), pFilename); +} + +int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) +{ + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "saving to '%s'...", pFileName); + m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "editor", aBuf); + CDataFileWriter df; + if(!df.Open(pStorage, pFileName)) + { + str_format(aBuf, sizeof(aBuf), "failed to open file '%s'...", pFileName); + m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "editor", aBuf); + return 0; + } + + // save version + { + CMapItemVersion Item; + Item.m_Version = 1; + df.AddItem(MAPITEMTYPE_VERSION, 0, sizeof(Item), &Item); + } + + // save map info + { + CMapItemInfoSettings Item; + Item.m_Version = 1; + + if(m_MapInfo.m_aAuthor[0]) + Item.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor)+1, m_MapInfo.m_aAuthor); + else + Item.m_Author = -1; + if(m_MapInfo.m_aVersion[0]) + Item.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion)+1, m_MapInfo.m_aVersion); + else + Item.m_MapVersion = -1; + if(m_MapInfo.m_aCredits[0]) + Item.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits)+1, m_MapInfo.m_aCredits); + else + Item.m_Credits = -1; + if(m_MapInfo.m_aLicense[0]) + Item.m_License = df.AddData(str_length(m_MapInfo.m_aLicense)+1, m_MapInfo.m_aLicense); + else + Item.m_License = -1; + + Item.m_Settings = -1; + if(m_lSettings.size()) + { + int Size = 0; + for(int i = 0; i < m_lSettings.size(); i++) + { + Size += str_length(m_lSettings[i].m_aCommand) + 1; + } + + char *pSettings = (char *)mem_alloc(Size, 1); + char *pNext = pSettings; + for(int i = 0; i < m_lSettings.size(); i++) + { + int Length = str_length(m_lSettings[i].m_aCommand) + 1; + mem_copy(pNext, m_lSettings[i].m_aCommand, Length); + pNext += Length; + } + Item.m_Settings = df.AddData(Size, pSettings); + mem_free(pSettings); + } + + df.AddItem(MAPITEMTYPE_INFO, 0, sizeof(Item), &Item); + } + + // save images + 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; + Item.m_ImageName = df.AddData(str_length(pImg->m_aName)+1, pImg->m_aName); + if(pImg->m_External) + Item.m_ImageData = -1; + else + { + if(pImg->m_Format == CImageInfo::FORMAT_RGB) + { + // Convert to RGBA + unsigned char *pData = (unsigned char*) mem_alloc(Item.m_Width*Item.m_Height*4, 1); + for(int i = 0; i < Item.m_Width*Item.m_Height; i++) + { + pData[i*4] = ((unsigned char*)(pImg->m_pData))[i*3]; + pData[i*4+1] = ((unsigned char*)(pImg->m_pData))[i*3+1]; + pData[i*4+2] = ((unsigned char*)(pImg->m_pData))[i*3+2]; + pData[i*4+3] = 255; + } + Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*4, pData); + mem_free(pData); + } + else + { + Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*4, pImg->m_pData); + } + } + df.AddItem(MAPITEMTYPE_IMAGE, i, sizeof(Item), &Item); + } + + // save sounds + for(int i = 0; i < m_lSounds.size(); i++) + { + CEditorSound *pSound = m_lSounds[i]; + + CMapItemSound Item; + Item.m_Version = 1; + + Item.m_External = pSound->m_External; + Item.m_SoundName = df.AddData(str_length(pSound->m_aName)+1, pSound->m_aName); + if(pSound->m_External) + { + Item.m_SoundDataSize = 0; + Item.m_SoundData = -1; + } + else + { + Item.m_SoundData = df.AddData(pSound->m_DataSize, pSound->m_pData); + Item.m_SoundDataSize = pSound->m_DataSize; + } + + df.AddItem(MAPITEMTYPE_SOUND, i, sizeof(Item), &Item); + } + + // save layers + int LayerCount = 0, GroupCount = 0; + for(int g = 0; g < m_lGroups.size(); g++) + { + CLayerGroup *pGroup = m_lGroups[g]; + if(!pGroup->m_SaveToMap) + continue; + + 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; + GItem.m_OffsetY = pGroup->m_OffsetY; + GItem.m_UseClipping = pGroup->m_UseClipping; + GItem.m_ClipX = pGroup->m_ClipX; + GItem.m_ClipY = pGroup->m_ClipY; + GItem.m_ClipW = pGroup->m_ClipW; + GItem.m_ClipH = pGroup->m_ClipH; + GItem.m_StartLayer = LayerCount; + GItem.m_NumLayers = 0; + + // save group name + StrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), pGroup->m_aName); + + for(int l = 0; l < pGroup->m_lLayers.size(); l++) + { + if(!pGroup->m_lLayers[l]->m_SaveToMap) + continue; + + if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_TILES) + { + 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 = 3; + + Item.m_Layer.m_Flags = pLayer->m_Flags; + Item.m_Layer.m_Type = pLayer->m_Type; + + Item.m_Color = pLayer->m_Color; + Item.m_ColorEnv = pLayer->m_ColorEnv; + Item.m_ColorEnvOffset = pLayer->m_ColorEnvOffset; + + Item.m_Width = pLayer->m_Width; + Item.m_Height = pLayer->m_Height; + // Item.m_Flags = pLayer->m_Game ? TILESLAYERFLAG_GAME : 0; + + if(pLayer->m_Tele) + Item.m_Flags = TILESLAYERFLAG_TELE; + else if(pLayer->m_Speedup) + Item.m_Flags = TILESLAYERFLAG_SPEEDUP; + else if(pLayer->m_Front) + Item.m_Flags = TILESLAYERFLAG_FRONT; + else if(pLayer->m_Switch) + Item.m_Flags = TILESLAYERFLAG_SWITCH; + else if(pLayer->m_Tune) + Item.m_Flags = TILESLAYERFLAG_TUNE; + else + Item.m_Flags = pLayer->m_Game ? TILESLAYERFLAG_GAME : 0; + + Item.m_Image = pLayer->m_Image; + if(pLayer->m_Tele) + { + CTile *Tiles = new CTile[pLayer->m_Width*pLayer->m_Height]; + mem_zero(Tiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), Tiles); + Item.m_Tele = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTeleTile), ((CLayerTele *)pLayer)->m_pTeleTile); + delete[] Tiles; + } + else if(pLayer->m_Speedup) + { + CTile *Tiles = new CTile[pLayer->m_Width*pLayer->m_Height]; + mem_zero(Tiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), Tiles); + Item.m_Speedup = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CSpeedupTile), ((CLayerSpeedup *)pLayer)->m_pSpeedupTile); + delete[] Tiles; + } + else if(pLayer->m_Front) + { + CTile *Tiles = new CTile[pLayer->m_Width*pLayer->m_Height]; + mem_zero(Tiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), Tiles); + Item.m_Front = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); + delete[] Tiles; + } + else if(pLayer->m_Switch) + { + CTile *Tiles = new CTile[pLayer->m_Width*pLayer->m_Height]; + mem_zero(Tiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), Tiles); + Item.m_Switch = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CSwitchTile), ((CLayerSwitch *)pLayer)->m_pSwitchTile); + delete[] Tiles; + } + else if(pLayer->m_Tune) + { + CTile *Tiles = new CTile[pLayer->m_Width*pLayer->m_Height]; + mem_zero(Tiles, pLayer->m_Width*pLayer->m_Height*sizeof(CTile)); + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), Tiles); + Item.m_Tune = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTuneTile), ((CLayerTune *)pLayer)->m_pTuneTile); + delete[] Tiles; + } + else + Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); + + // save layer name + StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + + df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); + + GItem.m_NumLayers++; + LayerCount++; + } + else if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_QUADS) + { + m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving quads layer"); + CLayerQuads *pLayer = (CLayerQuads *)pGroup->m_lLayers[l]; + if(pLayer->m_lQuads.size()) + { + CMapItemLayerQuads Item; + Item.m_Version = 2; + 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()); + + // save layer name + StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + + df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); + + // clean up + //mem_free(quads); + + GItem.m_NumLayers++; + LayerCount++; + } + } + else if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_SOUNDS) + { + m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving sounds layer"); + CLayerSounds *pLayer = (CLayerSounds *)pGroup->m_lLayers[l]; + if(pLayer->m_lSources.size()) + { + CMapItemLayerSounds Item; + Item.m_Version = CMapItemLayerSounds::CURRENT_VERSION; + Item.m_Layer.m_Flags = pLayer->m_Flags; + Item.m_Layer.m_Type = pLayer->m_Type; + Item.m_Sound = pLayer->m_Sound; + + // add the data + Item.m_NumSources = pLayer->m_lSources.size(); + Item.m_Data = df.AddDataSwapped(pLayer->m_lSources.size()*sizeof(CSoundSource), pLayer->m_lSources.base_ptr()); + + // save layer name + StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); + + df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); + GItem.m_NumLayers++; + LayerCount++; + } + } + } + + df.AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem); + } + + // save envelopes + int PointCount = 0; + for(int e = 0; e < m_lEnvelopes.size(); e++) + { + CMapItemEnvelope Item; + Item.m_Version = CMapItemEnvelope::CURRENT_VERSION; + Item.m_Channels = m_lEnvelopes[e]->m_Channels; + Item.m_StartPoint = PointCount; + Item.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size(); + Item.m_Synchronized = m_lEnvelopes[e]->m_Synchronized; + 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(); + mem_copy(&pPoints[PointCount], m_lEnvelopes[e]->m_lPoints.base_ptr(), sizeof(CEnvPoint)*Count); + PointCount += Count; + } + + df.AddItem(MAPITEMTYPE_ENVPOINTS, 0, TotalSize, pPoints); + mem_free(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()) + { + CServerInfo CurrentServerInfo; + m_pEditor->Client()->GetServerInfo(&CurrentServerInfo); + const unsigned char ipv4Localhost[16] = {127,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0}; + const unsigned char ipv6Localhost[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; + + // and if we're on localhost + if(!mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv4Localhost, sizeof(ipv4Localhost)) + || !mem_comp(CurrentServerInfo.m_NetAddr.ip, ipv6Localhost, sizeof(ipv6Localhost))) + { + char aMapName[128]; + m_pEditor->ExtractName(pFileName, aMapName, sizeof(aMapName)); + if(!str_comp(aMapName, CurrentServerInfo.m_aMap)) + m_pEditor->Client()->Rcon("reload"); + } + } + + return 1; +} + +int CEditor::Load(const char *pFileName, int StorageType) +{ + Reset(); + return m_Map.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType); +} + +int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int StorageType) +{ + CDataFileReader DataFile; + //DATAFILE *df = datafile_load(filename); + if(!DataFile.Open(pStorage, pFileName, StorageType)) + return 0; + + Clean(); + + // check version + CMapItemVersion *pItem = (CMapItemVersion *)DataFile.FindItem(MAPITEMTYPE_VERSION, 0); + if(!pItem) + { + // import old map + /*MAP old_mapstuff; + editor->reset(); + editor_load_old(df, this); + */ + return 0; + } + else if(pItem->m_Version == 1) + { + //editor.reset(false); + + // load map info + { + int Start, Num; + DataFile.GetType(MAPITEMTYPE_INFO, &Start, &Num); + for(int i = Start; i < Start + Num; i++) + { + int ItemSize = DataFile.GetItemSize(Start) - 8; + int ItemID; + CMapItemInfoSettings *pItem = (CMapItemInfoSettings *)DataFile.GetItem(i, 0, &ItemID); + if(!pItem || ItemID != 0) + continue; + + if(pItem->m_Author > -1) + str_copy(m_MapInfo.m_aAuthor, (char *)DataFile.GetData(pItem->m_Author), sizeof(m_MapInfo.m_aAuthor)); + if(pItem->m_MapVersion > -1) + str_copy(m_MapInfo.m_aVersion, (char *)DataFile.GetData(pItem->m_MapVersion), sizeof(m_MapInfo.m_aVersion)); + if(pItem->m_Credits > -1) + str_copy(m_MapInfo.m_aCredits, (char *)DataFile.GetData(pItem->m_Credits), sizeof(m_MapInfo.m_aCredits)); + if(pItem->m_License > -1) + str_copy(m_MapInfo.m_aLicense, (char *)DataFile.GetData(pItem->m_License), sizeof(m_MapInfo.m_aLicense)); + + if(pItem->m_Version != 1 || ItemSize < (int)sizeof(CMapItemInfoSettings)) + break; + + if(!(pItem->m_Settings > -1)) + break; + + int Size = DataFile.GetUncompressedDataSize(pItem->m_Settings); + char *pSettings = (char *)DataFile.GetData(pItem->m_Settings); + char *pNext = pSettings; + while(pNext < pSettings + Size) + { + int StrSize = str_length(pNext) + 1; + CSetting Setting; + str_copy(Setting.m_aCommand, pNext, sizeof(Setting.m_aCommand)); + m_lSettings.add(Setting); + pNext += StrSize; + } + } + } + + // load images + { + int Start, Num; + DataFile.GetType( MAPITEMTYPE_IMAGE, &Start, &Num); + for(int i = 0; i < Num; i++) + { + CMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start+i, 0, 0); + char *pName = (char *)DataFile.GetData(pItem->m_ImageName); + + // copy base info + CEditorImage *pImg = new CEditorImage(m_pEditor); + pImg->m_External = pItem->m_External; + + if(pItem->m_External) + { + 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)) + { + *pImg = ImgInfo; + pImg->m_TexID = m_pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); + ImgInfo.m_pData = 0; + pImg->m_External = 1; + } + } + else + { + 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); + mem_copy(pImg->m_pData, pData, pImg->m_Width*pImg->m_Height*4); + pImg->m_TexID = m_pEditor->Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Format, pImg->m_pData, CImageInfo::FORMAT_AUTO, 0); + } + + // copy image name + if(pName) + str_copy(pImg->m_aName, pName, 128); + + // load auto mapper file + pImg->m_AutoMapper.Load(pImg->m_aName); + + m_lImages.add(pImg); + + // unload image + DataFile.UnloadData(pItem->m_ImageData); + DataFile.UnloadData(pItem->m_ImageName); + } + } + + // load sounds + { + int Start, Num; + DataFile.GetType( MAPITEMTYPE_SOUND, &Start, &Num); + for(int i = 0; i < Num; i++) + { + CMapItemSound *pItem = (CMapItemSound *)DataFile.GetItem(Start+i, 0, 0); + char *pName = (char *)DataFile.GetData(pItem->m_SoundName); + + // copy base info + CEditorSound *pSound = new CEditorSound(m_pEditor); + pSound->m_External = pItem->m_External; + + if(pItem->m_External) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf),"mapres/%s.opus", pName); + + // load external + IOHANDLE SoundFile = pStorage->OpenFile(pName, IOFLAG_READ, IStorage::TYPE_ALL); + if(SoundFile) + { + // read the whole file into memory + pSound->m_DataSize = io_length(SoundFile); + + if(pSound->m_DataSize > 0) + { + pSound->m_pData = mem_alloc(pSound->m_DataSize, 1); + io_read(SoundFile, pSound->m_pData, pSound->m_DataSize); + } + io_close(SoundFile); + if(pSound->m_DataSize > 0) + { + pSound->m_SoundID = m_pEditor->Sound()->LoadOpusFromMem(pSound->m_pData, pSound->m_DataSize, true); + } + } + } + else + { + pSound->m_DataSize = pItem->m_SoundDataSize; + + // copy sample data + void *pData = DataFile.GetData(pItem->m_SoundData); + pSound->m_pData = mem_alloc(pSound->m_DataSize, 1); + mem_copy(pSound->m_pData, pData, pSound->m_DataSize); + pSound->m_SoundID = m_pEditor->Sound()->LoadOpusFromMem(pSound->m_pData, pSound->m_DataSize, true); + } + + // copy image name + if(pName) + str_copy(pSound->m_aName, pName, sizeof(pSound->m_aName)); + + m_lSounds.add(pSound); + + // unload image + DataFile.UnloadData(pItem->m_SoundData); + DataFile.UnloadData(pItem->m_SoundName); + } + } + + // 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; + pGroup->m_ClipX = pGItem->m_ClipX; + pGroup->m_ClipY = pGItem->m_ClipY; + pGroup->m_ClipW = pGItem->m_ClipW; + pGroup->m_ClipH = pGItem->m_ClipH; + } + + // load group name + if(pGItem->m_Version >= 3) + IntsToStr(pGItem->m_aName, sizeof(pGroup->m_aName)/sizeof(int), pGroup->m_aName); + + 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&TILESLAYERFLAG_GAME) + { + pTiles = new CLayerGame(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeGameLayer(pTiles); + MakeGameGroup(pGroup); + } + else if(pTilemapItem->m_Flags&TILESLAYERFLAG_TELE) + { + if(pTilemapItem->m_Version <= 2) + pTilemapItem->m_Tele = *((int*)(pTilemapItem) + 15); + + pTiles = new CLayerTele(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeTeleLayer(pTiles); + } + else if(pTilemapItem->m_Flags&TILESLAYERFLAG_SPEEDUP) + { + if(pTilemapItem->m_Version <= 2) + pTilemapItem->m_Speedup = *((int*)(pTilemapItem) + 16); + + pTiles = new CLayerSpeedup(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeSpeedupLayer(pTiles); + } + else if(pTilemapItem->m_Flags&TILESLAYERFLAG_FRONT) + { + if(pTilemapItem->m_Version <= 2) + pTilemapItem->m_Front = *((int*)(pTilemapItem) + 17); + + pTiles = new CLayerFront(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeFrontLayer(pTiles); + } + else if(pTilemapItem->m_Flags&TILESLAYERFLAG_SWITCH) + { + if(pTilemapItem->m_Version <= 2) + pTilemapItem->m_Switch = *((int*)(pTilemapItem) + 18); + + pTiles = new CLayerSwitch(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeSwitchLayer(pTiles); + } + else if(pTilemapItem->m_Flags&TILESLAYERFLAG_TUNE) + { + if(pTilemapItem->m_Version <= 2) + pTilemapItem->m_Tune = *((int*)(pTilemapItem) + 19); + + pTiles = new CLayerTune(pTilemapItem->m_Width, pTilemapItem->m_Height); + MakeTuneLayer(pTiles); + } + else + { + pTiles = new CLayerTiles(pTilemapItem->m_Width, pTilemapItem->m_Height); + pTiles->m_pEditor = m_pEditor; + pTiles->m_Color = pTilemapItem->m_Color; + pTiles->m_ColorEnv = pTilemapItem->m_ColorEnv; + pTiles->m_ColorEnvOffset = pTilemapItem->m_ColorEnvOffset; + } + + pLayer = pTiles; + + pGroup->AddLayer(pTiles); + void *pData = DataFile.GetData(pTilemapItem->m_Data); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Data); + pTiles->m_Image = pTilemapItem->m_Image; + pTiles->m_Game = pTilemapItem->m_Flags&TILESLAYERFLAG_GAME; + + // load layer name + if(pTilemapItem->m_Version >= 3) + IntsToStr(pTilemapItem->m_aName, sizeof(pTiles->m_aName)/sizeof(int), pTiles->m_aName); + + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTile)) + { + 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++) + { + if(pTiles->m_pTiles[i].m_Index) + pTiles->m_pTiles[i].m_Index += ENTITY_OFFSET; + } + } + + // Convert race stoppers to ddrace stoppers + /*if(pTiles->m_Game) + { + for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + { + if(pTiles->m_pTiles[i].m_Index == 29) + { + pTiles->m_pTiles[i].m_Index = 60; + pTiles->m_pTiles[i].m_Flags = TILEFLAG_HFLIP|TILEFLAG_VFLIP|TILEFLAG_ROTATE; + } + else if(pTiles->m_pTiles[i].m_Index == 30) + { + pTiles->m_pTiles[i].m_Index = 60; + pTiles->m_pTiles[i].m_Flags = TILEFLAG_ROTATE; + } + else if(pTiles->m_pTiles[i].m_Index == 31) + { + pTiles->m_pTiles[i].m_Index = 60; + pTiles->m_pTiles[i].m_Flags = TILEFLAG_HFLIP|TILEFLAG_VFLIP; + } + else if(pTiles->m_pTiles[i].m_Index == 32) + { + pTiles->m_pTiles[i].m_Index = 60; + pTiles->m_pTiles[i].m_Flags = 0; + } + } + }*/ + } + + DataFile.UnloadData(pTilemapItem->m_Data); + + if(pTiles->m_Tele) + { + void *pTeleData = DataFile.GetData(pTilemapItem->m_Tele); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Tele); + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTeleTile)) + { + mem_copy(((CLayerTele*)pTiles)->m_pTeleTile, pTeleData, pTiles->m_Width*pTiles->m_Height*sizeof(CTeleTile)); + + for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + { + if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELEIN) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELEIN; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELEINEVIL) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELEINEVIL; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELEOUT) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELEOUT; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELECHECK) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELECHECK; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELECHECKIN) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELECHECKIN; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELECHECKINEVIL) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELECHECKINEVIL; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELECHECKOUT) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELECHECKOUT; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELEINWEAPON) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELEINWEAPON; + else if(((CLayerTele*)pTiles)->m_pTeleTile[i].m_Type == TILE_TELEINHOOK) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TELEINHOOK; + else + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = 0; + } + } + DataFile.UnloadData(pTilemapItem->m_Tele); + } + else if(pTiles->m_Speedup) + { + void *pSpeedupData = DataFile.GetData(pTilemapItem->m_Speedup); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Speedup); + + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CSpeedupTile)) + { + mem_copy(((CLayerSpeedup*)pTiles)->m_pSpeedupTile, pSpeedupData, pTiles->m_Width*pTiles->m_Height*sizeof(CSpeedupTile)); + + for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + { + if(((CLayerSpeedup*)pTiles)->m_pSpeedupTile[i].m_Force > 0) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_BOOST; + else + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = 0; + } + } + + DataFile.UnloadData(pTilemapItem->m_Speedup); + } + else if(pTiles->m_Front) + { + void *pFrontData = DataFile.GetData(pTilemapItem->m_Front); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Front); + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTile)) + mem_copy(((CLayerFront*)pTiles)->m_pTiles, pFrontData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile)); + + DataFile.UnloadData(pTilemapItem->m_Front); + } + else if(pTiles->m_Switch) + { + void *pSwitchData = DataFile.GetData(pTilemapItem->m_Switch); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Switch); + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CSwitchTile)) + { + mem_copy(((CLayerSwitch*)pTiles)->m_pSwitchTile, pSwitchData, pTiles->m_Width*pTiles->m_Height*sizeof(CSwitchTile)); + + for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + { + if(((((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type > (ENTITY_CRAZY_SHOTGUN + ENTITY_OFFSET) && ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type < (ENTITY_DRAGGER_WEAK + ENTITY_OFFSET)) || ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == (ENTITY_LASER_O_FAST + 1 + ENTITY_OFFSET))) + continue; + if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_SWITCHTIMEDOPEN) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_SWITCHTIMEDOPEN; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_SWITCHTIMEDCLOSE) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_SWITCHTIMEDCLOSE; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_SWITCHOPEN) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_SWITCHOPEN; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_SWITCHCLOSE) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_SWITCHCLOSE; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_FREEZE) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_FREEZE; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_DFREEZE) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_DFREEZE; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_DUNFREEZE) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_DUNFREEZE; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type >= (ENTITY_ARMOR_1 + ENTITY_OFFSET) && ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type <= (ENTITY_DOOR + ENTITY_OFFSET)) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_HIT_START) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_HIT_START; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_HIT_END) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_HIT_END; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_JUMP) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_JUMP; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_PENALTY) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_PENALTY; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + else if(((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Type == TILE_BONUS) + { + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_BONUS; + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Flags = ((CLayerSwitch*)pTiles)->m_pSwitchTile[i].m_Flags; + } + } + } + DataFile.UnloadData(pTilemapItem->m_Switch); + } + else if(pTiles->m_Tune) + { + void *pTuneData = DataFile.GetData(pTilemapItem->m_Tune); + unsigned int Size = DataFile.GetUncompressedDataSize(pTilemapItem->m_Tune); + if (Size >= pTiles->m_Width*pTiles->m_Height*sizeof(CTuneTile)) + { + mem_copy(((CLayerTune*)pTiles)->m_pTuneTile, pTuneData, pTiles->m_Width*pTiles->m_Height*sizeof(CTuneTile)); + + for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) + { + if(((CLayerTune*)pTiles)->m_pTuneTile[i].m_Type == TILE_TUNE1) + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = TILE_TUNE1; + else + ((CLayerTiles*)pTiles)->m_pTiles[i].m_Index = 0; + } + } + DataFile.UnloadData(pTilemapItem->m_Tune); + } + } + else if(pLayerItem->m_Type == LAYERTYPE_QUADS) + { + CMapItemLayerQuads *pQuadsItem = (CMapItemLayerQuads *)pLayerItem; + CLayerQuads *pQuads = new CLayerQuads; + pQuads->m_pEditor = m_pEditor; + pLayer = pQuads; + pQuads->m_Image = pQuadsItem->m_Image; + if(pQuads->m_Image < -1 || pQuads->m_Image >= m_lImages.size()) + pQuads->m_Image = -1; + + // load layer name + if(pQuadsItem->m_Version >= 2) + IntsToStr(pQuadsItem->m_aName, sizeof(pQuads->m_aName)/sizeof(int), pQuads->m_aName); + + void *pData = DataFile.GetDataSwapped(pQuadsItem->m_Data); + pGroup->AddLayer(pQuads); + pQuads->m_lQuads.set_size(pQuadsItem->m_NumQuads); + mem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad)*pQuadsItem->m_NumQuads); + DataFile.UnloadData(pQuadsItem->m_Data); + } + else if(pLayerItem->m_Type == LAYERTYPE_SOUNDS) + { + CMapItemLayerSounds *pSoundsItem = (CMapItemLayerSounds *)pLayerItem; + if(pSoundsItem->m_Version < 1 || pSoundsItem->m_Version > CMapItemLayerSounds::CURRENT_VERSION) + continue; + + CLayerSounds *pSounds = new CLayerSounds; + pSounds->m_pEditor = m_pEditor; + pLayer = pSounds; + pSounds->m_Sound = pSoundsItem->m_Sound; + + // validate m_Sound + if(pSounds->m_Sound < -1 || pSounds->m_Sound >= m_lSounds.size()) + pSounds->m_Sound = -1; + + // load layer name + if(pSoundsItem->m_Version >= 1) + IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName)/sizeof(int), pSounds->m_aName); + + // load data + void *pData = DataFile.GetDataSwapped(pSoundsItem->m_Data); + pGroup->AddLayer(pSounds); + pSounds->m_lSources.set_size(pSoundsItem->m_NumSources); + mem_copy(pSounds->m_lSources.base_ptr(), pData, sizeof(CSoundSource)*pSoundsItem->m_NumSources); + DataFile.UnloadData(pSoundsItem->m_Data); + } + else if(pLayerItem->m_Type == LAYERTYPE_SOUNDS_DEPRECATED) + { + // compatibility with old sound layers + CMapItemLayerSounds *pSoundsItem = (CMapItemLayerSounds *)pLayerItem; + if(pSoundsItem->m_Version < 1 || pSoundsItem->m_Version > CMapItemLayerSounds::CURRENT_VERSION) + continue; + + CLayerSounds *pSounds = new CLayerSounds; + pSounds->m_pEditor = m_pEditor; + pLayer = pSounds; + pSounds->m_Sound = pSoundsItem->m_Sound; + + // validate m_Sound + if(pSounds->m_Sound < -1 || pSounds->m_Sound >= m_lSounds.size()) + pSounds->m_Sound = -1; + + // load layer name + if(pSoundsItem->m_Version >= 1) + IntsToStr(pSoundsItem->m_aName, sizeof(pSounds->m_aName)/sizeof(int), pSounds->m_aName); + + // load data + CSoundSource_DEPRECATED *pData = (CSoundSource_DEPRECATED *)DataFile.GetDataSwapped(pSoundsItem->m_Data); + pGroup->AddLayer(pSounds); + pSounds->m_lSources.set_size(pSoundsItem->m_NumSources); + + for(int i = 0; i < pSoundsItem->m_NumSources; i++) + { + CSoundSource_DEPRECATED *pOldSource = &pData[i]; + + CSoundSource &Source = pSounds->m_lSources[i]; + Source.m_Position = pOldSource->m_Position; + Source.m_Loop = pOldSource->m_Loop; + Source.m_Pan = true; + Source.m_TimeDelay = pOldSource->m_TimeDelay; + Source.m_Falloff = 0; + + Source.m_PosEnv = pOldSource->m_PosEnv; + Source.m_PosEnvOffset = pOldSource->m_PosEnvOffset; + Source.m_SoundEnv = pOldSource->m_SoundEnv; + Source.m_SoundEnvOffset = pOldSource->m_SoundEnvOffset; + + Source.m_Shape.m_Type = CSoundShape::SHAPE_CIRCLE; + Source.m_Shape.m_Circle.m_Radius = pOldSource->m_FalloffDistance; + } + + DataFile.UnloadData(pSoundsItem->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++) + { + CMapItemEnvelope *pItem = (CMapItemEnvelope *)DataFile.GetItem(Start+e, 0, 0); + CEnvelope *pEnv = new CEnvelope(pItem->m_Channels); + pEnv->m_lPoints.set_size(pItem->m_NumPoints); + mem_copy(pEnv->m_lPoints.base_ptr(), &pPoints[pItem->m_StartPoint], sizeof(CEnvPoint)*pItem->m_NumPoints); + if(pItem->m_aName[0] != -1) // compatibility with old maps + IntsToStr(pItem->m_aName, sizeof(pItem->m_aName)/sizeof(int), pEnv->m_aName); + m_lEnvelopes.add(pEnv); + if(pItem->m_Version >= 2) + pEnv->m_Synchronized = pItem->m_Synchronized; + } + } + } + else + return 0; + + return 1; +} + +static int gs_ModifyAddAmount = 0; +static void ModifyAdd(int *pIndex) +{ + if(*pIndex >= 0) + *pIndex += gs_ModifyAddAmount; +} + +int CEditor::Append(const char *pFileName, int StorageType) +{ + CEditorMap NewMap; + NewMap.m_pEditor = this; + + int Err; + Err = NewMap.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType); + if(!Err) + return Err; + + // 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) + delete NewMap.m_lGroups[i]; + else + { + NewMap.m_lGroups[i]->m_pMap = &m_Map; + m_Map.m_lGroups.add(NewMap.m_lGroups[i]); + } + } + NewMap.m_lGroups.clear(); + + // all done \o/ + return 0; +} diff --git a/src/game/editor/layer_game.cpp b/src/game/editor/layer_game.cpp new file mode 100644 index 0000000..7e879c3 --- /dev/null +++ b/src/game/editor/layer_game.cpp @@ -0,0 +1,22 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "editor.h" + + +CLayerGame::CLayerGame(int w, int h) +: CLayerTiles(w, h) +{ + str_copy(m_aName, "Game", sizeof(m_aName)); + m_Game = 1; +} + +CLayerGame::~CLayerGame() +{ +} + +int CLayerGame::RenderProperties(CUIRect *pToolbox) +{ + int r = CLayerTiles::RenderProperties(pToolbox); + m_Image = -1; + return r; +} diff --git a/src/game/editor/layer_quads.cpp b/src/game/editor/layer_quads.cpp new file mode 100644 index 0000000..15c0035 --- /dev/null +++ b/src/game/editor/layer_quads.cpp @@ -0,0 +1,277 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> + +#include <engine/console.h> +#include <engine/graphics.h> + +#include "editor.h" +#include <game/generated/client_data.h> +#include <game/client/render.h> +#include <game/localization.h> + +CLayerQuads::CLayerQuads() +{ + m_Type = LAYERTYPE_QUADS; + str_copy(m_aName, "Quads", sizeof(m_aName)); + m_Image = -1; +} + +CLayerQuads::~CLayerQuads() +{ +} + +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); + + Graphics()->BlendNone(); + m_pEditor->RenderTools()->ForceRenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_OPAQUE, m_pEditor->EnvelopeEval, m_pEditor); + Graphics()->BlendNormal(); + m_pEditor->RenderTools()->ForceRenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_TRANSPARENT, m_pEditor->EnvelopeEval, m_pEditor); +} + +CQuad *CLayerQuads::NewQuad() +{ + m_pEditor->m_Map.m_Modified = true; + + CQuad *q = &m_lQuads[m_lQuads.add(CQuad())]; + + q->m_PosEnv = -1; + q->m_ColorEnv = -1; + q->m_PosEnvOffset = 0; + q->m_ColorEnvOffset = 0; + int x = 0, y = 0; + q->m_aPoints[0].x = x; + q->m_aPoints[0].y = y; + q->m_aPoints[1].x = x+64; + q->m_aPoints[1].y = y; + q->m_aPoints[2].x = x; + q->m_aPoints[2].y = y+64; + q->m_aPoints[3].x = x+64; + q->m_aPoints[3].y = y+64; + + 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; + q->m_aColors[3].r = 255; q->m_aColors[3].g = 255; q->m_aColors[3].b = 255; q->m_aColors[3].a = 255; + + return q; +} + +void CLayerQuads::BrushSelecting(CUIRect Rect) +{ + // draw selection rectangle + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y), + IGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h), + IGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h), + IGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)}; + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(Array, 4); + Graphics()->LinesEnd(); +} + +int CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) +{ + // create new layers + CLayerQuads *pGrabbed = new CLayerQuads(); + 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; +} + +void CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy) +{ + CLayerQuads *l = (CLayerQuads *)pBrush; + 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; +} + +void Swap(CPoint& a, CPoint& b) +{ + CPoint tmp; + tmp.x = a.x; + tmp.y = a.y; + + a.x = b.x; + a.y = b.y; + + b.x = tmp.x; + b.y = tmp.y; +} + +void CLayerQuads::BrushFlipX() +{ + for(int i = 0; i < m_lQuads.size(); i++) + { + CQuad *q = &m_lQuads[i]; + + Swap(q->m_aPoints[0], q->m_aPoints[1]); + Swap(q->m_aPoints[2], q->m_aPoints[3]); + } + m_pEditor->m_Map.m_Modified = true; +} + +void CLayerQuads::BrushFlipY() +{ + for(int i = 0; i < m_lQuads.size(); i++) + { + CQuad *q = &m_lQuads[i]; + + Swap(q->m_aPoints[0], q->m_aPoints[2]); + Swap(q->m_aPoints[1], q->m_aPoints[3]); + } + m_pEditor->m_Map.m_Modified = true; +} + +void Rotate(vec2 *pCenter, vec2 *pPoint, float Rotation) +{ + float x = pPoint->x - pCenter->x; + float y = pPoint->y - pCenter->y; + pPoint->x = x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x; + pPoint->y = x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y; +} + +void CLayerQuads::BrushRotate(float Amount) +{ + vec2 Center; + GetSize(&Center.x, &Center.y); + Center.x /= 2; + Center.y /= 2; + + 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)); + Rotate(&Center, &Pos, Amount); + q->m_aPoints[p].x = f2fx(Pos.x); + q->m_aPoints[p].y = f2fx(Pos.y); + } + } +} + +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++) + { + *w = max(*w, fx2f(m_lQuads[i].m_aPoints[p].x)); + *h = max(*h, fx2f(m_lQuads[i].m_aPoints[p].y)); + } + } +} + +extern int gs_SelectedPoints; + +int CLayerQuads::RenderProperties(CUIRect *pToolBox) +{ + // layer props + enum + { + 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) + m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); + else + m_Image = -1; + } + + return 0; +} + + +void CLayerQuads::ModifyImageIndex(INDEX_MODIFY_FUNC Func) +{ + Func(&m_Image); +} + +void CLayerQuads::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) +{ + for(int i = 0; i < m_lQuads.size(); i++) + { + Func(&m_lQuads[i].m_PosEnv); + Func(&m_lQuads[i].m_ColorEnv); + } +} diff --git a/src/game/editor/layer_sounds.cpp b/src/game/editor/layer_sounds.cpp new file mode 100644 index 0000000..38bd919 --- /dev/null +++ b/src/game/editor/layer_sounds.cpp @@ -0,0 +1,232 @@ + +#include <game/generated/client_data.h> + +#include "editor.h" + +static const float s_SourceVisualSize = 32.0f; + +CLayerSounds::CLayerSounds() +{ + m_Type = LAYERTYPE_SOUNDS; + str_copy(m_aName, "Sounds", sizeof(m_aName)); + m_Sound = -1; +} + +CLayerSounds::~CLayerSounds() +{ +} + +void CLayerSounds::Render() +{ + // TODO: nice texture + Graphics()->TextureSet(-1); + Graphics()->BlendNormal(); + Graphics()->QuadsBegin(); + + // draw falloff distance + Graphics()->SetColor(0.6f, 0.8f, 1.0f, 0.4f); + for(int i = 0; i < m_lSources.size(); i++) + { + CSoundSource *pSource = &m_lSources[i]; + + float OffsetX = 0; + float OffsetY = 0; + + if(pSource->m_PosEnv >= 0) + { + float aChannels[4]; + m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset/1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); + OffsetX = aChannels[0]; + OffsetY = aChannels[1]; + } + + switch(pSource->m_Shape.m_Type) + { + case CSoundShape::SHAPE_CIRCLE: + { + m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, + pSource->m_Shape.m_Circle.m_Radius, 32); + + float Falloff = ((float)pSource->m_Falloff/255.0f); + if(Falloff > 0.0f) + m_pEditor->RenderTools()->DrawCircle(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, + pSource->m_Shape.m_Circle.m_Radius*Falloff, 32); + break; + } + case CSoundShape::SHAPE_RECTANGLE: + { + float Width = fx2f(pSource->m_Shape.m_Rectangle.m_Width); + float Height = fx2f(pSource->m_Shape.m_Rectangle.m_Height); + m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x)+OffsetX - Width/2, fx2f(pSource->m_Position.y)+OffsetY - Height/2, + Width, Height, 0.0f); + + float Falloff = ((float)pSource->m_Falloff/255.0f); + if(Falloff > 0.0f) + m_pEditor->RenderTools()->DrawRoundRect(fx2f(pSource->m_Position.x)+OffsetX - Falloff*Width/2, fx2f(pSource->m_Position.y)+OffsetY - Falloff*Height/2, + Width*Falloff, Height*Falloff, 0.0f); + break; + } + } + } + + Graphics()->QuadsEnd(); + + + // draw handles + Graphics()->TextureSet(g_pData->m_aImages[IMAGE_AUDIO_SOURCE].m_Id); + Graphics()->QuadsBegin(); + + Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); + m_pEditor->RenderTools()->SelectSprite(SPRITE_AUDIO_SOURCE); + for(int i = 0; i < m_lSources.size(); i++) + { + CSoundSource *pSource = &m_lSources[i]; + + float OffsetX = 0; + float OffsetY = 0; + + if(pSource->m_PosEnv >= 0) + { + float aChannels[4]; + m_pEditor->EnvelopeEval(pSource->m_PosEnvOffset/1000.0f, pSource->m_PosEnv, aChannels, m_pEditor); + OffsetX = aChannels[0]; + OffsetY = aChannels[1]; + } + + m_pEditor->RenderTools()->DrawSprite(fx2f(pSource->m_Position.x)+OffsetX, fx2f(pSource->m_Position.y)+OffsetY, s_SourceVisualSize*m_pEditor->m_WorldZoom); + } + + Graphics()->QuadsEnd(); +} + +CSoundSource *CLayerSounds::NewSource() +{ + m_pEditor->m_Map.m_Modified = true; + + CSoundSource *pSource = &m_lSources[m_lSources.add(CSoundSource())]; + + pSource->m_Position.x = 0; + pSource->m_Position.y = 0; + + pSource->m_Loop = 1; + pSource->m_Pan = 1; + pSource->m_TimeDelay = 0; + + pSource->m_PosEnv = -1; + pSource->m_PosEnvOffset = 0; + pSource->m_SoundEnv = -1; + pSource->m_SoundEnvOffset = 0; + + pSource->m_Falloff = 80; + + pSource->m_Shape.m_Type = CSoundShape::SHAPE_CIRCLE; + pSource->m_Shape.m_Circle.m_Radius = 1500; + + /* + pSource->m_Shape.m_Type = CSoundShape::SHAPE_RECTANGLE; + pSource->m_Shape.m_Rectangle.m_Width = f2fx(1500.0f); + pSource->m_Shape.m_Rectangle.m_Height = f2fx(1000.0f); + */ + + return pSource; +} + +void CLayerSounds::BrushSelecting(CUIRect Rect) +{ + // draw selection rectangle + IGraphics::CLineItem Array[4] = { + IGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y), + IGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h), + IGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h), + IGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)}; + Graphics()->TextureSet(-1); + Graphics()->LinesBegin(); + Graphics()->LinesDraw(Array, 4); + Graphics()->LinesEnd(); +} + +int CLayerSounds::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) +{ + // create new layer + CLayerSounds *pGrabbed = new CLayerSounds(); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_Sound = m_Sound; + pBrush->AddLayer(pGrabbed); + + for(int i = 0; i < m_lSources.size(); i++) + { + CSoundSource *pSource = &m_lSources[i]; + float px = fx2f(pSource->m_Position.x); + float py = fx2f(pSource->m_Position.y); + + if(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h) + { + CSoundSource n; + n = *pSource; + + n.m_Position.x -= f2fx(Rect.x); + n.m_Position.y -= f2fx(Rect.y); + + pGrabbed->m_lSources.add(n); + } + } + + return pGrabbed->m_lSources.size()?1:0; +} + +void CLayerSounds::BrushPlace(CLayer *pBrush, float wx, float wy) +{ + CLayerSounds *l = (CLayerSounds *)pBrush; + for(int i = 0; i < l->m_lSources.size(); i++) + { + CSoundSource n = l->m_lSources[i]; + + n.m_Position.x += f2fx(wx); + n.m_Position.y += f2fx(wy); + + m_lSources.add(n); + } + m_pEditor->m_Map.m_Modified = true; +} + +int CLayerSounds::RenderProperties(CUIRect *pToolBox) +{ + // + enum + { + PROP_SOUND=0, + NUM_PROPS, + }; + + CProperty aProps[] = { + {"Sound", m_Sound, PROPTYPE_SOUND, -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_SOUND) + { + if(NewVal >= 0) + m_Sound = NewVal%m_pEditor->m_Map.m_lSounds.size(); + else + m_Sound = -1; + } + + return 0; +} + +void CLayerSounds::ModifySoundIndex(INDEX_MODIFY_FUNC Func) +{ + Func(&m_Sound); +} + +void CLayerSounds::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) +{ + for(int i = 0; i < m_lSources.size(); i++) + Func(&m_lSources[i].m_SoundEnv); +} diff --git a/src/game/editor/layer_tiles.cpp b/src/game/editor/layer_tiles.cpp new file mode 100644 index 0000000..97b9907 --- /dev/null +++ b/src/game/editor/layer_tiles.cpp @@ -0,0 +1,1774 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/math.h> + +#include <engine/client.h> +#include <engine/graphics.h> +#include <engine/textrender.h> + +#include <game/generated/client_data.h> +#include <game/client/render.h> +#include "editor.h" + +#include <game/localization.h> + +#include <engine/input.h> +#include <engine/keys.h> + +CLayerTiles::CLayerTiles(int w, int h) +{ + m_Type = LAYERTYPE_TILES; + str_copy(m_aName, "Tiles", sizeof(m_aName)); + m_Width = w; + m_Height = h; + m_Image = -1; + m_TexID = -1; + m_Game = 0; + m_Color.r = 255; + m_Color.g = 255; + m_Color.b = 255; + m_Color.a = 255; + m_ColorEnv = -1; + m_ColorEnvOffset = 0; + + m_Tele = 0; + m_Speedup = 0; + m_Front = 0; + m_Switch = 0; + m_Tune = 0; + + m_pTiles = new CTile[m_Width*m_Height]; + mem_zero(m_pTiles, m_Width*m_Height*sizeof(CTile)); +} + +CLayerTiles::~CLayerTiles() +{ + delete [] m_pTiles; +} + +void CLayerTiles::PrepareForSave() +{ + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + m_pTiles[y*m_Width+x].m_Flags &= TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE; + + if(m_Image != -1 && m_Color.a == 255) + { + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + m_pTiles[y*m_Width+x].m_Flags |= m_pEditor->m_Map.m_lImages[m_Image]->m_aTileFlags[m_pTiles[y*m_Width+x].m_Index]; + } +} + +void CLayerTiles::MakePalette() +{ + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + m_pTiles[y*m_Width+x].m_Index = y*16+x; +} + +void CLayerTiles::Render() +{ + if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size()) + m_TexID = m_pEditor->m_Map.m_lImages[m_Image]->m_TexID; + Graphics()->TextureSet(m_TexID); + vec4 Color = vec4(m_Color.r/255.0f, m_Color.g/255.0f, m_Color.b/255.0f, m_Color.a/255.0f); + Graphics()->BlendNone(); + m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_OPAQUE, + m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); + Graphics()->BlendNormal(); + m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_TRANSPARENT, + m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); + + // Render DDRace Layers + if(m_Tele) + m_pEditor->RenderTools()->RenderTeleOverlay(((CLayerTele*)this)->m_pTeleTile, m_Width, m_Height, 32.0f); + if(m_Speedup) + m_pEditor->RenderTools()->RenderSpeedupOverlay(((CLayerSpeedup*)this)->m_pSpeedupTile, m_Width, m_Height, 32.0f); + if(m_Switch) + m_pEditor->RenderTools()->RenderSwitchOverlay(((CLayerSwitch*)this)->m_pSwitchTile, m_Width, m_Height, 32.0f); + if(m_Tune) + m_pEditor->RenderTools()->RenderTuneOverlay(((CLayerTune*)this)->m_pTuneTile, m_Width, m_Height, 32.0f); +} + +int CLayerTiles::ConvertX(float x) const { return (int)(x/32.0f); } +int CLayerTiles::ConvertY(float y) const { return (int)(y/32.0f); } + +void CLayerTiles::Convert(CUIRect Rect, RECTi *pOut) +{ + pOut->x = ConvertX(Rect.x); + pOut->y = ConvertY(Rect.y); + pOut->w = ConvertX(Rect.x+Rect.w+31) - pOut->x; + pOut->h = ConvertY(Rect.y+Rect.h+31) - pOut->y; +} + +void CLayerTiles::Snap(CUIRect *pRect) +{ + RECTi Out; + Convert(*pRect, &Out); + pRect->x = Out.x*32.0f; + pRect->y = Out.y*32.0f; + pRect->w = Out.w*32.0f; + pRect->h = Out.h*32.0f; +} + +void CLayerTiles::Clamp(RECTi *pRect) +{ + if(pRect->x < 0) + { + 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) + pRect->w = 0; +} + +void CLayerTiles::BrushSelecting(CUIRect Rect) +{ + Graphics()->TextureSet(-1); + m_pEditor->Graphics()->QuadsBegin(); + m_pEditor->Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.4f); + Snap(&Rect); + IGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h); + m_pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); + m_pEditor->Graphics()->QuadsEnd(); + char aBuf[16]; + str_format(aBuf, sizeof(aBuf), "%d,%d", ConvertX(Rect.w), ConvertY(Rect.h)); + TextRender()->Text(0, Rect.x+3.0f, Rect.y+3.0f, m_pEditor->m_ShowPicker?15.0f:15.0f*m_pEditor->m_WorldZoom, aBuf, -1); +} + +int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) +{ + RECTi r; + Convert(Rect, &r); + Clamp(&r); + + if(!r.w || !r.h) + return 0; + + // create new layers + if(m_pEditor->GetSelectedLayer(0) == m_pEditor->m_Map.m_pTeleLayer) + { + CLayerTele *pGrabbed = new CLayerTele(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + + // copy the tele data + if(!m_pEditor->Input()->KeyPressed(KEY_SPACE)) + for(int y = 0; y < r.h; y++) + for(int x = 0; x < r.w; x++) + { + pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x] = ((CLayerTele*)this)->m_pTeleTile[(r.y+y)*m_Width+(r.x+x)]; + if(pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEIN || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEOUT || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINEVIL || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKINEVIL || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECK || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKOUT || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELECHECKIN || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINWEAPON || pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Type == TILE_TELEINHOOK) + m_pEditor->m_TeleNumber = pGrabbed->m_pTeleTile[y*pGrabbed->m_Width+x].m_Number; + } + pGrabbed->m_TeleNum = m_pEditor->m_TeleNumber; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + else if(m_pEditor->GetSelectedLayer(0) == m_pEditor->m_Map.m_pSpeedupLayer) + { + CLayerSpeedup *pGrabbed = new CLayerSpeedup(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + + // copy the speedup data + if(!m_pEditor->Input()->KeyPressed(KEY_SPACE)) + for(int y = 0; y < r.h; y++) + for(int x = 0; x < r.w; x++) + { + pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x] = ((CLayerSpeedup*)this)->m_pSpeedupTile[(r.y+y)*m_Width+(r.x+x)]; + if(pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Type == TILE_BOOST) + { + m_pEditor->m_SpeedupAngle = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Angle; + m_pEditor->m_SpeedupForce = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_Force; + m_pEditor->m_SpeedupMaxSpeed = pGrabbed->m_pSpeedupTile[y*pGrabbed->m_Width+x].m_MaxSpeed; + } + } + pGrabbed->m_SpeedupForce = m_pEditor->m_SpeedupForce; + pGrabbed->m_SpeedupMaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + pGrabbed->m_SpeedupAngle = m_pEditor->m_SpeedupAngle; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + else if(m_pEditor->GetSelectedLayer(0) == m_pEditor->m_Map.m_pSwitchLayer) + { + CLayerSwitch *pGrabbed = new CLayerSwitch(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + + // copy the switch data + if(!m_pEditor->Input()->KeyPressed(KEY_SPACE)) + for(int y = 0; y < r.h; y++) + for(int x = 0; x < r.w; x++) + { + pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x] = ((CLayerSwitch*)this)->m_pSwitchTile[(r.y+y)*m_Width+(r.x+x)]; + if(pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == ENTITY_DOOR + ENTITY_OFFSET || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_HIT_START || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_HIT_END || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_SWITCHOPEN || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_SWITCHCLOSE || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_SWITCHTIMEDOPEN || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_SWITCHTIMEDCLOSE || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == ENTITY_LASER_LONG + ENTITY_OFFSET || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == ENTITY_LASER_MEDIUM + ENTITY_OFFSET || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == ENTITY_LASER_SHORT + ENTITY_OFFSET || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_JUMP || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_PENALTY || pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Type == TILE_BONUS) + { + m_pEditor->m_SwitchNum = pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Number; + m_pEditor->m_SwitchDelay = pGrabbed->m_pSwitchTile[y*pGrabbed->m_Width+x].m_Delay; + } + } + pGrabbed->m_SwitchNumber = m_pEditor->m_SwitchNum; + pGrabbed->m_SwitchDelay = m_pEditor->m_SwitchDelay; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + + else if(m_pEditor->GetSelectedLayer(0) == m_pEditor->m_Map.m_pTuneLayer) + { + CLayerTune *pGrabbed = new CLayerTune(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + + // copy the tiles + if(!m_pEditor->Input()->KeyPressed(KEY_SPACE)) + for(int y = 0; y < r.h; y++) + for(int x = 0; x < r.w; x++) + { + pGrabbed->m_pTuneTile[y*pGrabbed->m_Width+x] = ((CLayerTune*)this)->m_pTuneTile[(r.y+y)*m_Width+(r.x+x)]; + if(pGrabbed->m_pTuneTile[y*pGrabbed->m_Width+x].m_Type == TILE_TUNE1) + { + m_pEditor->m_TuningNum = pGrabbed->m_pTuneTile[y*pGrabbed->m_Width+x].m_Number; + } + } + pGrabbed->m_TuningNumber = m_pEditor->m_TuningNum; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + else if(m_pEditor->GetSelectedLayer(0) == m_pEditor->m_Map.m_pFrontLayer) + { + CLayerFront *pGrabbed = new CLayerFront(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + else + { + CLayerTiles *pGrabbed = new CLayerTiles(r.w, r.h); + pGrabbed->m_pEditor = m_pEditor; + pGrabbed->m_TexID = m_TexID; + 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)]; + str_copy(pGrabbed->m_aFileName, m_pEditor->m_aFileName, sizeof(pGrabbed->m_aFileName)); + } + + return 1; +} + +void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) +{ + if(m_Readonly) + return; + + Snap(&Rect); + + 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)]; + } + } + m_pEditor->m_Map.m_Modified = true; +} + +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++) + { + int fx = x+sx; + 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; +} + +void CLayerTiles::BrushFlipX() +{ + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width/2; x++) + { + CTile Tmp = m_pTiles[y*m_Width+x]; + m_pTiles[y*m_Width+x] = m_pTiles[y*m_Width+m_Width-1-x]; + m_pTiles[y*m_Width+m_Width-1-x] = Tmp; + } + + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP; +} + +void CLayerTiles::BrushFlipY() +{ + for(int y = 0; y < m_Height/2; y++) + for(int x = 0; x < m_Width; x++) + { + CTile Tmp = m_pTiles[y*m_Width+x]; + m_pTiles[y*m_Width+x] = m_pTiles[(m_Height-1-y)*m_Width+x]; + m_pTiles[(m_Height-1-y)*m_Width+x] = Tmp; + } + + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width; x++) + m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP; +} + +void CLayerTiles::BrushRotate(float Amount) +{ + int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + if(Rotation < 0) + Rotation +=4; + + if(Rotation == 1 || Rotation == 3) + { + // 90° rotation + CTile *pTempData = new CTile[m_Width*m_Height]; + mem_copy(pTempData, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTile *pDst = m_pTiles; + for(int x = 0; x < m_Width; ++x) + for(int y = m_Height-1; y >= 0; --y, ++pDst) + { + *pDst = pTempData[y*m_Width+x]; + if(pDst->m_Flags&TILEFLAG_ROTATE) + pDst->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP); + pDst->m_Flags ^= TILEFLAG_ROTATE; + } + + int Temp = m_Width; + m_Width = m_Height; + m_Height = Temp; + delete[] pTempData; + } + + if(Rotation == 2 || Rotation == 3) + { + BrushFlipX(); + BrushFlipY(); + } +} + +void CLayerTiles::Resize(int NewW, int NewH) +{ + CTile *pNewData = new CTile[NewW*NewH]; + mem_zero(pNewData, NewW*NewH*sizeof(CTile)); + + // 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; + m_Width = NewW; + m_Height = NewH; + + // resize tele layer if available + if(m_Game && m_pEditor->m_Map.m_pTeleLayer && (m_pEditor->m_Map.m_pTeleLayer->m_Width != NewW || m_pEditor->m_Map.m_pTeleLayer->m_Height != NewH)) + m_pEditor->m_Map.m_pTeleLayer->Resize(NewW, NewH); + + // resize speedup layer if available + if(m_Game && m_pEditor->m_Map.m_pSpeedupLayer && (m_pEditor->m_Map.m_pSpeedupLayer->m_Width != NewW || m_pEditor->m_Map.m_pSpeedupLayer->m_Height != NewH)) + m_pEditor->m_Map.m_pSpeedupLayer->Resize(NewW, NewH); + + // resize front layer + if(m_Game && m_pEditor->m_Map.m_pFrontLayer && (m_pEditor->m_Map.m_pFrontLayer->m_Width != NewW || m_pEditor->m_Map.m_pFrontLayer->m_Height != NewH)) + m_pEditor->m_Map.m_pFrontLayer->Resize(NewW, NewH); + + // resize switch layer if available + if(m_Game && m_pEditor->m_Map.m_pSwitchLayer && (m_pEditor->m_Map.m_pSwitchLayer->m_Width != NewW || m_pEditor->m_Map.m_pSwitchLayer->m_Height != NewH)) + m_pEditor->m_Map.m_pSwitchLayer->Resize(NewW, NewH); + + // resize tune layer if available + if(m_Game && m_pEditor->m_Map.m_pTuneLayer && (m_pEditor->m_Map.m_pTuneLayer->m_Width != NewW || m_pEditor->m_Map.m_pTuneLayer->m_Height != NewH)) + m_pEditor->m_Map.m_pTuneLayer->Resize(NewW, NewH); +} + +void CLayerTiles::Shift(int Direction) +{ + int o = m_pEditor->m_ShiftBy; + + switch(Direction) + { + case 1: + { + // left + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTiles[y*m_Width], &m_pTiles[y*m_Width+o], (m_Width-o)*sizeof(CTile)); + mem_zero(&m_pTiles[y*m_Width + (m_Width-o)], o*sizeof(CTile)); + } + } + break; + case 2: + { + // right + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTiles[y*m_Width+o], &m_pTiles[y*m_Width], (m_Width-o)*sizeof(CTile)); + mem_zero(&m_pTiles[y*m_Width], o*sizeof(CTile)); + } + } + break; + case 4: + { + // up + for(int y = 0; y < m_Height-o; ++y) + { + mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y+o)*m_Width], m_Width*sizeof(CTile)); + mem_zero(&m_pTiles[(y+o)*m_Width], m_Width*sizeof(CTile)); + } + } + break; + case 8: + { + // down + for(int y = m_Height-1; y >= o; --y) + { + mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y-o)*m_Width], m_Width*sizeof(CTile)); + mem_zero(&m_pTiles[(y-o)*m_Width], m_Width*sizeof(CTile)); + } + } + } +} + +void CLayerTiles::ShowInfo() +{ + float ScreenX0, ScreenY0, ScreenX1, ScreenY1; + Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); + Graphics()->TextureSet(m_pEditor->Client()->GetDebugFont()); + Graphics()->QuadsBegin(); + + 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++) + { + int c = x + y*m_Width; + if(m_pTiles[c].m_Index) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "%i", m_pTiles[c].m_Index); + m_pEditor->Graphics()->QuadsText(x*32, y*32, 16.0f, aBuf); + + char aFlags[4] = { m_pTiles[c].m_Flags&TILEFLAG_VFLIP ? 'V' : ' ', + m_pTiles[c].m_Flags&TILEFLAG_HFLIP ? 'H' : ' ', + m_pTiles[c].m_Flags&TILEFLAG_ROTATE? 'R' : ' ', + 0}; + m_pEditor->Graphics()->QuadsText(x*32, y*32+16, 16.0f, aFlags); + } + x += m_pTiles[c].m_Skip; + } + + Graphics()->QuadsEnd(); + Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); +} + +int CLayerTiles::RenderProperties(CUIRect *pToolBox) +{ + CUIRect Button; + + bool InGameGroup = !find_linear(m_pEditor->m_Map.m_pGameGroup->m_lLayers.all(), this).empty(); + if(m_pEditor->m_Map.m_pGameLayer != this) + { + if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size() && m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.IsLoaded()) + { + static int s_AutoMapperButton = 0; + pToolBox->HSplitBottom(12.0f, pToolBox, &Button); + if(m_pEditor->DoButton_Editor(&s_AutoMapperButton, "Auto map", 0, &Button, 0, "")) + m_pEditor->PopupSelectConfigAutoMapInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY()); + + int Result = m_pEditor->PopupSelectConfigAutoMapResult(); + if(Result > -1) + { + m_pEditor->m_Map.m_lImages[m_Image]->m_AutoMapper.Proceed(this, Result); + return 1; + } + } + } + else if(m_pEditor->m_Map.m_pGameLayer == this || m_pEditor->m_Map.m_pTeleLayer == this || m_pEditor->m_Map.m_pSpeedupLayer == this || m_pEditor->m_Map.m_pFrontLayer == this || m_pEditor->m_Map.m_pSwitchLayer == this || m_pEditor->m_Map.m_pTuneLayer == this) + InGameGroup = false; + + if(InGameGroup) + { + pToolBox->HSplitBottom(2.0f, pToolBox, 0); + pToolBox->HSplitBottom(12.0f, pToolBox, &Button); + static int s_ColclButton = 0; + if(m_pEditor->DoButton_Editor(&s_ColclButton, "Game tiles", 0, &Button, 0, "Constructs game tiles from this layer")) + m_pEditor->PopupSelectGametileOpInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY()); + + int Result = m_pEditor->PopupSelectGameTileOpResult(); + switch(Result) + { + case 4: + Result = TILE_FREEZE; + break; + case 5: + Result = TILE_UNFREEZE; + break; + case 6: + Result = TILE_DFREEZE; + break; + case 7: + Result = TILE_DUNFREEZE; + break; + case 8: + Result = TILE_TELECHECKIN; + break; + case 9: + Result = TILE_TELECHECKINEVIL; + break; + default: + break; + } + if(Result > -1) + { + if (Result != TILE_TELECHECKIN && Result != TILE_TELECHECKINEVIL) + { + CLayerTiles *gl = m_pEditor->m_Map.m_pGameLayer; + + int w = min(gl->m_Width, m_Width); + int h = min(gl->m_Height, m_Height); + for(int y = 0; y < h; y++) + for(int x = 0; x < w; x++) + if(m_pTiles[y*m_Width+x].m_Index) + gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR+Result; + } + else if (m_pEditor->m_Map.m_pTeleLayer) + { + CLayerTele *gl = m_pEditor->m_Map.m_pTeleLayer; + + int w = min(gl->m_Width, m_Width); + int h = min(gl->m_Height, m_Height); + for(int y = 0; y < h; y++) + for(int x = 0; x < w; x++) + if(m_pTiles[y*m_Width+x].m_Index) + { + gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR+Result; + gl->m_pTeleTile[y*gl->m_Width+x].m_Number = 1; + gl->m_pTeleTile[y*gl->m_Width+x].m_Type = TILE_AIR+Result; + } + } + + return 1; + } + } + + enum + { + PROP_WIDTH=0, + PROP_HEIGHT, + PROP_SHIFT, + PROP_SHIFT_BY, + PROP_IMAGE, + PROP_COLOR, + PROP_COLOR_ENV, + PROP_COLOR_ENV_OFFSET, + 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}, + {"Shift", 0, PROPTYPE_SHIFT, 0, 0}, + {"Shift by", m_pEditor->m_ShiftBy, PROPTYPE_INT_SCROLL, 1, 1000000000}, + {"Image", m_Image, PROPTYPE_IMAGE, 0, 0}, + {"Color", Color, PROPTYPE_COLOR, 0, 0}, + {"Color Env", m_ColorEnv+1, PROPTYPE_INT_STEP, 0, m_pEditor->m_Map.m_lEnvelopes.size()+1}, + {"Color TO", m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {0}, + }; + + if(m_pEditor->m_Map.m_pGameLayer == this || m_pEditor->m_Map.m_pTeleLayer == this || m_pEditor->m_Map.m_pSpeedupLayer == this || m_pEditor->m_Map.m_pFrontLayer == this || m_pEditor->m_Map.m_pSwitchLayer == this || m_pEditor->m_Map.m_pTuneLayer == this) // remove the image and color properties if this is the game/tele/speedup/front/switch layer + { + aProps[4].m_pName = 0; + aProps[5].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) + Resize(m_Width, NewVal); + else if(Prop == PROP_SHIFT) + Shift(NewVal); + else if(Prop == PROP_SHIFT_BY) + m_pEditor->m_ShiftBy = NewVal; + else if(Prop == PROP_IMAGE) + { + if (NewVal == -1) + { + m_TexID = -1; + m_Image = -1; + } + else + m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); + } + else if(Prop == PROP_COLOR) + { + m_Color.r = (NewVal>>24)&0xff; + m_Color.g = (NewVal>>16)&0xff; + m_Color.b = (NewVal>>8)&0xff; + m_Color.a = NewVal&0xff; + } + if(Prop == PROP_COLOR_ENV) + { + int Index = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1); + int Step = (Index-m_ColorEnv)%2; + if(Step != 0) + { + for(; Index >= -1 && Index < m_pEditor->m_Map.m_lEnvelopes.size(); Index += Step) + if(Index == -1 || m_pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4) + { + m_ColorEnv = Index; + break; + } + } + } + if(Prop == PROP_COLOR_ENV_OFFSET) + m_ColorEnvOffset = NewVal; + + return 0; +} + + +void CLayerTiles::ModifyImageIndex(INDEX_MODIFY_FUNC Func) +{ + Func(&m_Image); +} + +void CLayerTiles::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) +{ +} + +CLayerTele::CLayerTele(int w, int h) +: CLayerTiles(w, h) +{ + //m_Type = LAYERTYPE_TELE; + str_copy(m_aName, "Tele", sizeof(m_aName)); + m_Tele = 1; + + m_pTeleTile = new CTeleTile[w*h]; + mem_zero(m_pTeleTile, w*h*sizeof(CTeleTile)); +} + +CLayerTele::~CLayerTele() +{ + delete[] m_pTeleTile; +} + +void CLayerTele::Resize(int NewW, int NewH) +{ + // resize tele data + CTeleTile *pNewTeleData = new CTeleTile[NewW*NewH]; + mem_zero(pNewTeleData, NewW*NewH*sizeof(CTeleTile)); + + // copy old data + for(int y = 0; y < min(NewH, m_Height); y++) + mem_copy(&pNewTeleData[y*NewW], &m_pTeleTile[y*m_Width], min(m_Width, NewW)*sizeof(CTeleTile)); + + // replace old + delete [] m_pTeleTile; + m_pTeleTile = pNewTeleData; + + // resize tile data + CLayerTiles::Resize(NewW, NewH); + + // resize gamelayer too + if(m_pEditor->m_Map.m_pGameLayer->m_Width != NewW || m_pEditor->m_Map.m_pGameLayer->m_Height != NewH) + m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); +} + +void CLayerTele::Shift(int Direction) +{ + CLayerTiles::Shift(Direction); + int o = m_pEditor->m_ShiftBy; + + switch(Direction) + { + case 1: + { + // left + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTeleTile[y*m_Width], &m_pTeleTile[y*m_Width+o], (m_Width-o)*sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[y*m_Width + (m_Width-o)], o*sizeof(CTeleTile)); + } + } + break; + case 2: + { + // right + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTeleTile[y*m_Width+o], &m_pTeleTile[y*m_Width], (m_Width-o)*sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[y*m_Width], o*sizeof(CTeleTile)); + } + } + break; + case 4: + { + // up + for(int y = 0; y < m_Height-o; ++y) + { + mem_copy(&m_pTeleTile[y*m_Width], &m_pTeleTile[(y+o)*m_Width], m_Width*sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[(y+o)*m_Width], m_Width*sizeof(CTeleTile)); + } + } + break; + case 8: + { + // down + for(int y = m_Height-1; y >= o; --y) + { + mem_copy(&m_pTeleTile[y*m_Width], &m_pTeleTile[(y-o)*m_Width], m_Width*sizeof(CTeleTile)); + mem_zero(&m_pTeleTile[(y-o)*m_Width], m_Width*sizeof(CTeleTile)); + } + } + } +} + +void CLayerTele::BrushDraw(CLayer *pBrush, float wx, float wy) +{ + if(m_Readonly) + return; + + CLayerTele *l = (CLayerTele *)pBrush; + int sx = ConvertX(wx); + int sy = ConvertY(wy); + if(str_comp(l->m_aFileName, m_pEditor->m_aFileName)) + m_pEditor->m_TeleNumber = l->m_TeleNum; + + for(int y = 0; y < l->m_Height; y++) + for(int x = 0; x < l->m_Width; x++) + { + int fx = x+sx; + int fy = y+sy; + if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELEIN || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELEINEVIL || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELECHECKINEVIL || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELEOUT || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELECHECK || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELECHECKOUT || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELECHECKIN || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELEINWEAPON || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TELEINHOOK) + { + if(m_pEditor->m_TeleNumber != l->m_TeleNum) + { + m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + } + else if(l->m_pTeleTile[y*l->m_Width+x].m_Number) + m_pTeleTile[fy*m_Width+fx].m_Number = l->m_pTeleTile[y*l->m_Width+x].m_Number; + else + { + if(!m_pEditor->m_TeleNumber) + { + m_pTeleTile[fy*m_Width+fx].m_Number = 0; + m_pTeleTile[fy*m_Width+fx].m_Type = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + continue; + } + else + m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + } + + m_pTeleTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else + { + m_pTeleTile[fy*m_Width+fx].m_Number = 0; + m_pTeleTile[fy*m_Width+fx].m_Type = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + } + } + m_pEditor->m_Map.m_Modified = true; +} + +void CLayerTele::BrushFlipX() +{ + CLayerTiles::BrushFlipX(); + + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width/2; x++) + { + CTeleTile Tmp = m_pTeleTile[y*m_Width+x]; + m_pTeleTile[y*m_Width+x] = m_pTeleTile[y*m_Width+m_Width-1-x]; + m_pTeleTile[y*m_Width+m_Width-1-x] = Tmp; + } +} + +void CLayerTele::BrushFlipY() +{ + CLayerTiles::BrushFlipY(); + + for(int y = 0; y < m_Height/2; y++) + for(int x = 0; x < m_Width; x++) + { + CTeleTile Tmp = m_pTeleTile[y*m_Width+x]; + m_pTeleTile[y*m_Width+x] = m_pTeleTile[(m_Height-1-y)*m_Width+x]; + m_pTeleTile[(m_Height-1-y)*m_Width+x] = Tmp; + } +} + +void CLayerTele::BrushRotate(float Amount) +{ + int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + if(Rotation < 0) + Rotation +=4; + + if(Rotation == 1 || Rotation == 3) + { + // 90° rotation + CTeleTile *pTempData1 = new CTeleTile[m_Width*m_Height]; + CTile *pTempData2 = new CTile[m_Width*m_Height]; + mem_copy(pTempData1, m_pTeleTile, m_Width*m_Height*sizeof(CTeleTile)); + mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTeleTile *pDst1 = m_pTeleTile; + CTile *pDst2 = m_pTiles; + for(int x = 0; x < m_Width; ++x) + for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + { + *pDst1 = pTempData1[y*m_Width+x]; + *pDst2 = pTempData2[y*m_Width+x]; + } + + int Temp = m_Width; + m_Width = m_Height; + m_Height = Temp; + delete[] pTempData1; + delete[] pTempData2; + } + + if(Rotation == 2 || Rotation == 3) + { + BrushFlipX(); + BrushFlipY(); + } +} + +void CLayerTele::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) +{ + if(m_Readonly) + return; + + Snap(&Rect); // corrects Rect; no need of <= + + Snap(&Rect); + + int sx = ConvertX(Rect.x); + int sy = ConvertY(Rect.y); + int w = ConvertX(Rect.w); + int h = ConvertY(Rect.h); + + CLayerTele *pLt = static_cast<CLayerTele*>(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 || !(pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index) // air chosen: reset + { + m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pTeleTile[fy*m_Width+fx].m_Type = 0; + m_pTeleTile[fy*m_Width+fx].m_Number = 0; + } + 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_pTeleTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + if(m_pTiles[fy*m_Width+fx].m_Index > 0) + { + if((!pLt->m_pTeleTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number && m_pEditor->m_TeleNumber) || m_pEditor->m_TeleNumber != pLt->m_TeleNum) + m_pTeleTile[fy*m_Width+fx].m_Number = m_pEditor->m_TeleNumber; + else + m_pTeleTile[fy*m_Width+fx].m_Number = pLt->m_pTeleTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; + } + } + } + } +} + +CLayerSpeedup::CLayerSpeedup(int w, int h) +: CLayerTiles(w, h) +{ + //m_Type = LAYERTYPE_SPEEDUP; + str_copy(m_aName, "Speedup", sizeof(m_aName)); + m_Speedup = 1; + + m_pSpeedupTile = new CSpeedupTile[w*h]; + mem_zero(m_pSpeedupTile, w*h*sizeof(CSpeedupTile)); +} + +CLayerSpeedup::~CLayerSpeedup() +{ + delete[] m_pSpeedupTile; +} + +void CLayerSpeedup::Resize(int NewW, int NewH) +{ + // resize speedup data + CSpeedupTile *pNewSpeedupData = new CSpeedupTile[NewW*NewH]; + mem_zero(pNewSpeedupData, NewW*NewH*sizeof(CSpeedupTile)); + + // copy old data + for(int y = 0; y < min(NewH, m_Height); y++) + mem_copy(&pNewSpeedupData[y*NewW], &m_pSpeedupTile[y*m_Width], min(m_Width, NewW)*sizeof(CSpeedupTile)); + + // replace old + delete [] m_pSpeedupTile; + m_pSpeedupTile = pNewSpeedupData; + + // resize tile data + CLayerTiles::Resize(NewW, NewH); + + // resize gamelayer too + if(m_pEditor->m_Map.m_pGameLayer->m_Width != NewW || m_pEditor->m_Map.m_pGameLayer->m_Height != NewH) + m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); +} + +void CLayerSpeedup::Shift(int Direction) +{ + CLayerTiles::Shift(Direction); + int o = m_pEditor->m_ShiftBy; + + switch(Direction) + { + case 1: + { + // left + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[y*m_Width+o], (m_Width-o)*sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[y*m_Width + (m_Width-o)], o*sizeof(CSpeedupTile)); + } + } + break; + case 2: + { + // right + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pSpeedupTile[y*m_Width+o], &m_pSpeedupTile[y*m_Width], (m_Width-o)*sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[y*m_Width], o*sizeof(CSpeedupTile)); + } + } + break; + case 4: + { + // up + for(int y = 0; y < m_Height-o; ++y) + { + mem_copy(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[(y+o)*m_Width], m_Width*sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[(y+o)*m_Width], m_Width*sizeof(CSpeedupTile)); + } + } + break; + case 8: + { + // down + for(int y = m_Height-1; y >= o; --y) + { + mem_copy(&m_pSpeedupTile[y*m_Width], &m_pSpeedupTile[(y-o)*m_Width], m_Width*sizeof(CSpeedupTile)); + mem_zero(&m_pSpeedupTile[(y-o)*m_Width], m_Width*sizeof(CSpeedupTile)); + } + } + } +} + +void CLayerSpeedup::BrushDraw(CLayer *pBrush, float wx, float wy) +{ + if(m_Readonly) + return; + + CLayerSpeedup *l = (CLayerSpeedup *)pBrush; + int sx = ConvertX(wx); + int sy = ConvertY(wy); + if(str_comp(l->m_aFileName, m_pEditor->m_aFileName)) + { + m_pEditor->m_SpeedupAngle = l->m_SpeedupAngle; + m_pEditor->m_SpeedupForce = l->m_SpeedupForce; + m_pEditor->m_SpeedupMaxSpeed = l->m_SpeedupMaxSpeed; + } + + for(int y = 0; y < l->m_Height; y++) + for(int x = 0; x < l->m_Width; x++) + { + int fx = x+sx; + int fy = y+sy; + if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_BOOST) + { + if(m_pEditor->m_SpeedupAngle != l->m_SpeedupAngle || m_pEditor->m_SpeedupForce != l->m_SpeedupForce || m_pEditor->m_SpeedupMaxSpeed != l->m_SpeedupMaxSpeed) + { + m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; + m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else if(l->m_pSpeedupTile[y*l->m_Width+x].m_Force) + { + m_pSpeedupTile[fy*m_Width+fx].m_Force = l->m_pSpeedupTile[y*l->m_Width+x].m_Force; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = l->m_pSpeedupTile[y*l->m_Width+x].m_Angle; + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = l->m_pSpeedupTile[y*l->m_Width+x].m_MaxSpeed; + m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else if(m_pEditor->m_SpeedupForce) + { + m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; + m_pSpeedupTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else + { + m_pSpeedupTile[fy*m_Width+fx].m_Force = 0; + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = 0; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + } + } + else + { + m_pSpeedupTile[fy*m_Width+fx].m_Force = 0; + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = 0; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + } + } + m_pEditor->m_Map.m_Modified = true; +} + +void CLayerSpeedup::BrushFlipX() +{ + CLayerTiles::BrushFlipX(); + + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width/2; x++) + { + CSpeedupTile Tmp = m_pSpeedupTile[y*m_Width+x]; + m_pSpeedupTile[y*m_Width+x] = m_pSpeedupTile[y*m_Width+m_Width-1-x]; + m_pSpeedupTile[y*m_Width+m_Width-1-x] = Tmp; + } +} + +void CLayerSpeedup::BrushFlipY() +{ + CLayerTiles::BrushFlipY(); + + for(int y = 0; y < m_Height/2; y++) + for(int x = 0; x < m_Width; x++) + { + CSpeedupTile Tmp = m_pSpeedupTile[y*m_Width+x]; + m_pSpeedupTile[y*m_Width+x] = m_pSpeedupTile[(m_Height-1-y)*m_Width+x]; + m_pSpeedupTile[(m_Height-1-y)*m_Width+x] = Tmp; + } +} + +void CLayerSpeedup::BrushRotate(float Amount) +{ + int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + if(Rotation < 0) + Rotation +=4; + + if(Rotation == 1 || Rotation == 3) + { + // 90° rotation + CSpeedupTile *pTempData1 = new CSpeedupTile[m_Width*m_Height]; + CTile *pTempData2 = new CTile[m_Width*m_Height]; + mem_copy(pTempData1, m_pSpeedupTile, m_Width*m_Height*sizeof(CSpeedupTile)); + mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CSpeedupTile *pDst1 = m_pSpeedupTile; + CTile *pDst2 = m_pTiles; + for(int x = 0; x < m_Width; ++x) + for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + { + *pDst1 = pTempData1[y*m_Width+x]; + *pDst2 = pTempData2[y*m_Width+x]; + } + + int Temp = m_Width; + m_Width = m_Height; + m_Height = Temp; + delete[] pTempData1; + delete[] pTempData2; + } + + if(Rotation == 2 || Rotation == 3) + { + BrushFlipX(); + BrushFlipY(); + } +} + +void CLayerSpeedup::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) +{ + if(m_Readonly) + return; + + Snap(&Rect); // corrects Rect; no need of <= + + Snap(&Rect); + + int sx = ConvertX(Rect.x); + int sy = ConvertY(Rect.y); + int w = ConvertX(Rect.w); + int h = ConvertY(Rect.h); + + CLayerSpeedup *pLt = static_cast<CLayerSpeedup*>(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 || (pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index != TILE_BOOST) // no speed up tile choosen: reset + { + m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pSpeedupTile[fy*m_Width+fx].m_Force = 0; + m_pSpeedupTile[fy*m_Width+fx].m_Angle = 0; + } + 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_pSpeedupTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + if(m_pTiles[fy*m_Width+fx].m_Index > 0) + { + if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Force && m_pEditor->m_SpeedupForce) || m_pEditor->m_SpeedupForce != pLt->m_SpeedupForce) + m_pSpeedupTile[fy*m_Width+fx].m_Force = m_pEditor->m_SpeedupForce; + else + m_pSpeedupTile[fy*m_Width+fx].m_Force = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Force; + if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Angle && m_pEditor->m_SpeedupAngle) || m_pEditor->m_SpeedupAngle != pLt->m_SpeedupAngle) + m_pSpeedupTile[fy*m_Width+fx].m_Angle = m_pEditor->m_SpeedupAngle; + else + m_pSpeedupTile[fy*m_Width+fx].m_Angle = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Angle; + if((!pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_MaxSpeed && m_pEditor->m_SpeedupMaxSpeed) || m_pEditor->m_SpeedupMaxSpeed != pLt->m_SpeedupMaxSpeed) + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = m_pEditor->m_SpeedupMaxSpeed; + else + m_pSpeedupTile[fy*m_Width+fx].m_MaxSpeed = pLt->m_pSpeedupTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_MaxSpeed; + } + } + } + } +} + +CLayerFront::CLayerFront(int w, int h) +: CLayerTiles(w, h) +{ + //m_Type = LAYERTYPE_FRONT; + str_copy(m_aName, "Front", sizeof(m_aName)); + m_Front = 1; +} + +void CLayerFront::Resize(int NewW, int NewH) +{ + // resize tile data + CLayerTiles::Resize(NewW, NewH); + + // resize gamelayer too + if(m_pEditor->m_Map.m_pGameLayer->m_Width != NewW || m_pEditor->m_Map.m_pGameLayer->m_Height != NewH) + m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); +} + +void CLayerFront::Shift(int Direction) +{ + CLayerTiles::Shift(Direction); +} + +void CLayerFront::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++) + { + int fx = x+sx; + 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; +} + +CLayerSwitch::CLayerSwitch(int w, int h) +: CLayerTiles(w, h) +{ + //m_Type = LAYERTYPE_SWITCH; + str_copy(m_aName, "Switch", sizeof(m_aName)); + m_Switch = 1; + + m_pSwitchTile = new CSwitchTile[w*h]; + mem_zero(m_pSwitchTile, w*h*sizeof(CSwitchTile)); +} + +CLayerSwitch::~CLayerSwitch() +{ + delete[] m_pSwitchTile; +} + +void CLayerSwitch::Resize(int NewW, int NewH) +{ + // resize switch data + CSwitchTile *pNewSwitchData = new CSwitchTile[NewW*NewH]; + mem_zero(pNewSwitchData, NewW*NewH*sizeof(CSwitchTile)); + + // copy old data + for(int y = 0; y < min(NewH, m_Height); y++) + mem_copy(&pNewSwitchData[y*NewW], &m_pSwitchTile[y*m_Width], min(m_Width, NewW)*sizeof(CSwitchTile)); + + // replace old + delete [] m_pSwitchTile; + m_pSwitchTile = pNewSwitchData; + + // resize tile data + CLayerTiles::Resize(NewW, NewH); + + // resize gamelayer too + if(m_pEditor->m_Map.m_pGameLayer->m_Width != NewW || m_pEditor->m_Map.m_pGameLayer->m_Height != NewH) + m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); +} + +void CLayerSwitch::Shift(int Direction) +{ + CLayerTiles::Shift(Direction); + int o = m_pEditor->m_ShiftBy; + + switch(Direction) + { + case 1: + { + // left + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[y*m_Width+o], (m_Width-o)*sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[y*m_Width + (m_Width-o)], o*sizeof(CSwitchTile)); + } + } + break; + case 2: + { + // right + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pSwitchTile[y*m_Width+o], &m_pSwitchTile[y*m_Width], (m_Width-o)*sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[y*m_Width], o*sizeof(CSwitchTile)); + } + } + break; + case 4: + { + // up + for(int y = 0; y < m_Height-o; ++y) + { + mem_copy(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[(y+o)*m_Width], m_Width*sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[(y+o)*m_Width], m_Width*sizeof(CSwitchTile)); + } + } + break; + case 8: + { + // down + for(int y = m_Height-1; y >= o; --y) + { + mem_copy(&m_pSwitchTile[y*m_Width], &m_pSwitchTile[(y-o)*m_Width], m_Width*sizeof(CSwitchTile)); + mem_zero(&m_pSwitchTile[(y-o)*m_Width], m_Width*sizeof(CSwitchTile)); + } + } + } +} + +void CLayerSwitch::BrushDraw(CLayer *pBrush, float wx, float wy) +{ + if(m_Readonly) + return; + + CLayerSwitch *l = (CLayerSwitch *)pBrush; + int sx = ConvertX(wx); + int sy = ConvertY(wy); + if(str_comp(l->m_aFileName, m_pEditor->m_aFileName)) + { + m_pEditor->m_SwitchNum = l->m_SwitchNumber; + m_pEditor->m_SwitchDelay = l->m_SwitchDelay; + } + + for(int y = 0; y < l->m_Height; y++) + for(int x = 0; x < l->m_Width; x++) + { + int fx = x+sx; + int fy = y+sy; + if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if((l->m_pTiles[y*l->m_Width+x].m_Index >= (ENTITY_ARMOR_1 + ENTITY_OFFSET) && l->m_pTiles[y*l->m_Width+x].m_Index <= (ENTITY_DOOR + ENTITY_OFFSET)) || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_HIT_START || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_HIT_END || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_SWITCHOPEN || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_SWITCHCLOSE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_SWITCHTIMEDOPEN || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_SWITCHTIMEDCLOSE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_FREEZE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DFREEZE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DUNFREEZE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_JUMP || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_PENALTY || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_BONUS) + { + if(m_pEditor->m_SwitchNum != l->m_SwitchNumber || m_pEditor->m_SwitchDelay != l->m_SwitchDelay) + { + m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; + m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + } + else if(l->m_pSwitchTile[y*l->m_Width+x].m_Number) + { + m_pSwitchTile[fy*m_Width+fx].m_Number = l->m_pSwitchTile[y*l->m_Width+x].m_Number; + m_pSwitchTile[fy*m_Width+fx].m_Delay = l->m_pSwitchTile[y*l->m_Width+x].m_Delay; + } + else + { + m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; + m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + } + + m_pSwitchTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pSwitchTile[fy*m_Width+fx].m_Flags = l->m_pTiles[y*l->m_Width+x].m_Flags; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else + { + m_pSwitchTile[fy*m_Width+fx].m_Number = 0; + m_pSwitchTile[fy*m_Width+fx].m_Type = 0; + m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; + m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + } + + if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_FREEZE) + { + m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; + } + else if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DFREEZE || l->m_pTiles[y*l->m_Width+x].m_Index == TILE_DUNFREEZE) + { + m_pSwitchTile[fy*m_Width+fx].m_Flags = 0; + m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; + } + } + m_pEditor->m_Map.m_Modified = true; +} + +void CLayerSwitch::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) +{ + if(m_Readonly) + return; + + Snap(&Rect); // corrects Rect; no need of <= + + Snap(&Rect); + + int sx = ConvertX(Rect.x); + int sy = ConvertY(Rect.y); + int w = ConvertX(Rect.w); + int h = ConvertY(Rect.h); + + CLayerSwitch *pLt = static_cast<CLayerSwitch*>(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 || !(pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index) // at least reset the tile if air is choosen + { + m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pSwitchTile[fy*m_Width+fx].m_Type = 0; + m_pSwitchTile[fy*m_Width+fx].m_Number = 0; + m_pSwitchTile[fy*m_Width+fx].m_Delay = 0; + } + 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_pSwitchTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + if(m_pEditor->m_SwitchNum && m_pTiles[fy*m_Width+fx].m_Index > 0) + { + if((!pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number) || m_pEditor->m_SwitchNum != pLt->m_SwitchNumber) + m_pSwitchTile[fy*m_Width+fx].m_Number = m_pEditor->m_SwitchNum; + else + m_pSwitchTile[fy*m_Width+fx].m_Number = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; + if((!pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Delay) || m_pEditor->m_SwitchDelay != pLt->m_SwitchDelay) + m_pSwitchTile[fy*m_Width+fx].m_Delay = m_pEditor->m_SwitchDelay; + else + m_pSwitchTile[fy*m_Width+fx].m_Delay = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Delay; + m_pSwitchTile[fy*m_Width+fx].m_Flags = pLt->m_pSwitchTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Flags; + } + } + } + } +} + +//------------------------------------------------------ + +CLayerTune::CLayerTune(int w, int h) +: CLayerTiles(w, h) +{ + //m_Type = LAYERTYPE_SWITCH; + str_copy(m_aName, "Tune", sizeof(m_aName)); + m_Tune = 1; + + m_pTuneTile = new CTuneTile[w*h]; + mem_zero(m_pTuneTile, w*h*sizeof(CTuneTile)); +} + +CLayerTune::~CLayerTune() +{ + delete[] m_pTuneTile; +} + +void CLayerTune::Resize(int NewW, int NewH) +{ + // resize Tune data + CTuneTile *pNewTuneData = new CTuneTile[NewW*NewH]; + mem_zero(pNewTuneData, NewW*NewH*sizeof(CTuneTile)); + + // copy old data + for(int y = 0; y < min(NewH, m_Height); y++) + mem_copy(&pNewTuneData[y*NewW], &m_pTuneTile[y*m_Width], min(m_Width, NewW)*sizeof(CTuneTile)); + + // replace old + delete [] m_pTuneTile; + m_pTuneTile = pNewTuneData; + + // resize tile data + CLayerTiles::Resize(NewW, NewH); + + // resize gamelayer too + if(m_pEditor->m_Map.m_pGameLayer->m_Width != NewW || m_pEditor->m_Map.m_pGameLayer->m_Height != NewH) + m_pEditor->m_Map.m_pGameLayer->Resize(NewW, NewH); +} + +void CLayerTune::Shift(int Direction) +{ + CLayerTiles::Shift(Direction); + int o = m_pEditor->m_ShiftBy; + + switch(Direction) + { + case 1: + { + // left + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTuneTile[y*m_Width], &m_pTuneTile[y*m_Width+o], (m_Width-o)*sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[y*m_Width + (m_Width-o)], o*sizeof(CTuneTile)); + } + } + break; + case 2: + { + // right + for(int y = 0; y < m_Height; ++y) + { + mem_move(&m_pTuneTile[y*m_Width+o], &m_pTuneTile[y*m_Width], (m_Width-o)*sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[y*m_Width], o*sizeof(CTuneTile)); + } + } + break; + case 4: + { + // up + for(int y = 0; y < m_Height-o; ++y) + { + mem_copy(&m_pTuneTile[y*m_Width], &m_pTuneTile[(y+o)*m_Width], m_Width*sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[(y+o)*m_Width], m_Width*sizeof(CTuneTile)); + } + } + break; + case 8: + { + // down + for(int y = m_Height-1; y >= o; --y) + { + mem_copy(&m_pTuneTile[y*m_Width], &m_pTuneTile[(y-o)*m_Width], m_Width*sizeof(CTuneTile)); + mem_zero(&m_pTuneTile[(y-o)*m_Width], m_Width*sizeof(CTuneTile)); + } + } + } +} + +void CLayerTune::BrushDraw(CLayer *pBrush, float wx, float wy) +{ + if(m_Readonly) + return; + + CLayerTune *l = (CLayerTune *)pBrush; + int sx = ConvertX(wx); + int sy = ConvertY(wy); + if(str_comp(l->m_aFileName, m_pEditor->m_aFileName)) + { + m_pEditor->m_TuningNum = l->m_TuningNumber; + } + + for(int y = 0; y < l->m_Height; y++) + for(int x = 0; x < l->m_Width; x++) + { + int fx = x+sx; + int fy = y+sy; + if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) + continue; + + if(l->m_pTiles[y*l->m_Width+x].m_Index == TILE_TUNE1) + { + if(m_pEditor->m_TuningNum != l->m_TuningNumber) + { + m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; + } + else if(l->m_pTuneTile[y*l->m_Width+x].m_Number) + m_pTuneTile[fy*m_Width+fx].m_Number = l->m_pTuneTile[y*l->m_Width+x].m_Number; + else + { + if(!m_pEditor->m_TuningNum) + { + m_pTuneTile[fy*m_Width+fx].m_Number = 0; + m_pTuneTile[fy*m_Width+fx].m_Type = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + continue; + } + else + m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; + } + + m_pTuneTile[fy*m_Width+fx].m_Type = l->m_pTiles[y*l->m_Width+x].m_Index; + m_pTiles[fy*m_Width+fx].m_Index = l->m_pTiles[y*l->m_Width+x].m_Index; + } + else + { + m_pTuneTile[fy*m_Width+fx].m_Number = 0; + m_pTuneTile[fy*m_Width+fx].m_Type = 0; + m_pTiles[fy*m_Width+fx].m_Index = 0; + } + } + m_pEditor->m_Map.m_Modified = true; +} + + +void CLayerTune::BrushFlipX() +{ + CLayerTiles::BrushFlipX(); + + for(int y = 0; y < m_Height; y++) + for(int x = 0; x < m_Width/2; x++) + { + CTuneTile Tmp = m_pTuneTile[y*m_Width+x]; + m_pTuneTile[y*m_Width+x] = m_pTuneTile[y*m_Width+m_Width-1-x]; + m_pTuneTile[y*m_Width+m_Width-1-x] = Tmp; + } +} + +void CLayerTune::BrushFlipY() +{ + CLayerTiles::BrushFlipY(); + + for(int y = 0; y < m_Height/2; y++) + for(int x = 0; x < m_Width; x++) + { + CTuneTile Tmp = m_pTuneTile[y*m_Width+x]; + m_pTuneTile[y*m_Width+x] = m_pTuneTile[(m_Height-1-y)*m_Width+x]; + m_pTuneTile[(m_Height-1-y)*m_Width+x] = Tmp; + } +} + +void CLayerTune::BrushRotate(float Amount) +{ + int Rotation = (round_to_int(360.0f*Amount/(pi*2))/90)%4; // 0=0°, 1=90°, 2=180°, 3=270° + if(Rotation < 0) + Rotation +=4; + + if(Rotation == 1 || Rotation == 3) + { + // 90° rotation + CTuneTile *pTempData1 = new CTuneTile[m_Width*m_Height]; + CTile *pTempData2 = new CTile[m_Width*m_Height]; + mem_copy(pTempData1, m_pTuneTile, m_Width*m_Height*sizeof(CTuneTile)); + mem_copy(pTempData2, m_pTiles, m_Width*m_Height*sizeof(CTile)); + CTuneTile *pDst1 = m_pTuneTile; + CTile *pDst2 = m_pTiles; + for(int x = 0; x < m_Width; ++x) + for(int y = m_Height-1; y >= 0; --y, ++pDst1, ++pDst2) + { + *pDst1 = pTempData1[y*m_Width+x]; + *pDst2 = pTempData2[y*m_Width+x]; + } + + int Temp = m_Width; + m_Width = m_Height; + m_Height = Temp; + delete[] pTempData1; + delete[] pTempData2; + } + + if(Rotation == 2 || Rotation == 3) + { + BrushFlipX(); + BrushFlipY(); + } +} + + +void CLayerTune::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) +{ + if(m_Readonly) + return; + + Snap(&Rect); // corrects Rect; no need of <= + + int sx = ConvertX(Rect.x); + int sy = ConvertY(Rect.y); + int w = ConvertX(Rect.w); + int h = ConvertY(Rect.h); + + CLayerTune *pLt = static_cast<CLayerTune*>(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 || (pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]).m_Index != TILE_TUNE1) // \o/ this fixes editor bug; TODO: use IsUsedInThisLayer here + { + m_pTiles[fy*m_Width+fx].m_Index = 0; + m_pTuneTile[fy*m_Width+fx].m_Type = 0; + m_pTuneTile[fy*m_Width+fx].m_Number = 0; + } + 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_pTuneTile[fy*m_Width+fx].m_Type = m_pTiles[fy*m_Width+fx].m_Index; + if(m_pTiles[fy*m_Width+fx].m_Index > 0) + { + if((!pLt->m_pTuneTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number && m_pEditor->m_TuningNum) || m_pEditor->m_TuningNum != pLt->m_TuningNumber) + m_pTuneTile[fy*m_Width+fx].m_Number = m_pEditor->m_TuningNum; + else + m_pTuneTile[fy*m_Width+fx].m_Number = pLt->m_pTuneTile[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)].m_Number; + } + } + } + } +} diff --git a/src/game/editor/popups.cpp b/src/game/editor/popups.cpp new file mode 100644 index 0000000..2c97d4e --- /dev/null +++ b/src/game/editor/popups.cpp @@ -0,0 +1,1627 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include <base/color.h> +#include <base/tl/array.h> + +#include <engine/console.h> +#include <engine/graphics.h> +#include <engine/input.h> +#include <engine/keys.h> +#include <engine/storage.h> + +#include "editor.h" + + +// popup menu handling +static struct +{ + CUIRect m_Rect; + void *m_pId; + int (*m_pfnFunc)(CEditor *pEditor, CUIRect Rect); + int m_IsMenu; + void *m_pExtra; +} s_UiPopups[8]; + +static int g_UiNumPopups = 0; + +void CEditor::UiInvokePopupMenu(void *pID, int Flags, float x, float y, float Width, float Height, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra) +{ + if(g_UiNumPopups > 7) + return; + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", "invoked"); + if(x + Width > UI()->Screen()->w) + x -= Width; + if(y + Height > UI()->Screen()->h) + y -= Height; + s_UiPopups[g_UiNumPopups].m_pId = pID; + s_UiPopups[g_UiNumPopups].m_IsMenu = Flags; + s_UiPopups[g_UiNumPopups].m_Rect.x = x; + s_UiPopups[g_UiNumPopups].m_Rect.y = y; + s_UiPopups[g_UiNumPopups].m_Rect.w = Width; + s_UiPopups[g_UiNumPopups].m_Rect.h = Height; + s_UiPopups[g_UiNumPopups].m_pfnFunc = pfnFunc; + s_UiPopups[g_UiNumPopups].m_pExtra = pExtra; + g_UiNumPopups++; +} + +void CEditor::UiDoPopupMenu() +{ + for(int i = 0; i < g_UiNumPopups; i++) + { + 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)) + { + if(!Inside) + g_UiNumPopups--; + UI()->SetActiveItem(0); + } + } + else if(UI()->HotItem() == &s_UiPopups[i].m_pId) + { + 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)) + { + m_LockMouse = false; + UI()->SetActiveItem(0); + g_UiNumPopups--; + } + + if(Input()->KeyDown(KEY_ESCAPE)) + { + m_LockMouse = false; + UI()->SetActiveItem(0); + g_UiNumPopups--; + } + } +} + + +int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) +{ + // remove group button + 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()) + { + if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete group", 0, &Button, 0, "Delete group")) + { + pEditor->m_Map.DeleteGroup(pEditor->m_SelectedGroup); + pEditor->m_SelectedGroup = max(0, pEditor->m_SelectedGroup-1); + return 1; + } + } + else + { + if(pEditor->DoButton_Editor(&s_DeleteButton, "Clean up game tiles", 0, &Button, 0, "Removes game tiles that aren't based on a layer")) + { + // gather all tile layers + array<CLayerTiles*> Layers; + for(int i = 0; i < pEditor->m_Map.m_pGameGroup->m_lLayers.size(); ++i) + { + if(pEditor->m_Map.m_pGameGroup->m_lLayers[i] != pEditor->m_Map.m_pGameLayer && pEditor->m_Map.m_pGameGroup->m_lLayers[i]->m_Type == LAYERTYPE_TILES) + Layers.add(static_cast<CLayerTiles *>(pEditor->m_Map.m_pGameGroup->m_lLayers[i])); + } + + // search for unneeded game tiles + CLayerTiles *gl = pEditor->m_Map.m_pGameLayer; + for(int y = 0; y < gl->m_Height; ++y) + for(int x = 0; x < gl->m_Width; ++x) + { + if(gl->m_pTiles[y*gl->m_Width+x].m_Index > static_cast<unsigned char>(TILE_NOHOOK)) + continue; + + bool Found = false; + for(int i = 0; i < Layers.size(); ++i) + { + if(x < Layers[i]->m_Width && y < Layers[i]->m_Height && Layers[i]->m_pTiles[y*Layers[i]->m_Width+x].m_Index) + { + Found = true; + break; + } + } + + if(!Found) + { + gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR; + pEditor->m_Map.m_Modified = true; + } + } + + return 1; + } + } + + if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pTeleLayer) + { + // new tele layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewSwitchLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewSwitchLayerButton, "Add tele layer", 0, &Button, 0, "Creates a new tele layer")) + { + CLayer *l = new CLayerTele(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeTeleLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Brush.Clear(); + return 1; + } + } + + if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pSpeedupLayer) + { + // new speedup layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewSwitchLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewSwitchLayerButton, "Add speedup layer", 0, &Button, 0, "Creates a new speedup layer")) + { + CLayer *l = new CLayerSpeedup(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeSpeedupLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Brush.Clear(); + return 1; + } + } + + if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pTuneLayer) + { + // new tune layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewSwitchLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewSwitchLayerButton, "Add tune layer", 0, &Button, 0, "Creates a new tuning layer")) + { + CLayer *l = new CLayerTune(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeTuneLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Brush.Clear(); + return 1; + } + } + + if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pFrontLayer) + { + // new force layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewFrontLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewFrontLayerButton, "Add front layer", 0, &Button, 0, "Creates a new item layer")) + { + CLayer *l = new CLayerFront(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeFrontLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Brush.Clear(); + return 1; + } + } + + if(pEditor->GetSelectedGroup()->m_GameGroup && !pEditor->m_Map.m_pSwitchLayer) + { + // new Switch layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewSwitchLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewSwitchLayerButton, "Add switch layer", 0, &Button, 0, "Creates a new switch layer")) + { + CLayer *l = new CLayerSwitch(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + pEditor->m_Map.MakeSwitchLayer(l); + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Brush.Clear(); + return 1; + } + } + + // new quad layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewQuadLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewQuadLayerButton, "Add quads layer", 0, &Button, 0, "Creates a new quad layer")) + { + CLayer *l = new CLayerQuads; + l->m_pEditor = pEditor; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; + return 1; + } + + // new tile layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewTileLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewTileLayerButton, "Add tile layer", 0, &Button, 0, "Creates a new tile layer")) + { + CLayer *l = new CLayerTiles(pEditor->m_Map.m_pGameLayer->m_Width, pEditor->m_Map.m_pGameLayer->m_Height); + l->m_pEditor = pEditor; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; + return 1; + } + + // new sound layer + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_NewSoundLayerButton = 0; + if(pEditor->DoButton_Editor(&s_NewSoundLayerButton, "Add sound layer", 0, &Button, 0, "Creates a new sound layer")) + { + CLayer *l = new CLayerSounds; + l->m_pEditor = pEditor; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; + return 1; + } + + // group name + if(!pEditor->GetSelectedGroup()->m_GameGroup) + { + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static float s_Name = 0; + pEditor->UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); + Button.VSplitLeft(40.0f, 0, &Button); + if(pEditor->DoEditBox(&s_Name, &Button, pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName, sizeof(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName), 10.0f, &s_Name)) + pEditor->m_Map.m_Modified = true; + } + + enum + { + PROP_ORDER=0, + PROP_POS_X, + PROP_POS_Y, + PROP_PARA_X, + PROP_PARA_Y, + PROP_USE_CLIPPING, + PROP_CLIP_X, + PROP_CLIP_Y, + PROP_CLIP_W, + 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}, + {"Pos Y", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Para X", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Para Y", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + + {"Use Clipping", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping, PROPTYPE_BOOL, 0, 1}, + {"Clip X", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Clip Y", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Clip W", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW, PROPTYPE_INT_SCROLL, 0, 1000000}, + {"Clip H", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH, PROPTYPE_INT_SCROLL, 0, 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) + { + if(Prop == PROP_PARA_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX = NewVal; + else if(Prop == PROP_PARA_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY = NewVal; + else if(Prop == PROP_POS_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX = -NewVal; + else if(Prop == PROP_POS_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY = -NewVal; + else if(Prop == PROP_USE_CLIPPING) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping = NewVal; + else if(Prop == PROP_CLIP_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX = NewVal; + else if(Prop == PROP_CLIP_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY = NewVal; + 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; +} + +int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) +{ + // remove layer button + 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")) + { + if(pEditor->GetSelectedLayer(0) == pEditor->m_Map.m_pFrontLayer) + pEditor->m_Map.m_pFrontLayer = 0x0; + if(pEditor->GetSelectedLayer(0) == pEditor->m_Map.m_pTeleLayer) + pEditor->m_Map.m_pTeleLayer = 0x0; + if(pEditor->GetSelectedLayer(0) == pEditor->m_Map.m_pSpeedupLayer) + pEditor->m_Map.m_pSpeedupLayer = 0x0; + if(pEditor->GetSelectedLayer(0) == pEditor->m_Map.m_pSwitchLayer) + pEditor->m_Map.m_pSwitchLayer = 0x0; + if(pEditor->GetSelectedLayer(0) == pEditor->m_Map.m_pTuneLayer) + pEditor->m_Map.m_pTuneLayer = 0x0; + pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->DeleteLayer(pEditor->m_SelectedLayer); + return 1; + } + + // layer name + // if(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0)) + if(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0) && pEditor->m_Map.m_pTeleLayer != pEditor->GetSelectedLayer(0) && pEditor->m_Map.m_pSpeedupLayer != pEditor->GetSelectedLayer(0) && pEditor->m_Map.m_pFrontLayer != pEditor->GetSelectedLayer(0) && pEditor->m_Map.m_pSwitchLayer != pEditor->GetSelectedLayer(0) && pEditor->m_Map.m_pTuneLayer != pEditor->GetSelectedLayer(0)) + { + View.HSplitBottom(5.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static float s_Name = 0; + pEditor->UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); + Button.VSplitLeft(40.0f, 0, &Button); + if(pEditor->DoEditBox(&s_Name, &Button, pEditor->GetSelectedLayer(0)->m_aName, sizeof(pEditor->GetSelectedLayer(0)->m_aName), 10.0f, &s_Name)) + pEditor->m_Map.m_Modified = true; + } + + 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, + PROP_ORDER, + 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()}, + {"Detail", pCurrentLayer->m_Flags&LAYERFLAG_DETAIL, PROPTYPE_BOOL, 0, 1}, + {0}, + }; + + // if(pEditor->m_Map.m_pGameLayer == pEditor->GetSelectedLayer(0)) // dont use Group and Detail from the selection if this is the game layer + if(pEditor->m_Map.m_pGameLayer == pEditor->GetSelectedLayer(0) || pEditor->m_Map.m_pTeleLayer == pEditor->GetSelectedLayer(0) || pEditor->m_Map.m_pSpeedupLayer == pEditor->GetSelectedLayer(0) || pEditor->m_Map.m_pFrontLayer == pEditor->GetSelectedLayer(0) || pEditor->m_Map.m_pSwitchLayer == pEditor->GetSelectedLayer(0) || pEditor->m_Map.m_pTuneLayer == pEditor->GetSelectedLayer(0)) // dont use Group and Detail from the selection if this is the game layer + { + 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) + { + if(NewVal >= 0 && NewVal < pEditor->m_Map.m_lGroups.size()) + { + pCurrentGroup->m_lLayers.remove(pCurrentLayer); + pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.add(pCurrentLayer); + pEditor->m_SelectedGroup = NewVal; + pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.size()-1; + } + } + else if(Prop == PROP_HQ) + { + pCurrentLayer->m_Flags &= ~LAYERFLAG_DETAIL; + if(NewVal) + pCurrentLayer->m_Flags |= LAYERFLAG_DETAIL; + } + + return pCurrentLayer->RenderProperties(&View); +} + +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; + if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete", 0, &Button, 0, "Deletes the current quad")) + { + CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS); + if(pLayer) + { + pEditor->m_Map.m_Modified = true; + pLayer->m_lQuads.remove_index(pEditor->m_SelectedQuad); + pEditor->m_SelectedQuad--; + } + return 1; + } + + // aspect ratio button + View.HSplitBottom(10.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS); + if(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < pEditor->m_Map.m_lImages.size()) + { + static int s_AspectRatioButton = 0; + if(pEditor->DoButton_Editor(&s_AspectRatioButton, "Aspect ratio", 0, &Button, 0, "Resizes the current Quad based on the aspect ratio of the image")) + { + int Top = pQuad->m_aPoints[0].y; + int Left = pQuad->m_aPoints[0].x; + 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; + if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x; + if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x; + } + + 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; + pQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Top+Height; + pEditor->m_Map.m_Modified = true; + return 1; + } + } + + // align button + View.HSplitBottom(6.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_AlignButton = 0; + if(pEditor->DoButton_Editor(&s_AlignButton, "Align", 0, &Button, 0, "Aligns coordinates of the quad points")) + { + for(int k = 1; k < 4; k++) + { + pQuad->m_aPoints[k].x = 1000.0f * (int(pQuad->m_aPoints[k].x) / 1000); + pQuad->m_aPoints[k].y = 1000.0f * (int(pQuad->m_aPoints[k].y) / 1000); + } + pEditor->m_Map.m_Modified = true; + return 1; + } + + // square button + View.HSplitBottom(6.0f, &View, &Button); + View.HSplitBottom(12.0f, &View, &Button); + static int s_Button = 0; + if(pEditor->DoButton_Editor(&s_Button, "Square", 0, &Button, 0, "Squares the current quad")) + { + int Top = pQuad->m_aPoints[0].y; + 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; + if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x; + 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; + pQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Bottom; + pEditor->m_Map.m_Modified = true; + return 1; + } + + + enum + { + PROP_POS_X=0, + PROP_POS_Y, + PROP_POS_ENV, + PROP_POS_ENV_OFFSET, + PROP_COLOR_ENV, + 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}, + {"Pos. Env", pQuad->m_PosEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, + {"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; + for(int k = 0; k < 5; ++k) + pQuad->m_aPoints[k].x += Offset; + } + if(Prop == PROP_POS_Y) + { + float Offset = NewVal*1000-pQuad->m_aPoints[4].y; + for(int k = 0; k < 5; ++k) + pQuad->m_aPoints[k].y += Offset; + } + if(Prop == PROP_POS_ENV) + { + int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); + int Step = (Index-pQuad->m_PosEnv)%2; + if(Step != 0) + { + for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) + if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 3) + { + pQuad->m_PosEnv = Index; + break; + } + } + } + if(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal; + if(Prop == PROP_COLOR_ENV) + { + int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); + int Step = (Index-pQuad->m_ColorEnv)%2; + if(Step != 0) + { + for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) + if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4) + { + pQuad->m_ColorEnv = Index; + break; + } + } + } + if(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal; + + return 0; +} + +int CEditor::PopupSource(CEditor *pEditor, CUIRect View) +{ + CSoundSource *pSource = pEditor->GetSelectedSource(); + + CUIRect Button; + + // delete button + View.HSplitBottom(12.0f, &View, &Button); + static int s_DeleteButton = 0; + if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete", 0, &Button, 0, "Deletes the current source")) + { + CLayerSounds *pLayer = (CLayerSounds *)pEditor->GetSelectedLayerType(0, LAYERTYPE_SOUNDS); + if(pLayer) + { + pEditor->m_Map.m_Modified = true; + pLayer->m_lSources.remove_index(pEditor->m_SelectedSource); + pEditor->m_SelectedSource--; + } + return 1; + } + + // Sound shape button + CUIRect ShapeButton; + View.HSplitBottom(3.0f, &View, 0x0); + View.HSplitBottom(12.0f, &View, &ShapeButton); + static int s_ShapeTypeButton = 0; + + static const char *s_aShapeNames[] = { + "Rectangle", + "Circle" + }; + + pSource->m_Shape.m_Type = pSource->m_Shape.m_Type%CSoundShape::NUM_SHAPES; // prevent out of array errors + + if(pEditor->DoButton_Editor(&s_ShapeTypeButton, s_aShapeNames[pSource->m_Shape.m_Type], 0, &ShapeButton, 0, "Change shape")) + { + pSource->m_Shape.m_Type = (pSource->m_Shape.m_Type+1)%CSoundShape::NUM_SHAPES; + + // set default values + switch(pSource->m_Shape.m_Type) + { + case CSoundShape::SHAPE_CIRCLE: + { + pSource->m_Shape.m_Circle.m_Radius = 1000.0f; + break; + } + case CSoundShape::SHAPE_RECTANGLE: + { + pSource->m_Shape.m_Rectangle.m_Width = f2fx(1000.0f); + pSource->m_Shape.m_Rectangle.m_Height = f2fx(800.0f); + break; + } + } + } + + + enum + { + PROP_POS_X=0, + PROP_POS_Y, + PROP_LOOP, + PROP_PAN, + PROP_TIME_DELAY, + PROP_FALLOFF, + PROP_POS_ENV, + PROP_POS_ENV_OFFSET, + PROP_SOUND_ENV, + PROP_SOUND_ENV_OFFSET, + NUM_PROPS, + }; + + CProperty aProps[] = { + {"Pos X", pSource->m_Position.x/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Pos Y", pSource->m_Position.y/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Loop", pSource->m_Loop, PROPTYPE_BOOL, 0, 1}, + {"Pan", pSource->m_Pan, PROPTYPE_BOOL, 0, 1}, + {"Delay", pSource->m_TimeDelay, PROPTYPE_INT_SCROLL, 0, 1000000}, + {"Falloff", pSource->m_Falloff, PROPTYPE_INT_SCROLL, 0, 255}, + {"Pos. Env", pSource->m_PosEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, + {"Pos. TO", pSource->m_PosEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, + {"Sound Env", pSource->m_SoundEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, + {"Sound. TO", pSource->m_PosEnvOffset, 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) pSource->m_Position.x = NewVal*1000; + if(Prop == PROP_POS_Y) pSource->m_Position.y = NewVal*1000; + if(Prop == PROP_LOOP) pSource->m_Loop = NewVal; + if(Prop == PROP_PAN) pSource->m_Pan = NewVal; + if(Prop == PROP_TIME_DELAY) pSource->m_TimeDelay = NewVal; + if(Prop == PROP_FALLOFF) pSource->m_Falloff = NewVal; + if(Prop == PROP_POS_ENV) + { + int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); + int Step = (Index-pSource->m_PosEnv)%2; + if(Step != 0) + { + for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) + if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 3) + { + pSource->m_PosEnv = Index; + break; + } + } + } + if(Prop == PROP_POS_ENV_OFFSET) pSource->m_PosEnvOffset = NewVal; + if(Prop == PROP_SOUND_ENV) + { + int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); + int Step = (Index-pSource->m_SoundEnv)%2; + if(Step != 0) + { + for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) + if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 1) + { + pSource->m_SoundEnv = Index; + break; + } + } + } + if(Prop == PROP_SOUND_ENV_OFFSET) pSource->m_SoundEnvOffset = NewVal; + + // source shape properties + switch(pSource->m_Shape.m_Type) + { + case CSoundShape::SHAPE_CIRCLE: + { + enum + { + PROP_CIRCLE_RADIUS=0, + NUM_CIRCLE_PROPS, + }; + + CProperty aCircleProps[] = { + {"Radius", pSource->m_Shape.m_Circle.m_Radius, PROPTYPE_INT_SCROLL, 0, 1000000}, + + {0}, + }; + + static int s_aCircleIds[NUM_CIRCLE_PROPS] = {0}; + + NewVal = 0; + Prop = pEditor->DoProperties(&View, aCircleProps, s_aCircleIds, &NewVal); + if(Prop != -1) + pEditor->m_Map.m_Modified = true; + + if(Prop == PROP_CIRCLE_RADIUS) pSource->m_Shape.m_Circle.m_Radius = NewVal; + + break; + } + + case CSoundShape::SHAPE_RECTANGLE: + { + enum + { + PROP_RECTANGLE_WIDTH=0, + PROP_RECTANGLE_HEIGHT, + NUM_RECTANGLE_PROPS, + }; + + CProperty aRectangleProps[] = { + {"Width", pSource->m_Shape.m_Rectangle.m_Width/1024, PROPTYPE_INT_SCROLL, 0, 1000000}, + {"Height", pSource->m_Shape.m_Rectangle.m_Height/1024, PROPTYPE_INT_SCROLL, 0, 1000000}, + + {0}, + }; + + static int s_aRectangleIds[NUM_RECTANGLE_PROPS] = {0}; + + NewVal = 0; + Prop = pEditor->DoProperties(&View, aRectangleProps, s_aRectangleIds, &NewVal); + if(Prop != -1) + pEditor->m_Map.m_Modified = true; + + if(Prop == PROP_RECTANGLE_WIDTH) pSource->m_Shape.m_Rectangle.m_Width = NewVal*1024; + if(Prop == PROP_RECTANGLE_HEIGHT) pSource->m_Shape.m_Rectangle.m_Height = NewVal*1024; + + break; + } + } + + + return 0; +} + +int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) +{ + CQuad *pQuad = pEditor->GetSelectedQuad(); + + enum + { + PROP_POS_X=0, + PROP_POS_Y, + PROP_COLOR, + NUM_PROPS, + }; + + int Color = 0; + int x = 0, y = 0; + + for(int v = 0; v < 4; v++) + { + if(pEditor->m_SelectedPoints&(1<<v)) + { + Color = 0; + Color |= pQuad->m_aColors[v].r<<24; + Color |= pQuad->m_aColors[v].g<<16; + Color |= pQuad->m_aColors[v].b<<8; + Color |= pQuad->m_aColors[v].a; + + x = pQuad->m_aPoints[v].x/1000; + 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); + if(Prop != -1) + pEditor->m_Map.m_Modified = true; + + if(Prop == PROP_POS_X) + { + for(int v = 0; v < 4; v++) + if(pEditor->m_SelectedPoints&(1<<v)) + pQuad->m_aPoints[v].x = NewVal*1000; + } + if(Prop == PROP_POS_Y) + { + for(int v = 0; v < 4; v++) + if(pEditor->m_SelectedPoints&(1<<v)) + pQuad->m_aPoints[v].y = NewVal*1000; + } + if(Prop == PROP_COLOR) + { + for(int v = 0; v < 4; v++) + { + if(pEditor->m_SelectedPoints&(1<<v)) + { + pQuad->m_aColors[v].r = (NewVal>>24)&0xff; + pQuad->m_aColors[v].g = (NewVal>>16)&0xff; + pQuad->m_aColors[v].b = (NewVal>>8)&0xff; + pQuad->m_aColors[v].a = NewVal&0xff; + } + } + } + + return 0; +} + +int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) +{ + CUIRect Label, ButtonBar; + + // title + View.HSplitTop(10.0f, 0, &View); + View.HSplitTop(30.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Create new folder", 20.0f, 0); + + View.HSplitBottom(10.0f, &View, 0); + View.HSplitBottom(20.0f, &View, &ButtonBar); + + if(pEditor->m_FileDialogErrString[0] == 0) + { + // interaction box + View.HSplitBottom(40.0f, &View, 0); + View.VMargin(40.0f, &View); + View.HSplitBottom(20.0f, &View, &Label); + static float s_FolderBox = 0; + pEditor->DoEditBox(&s_FolderBox, &Label, pEditor->m_FileDialogNewFolderName, sizeof(pEditor->m_FileDialogNewFolderName), 15.0f, &s_FolderBox); + View.HSplitBottom(20.0f, &View, &Label); + pEditor->UI()->DoLabel(&Label, "Name:", 10.0f, -1); + + // button bar + ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); + static int s_CreateButton = 0; + if(pEditor->DoButton_Editor(&s_CreateButton, "Create", 0, &Label, 0, 0)) + { + // create the folder + if(*pEditor->m_FileDialogNewFolderName) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s/%s", pEditor->m_pFileDialogPath, pEditor->m_FileDialogNewFolderName); + if(pEditor->Storage()->CreateFolder(aBuf, IStorage::TYPE_SAVE)) + { + pEditor->FilelistPopulate(IStorage::TYPE_SAVE); + return 1; + } + 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); + static int s_AbortButton = 0; + if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) + return 1; + } + else + { + // error text + View.HSplitTop(30.0f, 0, &View); + View.VMargin(40.0f, &View); + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Error:", 10.0f, -1); + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Unable to create the folder", 10.0f, -1, View.w); + + // button + ButtonBar.VMargin(ButtonBar.w/2.0f-55.0f, &ButtonBar); + static int s_CreateButton = 0; + if(pEditor->DoButton_Editor(&s_CreateButton, "Ok", 0, &ButtonBar, 0, 0)) + return 1; + } + + return 0; +} + +int CEditor::PopupMapInfo(CEditor *pEditor, CUIRect View) +{ + CUIRect Label, ButtonBar, Button; + + // title + View.HSplitTop(10.0f, 0, &View); + View.HSplitTop(30.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Map details", 20.0f, 0); + + View.HSplitBottom(10.0f, &View, 0); + View.HSplitBottom(20.0f, &View, &ButtonBar); + + View.VMargin(40.0f, &View); + + // author box + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Author:", 10.0f, -1); + Label.VSplitLeft(40.0f, 0, &Button); + Button.HSplitTop(12.0f, &Button, 0); + static float s_AuthorBox = 0; + pEditor->DoEditBox(&s_AuthorBox, &Button, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthorTmp), 10.0f, &s_AuthorBox); + + // version box + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Version:", 10.0f, -1); + Label.VSplitLeft(40.0f, 0, &Button); + Button.HSplitTop(12.0f, &Button, 0); + static float s_VersionBox = 0; + pEditor->DoEditBox(&s_VersionBox, &Button, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersionTmp), 10.0f, &s_VersionBox); + + // credits box + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "Credits:", 10.0f, -1); + Label.VSplitLeft(40.0f, 0, &Button); + Button.HSplitTop(12.0f, &Button, 0); + static float s_CreditsBox = 0; + pEditor->DoEditBox(&s_CreditsBox, &Button, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCreditsTmp), 10.0f, &s_CreditsBox); + + // license box + View.HSplitTop(20.0f, &Label, &View); + pEditor->UI()->DoLabel(&Label, "License:", 10.0f, -1); + Label.VSplitLeft(40.0f, 0, &Button); + Button.HSplitTop(12.0f, &Button, 0); + static float s_LicenseBox = 0; + pEditor->DoEditBox(&s_LicenseBox, &Button, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicenseTmp), 10.0f, &s_LicenseBox); + + // button bar + ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); + static int s_CreateButton = 0; + if(pEditor->DoButton_Editor(&s_CreateButton, "Save", 0, &Label, 0, 0)) + { + str_copy(pEditor->m_Map.m_MapInfo.m_aAuthor, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthor)); + str_copy(pEditor->m_Map.m_MapInfo.m_aVersion, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersion)); + str_copy(pEditor->m_Map.m_MapInfo.m_aCredits, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCredits)); + str_copy(pEditor->m_Map.m_MapInfo.m_aLicense, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicense)); + return 1; + } + + ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); + ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); + static int s_AbortButton = 0; + if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) + return 1; + + return 0; +} + +int CEditor::PopupEvent(CEditor *pEditor, CUIRect View) +{ + CUIRect Label, ButtonBar; + + // title + View.HSplitTop(10.0f, 0, &View); + View.HSplitTop(30.0f, &Label, &View); + if(pEditor->m_PopupEventType == POPEVENT_EXIT) + pEditor->UI()->DoLabel(&Label, "Exit the editor", 20.0f, 0); + else if(pEditor->m_PopupEventType == POPEVENT_LOAD) + pEditor->UI()->DoLabel(&Label, "Load map", 20.0f, 0); + else if(pEditor->m_PopupEventType == POPEVENT_NEW) + pEditor->UI()->DoLabel(&Label, "New map", 20.0f, 0); + else if(pEditor->m_PopupEventType == POPEVENT_SAVE) + pEditor->UI()->DoLabel(&Label, "Save map", 20.0f, 0); + + View.HSplitBottom(10.0f, &View, 0); + View.HSplitBottom(20.0f, &View, &ButtonBar); + + // notification text + View.HSplitTop(30.0f, 0, &View); + View.VMargin(40.0f, &View); + View.HSplitTop(20.0f, &Label, &View); + if(pEditor->m_PopupEventType == POPEVENT_EXIT) + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you exit the editor.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); + else if(pEditor->m_PopupEventType == POPEVENT_LOAD) + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you load a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); + else if(pEditor->m_PopupEventType == POPEVENT_NEW) + pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you create a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); + else if(pEditor->m_PopupEventType == POPEVENT_SAVE) + pEditor->UI()->DoLabel(&Label, "The file already exists.\nDo you want to overwrite the map?", 10.0f, -1); + + // button bar + ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); + ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); + static int s_OkButton = 0; + if(pEditor->DoButton_Editor(&s_OkButton, "Ok", 0, &Label, 0, 0)) + { + if(pEditor->m_PopupEventType == POPEVENT_EXIT) + g_Config.m_ClEditor = 0; + else if(pEditor->m_PopupEventType == POPEVENT_LOAD) + pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", pEditor->CallbackOpenMap, pEditor); + else if(pEditor->m_PopupEventType == POPEVENT_NEW) + { + pEditor->Reset(); + pEditor->m_aFileName[0] = 0; + } + else if(pEditor->m_PopupEventType == POPEVENT_SAVE) + pEditor->CallbackSaveMap(pEditor->m_aFileSaveName, IStorage::TYPE_SAVE, pEditor); + pEditor->m_PopupEventWasActivated = false; + return 1; + } + ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); + ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); + static int s_AbortButton = 0; + if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) + { + pEditor->m_PopupEventWasActivated = false; + return 1; + } + + return 0; +} + + +static int g_SelectImageSelected = -100; +static int g_SelectImageCurrent = -100; + +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; + + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + float ImagesHeight = pEditor->m_Map.m_lImages.size() * 14; + float ScrollDifference = ImagesHeight - ButtonBar.h; + + if(pEditor->m_Map.m_lImages.size() > 20) // Do we need a scrollbar? + { + CUIRect Scroll; + ButtonBar.VSplitRight(15.0f, &ButtonBar, &Scroll); + ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = pEditor->UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(pEditor->UI()->MouseInside(&Scroll) || pEditor->UI()->MouseInside(&ButtonBar)) + { + int ScrollNum = (int)((ImagesHeight-ButtonBar.h)/14.0f)+1; + if(ScrollNum > 0) + { + if(pEditor->Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(pEditor->Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + } + } + + float ImageStartAt = ScrollDifference * s_ScrollValue; + if(ImageStartAt < 0.0f) + ImageStartAt = 0.0f; + + float ImageStopAt = ImagesHeight - ScrollDifference * (1 - s_ScrollValue); + float ImageCur = 0.0f; + for(int i = -1; i < pEditor->m_Map.m_lImages.size(); i++) + { + if(ImageCur > ImageStopAt) + break; + if(ImageCur < ImageStartAt) + { + ImageCur += 14.0f; + continue; + } + ImageCur += 14.0f; + + CUIRect Button; + ButtonBar.HSplitTop(14.0f, &Button, &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)) + g_SelectImageSelected = -1; + } + else + { + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], pEditor->m_Map.m_lImages[i]->m_aName, i==g_SelectImageCurrent, &Button)) + g_SelectImageSelected = i; + } + } + + if(ShowImage >= 0 && ShowImage < pEditor->m_Map.m_lImages.size()) + { + if(ImageView.h < ImageView.w) + ImageView.w = ImageView.h; + else + ImageView.h = ImageView.w; + float Max = (float)(max(pEditor->m_Map.m_lImages[ShowImage]->m_Width, pEditor->m_Map.m_lImages[ShowImage]->m_Height)); + ImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width/Max; + ImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height/Max; + pEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_TexID); + pEditor->Graphics()->BlendNormal(); + pEditor->Graphics()->WrapClamp(); + pEditor->Graphics()->QuadsBegin(); + IGraphics::CQuadItem QuadItem(ImageView.x, ImageView.y, ImageView.w, ImageView.h); + pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); + pEditor->Graphics()->QuadsEnd(); + pEditor->Graphics()->WrapNormal(); + } + + return 0; +} + +void CEditor::PopupSelectImageInvoke(int Current, float x, float y) +{ + static int s_SelectImagePopupId = 0; + g_SelectImageSelected = -100; + g_SelectImageCurrent = Current; + UiInvokePopupMenu(&s_SelectImagePopupId, 0, x, y, 400, 300, PopupSelectImage); +} + +int CEditor::PopupSelectImageResult() +{ + if(g_SelectImageSelected == -100) + return -100; + + g_SelectImageCurrent = g_SelectImageSelected; + g_SelectImageSelected = -100; + return g_SelectImageCurrent; +} + +static int g_SelectSoundSelected = -100; +static int g_SelectSoundCurrent = -100; + +int CEditor::PopupSelectSound(CEditor *pEditor, CUIRect View) +{ + CUIRect ButtonBar, SoundView; + View.VSplitLeft(80.0f, &ButtonBar, &View); + View.Margin(10.0f, &SoundView); + + + static int s_ScrollBar = 0; + static float s_ScrollValue = 0; + float SoundsHeight = pEditor->m_Map.m_lSounds.size() * 14; + float ScrollDifference = SoundsHeight - ButtonBar.h; + + if(pEditor->m_Map.m_lSounds.size() > 20) // Do we need a scrollbar? + { + CUIRect Scroll; + ButtonBar.VSplitRight(15.0f, &ButtonBar, &Scroll); + ButtonBar.VSplitRight(3.0f, &ButtonBar, 0); // extra spacing + Scroll.HMargin(5.0f, &Scroll); + s_ScrollValue = pEditor->UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); + + if(pEditor->UI()->MouseInside(&Scroll) || pEditor->UI()->MouseInside(&ButtonBar)) + { + int ScrollNum = (int)((SoundsHeight-ButtonBar.h)/14.0f)+1; + if(ScrollNum > 0) + { + if(pEditor->Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) + s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); + if(pEditor->Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) + s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); + } + } + } + + float SoundStartAt = ScrollDifference * s_ScrollValue; + if(SoundStartAt < 0.0f) + SoundStartAt = 0.0f; + + float SoundStopAt = SoundsHeight - ScrollDifference * (1 - s_ScrollValue); + float SoundCur = 0.0f; + for(int i = -1; i < pEditor->m_Map.m_lSounds.size(); i++) + { + if(SoundCur > SoundStopAt) + break; + if(SoundCur < SoundStartAt) + { + SoundCur += 14.0f; + continue; + } + SoundCur += 14.0f; + + CUIRect Button; + ButtonBar.HSplitTop(14.0f, &Button, &ButtonBar); + + //if(pEditor->UI()->MouseInside(&Button)) + // ShowSound = i; + + if(i == -1) + { + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], "None", i==g_SelectSoundCurrent, &Button)) + g_SelectSoundSelected = -1; + } + else + { + if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lSounds[i], pEditor->m_Map.m_lSounds[i]->m_aName, i==g_SelectSoundCurrent, &Button)) + g_SelectSoundSelected = i; + } + } + + return 0; +} + +void CEditor::PopupSelectSoundInvoke(int Current, float x, float y) +{ + static int s_SelectSoundPopupId = 0; + g_SelectSoundSelected = -100; + g_SelectSoundCurrent = Current; + UiInvokePopupMenu(&s_SelectSoundPopupId, 0, x, y, 400, 300, PopupSelectSound); +} + +int CEditor::PopupSelectSoundResult() +{ + if(g_SelectSoundSelected == -100) + return -100; + + g_SelectSoundCurrent = g_SelectSoundSelected; + g_SelectSoundSelected = -100; + return g_SelectSoundCurrent; +} + +static int s_GametileOpSelected = -1; + +int CEditor::PopupSelectGametileOp(CEditor *pEditor, CUIRect View) +{ + static const char *s_pButtonNames[] = { "Clear", "Collision", "Death", "Unhookable", "Freeze", "Unfreeze", "Deep Freeze", "Deep Unfreeze", "Check-Tele From", "Evil Check-Tele From" }; + static unsigned s_NumButtons = sizeof(s_pButtonNames) / sizeof(char*); + CUIRect Button; + + for(unsigned i = 0; i < s_NumButtons; ++i) + { + View.HSplitTop(2.0f, 0, &View); + View.HSplitTop(12.0f, &Button, &View); + if(pEditor->DoButton_Editor(&s_pButtonNames[i], s_pButtonNames[i], 0, &Button, 0, 0)) + s_GametileOpSelected = i; + } + + return 0; +} + +void CEditor::PopupSelectGametileOpInvoke(float x, float y) +{ + static int s_SelectGametileOpPopupId = 0; + s_GametileOpSelected = -1; + UiInvokePopupMenu(&s_SelectGametileOpPopupId, 0, x, y, 120.0f, 150.0f, PopupSelectGametileOp); +} + +int CEditor::PopupSelectGameTileOpResult() +{ + if(s_GametileOpSelected < 0) + return -1; + + int Result = s_GametileOpSelected; + s_GametileOpSelected = -1; + return Result; +} + +static int s_AutoMapConfigSelected = -1; + +int CEditor::PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View) +{ + CLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0)); + CUIRect Button; + static int s_AutoMapperConfigButtons[256]; + CAutoMapper *pAutoMapper = &pEditor->m_Map.m_lImages[pLayer->m_Image]->m_AutoMapper; + + for(int i = 0; i < pAutoMapper->ConfigNamesNum(); ++i) + { + View.HSplitTop(2.0f, 0, &View); + View.HSplitTop(12.0f, &Button, &View); + if(pEditor->DoButton_Editor(&s_AutoMapperConfigButtons[i], pAutoMapper->GetConfigName(i), 0, &Button, 0, 0)) + s_AutoMapConfigSelected = i; + } + + return 0; +} + +void CEditor::PopupSelectConfigAutoMapInvoke(float x, float y) +{ + static int s_AutoMapConfigSelectID = 0; + s_AutoMapConfigSelected = -1; + CLayerTiles *pLayer = static_cast<CLayerTiles*>(GetSelectedLayer(0)); + if(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size() && + m_Map.m_lImages[pLayer->m_Image]->m_AutoMapper.ConfigNamesNum()) + UiInvokePopupMenu(&s_AutoMapConfigSelectID, 0, x, y, 120.0f, 12.0f+14.0f*m_Map.m_lImages[pLayer->m_Image]->m_AutoMapper.ConfigNamesNum(), PopupSelectConfigAutoMap); +} + +int CEditor::PopupSelectConfigAutoMapResult() +{ + if(s_AutoMapConfigSelected < 0) + return -1; + + int Result = s_AutoMapConfigSelected; + s_AutoMapConfigSelected = -1; + return Result; +} + +// DDRace + +int CEditor::PopupTele(CEditor *pEditor, CUIRect View) +{ + CUIRect Button; + View.HSplitBottom(12.0f, &View, &Button); + + enum + { + PROP_TELE=0, + NUM_PROPS, + }; + + CProperty aProps[] = { + {"Number", pEditor->m_TeleNumber, PROPTYPE_INT_STEP, 0, 255}, + {0}, + }; + + static int s_aIds[NUM_PROPS] = {0}; + int NewVal = 0; + static vec4 s_color = vec4(1,1,1,0.5f); + + int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal, s_color); + + if(Prop == PROP_TELE) + { + NewVal = (NewVal + 256) % 256; + + CLayerTele *gl = pEditor->m_Map.m_pTeleLayer; + for(int y = 0; y < gl->m_Height; ++y) + { + for(int x = 0; x < gl->m_Width; ++x) + { + if(gl->m_pTeleTile[y*gl->m_Width+x].m_Number == NewVal) + { + s_color = vec4(1,0.5f,0.5f,0.5f); + goto done; + } + } + } + + s_color = vec4(0.5f,1,0.5f,0.5f); + + done: + pEditor->m_TeleNumber = NewVal; + } + + return 0; +} + +int CEditor::PopupSpeedup(CEditor *pEditor, CUIRect View) +{ + CUIRect Button; + View.HSplitBottom(12.0f, &View, &Button); + + enum + { + PROP_FORCE=0, + PROP_MAXSPEED, + PROP_ANGLE, + NUM_PROPS + }; + + CProperty aProps[] = { + {"Force", pEditor->m_SpeedupForce, PROPTYPE_INT_SCROLL, 0, 255}, + {"Max Speed", pEditor->m_SpeedupMaxSpeed, PROPTYPE_INT_SCROLL, 0, 255}, + {"Angle", pEditor->m_SpeedupAngle, PROPTYPE_ANGLE_SCROLL, 0, 359}, + {0}, + }; + + static int s_aIds[NUM_PROPS] = {0}; + int NewVal = 0; + int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); + + if(Prop == PROP_FORCE) + pEditor->m_SpeedupForce = clamp(NewVal, 0, 255); + if(Prop == PROP_MAXSPEED) + pEditor->m_SpeedupMaxSpeed = clamp(NewVal, 0, 255); + if(Prop == PROP_ANGLE) + pEditor->m_SpeedupAngle = clamp(NewVal, 0, 359); + + return 0; +} + +int CEditor::PopupSwitch(CEditor *pEditor, CUIRect View) +{ + CUIRect Button; + View.HSplitBottom(12.0f, &View, &Button); + + enum + { + PROP_SwitchNumber=0, + PROP_SwitchDelay, + NUM_PROPS, + }; + + CProperty aProps[] = { + {"Number", pEditor->m_SwitchNum, PROPTYPE_INT_STEP, 0, 255}, + {"Delay", pEditor->m_SwitchDelay, PROPTYPE_INT_STEP, 0, 255}, + {0}, + }; + + static int s_aIds[NUM_PROPS] = {0}; + int NewVal = 0; + static vec4 s_color = vec4(1,1,1,0.5f); + int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal, s_color); + + if(Prop == PROP_SwitchNumber) + { + NewVal = (NewVal + 256) % 256; + + CLayerSwitch *gl = pEditor->m_Map.m_pSwitchLayer; + for(int y = 0; y < gl->m_Height; ++y) + { + for(int x = 0; x < gl->m_Width; ++x) + { + if(gl->m_pSwitchTile[y*gl->m_Width+x].m_Number == NewVal) + { + s_color = vec4(1,0.5f,0.5f,0.5f); + goto done; + } + } + } + + s_color = vec4(0.5f,1,0.5f,0.5f); + + done: + pEditor->m_SwitchNum = NewVal; + } + if(Prop == PROP_SwitchDelay) + pEditor->m_SwitchDelay = (NewVal + 256) % 256; + + return 0; +} + +int CEditor::PopupTune(CEditor *pEditor, CUIRect View) +{ + CUIRect Button; + View.HSplitBottom(12.0f, &View, &Button); + + enum + { + PROP_TUNE=0, + NUM_PROPS, + }; + + CProperty aProps[] = { + {"Zone", pEditor->m_TuningNum, PROPTYPE_INT_STEP, 1, 255}, + {0}, + }; + + static int s_aIds[NUM_PROPS] = {0}; + int NewVal = 0; + int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); + + if(Prop == PROP_TUNE) + pEditor->m_TuningNum = (NewVal - 1 + 255) % 255 + 1; + + return 0; +} + +int CEditor::PopupColorPicker(CEditor *pEditor, CUIRect View) +{ + CUIRect SVPicker, HuePicker; + View.VSplitRight(20.0f, &SVPicker, &HuePicker); + HuePicker.VSplitLeft(4.0f, 0x0, &HuePicker); + + pEditor->Graphics()->TextureSet(-1); + pEditor->Graphics()->QuadsBegin(); + + // base: white - hue + vec3 hsv = pEditor->ms_PickerColor; + IGraphics::CColorVertex ColorArray[4]; + + vec3 c = HsvToRgb(vec3(hsv.x, 0.0f, 1.0f)); + ColorArray[0] = IGraphics::CColorVertex(0, c.r, c.g, c.b, 1.0f); + c = HsvToRgb(vec3(hsv.x, 1.0f, 1.0f)); + ColorArray[1] = IGraphics::CColorVertex(1, c.r, c.g, c.b, 1.0f); + c = HsvToRgb(vec3(hsv.x, 1.0f, 1.0f)); + ColorArray[2] = IGraphics::CColorVertex(2, c.r, c.g, c.b, 1.0f); + c = HsvToRgb(vec3(hsv.x, 0.0f, 1.0f)); + ColorArray[3] = IGraphics::CColorVertex(3, c.r, c.g, c.b, 1.0f); + + pEditor->Graphics()->SetColorVertex(ColorArray, 4); + + IGraphics::CQuadItem QuadItem(SVPicker.x, SVPicker.y, SVPicker.w, SVPicker.h); + pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); + + // base: transparent - black + ColorArray[0] = IGraphics::CColorVertex(0, 0.0f, 0.0f, 0.0f, 0.0f); + ColorArray[1] = IGraphics::CColorVertex(1, 0.0f, 0.0f, 0.0f, 0.0f); + ColorArray[2] = IGraphics::CColorVertex(2, 0.0f, 0.0f, 0.0f, 1.0f); + ColorArray[3] = IGraphics::CColorVertex(3, 0.0f, 0.0f, 0.0f, 1.0f); + + pEditor->Graphics()->SetColorVertex(ColorArray, 4); + + pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); + + pEditor->Graphics()->QuadsEnd(); + + // marker + vec2 Marker = vec2(hsv.y*pEditor->UI()->Scale(), (1.0f - hsv.z)*pEditor->UI()->Scale()) * vec2(SVPicker.w, SVPicker.h); + pEditor->Graphics()->QuadsBegin(); + pEditor->Graphics()->SetColor(0.5f, 0.5f, 0.5f, 1.0f); + IGraphics::CQuadItem aMarker[2]; + aMarker[0] = IGraphics::CQuadItem(SVPicker.x+Marker.x, SVPicker.y+Marker.y - 5.0f*pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize(), 11.0f*pEditor->UI()->PixelSize()); + aMarker[1] = IGraphics::CQuadItem(SVPicker.x+Marker.x - 5.0f*pEditor->UI()->PixelSize(), SVPicker.y+Marker.y, 11.0f*pEditor->UI()->PixelSize(), pEditor->UI()->PixelSize()); + pEditor->Graphics()->QuadsDrawTL(aMarker, 2); + pEditor->Graphics()->QuadsEnd(); + + // logic + float X, Y; + if(pEditor->UI()->DoPickerLogic(&pEditor->ms_SVPicker, &SVPicker, &X, &Y)) + { + hsv.y = X/SVPicker.w; + hsv.z = 1.0f - Y/SVPicker.h; + } + + // hue slider + static const float s_aColorIndices[7][3] = { + {1.0f, 0.0f, 0.0f}, // red + {1.0f, 0.0f, 1.0f}, // magenta + {0.0f, 0.0f, 1.0f}, // blue + {0.0f, 1.0f, 1.0f}, // cyan + {0.0f, 1.0f, 0.0f}, // green + {1.0f, 1.0f, 0.0f}, // yellow + {1.0f, 0.0f, 0.0f} // red + }; + + pEditor->Graphics()->QuadsBegin(); + vec4 ColorTop, ColorBottom; + float Offset = HuePicker.h/6.0f; + for(int j = 0; j < 6; j++) + { + ColorTop = vec4(s_aColorIndices[j][0], s_aColorIndices[j][1], s_aColorIndices[j][2], 1.0f); + ColorBottom = vec4(s_aColorIndices[j+1][0], s_aColorIndices[j+1][1], s_aColorIndices[j+1][2], 1.0f); + + ColorArray[0] = IGraphics::CColorVertex(0, ColorTop.r, ColorTop.g, ColorTop.b, ColorTop.a); + ColorArray[1] = IGraphics::CColorVertex(1, ColorTop.r, ColorTop.g, ColorTop.b, ColorTop.a); + ColorArray[2] = IGraphics::CColorVertex(2, ColorBottom.r, ColorBottom.g, ColorBottom.b, ColorBottom.a); + ColorArray[3] = IGraphics::CColorVertex(3, ColorBottom.r, ColorBottom.g, ColorBottom.b, ColorBottom.a); + pEditor->Graphics()->SetColorVertex(ColorArray, 4); + IGraphics::CQuadItem QuadItem(HuePicker.x, HuePicker.y+Offset*j, HuePicker.w, Offset); + pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); + } + + // marker + pEditor->Graphics()->SetColor(0.5f, 0.5f, 0.5f, 1.0f); + IGraphics::CQuadItem QuadItemMarker(HuePicker.x, HuePicker.y + (1.0f - hsv.x) * HuePicker.h * pEditor->UI()->Scale(), HuePicker.w, pEditor->UI()->PixelSize()); + pEditor->Graphics()->QuadsDrawTL(&QuadItemMarker, 1); + + pEditor->Graphics()->QuadsEnd(); + + if(pEditor->UI()->DoPickerLogic(&pEditor->ms_HuePicker, &HuePicker, &X, &Y)) + { + hsv.x = 1.0f - Y/HuePicker.h; + } + + pEditor->ms_PickerColor = hsv; + + return 0; +} diff --git a/src/game/gamecore.cpp b/src/game/gamecore.cpp new file mode 100644 index 0000000..299eb42 --- /dev/null +++ b/src/game/gamecore.cpp @@ -0,0 +1,794 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "gamecore.h" + +#include <engine/shared/config.h> +#include <engine/server/server.h> +const char *CTuningParams::m_apNames[] = +{ + #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) #ScriptName, + #include "tuning.h" + #undef MACRO_TUNING_PARAM +}; + + +bool CTuningParams::Set(int Index, float Value) +{ + if(Index < 0 || Index >= Num()) + return false; + ((CTuneParam *)this)[Index] = Value; + return true; +} + +bool CTuningParams::Get(int Index, float *pValue) +{ + if(Index < 0 || Index >= Num()) + return false; + *pValue = (float)((CTuneParam *)this)[Index]; + return true; +} + +bool CTuningParams::Set(const char *pName, float Value) +{ + for(int i = 0; i < Num(); i++) + if(str_comp_nocase(pName, m_apNames[i]) == 0) + return Set(i, Value); + return false; +} + +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; +} + +float HermiteBasis1(float v) +{ + return 2*v*v*v - 3*v*v+1; +} + +float VelocityRamp(float Value, float Start, float Range, float Curvature) +{ + if(Value < Start) + return 1.0f; + return 1.0f/powf(Curvature, (Value-Start)/Range); +} + +void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore* pTeams) +{ + m_pWorld = pWorld; + m_pCollision = pCollision; + m_pTeleOuts = NULL; + + m_pTeams = pTeams; + m_Id = -1; + m_Hook = true; + m_Collision = true; + m_JumpedTotal = 0; + m_Jumps = 2; +} + +void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore* pTeams, std::map<int, std::vector<vec2> > *pTeleOuts) +{ + m_pWorld = pWorld; + m_pCollision = pCollision; + m_pTeleOuts = pTeleOuts; + + m_pTeams = pTeams; + m_Id = -1; + m_Hook = true; + m_Collision = true; + m_JumpedTotal = 0; + m_Jumps = 2; +} + +void CCharacterCore::Reset() +{ + m_Pos = vec2(0,0); + m_Vel = vec2(0,0); + m_NewHook = false; + m_HookPos = vec2(0,0); + m_HookDir = vec2(0,0); + m_HookTick = 0; + m_HookState = HOOK_IDLE; + m_HookedPlayer = -1; + m_Jumped = 0; + m_JumpedTotal = 0; + m_Jumps = 2; + m_TriggeredEvents = 0; + m_Hook = true; + m_Collision = true; +} + +void CCharacterCore::Tick(bool UseInput, bool IsClient) +{ + float PhysSize = 28.0f; + int MapIndex = Collision()->GetPureMapIndex(m_Pos);; + int MapIndexL = Collision()->GetPureMapIndex(vec2(m_Pos.x + (28/2)+4,m_Pos.y)); + int MapIndexR = Collision()->GetPureMapIndex(vec2(m_Pos.x - (28/2)-4,m_Pos.y)); + int MapIndexT = Collision()->GetPureMapIndex(vec2(m_Pos.x,m_Pos.y + (28/2)+4)); + int MapIndexB = Collision()->GetPureMapIndex(vec2(m_Pos.x,m_Pos.y - (28/2)-4)); + //dbg_msg("","N%d L%d R%d B%d T%d",MapIndex,MapIndexL,MapIndexR,MapIndexB,MapIndexT); + m_TileIndex = Collision()->GetTileIndex(MapIndex); + m_TileFlags = Collision()->GetTileFlags(MapIndex); + m_TileIndexL = Collision()->GetTileIndex(MapIndexL); + m_TileFlagsL = Collision()->GetTileFlags(MapIndexL); + m_TileIndexR = Collision()->GetTileIndex(MapIndexR); + m_TileFlagsR = Collision()->GetTileFlags(MapIndexR); + m_TileIndexB = Collision()->GetTileIndex(MapIndexB); + m_TileFlagsB = Collision()->GetTileFlags(MapIndexB); + m_TileIndexT = Collision()->GetTileIndex(MapIndexT); + m_TileFlagsT = Collision()->GetTileFlags(MapIndexT); + m_TileFIndex = Collision()->GetFTileIndex(MapIndex); + m_TileFFlags = Collision()->GetFTileFlags(MapIndex); + m_TileFIndexL = Collision()->GetFTileIndex(MapIndexL); + m_TileFFlagsL = Collision()->GetFTileFlags(MapIndexL); + m_TileFIndexR = Collision()->GetFTileIndex(MapIndexR); + m_TileFFlagsR = Collision()->GetFTileFlags(MapIndexR); + m_TileFIndexB = Collision()->GetFTileIndex(MapIndexB); + m_TileFFlagsB = Collision()->GetFTileFlags(MapIndexB); + m_TileFIndexT = Collision()->GetFTileIndex(MapIndexT); + m_TileFFlagsT = Collision()->GetFTileFlags(MapIndexT); + m_TileSIndex = (UseInput && IsRightTeam(MapIndex))?Collision()->GetDTileIndex(MapIndex):0; + m_TileSFlags = (UseInput && IsRightTeam(MapIndex))?Collision()->GetDTileFlags(MapIndex):0; + m_TileSIndexL = (UseInput && IsRightTeam(MapIndexL))?Collision()->GetDTileIndex(MapIndexL):0; + m_TileSFlagsL = (UseInput && IsRightTeam(MapIndexL))?Collision()->GetDTileFlags(MapIndexL):0; + m_TileSIndexR = (UseInput && IsRightTeam(MapIndexR))?Collision()->GetDTileIndex(MapIndexR):0; + m_TileSFlagsR = (UseInput && IsRightTeam(MapIndexR))?Collision()->GetDTileFlags(MapIndexR):0; + m_TileSIndexB = (UseInput && IsRightTeam(MapIndexB))?Collision()->GetDTileIndex(MapIndexB):0; + m_TileSFlagsB = (UseInput && IsRightTeam(MapIndexB))?Collision()->GetDTileFlags(MapIndexB):0; + m_TileSIndexT = (UseInput && IsRightTeam(MapIndexT))?Collision()->GetDTileIndex(MapIndexT):0; + m_TileSFlagsT = (UseInput && IsRightTeam(MapIndexT))?Collision()->GetDTileFlags(MapIndexT):0; + m_TriggeredEvents = 0; + + vec2 PrevPos = m_Pos; + + // 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[g_Config.m_ClDummy].m_Gravity; + + float MaxSpeed = Grounded ? m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GroundControlSpeed : m_pWorld->m_Tuning[g_Config.m_ClDummy].m_AirControlSpeed; + float Accel = Grounded ? m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GroundControlAccel : m_pWorld->m_Tuning[g_Config.m_ClDummy].m_AirControlAccel; + float Friction = Grounded ? m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GroundFriction : m_pWorld->m_Tuning[g_Config.m_ClDummy].m_AirFriction; + + // handle input + if(UseInput) + { + m_Direction = m_Input.m_Direction; + + // setup angle + float a = 0; + if(m_Input.m_TargetX == 0) + 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 + if(m_Input.m_Jump) + { + if(!(m_Jumped&1)) + { + if(Grounded) + { + m_TriggeredEvents |= COREEVENT_GROUND_JUMP; + m_Vel.y = -m_pWorld->m_Tuning[g_Config.m_ClDummy].m_GroundJumpImpulse; + m_Jumped |= 1; + m_JumpedTotal = 1; + } + else if(!(m_Jumped&2)) + { + m_TriggeredEvents |= COREEVENT_AIR_JUMP; + m_Vel.y = -m_pWorld->m_Tuning[g_Config.m_ClDummy].m_AirJumpImpulse; + m_Jumped |= 3; + m_JumpedTotal++; + } + } + } + else + m_Jumped &= ~1; + + // handle hook + if(m_Input.m_Hook) + { + if(m_HookState == HOOK_IDLE) + { + m_HookState = HOOK_FLYING; + m_HookPos = m_Pos+TargetDirection*PhysSize*1.5f; + m_HookDir = TargetDirection; + m_HookedPlayer = -1; + m_HookTick = SERVER_TICK_SPEED * (1.25f - m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDuration); + m_TriggeredEvents |= COREEVENT_HOOK_LAUNCH; + } + } + else + { + m_HookedPlayer = -1; + m_HookState = HOOK_IDLE; + 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); + if(m_Direction > 0) + 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 (player is holding space bar) + // 2 bit = to keep track if a air-jump has been made (tee gets dark feet) + if(Grounded) + { + m_Jumped &= ~2; + m_JumpedTotal = 0; + } + + // do hook + if(m_HookState == HOOK_IDLE) + { + m_HookedPlayer = -1; + m_HookState = HOOK_IDLE; + m_HookPos = m_Pos; + } + else if(m_HookState >= HOOK_RETRACT_START && m_HookState < HOOK_RETRACT_END) + { + m_HookState++; + } + else if(m_HookState == HOOK_RETRACT_END) + { + m_HookState = HOOK_RETRACTED; + m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + m_HookState = HOOK_RETRACTED; + } + else if(m_HookState == HOOK_FLYING) + { + vec2 NewPos = m_HookPos+m_HookDir*m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookFireSpeed; + if((!m_NewHook && distance(m_Pos, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength) + || (m_NewHook && distance(m_HookTeleBase, NewPos) > m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength)) + { + m_HookState = HOOK_RETRACT_START; + NewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength; + m_pReset = true; + } + + // make sure that the hook doesn't go though the ground + bool GoingToHitGround = false; + bool GoingToRetract = false; + bool GoingThroughTele = false; + int teleNr = 0; + int Hit = m_pCollision->IntersectLineTeleHook(m_HookPos, NewPos, &NewPos, 0, &teleNr, true); + + //m_NewHook = false; + + if(Hit) + { + if(Hit&CCollision::COLFLAG_NOHOOK) + GoingToRetract = true; + else if (Hit&CCollision::COLFLAG_TELE) + GoingThroughTele = true; + else + GoingToHitGround = true; + m_pReset = true; + } + + // Check against other players first + if(this->m_Hook && m_pWorld && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking) + { + float Distance = 0.0f; + for(int i = 0; i < MAX_CLIENTS; i++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; + if(!pCharCore || pCharCore == this || !m_pTeams->CanCollide(i, m_Id)) + continue; + + vec2 ClosestPoint = closest_point_on_line(m_HookPos, NewPos, pCharCore->m_Pos); + if(distance(pCharCore->m_Pos, ClosestPoint) < PhysSize+2.0f) + { + if (m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance) + { + m_TriggeredEvents |= COREEVENT_HOOK_ATTACH_PLAYER; + m_HookState = HOOK_GRABBED; + m_HookedPlayer = i; + Distance = distance(m_HookPos, pCharCore->m_Pos); + } + } + } + } + + if(m_HookState == HOOK_FLYING) + { + // check against ground + if(GoingToHitGround) + { + m_TriggeredEvents |= COREEVENT_HOOK_ATTACH_GROUND; + m_HookState = HOOK_GRABBED; + } + else if(GoingToRetract) + { + m_TriggeredEvents |= COREEVENT_HOOK_HIT_NOHOOK; + m_HookState = HOOK_RETRACT_START; + } + + if(GoingThroughTele && m_pTeleOuts && m_pTeleOuts->size() && (*m_pTeleOuts)[teleNr-1].size()) + { + m_TriggeredEvents = 0; + m_HookedPlayer = -1; + + m_NewHook = true; + int Num = (*m_pTeleOuts)[teleNr-1].size(); + m_HookPos = (*m_pTeleOuts)[teleNr-1][(Num==1)?0:rand() % Num]+TargetDirection*PhysSize*1.5f; + m_HookDir = TargetDirection; + m_HookTeleBase = m_HookPos; + } + else + { + m_HookPos = NewPos; + } + } + } + + if(m_HookState == HOOK_GRABBED) + { + if(m_HookedPlayer != -1) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[m_HookedPlayer]; + if(pCharCore && (IsClient || m_pTeams->CanKeepHook(m_Id, pCharCore->m_Id))) + m_HookPos = pCharCore->m_Pos; + else + { + // release hook + m_HookedPlayer = -1; + m_HookState = HOOK_RETRACTED; + 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) + { + vec2 HookVel = normalize(m_HookPos-m_Pos)*m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel; + // the hook as more power to drag you up then down. + // 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)) + 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[g_Config.m_ClDummy].m_HookDragSpeed || length(NewVel) < length(m_Vel)) + m_Vel = NewVel; // no problem. apply + + } + + // release hook (max default hook time is 1.25 s) + m_HookTick++; + if(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED+SERVER_TICK_SPEED/5 || !m_pWorld->m_apCharacters[m_HookedPlayer])) + { + m_HookedPlayer = -1; + m_HookState = HOOK_RETRACTED; + m_HookPos = m_Pos; + } + } + + if(m_pWorld) + { + for(int i = 0; i < MAX_CLIENTS; i++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; + if(!pCharCore) + continue; + + //player *p = (player*)ent; + //if(pCharCore == this) // || !(p->flags&FLAG_ALIVE) + + if(pCharCore == this || (m_Id != -1 && !m_pTeams->CanCollide(m_Id, i))) + 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); + if(pCharCore->m_Collision && this->m_Collision && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision && Distance < PhysSize*1.25f && Distance > 0.0f) + { + float a = (PhysSize*1.45f - Distance); + float Velocity = 0.5f; + + // make sure that we don't add excess force by checking the + // direction against the current velocity. if not zero. + if (length(m_Vel) > 0.0001) + Velocity = 1-(dot(normalize(m_Vel), Dir)+1)/2; + + m_Vel += Dir*a*(Velocity*0.75f); + m_Vel *= 0.85f; + } + + // handle hook influence + if(m_Hook && m_HookedPlayer == i && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerHooking) + { + if(Distance > PhysSize*1.50f) // TODO: fix tweakable variable + { + float Accel = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragAccel * (Distance/m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookLength); + float DragSpeed = m_pWorld->m_Tuning[g_Config.m_ClDummy].m_HookDragSpeed; + + // add force to the hooked player + vec2 Temp = pCharCore->m_Vel; + Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel*Dir.x*1.5f); + Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel*Dir.y*1.5f); + if(Temp.x > 0 && ((pCharCore->m_TileIndex == TILE_STOP && pCharCore->m_TileFlags == ROTATION_270) || (pCharCore->m_TileIndexL == TILE_STOP && pCharCore->m_TileFlagsL == ROTATION_270) || (pCharCore->m_TileIndexL == TILE_STOPS && (pCharCore->m_TileFlagsL == ROTATION_90 || pCharCore->m_TileFlagsL ==ROTATION_270)) || (pCharCore->m_TileIndexL == TILE_STOPA) || (pCharCore->m_TileFIndex == TILE_STOP && pCharCore->m_TileFFlags == ROTATION_270) || (pCharCore->m_TileFIndexL == TILE_STOP && pCharCore->m_TileFFlagsL == ROTATION_270) || (pCharCore->m_TileFIndexL == TILE_STOPS && (pCharCore->m_TileFFlagsL == ROTATION_90 || pCharCore->m_TileFFlagsL == ROTATION_270)) || (pCharCore->m_TileFIndexL == TILE_STOPA) || (pCharCore->m_TileSIndex == TILE_STOP && pCharCore->m_TileSFlags == ROTATION_270) || (pCharCore->m_TileSIndexL == TILE_STOP && pCharCore->m_TileSFlagsL == ROTATION_270) || (pCharCore->m_TileSIndexL == TILE_STOPS && (pCharCore->m_TileSFlagsL == ROTATION_90 || pCharCore->m_TileSFlagsL == ROTATION_270)) || (pCharCore->m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((pCharCore->m_TileIndex == TILE_STOP && pCharCore->m_TileFlags == ROTATION_90) || (pCharCore->m_TileIndexR == TILE_STOP && pCharCore->m_TileFlagsR == ROTATION_90) || (pCharCore->m_TileIndexR == TILE_STOPS && (pCharCore->m_TileFlagsR == ROTATION_90 || pCharCore->m_TileFlagsR == ROTATION_270)) || (pCharCore->m_TileIndexR == TILE_STOPA) || (pCharCore->m_TileFIndex == TILE_STOP && pCharCore->m_TileFFlags == ROTATION_90) || (pCharCore->m_TileFIndexR == TILE_STOP && pCharCore->m_TileFFlagsR == ROTATION_90) || (pCharCore->m_TileFIndexR == TILE_STOPS && (pCharCore->m_TileFFlagsR == ROTATION_90 || pCharCore->m_TileFFlagsR == ROTATION_270)) || (pCharCore->m_TileFIndexR == TILE_STOPA) || (pCharCore->m_TileSIndex == TILE_STOP && pCharCore->m_TileSFlags == ROTATION_90) || (pCharCore->m_TileSIndexR == TILE_STOP && pCharCore->m_TileSFlagsR == ROTATION_90) || (pCharCore->m_TileSIndexR == TILE_STOPS && (pCharCore->m_TileSFlagsR == ROTATION_90 || pCharCore->m_TileSFlagsR == ROTATION_270)) || (pCharCore->m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((pCharCore->m_TileIndex == TILE_STOP && pCharCore->m_TileFlags == ROTATION_180) || (pCharCore->m_TileIndexB == TILE_STOP && pCharCore->m_TileFlagsB == ROTATION_180) || (pCharCore->m_TileIndexB == TILE_STOPS && (pCharCore->m_TileFlagsB == ROTATION_0 || pCharCore->m_TileFlagsB == ROTATION_180)) || (pCharCore->m_TileIndexB == TILE_STOPA) || (pCharCore->m_TileFIndex == TILE_STOP && pCharCore->m_TileFFlags == ROTATION_180) || (pCharCore->m_TileFIndexB == TILE_STOP && pCharCore->m_TileFFlagsB == ROTATION_180) || (pCharCore->m_TileFIndexB == TILE_STOPS && (pCharCore->m_TileFFlagsB == ROTATION_0 || pCharCore->m_TileFFlagsB == ROTATION_180)) || (pCharCore->m_TileFIndexB == TILE_STOPA) || (pCharCore->m_TileSIndex == TILE_STOP && pCharCore->m_TileSFlags == ROTATION_180) || (pCharCore->m_TileSIndexB == TILE_STOP && pCharCore->m_TileSFlagsB == ROTATION_180) || (pCharCore->m_TileSIndexB == TILE_STOPS && (pCharCore->m_TileSFlagsB == ROTATION_0 || pCharCore->m_TileSFlagsB == ROTATION_180)) || (pCharCore->m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((pCharCore->m_TileIndex == TILE_STOP && pCharCore->m_TileFlags == ROTATION_0) || (pCharCore->m_TileIndexT == TILE_STOP && pCharCore->m_TileFlagsT == ROTATION_0) || (pCharCore->m_TileIndexT == TILE_STOPS && (pCharCore->m_TileFlagsT == ROTATION_0 || pCharCore->m_TileFlagsT == ROTATION_180)) || (pCharCore->m_TileIndexT == TILE_STOPA) || (pCharCore->m_TileFIndex == TILE_STOP && pCharCore->m_TileFFlags == ROTATION_0) || (pCharCore->m_TileFIndexT == TILE_STOP && pCharCore->m_TileFFlagsT == ROTATION_0) || (pCharCore->m_TileFIndexT == TILE_STOPS && (pCharCore->m_TileFFlagsT == ROTATION_0 || pCharCore->m_TileFFlagsT == ROTATION_180)) || (pCharCore->m_TileFIndexT == TILE_STOPA) || (pCharCore->m_TileSIndex == TILE_STOP && pCharCore->m_TileSFlags == ROTATION_0) || (pCharCore->m_TileSIndexT == TILE_STOP && pCharCore->m_TileSFlagsT == ROTATION_0) || (pCharCore->m_TileSIndexT == TILE_STOPS && (pCharCore->m_TileSFlagsT == ROTATION_0 || pCharCore->m_TileSFlagsT == ROTATION_180)) || (pCharCore->m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + + // add a little bit force to the guy who has the grip + pCharCore->m_Vel = Temp; + Temp.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, -Accel*Dir.x*0.25f); + Temp.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, -Accel*Dir.y*0.25f); + if(Temp.x > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + m_Vel = Temp; + } + } + } + + if (m_HookState != HOOK_FLYING) + { + m_NewHook = false; + } + + int Index = MapIndex; + if(g_Config.m_ClPredictDDRace && IsClient && m_pCollision->IsSpeedup(Index)) + { + vec2 Direction, MaxVel, TempVel = m_Vel; + int Force, MaxSpeed = 0; + float TeeAngle, SpeederAngle, DiffAngle, SpeedLeft, TeeSpeed; + m_pCollision->GetSpeedup(Index, &Direction, &Force, &MaxSpeed); + if(Force == 255 && MaxSpeed) + { + m_Vel = Direction * (MaxSpeed/5); + } + else + { + if(MaxSpeed > 0 && MaxSpeed < 5) MaxSpeed = 5; + //dbg_msg("speedup tile start","Direction %f %f, Force %d, Max Speed %d", (Direction).x,(Direction).y, Force, MaxSpeed); + if(MaxSpeed > 0) + { + if(Direction.x > 0.0000001f) + SpeederAngle = -atan(Direction.y / Direction.x); + else if(Direction.x < 0.0000001f) + SpeederAngle = atan(Direction.y / Direction.x) + 2.0f * asin(1.0f); + else if(Direction.y > 0.0000001f) + SpeederAngle = asin(1.0f); + else + SpeederAngle = asin(-1.0f); + + if(SpeederAngle < 0) + SpeederAngle = 4.0f * asin(1.0f) + SpeederAngle; + + if(TempVel.x > 0.0000001f) + TeeAngle = -atan(TempVel.y / TempVel.x); + else if(TempVel.x < 0.0000001f) + TeeAngle = atan(TempVel.y / TempVel.x) + 2.0f * asin(1.0f); + else if(TempVel.y > 0.0000001f) + TeeAngle = asin(1.0f); + else + TeeAngle = asin(-1.0f); + + if(TeeAngle < 0) + TeeAngle = 4.0f * asin(1.0f) + TeeAngle; + + TeeSpeed = sqrt(pow(TempVel.x, 2) + pow(TempVel.y, 2)); + + DiffAngle = SpeederAngle - TeeAngle; + SpeedLeft = MaxSpeed / 5.0f - cos(DiffAngle) * TeeSpeed; + //dbg_msg("speedup tile debug","MaxSpeed %i, TeeSpeed %f, SpeedLeft %f, SpeederAngle %f, TeeAngle %f", MaxSpeed, TeeSpeed, SpeedLeft, SpeederAngle, TeeAngle); + if(abs((int)SpeedLeft) > Force && SpeedLeft > 0.0000001f) + TempVel += Direction * Force; + else if(abs((int)SpeedLeft) > Force) + TempVel += Direction * -Force; + else + TempVel += Direction * SpeedLeft; + } + else + TempVel += Direction * Force; + + + if(TempVel.x > 0 && ((this->m_TileIndex == TILE_STOP && this->m_TileFlags == ROTATION_270) || (this->m_TileIndexL == TILE_STOP && this->m_TileFlagsL == ROTATION_270) || (this->m_TileIndexL == TILE_STOPS && (this->m_TileFlagsL == ROTATION_90 || this->m_TileFlagsL ==ROTATION_270)) || (this->m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA))) + TempVel.x = 0; + if(TempVel.x < 0 && ((this->m_TileIndex == TILE_STOP && this->m_TileFlags == ROTATION_90) || (this->m_TileIndexR == TILE_STOP && this->m_TileFlagsR == ROTATION_90) || (this->m_TileIndexR == TILE_STOPS && (this->m_TileFlagsR == ROTATION_90 || this->m_TileFlagsR == ROTATION_270)) || (this->m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA))) + TempVel.x = 0; + if(TempVel.y < 0 && ((this->m_TileIndex == TILE_STOP && this->m_TileFlags == ROTATION_180) || (this->m_TileIndexB == TILE_STOP && this->m_TileFlagsB == ROTATION_180) || (this->m_TileIndexB == TILE_STOPS && (this->m_TileFlagsB == ROTATION_0 || this->m_TileFlagsB == ROTATION_180)) || (this->m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA))) + TempVel.y = 0; + if(TempVel.y > 0 && ((this->m_TileIndex == TILE_STOP && this->m_TileFlags == ROTATION_0) || (this->m_TileIndexT == TILE_STOP && this->m_TileFlagsT == ROTATION_0) || (this->m_TileIndexT == TILE_STOPS && (this->m_TileFlagsT == ROTATION_0 || this->m_TileFlagsT == ROTATION_180)) || (this->m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA))) + TempVel.y = 0; + + + m_Vel = TempVel; + //dbg_msg("speedup tile end","(Direction*Force) %f %f m_Vel%f %f",(Direction*Force).x,(Direction*Force).y,m_Vel.x,m_Vel.y); + //dbg_msg("speedup tile end","Direction %f %f, Force %d, Max Speed %d", (Direction).x,(Direction).y, Force, MaxSpeed); + } + } + + // jetpack and ninjajetpack prediction + if(IsClient && UseInput && (m_Input.m_Fire&1) && (m_ActiveWeapon == WEAPON_GUN || m_ActiveWeapon == WEAPON_NINJA)) { + m_Vel += TargetDirection * -1.0f * (m_pWorld->m_Tuning[g_Config.m_ClDummy].m_JetpackStrength / 100.0f / 6.11f); + } + + if(g_Config.m_ClPredictDDRace && IsClient) + { + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA)) && m_Vel.x > 0) + { + if((int)m_pCollision->GetPos(MapIndexL).x < (int)m_Pos.x) + m_Pos = PrevPos; + m_Vel.x = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA)) && m_Vel.x < 0) + { + if((int)m_pCollision->GetPos(MapIndexR).x) + if((int)m_pCollision->GetPos(MapIndexR).x < (int)m_Pos.x) + m_Pos = PrevPos; + m_Vel.x = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA)) && m_Vel.y < 0) + { + if((int)m_pCollision->GetPos(MapIndexB).y) + if((int)m_pCollision->GetPos(MapIndexB).y < (int)m_Pos.y) + m_Pos = PrevPos; + m_Vel.y = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA)) && m_Vel.y > 0) + { + if((int)m_pCollision->GetPos(MapIndexT).y) + if((int)m_pCollision->GetPos(MapIndexT).y < (int)m_Pos.y) + m_Pos = PrevPos; + m_Vel.y = 0; + m_Jumped = 0; + m_JumpedTotal = 0; + } + } + } + + // clamp the velocity to something sane + if(length(m_Vel) > 6000) + m_Vel = normalize(m_Vel) * 6000; +} + +void CCharacterCore::Move() +{ + float RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampStart, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampRange, m_pWorld->m_Tuning[g_Config.m_ClDummy].m_VelrampCurvature); + + m_Vel.x = m_Vel.x*RampValue; + + vec2 NewPos = m_Pos; + + vec2 OldVel = m_Vel; + m_pCollision->MoveBox(&NewPos, &m_Vel, vec2(28.0f, 28.0f), 0); + + m_Colliding = 0; + if(m_Vel.x < 0.001 && m_Vel.x > -0.001) + { + if(OldVel.x > 0) + m_Colliding = 1; + else if(OldVel.x < 0) + m_Colliding = 2; + } + else + m_LeftWall = true; + + m_Vel.x = m_Vel.x*(1.0f/RampValue); + + if(m_pWorld && m_pWorld->m_Tuning[g_Config.m_ClDummy].m_PlayerCollision && this->m_Collision) + { + // check player collision + float Distance = distance(m_Pos, NewPos); + int End = Distance+1; + vec2 LastPos = m_Pos; + for(int i = 0; i < End; i++) + { + float a = i/Distance; + vec2 Pos = mix(m_Pos, NewPos, a); + for(int p = 0; p < MAX_CLIENTS; p++) + { + CCharacterCore *pCharCore = m_pWorld->m_apCharacters[p]; + if(!pCharCore || pCharCore == this || !pCharCore->m_Collision || (m_Id != -1 && !m_pTeams->CanCollide(m_Id, p))) + continue; + float D = distance(Pos, pCharCore->m_Pos); + if(D < 28.0f && D > 0.0f) + { + if(a > 0.0f) + m_Pos = LastPos; + else if(distance(NewPos, pCharCore->m_Pos) > D) + m_Pos = NewPos; + return; + } + else if(D <= 0.001f && D >= -0.001f) + { + if(a > 0.0f) + m_Pos = LastPos; + else if(distance(NewPos, pCharCore->m_Pos) > D) + m_Pos = NewPos; + return; + } + } + LastPos = Pos; + } + } + + m_Pos = NewPos; +} + +void CCharacterCore::Write(CNetObj_CharacterCore *pObjCore) +{ + pObjCore->m_X = round_to_int(m_Pos.x); + pObjCore->m_Y = round_to_int(m_Pos.y); + + pObjCore->m_VelX = round_to_int(m_Vel.x*256.0f); + pObjCore->m_VelY = round_to_int(m_Vel.y*256.0f); + pObjCore->m_HookState = m_HookState; + pObjCore->m_HookTick = m_HookTick; + pObjCore->m_HookX = round_to_int(m_HookPos.x); + pObjCore->m_HookY = round_to_int(m_HookPos.y); + pObjCore->m_HookDx = round_to_int(m_HookDir.x*256.0f); + pObjCore->m_HookDy = round_to_int(m_HookDir.y*256.0f); + pObjCore->m_HookedPlayer = m_HookedPlayer; + pObjCore->m_Jumped = m_Jumped; + pObjCore->m_Direction = m_Direction; + pObjCore->m_Angle = m_Angle; +} + +void CCharacterCore::Read(const CNetObj_CharacterCore *pObjCore) +{ + m_Pos.x = pObjCore->m_X; + m_Pos.y = pObjCore->m_Y; + m_Vel.x = pObjCore->m_VelX/256.0f; + m_Vel.y = pObjCore->m_VelY/256.0f; + m_HookState = pObjCore->m_HookState; + m_HookTick = pObjCore->m_HookTick; + m_HookPos.x = pObjCore->m_HookX; + m_HookPos.y = pObjCore->m_HookY; + m_HookDir.x = pObjCore->m_HookDx/256.0f; + m_HookDir.y = pObjCore->m_HookDy/256.0f; + m_HookedPlayer = pObjCore->m_HookedPlayer; + m_Jumped = pObjCore->m_Jumped; + m_Direction = pObjCore->m_Direction; + m_Angle = pObjCore->m_Angle; +} + +void CCharacterCore::Quantize() +{ + CNetObj_CharacterCore Core; + Write(&Core); + Read(&Core); +} + +// DDRace + +bool CCharacterCore::IsRightTeam(int MapIndex) +{ + if(Collision()->m_pSwitchers) + if(m_pTeams->Team(m_Id) != (m_pTeams->m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER)) + return Collision()->m_pSwitchers[Collision()->GetDTileNumber(MapIndex)].m_Status[m_pTeams->Team(m_Id)]; + return false; +} + +void CCharacterCore::LimitForce(vec2 *Force) +{ + vec2 Temp = *Force; + if(Temp.x > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + *Force = Temp; +} + +void CCharacterCore::ApplyForce(vec2 Force) +{ + vec2 Temp = m_Vel + Force; + LimitForce(&Temp); + m_Vel = Temp; +} + +bool UseExtraInfo(const CNetObj_Projectile *pProj) +{ + bool ExtraInfoFlag = ((abs(pProj->m_VelY) & (1<<9)) != 0); + return ExtraInfoFlag; +} + +void ExtractInfo(const CNetObj_Projectile *pProj, vec2 *StartPos, vec2 *StartVel, bool IsDDNet) +{ + if(!UseExtraInfo(pProj) || !IsDDNet) + { + StartPos->x = pProj->m_X; + StartPos->y = pProj->m_Y; + StartVel->x = pProj->m_VelX/100.0f; + StartVel->y = pProj->m_VelY/100.0f; + } + else + { + StartPos->x = pProj->m_X/100.0f; + StartPos->y = pProj->m_Y/100.0f; + float Angle = pProj->m_VelX/1000000.0f; + StartVel->x = sin(-Angle); + StartVel->y = cos(-Angle); + } +} + +void ExtractExtraInfo(const CNetObj_Projectile *pProj, int *Owner, bool *Explosive, int *Bouncing, bool *Freeze) +{ + int Data = pProj->m_VelY; + if(Owner) + { + *Owner = Data & 255; + if((Data>>8) & 1) + *Owner = -(*Owner); + } + if(Bouncing) + *Bouncing = (Data>>10) & 3; + if(Explosive) + *Explosive = (Data>>12) & 1; + if(Freeze) + *Freeze = (Data>>13) & 1; +} + +void SnapshotRemoveExtraInfo(unsigned char *pData) +{ + CSnapshot *pSnap = (CSnapshot*) pData; + for(int Index = 0; Index < pSnap->NumItems(); Index++) + { + CSnapshotItem *pItem = pSnap->GetItem(Index); + if(pItem->Type() == NETOBJTYPE_PROJECTILE) + { + CNetObj_Projectile* pProj = (CNetObj_Projectile*) ((void*)pItem->Data()); + if(UseExtraInfo(pProj)) + { + vec2 Pos; + vec2 Vel; + ExtractInfo(pProj, &Pos, &Vel, 1); + pProj->m_X = Pos.x; + pProj->m_Y = Pos.y; + pProj->m_VelX = (int)(Vel.x*100.0f); + pProj->m_VelY = (int)(Vel.y*100.0f); + } + } + } +} diff --git a/src/game/gamecore.h b/src/game/gamecore.h new file mode 100644 index 0000000..41d9aba --- /dev/null +++ b/src/game/gamecore.h @@ -0,0 +1,304 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_GAMECORE_H +#define GAME_GAMECORE_H + +#include <base/system.h> +#include <base/math.h> + +#include <map> +#include <vector> + +#include <math.h> +#include "collision.h" +#include <engine/shared/protocol.h> +#include <game/generated/protocol.h> + +#include "teamscore.h" +#include "mapitems.h" + + +class CTuneParam +{ + int m_Value; +public: + void Set(int v) { m_Value = v; } + int Get() const { return m_Value; } + CTuneParam &operator = (int v) { m_Value = (int)(v*100.0f); return *this; } + CTuneParam &operator = (float v) { m_Value = (int)(v*100.0f); return *this; } + operator float() const { return m_Value/100.0f; } +}; + +class CTuningParams +{ +public: + CTuningParams() + { + const float TicksPerSecond = 50.0f; + #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) m_##Name.Set((int)(Value*100.0f)); + #include "tuning.h" + #undef MACRO_TUNING_PARAM + } + + static const char *m_apNames[]; + + #define MACRO_TUNING_PARAM(Name,ScriptName,Value,Description) 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); + bool Get(int Index, float *pValue); + bool Get(const char *pName, float *pValue); +}; + + +inline vec2 GetDirection(int Angle) +{ + float a = Angle/256.0f; + return vec2(cosf(a), sinf(a)); +} + +inline vec2 GetDir(float Angle) +{ + return vec2(cosf(Angle), sinf(Angle)); +} + +inline float GetAngle(vec2 Dir) +{ + if(Dir.x == 0 && Dir.y == 0) + return 0.0f; + float a = atanf(Dir.y/Dir.x); + if(Dir.x < 0) + a = a+pi; + return a; +} + +inline void StrToInts(int *pInts, int Num, const char *pStr) +{ + int Index = 0; + while(Num) + { + char aBuf[4] = {0,0,0,0}; + for(int c = 0; c < 4 && pStr[Index]; c++, Index++) + aBuf[c] = pStr[Index]; + *pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128); + pInts++; + Num--; + } + + // null terminate + pInts[-1] &= 0xffffff00; +} + +inline void IntsToStr(const int *pInts, int Num, char *pStr) +{ + while(Num) + { + pStr[0] = (((*pInts)>>24)&0xff)-128; + pStr[1] = (((*pInts)>>16)&0xff)-128; + pStr[2] = (((*pInts)>>8)&0xff)-128; + pStr[3] = ((*pInts)&0xff)-128; + pStr += 4; + pInts++; + Num--; + } + + // null terminate + pStr[-1] = 0; +} + + + +inline vec2 CalcPos(vec2 Pos, vec2 Velocity, float Curvature, float Speed, float Time) +{ + vec2 n; + Time *= Speed; + n.x = Pos.x + Velocity.x*Time; + n.y = Pos.y + Velocity.y*Time + Curvature/10000*(Time*Time); + return n; +} + + +template<typename T> +inline T SaturatedAdd(T Min, T Max, T Current, T Modifier) +{ + if(Modifier < 0) + { + if(Current < Min) + return Current; + Current += Modifier; + if(Current < Min) + Current = Min; + return Current; + } + else + { + if(Current > Max) + return Current; + Current += Modifier; + if(Current > Max) + Current = Max; + return Current; + } +} + + +float VelocityRamp(float Value, float Start, float Range, float Curvature); + +// hooking stuff +enum +{ + HOOK_RETRACTED=-1, + HOOK_IDLE=0, + HOOK_RETRACT_START=1, + HOOK_RETRACT_END=3, + HOOK_FLYING, + HOOK_GRABBED, + + COREEVENT_GROUND_JUMP=0x01, + COREEVENT_AIR_JUMP=0x02, + COREEVENT_HOOK_LAUNCH=0x04, + COREEVENT_HOOK_ATTACH_PLAYER=0x08, + COREEVENT_HOOK_ATTACH_GROUND=0x10, + COREEVENT_HOOK_HIT_NOHOOK=0x20, + COREEVENT_HOOK_RETRACT=0x40, + //COREEVENT_HOOK_TELE=0x80, +}; + +class CWorldCore +{ +public: + CWorldCore() + { + mem_zero(m_apCharacters, sizeof(m_apCharacters)); + } + + CTuningParams m_Tuning[2]; + class CCharacterCore *m_apCharacters[MAX_CLIENTS]; +}; + +class CCharacterCore +{ + friend class CCharacter; + CWorldCore *m_pWorld; + CCollision *m_pCollision; + std::map<int, std::vector<vec2> > *m_pTeleOuts; +public: + vec2 m_Pos; + vec2 m_Vel; + bool m_Hook; + bool m_Collision; + + vec2 m_HookPos; + vec2 m_HookDir; + vec2 m_HookTeleBase; + int m_HookTick; + int m_HookState; + int m_HookedPlayer; + int m_ActiveWeapon; + + bool m_NewHook; + + int m_Jumped; + int m_JumpedTotal; + int m_Jumps; + + int m_Direction; + int m_Angle; + CNetObj_PlayerInput m_Input; + + int m_TriggeredEvents; + + void Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore* pTeams); + void Init(CWorldCore *pWorld, CCollision *pCollision, CTeamsCore* pTeams, std::map<int, std::vector<vec2> > *pTeleOuts); + void Reset(); + void Tick(bool UseInput, bool IsClient); + void Move(); + + void Read(const CNetObj_CharacterCore *pObjCore); + void Write(CNetObj_CharacterCore *pObjCore); + void Quantize(); + + // DDRace + + int m_Id; + bool m_pReset; + class CCollision *Collision() { return m_pCollision; } + + vec2 m_LastVel; + int m_Colliding; + bool m_LeftWall; + + void LimitForce(vec2 *Force); + void ApplyForce(vec2 Force); + +private: + + CTeamsCore* m_pTeams; + int m_TileIndex; + int m_TileFlags; + int m_TileFIndex; + int m_TileFFlags; + int m_TileSIndex; + int m_TileSFlags; + int m_TileIndexL; + int m_TileFlagsL; + int m_TileFIndexL; + int m_TileFFlagsL; + int m_TileSIndexL; + int m_TileSFlagsL; + int m_TileIndexR; + int m_TileFlagsR; + int m_TileFIndexR; + int m_TileFFlagsR; + int m_TileSIndexR; + int m_TileSFlagsR; + int m_TileIndexT; + int m_TileFlagsT; + int m_TileFIndexT; + int m_TileFFlagsT; + int m_TileSIndexT; + int m_TileSFlagsT; + int m_TileIndexB; + int m_TileFlagsB; + int m_TileFIndexB; + int m_TileFFlagsB; + int m_TileSIndexB; + int m_TileSFlagsB; + bool IsRightTeam(int MapIndex); +}; + +//input count +struct CInputCount +{ + int m_Presses; + int m_Releases; +}; + +inline CInputCount CountInput(int Prev, int Cur) +{ + CInputCount c = {0, 0}; + Prev &= INPUT_STATE_MASK; + Cur &= INPUT_STATE_MASK; + int i = Prev; + + while(i != Cur) + { + i = (i+1)&INPUT_STATE_MASK; + if(i&1) + c.m_Presses++; + else + c.m_Releases++; + } + + return c; +} + +bool UseExtraInfo(const CNetObj_Projectile *pProj); +void ExtractInfo(const CNetObj_Projectile *pProj, vec2 *StartPos, vec2 *StartVel, bool IsDDNet); +void ExtractExtraInfo(const CNetObj_Projectile *pProj, int *Owner, bool *Explosive, int *Bouncing, bool *Freeze); +void SnapshotRemoveExtraInfo(unsigned char *pData); + +#endif diff --git a/src/game/layers.cpp b/src/game/layers.cpp new file mode 100644 index 0000000..73f9d96 --- /dev/null +++ b/src/game/layers.cpp @@ -0,0 +1,182 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "layers.h" + +CLayers::CLayers() +{ + m_GroupsNum = 0; + m_GroupsStart = 0; + m_LayersNum = 0; + m_LayersStart = 0; + m_pGameGroup = 0; + m_pGameLayer = 0; + m_pMap = 0; + + m_pTeleLayer = 0; + m_pSpeedupLayer = 0; + m_pFrontLayer = 0; + m_pSwitchLayer = 0; + m_pTuneLayer = 0; +} + +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); + + m_pTeleLayer = 0; + m_pSpeedupLayer = 0; + m_pFrontLayer = 0; + m_pSwitchLayer = 0; + m_pTuneLayer = 0; + + 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); + + if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) + { + m_pGameLayer = pTilemap; + m_pGameGroup = pGroup; + + // make sure the game group has standard settings + m_pGameGroup->m_OffsetX = 0; + 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; + m_pGameGroup->m_ClipX = 0; + m_pGameGroup->m_ClipY = 0; + m_pGameGroup->m_ClipW = 0; + m_pGameGroup->m_ClipH = 0; + } + + //break; + } + if(pTilemap->m_Flags&TILESLAYERFLAG_TELE) + { + if(pTilemap->m_Version <= 2) + { + pTilemap->m_Tele = *((int*)(pTilemap) + 15); + } + m_pTeleLayer = pTilemap; + } + if(pTilemap->m_Flags&TILESLAYERFLAG_SPEEDUP) + { + if(pTilemap->m_Version <= 2) + { + pTilemap->m_Speedup = *((int*)(pTilemap) + 16); + } + m_pSpeedupLayer = pTilemap; + } + if(pTilemap->m_Flags&TILESLAYERFLAG_FRONT) + { + if(pTilemap->m_Version <= 2) + { + pTilemap->m_Front = *((int*)(pTilemap) + 17); + } + m_pFrontLayer = pTilemap; + } + if(pTilemap->m_Flags&TILESLAYERFLAG_SWITCH) + { + if(pTilemap->m_Version <= 2) + { + pTilemap->m_Switch = *((int*)(pTilemap) + 18); + } + m_pSwitchLayer = pTilemap; + } + if(pTilemap->m_Flags&TILESLAYERFLAG_TUNE) + { + if(pTilemap->m_Version <= 2) + { + pTilemap->m_Tune = *((int*)(pTilemap) + 19); + } + m_pTuneLayer = pTilemap; + } + } + } + } +} + +void CLayers::InitBackground(class IMap *pMap) +{ + m_pMap = pMap; + m_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum); + m_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum); + + //following is here to prevent crash using standard map as background + m_pTeleLayer = 0; + m_pSpeedupLayer = 0; + m_pFrontLayer = 0; + m_pSwitchLayer = 0; + m_pTuneLayer = 0; + + 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); + + if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) + { + m_pGameLayer = pTilemap; + m_pGameGroup = pGroup; + + // make sure the game group has standard settings + m_pGameGroup->m_OffsetX = 0; + 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; + m_pGameGroup->m_ClipX = 0; + m_pGameGroup->m_ClipY = 0; + m_pGameGroup->m_ClipW = 0; + m_pGameGroup->m_ClipH = 0; + } + + //We don't care about tile layers. + } + } + } + } +} + +CMapItemGroup *CLayers::GetGroup(int Index) const +{ + return static_cast<CMapItemGroup *>(m_pMap->GetItem(m_GroupsStart+Index, 0, 0)); +} + +CMapItemLayer *CLayers::GetLayer(int Index) const +{ + return static_cast<CMapItemLayer *>(m_pMap->GetItem(m_LayersStart+Index, 0, 0)); +} + +// DDRace + +void CLayers::Dest() +{ + /*m_pTeleLayer = 0; + m_pSpeedupLayer = 0; + m_pFrontLayer = 0; + m_pSwitchLayer = 0; + m_pTuneLayer = 0;*/ +} diff --git a/src/game/layers.h b/src/game/layers.h new file mode 100644 index 0000000..0c317be --- /dev/null +++ b/src/game/layers.h @@ -0,0 +1,48 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_LAYERS_H +#define GAME_LAYERS_H + +#include <engine/map.h> +#include <game/mapitems.h> + +class CLayers +{ + int m_GroupsNum; + int m_GroupsStart; + int m_LayersNum; + int m_LayersStart; + CMapItemGroup *m_pGameGroup; + CMapItemLayerTilemap *m_pGameLayer; + class IMap *m_pMap; + +public: + CLayers(); + void Init(class IKernel *pKernel); + void InitBackground(class IMap *pMap); + int NumGroups() const { return m_GroupsNum; }; + class IMap *Map() const { return m_pMap; }; + CMapItemGroup *GameGroup() const { return m_pGameGroup; }; + CMapItemLayerTilemap *GameLayer() const { return m_pGameLayer; }; + CMapItemGroup *GetGroup(int Index) const; + CMapItemLayer *GetLayer(int Index) const; + + // DDRace + + void Dest(); + CMapItemLayerTilemap *TeleLayer() const { return m_pTeleLayer; }; + CMapItemLayerTilemap *SpeedupLayer() const { return m_pSpeedupLayer; }; + CMapItemLayerTilemap *FrontLayer() const { return m_pFrontLayer; }; + CMapItemLayerTilemap *SwitchLayer() const { return m_pSwitchLayer; }; + CMapItemLayerTilemap *TuneLayer() const { return m_pTuneLayer; }; + +private: + + CMapItemLayerTilemap *m_pTeleLayer; + CMapItemLayerTilemap *m_pSpeedupLayer; + CMapItemLayerTilemap *m_pFrontLayer; + CMapItemLayerTilemap *m_pSwitchLayer; + CMapItemLayerTilemap *m_pTuneLayer; +}; + +#endif diff --git a/src/game/localization.cpp b/src/game/localization.cpp new file mode 100644 index 0000000..8ab8831 --- /dev/null +++ b/src/game/localization.cpp @@ -0,0 +1,112 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "localization.h" +#include <base/tl/algorithm.h> + +#include <engine/shared/linereader.h> +#include <engine/console.h> +#include <engine/storage.h> + +const char *Localize(const char *pStr) +{ + const char *pNewStr = g_Localization.FindString(str_quickhash(pStr)); + return pNewStr ? pNewStr : pStr; +} + +CLocConstString::CLocConstString(const char *pStr) +{ + m_pDefaultStr = pStr; + m_Hash = str_quickhash(m_pDefaultStr); + m_Version = -1; +} + +void CLocConstString::Reload() +{ + m_Version = g_Localization.Version(); + const char *pNewStr = g_Localization.FindString(m_Hash); + m_pCurrentStr = pNewStr; + if(!m_pCurrentStr) + m_pCurrentStr = m_pDefaultStr; +} + +CLocalizationDatabase::CLocalizationDatabase() +{ + m_VersionCounter = 0; + m_CurrentVersion = 0; +} + +void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr) +{ + CString s; + s.m_Hash = str_quickhash(pOrgStr); + s.m_Replacement = *pNewStr ? pNewStr : pOrgStr; + m_Strings.add(s); +} + +bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole) +{ + // empty string means unload + if(pFilename[0] == 0) + { + m_Strings.clear(); + 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); + char *pLine; + while((pLine = LineReader.Get())) + { + if(!str_length(pLine)) + continue; + + if(pLine[0] == '#') // skip comments + continue; + + str_copy(aOrigin, pLine, sizeof(aOrigin)); + char *pReplacement = LineReader.Get(); + if(!pReplacement) + { + 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); + pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); + continue; + } + + pReplacement += 3; + AddString(aOrigin, pReplacement); + } + io_close(IoHandle); + + m_CurrentVersion = ++m_VersionCounter; + return true; +} + +const char *CLocalizationDatabase::FindString(unsigned Hash) +{ + CString String; + String.m_Hash = Hash; + sorted_array<CString>::range r = ::find_binary(m_Strings.all(), String); + if(r.empty()) + return 0; + return r.front().m_Replacement; +} + +CLocalizationDatabase g_Localization; diff --git a/src/game/localization.h b/src/game/localization.h new file mode 100644 index 0000000..49edd86 --- /dev/null +++ b/src/game/localization.h @@ -0,0 +1,60 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_LOCALIZATION_H +#define GAME_LOCALIZATION_H +#include <base/tl/string.h> +#include <base/tl/sorted_array.h> + +class CLocalizationDatabase +{ + class CString + { + public: + unsigned m_Hash; + + // TODO: do this as an const char * and put everything on a incremental heap + string m_Replacement; + + bool operator <(const CString &Other) const { return m_Hash < Other.m_Hash; } + bool operator <=(const CString &Other) const { return m_Hash <= Other.m_Hash; } + bool operator ==(const CString &Other) const { return m_Hash == Other.m_Hash; } + }; + + 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); +}; + +extern CLocalizationDatabase g_Localization; + +class CLocConstString +{ + const char *m_pDefaultStr; + const char *m_pCurrentStr; + unsigned m_Hash; + int m_Version; +public: + CLocConstString(const char *pStr); + void Reload(); + + inline operator const char *() + { + if(m_Version != g_Localization.Version()) + Reload(); + return m_pCurrentStr; + } +}; + + +extern const char *Localize(const char *pStr); +#endif diff --git a/src/game/mapitems.h b/src/game/mapitems.h new file mode 100644 index 0000000..29791c0 --- /dev/null +++ b/src/game/mapitems.h @@ -0,0 +1,462 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_MAPITEMS_H +#define GAME_MAPITEMS_H + +#include <engine/shared/protocol.h> + +// layer types +enum +{ + // TODO(Shereef Marzouk): fix this for vanilla, make use of LAYERTYPE_GAME instead of using m_game variable in the editor. + LAYERTYPE_INVALID=0, + LAYERTYPE_GAME, + LAYERTYPE_TILES, + LAYERTYPE_QUADS, + LAYERTYPE_FRONT, + LAYERTYPE_TELE, + LAYERTYPE_SPEEDUP, + LAYERTYPE_SWITCH, + LAYERTYPE_TUNE, + LAYERTYPE_SOUNDS_DEPRECATED, // deprecated! do not use this, this is just for compatibility reasons + LAYERTYPE_SOUNDS, + + MAPITEMTYPE_VERSION=0, + MAPITEMTYPE_INFO, + MAPITEMTYPE_IMAGE, + MAPITEMTYPE_ENVELOPE, + MAPITEMTYPE_GROUP, + MAPITEMTYPE_LAYER, + MAPITEMTYPE_ENVPOINTS, + MAPITEMTYPE_SOUND, + + + CURVETYPE_STEP=0, + CURVETYPE_LINEAR, + CURVETYPE_SLOW, + CURVETYPE_FAST, + CURVETYPE_SMOOTH, + NUM_CURVETYPES, + + // game layer tiles + // TODO define which Layer uses which tiles (needed for mapeditor) + ENTITY_NULL=0, + ENTITY_SPAWN, + ENTITY_SPAWN_RED, + ENTITY_SPAWN_BLUE, + ENTITY_FLAGSTAND_RED, + ENTITY_FLAGSTAND_BLUE, + ENTITY_ARMOR_1, + ENTITY_HEALTH_1, + ENTITY_WEAPON_SHOTGUN, + ENTITY_WEAPON_GRENADE, + ENTITY_POWERUP_NINJA, + ENTITY_WEAPON_RIFLE, + //DDRace - Main Lasers + ENTITY_LASER_FAST_CW, + ENTITY_LASER_NORMAL_CW, + ENTITY_LASER_SLOW_CW, + ENTITY_LASER_STOP, + ENTITY_LASER_SLOW_CCW, + ENTITY_LASER_NORMAL_CCW, + ENTITY_LASER_FAST_CCW, + //DDRace - Laser Modifiers + ENTITY_LASER_SHORT, + ENTITY_LASER_MEDIUM, + ENTITY_LASER_LONG, + ENTITY_LASER_C_SLOW, + ENTITY_LASER_C_NORMAL, + ENTITY_LASER_C_FAST, + ENTITY_LASER_O_SLOW, + ENTITY_LASER_O_NORMAL, + ENTITY_LASER_O_FAST, + //DDRace - Plasma + ENTITY_PLASMAE=29, + ENTITY_PLASMAF, + ENTITY_PLASMA, + ENTITY_PLASMAU, + //DDRace - Shotgun + ENTITY_CRAZY_SHOTGUN_EX, + ENTITY_CRAZY_SHOTGUN, + //DDRace - Draggers + ENTITY_DRAGGER_WEAK=42, + ENTITY_DRAGGER_NORMAL, + ENTITY_DRAGGER_STRONG, + //Draggers Behind Walls + ENTITY_DRAGGER_WEAK_NW, + ENTITY_DRAGGER_NORMAL_NW, + ENTITY_DRAGGER_STRONG_NW, + //Doors + ENTITY_DOOR=49, + //End Of Lower Tiles + NUM_ENTITIES, + //Start From Top Left + //Tile Controllers + TILE_AIR=0, + TILE_SOLID, + TILE_DEATH, + TILE_NOHOOK, + TILE_NOLASER, + TILE_THROUGH = 6, + TILE_JUMP, + TILE_FREEZE = 9, + TILE_TELEINEVIL, + TILE_UNFREEZE, + TILE_DFREEZE, + TILE_DUNFREEZE, + TILE_TELEINWEAPON, + TILE_TELEINHOOK, + TILE_WALLJUMP = 16, + TILE_EHOOK_START, + TILE_EHOOK_END, + TILE_HIT_START, + TILE_HIT_END, + TILE_SOLO_START, + TILE_SOLO_END, + //Switches + TILE_SWITCHTIMEDOPEN = 22, + TILE_SWITCHTIMEDCLOSE, + TILE_SWITCHOPEN, + TILE_SWITCHCLOSE, + TILE_TELEIN, + TILE_TELEOUT, + TILE_BOOST, + TILE_TELECHECK, + TILE_TELECHECKOUT, + TILE_TELECHECKIN, + TILE_REFILL_JUMPS = 32, + TILE_BEGIN, + TILE_END, + TILE_STOP = 60, + TILE_STOPS, + TILE_STOPA, + TILE_TELECHECKINEVIL = 63, + TILE_CP = 64, + TILE_CP_F, + TILE_TUNE1 = 68, + TILE_OLDLASER = 71, + TILE_NPC, + TILE_EHOOK, + TILE_NOHIT, + TILE_NPH, + TILE_UNLOCK_TEAM, + TILE_PENALTY = 79, + TILE_NPC_END = 88, + TILE_SUPER_END, + TILE_JETPACK_END, + TILE_NPH_END, + TILE_BONUS = 95, + TILE_NPC_START = 104, + TILE_SUPER_START, + TILE_JETPACK_START, + TILE_NPH_START, + + TILE_WARIOWARE_REDTILE = 185, + TILE_WARIOWARE_GREENTILE, + TILE_WARIOWARE_BLUETILE, + TILE_WARIOWARE_YELLOWTILE, + TILE_WARIOWARE_WIN, + + TILE_MAX_ENTITIES, + + //End of higher tiles + //Layers + LAYER_GAME=0, + LAYER_FRONT, + LAYER_TELE, + LAYER_SPEEDUP, + LAYER_SWITCH, + LAYER_TUNE, + NUM_LAYERS, + //Flags + TILEFLAG_VFLIP=1, + TILEFLAG_HFLIP=2, + TILEFLAG_OPAQUE=4, + TILEFLAG_ROTATE=8, + //Rotation + ROTATION_0 = 0, + ROTATION_90 = TILEFLAG_ROTATE, + ROTATION_180 = (TILEFLAG_VFLIP|TILEFLAG_HFLIP), + ROTATION_270 = (TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE), + + LAYERFLAG_DETAIL=1, + TILESLAYERFLAG_GAME=1, + TILESLAYERFLAG_TELE=2, + TILESLAYERFLAG_SPEEDUP=4, + TILESLAYERFLAG_FRONT=8, + TILESLAYERFLAG_SWITCH=16, + TILESLAYERFLAG_TUNE=32, + + ENTITY_OFFSET=255-16*4, +}; + +struct CPoint +{ + int x, y; // 22.10 fixed point +}; + +struct CColor +{ + int r, g, b, a; +}; + +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; +}; + +class CTile +{ +public: + unsigned char m_Index; + unsigned char m_Flags; + unsigned char m_Skip; + unsigned char m_Reserved; +}; + +struct CMapItemInfo +{ + int m_Version; + int m_Author; + int m_MapVersion; + int m_Credits; + int m_License; +} ; + +struct CMapItemInfoSettings : CMapItemInfo +{ + int m_Settings; +} ; + +struct CMapItemImage +{ + int m_Version; + int m_Width; + int m_Height; + int m_External; + int m_ImageName; + int m_ImageData; +} ; + +struct CMapItemGroup_v1 +{ + int m_Version; + int m_OffsetX; + int m_OffsetY; + int m_ParallaxX; + int m_ParallaxY; + + int m_StartLayer; + int m_NumLayers; +} ; + + +struct CMapItemGroup : public CMapItemGroup_v1 +{ + enum { CURRENT_VERSION=3 }; + + int m_UseClipping; + int m_ClipX; + int m_ClipY; + int m_ClipW; + int m_ClipH; + + int m_aName[3]; +} ; + +struct CMapItemLayer +{ + int m_Version; + int m_Type; + int m_Flags; +} ; + +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; + + int m_aName[3]; + + // DDRace + + int m_Tele; + int m_Speedup; + int m_Front; + int m_Switch; + int m_Tune; +} ; + +struct CMapItemLayerQuads +{ + CMapItemLayer m_Layer; + int m_Version; + + int m_NumQuads; + int m_Data; + int m_Image; + + int m_aName[3]; +} ; + +struct CMapItemVersion +{ + int m_Version; +} ; + +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; } +} ; + +struct CMapItemEnvelope_v1 +{ + int m_Version; + int m_Channels; + int m_StartPoint; + int m_NumPoints; + int m_aName[8]; +} ; + +struct CMapItemEnvelope : public CMapItemEnvelope_v1 +{ + enum { CURRENT_VERSION=2 }; + int m_Synchronized; +}; + +struct CSoundShape +{ + enum + { + SHAPE_RECTANGLE = 0, + SHAPE_CIRCLE, + NUM_SHAPES, + }; + + struct CRectangle + { + int m_Width, m_Height; // fxp 22.10 + }; + + struct CCircle + { + int m_Radius; + }; + + int m_Type; + + union + { + CRectangle m_Rectangle; + CCircle m_Circle; + }; +}; + +struct CSoundSource +{ + CPoint m_Position; + int m_Loop; + int m_Pan; // 0 - no panning, 1 - panning + int m_TimeDelay; // in s + int m_Falloff; // [0,255] // 0 - No falloff, 255 - full + + int m_PosEnv; + int m_PosEnvOffset; + int m_SoundEnv; + int m_SoundEnvOffset; + + CSoundShape m_Shape; +}; + +struct CMapItemLayerSounds +{ + enum { CURRENT_VERSION=2 }; + + CMapItemLayer m_Layer; + int m_Version; + + int m_NumSources; + int m_Data; + int m_Sound; + + int m_aName[3]; +}; + +struct CMapItemSound +{ + int m_Version; + + int m_External; + + int m_SoundName; + int m_SoundData; + int m_SoundDataSize; +} ; + + +// DDRace + +class CTeleTile +{ +public: + unsigned char m_Number; + unsigned char m_Type; +}; + +class CSpeedupTile +{ +public: + unsigned char m_Force; + unsigned char m_MaxSpeed; + unsigned char m_Type; + short m_Angle; +}; + +class CSwitchTile +{ +public: + unsigned char m_Number; + unsigned char m_Type; + unsigned char m_Flags; + unsigned char m_Delay; +}; + +class CDoorTile +{ +public: + unsigned char m_Index; + unsigned char m_Flags; + int m_Number; +}; + +class CTuneTile +{ +public: + unsigned char m_Number; + unsigned char m_Type; +}; + +#endif diff --git a/src/game/server/ddracechat.cpp b/src/game/server/ddracechat.cpp new file mode 100644 index 0000000..184c619 --- /dev/null +++ b/src/game/server/ddracechat.cpp @@ -0,0 +1,1292 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "gamecontext.h" +#include <engine/shared/config.h> +#include <engine/shared/protocol.h> +#include <engine/server/server.h> +#include <game/server/teams.h> +#include <game/server/gamemodes/DDRace.h> +#include <game/version.h> +#include <game/generated/nethash.cpp> +#if defined(CONF_SQL) +#include <game/server/score/sql_score.h> +#endif + +bool CheckClientID(int ClientID); + +void CGameContext::ConCredits(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "DDRaceNetwork is maintained by deen."); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "Many ideas from the great community,"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "Help and code by eeeee, HMH, east, CookieMichal, Learath2,"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "Savander, laxa, Tobii, BeaR, Wohoo, nuborn, DoNe, Shiki,"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "trml, Soreu, hi_leute_gll, Lady Saavik, Chairn, heinrich5991 &"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "others."); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "Based on DDRace by the DDRace developers,"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "which is a mod of Teeworlds by the Teeworlds developers."); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "credit", + "Check the changes on ddnet.tw"); +} + +void CGameContext::ConInfo(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "DDraceNetwork Mod. Version: " GAME_VERSION); +#if defined( GIT_SHORTREV_HASH ) + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "Git revision hash: " GIT_SHORTREV_HASH); +#endif + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "Official site: ddnet.tw"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "For more Info /cmdlist"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "Or visit ddnet.tw"); +} + +void CGameContext::ConHelp(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + + if (pResult->NumArguments() == 0) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", + "/cmdlist will show a list of all chat commands"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", + "/help + any command will show you the help for this command"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", + "Example /help settings will display the help about "); + } + else + { + const char *pArg = pResult->GetString(0); + const IConsole::CCommandInfo *pCmdInfo = + pSelf->Console()->GetCommandInfo(pArg, CFGFLAG_SERVER, false); + if (pCmdInfo) + { + if (pCmdInfo->m_pParams) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Usage: %s %s", pCmdInfo->m_pName, pCmdInfo->m_pParams); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", aBuf); + } + + if (pCmdInfo->m_pHelp) + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "help", pCmdInfo->m_pHelp); + } + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "help", + "Command is either unknown or you have given a blank command without any parameters."); + } +} + +void CGameContext::ConSettings(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + + if (pResult->NumArguments() == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "setting", + "to check a server setting say /settings and setting's name, setting names are:"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "setting", + "teams, cheats, collision, hooking, endlesshooking, me, "); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "setting", + "hitting, oldlaser, timeout, votes, pause and scores"); + } + else + { + const char *pArg = pResult->GetString(0); + char aBuf[256]; + float ColTemp; + float HookTemp; + pSelf->m_Tuning.Get("player_collision", &ColTemp); + pSelf->m_Tuning.Get("player_hooking", &HookTemp); + if (str_comp(pArg, "teams") == 0) + { + str_format( + aBuf, + sizeof(aBuf), + "%s %s", + g_Config.m_SvTeam == 1 ? + "Teams are available on this server" : + (g_Config.m_SvTeam == 0 || g_Config.m_SvTeam == 3) ? + "Teams are not available on this server" : + "You have to be in a team to play on this server", /*g_Config.m_SvTeamStrict ? "and if you die in a team all of you die" : */ + "and if you die in a team only you die"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", + aBuf); + } + else if (str_comp(pArg, "collision") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + ColTemp ? + "Players can collide on this server" : + "Players Can't collide on this server"); + } + else if (str_comp(pArg, "hooking") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + HookTemp ? + "Players can hook each other on this server" : + "Players Can't hook each other on this server"); + } + else if (str_comp(pArg, "endlesshooking") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvEndlessDrag ? + "Players can hook time is unlimited" : + "Players can hook time is limited"); + } + else if (str_comp(pArg, "hitting") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvHit ? + "Player's weapons affect each other" : + "Player's weapons has no affect on each other"); + } + else if (str_comp(pArg, "oldlaser") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvOldLaser ? + "Lasers can hit you if you shot them and that they pull you towards the bounce origin (Like DDRace Beta)" : + "Lasers can't hit you if you shot them, and they pull others towards the shooter"); + } + else if (str_comp(pArg, "me") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvSlashMe ? + "Players can use /me commands the famous IRC Command" : + "Players Can't use the /me command"); + } + else if (str_comp(pArg, "timeout") == 0) + { + str_format(aBuf, sizeof(aBuf), + "The Server Timeout is currently set to %d seconds", + g_Config.m_ConnTimeout); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "settings", + aBuf); + } + else if (str_comp(pArg, "votes") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvVoteKick ? + "Players can use Callvote menu tab to kick offenders" : + "Players Can't use the Callvote menu tab to kick offenders"); + if (g_Config.m_SvVoteKick) + str_format( + aBuf, + sizeof(aBuf), + "Players are banned for %d second(s) if they get voted off", + g_Config.m_SvVoteKickBantime); + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvVoteKickBantime ? + aBuf : + "Players are just kicked and not banned if they get voted off"); + } + else if (str_comp(pArg, "pause") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvPauseable ? + g_Config.m_SvPauseTime ? + "/pause is available on this server and it pauses your time too" : + "/pause is available on this server but it doesn't pause your time" + :"/pause is NOT available on this server"); + } + else if (str_comp(pArg, "scores") == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "settings", + g_Config.m_SvHideScore ? + "Scores are private on this server" : + "Scores are public on this server"); + } + } +} + +void CGameContext::ConRules(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + bool Printed = false; + if (g_Config.m_SvDDRaceRules) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + "Be nice."); + Printed = true; + } + if (g_Config.m_SvRulesLine1[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine1); + Printed = true; + } + if (g_Config.m_SvRulesLine2[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine2); + Printed = true; + } + if (g_Config.m_SvRulesLine3[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine3); + Printed = true; + } + if (g_Config.m_SvRulesLine4[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine4); + Printed = true; + } + if (g_Config.m_SvRulesLine5[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine5); + Printed = true; + } + if (g_Config.m_SvRulesLine6[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine6); + Printed = true; + } + if (g_Config.m_SvRulesLine7[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine7); + Printed = true; + } + if (g_Config.m_SvRulesLine8[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine8); + Printed = true; + } + if (g_Config.m_SvRulesLine9[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine9); + Printed = true; + } + if (g_Config.m_SvRulesLine10[0]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + g_Config.m_SvRulesLine10); + Printed = true; + } + if (!Printed) + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "rules", + "No Rules Defined, Kill em all!!"); +} + +void CGameContext::ConToggleSpec(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + char aBuf[128]; + + if(!g_Config.m_SvPauseable) + { + ConTogglePause(pResult, pUserData); + return; + } + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + if (pPlayer->GetCharacter() == 0) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "spec", + "You can't spec while you are dead/a spectator."); + return; + } + if (pPlayer->m_Paused == CPlayer::PAUSED_SPEC && g_Config.m_SvPauseable) + { + ConTogglePause(pResult, pUserData); + return; + } + + if (pPlayer->m_Paused == CPlayer::PAUSED_FORCE) + { + str_format(aBuf, sizeof(aBuf), "You are force-specced. %ds left.", pPlayer->m_ForcePauseTime/pSelf->Server()->TickSpeed()); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "spec", aBuf); + return; + } + + pPlayer->m_Paused = (pPlayer->m_Paused == CPlayer::PAUSED_PAUSED) ? CPlayer::PAUSED_NONE : CPlayer::PAUSED_PAUSED; +} + +void CGameContext::ConTogglePause(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; + char aBuf[128]; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if(!pPlayer) + return; + + if (pPlayer->GetCharacter() == 0) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "pause", + "You can't pause while you are dead/a spectator."); + return; + } + + if(pPlayer->m_Paused == CPlayer::PAUSED_FORCE) + { + str_format(aBuf, sizeof(aBuf), "You are force-paused. %ds left.", pPlayer->m_ForcePauseTime/pSelf->Server()->TickSpeed()); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "pause", aBuf); + return; + } + + pPlayer->m_Paused = (pPlayer->m_Paused == CPlayer::PAUSED_SPEC) ? CPlayer::PAUSED_NONE : CPlayer::PAUSED_SPEC; +} + +void CGameContext::ConTeamTop5(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + if(pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (g_Config.m_SvHideScore) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "teamtop5", + "Showing the team top 5 is not allowed on this server."); + return; + } + + if (pResult->NumArguments() > 0 && pResult->GetInteger(0) >= 0) + pSelf->Score()->ShowTeamTop5(pResult, pResult->m_ClientID, pUserData, + pResult->GetInteger(0)); + else + pSelf->Score()->ShowTeamTop5(pResult, pResult->m_ClientID, pUserData); + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConTop5(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + if(pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (g_Config.m_SvHideScore) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "top5", + "Showing the top 5 is not allowed on this server."); + return; + } + + if (pResult->NumArguments() > 0 && pResult->GetInteger(0) >= 0) + pSelf->Score()->ShowTop5(pResult, pResult->m_ClientID, pUserData, + pResult->GetInteger(0)); + else + pSelf->Score()->ShowTop5(pResult, pResult->m_ClientID, pUserData); + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +#if defined(CONF_SQL) +void CGameContext::ConTimes(IConsole::IResult *pResult, void *pUserData) +{ + if(!CheckClientID(pResult->m_ClientID)) return; + CGameContext *pSelf = (CGameContext *)pUserData; + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + if(pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if(g_Config.m_SvUseSQL) + { + CSqlScore *pScore = (CSqlScore *)pSelf->Score(); + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if(!pPlayer) + return; + + if(pResult->NumArguments() == 0) + { + pScore->ShowTimes(pPlayer->GetCID(),1); + return; + } + + else if(pResult->NumArguments() < 3) + { + if (pResult->NumArguments() == 1) + { + if(pResult->GetInteger(0) != 0) + pScore->ShowTimes(pPlayer->GetCID(),pResult->GetInteger(0)); + else + pScore->ShowTimes(pPlayer->GetCID(), (str_comp(pResult->GetString(0), "me") == 0) ? pSelf->Server()->ClientName(pResult->m_ClientID) : pResult->GetString(0),1); + return; + } + else if (pResult->GetInteger(1) != 0) + { + pScore->ShowTimes(pPlayer->GetCID(), (str_comp(pResult->GetString(0), "me") == 0) ? pSelf->Server()->ClientName(pResult->m_ClientID) : pResult->GetString(0),pResult->GetInteger(1)); + return; + } + } + + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "times", "/times needs 0, 1 or 2 parameter. 1. = name, 2. = start number"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "times", "Example: /times, /times me, /times Hans, /times \"Papa Smurf\" 5"); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "times", "Bad: /times Papa Smurf 5 # Good: /times \"Papa Smurf\" 5 "); + +#if defined(CONF_SQL) + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif + } +} +#endif + +void CGameContext::ConDND(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if(!CheckClientID(pResult->m_ClientID)) return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if(!pPlayer) + return; + + if(pPlayer->m_DND) + { + pPlayer->m_DND = false; + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "dnd", "You will receive global chat and server messages"); + } + else + { + pPlayer->m_DND = true; + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "dnd", "You will not receive any further global chat and server messages"); + } +} + +void CGameContext::ConMap(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + if (g_Config.m_SvMapVote == 0) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "map", + "Admin has disabled /map"); + return; + } + + if (pResult->NumArguments() <= 0) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "map", "Example: /map adr3 to call vote for Adrenaline 3. This means that the map name must start with 'a' and contain the characters 'd', 'r' and '3' in that order"); + return; + } + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + pSelf->Score()->MapVote(pResult->m_ClientID, pResult->GetString(0)); + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConMapInfo(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (pResult->NumArguments() > 0) + pSelf->Score()->MapInfo(pResult->m_ClientID, pResult->GetString(0)); + else + pSelf->Score()->MapInfo(pResult->m_ClientID, g_Config.m_SvMap); + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConTimeout(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + for(int i = 0; i < pSelf->Server()->MaxClients(); i++) + { + if (i == pResult->m_ClientID) continue; + if (!pSelf->m_apPlayers[i]) continue; + if (str_comp(pSelf->m_apPlayers[i]->m_TimeoutCode, pResult->GetString(0))) continue; + if (((CServer *)pSelf->Server())->m_NetServer.SetTimedOut(i, pResult->m_ClientID)) + { + ((CServer *)pSelf->Server())->DelClientCallback(pResult->m_ClientID, "Timeout Protection used", ((CServer *)pSelf->Server())); + ((CServer *)pSelf->Server())->m_aClients[i].m_Authed = CServer::AUTHED_NO; + if (pSelf->m_apPlayers[i]->GetCharacter()) + ((CGameContext *)(((CServer *)pSelf->Server())->GameServer()))->SendTuningParams(i, pSelf->m_apPlayers[i]->GetCharacter()->m_TuneZone); + return; + } + } + + ((CServer *)pSelf->Server())->m_NetServer.SetTimeoutProtected(pResult->m_ClientID); + str_copy(pPlayer->m_TimeoutCode, pResult->GetString(0), sizeof(pPlayer->m_TimeoutCode)); +} + +void CGameContext::ConSave(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(!g_Config.m_SvSaveGames) + { + pSelf->SendChatTarget(pResult->m_ClientID, "Save-function is disabled on this server"); + return; + } + + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; + + int Team = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); + + const char* pCode = pResult->GetString(0); + char aCountry[5]; + if(str_length(pCode) > 3 && pCode[0] >= 'A' && pCode[0] <= 'Z' && pCode[1] >= 'A' + && pCode[1] <= 'Z' && pCode[2] >= 'A' && pCode[2] <= 'Z') + { + if(pCode[3] == ' ') + { + str_copy(aCountry, pCode, 4); + pCode = pCode + 4; + } + else if(str_length(pCode) > 4 && pCode[4] == ' ') + { + str_copy(aCountry, pCode, 5); + pCode = pCode + 5; + } + else + { + str_copy(aCountry, g_Config.m_SvSqlServerName, sizeof(aCountry)); + } + } + else + { + str_copy(aCountry, g_Config.m_SvSqlServerName, sizeof(aCountry)); + } + + pSelf->Score()->SaveTeam(Team, pCode, pResult->m_ClientID, aCountry); + + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConLoad(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(!g_Config.m_SvSaveGames) + { + pSelf->SendChatTarget(pResult->m_ClientID, "Save-function is disabled on this server"); + return; + } + + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (pResult->NumArguments() > 0) + pSelf->Score()->LoadTeam(pResult->GetString(0), pResult->m_ClientID); + else + return; + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConTeamRank(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (pResult->NumArguments() > 0) + if (!g_Config.m_SvHideScore) + pSelf->Score()->ShowTeamRank(pResult->m_ClientID, pResult->GetString(0), + true); + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "teamrank", + "Showing the team rank of other players is not allowed on this server."); + else + pSelf->Score()->ShowTeamRank(pResult->m_ClientID, + pSelf->Server()->ClientName(pResult->m_ClientID)); + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConRank(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + if(pPlayer->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; +#endif + + if (pResult->NumArguments() > 0) + if (!g_Config.m_SvHideScore) + pSelf->Score()->ShowRank(pResult->m_ClientID, pResult->GetString(0), + true); + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "rank", + "Showing the rank of other players is not allowed on this server."); + else + pSelf->Score()->ShowRank(pResult->m_ClientID, + pSelf->Server()->ClientName(pResult->m_ClientID)); + +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + pPlayer->m_LastSQLQuery = pSelf->Server()->Tick(); +#endif +} + +void CGameContext::ConLockTeam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + int Team = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(pResult->m_ClientID); + + bool Lock = ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.TeamLocked(Team); + + if (pResult->NumArguments() > 0) + Lock = !pResult->GetInteger(0); + + if(Team > TEAM_FLOCK && Team < TEAM_SUPER) + { + char aBuf[512]; + if(Lock) + { + ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.SetTeamLock(Team, false); + + str_format(aBuf, sizeof(aBuf), "'%s' unlocked your team.", pSelf->Server()->ClientName(pResult->m_ClientID)); + + for (int i = 0; i < MAX_CLIENTS; i++) + if (((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) + pSelf->SendChatTarget(i, aBuf); + } + else if(!g_Config.m_SvTeamLock) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "Team locking is disabled on this server"); + } + else + { + ((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.SetTeamLock(Team, true); + + str_format(aBuf, sizeof(aBuf), "'%s' locked your team. After the race started killing will kill everyone in your team.", pSelf->Server()->ClientName(pResult->m_ClientID)); + + for (int i = 0; i < MAX_CLIENTS; i++) + if (((CGameControllerDDRace*) pSelf->m_pController)->m_Teams.m_Core.Team(i) == Team) + pSelf->SendChatTarget(i, aBuf); + } + } + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "print", + "This team can't be locked"); +} + +void CGameContext::ConJoinTeam(IConsole::IResult *pResult, void *pUserData) +{ + return; +} + +void CGameContext::ConMe(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + char aBuf[256 + 24]; + + str_format(aBuf, 256 + 24, "'%s' %s", + pSelf->Server()->ClientName(pResult->m_ClientID), + pResult->GetString(0)); + if (g_Config.m_SvSlashMe) + pSelf->SendChat(-2, CGameContext::CHAT_ALL, aBuf, pResult->m_ClientID); + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "me", + "/me is disabled on this server, admin can enable it by using sv_slash_me"); +} + +void CGameContext::ConConverse(IConsole::IResult *pResult, void *pUserData) +{ + // This will never be called +} + +void CGameContext::ConWhisper(IConsole::IResult *pResult, void *pUserData) +{ + // This will never be called +} + +void CGameContext::ConSetEyeEmote(IConsole::IResult *pResult, + void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + if(pResult->NumArguments() == 0) { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + (pPlayer->m_EyeEmote) ? + "You can now use the preset eye emotes." : + "You don't have any eye emotes, remember to bind some. (until you die)"); + return; + } + else if(str_comp_nocase(pResult->GetString(0), "on") == 0) + pPlayer->m_EyeEmote = true; + else if(str_comp_nocase(pResult->GetString(0), "off") == 0) + pPlayer->m_EyeEmote = false; + else if(str_comp_nocase(pResult->GetString(0), "toggle") == 0) + pPlayer->m_EyeEmote = !pPlayer->m_EyeEmote; + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + (pPlayer->m_EyeEmote) ? + "You can now use the preset eye emotes." : + "You don't have any eye emotes, remember to bind some. (until you die)"); +} + +void CGameContext::ConEyeEmote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (g_Config.m_SvEmotionalTees == -1) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "emote", + "Server admin disabled emotes."); + return; + } + + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + if (pResult->NumArguments() == 0) + { + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + "Emote commands are: /emote surprise /emote blink /emote close /emote angry /emote happy /emote pain"); + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "emote", + "Example: /emote surprise 10 for 10 seconds or /emote surprise (default 1 second)"); + } + else + { + if(pPlayer->m_LastEyeEmote + g_Config.m_SvEyeEmoteChangeDelay * pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; + + if (!str_comp(pResult->GetString(0), "angry")) + pPlayer->m_DefEmote = EMOTE_ANGRY; + else if (!str_comp(pResult->GetString(0), "blink")) + pPlayer->m_DefEmote = EMOTE_BLINK; + else if (!str_comp(pResult->GetString(0), "close")) + pPlayer->m_DefEmote = EMOTE_BLINK; + else if (!str_comp(pResult->GetString(0), "happy")) + pPlayer->m_DefEmote = EMOTE_HAPPY; + else if (!str_comp(pResult->GetString(0), "pain")) + pPlayer->m_DefEmote = EMOTE_PAIN; + else if (!str_comp(pResult->GetString(0), "surprise")) + pPlayer->m_DefEmote = EMOTE_SURPRISE; + else if (!str_comp(pResult->GetString(0), "normal")) + pPlayer->m_DefEmote = EMOTE_NORMAL; + else + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, + "emote", "Unknown emote... Say /emote"); + + int Duration = 1; + if (pResult->NumArguments() > 1) + Duration = pResult->GetInteger(1); + + pPlayer->m_DefEmoteReset = pSelf->Server()->Tick() + + Duration * pSelf->Server()->TickSpeed(); + pPlayer->m_LastEyeEmote = pSelf->Server()->Tick(); + } +} + +void CGameContext::ConNinjaJetpack(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + if (pResult->NumArguments()) + pPlayer->m_NinjaJetpack = pResult->GetInteger(0); + else + pPlayer->m_NinjaJetpack = !pPlayer->m_NinjaJetpack; +} + +void CGameContext::ConShowOthers(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + if (g_Config.m_SvShowOthers) + { + if (pResult->NumArguments()) + pPlayer->m_ShowOthers = pResult->GetInteger(0); + else + pPlayer->m_ShowOthers = !pPlayer->m_ShowOthers; + } + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "showotherschat", + "Showing players from other teams is disabled by the server admin"); +} + +void CGameContext::ConShowAll(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + if (pResult->NumArguments()) + pPlayer->m_ShowAll = pResult->GetInteger(0); + else + pPlayer->m_ShowAll = !pPlayer->m_ShowAll; +} + +void CGameContext::ConSpecTeam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + if (pResult->NumArguments()) + pPlayer->m_SpecTeam = pResult->GetInteger(0); + else + pPlayer->m_SpecTeam = !pPlayer->m_SpecTeam; +} + +bool CheckClientID(int ClientID) +{ + dbg_assert(ClientID >= 0 || ClientID < MAX_CLIENTS, + "The Client ID is wrong"); + if (ClientID < 0 || ClientID >= MAX_CLIENTS) + return false; + return true; +} + +void CGameContext::ConSayTime(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + int ClientID; + char aBufname[MAX_NAME_LENGTH]; + + if (pResult->NumArguments() > 0) + { + for(ClientID = 0; ClientID < MAX_CLIENTS; ClientID++) + if (str_comp(pResult->GetString(0), pSelf->Server()->ClientName(ClientID)) == 0) + break; + + if(ClientID == MAX_CLIENTS) + return; + + str_format(aBufname, sizeof(aBufname), "%s's", pSelf->Server()->ClientName(ClientID)); + } + else + { + str_copy(aBufname, "Your", sizeof(aBufname)); + ClientID = pResult->m_ClientID; + } + + CPlayer *pPlayer = pSelf->m_apPlayers[ClientID]; + if (!pPlayer) + return; + CCharacter* pChr = pPlayer->GetCharacter(); + if (!pChr) + return; + if(pChr->m_DDRaceState != DDRACE_STARTED) + return; + + char aBuftime[64]; + int IntTime = (int) ((float) (pSelf->Server()->Tick() - pChr->m_StartTime) + / ((float) pSelf->Server()->TickSpeed())); + str_format(aBuftime, sizeof(aBuftime), "%s time is %s%d:%s%d", + aBufname, + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "time", aBuftime); +} + +void CGameContext::ConSayTimeAll(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + CCharacter* pChr = pPlayer->GetCharacter(); + if (!pChr) + return; + if(pChr->m_DDRaceState != DDRACE_STARTED) + return; + + char aBuftime[64]; + int IntTime = (int) ((float) (pSelf->Server()->Tick() - pChr->m_StartTime) + / ((float) pSelf->Server()->TickSpeed())); + str_format(aBuftime, sizeof(aBuftime), + "%s\'s current race time is %s%d:%s%d", + pSelf->Server()->ClientName(pResult->m_ClientID), + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuftime, pResult->m_ClientID); +} + +void CGameContext::ConTime(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + CCharacter* pChr = pPlayer->GetCharacter(); + if (!pChr) + return; + + char aBuftime[64]; + int IntTime = (int) ((float) (pSelf->Server()->Tick() - pChr->m_StartTime) + / ((float) pSelf->Server()->TickSpeed())); + str_format(aBuftime, sizeof(aBuftime), "Your time is %s%d:%s%d", + ((IntTime / 60) > 9) ? "" : "0", IntTime / 60, + ((IntTime % 60) > 9) ? "" : "0", IntTime % 60); + pSelf->SendBroadcast(aBuftime, pResult->m_ClientID); +} + +void CGameContext::ConSetTimerType(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + + if (!CheckClientID(pResult->m_ClientID)) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + const char msg[3][128] = {"game/round timer.", "broadcast.", "both game/round timer and broadcast."}; + char aBuf[128]; + if(pPlayer->m_TimerType <= 2 && pPlayer->m_TimerType >= 0) + str_format(aBuf, sizeof(aBuf), "Timer is displayed in", msg[pPlayer->m_TimerType]); + else if(pPlayer->m_TimerType == 3) + str_format(aBuf, sizeof(aBuf), "Timer isn't displayed."); + + if(pResult->NumArguments() == 0) { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"timer",aBuf); + return; + } + else if(str_comp_nocase(pResult->GetString(0), "gametimer") == 0) { + pSelf->SendBroadcast("", pResult->m_ClientID); + pPlayer->m_TimerType = 0; + } + else if(str_comp_nocase(pResult->GetString(0), "broadcast") == 0) + pPlayer->m_TimerType = 1; + else if(str_comp_nocase(pResult->GetString(0), "both") == 0) + pPlayer->m_TimerType = 2; + else if(str_comp_nocase(pResult->GetString(0), "none") == 0) + pPlayer->m_TimerType = 3; + else if(str_comp_nocase(pResult->GetString(0), "cycle") == 0) { + if(pPlayer->m_TimerType < 3) + pPlayer->m_TimerType++; + else if(pPlayer->m_TimerType == 3) + pPlayer->m_TimerType = 0; + } + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"timer",aBuf); +} + +void CGameContext::ConRescue(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + CCharacter* pChr = pPlayer->GetCharacter(); + if (!pChr) + return; + + if (!g_Config.m_SvRescue) { + pSelf->SendChatTarget(pPlayer->GetCID(), "Rescue is not enabled on this server"); + return; + } + + pChr->Rescue(); +} + +void CGameContext::ConProtectedKill(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + CCharacter* pChr = pPlayer->GetCharacter(); + if (!pChr) + return; + + int CurrTime = (pSelf->Server()->Tick() - pChr->m_StartTime) / pSelf->Server()->TickSpeed(); + if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == DDRACE_STARTED) + { + pPlayer->KillCharacter(WEAPON_SELF); + + //char aBuf[64]; + //str_format(aBuf, sizeof(aBuf), "You killed yourself in: %s%d:%s%d", + // ((CurrTime / 60) > 9) ? "" : "0", CurrTime / 60, + // ((CurrTime % 60) > 9) ? "" : "0", CurrTime % 60); + //pSelf->SendChatTarget(pResult->m_ClientID, aBuf); + } +} + + +// headbot +void CGameContext::ConEarRape(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + CPlayer *poop = pSelf->m_apPlayers[pResult->m_ClientID]; + CCharacter *poopy = poop->GetCharacter(); + + if (pSelf->earrape_timer) + { + char buf[256]; + str_format(buf, sizeof(buf), "wait %d seconds", pSelf->earrape_timer / pSelf->Server()->TickSpeed()); + pSelf->SendChatTarget(pResult->m_ClientID, buf); + return; + } + if (not poopy) return; + + pSelf->earrape_timer = 600 * pSelf->Server()->TickSpeed(); + + poop->m_DefEmote = EMOTE_HAPPY; + poop->m_DefEmoteReset = pSelf->Server()->Tick() + (5000 * pSelf->Server()->TickSpeed()); + poop->m_LastEyeEmote = pSelf->Server()->Tick(); + + for (int i=0; i<30; i++) pSelf->CreateSound(poopy->m_Pos, SOUND_MENU); +} + +#if defined(CONF_SQL) +void CGameContext::ConPoints(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + if(pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; + + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + if (!pPlayer) + return; + + if (pResult->NumArguments() > 0) + if (!g_Config.m_SvHideScore) + pSelf->Score()->ShowPoints(pResult->m_ClientID, pResult->GetString(0), + true); + else + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "points", + "Showing the global points of other players is not allowed on this server."); + else + pSelf->Score()->ShowPoints(pResult->m_ClientID, + pSelf->Server()->ClientName(pResult->m_ClientID)); + + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery = pSelf->Server()->Tick(); +} +#endif + +#if defined(CONF_SQL) +void CGameContext::ConTopPoints(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + if(pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery + pSelf->Server()->TickSpeed() >= pSelf->Server()->Tick()) + return; + + if (g_Config.m_SvHideScore) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "toppoints", + "Showing the global top points is not allowed on this server."); + return; + } + + if (pResult->NumArguments() > 0 && pResult->GetInteger(0) >= 0) + pSelf->Score()->ShowTopPoints(pResult, pResult->m_ClientID, pUserData, + pResult->GetInteger(0)); + else + pSelf->Score()->ShowTopPoints(pResult, pResult->m_ClientID, pUserData); + + if(pSelf->m_apPlayers[pResult->m_ClientID] && g_Config.m_SvUseSQL) + pSelf->m_apPlayers[pResult->m_ClientID]->m_LastSQLQuery = pSelf->Server()->Tick(); +} +#endif diff --git a/src/game/server/ddracechat.h b/src/game/server/ddracechat.h new file mode 100644 index 0000000..3c7d5be --- /dev/null +++ b/src/game/server/ddracechat.h @@ -0,0 +1,59 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_DDRACECOMMANDS_H +#define GAME_SERVER_DDRACECOMMANDS_H +#undef GAME_SERVER_DDRACECOMMANDS_H // this file can be included several times +#ifndef CHAT_COMMAND +#define CHAT_COMMAND(name, params, flags, callback, userdata, help) +#endif + +CHAT_COMMAND("credits", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConCredits, this, "Shows the credits of the DDRace mod") +CHAT_COMMAND("emote", "?s[emote name] i[duration in seconds]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConEyeEmote, this, "Sets your tee's eye emote") +CHAT_COMMAND("eyeemote", "?s['on'|'off'|'toggle']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSetEyeEmote, this, "Toggles use of standard eye-emotes on/off, eyeemote s, where s = on for on, off for off, toggle for toggle and nothing to show current status") +CHAT_COMMAND("settings", "?s[configname]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSettings, this, "Shows gameplay information for this server") +CHAT_COMMAND("help", "?r[command]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConHelp, this, "Shows help to command r, general help if left blank") +CHAT_COMMAND("info", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConInfo, this, "Shows info about this server") +CHAT_COMMAND("me", "r[message]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConMe, this, "Like the famous irc command '/me says hi' will display '<yourname> says hi'") +CHAT_COMMAND("w", "s[player name] r[message]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConWhisper, this, "Whisper something to someone (private message)") +CHAT_COMMAND("whisper", "s[player name] r[message]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConWhisper, this, "Whisper something to someone (private message)") +CHAT_COMMAND("c", "r[message]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConConverse, this, "Converse with the last person you whispered to (private message)"); +CHAT_COMMAND("converse", "r[message]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConConverse, this, "Converse with the last person you whispered to (private message)"); +CHAT_COMMAND("pause", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTogglePause, this, "Toggles pause") +CHAT_COMMAND("spec", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConToggleSpec, this, "Toggles spec (if not activated on the server, it toggles pause)") +CHAT_COMMAND("dnd", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConDND, this, "Toggle Do Not Disturb (no chat and server messages)") +CHAT_COMMAND("mapinfo", "?r[map]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConMapInfo, this, "Show info about the map with name r gives (current map by default)") +CHAT_COMMAND("timeout", "s[code]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTimeout, this, "Set timeout protection code s") +CHAT_COMMAND("save", "r[code]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSave, this, "Save team with code r") +CHAT_COMMAND("load", "r[code]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConLoad, this, "Load with code r") +CHAT_COMMAND("map", "?r[map]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConMap, this, "Vote a map by name") +CHAT_COMMAND("rankteam", "?r[playername]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTeamRank, this, "Shows the team rank of player with name r (your team rank by default)") +CHAT_COMMAND("teamrank", "?r[playername]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTeamRank, this, "Shows the team rank of player with name r (your team rank by default)") +CHAT_COMMAND("rank", "?r[playername]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConRank, this, "Shows the rank of player with name r (your rank by default)") +CHAT_COMMAND("rules", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConRules, this, "Shows the server rules") +CHAT_COMMAND("team", "?i[id]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConJoinTeam, this, "Lets you join team i (shows your team if left blank)") +CHAT_COMMAND("lock", "?i['0'|'1']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConLockTeam, this, "Lock team so no-one else can join it") +CHAT_COMMAND("top5team", "?i[rank to start with]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTeamTop5, this, "Shows five team ranks of the ladder beginning with rank i (1 by default)") +CHAT_COMMAND("teamtop5", "?i[rank to start with]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTeamTop5, this, "Shows five team ranks of the ladder beginning with rank i (1 by default)") +CHAT_COMMAND("top5", "?i[rank to start with]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTop5, this, "Shows five ranks of the ladder beginning with rank i (1 by default)") +CHAT_COMMAND("showothers", "?i['0'|'1']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConShowOthers, this, "Whether to show players from other teams or not (off by default), optional i = 0 for off else for on") +CHAT_COMMAND("specteam", "?i['0'|'1']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSpecTeam, this, "Whether to show players from other teams when spectating (on by default), optional i = 0 for off else for on") +CHAT_COMMAND("ninjajetpack", "?i['0'|'1']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConNinjaJetpack, this, "Whether to use ninja jetpack or not. Makes jetpack look more awesome") +CHAT_COMMAND("saytime", "?r[playername]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSayTime, this, "Privately messages someone's current time in this current running race (your time by default)") +CHAT_COMMAND("saytimeall", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSayTimeAll, this, "Publicly messages everyone your current time in this current running race") +CHAT_COMMAND("time", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTime, this, "Privately shows you your current time in this current running race in the broadcast message") +CHAT_COMMAND("timer", "?s['gametimer'|'broadcast'|'both'|'none'|'cycle']", CFGFLAG_CHAT|CFGFLAG_SERVER, ConSetTimerType, this, "Personal Setting of showing time in either broadcast or game/round timer, timer s, where s = broadcast for broadcast, gametimer for game/round timer, cycle for cycle, both for both, none for no timer and nothing to show current status") +CHAT_COMMAND("r", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConRescue, this, "Teleport yourself out of freeze (use sv_rescue 1 to enable this feature)") +CHAT_COMMAND("rescue", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConRescue, this, "Teleport yourself out of freeze (use sv_rescue 1 to enable this feature)") + +CHAT_COMMAND("kill", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConProtectedKill, this, "Kill yourself") + +// headbot +CHAT_COMMAND("earrape", "", CFGFLAG_CHAT|CFGFLAG_SERVER, ConEarRape, this, "noisy") + +#if defined(CONF_SQL) +CHAT_COMMAND("times", "?s[playername] ?i[number of times to skip]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTimes, this, "/times ?s?i shows last 5 times of the server or of a player beginning with name s starting with time i (i = 1 by default)") +CHAT_COMMAND("points", "?r[playername]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConPoints, this, "Shows the global points of a player beginning with name r (your rank by default)") +CHAT_COMMAND("top5points", "?i[number]", CFGFLAG_CHAT|CFGFLAG_SERVER, ConTopPoints, this, "Shows five points of the global point ladder beginning with rank i (1 by default)") +#endif +#undef CHAT_COMMAND + +#endif diff --git a/src/game/server/ddracecommands.cpp b/src/game/server/ddracecommands.cpp new file mode 100644 index 0000000..bb08faa --- /dev/null +++ b/src/game/server/ddracecommands.cpp @@ -0,0 +1,532 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "gamecontext.h" +#include <engine/shared/config.h> +#include <engine/server/server.h> +#include <game/server/teams.h> +#include <game/server/gamemodes/DDRace.h> +#include <game/version.h> +#include <game/generated/nethash.cpp> +#if defined(CONF_SQL) +#include <game/server/score/sql_score.h> +#endif + +bool CheckClientID(int ClientID); + +void CGameContext::ConGoLeft(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, -1, 0); +} + +void CGameContext::ConGoRight(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, 1, 0); +} + +void CGameContext::ConGoDown(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, 0, 1); +} + +void CGameContext::ConGoUp(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, 0, -1); +} + +void CGameContext::ConMove(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, pResult->GetInteger(0), + pResult->GetInteger(1)); +} + +void CGameContext::ConMoveRaw(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + pSelf->MoveCharacter(pResult->m_ClientID, pResult->GetInteger(0), + pResult->GetInteger(1), true); +} + +void CGameContext::MoveCharacter(int ClientID, int X, int Y, bool Raw) +{ + CCharacter* pChr = GetPlayerChar(ClientID); + + if (!pChr) + return; + + pChr->Core()->m_Pos.x += ((Raw) ? 1 : 32) * X; + pChr->Core()->m_Pos.y += ((Raw) ? 1 : 32) * Y; + pChr->m_DDRaceState = DDRACE_CHEAT; +} + +void CGameContext::ConKillPlayer(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + int Victim = pResult->GetVictim(); + + if (pSelf->m_apPlayers[Victim]) + { + pSelf->m_apPlayers[Victim]->KillCharacter(WEAPON_GAME); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s was killed by %s", + pSelf->Server()->ClientName(Victim), + pSelf->Server()->ClientName(pResult->m_ClientID)); + pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } +} + +void CGameContext::ConNinja(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_NINJA, false); +} + +void CGameContext::ConSuper(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr && !pChr->m_Super) + { + pChr->m_Super = true; + pChr->UnFreeze(); + pChr->m_TeamBeforeSuper = pChr->Team(); + pChr->Teams()->SetCharacterTeam(pResult->m_ClientID, TEAM_SUPER); + pChr->m_DDRaceState = DDRACE_CHEAT; + } +} + +void CGameContext::ConUnSuper(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr && pChr->m_Super) + { + pChr->m_Super = false; + pChr->Teams()->SetForceCharacterTeam(pResult->m_ClientID, + pChr->m_TeamBeforeSuper); + } +} + +void CGameContext::ConUnSolo(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr) + pChr->SetSolo(false); +} + +void CGameContext::ConUnDeep(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr) + pChr->m_DeepFreeze = false; +} + +void CGameContext::ConShotgun(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_SHOTGUN, false); +} + +void CGameContext::ConGrenade(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_GRENADE, false); +} + +void CGameContext::ConRifle(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_RIFLE, false); +} + +void CGameContext::ConWeapons(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, -1, false); +} + +void CGameContext::ConUnShotgun(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_SHOTGUN, true); +} + +void CGameContext::ConUnGrenade(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_GRENADE, true); +} + +void CGameContext::ConUnRifle(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, WEAPON_RIFLE, true); +} + +void CGameContext::ConUnWeapons(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, -1, true); +} + +void CGameContext::ConAddWeapon(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, pResult->GetInteger(0), false); +} + +void CGameContext::ConRemoveWeapon(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->ModifyWeapons(pResult, pUserData, pResult->GetInteger(0), true); +} + +void CGameContext::ModifyWeapons(IConsole::IResult *pResult, void *pUserData, + int Weapon, bool Remove) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + int ClientID = pResult->m_ClientID; + if (clamp(Weapon, -1, NUM_WEAPONS - 1) != Weapon) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "invalid weapon id"); + return; + } + + CCharacter* pChr = GetPlayerChar(ClientID); + if (!pChr) + return; + + if (Weapon == -1) + { + if (Remove + && (pChr->GetActiveWeapon() == WEAPON_SHOTGUN + || pChr->GetActiveWeapon() == WEAPON_GRENADE + || pChr->GetActiveWeapon() == WEAPON_RIFLE)) + pChr->SetActiveWeapon(WEAPON_GUN); + + if (Remove) + { + pChr->SetWeaponGot(WEAPON_SHOTGUN, false); + pChr->SetWeaponGot(WEAPON_GRENADE, false); + pChr->SetWeaponGot(WEAPON_RIFLE, false); + } + else + pChr->GiveAllWeapons(); + } + else if (Weapon != WEAPON_NINJA) + { + if (Remove && pChr->GetActiveWeapon() == Weapon) + pChr->SetActiveWeapon(WEAPON_GUN); + + if (Remove) + pChr->SetWeaponGot(Weapon, false); + else + pChr->GiveWeapon(Weapon, -1); + } + else + { + if (Remove) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "info", + "you can't remove ninja"); + return; + } + + pChr->GiveNinja(); + } + + pChr->m_DDRaceState = DDRACE_CHEAT; +} + +void CGameContext::ConToTeleporter(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + unsigned int TeleTo = pResult->GetInteger(0); + + if (((CGameControllerDDRace*)pSelf->m_pController)->m_TeleOuts[TeleTo-1].size()) + { + int Num = ((CGameControllerDDRace*)pSelf->m_pController)->m_TeleOuts[TeleTo-1].size(); + vec2 TelePos = ((CGameControllerDDRace*)pSelf->m_pController)->m_TeleOuts[TeleTo-1][(!Num)?Num:rand() % Num]; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr) + { + pChr->Core()->m_Pos = TelePos; + pChr->m_Pos = TelePos; + pChr->m_PrevPos = TelePos; + pChr->m_DDRaceState = DDRACE_CHEAT; + } + } +} + +void CGameContext::ConToCheckTeleporter(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + unsigned int TeleTo = pResult->GetInteger(0); + + if (((CGameControllerDDRace*)pSelf->m_pController)->m_TeleCheckOuts[TeleTo-1].size()) + { + int Num = ((CGameControllerDDRace*)pSelf->m_pController)->m_TeleCheckOuts[TeleTo-1].size(); + vec2 TelePos = ((CGameControllerDDRace*)pSelf->m_pController)->m_TeleCheckOuts[TeleTo-1][(!Num)?Num:rand() % Num]; + CCharacter* pChr = pSelf->GetPlayerChar(pResult->m_ClientID); + if (pChr) + { + pChr->Core()->m_Pos = TelePos; + pChr->m_Pos = TelePos; + pChr->m_PrevPos = TelePos; + pChr->m_DDRaceState = DDRACE_CHEAT; + pChr->m_TeleCheckpoint = TeleTo; + } + } +} + +void CGameContext::ConTeleport(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + int TeleTo = pResult->GetInteger(0); + int Tele = pResult->m_ClientID; + if (pResult->NumArguments() > 0) + Tele = pResult->GetVictim(); + + if (pSelf->m_apPlayers[TeleTo]) + { + CCharacter* pChr = pSelf->GetPlayerChar(Tele); + if (pChr && pSelf->GetPlayerChar(TeleTo)) + { + pChr->Core()->m_Pos = pSelf->m_apPlayers[TeleTo]->m_ViewPos; + pChr->m_Pos = pSelf->m_apPlayers[TeleTo]->m_ViewPos; + pChr->m_PrevPos = pSelf->m_apPlayers[TeleTo]->m_ViewPos; + pChr->m_DDRaceState = DDRACE_CHEAT; + } + } +} + +void CGameContext::ConKill(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + if (!CheckClientID(pResult->m_ClientID)) + return; + CPlayer *pPlayer = pSelf->m_apPlayers[pResult->m_ClientID]; + + if (!pPlayer + || (pPlayer->m_LastKill + && pPlayer->m_LastKill + + pSelf->Server()->TickSpeed() + * g_Config.m_SvKillDelay + > pSelf->Server()->Tick())) + return; + + pPlayer->m_LastKill = pSelf->Server()->Tick(); + pPlayer->KillCharacter(WEAPON_SELF); + //pPlayer->m_RespawnTick = pSelf->Server()->Tick() + pSelf->Server()->TickSpeed() * g_Config.m_SvSuicidePenalty; +} + +void CGameContext::ConForcePause(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + CServer* pServ = (CServer*)pSelf->Server(); + int Victim = pResult->GetVictim(); + int Seconds = 0; + if (pResult->NumArguments() > 0) + Seconds = clamp(pResult->GetInteger(0), 0, 360); + + CPlayer *pPlayer = pSelf->m_apPlayers[Victim]; + if (!pPlayer) + return; + + pPlayer->m_ForcePauseTime = Seconds*pServ->TickSpeed(); + pPlayer->m_Paused = CPlayer::PAUSED_FORCE; +} + +void CGameContext::Mute(IConsole::IResult *pResult, NETADDR *Addr, int Secs, + const char *pDisplayName) +{ + char aBuf[128]; + int Found = 0; + // find a matching mute for this ip, update expiration time if found + for (int i = 0; i < m_NumMutes; i++) + { + if (net_addr_comp(&m_aMutes[i].m_Addr, Addr) == 0) + { + m_aMutes[i].m_Expire = Server()->Tick() + + Secs * Server()->TickSpeed(); + Found = 1; + } + } + + if (!Found) // nothing found so far, find a free slot.. + { + if (m_NumMutes < MAX_MUTES) + { + m_aMutes[m_NumMutes].m_Addr = *Addr; + m_aMutes[m_NumMutes].m_Expire = Server()->Tick() + + Secs * Server()->TickSpeed(); + m_NumMutes++; + Found = 1; + } + } + if (Found) + { + str_format(aBuf, sizeof aBuf, "'%s' has been muted for %d seconds.", + pDisplayName, Secs); + SendChat(-1, CHAT_ALL, aBuf); + } + else // no free slot found + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", "mute array is full"); +} + +void CGameContext::ConMute(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + pSelf->Console()->Print( + IConsole::OUTPUT_LEVEL_STANDARD, + "mutes", + "Use either 'muteid <client_id> <seconds>' or 'muteip <ip> <seconds>'"); +} + +// mute through client id +void CGameContext::ConMuteID(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + int Victim = pResult->GetVictim(); + + NETADDR Addr; + pSelf->Server()->GetClientAddr(Victim, &Addr); + + pSelf->Mute(pResult, &Addr, clamp(pResult->GetInteger(0), 1, 86400), + pSelf->Server()->ClientName(Victim)); +} + +// mute through ip, arguments reversed to workaround parsing +void CGameContext::ConMuteIP(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + NETADDR Addr; + if (net_addr_from_str(&Addr, pResult->GetString(0))) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", + "Invalid network address to mute"); + } + pSelf->Mute(pResult, &Addr, clamp(pResult->GetInteger(1), 1, 86400), + pResult->GetString(0)); +} + +// unmute by mute list index +void CGameContext::ConUnmute(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + char aIpBuf[64]; + char aBuf[64]; + int Victim = pResult->GetVictim(); + + if (Victim < 0 || Victim >= pSelf->m_NumMutes) + return; + + pSelf->m_NumMutes--; + pSelf->m_aMutes[Victim] = pSelf->m_aMutes[pSelf->m_NumMutes]; + + net_addr_str(&pSelf->m_aMutes[Victim].m_Addr, aIpBuf, sizeof(aIpBuf), false); + str_format(aBuf, sizeof(aBuf), "Unmuted %s", aIpBuf); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", aBuf); +} + +// list mutes +void CGameContext::ConMutes(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + char aIpBuf[64]; + char aBuf[128]; + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", + "Active mutes:"); + for (int i = 0; i < pSelf->m_NumMutes; i++) + { + net_addr_str(&pSelf->m_aMutes[i].m_Addr, aIpBuf, sizeof(aIpBuf), false); + str_format( + aBuf, + sizeof aBuf, + "%d: \"%s\", %d seconds left", + i, + aIpBuf, + (pSelf->m_aMutes[i].m_Expire - pSelf->Server()->Tick()) + / pSelf->Server()->TickSpeed()); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mutes", aBuf); + } +} + +void CGameContext::ConList(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int ClientID = pResult->m_ClientID; + if(!CheckClientID(ClientID)) return; + + char zerochar = 0; + if(pResult->NumArguments() > 0) + pSelf->List(ClientID, pResult->GetString(0)); + else + pSelf->List(ClientID, &zerochar); +} + +void CGameContext::ConFreezeHammer(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + int Victim = pResult->GetVictim(); + + CCharacter* pChr = pSelf->GetPlayerChar(Victim); + + if (!pChr) + return; + + char aBuf[128]; + str_format(aBuf, sizeof aBuf, "'%s' got freeze hammer!", + pSelf->Server()->ClientName(Victim)); + pSelf->SendChat(-1, CHAT_ALL, aBuf); + + pChr->m_FreezeHammer = true; +} + +void CGameContext::ConUnFreezeHammer(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + int Victim = pResult->GetVictim(); + + CCharacter* pChr = pSelf->GetPlayerChar(Victim); + + if (!pChr) + return; + + char aBuf[128]; + str_format(aBuf, sizeof aBuf, "'%s' lost freeze hammer!", + pSelf->Server()->ClientName(Victim)); + pSelf->SendChat(-1, CHAT_ALL, aBuf); + + pChr->m_FreezeHammer = false; +} diff --git a/src/game/server/entities/character.cpp b/src/game/server/entities/character.cpp new file mode 100644 index 0000000..81ed067 --- /dev/null +++ b/src/game/server/entities/character.cpp @@ -0,0 +1,2362 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <new> +#include <engine/shared/config.h> +#include <game/server/gamecontext.h> +#include <game/mapitems.h> + +#include "character.h" +#include "laser.h" +#include "projectile.h" + +#include <stdio.h> +#include <string.h> +#include <engine/server/server.h> +#include <game/server/gamemodes/WarioWare.h> +#include <game/server/score.h> +#include "light.h" + +MACRO_ALLOC_POOL_ID_IMPL(CCharacter, MAX_CLIENTS) + +// Character, "physical" player's part +CCharacter::CCharacter(CGameWorld *pWorld) +: CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER) +{ + m_ProximityRadius = ms_PhysSize; + m_Health = 0; + m_Armor = 0; +} + +void CCharacter::Reset() +{ + Destroy(); +} + +bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) +{ + m_EmoteStop = -1; + m_LastAction = -1; + m_LastNoAmmoSound = -1; + m_LastWeapon = WEAPON_HAMMER; + m_QueuedWeapon = -1; + m_LastRefillJumps = false; + m_LastPenalty = false; + m_LastBonus = false; + + m_pPlayer = pPlayer; + m_Pos = Pos; + + m_Core.Reset(); + m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision(), &((CGameControllerWarioWare*)GameServer()->m_pController)->m_Teams.m_Core, &((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts); + m_Core.m_ActiveWeapon = WEAPON_GUN; + m_Core.m_Pos = m_Pos; + GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; + + 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; + + GameServer()->m_pController->OnCharacterSpawn(this); + + Teams()->OnCharacterSpawn(GetPlayer()->GetCID()); + + DDRaceInit(); + + m_TuneZone = GameServer()->Collision()->IsTune(GameServer()->Collision()->GetMapIndex(Pos)); + m_TuneZoneOld = -1; // no zone leave msg on spawn + m_NeededFaketuning = 0; // reset fake tunings on respawn and send the client + SendZoneMsgs(); // we want a entermessage also on spawn + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); + + Server()->StartRecord(m_pPlayer->GetCID()); + + warioTimeOffset = warioTimeLength = 0; + + return true; +} + +void CCharacter::Destroy() +{ + GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; + m_Alive = false; +} + +void CCharacter::SetWeapon(int W) +{ + if(W == m_Core.m_ActiveWeapon) + return; + + m_LastWeapon = m_Core.m_ActiveWeapon; + m_QueuedWeapon = -1; + m_Core.m_ActiveWeapon = W; + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SWITCH, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + + if(m_Core.m_ActiveWeapon < 0 || m_Core.m_ActiveWeapon >= NUM_WEAPONS) + m_Core.m_ActiveWeapon = 0; +} + +void CCharacter::SetSolo(bool Solo) +{ + Teams()->m_Core.SetSolo(m_pPlayer->GetCID(), Solo); + + if(Solo) + m_NeededFaketuning |= FAKETUNE_SOLO; + else + m_NeededFaketuning &= ~FAKETUNE_SOLO; + + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings +} + +bool CCharacter::IsGrounded() +{ + if(GameServer()->Collision()->CheckPoint(m_Pos.x+m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + return true; + if(GameServer()->Collision()->CheckPoint(m_Pos.x-m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) + return true; + + int index = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x, m_Pos.y+m_ProximityRadius/2+4)); + int tile = GameServer()->Collision()->GetTileIndex(index); + int flags = GameServer()->Collision()->GetTileFlags(index); + if(tile == TILE_STOPA || (tile == TILE_STOP && flags == ROTATION_0) || (tile ==TILE_STOPS && (flags == ROTATION_0 || flags == ROTATION_180))) + return true; + tile = GameServer()->Collision()->GetFTileIndex(index); + flags = GameServer()->Collision()->GetFTileFlags(index); + if(tile == TILE_STOPA || (tile == TILE_STOP && flags == ROTATION_0) || (tile ==TILE_STOPS && (flags == ROTATION_0 || flags == ROTATION_180))) + return true; + + return false; +} + +void CCharacter::HandleJetpack() +{ + vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); + + bool FullAuto = false; + if(m_Core.m_ActiveWeapon == WEAPON_GRENADE || m_Core.m_ActiveWeapon == WEAPON_SHOTGUN || m_Core.m_ActiveWeapon == WEAPON_RIFLE) + FullAuto = true; + if (m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) + FullAuto = true; + + // check if we gonna fire + 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_Core.m_ActiveWeapon].m_Ammo) + WillFire = true; + + if(!WillFire) + return; + + // check for ammo + if(!m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + { + return; + } + + switch(m_Core.m_ActiveWeapon) + { + case WEAPON_GUN: + { + if (m_Jetpack) + { + float Strength; + if (!m_TuneZone) + Strength = GameServer()->Tuning()->m_JetpackStrength; + else + Strength = GameServer()->TuningList()[m_TuneZone].m_JetpackStrength; + TakeDamage(Direction * -1.0f * (Strength / 100.0f / 6.11f), g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); + } + } + } +} + +void CCharacter::HandleNinja() +{ + if(m_Core.m_ActiveWeapon != WEAPON_NINJA) + return; + + if ((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) + { + // time's up, return + m_Ninja.m_CurrentMoveTime = 0; + m_aWeapons[WEAPON_NINJA].m_Got = false; + m_Core.m_ActiveWeapon = m_LastWeapon; + + SetWeapon(m_Core.m_ActiveWeapon); + return; + } + + int NinjaTime = m_Ninja.m_ActivationTick + (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000) - Server()->Tick(); + + if (NinjaTime % Server()->TickSpeed() == 0 && NinjaTime / Server()->TickSpeed() <= 5) + { + GameServer()->CreateDamageInd(m_Pos, 0, NinjaTime / Server()->TickSpeed(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + + m_Armor = 10 - (NinjaTime / 15); + + // force ninja Weapon + SetWeapon(WEAPON_NINJA); + + m_Ninja.m_CurrentMoveTime--; + + if (m_Ninja.m_CurrentMoveTime == 0) + { + // reset velocity + m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; + } + + if (m_Ninja.m_CurrentMoveTime > 0) + { + // Set velocity + 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); + + // check if we Hit anything along the way + { + CCharacter *aEnts[MAX_CLIENTS]; + vec2 Dir = m_Pos - OldPos; + float Radius = m_ProximityRadius * 2.0f; + vec2 Center = OldPos + Dir * 0.5f; + int Num = GameServer()->m_World.FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + // check that we're not in solo part + if (Teams()->m_Core.GetSolo(m_pPlayer->GetCID())) + return; + + for (int i = 0; i < Num; ++i) + { + if (aEnts[i] == this) + continue; + + // Don't hit players in other teams + if (Team() != aEnts[i]->Team()) + continue; + + // Don't hit players in solo parts + if (Teams()->m_Core.GetSolo(aEnts[i]->m_pPlayer->GetCID())) + return; + + // make sure we haven't Hit this object before + bool bAlreadyHit = false; + for (int j = 0; j < m_NumObjectsHit; j++) + { + if (m_apHitObjects[j] == aEnts[i]) + bAlreadyHit = true; + } + if (bAlreadyHit) + continue; + + // check so we are sufficiently close + if (distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) + continue; + + // Hit a player, give him damage and stuffs... + GameServer()->CreateSound(aEnts[i]->m_Pos, SOUND_NINJA_HIT, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + // 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; + } + + return; +} + + +void CCharacter::DoWeaponSwitch() +{ + // make sure we can switch + if(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got) + return; + + // switch Weapon + SetWeapon(m_QueuedWeapon); +} + +void CCharacter::HandleWeaponSwitch() +{ + int WantedWeapon = m_Core.m_ActiveWeapon; + if(m_QueuedWeapon != -1) + WantedWeapon = m_QueuedWeapon; + + bool Anything = false; + for(int i = 0; i < NUM_WEAPONS - 1; ++i) + if(m_aWeapons[i].m_Got) + Anything = true; + if(!Anything) + return; + // 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; + + if(Next < 128) // make sure we only try sane stuff + { + while(Next) // Next Weapon selection + { + WantedWeapon = (WantedWeapon+1)%NUM_WEAPONS; + if(m_aWeapons[WantedWeapon].m_Got) + Next--; + } + } + + if(Prev < 128) // make sure we only try sane stuff + { + while(Prev) // Prev Weapon selection + { + WantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1; + if(m_aWeapons[WantedWeapon].m_Got) + Prev--; + } + } + + // Direct Weapon selection + if(m_LatestInput.m_WantedWeapon) + WantedWeapon = m_Input.m_WantedWeapon-1; + + // check for insane values + if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_Core.m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) + m_QueuedWeapon = WantedWeapon; + + DoWeaponSwitch(); +} + +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_Core.m_ActiveWeapon == WEAPON_GRENADE || m_Core.m_ActiveWeapon == WEAPON_SHOTGUN || m_Core.m_ActiveWeapon == WEAPON_RIFLE) + FullAuto = true; + if (m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN) + FullAuto = true; + + // check if we gonna fire + 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_Core.m_ActiveWeapon].m_Ammo) + WillFire = true; + + if(!WillFire) + return; + + // check for ammo + if(!m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo) + { + /*// 125ms is a magical limit of how fast a human can click + m_ReloadTimer = 125 * Server()->TickSpeed() / 1000; + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);*/ + // Timer stuff to avoid shrieking orchestra caused by unfreeze-plasma + if(m_PainSoundTimer<=0) + { + m_PainSoundTimer = 1 * Server()->TickSpeed(); + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + return; + } + + vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f; + + switch(m_Core.m_ActiveWeapon) + { + case WEAPON_HAMMER: + { + // reset objects Hit + m_NumObjectsHit = 0; + GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + + if (m_Hit&DISABLE_HIT_HAMMER) break; + + CCharacter *apEnts[MAX_CLIENTS]; + int Hits = 0; + 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)) + if((pTarget == this || (pTarget->IsAlive() && !CanCollide(pTarget->GetPlayer()->GetCID())))) + continue; + + // set his velocity to fast upward (for now) + if(length(pTarget->m_Pos-ProjStartPos) > 0.0f) + GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + else + GameServer()->CreateHammerHit(ProjStartPos, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + + 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_Core.m_ActiveWeapon);*/ + + float Strength; + if (!m_TuneZone) + Strength = GameServer()->Tuning()->m_HammerStrength; + else + Strength = GameServer()->TuningList()[m_TuneZone].m_HammerStrength; + + vec2 Temp = pTarget->m_Core.m_Vel + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f; + if(Temp.x > 0 && ((pTarget->m_TileIndex == TILE_STOP && pTarget->m_TileFlags == ROTATION_270) || (pTarget->m_TileIndexL == TILE_STOP && pTarget->m_TileFlagsL == ROTATION_270) || (pTarget->m_TileIndexL == TILE_STOPS && (pTarget->m_TileFlagsL == ROTATION_90 || pTarget->m_TileFlagsL ==ROTATION_270)) || (pTarget->m_TileIndexL == TILE_STOPA) || (pTarget->m_TileFIndex == TILE_STOP && pTarget->m_TileFFlags == ROTATION_270) || (pTarget->m_TileFIndexL == TILE_STOP && pTarget->m_TileFFlagsL == ROTATION_270) || (pTarget->m_TileFIndexL == TILE_STOPS && (pTarget->m_TileFFlagsL == ROTATION_90 || pTarget->m_TileFFlagsL == ROTATION_270)) || (pTarget->m_TileFIndexL == TILE_STOPA) || (pTarget->m_TileSIndex == TILE_STOP && pTarget->m_TileSFlags == ROTATION_270) || (pTarget->m_TileSIndexL == TILE_STOP && pTarget->m_TileSFlagsL == ROTATION_270) || (pTarget->m_TileSIndexL == TILE_STOPS && (pTarget->m_TileSFlagsL == ROTATION_90 || pTarget->m_TileSFlagsL == ROTATION_270)) || (pTarget->m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((pTarget->m_TileIndex == TILE_STOP && pTarget->m_TileFlags == ROTATION_90) || (pTarget->m_TileIndexR == TILE_STOP && pTarget->m_TileFlagsR == ROTATION_90) || (pTarget->m_TileIndexR == TILE_STOPS && (pTarget->m_TileFlagsR == ROTATION_90 || pTarget->m_TileFlagsR == ROTATION_270)) || (pTarget->m_TileIndexR == TILE_STOPA) || (pTarget->m_TileFIndex == TILE_STOP && pTarget->m_TileFFlags == ROTATION_90) || (pTarget->m_TileFIndexR == TILE_STOP && pTarget->m_TileFFlagsR == ROTATION_90) || (pTarget->m_TileFIndexR == TILE_STOPS && (pTarget->m_TileFFlagsR == ROTATION_90 || pTarget->m_TileFFlagsR == ROTATION_270)) || (pTarget->m_TileFIndexR == TILE_STOPA) || (pTarget->m_TileSIndex == TILE_STOP && pTarget->m_TileSFlags == ROTATION_90) || (pTarget->m_TileSIndexR == TILE_STOP && pTarget->m_TileSFlagsR == ROTATION_90) || (pTarget->m_TileSIndexR == TILE_STOPS && (pTarget->m_TileSFlagsR == ROTATION_90 || pTarget->m_TileSFlagsR == ROTATION_270)) || (pTarget->m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((pTarget->m_TileIndex == TILE_STOP && pTarget->m_TileFlags == ROTATION_180) || (pTarget->m_TileIndexB == TILE_STOP && pTarget->m_TileFlagsB == ROTATION_180) || (pTarget->m_TileIndexB == TILE_STOPS && (pTarget->m_TileFlagsB == ROTATION_0 || pTarget->m_TileFlagsB == ROTATION_180)) || (pTarget->m_TileIndexB == TILE_STOPA) || (pTarget->m_TileFIndex == TILE_STOP && pTarget->m_TileFFlags == ROTATION_180) || (pTarget->m_TileFIndexB == TILE_STOP && pTarget->m_TileFFlagsB == ROTATION_180) || (pTarget->m_TileFIndexB == TILE_STOPS && (pTarget->m_TileFFlagsB == ROTATION_0 || pTarget->m_TileFFlagsB == ROTATION_180)) || (pTarget->m_TileFIndexB == TILE_STOPA) || (pTarget->m_TileSIndex == TILE_STOP && pTarget->m_TileSFlags == ROTATION_180) || (pTarget->m_TileSIndexB == TILE_STOP && pTarget->m_TileSFlagsB == ROTATION_180) || (pTarget->m_TileSIndexB == TILE_STOPS && (pTarget->m_TileSFlagsB == ROTATION_0 || pTarget->m_TileSFlagsB == ROTATION_180)) || (pTarget->m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((pTarget->m_TileIndex == TILE_STOP && pTarget->m_TileFlags == ROTATION_0) || (pTarget->m_TileIndexT == TILE_STOP && pTarget->m_TileFlagsT == ROTATION_0) || (pTarget->m_TileIndexT == TILE_STOPS && (pTarget->m_TileFlagsT == ROTATION_0 || pTarget->m_TileFlagsT == ROTATION_180)) || (pTarget->m_TileIndexT == TILE_STOPA) || (pTarget->m_TileFIndex == TILE_STOP && pTarget->m_TileFFlags == ROTATION_0) || (pTarget->m_TileFIndexT == TILE_STOP && pTarget->m_TileFFlagsT == ROTATION_0) || (pTarget->m_TileFIndexT == TILE_STOPS && (pTarget->m_TileFFlagsT == ROTATION_0 || pTarget->m_TileFFlagsT == ROTATION_180)) || (pTarget->m_TileFIndexT == TILE_STOPA) || (pTarget->m_TileSIndex == TILE_STOP && pTarget->m_TileSFlags == ROTATION_0) || (pTarget->m_TileSIndexT == TILE_STOP && pTarget->m_TileSFlagsT == ROTATION_0) || (pTarget->m_TileSIndexT == TILE_STOPS && (pTarget->m_TileSFlagsT == ROTATION_0 || pTarget->m_TileSFlagsT == ROTATION_180)) || (pTarget->m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + Temp -= pTarget->m_Core.m_Vel; + pTarget->TakeDamage((vec2(0.f, -1.0f) + Temp) * Strength, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, + m_pPlayer->GetCID(), m_Core.m_ActiveWeapon); + pTarget->UnFreeze(); + + if(m_FreezeHammer) + pTarget->Freeze(); + + Hits++; + } + + // if we Hit anything, we have to wait for the reload + if(Hits) + m_ReloadTimer = Server()->TickSpeed()/3; + + } break; + + case WEAPON_GUN: + { + if (!m_Jetpack || !m_pPlayer->m_NinjaJetpack) + { + int Lifetime; + if (!m_TuneZone) + Lifetime = (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime); + else + Lifetime = (int)(Server()->TickSpeed()*GameServer()->TuningList()[m_TuneZone].m_GunLifetime); + + CProjectile *pProj = new CProjectile + ( + GameWorld(), + WEAPON_GUN,//Type + m_pPlayer->GetCID(),//Owner + ProjStartPos,//Pos + Direction,//Dir + Lifetime,//Span + 0,//Freeze + 0,//Explosive + 0,//Force + -1,//SoundImpact + WEAPON_GUN//Weapon + ); + + // 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, MSGFLAG_VITAL, m_pPlayer->GetCID()); + GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + } 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}; + float a = GetAngle(Direction); + a += Spreading[i+2]; + float v = 1-(absolute(i)/(float)ShotSpread); + float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v); + CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN, + m_pPlayer->GetCID(), + ProjStartPos, + 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, MSGFLAG_VITAL, m_pPlayer->GetCID()); + + GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);*/ + float LaserReach; + if (!m_TuneZone) + LaserReach = GameServer()->Tuning()->m_LaserReach; + else + LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; + + new CLaser(&GameServer()->m_World, m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_SHOTGUN); + GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } break; + + case WEAPON_GRENADE: + { + int Lifetime; + if (!m_TuneZone) + Lifetime = (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime); + else + Lifetime = (int)(Server()->TickSpeed()*GameServer()->TuningList()[m_TuneZone].m_GrenadeLifetime); + + CProjectile *pProj = new CProjectile + ( + GameWorld(), + WEAPON_GRENADE,//Type + m_pPlayer->GetCID(),//Owner + ProjStartPos,//Pos + Direction,//Dir + Lifetime,//Span + 0,//Freeze + true,//Explosive + 0,//Force + SOUND_GRENADE_EXPLODE,//SoundImpact + WEAPON_GRENADE//Weapon + );//SoundImpact + + // 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, MSGFLAG_VITAL, m_pPlayer->GetCID()); + + GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } break; + + case WEAPON_RIFLE: + { + float LaserReach; + if (!m_TuneZone) + LaserReach = GameServer()->Tuning()->m_LaserReach; + else + LaserReach = GameServer()->TuningList()[m_TuneZone].m_LaserReach; + + new CLaser(GameWorld(), m_Pos, Direction, LaserReach, m_pPlayer->GetCID(), WEAPON_RIFLE); + GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } 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, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } break; + + } + + m_AttackTick = Server()->Tick(); + + /*if(m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited + m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo--;*/ + + if(!m_ReloadTimer) + { + float FireDelay; + if (!m_TuneZone) + GameServer()->Tuning()->Get(38 + m_Core.m_ActiveWeapon, &FireDelay); + else + GameServer()->TuningList()[m_TuneZone].Get(38 + m_Core.m_ActiveWeapon, &FireDelay); + m_ReloadTimer = FireDelay * Server()->TickSpeed() / 1000; + } +} + +void CCharacter::HandleWeapons() +{ + //ninja + HandleNinja(); + HandleJetpack(); + + if(m_PainSoundTimer > 0) + m_PainSoundTimer--; + + // check reload timer + if(m_ReloadTimer) + { + m_ReloadTimer--; + return; + } + + // fire Weapon, if wanted + FireWeapon(); +/* + // ammo regen + int AmmoRegenTime = g_pData->m_Weapons.m_aId[m_Core.m_ActiveWeapon].m_Ammoregentime; + if(AmmoRegenTime) + { + // If equipped and not active, regen ammo? + if (m_ReloadTimer <= 0) + { + if (m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart < 0) + m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart = Server()->Tick(); + + if ((Server()->Tick() - m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart) >= AmmoRegenTime * Server()->TickSpeed() / 1000) + { + // Add some ammo + m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo = min(m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo + 1, 10); + m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart = -1; + } + } + else + { + m_aWeapons[m_Core.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; + if(!m_FreezeTime) + m_aWeapons[Weapon].m_Ammo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo); + return true; + } + return false; +} + +void CCharacter::GiveNinja() +{ + m_Ninja.m_ActivationTick = Server()->Tick(); + m_aWeapons[WEAPON_NINJA].m_Got = true; + if (!m_FreezeTime) + m_aWeapons[WEAPON_NINJA].m_Ammo = -1; + if (m_Core.m_ActiveWeapon != WEAPON_NINJA) + m_LastWeapon = m_Core.m_ActiveWeapon; + m_Core.m_ActiveWeapon = WEAPON_NINJA; + + if(!m_aWeapons[WEAPON_NINJA].m_Got) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_NINJA, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); +} + +void CCharacter::SetEmote(int Emote, int Tick) +{ + m_EmoteType = Emote; + m_EmoteStop = Tick; +} + +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++; + + // it is not allowed to aim in the center + if(m_Input.m_TargetX == 0 && m_Input.m_TargetY == 0) + 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)); + + // it is not allowed to aim in the center + if(m_LatestInput.m_TargetX == 0 && m_LatestInput.m_TargetY == 0) + m_LatestInput.m_TargetY = -1; + + if(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS) + { + HandleWeaponSwitch(); + FireWeapon(); + } + + mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); +} + +void CCharacter::ResetInput() +{ + m_Input.m_Direction = 0; + //m_Input.m_Hook = 0; + // simulate releasing the fire button + if((m_Input.m_Fire&1) != 0) + m_Input.m_Fire++; + m_Input.m_Fire &= INPUT_STATE_MASK; + m_Input.m_Jump = 0; + m_LatestPrevInput = m_LatestInput = m_Input; +} + +void CCharacter::Tick() +{ + /*if(m_pPlayer->m_ForceBalanced) + { + 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; + }*/ + + if (m_Paused) + return; + + DDRaceTick(); + + m_Core.m_Input = m_Input; + m_Core.Tick(true, false); + + /*// 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 || + 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 || + GameLayerClipped(m_Pos)) + { + Die(m_pPlayer->GetCID(), WEAPON_WORLD); + }*/ + + // handle Weapons + HandleWeapons(); + + DDRacePostCoreTick(); + + // Previnput + m_PrevInput = m_Input; + + m_PrevPos = m_Core.m_Pos; + return; +} + +void CCharacter::TickDefered() +{ + // advance the dummy + { + CWorldCore TempWorld; + m_ReckoningCore.Init(&TempWorld, GameServer()->Collision(), &((CGameControllerWarioWare*)GameServer()->m_pController)->m_Teams.m_Core, &((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts); + m_ReckoningCore.m_Id = m_pPlayer->GetCID(); + m_ReckoningCore.Tick(false, false); + 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.m_Id = m_pPlayer->GetCID(); + 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 + union + { + float f; + unsigned u; + }StartPosX, StartPosY, StartVelX, StartVelY; + + StartPosX.f = StartPos.x; + StartPosY.f = StartPos.y; + StartVelX.f = StartVel.x; + StartVelY.f = StartVel.y; + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", + StuckBefore, + StuckAfterMove, + StuckAfterQuant, + StartPos.x, StartPos.y, + StartVel.x, StartVel.y, + StartPosX.u, StartPosY.u, + StartVelX.u, StartVelY.u); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + } + + int Events = m_Core.m_TriggeredEvents; + //int Mask = CmaskAllExceptOne(m_pPlayer->GetCID()); + + if(Events&COREEVENT_GROUND_JUMP) GameServer()->CreateSound(m_Pos, SOUND_PLAYER_JUMP, Teams()->TeamMask(Team(), m_pPlayer->GetCID())); + + if(Events&COREEVENT_HOOK_ATTACH_PLAYER) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_PLAYER, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + if(Events&COREEVENT_HOOK_ATTACH_GROUND) GameServer()->CreateSound(m_Pos, SOUND_HOOK_ATTACH_GROUND, Teams()->TeamMask(Team(), m_pPlayer->GetCID(), m_pPlayer->GetCID())); + if(Events&COREEVENT_HOOK_HIT_NOHOOK) GameServer()->CreateSound(m_Pos, SOUND_HOOK_NOATTACH, Teams()->TeamMask(Team(), m_pPlayer->GetCID(), m_pPlayer->GetCID())); + + + 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; + CNetObj_Character Current; + mem_zero(&Predicted, sizeof(Predicted)); + mem_zero(&Current, sizeof(Current)); + m_ReckoningCore.Write(&Predicted); + m_Core.Write(&Current); + + // only allow dead reackoning for a top of 3 seconds + if(m_Core.m_pReset || m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) + { + m_ReckoningTick = Server()->Tick(); + m_SendCore = m_Core; + m_ReckoningCore = m_Core; + m_Core.m_pReset = false; + } + } +} + +void CCharacter::TickPaused() +{ + ++m_AttackTick; + ++m_DamageTakenTick; + ++m_Ninja.m_ActivationTick; + ++m_ReckoningTick; + if(m_LastAction != -1) + ++m_LastAction; + if(m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart > -1) + ++m_aWeapons[m_Core.m_ActiveWeapon].m_AmmoRegenStart; + if(m_EmoteStop > -1) + ++m_EmoteStop; +} + +bool CCharacter::IncreaseHealth(int Amount) +{ + if(m_Health >= 10) + return false; + m_Health = clamp(m_Health+Amount, 0, 10); + return true; +} + +bool CCharacter::IncreaseArmor(int Amount) +{ + if(m_Armor >= 10) + return false; + m_Armor = clamp(m_Armor+Amount, 0, 10); + return true; +} + +void CCharacter::Die(int Killer, int Weapon, float respawnSecs) +{ + if(Server()->IsRecording(m_pPlayer->GetCID())) + Server()->StopRecord(m_pPlayer->GetCID()); + + int ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, GameServer()->m_apPlayers[Killer], Weapon); + + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "kill killer='%d:%s' victim='%d:%s' weapon=%d special=%d", + Killer, Server()->ClientName(Killer), + m_pPlayer->GetCID(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + + // send the kill message + CNetMsg_Sv_KillMsg Msg; + Msg.m_Killer = Killer; + Msg.m_Victim = m_pPlayer->GetCID(); + Msg.m_Weapon = Weapon; + Msg.m_ModeSpecial = ModeSpecial; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); + + // a nice sound + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE, Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + + // this is for auto respawn after 3 secs + m_pPlayer->m_DieTick = Server()->Tick() + (Server()->TickSpeed() * respawnSecs); + + m_Alive = false; + GameServer()->m_World.RemoveEntity(this); + GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; + GameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + Teams()->OnCharacterDeath(GetPlayer()->GetCID(), 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; + + // m_pPlayer only inflicts half damage on self + if(From == m_pPlayer->GetCID()) + Dmg = max(1, Dmg/2); + + m_DamageTaken++; + + // create healthmod indicator + if(Server()->Tick() < m_DamageTakenTick+25) + { + // make sure that the damage indicators doesn't group together + GameServer()->CreateDamageInd(m_Pos, m_DamageTaken*0.25f, Dmg); + } + else + { + m_DamageTaken = 0; + GameServer()->CreateDamageInd(m_Pos, 0, Dmg); + } + + if(Dmg) + { + if(m_Armor) + { + if(Dmg > 1) + { + m_Health--; + Dmg--; + } + + if(Dmg > m_Armor) + { + Dmg -= m_Armor; + m_Armor = 0; + } + else + { + m_Armor -= Dmg; + Dmg = 0; + } + } + + m_Health -= Dmg; + } + + m_DamageTakenTick = Server()->Tick(); + + // do damage Hit sound + if(From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) + { + int64_t Mask = CmaskOne(From); + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS && GameServer()->m_apPlayers[i]->m_SpectatorID == From) + Mask |= CmaskOne(i); + } + GameServer()->CreateSound(GameServer()->m_apPlayers[From]->m_ViewPos, SOUND_HIT, Mask); + } + + // check for death + 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]) + { + CCharacter *pChr = GameServer()->m_apPlayers[From]->GetCharacter(); + if (pChr) + { + pChr->m_EmoteType = EMOTE_HAPPY; + pChr->m_EmoteStop = Server()->Tick() + Server()->TickSpeed(); + } + } + + return false; + } + + if (Dmg > 2) + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG); + else + GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT);*/ + + if (!m_Jetpack || m_Core.m_ActiveWeapon != WEAPON_GUN) + { + m_EmoteType = EMOTE_PAIN; + m_EmoteStop = Server()->Tick() + 500 * Server()->TickSpeed() / 1000; + } + + vec2 Temp = m_Core.m_Vel + Force; + if(Temp.x > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + m_Core.m_Vel = Temp; + + CGameControllerWarioWare* controller = ((CGameControllerWarioWare*)GameServer()->m_pController); + if (controller->isInGame() and controller->inMicroGame()) + { + controller->OnCharacterDamage(m_pPlayer->GetCID(), From, Dmg, Weapon); + } + else if (controller->getWarioState() == WW_GAMEOVER and From == controller->finalWinner) + { + float timeLeft = (controller->getTimeLength() - controller->getTimer()) / 1000.f; + Die(From, Weapon, timeLeft); + } + + return true; +} + +void CCharacter::Snap(int SnappingClient) +{ + int id = m_pPlayer->GetCID(); + + if(SnappingClient > -1 && !Server()->Translate(id, SnappingClient)) + return; + + if(NetworkClipped(SnappingClient)) + return; + + if(SnappingClient > -1) + { + CCharacter* SnapChar = GameServer()->GetPlayerChar(SnappingClient); + CPlayer* SnapPlayer = GameServer()->m_apPlayers[SnappingClient]; + + if((SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->m_Paused) && SnapPlayer->m_SpectatorID != -1 + && !CanCollide(SnapPlayer->m_SpectatorID) && !SnapPlayer->m_ShowOthers) + return; + + if( SnapPlayer->GetTeam() != TEAM_SPECTATORS && !SnapPlayer->m_Paused && SnapChar && !SnapChar->m_Super + && !CanCollide(SnappingClient) && !SnapPlayer->m_ShowOthers) + return; + + if((SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->m_Paused) && SnapPlayer->m_SpectatorID == -1 + && !CanCollide(SnappingClient) && SnapPlayer->m_SpecTeam) + return; + } + + if (m_Paused) + return; + + CNetObj_Character *pCharacter = static_cast<CNetObj_Character *>(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, id, sizeof(CNetObj_Character))); + if(!pCharacter) + return; + + // write down the m_Core + if(!m_ReckoningTick || GameServer()->m_World.m_Paused) + { + // no dead reckoning when paused because the client doesn't know + // how far to perform the reckoning + pCharacter->m_Tick = 0; + m_Core.Write(pCharacter); + } + else + { + pCharacter->m_Tick = m_ReckoningTick; + m_SendCore.Write(pCharacter); + } + + // set emote + if (m_EmoteStop < Server()->Tick()) + { + m_EmoteType = m_pPlayer->m_DefEmote; + m_EmoteStop = -1; + } + pCharacter->m_Emote = m_EmoteType; + + if (pCharacter->m_HookedPlayer != -1) + { + if (!Server()->Translate(pCharacter->m_HookedPlayer, SnappingClient)) + pCharacter->m_HookedPlayer = -1; + } + + pCharacter->m_AttackTick = m_AttackTick; + pCharacter->m_Direction = m_Input.m_Direction; + pCharacter->m_Weapon = m_Core.m_ActiveWeapon; + pCharacter->m_AmmoCount = 0; + pCharacter->m_Health = 0; + pCharacter->m_Armor = 0; + + // change eyes and use ninja graphic if player is freeze + if (m_DeepFreeze) + { + if (pCharacter->m_Emote == EMOTE_NORMAL) + pCharacter->m_Emote = EMOTE_PAIN; + pCharacter->m_Weapon = WEAPON_NINJA; + } + else if (m_FreezeTime > 0 || m_FreezeTime == -1) + { + if (pCharacter->m_Emote == EMOTE_NORMAL) + pCharacter->m_Emote = EMOTE_BLINK; + pCharacter->m_Weapon = WEAPON_NINJA; + } + + // jetpack and ninjajetpack prediction + if (m_pPlayer->GetCID() == SnappingClient) + { + if (m_Jetpack && pCharacter->m_Weapon != WEAPON_NINJA) + { + if (!(m_NeededFaketuning & FAKETUNE_JETPACK)) + { + m_NeededFaketuning |= FAKETUNE_JETPACK; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); + } + } + else + { + if (m_NeededFaketuning & FAKETUNE_JETPACK) + { + m_NeededFaketuning &= ~FAKETUNE_JETPACK; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); + } + } + } + + // change eyes, use ninja graphic and set ammo count if player has ninjajetpack + if (m_pPlayer->m_NinjaJetpack && m_Jetpack && m_Core.m_ActiveWeapon == WEAPON_GUN && !m_DeepFreeze && !(m_FreezeTime > 0 || m_FreezeTime == -1)) + { + if (pCharacter->m_Emote == EMOTE_NORMAL) + pCharacter->m_Emote = EMOTE_HAPPY; + pCharacter->m_Weapon = WEAPON_NINJA; + pCharacter->m_AmmoCount = 10; + } + + if(m_pPlayer->GetCID() == SnappingClient || SnappingClient == -1 || + (!g_Config.m_SvStrictSpectateMode && m_pPlayer->GetCID() == GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID)) + { + pCharacter->m_Health = m_Health; + pCharacter->m_Armor = m_Armor; + if(m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo > 0) + //pCharacter->m_AmmoCount = m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo; + pCharacter->m_AmmoCount = (!m_FreezeTime)?m_aWeapons[m_Core.m_ActiveWeapon].m_Ammo:0; + } + + if(GetPlayer()->m_Afk || GetPlayer()->m_Paused) + pCharacter->m_Emote = EMOTE_BLINK; + + if(pCharacter->m_Emote == EMOTE_NORMAL) + { + if(250 - ((Server()->Tick() - m_LastAction)%(250)) < 5) + pCharacter->m_Emote = EMOTE_BLINK; + } + + if(m_pPlayer->m_Halloween) + { + if(1200 - ((Server()->Tick() - m_LastAction)%(1200)) < 5) + { + GameServer()->SendEmoticon(m_pPlayer->GetCID(), EMOTICON_GHOST); + } + } + + pCharacter->m_PlayerFlags = GetPlayer()->m_PlayerFlags; +} + +int CCharacter::NetworkClipped(int SnappingClient) +{ + return NetworkClipped(SnappingClient, m_Pos); +} + +int CCharacter::NetworkClipped(int SnappingClient, vec2 CheckPos) +{ + if(SnappingClient == -1 || GameServer()->m_apPlayers[SnappingClient]->m_ShowAll) + 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) > 4000.0f) + return 1; + return 0; +} + +// DDRace + +bool CCharacter::CanCollide(int ClientID) +{ + return Teams()->m_Core.CanCollide(GetPlayer()->GetCID(), ClientID); +} +bool CCharacter::SameTeam(int ClientID) +{ + return Teams()->m_Core.SameTeam(GetPlayer()->GetCID(), ClientID); +} + +int CCharacter::Team() +{ + return Teams()->m_Core.Team(m_pPlayer->GetCID()); +} + +CGameTeams* CCharacter::Teams() +{ + return &((CGameControllerWarioWare*)GameServer()->m_pController)->m_Teams; +} + +void CCharacter::HandleBroadcast() +{ + CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); + + if(m_DDRaceState == DDRACE_STARTED && m_CpLastBroadcast != m_CpActive && + m_CpActive > -1 && m_CpTick > Server()->Tick() && m_pPlayer->m_ClientVersion == VERSION_VANILLA && + pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) + { + char aBroadcast[128]; + float Diff = m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive]; + str_format(aBroadcast, sizeof(aBroadcast), "Checkpoint | Diff : %+5.2f", Diff); + GameServer()->SendBroadcast(aBroadcast, m_pPlayer->GetCID()); + m_CpLastBroadcast = m_CpActive; + m_LastBroadcast = Server()->Tick(); + } + else if ((m_pPlayer->m_TimerType == 1 || m_pPlayer->m_TimerType == 2) && m_DDRaceState == DDRACE_STARTED && m_LastBroadcast + Server()->TickSpeed() * g_Config.m_SvTimeInBroadcastInterval <= Server()->Tick()) + { + char aBuftime[64]; + int IntTime = (int)((float)(Server()->Tick() - m_StartTime) / ((float)Server()->TickSpeed())); + str_format(aBuftime, sizeof(aBuftime), "%s%d:%s%d", ((IntTime/60) > 9)?"":"0", IntTime/60, ((IntTime%60) > 9)?"":"0", IntTime%60); + GameServer()->SendBroadcast(aBuftime, m_pPlayer->GetCID()); + m_CpLastBroadcast = m_CpActive; + m_LastBroadcast = Server()->Tick(); + } +} + +void CCharacter::HandleSkippableTiles(int Index) +{ + // 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 || + GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || + GameServer()->Collision()->GetFCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || + GameServer()->Collision()->GetFCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || + GameServer()->Collision()->GetFCollisionAt(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) && + !m_Super && !(Team() && Teams()->TeeFinished(m_pPlayer->GetCID()))) + { + CGameControllerWarioWare* controller = (CGameControllerWarioWare*)GameServer()->m_pController; + float timeLeft = (controller->getTimeLength() - controller->getTimer()) / 1000.f; + + Die(m_pPlayer->GetCID(), WEAPON_WORLD, timeLeft); + return; + } + + if (GameLayerClipped(m_Pos)) + { + Die(m_pPlayer->GetCID(), WEAPON_WORLD); + return; + } + + if(Index < 0) + return; + + // handle speedup tiles + if(GameServer()->Collision()->IsSpeedup(Index)) + { + vec2 Direction, MaxVel, TempVel = m_Core.m_Vel; + int Force, MaxSpeed = 0; + float TeeAngle, SpeederAngle, DiffAngle, SpeedLeft, TeeSpeed; + GameServer()->Collision()->GetSpeedup(Index, &Direction, &Force, &MaxSpeed); + if(Force == 255 && MaxSpeed) + { + m_Core.m_Vel = Direction * (MaxSpeed/5); + } + else + { + if(MaxSpeed > 0 && MaxSpeed < 5) MaxSpeed = 5; + //dbg_msg("speedup tile start","Direction %f %f, Force %d, Max Speed %d", (Direction).x,(Direction).y, Force, MaxSpeed); + if(MaxSpeed > 0) + { + if(Direction.x > 0.0000001f) + SpeederAngle = -atan(Direction.y / Direction.x); + else if(Direction.x < 0.0000001f) + SpeederAngle = atan(Direction.y / Direction.x) + 2.0f * asin(1.0f); + else if(Direction.y > 0.0000001f) + SpeederAngle = asin(1.0f); + else + SpeederAngle = asin(-1.0f); + + if(SpeederAngle < 0) + SpeederAngle = 4.0f * asin(1.0f) + SpeederAngle; + + if(TempVel.x > 0.0000001f) + TeeAngle = -atan(TempVel.y / TempVel.x); + else if(TempVel.x < 0.0000001f) + TeeAngle = atan(TempVel.y / TempVel.x) + 2.0f * asin(1.0f); + else if(TempVel.y > 0.0000001f) + TeeAngle = asin(1.0f); + else + TeeAngle = asin(-1.0f); + + if(TeeAngle < 0) + TeeAngle = 4.0f * asin(1.0f) + TeeAngle; + + TeeSpeed = sqrt(pow(TempVel.x, 2) + pow(TempVel.y, 2)); + + DiffAngle = SpeederAngle - TeeAngle; + SpeedLeft = MaxSpeed / 5.0f - cos(DiffAngle) * TeeSpeed; + //dbg_msg("speedup tile debug","MaxSpeed %i, TeeSpeed %f, SpeedLeft %f, SpeederAngle %f, TeeAngle %f", MaxSpeed, TeeSpeed, SpeedLeft, SpeederAngle, TeeAngle); + if(abs((int)SpeedLeft) > Force && SpeedLeft > 0.0000001f) + TempVel += Direction * Force; + else if(abs((int)SpeedLeft) > Force) + TempVel += Direction * -Force; + else + TempVel += Direction * SpeedLeft; + } + else + TempVel += Direction * Force; + + if(TempVel.x > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA))) + TempVel.x = 0; + if(TempVel.x < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA))) + TempVel.x = 0; + if(TempVel.y < 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA))) + TempVel.y = 0; + if(TempVel.y > 0 && ((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA))) + TempVel.y = 0; + m_Core.m_Vel = TempVel; + //dbg_msg("speedup tile end","(Direction*Force) %f %f m_Core.m_Vel%f %f",(Direction*Force).x,(Direction*Force).y,m_Core.m_Vel.x,m_Core.m_Vel.y); + //dbg_msg("speedup tile end","Direction %f %f, Force %d, Max Speed %d", (Direction).x,(Direction).y, Force, MaxSpeed); + } + } +} + +void CCharacter::HandleTiles(int Index) +{ + CGameControllerWarioWare* Controller = (CGameControllerWarioWare*)GameServer()->m_pController; + int MapIndex = Index; + //int PureMapIndex = GameServer()->Collision()->GetPureMapIndex(m_Pos); + float Offset = 4.0f; + int MapIndexL = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x + (m_ProximityRadius / 2) + Offset, m_Pos.y)); + int MapIndexR = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x - (m_ProximityRadius / 2) - Offset, m_Pos.y)); + int MapIndexT = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x, m_Pos.y + (m_ProximityRadius / 2) + Offset)); + int MapIndexB = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x, m_Pos.y - (m_ProximityRadius / 2) - Offset)); + //dbg_msg("","N%d L%d R%d B%d T%d",MapIndex,MapIndexL,MapIndexR,MapIndexB,MapIndexT); + m_TileIndex = GameServer()->Collision()->GetTileIndex(MapIndex); + m_TileFlags = GameServer()->Collision()->GetTileFlags(MapIndex); + m_TileIndexL = GameServer()->Collision()->GetTileIndex(MapIndexL); + m_TileFlagsL = GameServer()->Collision()->GetTileFlags(MapIndexL); + m_TileIndexR = GameServer()->Collision()->GetTileIndex(MapIndexR); + m_TileFlagsR = GameServer()->Collision()->GetTileFlags(MapIndexR); + m_TileIndexB = GameServer()->Collision()->GetTileIndex(MapIndexB); + m_TileFlagsB = GameServer()->Collision()->GetTileFlags(MapIndexB); + m_TileIndexT = GameServer()->Collision()->GetTileIndex(MapIndexT); + m_TileFlagsT = GameServer()->Collision()->GetTileFlags(MapIndexT); + m_TileFIndex = GameServer()->Collision()->GetFTileIndex(MapIndex); + m_TileFFlags = GameServer()->Collision()->GetFTileFlags(MapIndex); + m_TileFIndexL = GameServer()->Collision()->GetFTileIndex(MapIndexL); + m_TileFFlagsL = GameServer()->Collision()->GetFTileFlags(MapIndexL); + m_TileFIndexR = GameServer()->Collision()->GetFTileIndex(MapIndexR); + m_TileFFlagsR = GameServer()->Collision()->GetFTileFlags(MapIndexR); + m_TileFIndexB = GameServer()->Collision()->GetFTileIndex(MapIndexB); + m_TileFFlagsB = GameServer()->Collision()->GetFTileFlags(MapIndexB); + m_TileFIndexT = GameServer()->Collision()->GetFTileIndex(MapIndexT); + m_TileFFlagsT = GameServer()->Collision()->GetFTileFlags(MapIndexT);// + m_TileSIndex = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndex)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileIndex(MapIndex) : 0 : 0; + m_TileSFlags = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndex)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileFlags(MapIndex) : 0 : 0; + m_TileSIndexL = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexL)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileIndex(MapIndexL) : 0 : 0; + m_TileSFlagsL = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexL)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileFlags(MapIndexL) : 0 : 0; + m_TileSIndexR = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexR)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileIndex(MapIndexR) : 0 : 0; + m_TileSFlagsR = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexR)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileFlags(MapIndexR) : 0 : 0; + m_TileSIndexB = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexB)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileIndex(MapIndexB) : 0 : 0; + m_TileSFlagsB = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexB)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileFlags(MapIndexB) : 0 : 0; + m_TileSIndexT = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexT)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileIndex(MapIndexT) : 0 : 0; + m_TileSFlagsT = (GameServer()->Collision()->m_pSwitchers && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetDTileNumber(MapIndexT)].m_Status[Team()])?(Team() != TEAM_SUPER)? GameServer()->Collision()->GetDTileFlags(MapIndexT) : 0 : 0; + //dbg_msg("Tiles","%d, %d, %d, %d, %d", m_TileSIndex, m_TileSIndexL, m_TileSIndexR, m_TileSIndexB, m_TileSIndexT); + //Sensitivity + int S1 = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f)); + int S2 = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x + m_ProximityRadius / 3.f, m_Pos.y + m_ProximityRadius / 3.f)); + int S3 = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x - m_ProximityRadius / 3.f, m_Pos.y - m_ProximityRadius / 3.f)); + int S4 = GameServer()->Collision()->GetPureMapIndex(vec2(m_Pos.x - m_ProximityRadius / 3.f, m_Pos.y + m_ProximityRadius / 3.f)); + int Tile1 = GameServer()->Collision()->GetTileIndex(S1); + int Tile2 = GameServer()->Collision()->GetTileIndex(S2); + int Tile3 = GameServer()->Collision()->GetTileIndex(S3); + int Tile4 = GameServer()->Collision()->GetTileIndex(S4); + int FTile1 = GameServer()->Collision()->GetFTileIndex(S1); + int FTile2 = GameServer()->Collision()->GetFTileIndex(S2); + int FTile3 = GameServer()->Collision()->GetFTileIndex(S3); + int FTile4 = GameServer()->Collision()->GetFTileIndex(S4); + //dbg_msg("","N%d L%d R%d B%d T%d",m_TileIndex,m_TileIndexL,m_TileIndexR,m_TileIndexB,m_TileIndexT); + //dbg_msg("","N%d L%d R%d B%d T%d",m_TileFIndex,m_TileFIndexL,m_TileFIndexR,m_TileFIndexB,m_TileFIndexT); + if(Index < 0) + { + m_LastRefillJumps = false; + m_LastPenalty = false; + m_LastBonus = false; + return; + } + int cp = GameServer()->Collision()->IsCheckpoint(MapIndex); + if(cp != -1 && m_DDRaceState == DDRACE_STARTED && cp > m_CpActive) + { + m_CpActive = cp; + m_CpCurrent[cp] = m_Time; + m_CpTick = Server()->Tick() + Server()->TickSpeed() * 2; + if(m_pPlayer->m_ClientVersion >= VERSION_DDRACE) { + CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); + CNetMsg_Sv_DDRaceTime Msg; + Msg.m_Time = (int)m_Time; + Msg.m_Check = 0; + Msg.m_Finish = 0; + + if(m_CpActive != -1 && m_CpTick > Server()->Tick()) + { + if(pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) + { + float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive])*100; + Msg.m_Check = (int)Diff; + } + } + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); + } + } + int cpf = GameServer()->Collision()->IsFCheckpoint(MapIndex); + if(cpf != -1 && m_DDRaceState == DDRACE_STARTED && cpf > m_CpActive) + { + m_CpActive = cpf; + m_CpCurrent[cpf] = m_Time; + m_CpTick = Server()->Tick() + Server()->TickSpeed()*2; + if(m_pPlayer->m_ClientVersion >= VERSION_DDRACE) { + CPlayerData *pData = GameServer()->Score()->PlayerData(m_pPlayer->GetCID()); + CNetMsg_Sv_DDRaceTime Msg; + Msg.m_Time = (int)m_Time; + Msg.m_Check = 0; + Msg.m_Finish = 0; + + if(m_CpActive != -1 && m_CpTick > Server()->Tick()) + { + if(pData->m_BestTime && pData->m_aBestCpTime[m_CpActive] != 0) + { + float Diff = (m_CpCurrent[m_CpActive] - pData->m_aBestCpTime[m_CpActive])*100; + Msg.m_Check = (int)Diff; + } + } + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, m_pPlayer->GetCID()); + } + } + int tcp = GameServer()->Collision()->IsTCheckpoint(MapIndex); + if(tcp) + m_TeleCheckpoint = tcp; + + // start + if(((m_TileIndex == TILE_BEGIN) || (m_TileFIndex == TILE_BEGIN) || FTile1 == TILE_BEGIN || FTile2 == TILE_BEGIN || FTile3 == TILE_BEGIN || FTile4 == TILE_BEGIN || Tile1 == TILE_BEGIN || Tile2 == TILE_BEGIN || Tile3 == TILE_BEGIN || Tile4 == TILE_BEGIN) && (m_DDRaceState == DDRACE_NONE || m_DDRaceState == DDRACE_FINISHED || (m_DDRaceState == DDRACE_STARTED && !Team()))) + { + bool CanBegin = true; + if(g_Config.m_SvResetPickups) + { + for (int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; ++i) + { + m_aWeapons[i].m_Got = false; + if(m_Core.m_ActiveWeapon == i) + m_Core.m_ActiveWeapon = WEAPON_GUN; + } + } + if(g_Config.m_SvTeam == 2 && (Team() == TEAM_FLOCK || Teams()->Count(Team()) <= 1)) + { + if(m_LastStartWarning < Server()->Tick() - 3 * Server()->TickSpeed()) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"Server admin requires you to be in a team and with other tees to start"); + m_LastStartWarning = Server()->Tick(); + } + Die(GetPlayer()->GetCID(), WEAPON_WORLD); + CanBegin = false; + } + if(CanBegin) + { + Teams()->OnCharacterStart(m_pPlayer->GetCID()); + m_CpActive = -2; + } else { + + } + + + } + + // finish + if(((m_TileIndex == TILE_END) || (m_TileFIndex == TILE_END) || FTile1 == TILE_END || FTile2 == TILE_END || FTile3 == TILE_END || FTile4 == TILE_END || Tile1 == TILE_END || Tile2 == TILE_END || Tile3 == TILE_END || Tile4 == TILE_END) && m_DDRaceState == DDRACE_STARTED) + Controller->m_Teams.OnCharacterFinish(m_pPlayer->GetCID()); + + // freeze + if(((m_TileIndex == TILE_FREEZE) || (m_TileFIndex == TILE_FREEZE)) && !m_Super && !m_DeepFreeze) + Freeze(); + else if(((m_TileIndex == TILE_UNFREEZE) || (m_TileFIndex == TILE_UNFREEZE)) && !m_DeepFreeze) + UnFreeze(); + + // deep freeze + if(((m_TileIndex == TILE_DFREEZE) || (m_TileFIndex == TILE_DFREEZE)) && !m_Super && !m_DeepFreeze) + m_DeepFreeze = true; + else if(((m_TileIndex == TILE_DUNFREEZE) || (m_TileFIndex == TILE_DUNFREEZE)) && !m_Super && m_DeepFreeze) + m_DeepFreeze = false; + + // endless hook + if(((m_TileIndex == TILE_EHOOK_START) || (m_TileFIndex == TILE_EHOOK_START)) && !m_EndlessHook) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Endless hook has been activated"); + m_EndlessHook = true; + } + else if(((m_TileIndex == TILE_EHOOK_END) || (m_TileFIndex == TILE_EHOOK_END)) && m_EndlessHook) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "Endless hook has been deactivated"); + m_EndlessHook = false; + } + + // hit others + if(((m_TileIndex == TILE_HIT_END) || (m_TileFIndex == TILE_HIT_END)) && m_Hit != (DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_RIFLE|DISABLE_HIT_SHOTGUN)) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't hit others"); + m_Hit = DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_RIFLE|DISABLE_HIT_SHOTGUN; + m_NeededFaketuning |= FAKETUNE_NOHAMMER; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if(((m_TileIndex == TILE_HIT_START) || (m_TileFIndex == TILE_HIT_START)) && m_Hit != HIT_ALL) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can hit others"); + m_Hit = HIT_ALL; + m_NeededFaketuning &= ~FAKETUNE_NOHAMMER; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + + // collide with others + if(((m_TileIndex == TILE_NPC_END) || (m_TileFIndex == TILE_NPC_END)) && m_Core.m_Collision) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't collide with others"); + m_Core.m_Collision = false; + m_NeededFaketuning |= FAKETUNE_NOCOLL; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if(((m_TileIndex == TILE_NPC_START) || (m_TileFIndex == TILE_NPC_START)) && !m_Core.m_Collision) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can collide with others"); + m_Core.m_Collision = true; + m_NeededFaketuning &= ~FAKETUNE_NOCOLL; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + + // hook others + if(((m_TileIndex == TILE_NPH_END) || (m_TileFIndex == TILE_NPH_END)) && m_Core.m_Hook) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You can't hook others"); + m_Core.m_Hook = false; + m_NeededFaketuning |= FAKETUNE_NOHOOK; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if(((m_TileIndex == TILE_NPH_START) || (m_TileFIndex == TILE_NPH_START)) && !m_Core.m_Hook) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can hook others"); + m_Core.m_Hook = true; + m_NeededFaketuning &= ~FAKETUNE_NOHOOK; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + + // unlimited air jumps + if(((m_TileIndex == TILE_SUPER_START) || (m_TileFIndex == TILE_SUPER_START)) && !m_SuperJump) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You have unlimited air jumps"); + m_SuperJump = true; + if (m_Core.m_Jumps == 0) + { + m_NeededFaketuning &= ~FAKETUNE_NOJUMP; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + } + else if(((m_TileIndex == TILE_SUPER_END) || (m_TileFIndex == TILE_SUPER_END)) && m_SuperJump) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You don't have unlimited air jumps"); + m_SuperJump = false; + if (m_Core.m_Jumps == 0) + { + m_NeededFaketuning |= FAKETUNE_NOJUMP; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + } + + // walljump + if((m_TileIndex == TILE_WALLJUMP) || (m_TileFIndex == TILE_WALLJUMP)) + { + if(m_Core.m_Vel.y > 0 && m_Core.m_Colliding && m_Core.m_LeftWall) + { + m_Core.m_LeftWall = false; + m_Core.m_JumpedTotal = m_Core.m_Jumps - 1; + m_Core.m_Jumped = 1; + } + } + + // jetpack gun + if(((m_TileIndex == TILE_JETPACK_START) || (m_TileFIndex == TILE_JETPACK_START)) && !m_Jetpack) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You have a jetpack gun"); + m_Jetpack = true; + } + else if(((m_TileIndex == TILE_JETPACK_END) || (m_TileFIndex == TILE_JETPACK_END)) && m_Jetpack) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You lost your jetpack gun"); + m_Jetpack = false; + } + + // unlock team + else if((m_TileIndex == TILE_UNLOCK_TEAM) || (m_TileFIndex == TILE_UNLOCK_TEAM)) + { + Teams()->SetTeamLock(Team(), false); + } + + // solo part + if(((m_TileIndex == TILE_SOLO_START) || (m_TileFIndex == TILE_SOLO_START)) && !Teams()->m_Core.GetSolo(m_pPlayer->GetCID())) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You are now in a solo part."); + SetSolo(true); + } + else if(((m_TileIndex == TILE_SOLO_END) || (m_TileFIndex == TILE_SOLO_END)) && Teams()->m_Core.GetSolo(m_pPlayer->GetCID())) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(), "You are now out of the solo part."); + SetSolo(false); + } + + // refill jumps + if(((m_TileIndex == TILE_REFILL_JUMPS) || (m_TileFIndex == TILE_REFILL_JUMPS)) && !m_LastRefillJumps) + { + m_Core.m_JumpedTotal = 0; + m_Core.m_Jumped = 0; + m_LastRefillJumps = true; + } + if((m_TileIndex != TILE_REFILL_JUMPS) && (m_TileFIndex != TILE_REFILL_JUMPS)) + { + m_LastRefillJumps = false; + } + + // stopper + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_270) || (m_TileIndexL == TILE_STOP && m_TileFlagsL == ROTATION_270) || (m_TileIndexL == TILE_STOPS && (m_TileFlagsL == ROTATION_90 || m_TileFlagsL ==ROTATION_270)) || (m_TileIndexL == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_270) || (m_TileFIndexL == TILE_STOP && m_TileFFlagsL == ROTATION_270) || (m_TileFIndexL == TILE_STOPS && (m_TileFFlagsL == ROTATION_90 || m_TileFFlagsL == ROTATION_270)) || (m_TileFIndexL == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_270) || (m_TileSIndexL == TILE_STOP && m_TileSFlagsL == ROTATION_270) || (m_TileSIndexL == TILE_STOPS && (m_TileSFlagsL == ROTATION_90 || m_TileSFlagsL == ROTATION_270)) || (m_TileSIndexL == TILE_STOPA)) && m_Core.m_Vel.x > 0) + { + if((int)GameServer()->Collision()->GetPos(MapIndexL).x) + if((int)GameServer()->Collision()->GetPos(MapIndexL).x < (int)m_Core.m_Pos.x) + m_Core.m_Pos = m_PrevPos; + m_Core.m_Vel.x = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_90) || (m_TileIndexR == TILE_STOP && m_TileFlagsR == ROTATION_90) || (m_TileIndexR == TILE_STOPS && (m_TileFlagsR == ROTATION_90 || m_TileFlagsR == ROTATION_270)) || (m_TileIndexR == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_90) || (m_TileFIndexR == TILE_STOP && m_TileFFlagsR == ROTATION_90) || (m_TileFIndexR == TILE_STOPS && (m_TileFFlagsR == ROTATION_90 || m_TileFFlagsR == ROTATION_270)) || (m_TileFIndexR == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_90) || (m_TileSIndexR == TILE_STOP && m_TileSFlagsR == ROTATION_90) || (m_TileSIndexR == TILE_STOPS && (m_TileSFlagsR == ROTATION_90 || m_TileSFlagsR == ROTATION_270)) || (m_TileSIndexR == TILE_STOPA)) && m_Core.m_Vel.x < 0) + { + if((int)GameServer()->Collision()->GetPos(MapIndexR).x) + if((int)GameServer()->Collision()->GetPos(MapIndexR).x > (int)m_Core.m_Pos.x) + m_Core.m_Pos = m_PrevPos; + m_Core.m_Vel.x = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_180) || (m_TileIndexB == TILE_STOP && m_TileFlagsB == ROTATION_180) || (m_TileIndexB == TILE_STOPS && (m_TileFlagsB == ROTATION_0 || m_TileFlagsB == ROTATION_180)) || (m_TileIndexB == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_180) || (m_TileFIndexB == TILE_STOP && m_TileFFlagsB == ROTATION_180) || (m_TileFIndexB == TILE_STOPS && (m_TileFFlagsB == ROTATION_0 || m_TileFFlagsB == ROTATION_180)) || (m_TileFIndexB == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_180) || (m_TileSIndexB == TILE_STOP && m_TileSFlagsB == ROTATION_180) || (m_TileSIndexB == TILE_STOPS && (m_TileSFlagsB == ROTATION_0 || m_TileSFlagsB == ROTATION_180)) || (m_TileSIndexB == TILE_STOPA)) && m_Core.m_Vel.y < 0) + { + if((int)GameServer()->Collision()->GetPos(MapIndexB).y) + if((int)GameServer()->Collision()->GetPos(MapIndexB).y > (int)m_Core.m_Pos.y) + m_Core.m_Pos = m_PrevPos; + m_Core.m_Vel.y = 0; + } + if(((m_TileIndex == TILE_STOP && m_TileFlags == ROTATION_0) || (m_TileIndexT == TILE_STOP && m_TileFlagsT == ROTATION_0) || (m_TileIndexT == TILE_STOPS && (m_TileFlagsT == ROTATION_0 || m_TileFlagsT == ROTATION_180)) || (m_TileIndexT == TILE_STOPA) || (m_TileFIndex == TILE_STOP && m_TileFFlags == ROTATION_0) || (m_TileFIndexT == TILE_STOP && m_TileFFlagsT == ROTATION_0) || (m_TileFIndexT == TILE_STOPS && (m_TileFFlagsT == ROTATION_0 || m_TileFFlagsT == ROTATION_180)) || (m_TileFIndexT == TILE_STOPA) || (m_TileSIndex == TILE_STOP && m_TileSFlags == ROTATION_0) || (m_TileSIndexT == TILE_STOP && m_TileSFlagsT == ROTATION_0) || (m_TileSIndexT == TILE_STOPS && (m_TileSFlagsT == ROTATION_0 || m_TileSFlagsT == ROTATION_180)) || (m_TileSIndexT == TILE_STOPA)) && m_Core.m_Vel.y > 0) + { + //dbg_msg("","%f %f",GameServer()->Collision()->GetPos(MapIndex).y,m_Core.m_Pos.y); + if((int)GameServer()->Collision()->GetPos(MapIndexT).y) + if((int)GameServer()->Collision()->GetPos(MapIndexT).y < (int)m_Core.m_Pos.y) + m_Core.m_Pos = m_PrevPos; + m_Core.m_Vel.y = 0; + m_Core.m_Jumped = 0; + m_Core.m_JumpedTotal = 0; + } + + if(((m_TileIndex == TILE_WARIOWARE_WIN) || (m_TileFIndex == TILE_WARIOWARE_WIN))) + { + Controller->winMicroGame(m_pPlayer->GetCID()); + } + + // handle switch tiles + if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHOPEN && Team() != TEAM_SUPER) + { + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = true; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = 0; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHOPEN; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDOPEN && Team() != TEAM_SUPER) + { + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = true; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex)*Server()->TickSpeed() ; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDOPEN; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHTIMEDCLOSE && Team() != TEAM_SUPER) + { + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = false; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = Server()->Tick() + 1 + GameServer()->Collision()->GetSwitchDelay(MapIndex)*Server()->TickSpeed(); + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHTIMEDCLOSE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_SWITCHCLOSE && Team() != TEAM_SUPER) + { + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()] = false; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_EndTick[Team()] = 0; + GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Type[Team()] = TILE_SWITCHCLOSE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_FREEZE && Team() != TEAM_SUPER) + { + if(GameServer()->Collision()->GetSwitchNumber(MapIndex) == 0 || GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()]) + Freeze(GameServer()->Collision()->GetSwitchDelay(MapIndex)); + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_DFREEZE && Team() != TEAM_SUPER && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()]) + { + m_DeepFreeze = true; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_DUNFREEZE && Team() != TEAM_SUPER && GameServer()->Collision()->m_pSwitchers[GameServer()->Collision()->GetSwitchNumber(MapIndex)].m_Status[Team()]) + { + m_DeepFreeze = false; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_START && m_Hit&DISABLE_HIT_HAMMER && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_HAMMER) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can hammer hit others"); + m_Hit &= ~DISABLE_HIT_HAMMER; + m_NeededFaketuning &= ~FAKETUNE_NOHAMMER; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_END && !(m_Hit&DISABLE_HIT_HAMMER) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_HAMMER) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't hammer hit others"); + m_Hit |= DISABLE_HIT_HAMMER; + m_NeededFaketuning |= FAKETUNE_NOHAMMER; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_START && m_Hit&DISABLE_HIT_SHOTGUN && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_SHOTGUN) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with shotgun"); + m_Hit &= ~DISABLE_HIT_SHOTGUN; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_END && !(m_Hit&DISABLE_HIT_SHOTGUN) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_SHOTGUN) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with shotgun"); + m_Hit |= DISABLE_HIT_SHOTGUN; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_START && m_Hit&DISABLE_HIT_GRENADE && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_GRENADE) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with grenade"); + m_Hit &= ~DISABLE_HIT_GRENADE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_END && !(m_Hit&DISABLE_HIT_GRENADE) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_GRENADE) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with grenade"); + m_Hit |= DISABLE_HIT_GRENADE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_START && m_Hit&DISABLE_HIT_RIFLE && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_RIFLE) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can shoot others with rifle"); + m_Hit &= ~DISABLE_HIT_RIFLE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_HIT_END && !(m_Hit&DISABLE_HIT_RIFLE) && GameServer()->Collision()->GetSwitchDelay(MapIndex) == WEAPON_RIFLE) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"You can't shoot others with rifle"); + m_Hit |= DISABLE_HIT_RIFLE; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_JUMP) + { + int newJumps = GameServer()->Collision()->GetSwitchDelay(MapIndex); + + if (newJumps != m_Core.m_Jumps) + { + char aBuf[256]; + if(newJumps == 1) + str_format(aBuf, sizeof(aBuf), "You can jump %d time", newJumps); + else + str_format(aBuf, sizeof(aBuf), "You can jump %d times", newJumps); + GameServer()->SendChatTarget(GetPlayer()->GetCID(),aBuf); + + if (newJumps == 0 && !m_SuperJump) + { + m_NeededFaketuning |= FAKETUNE_NOJUMP; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + else if (m_Core.m_Jumps == 0) + { + m_NeededFaketuning &= ~FAKETUNE_NOJUMP; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } + + m_Core.m_Jumps = newJumps; + } + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_PENALTY && !m_LastPenalty) + { + int min = GameServer()->Collision()->GetSwitchDelay(MapIndex); + int sec = GameServer()->Collision()->GetSwitchNumber(MapIndex); + int Team = Teams()->m_Core.Team(m_Core.m_Id); + + m_StartTime -= (min * 60 + sec) * Server()->TickSpeed(); + + if (Team != TEAM_FLOCK && Team != TEAM_SUPER) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(Teams()->m_Core.Team(i) == Team && i != m_Core.m_Id && GameServer()->m_apPlayers[i]) + { + CCharacter* pChar = GameServer()->m_apPlayers[i]->GetCharacter(); + + if (pChar) + pChar->m_StartTime = m_StartTime; + } + } + } + + m_LastPenalty = true; + } + else if(GameServer()->Collision()->IsSwitch(MapIndex) == TILE_BONUS && !m_LastBonus) + { + int min = GameServer()->Collision()->GetSwitchDelay(MapIndex); + int sec = GameServer()->Collision()->GetSwitchNumber(MapIndex); + int Team = Teams()->m_Core.Team(m_Core.m_Id); + + m_StartTime += (min * 60 + sec) * Server()->TickSpeed(); + if (m_StartTime > Server()->Tick()) + m_StartTime = Server()->Tick(); + + if (Team != TEAM_FLOCK && Team != TEAM_SUPER) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(Teams()->m_Core.Team(i) == Team && i != m_Core.m_Id && GameServer()->m_apPlayers[i]) + { + CCharacter* pChar = GameServer()->m_apPlayers[i]->GetCharacter(); + + if (pChar) + pChar->m_StartTime = m_StartTime; + } + } + } + + m_LastBonus = true; + } + + if(GameServer()->Collision()->IsSwitch(MapIndex) != TILE_PENALTY) + { + m_LastPenalty = false; + } + + if(GameServer()->Collision()->IsSwitch(MapIndex) != TILE_BONUS) + { + m_LastBonus = false; + } + + int z = GameServer()->Collision()->IsTeleport(MapIndex); + if(!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons && z && Controller->m_TeleOuts[z-1].size()) + { + if (m_Super) + return; + int Num = Controller->m_TeleOuts[z-1].size(); + m_Core.m_Pos = Controller->m_TeleOuts[z-1][(!Num)?Num:rand() % Num]; + if(!g_Config.m_SvTeleportHoldHook) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + m_Core.m_HookPos = m_Core.m_Pos; + } + if(g_Config.m_SvTeleportLoseWeapons) + { + for(int i=WEAPON_SHOTGUN;i<NUM_WEAPONS-1;i++) + m_aWeapons[i].m_Got = false; + } + return; + } + int evilz = GameServer()->Collision()->IsEvilTeleport(MapIndex); + if(evilz && Controller->m_TeleOuts[evilz-1].size()) + { + if (m_Super) + return; + int Num = Controller->m_TeleOuts[evilz-1].size(); + m_Core.m_Pos = Controller->m_TeleOuts[evilz-1][(!Num)?Num:rand() % Num]; + if (!g_Config.m_SvOldTeleportHook && !g_Config.m_SvOldTeleportWeapons) + { + m_Core.m_Vel = vec2(0,0); + + if(!g_Config.m_SvTeleportHoldHook) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + GameWorld()->ReleaseHooked(GetPlayer()->GetCID()); + m_Core.m_HookPos = m_Core.m_Pos; + } + if(g_Config.m_SvTeleportLoseWeapons) + { + for(int i=WEAPON_SHOTGUN;i<NUM_WEAPONS-1;i++) + m_aWeapons[i].m_Got = false; + } + } + return; + } + if(GameServer()->Collision()->IsCheckEvilTeleport(MapIndex)) + { + if (m_Super) + return; + // first check if there is a TeleCheckOut for the current recorded checkpoint, if not check previous checkpoints + for(int k=m_TeleCheckpoint-1; k >= 0; k--) + { + if(Controller->m_TeleCheckOuts[k].size()) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + int Num = Controller->m_TeleCheckOuts[k].size(); + m_Core.m_Pos = Controller->m_TeleCheckOuts[k][(!Num)?Num:rand() % Num]; + GameWorld()->ReleaseHooked(GetPlayer()->GetCID()); + m_Core.m_Vel = vec2(0,0); + m_Core.m_HookPos = m_Core.m_Pos; + return; + } + } + // if no checkpointout have been found (or if there no recorded checkpoint), teleport to start + vec2 SpawnPos; + if(GameServer()->m_pController->CanSpawn(m_pPlayer->GetTeam(), &SpawnPos)) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + m_Core.m_Pos = SpawnPos; + GameWorld()->ReleaseHooked(GetPlayer()->GetCID()); + m_Core.m_Vel = vec2(0,0); + m_Core.m_HookPos = m_Core.m_Pos; + } + return; + } + if(GameServer()->Collision()->IsCheckTeleport(MapIndex)) + { + if (m_Super) + return; + // first check if there is a TeleCheckOut for the current recorded checkpoint, if not check previous checkpoints + for(int k=m_TeleCheckpoint-1; k >= 0; k--) + { + if(Controller->m_TeleCheckOuts[k].size()) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + int Num = Controller->m_TeleCheckOuts[k].size(); + m_Core.m_Pos = Controller->m_TeleCheckOuts[k][(!Num)?Num:rand() % Num]; + m_Core.m_HookPos = m_Core.m_Pos; + return; + } + } + // if no checkpointout have been found (or if there no recorded checkpoint), teleport to start + vec2 SpawnPos; + if(GameServer()->m_pController->CanSpawn(m_pPlayer->GetTeam(), &SpawnPos)) + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + m_Core.m_Pos = SpawnPos; + m_Core.m_HookPos = m_Core.m_Pos; + } + return; + } +} + +void CCharacter::HandleTuneLayer() +{ + + m_TuneZoneOld = m_TuneZone; + int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_Pos); + m_TuneZone = GameServer()->Collision()->IsTune(CurrentIndex); + + if(m_TuneZone) + m_Core.m_pWorld->m_Tuning[g_Config.m_ClDummy] = GameServer()->TuningList()[m_TuneZone]; // throw tunings from specific zone into gamecore + else + m_Core.m_pWorld->m_Tuning[g_Config.m_ClDummy] = *GameServer()->Tuning(); + + if (m_TuneZone != m_TuneZoneOld) // dont send tunigs all the time + { + // send zone msgs + SendZoneMsgs(); + } +} + +void CCharacter::SendZoneMsgs() +{ + // send zone leave msg + if (m_TuneZoneOld >= 0 && GameServer()->m_ZoneLeaveMsg[m_TuneZoneOld]) // m_TuneZoneOld >= 0: avoid zone leave msgs on spawn + { + const char* cur = GameServer()->m_ZoneLeaveMsg[m_TuneZoneOld]; + const char* pos; + while ((pos = str_find(cur, "\\n"))) + { + char aBuf[256]; + str_copy(aBuf, cur, pos - cur + 1); + aBuf[pos - cur + 1] = '\0'; + cur = pos + 2; + GameServer()->SendChatTarget(m_pPlayer->GetCID(), aBuf); + } + GameServer()->SendChatTarget(m_pPlayer->GetCID(), cur); + } + // send zone enter msg + if (GameServer()->m_ZoneEnterMsg[m_TuneZone]) + { + const char* cur = GameServer()->m_ZoneEnterMsg[m_TuneZone]; + const char* pos; + while ((pos = str_find(cur, "\\n"))) + { + char aBuf[256]; + str_copy(aBuf, cur, pos - cur + 1); + aBuf[pos - cur + 1] = '\0'; + cur = pos + 2; + GameServer()->SendChatTarget(m_pPlayer->GetCID(), aBuf); + } + GameServer()->SendChatTarget(m_pPlayer->GetCID(), cur); + } +} + +void CCharacter::DDRaceTick() +{ + m_Armor=(m_FreezeTime >= 0)?10-(m_FreezeTime/15):0; + if(m_Input.m_Direction != 0 || m_Input.m_Jump != 0) + m_LastMove = Server()->Tick(); + + if(m_FreezeTime > 0 || m_FreezeTime == -1) + { + if (m_FreezeTime % Server()->TickSpeed() == Server()->TickSpeed() - 1 || m_FreezeTime == -1) + { + GameServer()->CreateDamageInd(m_Pos, 0, (m_FreezeTime + 1) / Server()->TickSpeed(), Teams()->TeamMask(Team(), -1, m_pPlayer->GetCID())); + } + if(m_FreezeTime > 0) + m_FreezeTime--; + else + m_Ninja.m_ActivationTick = Server()->Tick(); + m_Input.m_Direction = 0; + m_Input.m_Jump = 0; + m_Input.m_Hook = 0; + if (m_FreezeTime == 1) + UnFreeze(); + } + + HandleTuneLayer(); // need this before coretick + + // look for save position for rescue feature + if(g_Config.m_SvRescue) { + int index = GameServer()->Collision()->GetPureMapIndex(m_Pos); + int tile = GameServer()->Collision()->GetTileIndex(index); + int ftile = GameServer()->Collision()->GetFTileIndex(index); + if(IsGrounded() && tile != TILE_FREEZE && tile != TILE_DFREEZE && ftile != TILE_FREEZE && ftile != TILE_DFREEZE) { + m_PrevSavePos = m_Pos; + m_SetSavePos = true; + } + } + + m_Core.m_Id = GetPlayer()->GetCID(); + + // headbot + + // ddnet 9 edition of zones + /*CLayers *layers = GameServer()->Layers(); + IMap *pMap = GameServer()->aKernel()->RequestInterface<IMap>(); + for(int i = 0; i < layers->NumGroups(); i++) + { + CMapItemGroup *pGroup = layers->GetGroup(i); + for(int l = 0; l < pGroup->m_NumLayers; l++) + { + CMapItemLayer *pLayer = layers->GetLayer(pGroup->m_StartLayer+l); + + if(pLayer->m_Type == LAYERTYPE_QUADS) + { + CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; + CQuad *pQuads = (CQuad *)pMap->GetDataSwapped(pQLayer->m_Data); + + char name[12]; + IntsToStr(pQLayer->m_aName, 3, name); + + int x0 = (pQuads->m_aPoints[0].x/1000/33); + int y0 = (pQuads->m_aPoints[0].y/1000/33); + int x1 = (pQuads->m_aPoints[1].x/1000/33)+2; + int y1 = (pQuads->m_aPoints[2].y/1000/33); + int pX = m_Core.m_Pos.x/32; + int pY = m_Core.m_Pos.y/32; + bool collide = (pX >= x0 and pX <= x1 and pY >= y0 and pY <= y1); + + + } + } + }*/ + + + if (GameServer()->Collision()->GetQuadAt("trainQuad", m_Core.m_Pos.x, m_Core.m_Pos.y) or + GameServer()->Collision()->GetQuadAt("acidQuad", m_Core.m_Pos.x, m_Core.m_Pos.y)) + { + CGameControllerWarioWare* controller = ((CGameControllerWarioWare*)GameServer()->m_pController); + float timeLeft = (controller->getTimeLength() - controller->getTimer()) / 1000.f; + + Die(m_pPlayer->GetCID(), WEAPON_WORLD, timeLeft); + } +} + + +void CCharacter::DDRacePostCoreTick() +{ + m_Time = (float)(Server()->Tick() - m_StartTime) / ((float)Server()->TickSpeed()); + + if (m_pPlayer->m_DefEmoteReset >= 0 && m_pPlayer->m_DefEmoteReset <= Server()->Tick()) + { + m_pPlayer->m_DefEmoteReset = -1; + m_EmoteType = m_pPlayer->m_DefEmote = EMOTE_NORMAL; + m_EmoteStop = -1; + } + + if (m_EndlessHook || (m_Super && g_Config.m_SvEndlessSuperHook)) + m_Core.m_HookTick = 0; + + if (m_DeepFreeze && !m_Super) + Freeze(); + + if (m_Core.m_Jumps == 0 && !m_Super) + m_Core.m_Jumped = 3; + else if (m_Core.m_Jumps == 1 && m_Core.m_Jumped > 0) + m_Core.m_Jumped = 3; + else if (m_Core.m_JumpedTotal < m_Core.m_Jumps - 1 && m_Core.m_Jumped > 1) + m_Core.m_Jumped = 1; + + if ((m_Super || m_SuperJump) && m_Core.m_Jumped > 1) + m_Core.m_Jumped = 1; + + int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_Pos); + HandleSkippableTiles(CurrentIndex); + + // handle Anti-Skip tiles + std::list < int > Indices = GameServer()->Collision()->GetMapIndices(m_PrevPos, m_Pos); + if(!Indices.empty()) + for(std::list < int >::iterator i = Indices.begin(); i != Indices.end(); i++) + { + HandleTiles(*i); + //dbg_msg("Running","%d", *i); + } + else + { + HandleTiles(CurrentIndex); + //dbg_msg("Running","%d", CurrentIndex); + } + + HandleBroadcast(); +} + +bool CCharacter::Freeze(int Seconds) +{ + if ((Seconds <= 0 || m_Super || m_FreezeTime == -1 || m_FreezeTime > Seconds * Server()->TickSpeed()) && Seconds != -1) + return false; + if (m_FreezeTick < Server()->Tick() - Server()->TickSpeed() || Seconds == -1) + { + for(int i = 0; i < NUM_WEAPONS; i++) + if(m_aWeapons[i].m_Got) + { + m_aWeapons[i].m_Ammo = 0; + } + m_Armor = 0; + m_FreezeTime = Seconds == -1 ? Seconds : Seconds * Server()->TickSpeed(); + m_FreezeTick = Server()->Tick(); + return true; + } + return false; +} + +bool CCharacter::Freeze() +{ + return Freeze(g_Config.m_SvFreezeDelay); +} + +bool CCharacter::UnFreeze() +{ + if (m_FreezeTime > 0) + { + m_Armor=10; + for(int i=0;i<NUM_WEAPONS;i++) + if(m_aWeapons[i].m_Got) + { + m_aWeapons[i].m_Ammo = -1; + } + if(!m_aWeapons[m_Core.m_ActiveWeapon].m_Got) + m_Core.m_ActiveWeapon = WEAPON_GUN; + m_FreezeTime = 0; + m_FreezeTick = 0; + if (m_Core.m_ActiveWeapon==WEAPON_HAMMER) m_ReloadTimer = 0; + return true; + } + return false; +} + +void CCharacter::GiveAllWeapons() +{ + for(int i=WEAPON_GUN;i<NUM_WEAPONS-1;i++) + { + m_aWeapons[i].m_Got = true; + if(!m_FreezeTime) m_aWeapons[i].m_Ammo = -1; + } + return; +} + +void CCharacter::Pause(bool Pause) +{ + m_Paused = Pause; + if(Pause) + { + GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; + GameServer()->m_World.RemoveEntity(this); + + if (m_Core.m_HookedPlayer != -1) // Keeping hook would allow cheats + { + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + } + } + else + { + m_Core.m_Vel = vec2(0,0); + GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; + GameServer()->m_World.InsertEntity(this); + } +} + +void CCharacter::DDRaceInit() +{ + m_Paused = false; + //m_DDRaceState = DDRACE_NONE; + m_DDRaceState = DDRACE_STARTED; + CGameControllerWarioWare* controller = ((CGameControllerWarioWare*)GameServer()->m_pController); + if (controller->getTimer() > 500) + { + if (controller->getState() == WW_WAITING) + { + int songs[2] = {g_Config.m_WwSndWaiting1_Offset, g_Config.m_WwSndWaiting2_Offset}; + setTimer(songs[rand() % 2]-10); + } + else if (controller->getState() == WW_INGAME) + { + setTimer(-60); + } + } + + + m_PrevPos = m_Pos; + m_SetSavePos = false; + m_LastBroadcast = 0; + m_TeamBeforeSuper = 0; + m_Core.m_Id = GetPlayer()->GetCID(); + if(g_Config.m_SvTeam == 2) + { + GameServer()->SendChatTarget(GetPlayer()->GetCID(),"Please join a team before you start"); + m_LastStartWarning = Server()->Tick(); + } + m_TeleCheckpoint = 0; + m_EndlessHook = g_Config.m_SvEndlessDrag; + m_Hit = g_Config.m_SvHit ? HIT_ALL : DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_RIFLE|DISABLE_HIT_SHOTGUN; + m_SuperJump = false; + m_Jetpack = false; + m_Core.m_Jumps = 2; + m_FreezeHammer = false; +} + +void CCharacter::Rescue() +{ + if (m_SetSavePos && !m_Super && !m_DeepFreeze && IsGrounded() && m_Pos == m_PrevPos) { + if (m_LastRescue + g_Config.m_SvRescueDelay * Server()->TickSpeed() > Server()->Tick()) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "You have to wait %d seconds until you can rescue yourself", (m_LastRescue + g_Config.m_SvRescueDelay * Server()->TickSpeed() - Server()->Tick()) / Server()->TickSpeed()); + GameServer()->SendChatTarget(GetPlayer()->GetCID(), aBuf); + return; + } + + int index = GameServer()->Collision()->GetPureMapIndex(m_Pos); + if (GameServer()->Collision()->GetTileIndex(index) == TILE_FREEZE || GameServer()->Collision()->GetFTileIndex(index) == TILE_FREEZE) { + m_LastRescue = Server()->Tick(); + m_Core.m_Pos = m_PrevSavePos; + m_Pos = m_PrevSavePos; + m_PrevPos = m_PrevSavePos; + m_Core.m_Vel = vec2(0, 0); + m_Core.m_HookedPlayer = -1; + m_Core.m_HookState = HOOK_RETRACTED; + m_Core.m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + GameWorld()->ReleaseHooked(GetPlayer()->GetCID()); + m_Core.m_HookPos = m_Core.m_Pos; + UnFreeze(); + } + } +} + +// headbot +void CCharacter::setTimer(float ms) +{ + m_StartTime = (int)(Server()->Tick() + ((-ms/1000.f) * Server()->TickSpeed())); +} + +float CCharacter::getTimer() +{ + return (Server()->Tick() - m_StartTime) / (float)(Server()->TickSpeed()) * 1000.f; +} + +void CCharacter::SetHookOthers(bool on) +{ + if (m_Core.m_Hook == on) return; + + m_Core.m_Hook = on; + if (on) + m_NeededFaketuning &= ~FAKETUNE_NOHOOK; + else + m_NeededFaketuning |= FAKETUNE_NOHOOK; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings +} + +void CCharacter::SetHitOthers(bool on) +{ + int newHit = (on) ? HIT_ALL : DISABLE_HIT_GRENADE|DISABLE_HIT_HAMMER|DISABLE_HIT_RIFLE|DISABLE_HIT_SHOTGUN; + if (m_Hit == newHit) return; + + m_Hit = newHit; + if (on) + m_NeededFaketuning &= ~FAKETUNE_NOHAMMER; + else + m_NeededFaketuning |= FAKETUNE_NOHAMMER; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings +} + +void CCharacter::SetCollideOthers(bool on) +{ + if (m_Core.m_Collision == on) return; + + m_Core.m_Collision = on; + if (on) + m_NeededFaketuning &= ~FAKETUNE_NOCOLL; + else + m_NeededFaketuning |= FAKETUNE_NOCOLL; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings +} + +void CCharacter::SetSuperJump(bool on) +{ + if (m_SuperJump == on) return; + + m_SuperJump = on; + if (m_Core.m_Jumps == 0) + { + if (on) + m_NeededFaketuning &= ~FAKETUNE_NOJUMP; + else + m_NeededFaketuning |= FAKETUNE_NOJUMP; + GameServer()->SendTuningParams(m_pPlayer->GetCID(), m_TuneZone); // update tunings + } +} \ No newline at end of file diff --git a/src/game/server/entities/character.h b/src/game/server/entities/character.h new file mode 100644 index 0000000..837dced --- /dev/null +++ b/src/game/server/entities/character.h @@ -0,0 +1,301 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_CHARACTER_H +#define GAME_SERVER_ENTITIES_CHARACTER_H + +#include <game/server/entity.h> +#include <game/generated/server_data.h> +#include <game/generated/protocol.h> + +#include <game/gamecore.h> + +class CGameTeams; + +enum +{ + WEAPON_GAME = -3, // team switching etc + WEAPON_SELF = -2, // console kill command + WEAPON_WORLD = -1, // death tiles etc +}; + +enum +{ + FAKETUNE_FREEZE = 1, + FAKETUNE_SOLO = 2, + FAKETUNE_NOJUMP = 4, + FAKETUNE_NOCOLL = 8, + FAKETUNE_NOHOOK = 16, + FAKETUNE_JETPACK = 32, + FAKETUNE_NOHAMMER = 64, +}; + +class CCharacter : public CEntity +{ + MACRO_ALLOC_POOL_ID() + + friend class CSaveTee; // need to use core + +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 TickPaused(); + virtual void Snap(int SnappingClient); + virtual int NetworkClipped(int SnappingClient); + virtual int NetworkClipped(int SnappingClient, vec2 CheckPos); + + bool IsGrounded(); + + void SetWeapon(int W); + void SetSolo(bool Solo); + void HandleWeaponSwitch(); + void DoWeaponSwitch(); + + void HandleWeapons(); + void HandleNinja(); + void HandleJetpack(); + + void OnPredictedInput(CNetObj_PlayerInput *pNewInput); + void OnDirectInput(CNetObj_PlayerInput *pNewInput); + void ResetInput(); + void FireWeapon(); + + void Die(int Killer, int Weapon, float respawnSecs=3.f); + 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); + + void Rescue(); + + int NeededFaketuning() {return m_NeededFaketuning;} + bool IsAlive() const { return m_Alive; } + bool IsPaused() const { return m_Paused; } + class CPlayer *GetPlayer() { return m_pPlayer; } + +private: + // player controlling this character + class CPlayer *m_pPlayer; + + bool m_Alive; + bool m_Paused; + int m_NeededFaketuning; + + // 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_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; + int m_LastNoAmmoSound; + + // these are non-heldback inputs + CNetObj_PlayerInput m_LatestPrevInput; + CNetObj_PlayerInput m_LatestInput; + + // input + CNetObj_PlayerInput m_PrevInput; + CNetObj_PlayerInput m_Input; + int m_NumInputs; + int m_Jumped; + + int m_DamageTakenTick; + + int m_Health; + int m_Armor; + + // ninja + struct + { + vec2 m_ActivationDir; + int m_ActivationTick; + int m_CurrentMoveTime; + int m_OldVelAmount; + } m_Ninja; + + // 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 + CCharacterCore m_ReckoningCore; // the dead reckoning core + + // DDRace + + + void HandleTiles(int Index); + float m_Time; + int m_LastBroadcast; + void DDRaceInit(); + void HandleSkippableTiles(int Index); + void DDRaceTick(); + void DDRacePostCoreTick(); + void HandleBroadcast(); + void HandleTuneLayer(); + void SendZoneMsgs(); + + bool m_SetSavePos; + vec2 m_PrevSavePos; + +public: + CGameTeams* Teams(); + void Pause(bool Pause); + bool Freeze(int Time); + bool Freeze(); + bool UnFreeze(); + void GiveAllWeapons(); + int m_DDRaceState; + int Team(); + bool CanCollide(int ClientID); + bool SameTeam(int ClientID); + bool m_Super; + bool m_SuperJump; + bool m_Jetpack; + bool m_NinjaJetpack; + int m_TeamBeforeSuper; + int m_FreezeTime; + int m_FreezeTick; + bool m_DeepFreeze; + bool m_EndlessHook; + bool m_FreezeHammer; + enum + { + HIT_ALL=0, + DISABLE_HIT_HAMMER=1, + DISABLE_HIT_SHOTGUN=2, + DISABLE_HIT_GRENADE=4, + DISABLE_HIT_RIFLE=8 + }; + int m_Hit; + int m_TuneZone; + int m_TuneZoneOld; + int m_PainSoundTimer; + int m_LastMove; + int m_StartTime; + vec2 m_PrevPos; + int m_TeleCheckpoint; + int m_CpTick; + int m_CpActive; + int m_CpLastBroadcast; + float m_CpCurrent[25]; + int m_TileIndex; + int m_TileFlags; + int m_TileFIndex; + int m_TileFFlags; + int m_TileSIndex; + int m_TileSFlags; + int m_TileIndexL; + int m_TileFlagsL; + int m_TileFIndexL; + int m_TileFFlagsL; + int m_TileSIndexL; + int m_TileSFlagsL; + int m_TileIndexR; + int m_TileFlagsR; + int m_TileFIndexR; + int m_TileFFlagsR; + int m_TileSIndexR; + int m_TileSFlagsR; + int m_TileIndexT; + int m_TileFlagsT; + int m_TileFIndexT; + int m_TileFFlagsT; + int m_TileSIndexT; + int m_TileSFlagsT; + int m_TileIndexB; + int m_TileFlagsB; + int m_TileFIndexB; + int m_TileFFlagsB; + int m_TileSIndexB; + int m_TileSFlagsB; + vec2 m_Intersection; + int64 m_LastStartWarning; + int64 m_LastRescue; + bool m_LastRefillJumps; + bool m_LastPenalty; + bool m_LastBonus; + + // Setters/Getters because i don't want to modify vanilla vars access modifiers + int GetLastWeapon() { return m_LastWeapon; }; + void SetLastWeapon(int LastWeap) {m_LastWeapon = LastWeap; }; + int GetActiveWeapon() { return m_Core.m_ActiveWeapon; }; + void SetActiveWeapon(int ActiveWeap) {m_Core.m_ActiveWeapon = ActiveWeap; }; + void SetLastAction(int LastAction) {m_LastAction = LastAction; }; + int GetArmor() { return m_Armor; }; + void SetArmor(int Armor) {m_Armor = Armor; }; + CCharacterCore GetCore() { return m_Core; }; + void SetCore(CCharacterCore Core) {m_Core = Core; }; + CCharacterCore* Core() { return &m_Core; }; + bool GetWeaponGot(int Type) { return m_aWeapons[Type].m_Got; }; + void SetWeaponGot(int Type, bool Value) { m_aWeapons[Type].m_Got = Value; }; + int GetWeaponAmmo(int Type) { return m_aWeapons[Type].m_Ammo; }; + void SetWeaponAmmo(int Type, int Value) { m_aWeapons[Type].m_Ammo = Value; }; + bool IsAlive() { return m_Alive; }; + void SetEmoteType(int EmoteType) { m_EmoteType = EmoteType; }; + void SetEmoteStop(int EmoteStop) { m_EmoteStop = EmoteStop; }; + void SetNinjaActivationDir(vec2 ActivationDir) { m_Ninja.m_ActivationDir = ActivationDir; }; + void SetNinjaActivationTick(int ActivationTick) { m_Ninja.m_ActivationTick = ActivationTick; }; + void SetNinjaCurrentMoveTime(int CurrentMoveTime) { m_Ninja.m_CurrentMoveTime = CurrentMoveTime; }; + void setTimer(float ms); + float getTimer(); + + // headbot + void SetPos(vec2 pos) { m_Core.m_Pos = pos; } + void SetRelativePos(vec2 pos) { m_Core.m_Pos += pos; } + void SetHookOthers(bool on); + void SetHitOthers(bool on); + void SetCollideOthers(bool on); + void SetSuperJump(bool on); + bool CanHitOthers() { return m_Hit == HIT_ALL; } + bool CanHookOthers() { return m_Core.m_Hook; } + bool CanCollideOthers() { return m_Core.m_Collision; } + vec2 GetPos() { return m_Core.m_Pos; } + bool IsMoving() { return m_Core.m_Input.m_Direction != 0; } + CNetObj_PlayerInput* GetInput() { return &m_Input; } + float warioTimeOffset, warioTimeLength; +}; + +enum +{ + DDRACE_NONE = 0, + DDRACE_STARTED, + DDRACE_CHEAT, // no time and won't start again unless ordered by a mod or death + DDRACE_FINISHED +}; + +#endif diff --git a/src/game/server/entities/door.cpp b/src/game/server/entities/door.cpp new file mode 100644 index 0000000..2c4b34f --- /dev/null +++ b/src/game/server/entities/door.cpp @@ -0,0 +1,115 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <engine/shared/config.h> +#include <game/server/gamemodes/DDRace.h> + +#include "door.h" + +CDoor::CDoor(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, + int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Number = Number; + m_Pos = Pos; + m_Length = Length; + m_Direction = vec2(sin(Rotation), cos(Rotation)); + vec2 To = Pos + normalize(m_Direction) * m_Length; + + GameServer()->Collision()->IntersectNoLaser(Pos, To, &this->m_To, 0); + ResetCollision(); + GameWorld()->InsertEntity(this); +} + +void CDoor::Open(int Tick, bool ActivatedTeam[]) +{ + m_EvalTick = Server()->Tick(); +} + +void CDoor::ResetCollision() +{ + for (int i = 0; i < m_Length - 1; i++) + { + vec2 CurrentPos(m_Pos.x + (m_Direction.x * i), + m_Pos.y + (m_Direction.y * i)); + if (GameServer()->Collision()->CheckPoint(CurrentPos) + || GameServer()->Collision()->GetTile(m_Pos.x, m_Pos.y) + || GameServer()->Collision()->GetFTile(m_Pos.x, m_Pos.y)) + break; + else + GameServer()->Collision()->SetDCollisionAt( + m_Pos.x + (m_Direction.x * i), + m_Pos.y + (m_Direction.y * i), TILE_STOPA, 0/*Flags*/, + m_Number); + } +} + +void CDoor::Open(int Team) +{ + +} + +void CDoor::Close(int Team) +{ + +} + +void CDoor::Reset() +{ + +} + +void CDoor::Tick() +{ + +} + +void CDoor::Snap(int SnappingClient) +{ + if (NetworkClipped(SnappingClient, m_Pos) + && NetworkClipped(SnappingClient, m_To)) + return; + + CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem( + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + + if (!pObj) + return; + + pObj->m_X = (int) m_Pos.x; + pObj->m_Y = (int) m_Pos.y; + + CCharacter * Char = GameServer()->GetPlayerChar(SnappingClient); + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; + + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 + || GameServer()->m_apPlayers[SnappingClient]->m_Paused) + && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); + + if (Char == 0) + return; + + if (Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] + && (!Tick)) + return; + + if (Char->Team() == TEAM_SUPER) + { + pObj->m_FromX = (int) m_Pos.x; + pObj->m_FromY = (int) m_Pos.y; + } + else if (Char->IsAlive() && GameServer()->Collision()->m_NumSwitchers > 0 + && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + { + pObj->m_FromX = (int) m_To.x; + pObj->m_FromY = (int) m_To.y; + } + else + { + pObj->m_FromX = (int) m_Pos.x; + pObj->m_FromY = (int) m_Pos.y; + } + pObj->m_StartTick = Server()->Tick(); +} diff --git a/src/game/server/entities/door.h b/src/game/server/entities/door.h new file mode 100644 index 0000000..4ab79dc --- /dev/null +++ b/src/game/server/entities/door.h @@ -0,0 +1,29 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_ENTITY_DOOR_H +#define GAME_SERVER_ENTITY_DOOR_H + +#include <game/server/entity.h> + +class CTrigger; + +class CDoor: public CEntity +{ + vec2 m_To; + int m_EvalTick; + void ResetCollision(); + int m_Length; + vec2 m_Direction; + +public: + void Open(int Tick, bool ActivatedTeam[]); + void Open(int Team); + void Close(int Team); + CDoor(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, + int Number); + + virtual void Reset(); + virtual void Tick(); + virtual void Snap(int SnappingClient); +}; + +#endif diff --git a/src/game/server/entities/dragger.cpp b/src/game/server/entities/dragger.cpp new file mode 100644 index 0000000..79ad7d1 --- /dev/null +++ b/src/game/server/entities/dragger.cpp @@ -0,0 +1,404 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include <engine/config.h> +#include <engine/server.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <game/server/teams.h> +#include <game/server/gamemodes/DDRace.h> +#include "dragger.h" + +CDragger::CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, + int CatchedTeam, int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Layer = Layer; + m_Number = Number; + m_Pos = Pos; + m_Strength = Strength; + m_EvalTick = Server()->Tick(); + m_NW = NW; + m_CatchedTeam = CatchedTeam; + GameWorld()->InsertEntity(this); + + for (int i = 0; i < MAX_CLIENTS; i++) + { + m_SoloIDs[i] = -1; + } +} + +void CDragger::Move() +{ + if (m_Target && (!m_Target->IsAlive() || (m_Target->IsAlive() + && (m_Target->m_Super || m_Target->IsPaused() + || (m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[m_Target->Team()]))))) + m_Target = 0; + + mem_zero(m_SoloEnts, sizeof(m_SoloEnts)); + CCharacter *TempEnts[MAX_CLIENTS]; + + int Num = GameServer()->m_World.FindEntities(m_Pos, g_Config.m_SvDraggerRange, + (CEntity**) m_SoloEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + mem_copy(TempEnts, m_SoloEnts, sizeof(TempEnts)); + + int Id = -1; + int MinLen = 0; + CCharacter *Temp; + for (int i = 0; i < Num; i++) + { + Temp = m_SoloEnts[i]; + if (Temp->Team() != m_CatchedTeam) + { + m_SoloEnts[i] = 0; + continue; + } + if (m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Temp->Team()]) + { + m_SoloEnts[i] = 0; + continue; + } + int Res = + m_NW ? GameServer()->Collision()->IntersectNoLaserNW(m_Pos, + Temp->m_Pos, 0, 0) : + GameServer()->Collision()->IntersectNoLaser(m_Pos, + Temp->m_Pos, 0, 0); + + if (Res == 0) + { + int Len = length(Temp->m_Pos - m_Pos); + if (MinLen == 0 || MinLen > Len) + { + MinLen = Len; + Id = i; + } + + if (!Temp->Teams()->m_Core.GetSolo(Temp->GetPlayer()->GetCID())) + m_SoloEnts[i] = 0; + } + else + { + m_SoloEnts[i] = 0; + } + } + + if (!m_Target) + m_Target = Id != -1 ? TempEnts[Id] : 0; + + if (m_Target) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (m_SoloEnts[i] == m_Target) + m_SoloEnts[i] = 0; + } + } +} + +void CDragger::Drag() +{ + if (m_Target) + { + CCharacter *Target = m_Target; + + for (int i = -1; i < MAX_CLIENTS; i++) + { + if (i >= 0) + Target = m_SoloEnts[i]; + + if (!Target) + continue; + + int Res = 0; + if (!m_NW) + Res = GameServer()->Collision()->IntersectNoLaser(m_Pos, + Target->m_Pos, 0, 0); + else + Res = GameServer()->Collision()->IntersectNoLaserNW(m_Pos, + Target->m_Pos, 0, 0); + if (Res || length(m_Pos - Target->m_Pos) > g_Config.m_SvDraggerRange) + { + Target = 0; + if (i == -1) + m_Target = 0; + else + m_SoloEnts[i] = 0; + } + else if (length(m_Pos - Target->m_Pos) > 28) + { + vec2 Temp = Target->Core()->m_Vel + + (normalize(m_Pos - Target->m_Pos) * m_Strength); + if (Temp.x > 0 + && ((Target->m_TileIndex == TILE_STOP + && Target->m_TileFlags == ROTATION_270) + || (Target->m_TileIndexL == TILE_STOP + && Target->m_TileFlagsL == ROTATION_270) + || (Target->m_TileIndexL == TILE_STOPS + && (Target->m_TileFlagsL == ROTATION_90 + || Target->m_TileFlagsL + == ROTATION_270)) + || (Target->m_TileIndexL == TILE_STOPA) + || (Target->m_TileFIndex == TILE_STOP + && Target->m_TileFFlags == ROTATION_270) + || (Target->m_TileFIndexL == TILE_STOP + && Target->m_TileFFlagsL == ROTATION_270) + || (Target->m_TileFIndexL == TILE_STOPS + && (Target->m_TileFFlagsL == ROTATION_90 + || Target->m_TileFFlagsL + == ROTATION_270)) + || (Target->m_TileFIndexL == TILE_STOPA) + || (Target->m_TileSIndex == TILE_STOP + && Target->m_TileSFlags == ROTATION_270) + || (Target->m_TileSIndexL == TILE_STOP + && Target->m_TileSFlagsL == ROTATION_270) + || (Target->m_TileSIndexL == TILE_STOPS + && (Target->m_TileSFlagsL == ROTATION_90 + || Target->m_TileSFlagsL + == ROTATION_270)) + || (Target->m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if (Temp.x < 0 + && ((Target->m_TileIndex == TILE_STOP + && Target->m_TileFlags == ROTATION_90) + || (Target->m_TileIndexR == TILE_STOP + && Target->m_TileFlagsR == ROTATION_90) + || (Target->m_TileIndexR == TILE_STOPS + && (Target->m_TileFlagsR == ROTATION_90 + || Target->m_TileFlagsR + == ROTATION_270)) + || (Target->m_TileIndexR == TILE_STOPA) + || (Target->m_TileFIndex == TILE_STOP + && Target->m_TileFFlags == ROTATION_90) + || (Target->m_TileFIndexR == TILE_STOP + && Target->m_TileFFlagsR == ROTATION_90) + || (Target->m_TileFIndexR == TILE_STOPS + && (Target->m_TileFFlagsR == ROTATION_90 + || Target->m_TileFFlagsR + == ROTATION_270)) + || (Target->m_TileFIndexR == TILE_STOPA) + || (Target->m_TileSIndex == TILE_STOP + && Target->m_TileSFlags == ROTATION_90) + || (Target->m_TileSIndexR == TILE_STOP + && Target->m_TileSFlagsR == ROTATION_90) + || (Target->m_TileSIndexR == TILE_STOPS + && (Target->m_TileSFlagsR == ROTATION_90 + || Target->m_TileSFlagsR + == ROTATION_270)) + || (Target->m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if (Temp.y < 0 + && ((Target->m_TileIndex == TILE_STOP + && Target->m_TileFlags == ROTATION_180) + || (Target->m_TileIndexB == TILE_STOP + && Target->m_TileFlagsB == ROTATION_180) + || (Target->m_TileIndexB == TILE_STOPS + && (Target->m_TileFlagsB == ROTATION_0 + || Target->m_TileFlagsB + == ROTATION_180)) + || (Target->m_TileIndexB == TILE_STOPA) + || (Target->m_TileFIndex == TILE_STOP + && Target->m_TileFFlags == ROTATION_180) + || (Target->m_TileFIndexB == TILE_STOP + && Target->m_TileFFlagsB == ROTATION_180) + || (Target->m_TileFIndexB == TILE_STOPS + && (Target->m_TileFFlagsB == ROTATION_0 + || Target->m_TileFFlagsB + == ROTATION_180)) + || (Target->m_TileFIndexB == TILE_STOPA) + || (Target->m_TileSIndex == TILE_STOP + && Target->m_TileSFlags == ROTATION_180) + || (Target->m_TileSIndexB == TILE_STOP + && Target->m_TileSFlagsB == ROTATION_180) + || (Target->m_TileSIndexB == TILE_STOPS + && (Target->m_TileSFlagsB == ROTATION_0 + || Target->m_TileSFlagsB + == ROTATION_180)) + || (Target->m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if (Temp.y > 0 + && ((Target->m_TileIndex == TILE_STOP + && Target->m_TileFlags == ROTATION_0) + || (Target->m_TileIndexT == TILE_STOP + && Target->m_TileFlagsT == ROTATION_0) + || (Target->m_TileIndexT == TILE_STOPS + && (Target->m_TileFlagsT == ROTATION_0 + || Target->m_TileFlagsT + == ROTATION_180)) + || (Target->m_TileIndexT == TILE_STOPA) + || (Target->m_TileFIndex == TILE_STOP + && Target->m_TileFFlags == ROTATION_0) + || (Target->m_TileFIndexT == TILE_STOP + && Target->m_TileFFlagsT == ROTATION_0) + || (Target->m_TileFIndexT == TILE_STOPS + && (Target->m_TileFFlagsT == ROTATION_0 + || Target->m_TileFFlagsT + == ROTATION_180)) + || (Target->m_TileFIndexT == TILE_STOPA) + || (Target->m_TileSIndex == TILE_STOP + && Target->m_TileSFlags == ROTATION_0) + || (Target->m_TileSIndexT == TILE_STOP + && Target->m_TileSFlagsT == ROTATION_0) + || (Target->m_TileSIndexT == TILE_STOPS + && (Target->m_TileSFlagsT == ROTATION_0 + || Target->m_TileSFlagsT + == ROTATION_180)) + || (Target->m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + Target->Core()->m_Vel = Temp; + } + } + } +} + +void CDragger::Reset() +{ + GameServer()->m_World.DestroyEntity(this); +} + +void CDragger::Tick() +{ + if (((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.GetTeamState( + m_CatchedTeam) == CGameTeams::TEAMSTATE_EMPTY) + return; + if (Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) + { + int Flags; + m_EvalTick = Server()->Tick(); + int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, + &Flags); + if (index) + { + m_Core = GameServer()->Collision()->CpSpeed(index, Flags); + } + m_Pos += m_Core; + Move(); + } + Drag(); + return; + +} + +void CDragger::Snap(int SnappingClient) +{ + if (((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.GetTeamState( + m_CatchedTeam) == CGameTeams::TEAMSTATE_EMPTY) + return; + + CCharacter *Target = m_Target; + + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (m_SoloIDs[i] == -1) + break; + + Server()->SnapFreeID(m_SoloIDs[i]); + m_SoloIDs[i] = -1; + } + + int pos = 0; + + for (int i = -1; i < MAX_CLIENTS; i++) + { + if (i >= 0) + { + Target = m_SoloEnts[i]; + + if (!Target) + continue; + } + + if (Target) + { + if (NetworkClipped(SnappingClient, m_Pos) + && NetworkClipped(SnappingClient, Target->m_Pos)) + continue; + } + else if (NetworkClipped(SnappingClient, m_Pos)) + continue; + + CCharacter * Char = GameServer()->GetPlayerChar(SnappingClient); + + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 + || GameServer()->m_apPlayers[SnappingClient]->m_Paused) + && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); + + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; + if (Char && Char->IsAlive() + && (m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] + && (!Tick))) + continue; + if (Char && Char->IsAlive()) + { + if (Char->Team() != m_CatchedTeam) + continue; + } + else + { + // send to spectators only active draggers and some inactive from team 0 + if (!((Target && Target->IsAlive()) || m_CatchedTeam == 0)) + continue; + } + + if (Char && Char->IsAlive() && Target && Target->IsAlive() && Target->GetPlayer()->GetCID() != Char->GetPlayer()->GetCID() && !Char->GetPlayer()->m_ShowOthers && + (Char->Teams()->m_Core.GetSolo(SnappingClient) || Char->Teams()->m_Core.GetSolo(Target->GetPlayer()->GetCID()))) + { + continue; + } + + CNetObj_Laser *obj; + + if (i == -1) + { + obj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem( + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + } + else + { + m_SoloIDs[pos] = Server()->SnapNewID(); + obj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem( // TODO: Have to free IDs again? + NETOBJTYPE_LASER, m_SoloIDs[pos], sizeof(CNetObj_Laser))); + pos++; + } + + if (!obj) + continue; + obj->m_X = (int) m_Pos.x; + obj->m_Y = (int) m_Pos.y; + if (Target) + { + obj->m_FromX = (int) Target->m_Pos.x; + obj->m_FromY = (int) Target->m_Pos.y; + } + else + { + obj->m_FromX = (int) m_Pos.x; + obj->m_FromY = (int) m_Pos.y; + } + + int StartTick = m_EvalTick; + if (StartTick < Server()->Tick() - 4) + StartTick = Server()->Tick() - 4; + else if (StartTick > Server()->Tick()) + StartTick = Server()->Tick(); + obj->m_StartTick = StartTick; + } +} + +CDraggerTeam::CDraggerTeam(CGameWorld *pGameWorld, vec2 Pos, float Strength, + bool NW, int Layer, int Number) +{ + for (int i = 0; i < MAX_CLIENTS; ++i) + { + m_Draggers[i] = new CDragger(pGameWorld, Pos, Strength, NW, i, Layer, + Number); + } +} + +//CDraggerTeam::~CDraggerTeam() { +//for(int i = 0; i < MAX_CLIENTS; ++i) { +// delete m_Draggers[i]; +//} +//} diff --git a/src/game/server/entities/dragger.h b/src/game/server/entities/dragger.h new file mode 100644 index 0000000..0bf812d --- /dev/null +++ b/src/game/server/entities/dragger.h @@ -0,0 +1,42 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_ENTITY_DRAGGER_H +#define GAME_SERVER_ENTITY_DRAGGER_H + +#include <game/server/entity.h> +class CCharacter; + +class CDragger: public CEntity +{ + vec2 m_Core; + float m_Strength; + int m_EvalTick; + void Move(); + void Drag(); + CCharacter * m_Target; + bool m_NW; + int m_CatchedTeam; + + CCharacter * m_SoloEnts[MAX_CLIENTS]; + int m_SoloIDs[MAX_CLIENTS]; +public: + + CDragger(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW, + int CatchedTeam, int Layer = 0, int Number = 0); + + virtual void Reset(); + virtual void Tick(); + virtual void Snap(int snapping_client); +}; + +class CDraggerTeam +{ + CDragger * m_Draggers[MAX_CLIENTS]; + +public: + + CDraggerTeam(CGameWorld *pGameWorld, vec2 Pos, float Strength, bool NW = + false, int Layer = 0, int Number = 0); + //~CDraggerTeam(); +}; + +#endif diff --git a/src/game/server/entities/flag.cpp b/src/game/server/entities/flag.cpp new file mode 100644 index 0000000..dfe5939 --- /dev/null +++ b/src/game/server/entities/flag.cpp @@ -0,0 +1,47 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +/* +#include <game/server/gamecontext.h> +#include "flag.h" + +CFlag::CFlag(CGameWorld *pGameWorld, int Team) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_FLAG) +{ + m_Team = Team; + m_ProximityRadius = ms_PhysSize; + m_pCarryingCharacter = NULL; + m_GrabTick = 0; + + Reset(); +} + +void CFlag::Reset() +{ + m_pCarryingCharacter = NULL; + m_AtStand = 1; + m_Pos = m_StandPos; + m_Vel = vec2(0,0); + m_GrabTick = 0; +} + +void CFlag::TickPaused() +{ + ++m_DropTick; + if(m_GrabTick) + ++m_GrabTick; +} + +void CFlag::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient)) + return; + + CNetObj_Flag *pFlag = (CNetObj_Flag *)Server()->SnapNewItem(NETOBJTYPE_FLAG, m_Team, sizeof(CNetObj_Flag)); + if(!pFlag) + return; + + pFlag->m_X = (int)m_Pos.x; + pFlag->m_Y = (int)m_Pos.y; + pFlag->m_Team = m_Team; +} +*/ diff --git a/src/game/server/entities/flag.h b/src/game/server/entities/flag.h new file mode 100644 index 0000000..dc286f6 --- /dev/null +++ b/src/game/server/entities/flag.h @@ -0,0 +1,30 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +/* +#ifndef GAME_SERVER_ENTITIES_FLAG_H +#define GAME_SERVER_ENTITIES_FLAG_H + +#include <game/server/entity.h> + +class CFlag : public CEntity +{ +public: + static const int ms_PhysSize = 14; + 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(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); +}; + +#endif +*/ diff --git a/src/game/server/entities/gun.cpp b/src/game/server/entities/gun.cpp new file mode 100644 index 0000000..516b3e5 --- /dev/null +++ b/src/game/server/entities/gun.cpp @@ -0,0 +1,137 @@ +/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */ +#include <engine/server.h> +#include <engine/shared/config.h> +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <game/server/teams.h> + +#include "gun.h" +#include "plasma.h" + +////////////////////////////////////////////////// +// CGun +////////////////////////////////////////////////// +CGun::CGun(CGameWorld *pGameWorld, vec2 Pos, bool Freeze, bool Explosive, int Layer, int Number) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Layer = Layer; + m_Number = Number; + m_LastFire = Server()->Tick(); + m_Pos = Pos; + m_EvalTick = Server()->Tick(); + m_Freeze = Freeze; + m_Explosive = Explosive; + + GameWorld()->InsertEntity(this); +} + + +void CGun::Fire() +{ + CCharacter *Ents[MAX_CLIENTS]; + int IdInTeam[MAX_CLIENTS]; + int LenInTeam[MAX_CLIENTS]; + for (int i = 0; i < MAX_CLIENTS; i++) + { + IdInTeam[i] = -1; + LenInTeam[i] = 0; + } + + int Num = -1; + Num = GameServer()->m_World.FindEntities(m_Pos, g_Config.m_SvPlasmaRange, (CEntity**)Ents, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + + for (int i = 0; i < Num; i++) + { + CCharacter *Target = Ents[i]; + //now gun doesn't affect on super + if(Target->Team() == TEAM_SUPER) + continue; + if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Target->Team()]) + continue; + int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos,0,0,false); + if (!res) + { + int Len = length(Target->m_Pos - m_Pos); + if (LenInTeam[Target->Team()] == 0 || LenInTeam[Target->Team()] > Len) + { + LenInTeam[Target->Team()] = Len; + IdInTeam[Target->Team()] = i; + } + } + } + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(IdInTeam[i] != -1) + { + CCharacter *Target = Ents[IdInTeam[i]]; + new CPlasma(&GameServer()->m_World, m_Pos, normalize(Target->m_Pos - m_Pos), m_Freeze, m_Explosive, i); + m_LastFire = Server()->Tick(); + } + } + for (int i = 0; i < Num; i++) + { + CCharacter *Target = Ents[i]; + if (Target->IsAlive() && Target->Teams()->m_Core.GetSolo(Target->GetPlayer()->GetCID())) + { + if (IdInTeam[Target->Team()] != i) + { + int res = GameServer()->Collision()->IntersectLine(m_Pos, Target->m_Pos,0,0,false); + if (!res) + { + new CPlasma(&GameServer()->m_World, m_Pos, normalize(Target->m_Pos - m_Pos), m_Freeze, m_Explosive, Target->Team()); + m_LastFire = Server()->Tick(); + } + } + } + } + +} + +void CGun::Reset() +{ + GameServer()->m_World.DestroyEntity(this); +} + +void CGun::Tick() +{ + if (Server()->Tick()%int(Server()->TickSpeed()*0.15f)==0) + { + int Flags; + m_EvalTick=Server()->Tick(); + int index = GameServer()->Collision()->IsMover(m_Pos.x,m_Pos.y, &Flags); + if (index) + { + m_Core=GameServer()->Collision()->CpSpeed(index, Flags); + } + m_Pos+=m_Core; + } + if (m_LastFire + Server()->TickSpeed() / g_Config.m_SvPlasmaPerSec <= Server()->Tick()) + Fire(); + +} + +void CGun::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient)) + return; + + CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); + + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 + || GameServer()->m_apPlayers[SnappingClient]->m_Paused) + && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); + + int Tick = (Server()->Tick()%Server()->TickSpeed())%11; + if (Char && Char->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) && (!Tick)) return; + CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + + if (!pObj) + return; + + pObj->m_X = (int)m_Pos.x; + pObj->m_Y = (int)m_Pos.y; + pObj->m_FromX = (int)m_Pos.x; + pObj->m_FromY = (int)m_Pos.y; + pObj->m_StartTick = m_EvalTick; +} diff --git a/src/game/server/entities/gun.h b/src/game/server/entities/gun.h new file mode 100644 index 0000000..06c2149 --- /dev/null +++ b/src/game/server/entities/gun.h @@ -0,0 +1,31 @@ +/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */ + +#ifndef CGun_TYPE +#define CGun_TYPE + +#include <game/server/entity.h> +#include <game/gamecore.h> + +class CCharacter; + +class CGun : public CEntity +{ + int m_EvalTick; + + vec2 m_Core; + bool m_Freeze; + bool m_Explosive; + + void Fire(); + int m_LastFire; + +public: + CGun(CGameWorld *pGameWorld, vec2 Pos, bool Freeze, bool Explosive, int Layer = 0, int Number = 0); + + virtual void Reset(); + virtual void Tick(); + virtual void Snap(int SnappingClient); +}; + + +#endif diff --git a/src/game/server/entities/laser.cpp b/src/game/server/entities/laser.cpp new file mode 100644 index 0000000..d53d0ea --- /dev/null +++ b/src/game/server/entities/laser.cpp @@ -0,0 +1,235 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <game/server/gamemodes/WarioWare.h> +#include "laser.h" + +#include <engine/shared/config.h> +#include <game/server/teams.h> + +CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Pos = Pos; + m_Owner = Owner; + m_Energy = StartEnergy; + m_Dir = Direction; + m_Bounces = 0; + m_EvalTick = 0; + m_TelePos = vec2(0,0); + m_WasTele = false; + m_Type = Type; + m_TuneZone = GameServer()->Collision()->IsTune(GameServer()->Collision()->GetMapIndex(m_Pos)); + m_TeamMask = GameServer()->GetPlayerChar(Owner) ? GameServer()->GetPlayerChar(Owner)->Teams()->TeamMask(GameServer()->GetPlayerChar(Owner)->Team(), -1, m_Owner) : 0; + GameWorld()->InsertEntity(this); + DoBounce(); +} + + +bool CLaser::HitCharacter(vec2 From, vec2 To) +{ + CGameControllerWarioWare* controller = ((CGameControllerWarioWare*)GameServer()->m_pController); + + vec2 At; + CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + CCharacter *pHit; + bool pDontHitSelf = g_Config.m_SvOldLaser || (m_Bounces == 0 && !m_WasTele); + + if (controller->getMicroGame() != MG_HIT_THE_TARGET) + { + if(pOwnerChar ? (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_RIFLE) && m_Type == WEAPON_RIFLE) || (!(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN) && m_Type == WEAPON_SHOTGUN) : g_Config.m_SvHit) + pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner); + else + pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pDontHitSelf ? pOwnerChar : 0, m_Owner, pOwnerChar); + } + else + { + pHit = GameServer()->m_World.IntersectBotCharacter(m_Pos, To, 0.f, At); + } + + if(!pHit || (pHit == pOwnerChar && g_Config.m_SvOldLaser) || (pHit != pOwnerChar && pOwnerChar ? (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_RIFLE and pHit->GetPlayer()->GetCID() < MAX_CLIENTS-1 and m_Type == WEAPON_RIFLE) || (pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_SHOTGUN && m_Type == WEAPON_SHOTGUN) : !g_Config.m_SvHit)) + return false; + m_From = From; + m_Pos = At; + m_Energy = -1; + if (m_Type == WEAPON_SHOTGUN) + { + vec2 Temp; + + float Strength; + if (!m_TuneZone) + Strength = GameServer()->Tuning()->m_ShotgunStrength; + else + Strength = GameServer()->TuningList()[m_TuneZone].m_ShotgunStrength; + + if(!g_Config.m_SvOldLaser) + Temp = pHit->Core()->m_Vel + normalize(m_PrevPos - pHit->Core()->m_Pos) * Strength; + else + Temp = pHit->Core()->m_Vel + normalize(pOwnerChar->Core()->m_Pos - pHit->Core()->m_Pos) * Strength; + if(Temp.x > 0 && ((pHit->m_TileIndex == TILE_STOP && pHit->m_TileFlags == ROTATION_270) || (pHit->m_TileIndexL == TILE_STOP && pHit->m_TileFlagsL == ROTATION_270) || (pHit->m_TileIndexL == TILE_STOPS && (pHit->m_TileFlagsL == ROTATION_90 || pHit->m_TileFlagsL ==ROTATION_270)) || (pHit->m_TileIndexL == TILE_STOPA) || (pHit->m_TileFIndex == TILE_STOP && pHit->m_TileFFlags == ROTATION_270) || (pHit->m_TileFIndexL == TILE_STOP && pHit->m_TileFFlagsL == ROTATION_270) || (pHit->m_TileFIndexL == TILE_STOPS && (pHit->m_TileFFlagsL == ROTATION_90 || pHit->m_TileFFlagsL == ROTATION_270)) || (pHit->m_TileFIndexL == TILE_STOPA) || (pHit->m_TileSIndex == TILE_STOP && pHit->m_TileSFlags == ROTATION_270) || (pHit->m_TileSIndexL == TILE_STOP && pHit->m_TileSFlagsL == ROTATION_270) || (pHit->m_TileSIndexL == TILE_STOPS && (pHit->m_TileSFlagsL == ROTATION_90 || pHit->m_TileSFlagsL == ROTATION_270)) || (pHit->m_TileSIndexL == TILE_STOPA))) + Temp.x = 0; + if(Temp.x < 0 && ((pHit->m_TileIndex == TILE_STOP && pHit->m_TileFlags == ROTATION_90) || (pHit->m_TileIndexR == TILE_STOP && pHit->m_TileFlagsR == ROTATION_90) || (pHit->m_TileIndexR == TILE_STOPS && (pHit->m_TileFlagsR == ROTATION_90 || pHit->m_TileFlagsR == ROTATION_270)) || (pHit->m_TileIndexR == TILE_STOPA) || (pHit->m_TileFIndex == TILE_STOP && pHit->m_TileFFlags == ROTATION_90) || (pHit->m_TileFIndexR == TILE_STOP && pHit->m_TileFFlagsR == ROTATION_90) || (pHit->m_TileFIndexR == TILE_STOPS && (pHit->m_TileFFlagsR == ROTATION_90 || pHit->m_TileFFlagsR == ROTATION_270)) || (pHit->m_TileFIndexR == TILE_STOPA) || (pHit->m_TileSIndex == TILE_STOP && pHit->m_TileSFlags == ROTATION_90) || (pHit->m_TileSIndexR == TILE_STOP && pHit->m_TileSFlagsR == ROTATION_90) || (pHit->m_TileSIndexR == TILE_STOPS && (pHit->m_TileSFlagsR == ROTATION_90 || pHit->m_TileSFlagsR == ROTATION_270)) || (pHit->m_TileSIndexR == TILE_STOPA))) + Temp.x = 0; + if(Temp.y < 0 && ((pHit->m_TileIndex == TILE_STOP && pHit->m_TileFlags == ROTATION_180) || (pHit->m_TileIndexB == TILE_STOP && pHit->m_TileFlagsB == ROTATION_180) || (pHit->m_TileIndexB == TILE_STOPS && (pHit->m_TileFlagsB == ROTATION_0 || pHit->m_TileFlagsB == ROTATION_180)) || (pHit->m_TileIndexB == TILE_STOPA) || (pHit->m_TileFIndex == TILE_STOP && pHit->m_TileFFlags == ROTATION_180) || (pHit->m_TileFIndexB == TILE_STOP && pHit->m_TileFFlagsB == ROTATION_180) || (pHit->m_TileFIndexB == TILE_STOPS && (pHit->m_TileFFlagsB == ROTATION_0 || pHit->m_TileFFlagsB == ROTATION_180)) || (pHit->m_TileFIndexB == TILE_STOPA) || (pHit->m_TileSIndex == TILE_STOP && pHit->m_TileSFlags == ROTATION_180) || (pHit->m_TileSIndexB == TILE_STOP && pHit->m_TileSFlagsB == ROTATION_180) || (pHit->m_TileSIndexB == TILE_STOPS && (pHit->m_TileSFlagsB == ROTATION_0 || pHit->m_TileSFlagsB == ROTATION_180)) || (pHit->m_TileSIndexB == TILE_STOPA))) + Temp.y = 0; + if(Temp.y > 0 && ((pHit->m_TileIndex == TILE_STOP && pHit->m_TileFlags == ROTATION_0) || (pHit->m_TileIndexT == TILE_STOP && pHit->m_TileFlagsT == ROTATION_0) || (pHit->m_TileIndexT == TILE_STOPS && (pHit->m_TileFlagsT == ROTATION_0 || pHit->m_TileFlagsT == ROTATION_180)) || (pHit->m_TileIndexT == TILE_STOPA) || (pHit->m_TileFIndex == TILE_STOP && pHit->m_TileFFlags == ROTATION_0) || (pHit->m_TileFIndexT == TILE_STOP && pHit->m_TileFFlagsT == ROTATION_0) || (pHit->m_TileFIndexT == TILE_STOPS && (pHit->m_TileFFlagsT == ROTATION_0 || pHit->m_TileFFlagsT == ROTATION_180)) || (pHit->m_TileFIndexT == TILE_STOPA) || (pHit->m_TileSIndex == TILE_STOP && pHit->m_TileSFlags == ROTATION_0) || (pHit->m_TileSIndexT == TILE_STOP && pHit->m_TileSFlagsT == ROTATION_0) || (pHit->m_TileSIndexT == TILE_STOPS && (pHit->m_TileSFlagsT == ROTATION_0 || pHit->m_TileSFlagsT == ROTATION_180)) || (pHit->m_TileSIndexT == TILE_STOPA))) + Temp.y = 0; + pHit->Core()->m_Vel = Temp; + } + else if (m_Type == WEAPON_RIFLE) + { + pHit->UnFreeze(); + + // WarioWare + if (pHit->GetPlayer()->GetCID() == MAX_CLIENTS-1) + { + controller->winMicroGame(m_Owner); + } + } + return true; +} + +void CLaser::DoBounce() +{ + m_EvalTick = Server()->Tick(); + + if(m_Energy < 0) + { + GameServer()->m_World.DestroyEntity(this); + return; + } + m_PrevPos = m_Pos; + vec2 Coltile; + + int Res; + int z; + + if (m_WasTele) + { + m_PrevPos = m_TelePos; + m_Pos = m_TelePos; + m_TelePos = vec2(0,0); + } + + vec2 To = m_Pos + m_Dir * m_Energy; + + Res = GameServer()->Collision()->IntersectLineTeleWeapon(m_Pos, To, &Coltile, &To, &z, false); + + if(Res) + { + if(!HitCharacter(m_Pos, To)) + { + // intersected + m_From = m_Pos; + m_Pos = To; + + vec2 TempPos = m_Pos; + vec2 TempDir = m_Dir * 4.0f; + + int f = 0; + if(Res == -1) + { + f = GameServer()->Collision()->GetTile(round_to_int(Coltile.x), round_to_int(Coltile.y)); + GameServer()->Collision()->SetCollisionAt(round_to_int(Coltile.x), round_to_int(Coltile.y), CCollision::COLFLAG_SOLID); + } + GameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0); + if(Res == -1) + { + GameServer()->Collision()->SetCollisionAt(round_to_int(Coltile.x), round_to_int(Coltile.y), f); + } + m_Pos = TempPos; + m_Dir = normalize(TempDir); + + if (!m_TuneZone) + m_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost; + else + m_Energy -= distance(m_From, m_Pos) + GameServer()->TuningList()[m_TuneZone].m_LaserBounceCost; + + if (Res&CCollision::COLFLAG_TELE && ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1].size()) + { + int Num = ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1].size(); + m_TelePos = ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1][(!Num)?Num:rand() % Num]; + m_WasTele = true; + } + else + { + m_Bounces++; + m_WasTele = false; + } + + int BounceNum = GameServer()->Tuning()->m_LaserBounceNum; + if (m_TuneZone) + BounceNum = GameServer()->TuningList()[m_TuneZone].m_LaserBounceNum; + + if(m_Bounces > BounceNum) + m_Energy = -1; + + GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE, m_TeamMask); + } + } + else + { + if(!HitCharacter(m_Pos, To)) + { + m_From = m_Pos; + m_Pos = To; + m_Energy = -1; + } + } + //m_Owner = -1; +} + +void CLaser::Reset() +{ + GameServer()->m_World.DestroyEntity(this); +} + +void CLaser::Tick() +{ + float Delay; + if (m_TuneZone) + Delay = GameServer()->TuningList()[m_TuneZone].m_LaserBounceDelay; + else + Delay = GameServer()->Tuning()->m_LaserBounceDelay; + + if(Server()->Tick() > m_EvalTick+(Server()->TickSpeed()*Delay/1000.0f)) + DoBounce(); +} + +void CLaser::TickPaused() +{ + ++m_EvalTick; +} + +void CLaser::Snap(int SnappingClient) +{ + if(NetworkClipped(SnappingClient)) + return; + CCharacter * OwnerChar = 0; + if(m_Owner >= 0) + OwnerChar = GameServer()->GetPlayerChar(m_Owner); + if(!OwnerChar) + return; + + CCharacter *pOwnerChar = 0; + int64_t TeamMask = -1LL; + + if(m_Owner >= 0) + pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + + if (pOwnerChar && pOwnerChar->IsAlive()) + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + + if(!CmaskIsSet(TeamMask, SnappingClient)) + return; + CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + if(!pObj) + return; + + pObj->m_X = (int)m_Pos.x; + pObj->m_Y = (int)m_Pos.y; + pObj->m_FromX = (int)m_From.x; + pObj->m_FromY = (int)m_From.y; + pObj->m_StartTick = m_EvalTick; +} diff --git a/src/game/server/entities/laser.h b/src/game/server/entities/laser.h new file mode 100644 index 0000000..be9aee6 --- /dev/null +++ b/src/game/server/entities/laser.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_LASER_H +#define GAME_SERVER_ENTITIES_LASER_H + +#include <game/server/entity.h> + +class CLaser : public CEntity +{ +public: + CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int Type); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +protected: + bool HitCharacter(vec2 From, vec2 To); + void DoBounce(); + +private: + vec2 m_From; + vec2 m_Dir; + vec2 m_TelePos; + bool m_WasTele; + float m_Energy; + int m_Bounces; + int m_EvalTick; + int m_Owner; + int m_TeamMask; + + // DDRace + + vec2 m_PrevPos; + int m_Type; + int m_TuneZone; +}; + +#endif diff --git a/src/game/server/entities/light.cpp b/src/game/server/entities/light.cpp new file mode 100644 index 0000000..03006ba --- /dev/null +++ b/src/game/server/entities/light.cpp @@ -0,0 +1,163 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include <engine/config.h> +#include <engine/server.h> +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include "light.h" +#include <game/mapitems.h> + +CLight::CLight(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, + int Layer, int Number) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Layer = Layer; + m_Number = Number; + m_Tick = (Server()->TickSpeed() * 0.15f); + m_Pos = Pos; + m_Rotation = Rotation; + m_Length = Length; + m_EvalTick = Server()->Tick(); + GameWorld()->InsertEntity(this); + Step(); +} + +bool CLight::HitCharacter() +{ + std::list<CCharacter *> HitCharacters = + GameServer()->m_World.IntersectedCharacters(m_Pos, m_To, 0.0f, 0); + if (HitCharacters.empty()) + return false; + for (std::list<CCharacter *>::iterator i = HitCharacters.begin(); + i != HitCharacters.end(); i++) + { + CCharacter * Char = *i; + if (m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + continue; + Char->Freeze(); + } + return true; +} + +void CLight::Move() +{ + if (m_Speed != 0) + { + if ((m_CurveLength >= m_Length && m_Speed > 0) + || (m_CurveLength <= 0 && m_Speed < 0)) + m_Speed = -m_Speed; + m_CurveLength += m_Speed * m_Tick + m_LengthL; + m_LengthL = 0; + if (m_CurveLength > m_Length) + { + m_LengthL = m_CurveLength - m_Length; + m_CurveLength = m_Length; + } + else if (m_CurveLength < 0) + { + m_LengthL = 0 + m_CurveLength; + m_CurveLength = 0; + } + } + + m_Rotation += m_AngularSpeed * m_Tick; + if (m_Rotation > pi * 2) + m_Rotation -= pi * 2; + else if (m_Rotation < 0) + m_Rotation += pi * 2; +} + +void CLight::Step() +{ + Move(); + vec2 dir(sin(m_Rotation), cos(m_Rotation)); + vec2 to2 = m_Pos + normalize(dir) * m_CurveLength; + GameServer()->Collision()->IntersectNoLaser(m_Pos, to2, &m_To, 0); +} + +void CLight::Reset() +{ + GameServer()->m_World.DestroyEntity(this); +} + +void CLight::Tick() +{ + + if (Server()->Tick() % int(Server()->TickSpeed() * 0.15f) == 0) + { + int Flags; + m_EvalTick = Server()->Tick(); + int index = GameServer()->Collision()->IsMover(m_Pos.x, m_Pos.y, + &Flags); + if (index) + { + m_Core = GameServer()->Collision()->CpSpeed(index, Flags); + } + m_Pos += m_Core; + Step(); + } + + HitCharacter(); + return; + +} + +void CLight::Snap(int SnappingClient) +{ + if (NetworkClipped(SnappingClient, m_Pos) + && NetworkClipped(SnappingClient, m_To)) + return; + + CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); + + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 + || GameServer()->m_apPlayers[SnappingClient]->m_Paused) + && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); + + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 6; + + if (Char && Char->IsAlive() + && m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()] + && (Tick)) + return; + + CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem( + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + + if (!pObj) + return; + + pObj->m_X = (int) m_Pos.x; + pObj->m_Y = (int) m_Pos.y; + + if (Char && Char->Team() == TEAM_SUPER) + { + pObj->m_FromX = (int) m_Pos.x; + pObj->m_FromY = (int) m_Pos.y; + } + else if (Char && m_Layer == LAYER_SWITCH + && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + { + pObj->m_FromX = (int) m_To.x; + pObj->m_FromY = (int) m_To.y; + } + else if (m_Layer != LAYER_SWITCH) + { + pObj->m_FromX = (int) m_To.x; + pObj->m_FromY = (int) m_To.y; + } + else + { + pObj->m_FromX = (int) m_Pos.x; + pObj->m_FromY = (int) m_Pos.y; + } + + int StartTick = m_EvalTick; + if (StartTick < Server()->Tick() - 4) + StartTick = Server()->Tick() - 4; + else if (StartTick > Server()->Tick()) + StartTick = Server()->Tick(); + pObj->m_StartTick = StartTick; +} diff --git a/src/game/server/entities/light.h b/src/game/server/entities/light.h new file mode 100644 index 0000000..3a20d5a --- /dev/null +++ b/src/game/server/entities/light.h @@ -0,0 +1,35 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_CEntity_CLight_H +#define GAME_SERVER_CEntity_CLight_H + +#include <game/server/entity.h> + +class CLight: public CEntity +{ + float m_Rotation; + vec2 m_To; + vec2 m_Core; + + int m_EvalTick; + + int m_Tick; + + bool HitCharacter(); + void Move(); + void Step(); +public: + int m_CurveLength; + int m_LengthL; + float m_AngularSpeed; + int m_Speed; + int m_Length; + + CLight(CGameWorld *pGameWorld, vec2 Pos, float Rotation, int Length, + int Layer = 0, int Number = 0); + + virtual void Reset(); + virtual void Tick(); + virtual void Snap(int SnappingClient); +}; + +#endif diff --git a/src/game/server/entities/pickup.cpp b/src/game/server/entities/pickup.cpp new file mode 100644 index 0000000..434beb5 --- /dev/null +++ b/src/game/server/entities/pickup.cpp @@ -0,0 +1,190 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include "pickup.h" + +#include <game/server/teams.h> + +CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType, int Layer, int Number) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) +{ + m_Type = Type; + m_Subtype = SubType; + m_ProximityRadius = PickupPhysSize; + + m_Layer = Layer; + m_Number = Number; + + Reset(); + + GameWorld()->InsertEntity(this); +} + +void CPickup::Reset() +{ + /*if (g_pData->m_aPickups[m_Type].m_Spawndelay > 0) + m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * g_pData->m_aPickups[m_Type].m_Spawndelay; + else + m_SpawnTick = -1;*/ +} + +void CPickup::Tick() +{ + Move(); + /*// wait for respawn + if(m_SpawnTick > 0) + { + if(Server()->Tick() > m_SpawnTick) + { + // respawn + m_SpawnTick = -1; + + if(m_Type == POWERUP_WEAPON) + GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN); + } + else + return; + }*/ + // Check if a player intersected us + CCharacter *apEnts[MAX_CLIENTS]; + int Num = GameWorld()->FindEntities(m_Pos, 20.0f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; ++i) { + CCharacter * pChr = apEnts[i]; + if(pChr && pChr->IsAlive()) + { + if(m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pChr->Team()]) continue; + bool sound = false; + // player picked us up, is someone was hooking us, let them go + switch (m_Type) + { + case POWERUP_HEALTH: + if(pChr->Freeze()) GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH, pChr->Teams()->TeamMask(pChr->Team())); + break; + + case POWERUP_ARMOR: + if(pChr->Team() == TEAM_SUPER) continue; + for(int i = WEAPON_SHOTGUN; i < NUM_WEAPONS; i++) + { + if(pChr->GetWeaponGot(i)) + { + if(!(pChr->m_FreezeTime && i == WEAPON_NINJA)) + { + pChr->SetWeaponGot(i, false); + pChr->SetWeaponAmmo(i, 0); + sound = true; + } + } + } + pChr->SetNinjaActivationDir(vec2(0,0)); + pChr->SetNinjaActivationTick(-500); + pChr->SetNinjaCurrentMoveTime(0); + if (sound) + { + pChr->SetLastWeapon(WEAPON_GUN); + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR, pChr->Teams()->TeamMask(pChr->Team())); + } + if(!pChr->m_FreezeTime && pChr->GetActiveWeapon() >= WEAPON_SHOTGUN) + pChr->SetActiveWeapon(WEAPON_HAMMER); + break; + + case POWERUP_WEAPON: + + if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS && (!pChr->GetWeaponGot(m_Subtype) || (pChr->GetWeaponAmmo(m_Subtype) != -1 && !pChr->m_FreezeTime))) + { + if(pChr->GiveWeapon(m_Subtype, -1)) + { + //RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; + + if(m_Subtype == WEAPON_GRENADE) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE, pChr->Teams()->TeamMask(pChr->Team())); + else if(m_Subtype == WEAPON_SHOTGUN) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); + else if(m_Subtype == WEAPON_RIFLE) + GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN, pChr->Teams()->TeamMask(pChr->Team())); + + if(pChr->GetPlayer()) + GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), m_Subtype); + } + } + break; + + case POWERUP_NINJA: + { + // activate ninja on target player + pChr->GiveNinja(); + //RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; + + /*// loop through all players, setting their emotes + CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); + for(; pC; pC = (CCharacter *)pC->TypeNext()) + { + if (pC != pChr) + pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed()); + }*/ + break; + } + default: + break; + }; + + /*if(RespawnTime >= 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "pickup player='%d:%s' item=%d/%d", + pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type, m_Subtype); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime; + }*/ + } + } +} + +void CPickup::TickPaused() +{ + /*if(m_SpawnTick != -1) + ++m_SpawnTick;*/ +} + +void CPickup::Snap(int SnappingClient) +{ + /*if(m_SpawnTick != -1 || NetworkClipped(SnappingClient)) + return;*/ + + CCharacter *Char = GameServer()->GetPlayerChar(SnappingClient); + + if(SnappingClient > -1 && (GameServer()->m_apPlayers[SnappingClient]->GetTeam() == -1 + || GameServer()->m_apPlayers[SnappingClient]->m_Paused) + && GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID != SPEC_FREEVIEW) + Char = GameServer()->GetPlayerChar(GameServer()->m_apPlayers[SnappingClient]->m_SpectatorID); + + int Tick = (Server()->Tick()%Server()->TickSpeed())%11; + if (Char && Char->IsAlive() && + (m_Layer == LAYER_SWITCH && + !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[Char->Team()]) + && (!Tick)) + return; + + CNetObj_Pickup *pP = static_cast<CNetObj_Pickup *>(Server()->SnapNewItem(NETOBJTYPE_PICKUP, m_ID, sizeof(CNetObj_Pickup))); + if(!pP) + return; + + pP->m_X = (int)m_Pos.x; + pP->m_Y = (int)m_Pos.y; + pP->m_Type = m_Type; + pP->m_Subtype = m_Subtype; +} + +void CPickup::Move() +{ + if (Server()->Tick()%int(Server()->TickSpeed() * 0.15f) == 0) + { + int Flags; + int index = GameServer()->Collision()->IsMover(m_Pos.x,m_Pos.y, &Flags); + if (index) + { + m_Core=GameServer()->Collision()->CpSpeed(index, Flags); + } + m_Pos += m_Core; + } +} diff --git a/src/game/server/entities/pickup.h b/src/game/server/entities/pickup.h new file mode 100644 index 0000000..8e5529f --- /dev/null +++ b/src/game/server/entities/pickup.h @@ -0,0 +1,32 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_PICKUP_H +#define GAME_SERVER_ENTITIES_PICKUP_H + +#include <game/server/entity.h> + +const int PickupPhysSize = 14; + +class CPickup : public CEntity +{ +public: + CPickup(CGameWorld *pGameWorld, int Type, int SubType = 0, int Layer = 0, int Number = 0); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +private: + + int m_Type; + int m_Subtype; + //int m_SpawnTick; + + // DDRace + + void Move(); + vec2 m_Core; +}; + +#endif diff --git a/src/game/server/entities/plasma.cpp b/src/game/server/entities/plasma.cpp new file mode 100644 index 0000000..063e4ea --- /dev/null +++ b/src/game/server/entities/plasma.cpp @@ -0,0 +1,127 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include <engine/server.h> +#include <engine/config.h> +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <game/server/teams.h> +#include <game/server/gamemodes/DDRace.h> +#include "plasma.h" + +const float ACCEL = 1.1f; + +CPlasma::CPlasma(CGameWorld *pGameWorld, vec2 Pos, vec2 Dir, bool Freeze, + bool Explosive, int ResponsibleTeam) : + CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) +{ + m_Pos = Pos; + m_Core = Dir; + m_Freeze = Freeze; + m_Explosive = Explosive; + m_EvalTick = Server()->Tick(); + m_LifeTime = Server()->TickSpeed() * 1.5; + m_ResponsibleTeam = ResponsibleTeam; + GameWorld()->InsertEntity(this); +} + +bool CPlasma::HitCharacter() +{ + vec2 To2; + CCharacter *Hit = GameServer()->m_World.IntersectCharacter(m_Pos, + m_Pos + m_Core, 0.0f, To2); + if (!Hit) + return false; + + if (Hit->Team() != m_ResponsibleTeam) + return false; + m_Freeze ? Hit->Freeze() : Hit->UnFreeze(); + if (m_Explosive) + GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true, + m_ResponsibleTeam, Hit->Teams()->TeamMask(m_ResponsibleTeam)); + GameServer()->m_World.DestroyEntity(this); + return true; +} + +void CPlasma::Move() +{ + m_Pos += m_Core; + m_Core *= ACCEL; +} + +void CPlasma::Reset() +{ + GameServer()->m_World.DestroyEntity(this); +} + +void CPlasma::Tick() +{ + if (m_LifeTime == 0) + { + Reset(); + return; + } + m_LifeTime--; + Move(); + HitCharacter(); + + int Res = 0; + Res = GameServer()->Collision()->IntersectNoLaser(m_Pos, m_Pos + m_Core, 0, + 0); + if (Res) + { + if (m_Explosive) + GameServer()->CreateExplosion( + m_Pos, + -1, + WEAPON_GRENADE, + true, + m_ResponsibleTeam, + ((CGameControllerDDRace*) GameServer()->m_pController)->m_Teams.TeamMask( + m_ResponsibleTeam)); + Reset(); + } + +} + +void CPlasma::Snap(int SnappingClient) +{ + if (NetworkClipped(SnappingClient)) + return; + CCharacter* SnapChar = GameServer()->GetPlayerChar(SnappingClient); + CPlayer* SnapPlayer = SnappingClient > -1 ? GameServer()->m_apPlayers[SnappingClient] : 0; + int Tick = (Server()->Tick() % Server()->TickSpeed()) % 11; + + if (SnapChar && SnapChar->IsAlive() + && (m_Layer == LAYER_SWITCH + && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[SnapChar->Team()]) + && (!Tick)) + return; + + if(SnapPlayer && (SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->m_Paused) && SnapPlayer->m_SpectatorID != -1 + && GameServer()->GetPlayerChar(SnapPlayer->m_SpectatorID) + && GameServer()->GetPlayerChar(SnapPlayer->m_SpectatorID)->Team() != m_ResponsibleTeam + && !SnapPlayer->m_ShowOthers) + return; + + if(SnapPlayer && SnapPlayer->GetTeam() != TEAM_SPECTATORS && !SnapPlayer->m_Paused && SnapChar + && SnapChar && SnapChar->Team() != m_ResponsibleTeam + && !SnapPlayer->m_ShowOthers) + return; + + if(SnapPlayer && (SnapPlayer->GetTeam() == TEAM_SPECTATORS || SnapPlayer->m_Paused) && SnapPlayer->m_SpectatorID == -1 + && SnapChar + && SnapChar->Team() != m_ResponsibleTeam + && SnapPlayer->m_SpecTeam) + return; + + CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem( + NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); + + if(!pObj) + return; + + pObj->m_X = (int) m_Pos.x; + pObj->m_Y = (int) m_Pos.y; + pObj->m_FromX = (int) m_Pos.x; + pObj->m_FromY = (int) m_Pos.y; + pObj->m_StartTick = m_EvalTick; +} diff --git a/src/game/server/entities/plasma.h b/src/game/server/entities/plasma.h new file mode 100644 index 0000000..0052a3a --- /dev/null +++ b/src/game/server/entities/plasma.h @@ -0,0 +1,31 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef PLASMA_TYPE +#define PLASMA_TYPE + +#include <game/server/entity.h> + +class CGun; + +class CPlasma: public CEntity +{ + vec2 m_Core; + int m_EvalTick; + int m_LifeTime; + + int m_ResponsibleTeam; + int m_Freeze; + + bool m_Explosive; + bool HitCharacter(); + void Move(); +public: + + CPlasma(CGameWorld *pGameWorld, vec2 Pos, vec2 Dir, bool Freeze, + bool Explosive, int ResponsibleTeam); + + virtual void Reset(); + virtual void Tick(); + virtual void Snap(int SnappingClient); +}; + +#endif diff --git a/src/game/server/entities/projectile.cpp b/src/game/server/entities/projectile.cpp new file mode 100644 index 0000000..1f039e0 --- /dev/null +++ b/src/game/server/entities/projectile.cpp @@ -0,0 +1,307 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <game/generated/protocol.h> +#include <game/server/gamecontext.h> +#include <game/server/gamemodes/WarioWare.h> +#include "projectile.h" + +#include <engine/shared/config.h> +#include <game/server/teams.h> + +CProjectile::CProjectile + ( + CGameWorld *pGameWorld, + int Type, + int Owner, + vec2 Pos, + vec2 Dir, + int Span, + bool Freeze, + bool Explosive, + float Force, + int SoundImpact, + int Weapon, + int Layer, + int Number + ) +: CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) +{ + m_Type = Type; + m_Pos = Pos; + m_Direction = Dir; + m_LifeSpan = Span; + m_Owner = Owner; + m_Force = Force; + //m_Damage = Damage; + m_SoundImpact = SoundImpact; + m_Weapon = Weapon; + m_StartTick = Server()->Tick(); + m_Explosive = Explosive; + + m_Layer = Layer; + m_Number = Number; + m_Freeze = Freeze; + + m_TuneZone = GameServer()->Collision()->IsTune(GameServer()->Collision()->GetMapIndex(m_Pos)); + + GameWorld()->InsertEntity(this); +} + +void CProjectile::Reset() +{ + if(m_LifeSpan > -2) + GameServer()->m_World.DestroyEntity(this); +} + +vec2 CProjectile::GetPos(float Time) +{ + float Curvature = 0; + float Speed = 0; + + switch(m_Type) + { + case WEAPON_GRENADE: + if (!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_GrenadeCurvature; + Speed = GameServer()->Tuning()->m_GrenadeSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_GrenadeCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_GrenadeSpeed; + } + + break; + + case WEAPON_SHOTGUN: + if (!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_ShotgunCurvature; + Speed = GameServer()->Tuning()->m_ShotgunSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_ShotgunCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_ShotgunSpeed; + } + + break; + + case WEAPON_GUN: + if (!m_TuneZone) + { + Curvature = GameServer()->Tuning()->m_GunCurvature; + Speed = GameServer()->Tuning()->m_GunSpeed; + } + else + { + Curvature = GameServer()->TuningList()[m_TuneZone].m_GunCurvature; + Speed = GameServer()->TuningList()[m_TuneZone].m_GunSpeed; + } + break; + } + + return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); +} + + +void CProjectile::Tick() +{ + float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed(); + float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + vec2 PrevPos = GetPos(Pt); + vec2 CurPos = GetPos(Ct); + vec2 ColPos; + vec2 NewPos; + int Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &ColPos, &NewPos, false); + CCharacter *pOwnerChar = 0; + + if(m_Owner >= 0) + pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + + CCharacter *pTargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, ColPos, m_Freeze ? 1.0f : 6.0f, ColPos, pOwnerChar, m_Owner); + + if(m_LifeSpan > -1) + m_LifeSpan--; + + int64_t TeamMask = -1LL; + bool isWeaponCollide = false; + if + ( + pOwnerChar && + pTargetChr && + pOwnerChar->IsAlive() && + pTargetChr->IsAlive() && + !pTargetChr->CanCollide(m_Owner) + ) + { + isWeaponCollide = true; + //TeamMask = OwnerChar->Teams()->TeamMask( OwnerChar->Team()); + } + if (pOwnerChar && pOwnerChar->IsAlive()) + { + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + } + else if (m_Owner >= 0) + { + GameServer()->m_World.DestroyEntity(this); + } + + if( ((pTargetChr && (pOwnerChar ? !(pOwnerChar->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || m_Owner == -1 || pTargetChr == pOwnerChar)) || Collide || GameLayerClipped(CurPos)) && !isWeaponCollide) + { + if(m_Explosive/*??*/ && (!pTargetChr || (pTargetChr && (!m_Freeze || (m_Weapon == WEAPON_SHOTGUN && Collide))))) + { + GameServer()->CreateExplosion(ColPos, m_Owner, m_Weapon, m_Owner == -1, (!pTargetChr ? -1 : pTargetChr->Team()), + (m_Owner != -1)? TeamMask : -1LL); + GameServer()->CreateSound(ColPos, m_SoundImpact, + (m_Owner != -1)? TeamMask : -1LL); + } + else if(pTargetChr && m_Freeze && ((m_Layer == LAYER_SWITCH && GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pTargetChr->Team()]) || m_Layer != LAYER_SWITCH)) + { + pTargetChr->Freeze(); + } + if(Collide && m_Bouncing != 0) + { + m_StartTick = Server()->Tick(); + m_Pos = NewPos+(-(m_Direction*4)); + if (m_Bouncing == 1) + m_Direction.x = -m_Direction.x; + else if(m_Bouncing == 2) + m_Direction.y = -m_Direction.y; + if (fabs(m_Direction.x) < 1e-6) + m_Direction.x = 0; + if (fabs(m_Direction.y) < 1e-6) + m_Direction.y = 0; + m_Pos += m_Direction; + } + else if (m_Weapon == WEAPON_GUN) + { + GameServer()->CreateDamageInd(CurPos, -atan2(m_Direction.x, m_Direction.y), 10, (m_Owner != -1)? TeamMask : -1LL); + GameServer()->m_World.DestroyEntity(this); + } + else + if (!m_Freeze) + GameServer()->m_World.DestroyEntity(this); + } + if(m_LifeSpan == -1) + { + if(m_Explosive) + { + if(m_Owner >= 0) + pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + + int64_t TeamMask = -1LL; + if (pOwnerChar && pOwnerChar->IsAlive()) + { + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + } + + GameServer()->CreateExplosion(ColPos, m_Owner, m_Weapon, m_Owner == -1, (!pOwnerChar ? -1 : pOwnerChar->Team()), + (m_Owner != -1)? TeamMask : -1LL); + GameServer()->CreateSound(ColPos, m_SoundImpact, + (m_Owner != -1)? TeamMask : -1LL); + } + GameServer()->m_World.DestroyEntity(this); + } + + int x = GameServer()->Collision()->GetIndex(PrevPos, CurPos); + int z; + if (g_Config.m_SvOldTeleportWeapons) + z = GameServer()->Collision()->IsTeleport(x); + else + z = GameServer()->Collision()->IsTeleportWeapon(x); + if (z && ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1].size()) + { + int Num = ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1].size(); + m_Pos = ((CGameControllerWarioWare*)GameServer()->m_pController)->m_TeleOuts[z-1][(!Num)?Num:rand() % Num]; + m_StartTick = Server()->Tick(); + } +} + +void CProjectile::TickPaused() +{ + ++m_StartTick; +} + +void CProjectile::FillInfo(CNetObj_Projectile *pProj) +{ + pProj->m_X = (int)m_Pos.x; + pProj->m_Y = (int)m_Pos.y; + pProj->m_VelX = (int)(m_Direction.x*100.0f); + pProj->m_VelY = (int)(m_Direction.y*100.0f); + pProj->m_StartTick = m_StartTick; + pProj->m_Type = m_Type; +} + +void CProjectile::Snap(int SnappingClient) +{ + float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); + + if(NetworkClipped(SnappingClient, GetPos(Ct))) + return; + + CCharacter* pSnapChar = GameServer()->GetPlayerChar(SnappingClient); + int Tick = (Server()->Tick()%Server()->TickSpeed())%((m_Explosive)?6:20); + if (pSnapChar && pSnapChar->IsAlive() && (m_Layer == LAYER_SWITCH && !GameServer()->Collision()->m_pSwitchers[m_Number].m_Status[pSnapChar->Team()] && (!Tick))) + return; + + CCharacter *pOwnerChar = 0; + int64_t TeamMask = -1LL; + + if(m_Owner >= 0) + pOwnerChar = GameServer()->GetPlayerChar(m_Owner); + + if (pOwnerChar && pOwnerChar->IsAlive()) + TeamMask = pOwnerChar->Teams()->TeamMask(pOwnerChar->Team(), -1, m_Owner); + + if(m_Owner != -1 && !CmaskIsSet(TeamMask, SnappingClient)) + return; + + CNetObj_Projectile *pProj = static_cast<CNetObj_Projectile *>(Server()->SnapNewItem(NETOBJTYPE_PROJECTILE, m_ID, sizeof(CNetObj_Projectile))); + if(pProj) + { + if(SnappingClient > -1 && GameServer()->m_apPlayers[SnappingClient] && GameServer()->m_apPlayers[SnappingClient]->m_ClientVersion >= VERSION_DDNET_ANTIPING_PROJECTILE) + FillExtraInfo(pProj); + else + FillInfo(pProj); + } +} + +// DDRace + +void CProjectile::SetBouncing(int Value) +{ + m_Bouncing = Value; +} + +void CProjectile::FillExtraInfo(CNetObj_Projectile *pProj) +{ + const int MaxPos = 0x7fffffff/100; + if(abs((int)m_Pos.y)+1 >= MaxPos || abs((int)m_Pos.x)+1 >= MaxPos) + { + //If the modified data would be too large to fit in an integer, send normal data instead + FillInfo(pProj); + return; + } + //Send additional/modified info, by modifiying the fields of the netobj + float Angle = -atan2f(m_Direction.x, m_Direction.y); + + int Data = 0; + Data |= (abs(m_Owner) & 255)<<0; + if(m_Owner < 0) + Data |= 1<<8; + Data |= 1<<9; //This bit tells the client to use the extra info + Data |= (m_Bouncing & 3)<<10; + if(m_Explosive) + Data |= 1<<12; + if(m_Freeze) + Data |= 1<<13; + + pProj->m_X = (int)(m_Pos.x * 100.0f); + pProj->m_Y = (int)(m_Pos.y * 100.0f); + pProj->m_VelX = (int)(Angle * 1000000.0f); + pProj->m_VelY = Data; + pProj->m_StartTick = m_StartTick; + pProj->m_Type = m_Type; +} diff --git a/src/game/server/entities/projectile.h b/src/game/server/entities/projectile.h new file mode 100644 index 0000000..9f745df --- /dev/null +++ b/src/game/server/entities/projectile.h @@ -0,0 +1,58 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITIES_PROJECTILE_H +#define GAME_SERVER_ENTITIES_PROJECTILE_H + +class CProjectile : public CEntity +{ +public: + CProjectile + ( + CGameWorld *pGameWorld, + int Type, + int Owner, + vec2 Pos, + vec2 Dir, + int Span, + bool Freeeze, + bool Explosive, + float Force, + int SoundImpact, + int Weapon, + int Layer = 0, + int Number = 0 + ); + + vec2 GetPos(float Time); + void FillInfo(CNetObj_Projectile *pProj); + + virtual void Reset(); + virtual void Tick(); + virtual void TickPaused(); + virtual void Snap(int SnappingClient); + +private: + vec2 m_Direction; + int m_LifeSpan; + int m_Owner; + int m_Type; + //int m_Damage; + int m_SoundImpact; + int m_Weapon; + float m_Force; + int m_StartTick; + bool m_Explosive; + + // DDRace + + int m_Bouncing; + bool m_Freeze; + int m_TuneZone; + +public: + + void SetBouncing(int Value); + void FillExtraInfo(CNetObj_Projectile *pProj); +}; + +#endif diff --git a/src/game/server/entity.cpp b/src/game/server/entity.cpp new file mode 100644 index 0000000..d288efe --- /dev/null +++ b/src/game/server/entity.cpp @@ -0,0 +1,56 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "entity.h" +#include "gamecontext.h" + +////////////////////////////////////////////////// +// Entity +////////////////////////////////////////////////// +CEntity::CEntity(CGameWorld *pGameWorld, int ObjType) +{ + m_pGameWorld = pGameWorld; + + m_ObjType = ObjType; + m_Pos = vec2(0,0); + m_ProximityRadius = 0; + + m_MarkedForDestroy = false; + m_ID = Server()->SnapNewID(); + + m_pPrevTypeEntity = 0; + m_pNextTypeEntity = 0; +} + +CEntity::~CEntity() +{ + GameWorld()->RemoveEntity(this); + Server()->SnapFreeID(m_ID); +} + +int CEntity::NetworkClipped(int SnappingClient) +{ + return NetworkClipped(SnappingClient, m_Pos); +} + +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) > 4000.0f) + return 1; + return 0; +} + +bool CEntity::GameLayerClipped(vec2 CheckPos) +{ + return round_to_int(CheckPos.x)/32 < -200 || round_to_int(CheckPos.x)/32 > GameServer()->Collision()->GetWidth()+200 || + round_to_int(CheckPos.y)/32 < -200 || round_to_int(CheckPos.y)/32 > GameServer()->Collision()->GetHeight()+200 ? true : false; +} diff --git a/src/game/server/entity.h b/src/game/server/entity.h new file mode 100644 index 0000000..2d4ef09 --- /dev/null +++ b/src/game/server/entity.h @@ -0,0 +1,164 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_ENTITY_H +#define GAME_SERVER_ENTITY_H + +#include <new> +#include <base/vmath.h> +#include <game/server/gameworld.h> + +#define MACRO_ALLOC_HEAP() \ + public: \ + void *operator new(size_t Size) \ + { \ + void *p = mem_alloc(Size, 1); \ + /*dbg_msg("", "++ %p %d", p, size);*/ \ + mem_zero(p, Size); \ + return p; \ + } \ + void operator delete(void *pPtr) \ + { \ + /*dbg_msg("", "-- %p", p);*/ \ + mem_free(pPtr); \ + } \ + private: + +#define MACRO_ALLOC_POOL_ID() \ + public: \ + 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}; \ + void *POOLTYPE::operator new(size_t Size, int id) \ + { \ + dbg_assert(sizeof(POOLTYPE) == Size, "size error"); \ + dbg_assert(!ms_PoolUsed##POOLTYPE[id], "already used"); \ + /*dbg_msg("pool", "++ %s %d", #POOLTYPE, id);*/ \ + ms_PoolUsed##POOLTYPE[id] = 1; \ + mem_zero(ms_PoolData##POOLTYPE[id], Size); \ + return ms_PoolData##POOLTYPE[id]; \ + } \ + void POOLTYPE::operator delete(void *p) \ + { \ + int id = (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE; \ + dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ + /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ + ms_PoolUsed##POOLTYPE[id] = 0; \ + mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ + } + +/* + Class: Entity + Basic entity class. +*/ +class CEntity +{ + MACRO_ALLOC_HEAP() + + friend class CGameWorld; // entity list handling + CEntity *m_pPrevTypeEntity; + CEntity *m_pNextTypeEntity; + +protected: + class CGameWorld *m_pGameWorld; + bool m_MarkedForDestroy; + int m_ID; + int m_ObjType; +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; } + + /* + Function: destroy + 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 + and moves the entity to it's new state and position. + */ + virtual void Tick() {} + + /* + Function: tick_defered + Called after all entities tick() function has been called. + */ + virtual void TickDefered() {} + + /* + Function: TickPaused + Called when the game is paused, to freeze the state and position of the entity. + */ + virtual void TickPaused() {} + + /* + 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 + snapshot of everything in the game for demo + recording. + */ + virtual void Snap(int SnappingClient) {} + + /* + Function: networkclipped(int snapping_client) + Performs a series of test to see if a client can see the + entity. + + Arguments: + snapping_client - ID of the client which snapshot is + 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. + */ + virtual int NetworkClipped(int SnappingClient); + virtual int NetworkClipped(int SnappingClient, vec2 CheckPos); + + bool GameLayerClipped(vec2 CheckPos); + + /* + Variable: proximity_radius + Contains the physical size of the entity. + */ + float m_ProximityRadius; + + /* + Variable: pos + Contains the current posititon of the entity. + */ + vec2 m_Pos; + + // DDRace + + int m_Number; + int m_Layer; +}; + +#endif diff --git a/src/game/server/eventhandler.cpp b/src/game/server/eventhandler.cpp new file mode 100644 index 0000000..a846285 --- /dev/null +++ b/src/game/server/eventhandler.cpp @@ -0,0 +1,58 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include "eventhandler.h" +#include "gamecontext.h" + +////////////////////////////////////////////////// +// Event handler +////////////////////////////////////////////////// +CEventHandler::CEventHandler() +{ + m_pGameServer = 0; + Clear(); +} + +void CEventHandler::SetGameServer(CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; +} + +void *CEventHandler::Create(int Type, int Size, int64_t Mask) +{ + if(m_NumEvents == MAX_EVENTS) + return 0; + if(m_CurrentOffset+Size >= MAX_DATASIZE) + return 0; + + void *p = &m_aData[m_CurrentOffset]; + m_aOffsets[m_NumEvents] = m_CurrentOffset; + m_aTypes[m_NumEvents] = Type; + m_aSizes[m_NumEvents] = Size; + m_aClientMasks[m_NumEvents] = Mask; + m_CurrentOffset += Size; + m_NumEvents++; + return p; +} + +void CEventHandler::Clear() +{ + m_NumEvents = 0; + m_CurrentOffset = 0; +} + +void CEventHandler::Snap(int SnappingClient) +{ + for(int i = 0; i < m_NumEvents; i++) + { + if(SnappingClient == -1 || CmaskIsSet(m_aClientMasks[i], SnappingClient)) + { + CNetEvent_Common *ev = (CNetEvent_Common *)&m_aData[m_aOffsets[i]]; + if(SnappingClient == -1 || distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, vec2(ev->m_X, ev->m_Y)) < 1500.0f) + { + void *d = GameServer()->Server()->SnapNewItem(m_aTypes[i], i, m_aSizes[i]); + if(d) + mem_copy(d, &m_aData[m_aOffsets[i]], m_aSizes[i]); + } + } + } +} diff --git a/src/game/server/eventhandler.h b/src/game/server/eventhandler.h new file mode 100644 index 0000000..e3a62c5 --- /dev/null +++ b/src/game/server/eventhandler.h @@ -0,0 +1,40 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_EVENTHANDLER_H +#define GAME_SERVER_EVENTHANDLER_H + +#ifdef _MSC_VER +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include <stdint.h> +#endif +// +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_aOffsets[MAX_EVENTS]; + int m_aSizes[MAX_EVENTS]; + int64_t 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, int64_t Mask = -1LL); + void Clear(); + void Snap(int SnappingClient); +}; + +#endif diff --git a/src/game/server/gamecontext.cpp b/src/game/server/gamecontext.cpp new file mode 100644 index 0000000..ed58c23 --- /dev/null +++ b/src/game/server/gamecontext.cpp @@ -0,0 +1,3341 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <base/tl/sorted_array.h> + +#include <new> +#include <base/math.h> +#include <engine/shared/config.h> +#include <engine/map.h> +#include <engine/console.h> +#include <engine/shared/datafile.h> +#include <engine/shared/linereader.h> +#include <engine/storage.h> +#include "gamecontext.h" +#include <game/version.h> +#include <game/collision.h> +#include <game/gamecore.h> +/*#include "gamemodes/dm.h" +#include "gamemodes/tdm.h" +#include "gamemodes/ctf.h" +#include "gamemodes/mod.h"*/ + +#include <stdio.h> +#include <string.h> +#include <engine/server/server.h> +#include "gamemodes/WarioWare.h" +#include "score.h" +#include "score/file_score.h" +#include <time.h> +#include <pthread.h> +#include <stdlib.h> +#include <unistd.h> +#if defined(CONF_SQL) +#include "score/sql_score.h" +#endif + +enum +{ + RESET, + NO_RESET +}; + +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; + m_pVoteOptionLast = 0; + m_NumVoteOptions = 0; + m_LastMapVote = 0; + //m_LockTeams = 0; + + if(Resetting==NO_RESET) + { + m_pVoteOptionHeap = new CHeap(); + m_pScore = 0; + m_NumMutes = 0; + } + m_ChatResponseTargetID = -1; + m_aDeleteTempfile[0] = 0; +} + +CGameContext::CGameContext(int Resetting) +{ + Construct(Resetting); +} + +CGameContext::CGameContext() +{ + Construct(NO_RESET); +} + +CGameContext::~CGameContext() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + delete m_apPlayers[i]; + if(!m_Resetting) + delete m_pVoteOptionHeap; + + if(m_pScore) + delete m_pScore; +} + +void CGameContext::Clear() +{ + CHeap *pVoteOptionHeap = m_pVoteOptionHeap; + CVoteOptionServer *pVoteOptionFirst = m_pVoteOptionFirst; + CVoteOptionServer *pVoteOptionLast = m_pVoteOptionLast; + int NumVoteOptions = m_NumVoteOptions; + CTuningParams Tuning = m_Tuning; + + m_Resetting = true; + this->~CGameContext(); + mem_zero(this, sizeof(*this)); + new (this) CGameContext(RESET); + + m_pVoteOptionHeap = pVoteOptionHeap; + m_pVoteOptionFirst = pVoteOptionFirst; + m_pVoteOptionLast = pVoteOptionLast; + m_NumVoteOptions = NumVoteOptions; + m_Tuning = Tuning; +} + + +class CCharacter *CGameContext::GetPlayerChar(int ClientID) +{ + if(ClientID < 0 || ClientID >= MAX_CLIENTS || !m_apPlayers[ClientID]) + return 0; + return m_apPlayers[ClientID]->GetCharacter(); +} + +void CGameContext::CreateDamageInd(vec2 Pos, float Angle, int Amount, int64_t Mask) +{ + float a = 3 * 3.14159f / 2 + Angle; + //float a = get_angle(dir); + float s = a-pi/3; + float e = a+pi/3; + for(int i = 0; i < Amount; i++) + { + float f = mix(s, e, float(i+1)/float(Amount+2)); + CNetEvent_DamageInd *pEvent = (CNetEvent_DamageInd *)m_Events.Create(NETEVENTTYPE_DAMAGEIND, sizeof(CNetEvent_DamageInd), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_Angle = (int)(f*256.0f); + } + } +} + +void CGameContext::CreateHammerHit(vec2 Pos, int64_t Mask) +{ + // create the event + CNetEvent_HammerHit *pEvent = (CNetEvent_HammerHit *)m_Events.Create(NETEVENTTYPE_HAMMERHIT, sizeof(CNetEvent_HammerHit), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + } +} + + +int CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, int ActivatedTeam, int64_t Mask) +{ + // create the event + CNetEvent_Explosion *pEvent = (CNetEvent_Explosion *)m_Events.Create(NETEVENTTYPE_EXPLOSION, sizeof(CNetEvent_Explosion), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + } +/* + if (!NoDamage) + { + */ + // deal damage + CCharacter *apEnts[MAX_CLIENTS]; + float Radius = 135.0f; + float InnerRadius = 48.0f; + int Num = m_World.FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + for(int i = 0; i < Num; i++) + { + vec2 Diff = apEnts[i]->m_Pos - Pos; + vec2 ForceDir(0,1); + float l = length(Diff); + if(l) + ForceDir = normalize(Diff); + l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); + float Strength; + if (Owner == -1 || !m_apPlayers[Owner] || !m_apPlayers[Owner]->m_TuneZone) + Strength = Tuning()->m_ExplosionStrength; + else + Strength = TuningList()[m_apPlayers[Owner]->m_TuneZone].m_ExplosionStrength; + + float Dmg = Strength * l; + if((int)Dmg) + { + if((GetPlayerChar(Owner) ? !(GetPlayerChar(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE) : g_Config.m_SvHit || NoDamage) || Owner == apEnts[i]->GetPlayer()->GetCID()) + { + if(Owner != -1 && apEnts[i]->IsAlive() && !apEnts[i]->CanCollide(Owner)) continue; + if(Owner == -1 && ActivatedTeam != -1 && apEnts[i]->IsAlive() && apEnts[i]->Team() != ActivatedTeam) continue; + apEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon); + if(GetPlayerChar(Owner) ? GetPlayerChar(Owner)->m_Hit&CCharacter::DISABLE_HIT_GRENADE : !g_Config.m_SvHit || NoDamage) break; + } + } + } + //} + + return Num; +} + +/* +void create_smoke(vec2 Pos) +{ + // create the event + EV_EXPLOSION *pEvent = (EV_EXPLOSION *)events.create(EVENT_SMOKE, sizeof(EV_EXPLOSION)); + if(pEvent) + { + pEvent->x = (int)Pos.x; + pEvent->y = (int)Pos.y; + } +}*/ + +void CGameContext::CreatePlayerSpawn(vec2 Pos, int64_t Mask) +{ + // create the event + CNetEvent_Spawn *ev = (CNetEvent_Spawn *)m_Events.Create(NETEVENTTYPE_SPAWN, sizeof(CNetEvent_Spawn), Mask); + if(ev) + { + ev->m_X = (int)Pos.x; + ev->m_Y = (int)Pos.y; + } +} + +void CGameContext::CreateDeath(vec2 Pos, int ClientID, int64_t Mask) +{ + // create the event + CNetEvent_Death *pEvent = (CNetEvent_Death *)m_Events.Create(NETEVENTTYPE_DEATH, sizeof(CNetEvent_Death), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_ClientID = ClientID; + } +} + +void CGameContext::CreateSound(vec2 Pos, int Sound, int64_t Mask) +{ + if (Sound < 0) + return; + + // create a sound + CNetEvent_SoundWorld *pEvent = (CNetEvent_SoundWorld *)m_Events.Create(NETEVENTTYPE_SOUNDWORLD, sizeof(CNetEvent_SoundWorld), Mask); + if(pEvent) + { + pEvent->m_X = (int)Pos.x; + pEvent->m_Y = (int)Pos.y; + pEvent->m_SoundID = Sound; + } +} + +void CGameContext::CreateSoundGlobal(int Sound, int Target) +{ + if (Sound < 0) + return; + + CNetMsg_Sv_SoundGlobal Msg; + Msg.m_SoundID = Sound; + if(Target == -2) + Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1); + else + { + int Flag = MSGFLAG_VITAL; + if(Target != -1) + Flag |= MSGFLAG_NORECORD; + Server()->SendPackMsg(&Msg, Flag, Target); + } +} + +void CGameContext::CallVote(int ClientID, const char *pDesc, const char *pCmd, const char *pReason, const char *pChatmsg) +{ + // check if a vote is already running + if(m_VoteCloseTime) + return; + + int64 Now = Server()->Tick(); + CPlayer *pPlayer = m_apPlayers[ClientID]; + + if(!pPlayer) + return; + + SendChat(-1, CGameContext::CHAT_ALL, pChatmsg); + StartVote(pDesc, pCmd, pReason); + pPlayer->m_Vote = 1; + pPlayer->m_VotePos = m_VotePos = 1; + m_VoteCreator = ClientID; + pPlayer->m_LastVoteCall = Now; +} + +void CGameContext::SendChatTarget(int To, const char *pText) +{ + CNetMsg_Sv_Chat Msg; + Msg.m_Team = 0; + Msg.m_ClientID = -1; + Msg.m_pMessage = pText; + if(g_Config.m_SvDemoChat) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, To); + else + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, To); +} + +void CGameContext::SendChatTeam(int Team, const char *pText) +{ + for(int i = 0; i<MAX_CLIENTS; i++) + if(((CGameControllerWarioWare*)m_pController)->m_Teams.m_Core.Team(i) == Team) + SendChatTarget(i, pText); +} + +void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText, int SpamProtectionClientID) +{ + if(SpamProtectionClientID >= 0 && SpamProtectionClientID < MAX_CLIENTS) + { + if(ProcessSpamProtection(SpamProtectionClientID)) + { + //SendChatTarget(SpamProtectionClientID, "Muted text:"); + //SendChatTarget(SpamProtectionClientID, pText); + return; + } + } + + char aBuf[256], aText[256]; + str_copy(aText, pText, sizeof(aText)); + if(ChatterClientID >= 0 && ChatterClientID < MAX_CLIENTS) + str_format(aBuf, sizeof(aBuf), "%d:%d:%s: %s", ChatterClientID, Team, Server()->ClientName(ChatterClientID), aText); + else if(ChatterClientID == -2) + { + str_format(aBuf, sizeof(aBuf), "### %s", aText); + str_copy(aText, aBuf, sizeof(aText)); + ChatterClientID = -1; + } + else + str_format(aBuf, sizeof(aBuf), "*** %s", aText); + Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, Team!=CHAT_ALL?"teamchat":"chat", aBuf); + + if(Team == CHAT_ALL) + { + CNetMsg_Sv_Chat Msg; + Msg.m_Team = 0; + Msg.m_ClientID = ChatterClientID; + Msg.m_pMessage = aText; + + // pack one for the recording only + if(g_Config.m_SvDemoChat) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + + // send to the clients + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i] != 0) { + if(!m_apPlayers[i]->m_DND) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + } + } + else + { + CTeamsCore * Teams = &((CGameControllerWarioWare*)m_pController)->m_Teams.m_Core; + CNetMsg_Sv_Chat Msg; + Msg.m_Team = 1; + Msg.m_ClientID = ChatterClientID; + Msg.m_pMessage = aText; + + // pack one for the recording only + if(g_Config.m_SvDemoChat) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); + + // send to the clients + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i] != 0) { + if(Team == CHAT_SPEC) { + if(m_apPlayers[i]->GetTeam() == CHAT_SPEC) { + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + } else { + if(Teams->Team(i) == Team && m_apPlayers[i]->GetTeam() != CHAT_SPEC) { + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); + } + } + } + } + } +} + +void CGameContext::SendEmoticon(int ClientID, int Emoticon) +{ + CNetMsg_Sv_Emoticon Msg; + Msg.m_ClientID = ClientID; + Msg.m_Emoticon = Emoticon; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); +} + +void CGameContext::SendWeaponPickup(int ClientID, int Weapon) +{ + CNetMsg_Sv_WeaponPickup Msg; + Msg.m_Weapon = Weapon; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + + +void CGameContext::SendBroadcast(const char *pText, int ClientID) +{ + CNetMsg_Sv_Broadcast Msg; + Msg.m_pMessage = pText; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +// +void CGameContext::StartVote(const char *pDesc, const char *pCommand, const char *pReason) +{ + // reset votes + m_VoteEnforce = VOTE_ENFORCE_UNKNOWN; + m_VoteEnforcer = -1; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + { + m_apPlayers[i]->m_Vote = 0; + m_apPlayers[i]->m_VotePos = 0; + } + } + + // start vote + m_VoteCloseTime = time_get() + time_freq() * g_Config.m_SvVoteTime; + str_copy(m_aVoteDescription, pDesc, sizeof(m_aVoteDescription)); + str_copy(m_aVoteCommand, pCommand, sizeof(m_aVoteCommand)); + str_copy(m_aVoteReason, pReason, sizeof(m_aVoteReason)); + SendVoteSet(-1); + m_VoteUpdate = true; +} + + +void CGameContext::EndVote() +{ + m_VoteCloseTime = 0; + SendVoteSet(-1); +} + +void CGameContext::SendVoteSet(int ClientID) +{ + CNetMsg_Sv_VoteSet Msg; + if(m_VoteCloseTime) + { + Msg.m_Timeout = (m_VoteCloseTime-time_get())/time_freq(); + Msg.m_pDescription = m_aVoteDescription; + Msg.m_pReason = m_aVoteReason; + } + else + { + Msg.m_Timeout = 0; + Msg.m_pDescription = ""; + Msg.m_pReason = ""; + } + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) +{ + if (Total > VANILLA_MAX_CLIENTS && m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_ClientVersion <= VERSION_DDRACE) + { + Yes = float(Yes) * VANILLA_MAX_CLIENTS / float(Total); + No = float(No) * VANILLA_MAX_CLIENTS / float(Total); + Total = VANILLA_MAX_CLIENTS; + } + + CNetMsg_Sv_VoteStatus Msg = {0}; + Msg.m_Total = Total; + Msg.m_Yes = Yes; + Msg.m_No = No; + Msg.m_Pass = Total - (Yes+No); + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); + +} + +void CGameContext::AbortVoteKickOnDisconnect(int ClientID) +{ + if(m_VoteCloseTime && ((!str_comp_num(m_aVoteCommand, "kick ", 5) && str_toint(&m_aVoteCommand[5]) == ClientID) || + (!str_comp_num(m_aVoteCommand, "set_team ", 9) && str_toint(&m_aVoteCommand[9]) == ClientID))) + m_VoteCloseTime = -1; +} + + +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) + { + CTuningParams p; + if(mem_comp(&p, &m_Tuning, sizeof(p)) != 0) + { + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "resetting tuning due to pure server"); + m_Tuning = p; + } + } +} + +void CGameContext::SendTuningParams(int ClientID, int Zone) +{ + if (ClientID == -1) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if (m_apPlayers[i]) + { + if(m_apPlayers[i]->GetCharacter()) + { + if (m_apPlayers[i]->GetCharacter()->m_TuneZone == Zone) + SendTuningParams(i, Zone); + } + else if (m_apPlayers[i]->m_TuneZone == Zone) + { + SendTuningParams(i, Zone); + } + } + } + return; + } + + CheckPureTuning(); + + CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); + int *pParams = 0; + if (Zone == 0) + pParams = (int *)&m_Tuning; + else + pParams = (int *)&(m_TuningList[Zone]); + + unsigned int last = sizeof(m_Tuning)/sizeof(int); + if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_ClientVersion < VERSION_DDNET_EXTRATUNES) + last = 33; + else if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_ClientVersion < VERSION_DDNET_HOOKDURATION_TUNE) + last = 37; + else if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_ClientVersion < VERSION_DDNET_FIREDELAY_TUNE) + last = 38; + + for(unsigned i = 0; i < last; i++) + { + if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetCharacter()) + { + if((i==31) // collision + && (m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_SOLO + || m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOCOLL)) + { + Msg.AddInt(0); + } + else if((i==32) // hooking + && (m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_SOLO + || m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHOOK)) + { + Msg.AddInt(0); + } + else if((i==3) // ground jump impulse + && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOJUMP) + { + Msg.AddInt(0); + } + else if((i==33) // jetpack + && !(m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_JETPACK)) + { + Msg.AddInt(0); + } + else if((i==36) // hammer hit + && m_apPlayers[ClientID]->GetCharacter()->NeededFaketuning() & FAKETUNE_NOHAMMER) + { + Msg.AddInt(0); + } + else + { + Msg.AddInt(pParams[i]); + } + } + else + Msg.AddInt(pParams[i]); // if everything is normal just send true tunings + } + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} +/* +void CGameContext::SwapTeams() +{ + if(!m_pController->IsTeamplay()) + return; + + SendChat(-1, CGameContext::CHAT_ALL, "Teams were swapped"); + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + m_apPlayers[i]->SetTeam(m_apPlayers[i]->GetTeam()^1, false); + } + + (void)m_pController->CheckTeamBalance(); +} +*/ +void CGameContext::OnTick() +{ + // check tuning + CheckPureTuning(); + + // headbot + m_Collision.SetTime(m_pController->getTimerNoMS()); + + // copy tuning + m_World.m_Core.m_Tuning[0] = m_Tuning; + m_World.Tick(); + + //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]) + { + // send vote options + ProgressVoteOptions(i); + + m_apPlayers[i]->Tick(); + m_apPlayers[i]->PostTick(); + + // headbot + + } + } + + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + m_apPlayers[i]->PostPostTick(); + } + + // update voting + if(m_VoteCloseTime) + { + // abort the kick-vote on player-leave + if(m_VoteCloseTime == -1) + { + SendChat(-1, CGameContext::CHAT_ALL, "Vote aborted"); + EndVote(); + } + else + { + int Total = 0, Yes = 0, No = 0, Online = 0; + bool Veto = false, VetoStop = false; + if(m_VoteUpdate) + { + // count votes + char aaBuf[MAX_CLIENTS][NETADDR_MAXSTRSIZE] = {{0}}; + for(int i = 0; i < MAX_CLIENTS; i++) + if(m_apPlayers[i] and i < MAX_CLIENTS-1) + { + Online++; + Server()->GetClientAddr(i, aaBuf[i], NETADDR_MAXSTRSIZE); + } + bool aVoteChecked[MAX_CLIENTS] = {0}; + for(int i = 0; i < MAX_CLIENTS; i++) + { + //if(!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || aVoteChecked[i]) // don't count in votes by spectators + if(!m_apPlayers[i] || i >= MAX_CLIENTS-1 || + (g_Config.m_SvSpectatorVotes == 0 && + m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) || + aVoteChecked[i]) // don't count in votes by spectators if the admin doesn't want it + continue; + + if((m_VoteKick || m_VoteSpec) && ((!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) || + (GetPlayerChar(m_VoteCreator) && GetPlayerChar(i) && + GetPlayerChar(m_VoteCreator)->Team() != GetPlayerChar(i)->Team()))) + continue; + + if(m_apPlayers[i]->m_Afk && i != m_VoteCreator) + 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) + { + if(!m_apPlayers[j] || aVoteChecked[j] || str_comp(aaBuf[j], aaBuf[i])) + continue; + + aVoteChecked[j] = true; + if(m_apPlayers[j]->m_Vote && (!ActVote || ActVotePos > m_apPlayers[j]->m_VotePos)) + { + ActVote = m_apPlayers[j]->m_Vote; + ActVotePos = m_apPlayers[j]->m_VotePos; + } + } + + Total++; + if(ActVote > 0) + Yes++; + else if(ActVote < 0) + No++; + + // veto right for players who have been active on server for long and who're not afk + if(!m_VoteKick && !m_VoteSpec && m_apPlayers[i] && + !m_apPlayers[i]->m_Afk && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && + g_Config.m_SvVoteVetoTime && + (Server()->Tick() - m_apPlayers[i]->m_JoinTick) / (Server()->TickSpeed() * 60) > g_Config.m_SvVoteVetoTime) + { + if(ActVote == 0) + Veto = true; + else if(ActVote < 0) + VetoStop = true; + } + } + + if(g_Config.m_SvVoteMaxTotal && Total > g_Config.m_SvVoteMaxTotal && + (m_VoteKick || m_VoteSpec)) + Total = g_Config.m_SvVoteMaxTotal; + + if((Yes > Total / (100.0 / g_Config.m_SvVoteYesPercentage) or not Online) && !Veto) + m_VoteEnforce = VOTE_ENFORCE_YES; + else if(No >= Total - Total / (100.0 / g_Config.m_SvVoteYesPercentage)) + m_VoteEnforce = VOTE_ENFORCE_NO; + + if(VetoStop) + m_VoteEnforce = VOTE_ENFORCE_NO; + + m_VoteWillPass = Yes > (Yes + No) / (100.0 / g_Config.m_SvVoteYesPercentage); + } + + if(time_get() > m_VoteCloseTime && !g_Config.m_SvVoteMajority) + m_VoteEnforce = (m_VoteWillPass && !Veto) ? VOTE_ENFORCE_YES : VOTE_ENFORCE_NO; + + if(m_VoteEnforce == VOTE_ENFORCE_YES) + { + Server()->SetRconCID(IServer::RCON_CID_VOTE); + Console()->ExecuteLine(m_aVoteCommand); + Server()->SetRconCID(IServer::RCON_CID_SERV); + EndVote(); + SendChat(-1, CGameContext::CHAT_ALL, "Vote passed"); + + if(m_apPlayers[m_VoteCreator]) + m_apPlayers[m_VoteCreator]->m_LastVoteCall = 0; + } + else if(m_VoteEnforce == VOTE_ENFORCE_YES_ADMIN) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf),"Vote passed enforced by server moderator"); + Console()->ExecuteLine(m_aVoteCommand, m_VoteEnforcer); + SendChat(-1, CGameContext::CHAT_ALL, aBuf); + EndVote(); + } + else if(m_VoteEnforce == VOTE_ENFORCE_NO_ADMIN) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf),"Vote failed enforced by server moderator"); + EndVote(); + SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + //else if(m_VoteEnforce == VOTE_ENFORCE_NO || time_get() > m_VoteCloseTime) + else if(m_VoteEnforce == VOTE_ENFORCE_NO || (time_get() > m_VoteCloseTime && g_Config.m_SvVoteMajority)) + { + EndVote(); + if(VetoStop || (m_VoteWillPass && Veto)) + SendChat(-1, CGameContext::CHAT_ALL, "Vote failed because of veto. Find an empty server instead"); + else + SendChat(-1, CGameContext::CHAT_ALL, "Vote failed"); + } + else if(m_VoteUpdate) + { + m_VoteUpdate = false; + for(int i = 0; i < MAX_CLIENTS; ++i) + if(Server()->ClientIngame(i)) + SendVoteStatus(i, Total, Yes, No); + } + } + } + for(int i = 0; i < m_NumMutes; i++) + { + if(m_aMutes[i].m_Expire <= Server()->Tick()) + { + m_NumMutes--; + m_aMutes[i] = m_aMutes[m_NumMutes]; + } + } + + if(Server()->Tick() % (g_Config.m_SvAnnouncementInterval * Server()->TickSpeed() * 60) == 0) + { + char *Line = ((CServer *) Server())->GetAnnouncementLine(g_Config.m_SvAnnouncementFileName); + if(Line) + SendChat(-1, CGameContext::CHAT_ALL, Line); + } + + if(Collision()->m_NumSwitchers > 0) + for (int i = 0; i < Collision()->m_NumSwitchers+1; ++i) + { + for (int j = 0; j < MAX_CLIENTS; ++j) + { + if(Collision()->m_pSwitchers[i].m_EndTick[j] <= Server()->Tick() && Collision()->m_pSwitchers[i].m_Type[j] == TILE_SWITCHTIMEDOPEN) + { + Collision()->m_pSwitchers[i].m_Status[j] = false; + Collision()->m_pSwitchers[i].m_EndTick[j] = 0; + Collision()->m_pSwitchers[i].m_Type[j] = TILE_SWITCHCLOSE; + } + else if(Collision()->m_pSwitchers[i].m_EndTick[j] <= Server()->Tick() && Collision()->m_pSwitchers[i].m_Type[j] == TILE_SWITCHTIMEDCLOSE) + { + Collision()->m_pSwitchers[i].m_Status[j] = true; + Collision()->m_pSwitchers[i].m_EndTick[j] = 0; + Collision()->m_pSwitchers[i].m_Type[j] = TILE_SWITCHOPEN; + } + } + } + + // headbot + if (earrape_timer) earrape_timer--; + + CNetObj_PlayerInput Input = {0}; + m_apPlayers[MAX_CLIENTS-1]->OnPredictedInput(&Input); + m_apPlayers[MAX_CLIENTS-1]->OnDirectInput(&Input); +} + +void* OnPipe(void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + FILE* pipe = pSelf->pipe; + + while (pSelf->pipe) + { + char aBuf[512]; + + if (fgets(aBuf, sizeof(aBuf), pipe) != NULL) + { + if (not pSelf->pipe) break; + + strtok(aBuf, "\n"); + if (pSelf->shellBroadcast) + { + int i; + for(i = 0; aBuf[i]; i++) + { + if(aBuf[i] == '\r') + { + aBuf[i] = '\n'; + } + } + aBuf[i] = '\0'; + + pSelf->SendBroadcast(aBuf, -1); + } + else pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + else + { + if (not pSelf->pipe) break; + _pclose(pipe); + pSelf->pipe = NULL; + break; + } + } + pthread_exit(NULL); + return 0; +} + +// Server hooks +void CGameContext::OnClientDirectInput(int ClientID, void *pInput) +{ + if(!m_World.m_Paused) + m_apPlayers[ClientID]->OnDirectInput((CNetObj_PlayerInput *)pInput); +} + +void CGameContext::OnClientPredictedInput(int ClientID, void *pInput) +{ + if(!m_World.m_Paused) + m_apPlayers[ClientID]->OnPredictedInput((CNetObj_PlayerInput *)pInput); +} + +struct CVoteOptionServer *CGameContext::GetVoteOption(int Index) +{ + CVoteOptionServer *pCurrent; + for (pCurrent = m_pVoteOptionFirst; + Index > 0 && pCurrent; + Index--, pCurrent = pCurrent->m_pNext); + + if (Index > 0) + return 0; + return pCurrent; +} + +void CGameContext::ProgressVoteOptions(int ClientID) +{ + CPlayer *pPl = m_apPlayers[ClientID]; + + if (pPl->m_SendVoteIndex == -1) + return; // we didn't start sending options yet + + if (pPl->m_SendVoteIndex > m_NumVoteOptions) + return; // shouldn't happen / fail silently + + int VotesLeft = m_NumVoteOptions - pPl->m_SendVoteIndex; + int NumVotesToSend = min(g_Config.m_SvSendVotesPerTick, VotesLeft); + + if (!VotesLeft) + { + // player has up to date vote option list + return; + } + + // build vote option list msg + int CurIndex = 0; + + CNetMsg_Sv_VoteOptionListAdd OptionMsg; + OptionMsg.m_pDescription0 = ""; + OptionMsg.m_pDescription1 = ""; + OptionMsg.m_pDescription2 = ""; + OptionMsg.m_pDescription3 = ""; + OptionMsg.m_pDescription4 = ""; + OptionMsg.m_pDescription5 = ""; + OptionMsg.m_pDescription6 = ""; + OptionMsg.m_pDescription7 = ""; + OptionMsg.m_pDescription8 = ""; + OptionMsg.m_pDescription9 = ""; + OptionMsg.m_pDescription10 = ""; + OptionMsg.m_pDescription11 = ""; + OptionMsg.m_pDescription12 = ""; + OptionMsg.m_pDescription13 = ""; + OptionMsg.m_pDescription14 = ""; + + // get current vote option by index + CVoteOptionServer *pCurrent = GetVoteOption(pPl->m_SendVoteIndex); + + while(CurIndex < NumVotesToSend && pCurrent != NULL) + { + switch(CurIndex) + { + case 0: OptionMsg.m_pDescription0 = pCurrent->m_aDescription; break; + case 1: OptionMsg.m_pDescription1 = pCurrent->m_aDescription; break; + case 2: OptionMsg.m_pDescription2 = pCurrent->m_aDescription; break; + case 3: OptionMsg.m_pDescription3 = pCurrent->m_aDescription; break; + case 4: OptionMsg.m_pDescription4 = pCurrent->m_aDescription; break; + case 5: OptionMsg.m_pDescription5 = pCurrent->m_aDescription; break; + case 6: OptionMsg.m_pDescription6 = pCurrent->m_aDescription; break; + case 7: OptionMsg.m_pDescription7 = pCurrent->m_aDescription; break; + case 8: OptionMsg.m_pDescription8 = pCurrent->m_aDescription; break; + case 9: OptionMsg.m_pDescription9 = pCurrent->m_aDescription; break; + case 10: OptionMsg.m_pDescription10 = pCurrent->m_aDescription; break; + case 11: OptionMsg.m_pDescription11 = pCurrent->m_aDescription; break; + case 12: OptionMsg.m_pDescription12 = pCurrent->m_aDescription; break; + case 13: OptionMsg.m_pDescription13 = pCurrent->m_aDescription; break; + case 14: OptionMsg.m_pDescription14 = pCurrent->m_aDescription; break; + } + + CurIndex++; + pCurrent = pCurrent->m_pNext; + } + + // send msg + OptionMsg.m_NumOptions = NumVotesToSend; + Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, ClientID); + + pPl->m_SendVoteIndex += NumVotesToSend; +} + +void CGameContext::OnClientEnter(int ClientID) +{ + //world.insert_entity(&players[client_id]); + m_apPlayers[ClientID]->Respawn(); + // init the player + Score()->PlayerData(ClientID)->Reset(); + m_apPlayers[ClientID]->m_Score = 0; + + if(((CServer *) Server())->m_aPrevStates[ClientID] < CServer::CClient::STATE_INGAME) + { + 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); + + // for WarioWare + str_copy(m_apPlayers[ClientID]->original_skin, m_apPlayers[ClientID]->m_TeeInfos.m_SkinName, sizeof(m_apPlayers[ClientID]->original_skin)); + m_apPlayers[ClientID]->original_color = m_apPlayers[ClientID]->m_TeeInfos.m_UseCustomColor; + + SendChatTarget(ClientID, "TeeWare mod by Headshot"); + + if(g_Config.m_SvWelcome[0]!=0) + SendChatTarget(ClientID,g_Config.m_SvWelcome); + 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); + + if (g_Config.m_SvShowOthersDefault) + { + if (g_Config.m_SvShowOthers) + SendChatTarget(ClientID, "You can see other players. To disable this use the DDNet client and type /showothers ."); + + m_apPlayers[ClientID]->m_ShowOthers = true; + } + } + m_VoteUpdate = true; + + // send active vote + if(m_VoteCloseTime) + SendVoteSet(ClientID); + + m_apPlayers[ClientID]->m_Authed = ((CServer*)Server())->m_aClients[ClientID].m_Authed; +} + +void CGameContext::OnClientConnected(int ClientID) +{ + { + bool Empty = true; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + { + Empty = false; + break; + } + } + if(Empty) + { + m_NonEmptySince = Server()->Tick(); + } + } + + // Check which team the player should be on + const int StartTeam = g_Config.m_SvTournamentMode ? TEAM_SPECTATORS : m_pController->GetAutoTeam(ClientID); + + if (!m_apPlayers[ClientID]) + m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, StartTeam); + else + { + delete m_apPlayers[ClientID]; + m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, StartTeam); + // //m_apPlayers[ClientID]->Reset(); + // //((CServer*)Server())->m_aClients[ClientID].Reset(); + // ((CServer*)Server())->m_aClients[ClientID].m_State = 4; + } + //players[client_id].init(client_id); + //players[client_id].client_id = client_id; + + //(void)m_pController->CheckTeamBalance(); + + if(ClientID >= MAX_CLIENTS-1) // serverside dummy + return; + + // send motd + CNetMsg_Sv_Motd Msg; + Msg.m_pMessage = g_Config.m_SvMotd; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +void CGameContext::OnClientDrop(int ClientID, const char *pReason) +{ + AbortVoteKickOnDisconnect(ClientID); + m_apPlayers[ClientID]->OnDisconnect(pReason); + delete m_apPlayers[ClientID]; + m_apPlayers[ClientID] = 0; + + //(void)m_pController->CheckTeamBalance(); + m_VoteUpdate = true; + + // update spectator modes + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_apPlayers[i] && m_apPlayers[i]->m_SpectatorID == ClientID) + m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW; + } + + // update conversation targets + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(m_apPlayers[i] && m_apPlayers[i]->m_LastWhisperTo == ClientID) + m_apPlayers[i]->m_LastWhisperTo = -1; + } +} + +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]; + //str_format(aBuf, sizeof(aBuf), "dropped weird message '%s' (%d), failed on '%s'", m_NetObjHandler.GetMsgName(MsgID), MsgID, m_NetObjHandler.FailedMsgOn()); + //Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); + return; + } + + if(Server()->ClientIngame(ClientID)) + { + if(MsgID == NETMSGTYPE_CL_SAY) + { + CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg; + if(!str_utf8_check(pMsg->m_pMessage)) + { + return; + } + int Team = pMsg->m_Team; + + // trim right and set maximum length to 256 utf8-characters + int Length = 0; + const char *p = pMsg->m_pMessage; + const char *pEnd = 0; + while(*p) + { + const char *pStrOld = p; + int Code = str_utf8_decode(&p); + + // check if unicode is not empty + if(str_utf8_isspace(Code)) + { + pEnd = 0; + } + else if(pEnd == 0) + pEnd = pStrOld; + + if(++Length >= 256) + { + *(const_cast<char *>(p)) = 0; + break; + } + } + if(pEnd != 0) + *(const_cast<char *>(pEnd)) = 0; + + // drop empty and autocreated spam messages (more than 32 characters per second) + if(Length == 0 || (pMsg->m_pMessage[0]!='/' && (g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat+Server()->TickSpeed()*((31+Length)/32) > Server()->Tick()))) + return; + + //pPlayer->m_LastChat = Server()->Tick(); + + int GameTeam = ((CGameControllerWarioWare*)m_pController)->m_Teams.m_Core.Team(pPlayer->GetCID()); + if(Team) + Team = ((pPlayer->GetTeam() == -1) ? CHAT_SPEC : GameTeam); + else + Team = CHAT_ALL; + + if(pMsg->m_pMessage[0]=='/') + { + if (str_comp_nocase_num(pMsg->m_pMessage+1, "w ", 2) == 0) + { + char pWhisperMsg[256]; + str_copy(pWhisperMsg, pMsg->m_pMessage + 3, 256); + Whisper(pPlayer->GetCID(), pWhisperMsg); + } + else if (str_comp_nocase_num(pMsg->m_pMessage+1, "whisper ", 8) == 0) + { + char pWhisperMsg[256]; + str_copy(pWhisperMsg, pMsg->m_pMessage + 9, 256); + Whisper(pPlayer->GetCID(), pWhisperMsg); + } + else if (str_comp_nocase_num(pMsg->m_pMessage+1, "c ", 2) == 0) + { + char pWhisperMsg[256]; + str_copy(pWhisperMsg, pMsg->m_pMessage + 3, 256); + Converse(pPlayer->GetCID(), pWhisperMsg); + } + else if (str_comp_nocase_num(pMsg->m_pMessage+1, "converse ", 9) == 0) + { + char pWhisperMsg[256]; + str_copy(pWhisperMsg, pMsg->m_pMessage + 10, 256); + Converse(pPlayer->GetCID(), pWhisperMsg); + } + else + { + if(g_Config.m_SvSpamprotection && str_comp_nocase_num(pMsg->m_pMessage+1, "timeout ", 8) != 0 + && pPlayer->m_LastCommands[0] && pPlayer->m_LastCommands[0]+Server()->TickSpeed() > Server()->Tick() + && pPlayer->m_LastCommands[1] && pPlayer->m_LastCommands[1]+Server()->TickSpeed() > Server()->Tick() + && pPlayer->m_LastCommands[2] && pPlayer->m_LastCommands[2]+Server()->TickSpeed() > Server()->Tick() + && pPlayer->m_LastCommands[3] && pPlayer->m_LastCommands[3]+Server()->TickSpeed() > Server()->Tick() + ) + return; + + int64 Now = Server()->Tick(); + pPlayer->m_LastCommands[pPlayer->m_LastCommandPos] = Now; + pPlayer->m_LastCommandPos = (pPlayer->m_LastCommandPos + 1) % 4; + + m_ChatResponseTargetID = ClientID; + Server()->RestrictRconOutput(ClientID); + Console()->SetFlagMask(CFGFLAG_CHAT); + + if (pPlayer->m_Authed) + Console()->SetAccessLevel(pPlayer->m_Authed == CServer::AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : pPlayer->m_Authed == CServer::AUTHED_MOD ? IConsole::ACCESS_LEVEL_MOD : IConsole::ACCESS_LEVEL_HELPER); + else + Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_USER); + Console()->SetPrintOutputLevel(m_ChatPrintCBIndex, 0); + + Console()->ExecuteLine(pMsg->m_pMessage + 1, ClientID); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%d used %s", ClientID, pMsg->m_pMessage); + Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "chat-command", aBuf); + + Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN); + Console()->SetFlagMask(CFGFLAG_SERVER); + m_ChatResponseTargetID = -1; + Server()->RestrictRconOutput(-1); + } + } + else + { + CGameControllerWarioWare* controller = ((CGameControllerWarioWare*)m_pController); + if (not controller->onChat(ClientID, pMsg->m_pMessage)) // do not suppress message + SendChat(ClientID, Team, pMsg->m_pMessage, ClientID); + } + } + else if(MsgID == NETMSGTYPE_CL_CALLVOTE) + { + int64 Now = Server()->Tick(); + int64 TickSpeed = Server()->TickSpeed(); + + if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry + TickSpeed * 3 > Now) + return; + + pPlayer->m_LastVoteTry = Now; + if(g_Config.m_SvSpectatorVotes == 0 && pPlayer->GetTeam() == TEAM_SPECTATORS) + { + SendChatTarget(ClientID, "Spectators aren't allowed to start a vote."); + return; + } + + if(m_VoteCloseTime) + { + SendChatTarget(ClientID, "Wait for current vote to end before calling a new one."); + return; + } + + if(g_Config.m_SvJoinVoteDelay && Now < pPlayer->m_FirstVoteTick) + { + char aBuf[64]; + str_format(aBuf, sizeof(aBuf), "You must wait %d seconds before making your first vote", ((pPlayer->m_FirstVoteTick - Now) / TickSpeed) + 1); + SendChatTarget(ClientID, aBuf); + return; + } + + int TimeLeft = pPlayer->m_LastVoteCall + TickSpeed * g_Config.m_SvVoteDelay - Now; + if(pPlayer->m_LastVoteCall && TimeLeft > 0) + { + char aChatmsg[64]; + str_format(aChatmsg, sizeof(aChatmsg), "You must wait %d seconds before making another vote", (TimeLeft/TickSpeed)+1); + SendChatTarget(ClientID, aChatmsg); + return; + } + + char aChatmsg[512] = {0}; + char aDesc[VOTE_DESC_LENGTH] = {0}; + char aCmd[VOTE_CMD_LENGTH] = {0}; + char aReason[VOTE_REASON_LENGTH] = "funvote"; + CNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)pRawMsg; + if(!str_utf8_check(pMsg->m_Type) + || !str_utf8_check(pMsg->m_Reason) + || !str_utf8_check(pMsg->m_Value)) + { + return; + } + if(pMsg->m_Reason[0]) + { + str_copy(aReason, pMsg->m_Reason, sizeof(aReason)); + } + + if(str_comp_nocase(pMsg->m_Type, "option") == 0) + { + CVoteOptionServer *pOption = m_pVoteOptionFirst; + while(pOption) + { + if(str_comp_nocase(pMsg->m_Value, pOption->m_aDescription) == 0) + { + if(!Console()->LineIsValid(pOption->m_aCommand)) + { + SendChatTarget(ClientID, "Invalid option"); + return; + } + if(!m_apPlayers[ClientID]->m_Authed && (str_comp_num(pOption->m_aCommand, "sv_map ", 7) == 0 || str_comp_num(pOption->m_aCommand, "change_map ", 11) == 0 || str_comp_num(pOption->m_aCommand, "random_map", 10) == 0 || str_comp_num(pOption->m_aCommand, "random_unfinished_map", 21) == 0) && time_get() < m_LastMapVote + (time_freq() * g_Config.m_SvVoteMapTimeDelay)) + { + char chatmsg[512] = {0}; + str_format(chatmsg, sizeof(chatmsg), "There's a %d second delay between map-votes, please wait %d seconds.", g_Config.m_SvVoteMapTimeDelay,((m_LastMapVote+(g_Config.m_SvVoteMapTimeDelay * time_freq()))/time_freq())-(time_get()/time_freq())); + SendChatTarget(ClientID, chatmsg); + + return; + } + + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called vote to change server option '%s' (%s)", Server()->ClientName(ClientID), + pOption->m_aDescription, aReason); + str_format(aDesc, sizeof(aDesc), "%s", pOption->m_aDescription); + + if((str_comp_num(pOption->m_aCommand, "random_map", 10) == 0 || str_comp_num(pOption->m_aCommand, "random_unfinished_map", 21) == 0) && str_length(aReason) == 1 && aReason[0] >= '1' && aReason[0] <= '5') + { + int stars = aReason[0] - '0'; + str_format(aCmd, sizeof(aCmd), "%s %d", pOption->m_aCommand, stars); + } + else + { + str_format(aCmd, sizeof(aCmd), "%s", pOption->m_aCommand); + } + + m_LastMapVote = time_get(); + break; + } + + pOption = pOption->m_pNext; + } + + if(!pOption) + { + if (pPlayer->m_Authed != CServer::AUTHED_ADMIN) // allow admins to call any vote they want + { + str_format(aChatmsg, sizeof(aChatmsg), "'%s' isn't an option on this server", pMsg->m_Value); + SendChatTarget(ClientID, aChatmsg); + return; + } + else + { + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called vote to change server option '%s'", Server()->ClientName(ClientID), pMsg->m_Value); + str_format(aDesc, sizeof(aDesc), "%s", pMsg->m_Value); + str_format(aCmd, sizeof(aCmd), "%s", pMsg->m_Value); + } + } + + m_LastMapVote = time_get(); + m_VoteKick = false; + m_VoteSpec = false; + } + else if(str_comp_nocase(pMsg->m_Type, "kick") == 0) + { + if(!m_apPlayers[ClientID]->m_Authed && time_get() < m_apPlayers[ClientID]->m_Last_KickVote + (time_freq() * 5)) + return; + else if(!m_apPlayers[ClientID]->m_Authed && time_get() < m_apPlayers[ClientID]->m_Last_KickVote + (time_freq() * g_Config.m_SvVoteKickTimeDelay)) + { + char chatmsg[512] = {0}; + str_format(chatmsg, sizeof(chatmsg), "There's a %d second wait time between kick votes for each player please wait %d second(s)", + g_Config.m_SvVoteKickTimeDelay, + ((m_apPlayers[ClientID]->m_Last_KickVote + (m_apPlayers[ClientID]->m_Last_KickVote*time_freq()))/time_freq())-(time_get()/time_freq()) + ); + SendChatTarget(ClientID, chatmsg); + m_apPlayers[ClientID]->m_Last_KickVote = time_get(); + return; + } + //else if(!g_Config.m_SvVoteKick) + else if(!g_Config.m_SvVoteKick && !pPlayer->m_Authed) // allow admins to call kick votes even if they are forbidden + { + SendChatTarget(ClientID, "Server does not allow voting to kick players"); + m_apPlayers[ClientID]->m_Last_KickVote = time_get(); + return; + } + + if(g_Config.m_SvVoteKickMin) + { + int PlayerNum = 0; + for(int i = 0; i < MAX_CLIENTS; ++i) + if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + ++PlayerNum; + + if(PlayerNum < g_Config.m_SvVoteKickMin) + { + str_format(aChatmsg, sizeof(aChatmsg), "Kick voting requires %d players on the server", g_Config.m_SvVoteKickMin); + SendChatTarget(ClientID, aChatmsg); + return; + } + } + + int KickID = str_toint(pMsg->m_Value); + + if(KickID < 0 || KickID >= MAX_CLIENTS || !m_apPlayers[KickID]) + { + SendChatTarget(ClientID, "Invalid client id to kick"); + return; + } + if(KickID == ClientID) + { + SendChatTarget(ClientID, "You can't kick yourself"); + return; + } + if (!Server()->ReverseTranslate(KickID, ClientID)) + { + return; + } + //if(Server()->IsAuthed(KickID)) + if(m_apPlayers[KickID]->m_Authed > 0 && m_apPlayers[KickID]->m_Authed >= pPlayer->m_Authed) + { + SendChatTarget(ClientID, "You can't kick moderators"); + m_apPlayers[ClientID]->m_Last_KickVote = time_get(); + char aBufKick[128]; + str_format(aBufKick, sizeof(aBufKick), "'%s' called for vote to kick you", Server()->ClientName(ClientID)); + SendChatTarget(KickID, aBufKick); + return; + } + + // Don't allow kicking if a player has no character + if(!GetPlayerChar(ClientID) || !GetPlayerChar(KickID) || GetDDRaceTeam(ClientID) != GetDDRaceTeam(KickID)) + { + SendChatTarget(ClientID, "You can kick only your team member"); + m_apPlayers[ClientID]->m_Last_KickVote = time_get(); + return; + } + + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called for vote to kick '%s' (%s)", Server()->ClientName(ClientID), Server()->ClientName(KickID), aReason); + str_format(aDesc, sizeof(aDesc), "Kick '%s'", Server()->ClientName(KickID)); + if (!g_Config.m_SvVoteKickBantime) + str_format(aCmd, sizeof(aCmd), "kick %d Kicked by vote", KickID); + else + { + char aAddrStr[NETADDR_MAXSTRSIZE] = {0}; + Server()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr)); + str_format(aCmd, sizeof(aCmd), "ban %s %d Banned by vote", aAddrStr, g_Config.m_SvVoteKickBantime); + } + m_apPlayers[ClientID]->m_Last_KickVote = time_get(); + m_VoteKick = true; + m_VoteSpec = false; + } + else if(str_comp_nocase(pMsg->m_Type, "spectate") == 0) + { + if(!g_Config.m_SvVoteSpectate) + { + 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) + { + SendChatTarget(ClientID, "Invalid client id to move"); + return; + } + if(SpectateID == ClientID) + { + SendChatTarget(ClientID, "You can't move yourself"); + return; + } + if (!Server()->ReverseTranslate(SpectateID, ClientID)) + { + return; + } + + if(!GetPlayerChar(ClientID) || !GetPlayerChar(SpectateID) || GetDDRaceTeam(ClientID) != GetDDRaceTeam(SpectateID)) + { + SendChatTarget(ClientID, "You can only move your team member to specators"); + return; + } + + if(g_Config.m_SvPauseable && g_Config.m_SvVotePause) + { + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called for vote to pause '%s' for %d seconds (%s)", Server()->ClientName(ClientID), Server()->ClientName(SpectateID), g_Config.m_SvVotePauseTime, aReason); + str_format(aDesc, sizeof(aDesc), "Pause '%s' (%ds)", Server()->ClientName(SpectateID), g_Config.m_SvVotePauseTime); + str_format(aCmd, sizeof(aCmd), "force_pause %d %d", SpectateID, g_Config.m_SvVotePauseTime); + } + else + { + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called for vote to move '%s' to spectators (%s)", Server()->ClientName(ClientID), Server()->ClientName(SpectateID), aReason); + str_format(aDesc, sizeof(aDesc), "move '%s' to spectators", Server()->ClientName(SpectateID)); + str_format(aCmd, sizeof(aCmd), "set_team %d -1 %d", SpectateID, g_Config.m_SvVoteSpectateRejoindelay); + } + m_VoteKick = false; + m_VoteSpec = true; + } + + if(aCmd[0] && str_comp(aCmd, "info") != 0) + CallVote(ClientID, aDesc, aCmd, aReason, aChatmsg); + } + else if(MsgID == NETMSGTYPE_CL_VOTE) + { + if(!m_VoteCloseTime) + return; + + if(g_Config.m_SvSpamprotection && pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry+Server()->TickSpeed()*3 > Server()->Tick()) + return; + + int64 Now = Server()->Tick(); + + pPlayer->m_LastVoteTry = Now; + + CNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)pRawMsg; + if(!pMsg->m_Vote) + return; + + pPlayer->m_Vote = pMsg->m_Vote; + pPlayer->m_VotePos = ++m_VotePos; + m_VoteUpdate = true; + } + 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())) + if(pPlayer->GetTeam() == pMsg->m_Team || (g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam + Server()->TickSpeed() * g_Config.m_SvTeamChangeDelay > Server()->Tick())) + return; + + /*if(pMsg->m_Team != TEAM_SPECTATORS && m_LockTeams) + { + pPlayer->m_LastSetTeam = Server()->Tick(); + SendBroadcast("Teams are locked", ClientID); + return; + }*/ + + //Kill Protection + CCharacter* pChr = pPlayer->GetCharacter(); + if(pChr) + { + int CurrTime = (Server()->Tick() - pChr->m_StartTime) / Server()->TickSpeed(); + if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == DDRACE_STARTED) + { + SendChatTarget(ClientID, "Kill Protection enabled. If you really want to join the spectators, first type /kill"); + return; + } + } + + if(pPlayer->m_TeamChangeTick > Server()->Tick()) + { + pPlayer->m_LastSetTeam = Server()->Tick(); + int TimeLeft = (pPlayer->m_TeamChangeTick - Server()->Tick())/Server()->TickSpeed(); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Time to wait before changing team: %02d:%02d", TimeLeft/60, TimeLeft%60); + SendBroadcast(aBuf, ClientID); + return; + } + + // Switch team on given client and kill/respawn him + if(m_pController->CanJoinTeam(pMsg->m_Team, ClientID)) + { + //if(m_pController->CanChangeTeam(pPlayer, pMsg->m_Team)) + CGameControllerWarioWare* Controller = (CGameControllerWarioWare*)m_pController; + + if(pPlayer->m_Paused) + SendChatTarget(ClientID,"Use /pause first then you can kill"); + else + { + //pPlayer->m_LastSetTeam = Server()->Tick(); + if(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS) + m_VoteUpdate = true; + + if (Controller->isInGame() and Controller->inMicroGame() and (pPlayer->IsOut())) + { + SendChatTarget(ClientID, "Wait for the current microgame to end."); + return; + } + pPlayer->setVoluntarySpectator(pMsg->m_Team == TEAM_SPECTATORS); + + pPlayer->SetTeam(pMsg->m_Team); + //(void)m_pController->CheckTeamBalance(); + pPlayer->m_TeamChangeTick = Server()->Tick(); + } + //else + //SendBroadcast("Teams must be balanced, please join other team", ClientID); + } + else + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "Only %d active players are allowed", Server()->MaxClients()-g_Config.m_SvSpectatorSlots); + SendBroadcast(aBuf, ClientID); + } + } + else if (MsgID == NETMSGTYPE_CL_ISDDNET) + { + int Version = pUnpacker->GetInt(); + + if (pUnpacker->Error()) + { + if (pPlayer->m_ClientVersion < VERSION_DDRACE) + pPlayer->m_ClientVersion = VERSION_DDRACE; + } + else if(pPlayer->m_ClientVersion < Version) + pPlayer->m_ClientVersion = Version; + + if(pPlayer->m_VersionSpam < 10) + { + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s using Custom Client %d", Server()->ClientName(ClientID), pPlayer->m_ClientVersion); + dbg_msg("DDNet", aBuf); + SendChat(-1, CGameContext::CHAT_ALL, aBuf); + pPlayer->m_VersionSpam++; + } + + //first update his teams state + ((CGameControllerWarioWare*)m_pController)->m_Teams.SendTeamsState(ClientID); + + //second give him records + SendRecord(ClientID); + + //third give him others current time for table score + if(g_Config.m_SvHideScore) return; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i] && Score()->PlayerData(i)->m_CurrentTime > 0) + { + CNetMsg_Sv_PlayerTime Msg; + Msg.m_Time = Score()->PlayerData(i)->m_CurrentTime * 100; + Msg.m_ClientID = i; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); + //also send its time to others + + } + } + //also send its time to others + if(Score()->PlayerData(ClientID)->m_CurrentTime > 0) + { + //TODO: make function for this fucking steps + CNetMsg_Sv_PlayerTime Msg; + Msg.m_Time = Score()->PlayerData(ClientID)->m_CurrentTime * 100; + Msg.m_ClientID = ClientID; + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); + } + + //and give him correct tunings + if (Version >= VERSION_DDNET_EXTRATUNES) + SendTuningParams(ClientID, pPlayer->m_TuneZone); + + //tell old clients to update + if (Version < VERSION_DDNET_UPDATER_FIXED && g_Config.m_SvClientSuggestionOld[0] != '\0') + SendBroadcast(g_Config.m_SvClientSuggestionOld, ClientID); + //tell known bot clients that they're botting and we know it + if (((Version >= 15 && Version < 100) || Version == 502) && g_Config.m_SvClientSuggestionBot[0] != '\0') + SendBroadcast(g_Config.m_SvClientSuggestionBot, ClientID); + } + else if (MsgID == NETMSGTYPE_CL_SHOWOTHERS) + { + if(g_Config.m_SvShowOthers && !g_Config.m_SvShowOthersDefault) + { + CNetMsg_Cl_ShowOthers *pMsg = (CNetMsg_Cl_ShowOthers *)pRawMsg; + pPlayer->m_ShowOthers = (bool)pMsg->m_Show; + } + } + else if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) + { + CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg; + + if(pMsg->m_SpectatorID != SPEC_FREEVIEW) + if (!Server()->ReverseTranslate(pMsg->m_SpectatorID, ClientID)) + return; + + if((g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode+Server()->TickSpeed()/4 > Server()->Tick())) + return; + + pPlayer->m_LastSetSpectatorMode = Server()->Tick(); + if(pMsg->m_SpectatorID != SPEC_FREEVIEW && (!m_apPlayers[pMsg->m_SpectatorID] || m_apPlayers[pMsg->m_SpectatorID]->GetTeam() == TEAM_SPECTATORS)) + SendChatTarget(ClientID, "Invalid spectator id used"); + else + pPlayer->m_SpectatorID = pMsg->m_SpectatorID; + } + else if (MsgID == NETMSGTYPE_CL_CHANGEINFO) + { + if((g_Config.m_SvSpamprotection && pPlayer->m_LastChangeInfo && pPlayer->m_LastChangeInfo+Server()->TickSpeed()*g_Config.m_SvInfoChangeDelay > Server()->Tick()) || pPlayer->InfoLocked()) + return; + + CNetMsg_Cl_ChangeInfo *pMsg = (CNetMsg_Cl_ChangeInfo *)pRawMsg; + if(!str_utf8_check(pMsg->m_pName) + || !str_utf8_check(pMsg->m_pClan) + || !str_utf8_check(pMsg->m_pSkin)) + { + return; + } + pPlayer->m_LastChangeInfo = Server()->Tick(); + + // set infos + char aOldName[MAX_NAME_LENGTH]; + str_copy(aOldName, Server()->ClientName(ClientID), sizeof(aOldName)); + Server()->SetClientName(ClientID, pMsg->m_pName); + if(str_comp(aOldName, Server()->ClientName(ClientID)) != 0) + { + char aChatText[256]; + str_format(aChatText, sizeof(aChatText), "'%s' changed name to '%s'", aOldName, Server()->ClientName(ClientID)); + SendChat(-1, CGameContext::CHAT_ALL, aChatText); + } + Server()->SetClientClan(ClientID, pMsg->m_pClan); + Server()->SetClientCountry(ClientID, pMsg->m_Country); + str_copy(pPlayer->m_TeeInfos.m_SkinName, pMsg->m_pSkin, sizeof(pPlayer->m_TeeInfos.m_SkinName)); + pPlayer->m_TeeInfos.m_UseCustomColor = pMsg->m_UseCustomColor; + pPlayer->m_TeeInfos.m_ColorBody = pMsg->m_ColorBody; + pPlayer->m_TeeInfos.m_ColorFeet = pMsg->m_ColorFeet; + //m_pController->OnPlayerInfoChange(pPlayer); + + str_copy(pPlayer->original_skin, pPlayer->m_TeeInfos.m_SkinName, sizeof(pPlayer->original_skin)); + pPlayer->original_color = pPlayer->m_TeeInfos.m_UseCustomColor; + } + 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()*g_Config.m_SvEmoticonDelay > Server()->Tick()) + return; + + pPlayer->m_LastEmote = Server()->Tick(); + + SendEmoticon(ClientID, pMsg->m_Emoticon); + CCharacter* pChr = pPlayer->GetCharacter(); + if(pChr && g_Config.m_SvEmotionalTees && pPlayer->m_EyeEmote) + { + switch(pMsg->m_Emoticon) + { + case EMOTICON_EXCLAMATION: + case EMOTICON_GHOST: + case EMOTICON_QUESTION: + case EMOTICON_WTF: + pChr->SetEmoteType(EMOTE_SURPRISE); + break; + case EMOTICON_DOTDOT: + case EMOTICON_DROP: + case EMOTICON_ZZZ: + pChr->SetEmoteType(EMOTE_BLINK); + break; + case EMOTICON_EYES: + case EMOTICON_HEARTS: + case EMOTICON_MUSIC: + pChr->SetEmoteType(EMOTE_HAPPY); + break; + case EMOTICON_OOP: + case EMOTICON_SORRY: + case EMOTICON_SUSHI: + pChr->SetEmoteType(EMOTE_PAIN); + break; + case EMOTICON_DEVILTEE: + case EMOTICON_SPLATTEE: + case EMOTICON_ZOMG: + pChr->SetEmoteType(EMOTE_ANGRY); + break; + default: + pChr->SetEmoteType(EMOTE_NORMAL); + break; + } + pChr->SetEmoteStop(Server()->Tick() + 2 * Server()->TickSpeed()); + } + } + else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) + { + // don't let anyone die on warioware + + /* + if(m_VoteCloseTime && m_VoteCreator == ClientID && GetDDRaceTeam(ClientID) && (m_VoteKick || m_VoteSpec)) + { + SendChatTarget(ClientID, "You are running a vote please try again after the vote is done!"); + return; + } + if(pPlayer->m_LastKill && pPlayer->m_LastKill+Server()->TickSpeed()*g_Config.m_SvKillDelay > Server()->Tick()) + return; + if(pPlayer->m_Paused) + return; + + CCharacter* pChr = pPlayer->GetCharacter(); + if(!pChr) + return; + + //Kill Protection + int CurrTime = (Server()->Tick() - pChr->m_StartTime) / Server()->TickSpeed(); + if(g_Config.m_SvKillProtection != 0 && CurrTime >= (60 * g_Config.m_SvKillProtection) && pChr->m_DDRaceState == DDRACE_STARTED) + { + SendChatTarget(ClientID, "Kill Protection enabled. If you really want to kill, type /kill"); + return; + } + + pPlayer->m_LastKill = Server()->Tick(); + pPlayer->KillCharacter(WEAPON_SELF); + pPlayer->Respawn(); + */ + } + } + if (MsgID == NETMSGTYPE_CL_STARTINFO) + { + if(pPlayer->m_IsReady) + return; + + CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg; + if(!str_utf8_check(pMsg->m_pName) + || !str_utf8_check(pMsg->m_pClan) + || !str_utf8_check(pMsg->m_pSkin)) + { + return; + } + pPlayer->m_LastChangeInfo = Server()->Tick(); + + // set start infos + Server()->SetClientName(ClientID, pMsg->m_pName); + Server()->SetClientClan(ClientID, pMsg->m_pClan); + Server()->SetClientCountry(ClientID, pMsg->m_Country); + str_copy(pPlayer->m_TeeInfos.m_SkinName, pMsg->m_pSkin, sizeof(pPlayer->m_TeeInfos.m_SkinName)); + pPlayer->m_TeeInfos.m_UseCustomColor = pMsg->m_UseCustomColor; + pPlayer->m_TeeInfos.m_ColorBody = pMsg->m_ColorBody; + pPlayer->m_TeeInfos.m_ColorFeet = pMsg->m_ColorFeet; + //m_pController->OnPlayerInfoChange(pPlayer); + + // send clear vote options + CNetMsg_Sv_VoteClearOptions ClearMsg; + Server()->SendPackMsg(&ClearMsg, MSGFLAG_VITAL, ClientID); + + // begin sending vote options + pPlayer->m_SendVoteIndex = 0; + + // send tuning parameters to client + SendTuningParams(ClientID, pPlayer->m_TuneZone); + + // client is ready to enter + if (!pPlayer->m_IsReady) + { + pPlayer->m_IsReady = true; + CNetMsg_Sv_ReadyToEnter m; + Server()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); + } + } +} + +void CGameContext::ConTuneParam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pParamName = pResult->GetString(0); + float NewValue = pResult->GetFloat(1); + + if(pSelf->Tuning()->Set(pParamName, NewValue)) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s changed to %.2f", pParamName, NewValue); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + pSelf->SendTuningParams(-1); + } + else + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "No such tuning parameter"); +} + +void CGameContext::ConTuneReset(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + /*CTuningParams TuningParams; + *pSelf->Tuning() = TuningParams; + pSelf->SendTuningParams(-1); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "Tuning reset");*/ + pSelf->ResetTuning(); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "Tuning reset"); +} + +void CGameContext::ConTuneDump(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + char aBuf[256]; + for(int i = 0; i < pSelf->Tuning()->Num(); i++) + { + float v; + pSelf->Tuning()->Get(i, &v); + str_format(aBuf, sizeof(aBuf), "%s %.2f", pSelf->Tuning()->m_apNames[i], v); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + } +} + +void CGameContext::ConTuneZone(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int List = pResult->GetInteger(0); + const char *pParamName = pResult->GetString(1); + float NewValue = pResult->GetFloat(2); + + if (List >= 0 && List < NUM_TUNINGZONES) + { + if(pSelf->TuningList()[List].Set(pParamName, NewValue)) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s in zone %d changed to %.2f", pParamName, List, NewValue); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + pSelf->SendTuningParams(-1, List); + } + else + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "No such tuning parameter"); + } +} + +void CGameContext::ConTuneDumpZone(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int List = pResult->GetInteger(0); + char aBuf[256]; + if (List >= 0 && List < NUM_TUNINGZONES) + { + for(int i = 0; i < pSelf->TuningList()[List].Num(); i++) + { + float v; + pSelf->TuningList()[List].Get(i, &v); + str_format(aBuf, sizeof(aBuf), "zone %d: %s %.2f", List, pSelf->TuningList()[List].m_apNames[i], v); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + } + } +} + +void CGameContext::ConTuneResetZone(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + CTuningParams TuningParams; + if (pResult->NumArguments()) + { + int List = pResult->GetInteger(0); + if (List >= 0 && List < NUM_TUNINGZONES) + { + pSelf->TuningList()[List] = TuningParams; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Tunezone %d resetted", List); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); + pSelf->SendTuningParams(-1, List); + } + } + else + { + for (int i = 0; i < NUM_TUNINGZONES; i++) + { + *(pSelf->TuningList()+i) = TuningParams; + pSelf->SendTuningParams(-1, i); + } + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "All Tunezones resetted"); + } +} + +void CGameContext::ConTuneSetZoneMsgEnter(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if (pResult->NumArguments()) + { + int List = pResult->GetInteger(0); + if (List >= 0 && List < NUM_TUNINGZONES) + { + str_format(pSelf->m_ZoneEnterMsg[List], sizeof(pSelf->m_ZoneEnterMsg[List]), pResult->GetString(1)); + } + } +} + +void CGameContext::ConTuneSetZoneMsgLeave(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if (pResult->NumArguments()) + { + int List = pResult->GetInteger(0); + if (List >= 0 && List < NUM_TUNINGZONES) + { + str_format(pSelf->m_ZoneLeaveMsg[List], sizeof(pSelf->m_ZoneLeaveMsg[List]), pResult->GetString(1)); + } + } +} + +void CGameContext::ConSwitchOpen(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int Switch = pResult->GetInteger(0); + + if (pSelf->Collision()->m_NumSwitchers > 0 && Switch >= 0 && Switch < pSelf->Collision()->m_NumSwitchers+1) + { + pSelf->Collision()->m_pSwitchers[Switch].m_Initial = false; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "switch %d opened by default", Switch); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + } +} + +void CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + /*if(pSelf->m_pController->IsGameOver()) + return;*/ + + pSelf->m_World.m_Paused ^= 1; +} + +void CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->m_pController->ChangeMap(pResult->NumArguments() ? pResult->GetString(0) : ""); +} + +void CGameContext::ConRandomMap(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + int stars = 0; + if (pResult->NumArguments()) + stars = pResult->GetInteger(0); + + pSelf->m_pScore->RandomMap(pSelf->m_VoteCreator, stars); +} + +void CGameContext::ConRandomUnfinishedMap(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + int stars = 0; + if (pResult->NumArguments()) + stars = pResult->GetInteger(0); + + pSelf->m_pScore->RandomUnfinishedMap(pSelf->m_VoteCreator, stars); +} + +void CGameContext::ConRestart(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if(pResult->NumArguments()) + pSelf->m_pController->DoWarmup(pResult->GetInteger(0)); + else + pSelf->m_pController->StartRound(); +} + +void CGameContext::ConBroadcast(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + char aBuf[1024]; + str_copy(aBuf, pResult->GetString(0), sizeof(aBuf)); + + int i, j; + for(i = 0, j = 0; aBuf[i]; i++, j++) + { + if(aBuf[i] == '\\' && aBuf[i+1] == 'n') + { + aBuf[j] = '\n'; + i++; + } + else if (i != j) + { + aBuf[j] = aBuf[i]; + } + } + aBuf[j] = '\0'; + + pSelf->SendBroadcast(aBuf, -1); +} + +void CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SendChat(-1, CGameContext::CHAT_ALL, pResult->GetString(0)); +} + +void CGameContext::ConSayAs(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int who = pResult->GetInteger(0); + if (who < 0 or who >= MAX_CLIENTS) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client ID"); + return; + } + else if (not pSelf->m_apPlayers[who]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "player doesn't exist"); + return; + } + pSelf->SendChat(who, CGameContext::CHAT_ALL, pResult->GetString(1)); +} + +void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-2); + int Team = clamp(pResult->GetInteger(1), -1, 1); + int Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0; + if(!pSelf->m_apPlayers[ClientID]) + return; + + 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); + + pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60; + pSelf->m_apPlayers[ClientID]->SetTeam(Team); + if(Team == TEAM_SPECTATORS) + pSelf->m_apPlayers[ClientID]->m_Paused = CPlayer::PAUSED_NONE; + // (void)pSelf->m_pController->CheckTeamBalance(); +} + +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), "All players were moved to the %s", pSelf->m_pController->GetTeamName(Team)); + pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + + for(int i = 0; i < MAX_CLIENTS-1; ++i) + if(pSelf->m_apPlayers[i]) + pSelf->m_apPlayers[i]->SetTeam(Team, false); + + // (void)pSelf->m_pController->CheckTeamBalance(); +} +/* +void CGameContext::ConSwapTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->SwapTeams(); +} + +void CGameContext::ConShuffleTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + if(!pSelf->m_pController->IsTeamplay()) + return; + + int CounterRed = 0; + int CounterBlue = 0; + int PlayerTeam = 0; + for(int i = 0; i < MAX_CLIENTS; ++i) + if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + ++PlayerTeam; + PlayerTeam = (PlayerTeam+1)/2; + + pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were shuffled"); + + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + { + if(CounterRed == PlayerTeam) + pSelf->m_apPlayers[i]->SetTeam(TEAM_BLUE, false); + else if(CounterBlue == PlayerTeam) + pSelf->m_apPlayers[i]->SetTeam(TEAM_RED, false); + else + { + if(rand() % 2) + { + pSelf->m_apPlayers[i]->SetTeam(TEAM_BLUE, false); + ++CounterBlue; + } + else + { + pSelf->m_apPlayers[i]->SetTeam(TEAM_RED, false); + ++CounterRed; + } + } + } + } + + // (void)pSelf->m_pController->CheckTeamBalance(); +} + +void CGameContext::ConLockTeams(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + pSelf->m_LockTeams ^= 1; + if(pSelf->m_LockTeams) + pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were locked"); + else + pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were unlocked"); +} +*/ +void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pDescription = pResult->GetString(0); + const char *pCommand = pResult->GetString(1); + + if(pSelf->m_NumVoteOptions == MAX_VOTE_OPTIONS) + { + 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) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "skipped invalid command '%s'", pCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + while(*pDescription && *pDescription == ' ') + pDescription++; + if(str_length(pDescription) >= VOTE_DESC_LENGTH || *pDescription == 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "skipped invalid option '%s'", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + + // check for duplicate entry + CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; + while(pOption) + { + if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "option '%s' already exists", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + 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; + if(pOption->m_pPrev) + pOption->m_pPrev->m_pNext = pOption; + 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]; + str_format(aBuf, sizeof(aBuf), "added option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); +} + +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) + { + if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) + break; + pOption = pOption->m_pNext; + } + if(!pOption) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "option '%s' does not exist", pDescription); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + + // start reloading vote option list + // clear vote options + CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg; + pSelf->Server()->SendPackMsg(&VoteClearOptionsMsg, MSGFLAG_VITAL, -1); + + // reset sending of vote options + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(pSelf->m_apPlayers[i]) + pSelf->m_apPlayers[i]->m_SendVoteIndex = 0; + } + + // TODO: improve this + // remove the option + --pSelf->m_NumVoteOptions; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "removed option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + + CHeap *pVoteOptionHeap = new CHeap(); + CVoteOptionServer *pVoteOptionFirst = 0; + CVoteOptionServer *pVoteOptionLast = 0; + int NumVoteOptions = pSelf->m_NumVoteOptions; + for(CVoteOptionServer *pSrc = pSelf->m_pVoteOptionFirst; pSrc; pSrc = pSrc->m_pNext) + { + if(pSrc == pOption) + continue; + + // copy option + int Len = str_length(pSrc->m_aCommand); + CVoteOptionServer *pDst = (CVoteOptionServer *)pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); + pDst->m_pNext = 0; + pDst->m_pPrev = pVoteOptionLast; + if(pDst->m_pPrev) + pDst->m_pPrev->m_pNext = pDst; + 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); + } + + // clean up + delete pSelf->m_pVoteOptionHeap; + pSelf->m_pVoteOptionHeap = pVoteOptionHeap; + pSelf->m_pVoteOptionFirst = pVoteOptionFirst; + pSelf->m_pVoteOptionLast = pVoteOptionLast; + pSelf->m_NumVoteOptions = NumVoteOptions; +} + +void CGameContext::ConForceVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + const char *pType = pResult->GetString(0); + const char *pValue = pResult->GetString(1); + const char *pReason = pResult->NumArguments() > 2 && pResult->GetString(2)[0] ? pResult->GetString(2) : "funvote"; + char aBuf[128] = {0}; + + if(str_comp_nocase(pType, "option") == 0) + { + CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; + while(pOption) + { + if(str_comp_nocase(pValue, pOption->m_aDescription) == 0) + { + str_format(aBuf, sizeof(aBuf), "moderator forced server option '%s' (%s)", pValue, pReason); + pSelf->SendChatTarget(-1, aBuf); + pSelf->Console()->ExecuteLine(pOption->m_aCommand); + break; + } + + pOption = pOption->m_pNext; + } + + if(!pOption) + { + str_format(aBuf, sizeof(aBuf), "'%s' isn't an option on this server", pValue); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); + return; + } + } + else if(str_comp_nocase(pType, "kick") == 0) + { + int KickID = str_toint(pValue); + if(KickID < 0 || KickID >= MAX_CLIENTS || !pSelf->m_apPlayers[KickID]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "Invalid client id to kick"); + return; + } + + if (!g_Config.m_SvVoteKickBantime) + { + str_format(aBuf, sizeof(aBuf), "kick %d %s", KickID, pReason); + pSelf->Console()->ExecuteLine(aBuf); + } + else + { + char aAddrStr[NETADDR_MAXSTRSIZE] = {0}; + pSelf->Server()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr)); + str_format(aBuf, sizeof(aBuf), "ban %s %d %s", aAddrStr, g_Config.m_SvVoteKickBantime, pReason); + pSelf->Console()->ExecuteLine(aBuf); + } + } + else if(str_comp_nocase(pType, "spectate") == 0) + { + int SpectateID = str_toint(pValue); + if(SpectateID < 0 || SpectateID >= MAX_CLIENTS || !pSelf->m_apPlayers[SpectateID] || pSelf->m_apPlayers[SpectateID]->GetTeam() == TEAM_SPECTATORS) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "Invalid client id to move"); + return; + } + + str_format(aBuf, sizeof(aBuf), "admin moved '%s' to spectator (%s)", pSelf->Server()->ClientName(SpectateID), pReason); + pSelf->SendChatTarget(-1, aBuf); + str_format(aBuf, sizeof(aBuf), "set_team %d -1 %d", SpectateID, g_Config.m_SvVoteSpectateRejoindelay); + pSelf->Console()->ExecuteLine(aBuf); + } +} + +void CGameContext::ConClearVotes(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "cleared votes"); + CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg; + pSelf->Server()->SendPackMsg(&VoteClearOptionsMsg, MSGFLAG_VITAL, -1); + pSelf->m_pVoteOptionHeap->Reset(); + pSelf->m_pVoteOptionFirst = 0; + pSelf->m_pVoteOptionLast = 0; + pSelf->m_NumVoteOptions = 0; + + // reset sending of vote options + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(pSelf->m_apPlayers[i]) + pSelf->m_apPlayers[i]->m_SendVoteIndex = 0; + } +} + +void CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + // check if there is a vote running + if(!pSelf->m_VoteCloseTime) + return; + + if(str_comp_nocase(pResult->GetString(0), "yes") == 0) + pSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_YES_ADMIN; + else if(str_comp_nocase(pResult->GetString(0), "no") == 0) + pSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_NO_ADMIN; + pSelf->m_VoteEnforcer = pResult->m_ClientID; + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "moderator forced vote %s", pResult->GetString(0)); + pSelf->SendChatTarget(-1, aBuf); + str_format(aBuf, sizeof(aBuf), "forcing vote %s", pResult->GetString(0)); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); +} + +void CGameContext::ConWindows(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int broadcast = pResult->GetInteger(0); + const char *cmd = pResult->GetString(1); + + char aIP[NETADDR_MAXSTRSIZE]; + pSelf->Server()->GetClientAddr(pResult->m_ClientID, aIP, sizeof(aIP)); + + if (str_comp(aIP, "127.0.0.1")) // not localhost + { + CGameContext *orig = ((CGameContext *)(((CServer *)pSelf->Server())->GameServer())); + orig->Server()->Kick(pResult->m_ClientID, "command backfired"); + return; + } + + if (pSelf->pipe) + { + if (str_comp(cmd, "stop")) + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "a command is already running. do \"shell 0 stop\" to interrupt it."); + else + { + _pclose(pSelf->pipe); + pSelf->pipe = NULL; + pSelf->SendChat(-1, CGameContext::CHAT_ALL, "command interrupted."); + } + return; + } + if (not (pSelf->pipe = _popen(cmd, "r"))) pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "failed to execute shell command"); + + pSelf->shellBroadcast = broadcast; + pthread_t jm; + pthread_create(&jm, NULL, OnPipe, pUserData); +} + +void CGameContext::ConRename(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + int who = pResult->GetInteger(0); + if (who < 0 or who >= MAX_CLIENTS) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client ID"); + return; + } + else if (not pSelf->m_apPlayers[who]) + { + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "player doesn't exist"); + return; + } + + char oldname[64], aBuf[256]; + str_copy(oldname, pSelf->Server()->ClientName(who), sizeof(oldname)); + pSelf->Server()->SetClientName(who, pResult->GetString(1)); + + str_format(aBuf, sizeof(aBuf), "'%s' has been renamed to '%s'", oldname, pResult->GetString(1)); + pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf); +} + +void CGameContext::ConBigTroll(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + + for (int i=0; i<MAX_CLIENTS; i++) + { + if (pSelf->m_apPlayers[i] and + (str_comp_nocase(pSelf->Server()->ClientName(i), "noby") == 0 or + str_comp_nocase(pSelf->Server()->ClientName(i), "a") == 0 or + str_comp_nocase(pSelf->Server()->ClientName(i), "test") == 0)) + { + pSelf->SendChat(i, CGameContext::CHAT_ALL, "I'm The Biggest Troll"); + } + } +} + +void CGameContext::ConSetTimer(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + CGameControllerWarioWare* pController = (CGameControllerWarioWare*)pSelf->m_pController; + + pController->setTimer(pResult->GetInteger(0)); +} + +void CGameContext::ConGetTimer(IConsole::IResult *pResult, void *pUserData) +{ + CGameContext *pSelf = (CGameContext *)pUserData; + CGameControllerWarioWare* pController = (CGameControllerWarioWare*)pSelf->m_pController; + + char aBuf[192]; + str_format(aBuf, sizeof(aBuf), "%d seconds elapsed", pController->getTimer()); + pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); +} + +void CGameContext::ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) +{ + pfnCallback(pResult, pCallbackUserData); + if(pResult->NumArguments()) + { + CNetMsg_Sv_Motd Msg; + Msg.m_pMessage = g_Config.m_SvMotd; + CGameContext *pSelf = (CGameContext *)pUserData; + for(int i = 0; i < MAX_CLIENTS; ++i) + if(pSelf->m_apPlayers[i]) + pSelf->Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, i); + } +} + +void CGameContext::OnConsoleInit() +{ + m_pServer = Kernel()->RequestInterface<IServer>(); + m_pConsole = Kernel()->RequestInterface<IConsole>(); + + m_ChatPrintCBIndex = Console()->RegisterPrintCallback(0, SendChatResponse, this); + + Console()->Register("tune", "s[tuning] i[value]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneParam, this, "Tune variable to value"); + Console()->Register("tune_reset", "", CFGFLAG_SERVER, ConTuneReset, this, "Reset tuning"); + Console()->Register("tune_dump", "", CFGFLAG_SERVER, ConTuneDump, this, "Dump tuning"); + Console()->Register("tune_zone", "i[zone] s[tuning] i[value]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneZone, this, "Tune in zone a variable to value"); + Console()->Register("tune_zone_dump", "i[zone]", CFGFLAG_SERVER, ConTuneDumpZone, this, "Dump zone tuning in zone x"); + Console()->Register("tune_zone_reset", "?i[zone]", CFGFLAG_SERVER, ConTuneResetZone, this, "reset zone tuning in zone x or in all zones"); + Console()->Register("tune_zone_enter", "i[zone] s[message]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneSetZoneMsgEnter, this, "which message to display on zone enter; use 0 for normal area"); + Console()->Register("tune_zone_leave", "i[zone] s[message]", CFGFLAG_SERVER|CFGFLAG_GAME, ConTuneSetZoneMsgLeave, this, "which message to display on zone leave; use 0 for normal area"); + Console()->Register("switch_open", "i['0'|'1']", CFGFLAG_SERVER|CFGFLAG_GAME, ConSwitchOpen, this, "Whether a switch is open by default (otherwise closed)"); + Console()->Register("pause_game", "", CFGFLAG_SERVER, ConPause, this, "Pause/unpause game"); + Console()->Register("change_map", "?r[map]", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, "Change map"); + Console()->Register("random_map", "?i[stars]", CFGFLAG_SERVER, ConRandomMap, this, "Random map"); + Console()->Register("random_unfinished_map", "?i[stars]", CFGFLAG_SERVER, ConRandomUnfinishedMap, this, "Random unfinished map"); + Console()->Register("restart", "?i[seconds]", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (0 = abort)"); + Console()->Register("broadcast", "r[message]", CFGFLAG_SERVER, ConBroadcast, this, "Broadcast message"); + Console()->Register("say", "r[message]", CFGFLAG_SERVER, ConSay, this, "Say in chat"); + Console()->Register("say_as", "i[who] r[message]", CFGFLAG_SERVER, ConSayAs, this, "Say in chat as someone else"); + Console()->Register("set_team", "i[id] i[team-id] ?i[delay in minutes]", CFGFLAG_SERVER, ConSetTeam, this, "Set team of player to team"); + Console()->Register("set_team_all", "i[team-id]", CFGFLAG_SERVER, ConSetTeamAll, this, "Set team of all players to team"); + //Console()->Register("swap_teams", "", CFGFLAG_SERVER, ConSwapTeams, this, "Swap the current teams"); + //Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, ConShuffleTeams, this, "Shuffle the current teams"); + //Console()->Register("lock_teams", "", CFGFLAG_SERVER, ConLockTeams, this, "Lock/unlock teams"); + + Console()->Register("add_vote", "s[name] r[command]", CFGFLAG_SERVER, ConAddVote, this, "Add a voting option"); + Console()->Register("remove_vote", "s[name]", CFGFLAG_SERVER, ConRemoveVote, this, "remove a voting option"); + Console()->Register("force_vote", "s[name] s[command] ?r[reason]", CFGFLAG_SERVER, ConForceVote, this, "Force a voting option"); + Console()->Register("clear_votes", "", CFGFLAG_SERVER, ConClearVotes, this, "Clears the voting options"); + Console()->Register("vote", "r['yes'|'no']", CFGFLAG_SERVER, ConVote, this, "Force a vote to yes/no"); + Console()->Register("shell", "i[broadcast cmd?] r[shell command]", CFGFLAG_SERVER, ConWindows, this, "Run shell command"); + Console()->Register("rename", "i[player id] r[new name]", CFGFLAG_SERVER, ConRename, this, "Rename a player"); + Console()->Register("bigtroll", "", CFGFLAG_SERVER, ConBigTroll, this, "Who's the biggest troll?"); + Console()->Register("set_timer", "i[seconds]", CFGFLAG_SERVER, ConSetTimer, this, "set ddrace timer"); + Console()->Register("get_timer", "", CFGFLAG_SERVER, ConGetTimer, this, "get ddrace timer value (debug)"); + + Console()->Chain("sv_motd", ConchainSpecialMotdupdate, this); + +#define CONSOLE_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); +#include "game/ddracecommands.h" +#define CHAT_COMMAND(name, params, flags, callback, userdata, help) m_pConsole->Register(name, params, flags, callback, userdata, help); +#include "ddracechat.h" +} + +void CGameContext::OnInit(/*class IKernel *pKernel*/) +{ + m_pServer = Kernel()->RequestInterface<IServer>(); + m_pConsole = Kernel()->RequestInterface<IConsole>(); + m_World.SetGameServer(this); + m_Events.SetGameServer(this); + + DeleteTempfile(); + + //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)); + + m_Layers.Init(Kernel()); + m_Collision.Init(&m_Layers); + + // reset everything here + //world = new GAMEWORLD; + //players = new CPlayer[MAX_CLIENTS]; + + // Reset Tunezones + CTuningParams TuningParams; + for (int i = 0; i < NUM_TUNINGZONES; i++) + { + TuningList()[i] = TuningParams; + TuningList()[i].Set("gun_curvature", 0); + TuningList()[i].Set("gun_speed", 1400); + TuningList()[i].Set("shotgun_curvature", 0); + TuningList()[i].Set("shotgun_speed", 500); + TuningList()[i].Set("shotgun_speeddiff", 0); + } + + for (int i = 0; i < NUM_TUNINGZONES; i++) // decided to send no text on changing Tunezones for now + { + str_format(m_ZoneEnterMsg[i], sizeof(m_ZoneEnterMsg[i]), "", i); + str_format(m_ZoneLeaveMsg[i], sizeof(m_ZoneLeaveMsg[i]), "", i); + } + // Reset Tuning + if(g_Config.m_SvTuneReset) + { + ResetTuning(); + } + else + { + Tuning()->Set("gun_speed", 1400); + Tuning()->Set("gun_curvature", 0); + Tuning()->Set("shotgun_speed", 500); + Tuning()->Set("shotgun_speeddiff", 0); + Tuning()->Set("shotgun_curvature", 0); + } + + if(g_Config.m_SvDDRaceTuneReset) + { + g_Config.m_SvHit = 1; + g_Config.m_SvEndlessDrag = 0; + g_Config.m_SvOldLaser = 0; + g_Config.m_SvOldTeleportHook = 0; + g_Config.m_SvOldTeleportWeapons = 0; + g_Config.m_SvTeleportHoldHook = 0; + g_Config.m_SvTeam = 1; + g_Config.m_SvShowOthersDefault = 0; + + if(Collision()->m_NumSwitchers > 0) + for (int i = 0; i < Collision()->m_NumSwitchers+1; ++i) + Collision()->m_pSwitchers[i].m_Initial = true; + } + + Console()->ExecuteFile(g_Config.m_SvResetFile); + + LoadMapSettings(); + + m_pController = new CGameControllerWarioWare(this); + ((CGameControllerWarioWare*)m_pController)->m_Teams.Reset(); + + if(g_Config.m_SvSoloServer) + { + g_Config.m_SvTeam = 3; + g_Config.m_SvShowOthersDefault = 1; + + Tuning()->Set("player_collision", 0); + Tuning()->Set("player_hooking", 0); + + for (int i = 0; i < NUM_TUNINGZONES; i++) + { + TuningList()[i].Set("player_collision", 0); + TuningList()[i].Set("player_hooking", 0); + } + } + + // delete old score object + if(m_pScore) + delete m_pScore; + + // create score object (add sql later) +#if defined(CONF_SQL) + if(g_Config.m_SvUseSQL) + m_pScore = new CSqlScore(this); + else +#endif + m_pScore = new CFileScore(this); + // setup core world + //for(int i = 0; i < MAX_CLIENTS; i++) + // game.players[i].core.world = &game.world.core; + + // 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; + */ + + CTile *pFront = 0; + CSwitchTile *pSwitch = 0; + if(m_Layers.FrontLayer()) + pFront = (CTile *)Kernel()->RequestInterface<IMap>()->GetData(m_Layers.FrontLayer()->m_Front); + if(m_Layers.SwitchLayer()) + pSwitch = (CSwitchTile *)Kernel()->RequestInterface<IMap>()->GetData(m_Layers.SwitchLayer()->m_Switch); + + 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 == TILE_OLDLASER) + { + g_Config.m_SvOldLaser = 1; + dbg_msg("Game Layer", "Found Old Laser Tile"); + } + else if(Index == TILE_NPC) + { + m_Tuning.Set("player_collision", 0); + dbg_msg("Game Layer", "Found No Collision Tile"); + } + else if(Index == TILE_EHOOK) + { + g_Config.m_SvEndlessDrag = 1; + dbg_msg("Game Layer", "Found No Unlimited hook time Tile"); + } + else if(Index == TILE_NOHIT) + { + g_Config.m_SvHit = 0; + dbg_msg("Game Layer", "Found No Weapons Hitting others Tile"); + } + else if(Index == TILE_NPH) + { + m_Tuning.Set("player_hooking", 0); + dbg_msg("Game Layer", "Found No Player Hooking Tile"); + } + + if(Index >= ENTITY_OFFSET) + { + vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); + //m_pController->OnEntity(Index-ENTITY_OFFSET, Pos); + m_pController->OnEntity(Index - ENTITY_OFFSET, Pos, LAYER_GAME, pTiles[y * pTileMap->m_Width + x].m_Flags); + } + + if(pFront) + { + Index = pFront[y * pTileMap->m_Width + x].m_Index; + if(Index == TILE_OLDLASER) + { + g_Config.m_SvOldLaser = 1; + dbg_msg("Front Layer", "Found Old Laser Tile"); + } + else if(Index == TILE_NPC) + { + m_Tuning.Set("player_collision", 0); + dbg_msg("Front Layer", "Found No Collision Tile"); + } + else if(Index == TILE_EHOOK) + { + g_Config.m_SvEndlessDrag = 1; + dbg_msg("Front Layer", "Found No Unlimited hook time Tile"); + } + else if(Index == TILE_NOHIT) + { + g_Config.m_SvHit = 0; + dbg_msg("Front Layer", "Found No Weapons Hitting others Tile"); + } + else if(Index == TILE_NPH) + { + m_Tuning.Set("player_hooking", 0); + dbg_msg("Front Layer", "Found No Player Hooking Tile"); + } + if(Index >= ENTITY_OFFSET) + { + vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); + m_pController->OnEntity(Index-ENTITY_OFFSET, Pos, LAYER_FRONT, pFront[y*pTileMap->m_Width+x].m_Flags); + } + } + if(pSwitch) + { + Index = pSwitch[y*pTileMap->m_Width + x].m_Type; + // TODO: Add off by default door here + // if (Index == TILE_DOOR_OFF) + if(Index >= ENTITY_OFFSET) + { + vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); + m_pController->OnEntity(Index-ENTITY_OFFSET, Pos, LAYER_SWITCH, pSwitch[y*pTileMap->m_Width+x].m_Flags, pSwitch[y*pTileMap->m_Width+x].m_Number); + } + } + } + } + + //game.world.insert_entity(game.Controller); + + OnClientConnected(MAX_CLIENTS-1); // need this dummy for a microgame + m_apPlayers[MAX_CLIENTS-1]->SetTeam(TEAM_SPECTATORS, false); + Server()->SetClientName(MAX_CLIENTS-1, "bot"); + str_copy(m_apPlayers[MAX_CLIENTS-1]->m_TeeInfos.m_SkinName, "Bot", sizeof(m_apPlayers[MAX_CLIENTS-1]->m_TeeInfos.m_SkinName)); +} + +void CGameContext::DeleteTempfile() +{ + if(m_aDeleteTempfile[0] != 0) + { + IStorage *pStorage = Kernel()->RequestInterface<IStorage>(); + pStorage->RemoveFile(m_aDeleteTempfile, IStorage::TYPE_SAVE); + m_aDeleteTempfile[0] = 0; + } +} + +void CGameContext::OnMapChange(char *pNewMapName, int MapNameSize) +{ + IStorage *pStorage = Kernel()->RequestInterface<IStorage>(); + + char aConfig[128]; + char aTemp[128]; + str_format(aConfig, sizeof(aConfig), "maps/%s.cfg", g_Config.m_SvMap); + str_format(aTemp, sizeof(aTemp), "%s.temp.%d", pNewMapName, pid()); + + IOHANDLE File = pStorage->OpenFile(aConfig, IOFLAG_READ, IStorage::TYPE_ALL); + if(!File) + { + // No map-specific config, just return. + return; + } + CLineReader LineReader; + LineReader.Init(File); + + array<char *> aLines; + char *pLine; + int TotalLength = 0; + while((pLine = LineReader.Get())) + { + int Length = str_length(pLine) + 1; + char *pCopy = (char *)mem_alloc(Length, 1); + mem_copy(pCopy, pLine, Length); + aLines.add(pCopy); + TotalLength += Length; + } + + char *pSettings = (char *)mem_alloc(TotalLength, 1); + int Offset = 0; + for(int i = 0; i < aLines.size(); i++) + { + int Length = str_length(aLines[i]) + 1; + mem_copy(pSettings + Offset, aLines[i], Length); + Offset += Length; + mem_free(aLines[i]); + } + + CDataFileReader Reader; + Reader.Open(pStorage, pNewMapName, IStorage::TYPE_ALL); + + CDataFileWriter Writer; + Writer.Init(); + + int SettingsIndex = Reader.NumData(); + bool FoundInfo = false; + for(int i = 0; i < Reader.NumItems(); i++) + { + int TypeID; + int ItemID; + int *pData = (int *)Reader.GetItem(i, &TypeID, &ItemID); + // GetItemSize returns item size including header, remove that. + int Size = Reader.GetItemSize(i) - sizeof(int) * 2; + CMapItemInfoSettings MapInfo; + if(TypeID == MAPITEMTYPE_INFO && ItemID == 0) + { + FoundInfo = true; + CMapItemInfoSettings *pInfo = (CMapItemInfoSettings *)pData; + if(Size >= (int)sizeof(CMapItemInfoSettings)) + { + if(pInfo->m_Settings > -1) + { + SettingsIndex = pInfo->m_Settings; + char *pMapSettings = (char *)Reader.GetData(SettingsIndex); + int DataSize = Reader.GetUncompressedDataSize(SettingsIndex); + if(DataSize == TotalLength && mem_comp(pSettings, pMapSettings, DataSize) == 0) + { + // Configs coincide, no need to update map. + return; + } + Reader.UnloadData(pInfo->m_Settings); + } + else + { + MapInfo = *pInfo; + MapInfo.m_Settings = SettingsIndex; + pData = (int *)&MapInfo; + Size = sizeof(MapInfo); + } + } + else + { + *(CMapItemInfo *)&MapInfo = *(CMapItemInfo *)pInfo; + MapInfo.m_Settings = SettingsIndex; + pData = (int *)&MapInfo; + Size = sizeof(MapInfo); + } + } + Writer.AddItem(TypeID, ItemID, Size, pData); + } + + if(!FoundInfo) + { + CMapItemInfoSettings Info; + Info.m_Version = 1; + Info.m_Author = -1; + Info.m_MapVersion = -1; + Info.m_Credits = -1; + Info.m_License = -1; + Info.m_Settings = SettingsIndex; + Writer.AddItem(MAPITEMTYPE_INFO, 0, sizeof(Info), &Info); + } + + for(int i = 0; i < Reader.NumData() || i == SettingsIndex; i++) + { + if(i == SettingsIndex) + { + Writer.AddData(TotalLength, pSettings); + continue; + } + unsigned char *pData = (unsigned char *)Reader.GetData(i); + int Size = Reader.GetUncompressedDataSize(i); + Writer.AddData(Size, pData); + Reader.UnloadData(i); + } + + dbg_msg("mapchange", "imported settings"); + Reader.Close(); + Writer.OpenFile(pStorage, aTemp); + Writer.Finish(); + + str_copy(pNewMapName, aTemp, MapNameSize); + str_copy(m_aDeleteTempfile, aTemp, sizeof(m_aDeleteTempfile)); +} + +void CGameContext::OnShutdown() +{ + DeleteTempfile(); + Console()->ResetServerGameSettings(); + Layers()->Dest(); + Collision()->Dest(); + delete m_pController; + m_pController = 0; + Clear(); +} + +void CGameContext::LoadMapSettings() +{ + IMap *pMap = Kernel()->RequestInterface<IMap>(); + int Start, Num; + pMap->GetType(MAPITEMTYPE_INFO, &Start, &Num); + for(int i = Start; i < Start + Num; i++) + { + int ItemID; + CMapItemInfoSettings *pItem = (CMapItemInfoSettings *)pMap->GetItem(i, 0, &ItemID); + int ItemSize = pMap->GetItemSize(i) - 8; + if(!pItem || ItemID != 0) + continue; + + if(ItemSize < (int)sizeof(CMapItemInfoSettings)) + break; + if(!(pItem->m_Settings > -1)) + break; + + int Size = pMap->GetUncompressedDataSize(pItem->m_Settings); + char *pSettings = (char *)pMap->GetData(pItem->m_Settings); + char *pNext = pSettings; + while(pNext < pSettings + Size) + { + int StrSize = str_length(pNext) + 1; + Console()->ExecuteLine(pNext, IConsole::CLIENT_ID_GAME); + pNext += StrSize; + } + pMap->UnloadData(pItem->m_Settings); + break; + } + + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "maps/%s.map.cfg", g_Config.m_SvMap); + Console()->ExecuteFile(aBuf, IConsole::CLIENT_ID_NO_GAME); +} + +void CGameContext::OnSnap(int ClientID) +{ + // add tuning to demo + CTuningParams StandardTuning; + if(ClientID == -1 && Server()->DemoRecorder_IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0) + { + CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); + int *pParams = (int *)&m_Tuning; + for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) + Msg.AddInt(pParams[i]); + Server()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND, 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]) + m_apPlayers[i]->Snap(ClientID); + } + + if(ClientID > -1) + m_apPlayers[ClientID]->FakeSnap(ClientID); + +} +void CGameContext::OnPreSnap() {} +void CGameContext::OnPostSnap() +{ + m_Events.Clear(); +} + +bool CGameContext::IsClientReady(int ClientID) +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_IsReady ? true : false; +} + +bool CGameContext::IsClientPlayer(int ClientID) +{ + return m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS ? false : true; +} + +const char *CGameContext::GameType() { return m_pController && m_pController->m_pGameType ? m_pController->m_pGameType : ""; } +const char *CGameContext::Version() { return GAME_VERSION; } +const char *CGameContext::NetVersion() { return GAME_NETVERSION; } + +IGameServer *CreateGameServer() { return new CGameContext; } + +void CGameContext::SendChatResponseAll(const char *pLine, void *pUser) +{ + CGameContext *pSelf = (CGameContext *)pUser; + + static volatile int ReentryGuard = 0; + const char *pLineOrig = pLine; + + if(ReentryGuard) + return; + ReentryGuard++; + + if(*pLine == '[') + do + pLine++; + while((pLine - 2 < pLineOrig || *(pLine - 2) != ':') && *pLine != 0);//remove the category (e.g. [Console]: No Such Command) + + pSelf->SendChat(-1, CHAT_ALL, pLine); + + ReentryGuard--; +} + +void CGameContext::SendChatResponse(const char *pLine, void *pUser, bool Highlighted) +{ + CGameContext *pSelf = (CGameContext *)pUser; + int ClientID = pSelf->m_ChatResponseTargetID; + + if(ClientID < 0 || ClientID >= MAX_CLIENTS) + return; + + const char *pLineOrig = pLine; + + static volatile int ReentryGuard = 0; + + if(ReentryGuard) + return; + ReentryGuard++; + + if(*pLine == '[') + do + pLine++; + while((pLine - 2 < pLineOrig || *(pLine - 2) != ':') && *pLine != 0); // remove the category (e.g. [Console]: No Such Command) + + pSelf->SendChatTarget(ClientID, pLine); + + ReentryGuard--; +} + +bool CGameContext::PlayerCollision() +{ + float Temp; + m_Tuning.Get("player_collision", &Temp); + return Temp != 0.0; +} + +bool CGameContext::PlayerHooking() +{ + float Temp; + m_Tuning.Get("player_hooking", &Temp); + return Temp != 0.0; +} + +float CGameContext::PlayerJetpack() +{ + float Temp; + m_Tuning.Get("player_jetpack", &Temp); + return Temp; +} + +void CGameContext::OnSetAuthed(int ClientID, int Level) +{ + CServer* pServ = (CServer*)Server(); + if(m_apPlayers[ClientID]) + { + m_apPlayers[ClientID]->m_Authed = Level; + char aBuf[512], aIP[NETADDR_MAXSTRSIZE]; + pServ->GetClientAddr(ClientID, aIP, sizeof(aIP)); + str_format(aBuf, sizeof(aBuf), "ban %s %d Banned by vote", aIP, g_Config.m_SvVoteKickBantime); + if(!str_comp_nocase(m_aVoteCommand, aBuf) && Level > 0) + { + m_VoteEnforce = CGameContext::VOTE_ENFORCE_NO_ADMIN; + Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "CGameContext", "Aborted vote by admin login."); + } + } +} + +void CGameContext::SendRecord(int ClientID) +{ + CNetMsg_Sv_Record RecordsMsg; + RecordsMsg.m_PlayerTimeBest = Score()->PlayerData(ClientID)->m_BestTime * 100.0f; + RecordsMsg.m_ServerTimeBest = m_pController->m_CurrentRecord * 100.0f; //TODO: finish this + Server()->SendPackMsg(&RecordsMsg, MSGFLAG_VITAL, ClientID); +} + +int CGameContext::ProcessSpamProtection(int ClientID) +{ + if(!m_apPlayers[ClientID]) + return 0; + if(g_Config.m_SvSpamprotection && m_apPlayers[ClientID]->m_LastChat + && m_apPlayers[ClientID]->m_LastChat + Server()->TickSpeed() * g_Config.m_SvChatDelay > Server()->Tick()) + return 1; + else + m_apPlayers[ClientID]->m_LastChat = Server()->Tick(); + NETADDR Addr; + Server()->GetClientAddr(ClientID, &Addr); + int Muted = 0; + + for(int i = 0; i < m_NumMutes && !Muted; i++) + { + if(!net_addr_comp(&Addr, &m_aMutes[i].m_Addr)) + Muted = (m_aMutes[i].m_Expire - Server()->Tick()) / Server()->TickSpeed(); + } + + if (Muted > 0) + { + char aBuf[128]; + str_format(aBuf, sizeof aBuf, "You are not permitted to talk for the next %d seconds.", Muted); + SendChatTarget(ClientID, aBuf); + return 1; + } + + if ((m_apPlayers[ClientID]->m_ChatScore += g_Config.m_SvChatPenalty) > g_Config.m_SvChatThreshold) + { + Mute(0, &Addr, g_Config.m_SvSpamMuteDuration, Server()->ClientName(ClientID)); + m_apPlayers[ClientID]->m_ChatScore = 0; + return 1; + } + + return 0; +} + +int CGameContext::GetDDRaceTeam(int ClientID) +{ + CGameControllerWarioWare* pController = (CGameControllerWarioWare*)m_pController; + return pController->m_Teams.m_Core.Team(ClientID); +} + +void CGameContext::ResetTuning() +{ + CTuningParams TuningParams; + m_Tuning = TuningParams; + Tuning()->Set("gun_speed", 1400); + Tuning()->Set("gun_curvature", 0); + Tuning()->Set("shotgun_speed", 500); + Tuning()->Set("shotgun_speeddiff", 0); + Tuning()->Set("shotgun_curvature", 0); + SendTuningParams(-1); +} + +bool CheckClientID2(int ClientID) +{ + dbg_assert(ClientID >= 0 || ClientID < MAX_CLIENTS, + "The Client ID is wrong"); + if (ClientID < 0 || ClientID >= MAX_CLIENTS) + return false; + return true; +} + +void CGameContext::Whisper(int ClientID, char *pStr) +{ + char *pName; + char *pMessage; + int Error = 0; + + if(ProcessSpamProtection(ClientID)) + return; + + pStr = str_skip_whitespaces(pStr); + + int Victim; + + // add token + if(*pStr == '"') + { + pStr++; + + pName = pStr; // we might have to process escape data + while(1) + { + if(pStr[0] == '"') + break; + else if(pStr[0] == '\\') + { + if(pStr[1] == '\\') + pStr++; // skip due to escape + else if(pStr[1] == '"') + pStr++; // skip due to escape + } + else if(pStr[0] == 0) + Error = 1; + + pStr++; + } + + // write null termination + *pStr = 0; + pStr++; + + for(Victim = 0; Victim < MAX_CLIENTS; Victim++) + if (str_comp(pName, Server()->ClientName(Victim)) == 0) + break; + + } + else + { + pName = pStr; + while(1) + { + if(pStr[0] == 0) + { + Error = 1; + break; + } + if(pStr[0] == ' ') + { + pStr[0] = 0; + for(Victim = 0; Victim < MAX_CLIENTS; Victim++) + if (str_comp(pName, Server()->ClientName(Victim)) == 0) + break; + + pStr[0] = ' '; + + if (Victim < MAX_CLIENTS) + break; + } + pStr++; + } + } + + if(pStr[0] != ' ') + { + Error = 1; + } + + *pStr = 0; + pStr++; + + pMessage = pStr; + + char aBuf[256]; + + if (Error) + { + str_format(aBuf, sizeof(aBuf), "Invalid whisper"); + SendChatTarget(ClientID, aBuf); + return; + } + + if (Victim >= MAX_CLIENTS || !CheckClientID2(Victim)) + { + str_format(aBuf, sizeof(aBuf), "No player with name \"%s\" found", pName); + SendChatTarget(ClientID, aBuf); + return; + } + + WhisperID(ClientID, Victim, pMessage); +} + +void CGameContext::WhisperID(int ClientID, int VictimID, char *pMessage) +{ + if (!CheckClientID2(ClientID)) + return; + + if (!CheckClientID2(VictimID)) + return; + + if (m_apPlayers[ClientID]) + m_apPlayers[ClientID]->m_LastWhisperTo = VictimID; + + char aBuf[256]; + + if (m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_ClientVersion >= VERSION_DDNET_WHISPER) + { + CNetMsg_Sv_Chat Msg; + Msg.m_Team = CHAT_WHISPER_SEND; + Msg.m_ClientID = VictimID; + Msg.m_pMessage = pMessage; + if(g_Config.m_SvDemoChat) + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); + else + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); + } + else + { + str_format(aBuf, sizeof(aBuf), "[→ %s] %s", Server()->ClientName(VictimID), pMessage); + SendChatTarget(ClientID, aBuf); + } + + if (m_apPlayers[VictimID] && m_apPlayers[VictimID]->m_ClientVersion >= VERSION_DDNET_WHISPER) + { + CNetMsg_Sv_Chat Msg2; + Msg2.m_Team = CHAT_WHISPER_RECV; + Msg2.m_ClientID = ClientID; + Msg2.m_pMessage = pMessage; + if(g_Config.m_SvDemoChat) + Server()->SendPackMsg(&Msg2, MSGFLAG_VITAL, VictimID); + else + Server()->SendPackMsg(&Msg2, MSGFLAG_VITAL|MSGFLAG_NORECORD, VictimID); + } + else + { + str_format(aBuf, sizeof(aBuf), "[← %s] %s", Server()->ClientName(ClientID), pMessage); + SendChatTarget(VictimID, aBuf); + } +} + +void CGameContext::Converse(int ClientID, char *pStr) +{ + CPlayer *pPlayer = m_apPlayers[ClientID]; + if (!pPlayer) + return; + + if(ProcessSpamProtection(ClientID)) + return; + + if (pPlayer->m_LastWhisperTo < 0) + SendChatTarget(ClientID, "You do not have an ongoing conversation. Whisper to someone to start one"); + else + { + WhisperID(ClientID, pPlayer->m_LastWhisperTo, pStr); + } +} + +void CGameContext::List(int ClientID, const char* filter) +{ + int total = 0; + char buf[256]; + int bufcnt = 0; + if (filter[0]) + str_format(buf, sizeof(buf), "Listing players with \"%s\" in name:", filter); + else + str_format(buf, sizeof(buf), "Listing all players:", filter); + SendChatTarget(ClientID, buf); + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(m_apPlayers[i]) + { + total++; + const char* name = Server()->ClientName(i); + if (str_find_nocase(name, filter) == NULL) + continue; + if (bufcnt + str_length(name) + 4 > 256) + { + SendChatTarget(ClientID, buf); + bufcnt = 0; + } + if (bufcnt != 0) + { + str_format(&buf[bufcnt], sizeof(buf) - bufcnt, ", %s", name); + bufcnt += 2 + str_length(name); + } + else + { + str_format(&buf[bufcnt], sizeof(buf) - bufcnt, "%s", name); + bufcnt += str_length(name); + } + } + } + if (bufcnt != 0) + SendChatTarget(ClientID, buf); + str_format(buf, sizeof(buf), "%d players online", total); + SendChatTarget(ClientID, buf); +} diff --git a/src/game/server/gamecontext.h b/src/game/server/gamecontext.h new file mode 100644 index 0000000..442565e --- /dev/null +++ b/src/game/server/gamecontext.h @@ -0,0 +1,407 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMECONTEXT_H +#define GAME_SERVER_GAMECONTEXT_H + +#include <iostream> + +#include <engine/server.h> +#include <engine/console.h> +#include <engine/shared/memheap.h> + +#include <game/layers.h> +#include <game/voting.h> + +#include "eventhandler.h" +#include "gamecontroller.h" +#include "gameworld.h" +#include "player.h" + +#include "score.h" +#ifdef _MSC_VER +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include <stdint.h> +#endif +/* + Tick + Game Context (CGameContext::tick) + Game World (GAMEWORLD::tick) + Reset world if requested (GAMEWORLD::reset) + All entities in the world (ENTITY::tick) + All entities in the world (ENTITY::tick_defered) + Remove entities marked for deletion (GAMEWORLD::remove_entities) + Game Controller (GAMECONTROLLER::tick) + All players (CPlayer::tick) + + + Snap + Game Context (CGameContext::snap) + Game World (GAMEWORLD::snap) + All entities in the world (ENTITY::snap) + Game Controller (GAMECONTROLLER::snap) + Events handler (EVENT_HANDLER::snap) + All players (CPlayer::snap) + +*/ + +enum +{ + NUM_TUNINGZONES = 256 +}; + + +// headbot +typedef struct _Song +{ + _Song(int Start, int Length, const char *Name) + { + start = Start; + length = Length; + str_copy(name, Name, sizeof(name)); + } + int start; + int length; + char name[64]; +} Song; + + +class CGameContext : public IGameServer +{ + IServer *m_pServer; + class IConsole *m_pConsole; + CLayers m_Layers; + CCollision m_Collision; + CNetObjHandler m_NetObjHandler; + CTuningParams m_Tuning; + CTuningParams m_TuningList[NUM_TUNINGZONES]; + + static void ConTuneParam(IConsole::IResult *pResult, void *pUserData); + static void ConTuneReset(IConsole::IResult *pResult, void *pUserData); + static void ConTuneDump(IConsole::IResult *pResult, void *pUserData); + static void ConTuneZone(IConsole::IResult *pResult, void *pUserData); + static void ConTuneDumpZone(IConsole::IResult *pResult, void *pUserData); + static void ConTuneResetZone(IConsole::IResult *pResult, void *pUserData); + static void ConTuneSetZoneMsgEnter(IConsole::IResult *pResult, void *pUserData); + static void ConTuneSetZoneMsgLeave(IConsole::IResult *pResult, void *pUserData); + static void ConSwitchOpen(IConsole::IResult *pResult, void *pUserData); + static void ConPause(IConsole::IResult *pResult, void *pUserData); + static void ConChangeMap(IConsole::IResult *pResult, void *pUserData); + static void ConRandomMap(IConsole::IResult *pResult, void *pUserData); + static void ConRandomUnfinishedMap(IConsole::IResult *pResult, void *pUserData); + static void ConSaveTeam(IConsole::IResult *pResult, void *pUserData); + static void ConLoadTeam(IConsole::IResult *pResult, void *pUserData); + static void ConRestart(IConsole::IResult *pResult, void *pUserData); + static void ConBroadcast(IConsole::IResult *pResult, void *pUserData); + static void ConSay(IConsole::IResult *pResult, void *pUserData); + static void ConSayAs(IConsole::IResult *pResult, void *pUserData); + static void ConSetTeam(IConsole::IResult *pResult, void *pUserData); + static void ConSetTeamAll(IConsole::IResult *pResult, void *pUserData); + //static void ConSwapTeams(IConsole::IResult *pResult, void *pUserData); + //static void ConShuffleTeams(IConsole::IResult *pResult, void *pUserData); + //static void ConLockTeams(IConsole::IResult *pResult, void *pUserData); + static void ConAddVote(IConsole::IResult *pResult, void *pUserData); + static void ConRemoveVote(IConsole::IResult *pResult, void *pUserData); + static void ConForceVote(IConsole::IResult *pResult, void *pUserData); + static void ConClearVotes(IConsole::IResult *pResult, void *pUserData); + static void ConVote(IConsole::IResult *pResult, void *pUserData); + static void ConWindows(IConsole::IResult *pResult, void *pUserData); + static void ConRename(IConsole::IResult *pResult, void *pUserData); + static void ConBigTroll(IConsole::IResult *pResult, void *pUserData); + static void ConSetTimer(IConsole::IResult *pResult, void *pUserData); + static void ConGetTimer(IConsole::IResult *pResult, void *pUserData); // debug shit + static void ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); + + CGameContext(int Resetting); + void Construct(int Resetting); + + bool m_Resetting; +public: + IServer *Server() const { return m_pServer; } + class IConsole *Console() { return m_pConsole; } + CCollision *Collision() { return &m_Collision; } + CTuningParams *Tuning() { return &m_Tuning; } + CTuningParams *TuningList() { return &m_TuningList[0]; } + + 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); + + //int m_LockTeams; + + // 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; + int m_VotePos; + char m_aVoteDescription[VOTE_DESC_LENGTH]; + char m_aVoteCommand[VOTE_CMD_LENGTH]; + char m_aVoteReason[VOTE_REASON_LENGTH]; + int m_NumVoteOptions; + int m_VoteEnforce; + char m_ZoneEnterMsg[NUM_TUNINGZONES][256]; // 0 is used for switching from or to area without tunings + char m_ZoneLeaveMsg[NUM_TUNINGZONES][256]; + + char m_aDeleteTempfile[128]; + void DeleteTempfile(); + + enum + { + VOTE_ENFORCE_UNKNOWN=0, + VOTE_ENFORCE_NO, + VOTE_ENFORCE_YES, + }; + CHeap *m_pVoteOptionHeap; + CVoteOptionServer *m_pVoteOptionFirst; + CVoteOptionServer *m_pVoteOptionLast; + + // helper functions + void CreateDamageInd(vec2 Pos, float AngleMod, int Amount, int64_t Mask=-1); + int CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage, int ActivatedTeam, int64_t Mask); + void CreateHammerHit(vec2 Pos, int64_t Mask=-1); + void CreatePlayerSpawn(vec2 Pos, int64_t Mask=-1); + void CreateDeath(vec2 Pos, int Who, int64_t Mask=-1); + void CreateSound(vec2 Pos, int Sound, int64_t Mask=-1); + void CreateSoundGlobal(int Sound, int Target=-1); + + + enum + { + CHAT_ALL=-2, + CHAT_SPEC=-1, + CHAT_RED=0, + CHAT_BLUE=1, + CHAT_WHISPER_SEND=2, + CHAT_WHISPER_RECV=3 + }; + + // network + void CallVote(int ClientID, const char *aDesc, const char *aCmd, const char *pReason, const char *aChatmsg); + void SendChatTarget(int To, const char *pText); + void SendChatTeam(int Team, const char *pText); + void SendChat(int ClientID, int Team, const char *pText, int SpamProtectionClientID = -1); + void SendEmoticon(int ClientID, int Emoticon); + void SendWeaponPickup(int ClientID, int Weapon); + void SendBroadcast(const char *pText, int ClientID); + + void List(int ClientID, const char* filter); + + // + void CheckPureTuning(); + void SendTuningParams(int ClientID, int Zone = 0); + + struct CVoteOptionServer *GetVoteOption(int Index); + void ProgressVoteOptions(int ClientID); + + // + //void SwapTeams(); + + void LoadMapSettings(); + + // engine events + virtual void OnInit(); + virtual void OnConsoleInit(); + virtual void OnMapChange(char *pNewMapName, int MapNameSize); + 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); + virtual void OnClientEnter(int ClientID); + virtual void OnClientDrop(int ClientID, const char *pReason); + virtual void OnClientDirectInput(int ClientID, void *pInput); + virtual void OnClientPredictedInput(int ClientID, void *pInput); + + virtual bool IsClientReady(int ClientID); + virtual bool IsClientPlayer(int ClientID); + + virtual const char *GameType(); + virtual const char *Version(); + virtual const char *NetVersion(); + + // DDRace + + int ProcessSpamProtection(int ClientID); + int GetDDRaceTeam(int ClientID); + // Describes the time when the first player joined the server. + int64 m_NonEmptySince; + int64 m_LastMapVote; + + //headbot + FILE* pipe; + int shellBroadcast; + int earrape_timer; + std::vector<Song*> songs; + Song* m_song; + +private: + + bool m_VoteWillPass; + class IScore *m_pScore; + + //DDRace Console Commands + + //static void ConMute(IConsole::IResult *pResult, void *pUserData); + //static void ConUnmute(IConsole::IResult *pResult, void *pUserData); + static void ConKillPlayer(IConsole::IResult *pResult, void *pUserData); + + static void ConNinja(IConsole::IResult *pResult, void *pUserData); + static void ConUnSolo(IConsole::IResult *pResult, void *pUserData); + static void ConUnDeep(IConsole::IResult *pResult, void *pUserData); + static void ConUnSuper(IConsole::IResult *pResult, void *pUserData); + static void ConSuper(IConsole::IResult *pResult, void *pUserData); + static void ConShotgun(IConsole::IResult *pResult, void *pUserData); + static void ConGrenade(IConsole::IResult *pResult, void *pUserData); + static void ConRifle(IConsole::IResult *pResult, void *pUserData); + static void ConWeapons(IConsole::IResult *pResult, void *pUserData); + static void ConUnShotgun(IConsole::IResult *pResult, void *pUserData); + static void ConUnGrenade(IConsole::IResult *pResult, void *pUserData); + static void ConUnRifle(IConsole::IResult *pResult, void *pUserData); + static void ConUnWeapons(IConsole::IResult *pResult, void *pUserData); + static void ConAddWeapon(IConsole::IResult *pResult, void *pUserData); + static void ConRemoveWeapon(IConsole::IResult *pResult, void *pUserData); + + void ModifyWeapons(IConsole::IResult *pResult, void *pUserData, int Weapon, bool Remove); + void MoveCharacter(int ClientID, int X, int Y, bool Raw = false); + static void ConGoLeft(IConsole::IResult *pResult, void *pUserData); + static void ConGoRight(IConsole::IResult *pResult, void *pUserData); + static void ConGoUp(IConsole::IResult *pResult, void *pUserData); + static void ConGoDown(IConsole::IResult *pResult, void *pUserData); + static void ConMove(IConsole::IResult *pResult, void *pUserData); + static void ConMoveRaw(IConsole::IResult *pResult, void *pUserData); + + static void ConToTeleporter(IConsole::IResult *pResult, void *pUserData); + static void ConToCheckTeleporter(IConsole::IResult *pResult, void *pUserData); + static void ConTeleport(IConsole::IResult *pResult, void *pUserData); + + static void ConCredits(IConsole::IResult *pResult, void *pUserData); + static void ConInfo(IConsole::IResult *pResult, void *pUserData); + static void ConHelp(IConsole::IResult *pResult, void *pUserData); + static void ConSettings(IConsole::IResult *pResult, void *pUserData); + static void ConRules(IConsole::IResult *pResult, void *pUserData); + static void ConKill(IConsole::IResult *pResult, void *pUserData); + static void ConTogglePause(IConsole::IResult *pResult, void *pUserData); + static void ConToggleSpec(IConsole::IResult *pResult, void *pUserData); + static void ConForcePause(IConsole::IResult *pResult, void *pUserData); + static void ConTeamTop5(IConsole::IResult *pResult, void *pUserData); + static void ConTop5(IConsole::IResult *pResult, void *pUserData); + #if defined(CONF_SQL) + static void ConTimes(IConsole::IResult *pResult, void *pUserData); + static void ConPoints(IConsole::IResult *pResult, void *pUserData); + static void ConTopPoints(IConsole::IResult *pResult, void *pUserData); + #endif + + static void ConUTF8(IConsole::IResult *pResult, void *pUserData); + static void ConDND(IConsole::IResult *pResult, void *pUserData); + static void ConMapInfo(IConsole::IResult *pResult, void *pUserData); + static void ConTimeout(IConsole::IResult *pResult, void *pUserData); + static void ConSave(IConsole::IResult *pResult, void *pUserData); + static void ConLoad(IConsole::IResult *pResult, void *pUserData); + static void ConMap(IConsole::IResult *pResult, void *pUserData); + static void ConTeamRank(IConsole::IResult *pResult, void *pUserData); + static void ConRank(IConsole::IResult *pResult, void *pUserData); + static void ConBroadTime(IConsole::IResult *pResult, void *pUserData); + static void ConJoinTeam(IConsole::IResult *pResult, void *pUserData); + static void ConLockTeam(IConsole::IResult *pResult, void *pUserData); + static void ConMe(IConsole::IResult *pResult, void *pUserData); + static void ConWhisper(IConsole::IResult *pResult, void *pUserData); + static void ConConverse(IConsole::IResult *pResult, void *pUserData); + static void ConSetEyeEmote(IConsole::IResult *pResult, void *pUserData); + static void ConToggleBroadcast(IConsole::IResult *pResult, void *pUserData); + static void ConEyeEmote(IConsole::IResult *pResult, void *pUserData); + static void ConShowOthers(IConsole::IResult *pResult, void *pUserData); + static void ConShowAll(IConsole::IResult *pResult, void *pUserData); + static void ConSpecTeam(IConsole::IResult *pResult, void *pUserData); + static void ConNinjaJetpack(IConsole::IResult *pResult, void *pUserData); + static void ConSayTime(IConsole::IResult *pResult, void *pUserData); + static void ConSayTimeAll(IConsole::IResult *pResult, void *pUserData); + static void ConTime(IConsole::IResult *pResult, void *pUserData); + static void ConSetTimerType(IConsole::IResult *pResult, void *pUserData); + static void ConRescue(IConsole::IResult *pResult, void *pUserData); + static void ConProtectedKill(IConsole::IResult *pResult, void *pUserData); + static void ConEarRape(IConsole::IResult *pResult, void *pUserData); + + + + static void ConMute(IConsole::IResult *pResult, void *pUserData); + static void ConMuteID(IConsole::IResult *pResult, void *pUserData); + static void ConMuteIP(IConsole::IResult *pResult, void *pUserData); + static void ConUnmute(IConsole::IResult *pResult, void *pUserData); + static void ConMutes(IConsole::IResult *pResult, void *pUserData); + + static void ConList(IConsole::IResult *pResult, void *pUserData); + static void ConFreezeHammer(IConsole::IResult *pResult, void *pUserData); + static void ConUnFreezeHammer(IConsole::IResult *pResult, void *pUserData); + + enum + { + MAX_MUTES=32, + }; + struct CMute + { + NETADDR m_Addr; + int m_Expire; + }; + + CMute m_aMutes[MAX_MUTES]; + int m_NumMutes; + void Mute(IConsole::IResult *pResult, NETADDR *Addr, int Secs, const char *pDisplayName); + void Whisper(int ClientID, char *pStr); + void WhisperID(int ClientID, int VictimID, char *pMessage); + void Converse(int ClientID, char *pStr); + +public: + CLayers *Layers() { return &m_Layers; } + IKernel *aKernel() { return Kernel(); } + class IScore *Score() { return m_pScore; } + bool m_VoteKick; + bool m_VoteSpec; + enum + { + VOTE_ENFORCE_NO_ADMIN = VOTE_ENFORCE_YES + 1, + VOTE_ENFORCE_YES_ADMIN + }; + int m_VoteEnforcer; + void SendRecord(int ClientID); + static void SendChatResponse(const char *pLine, void *pUser, bool Highlighted = false); + static void SendChatResponseAll(const char *pLine, void *pUser); + virtual void OnSetAuthed(int ClientID,int Level); + virtual bool PlayerCollision(); + virtual bool PlayerHooking(); + virtual float PlayerJetpack(); + + void ResetTuning(); + + int m_ChatResponseTargetID; + int m_ChatPrintCBIndex; +}; + +inline int64_t CmaskAll() { return -1LL; } +inline int64_t CmaskOne(int ClientID) { return 1LL<<ClientID; } +inline int64_t CmaskAllExceptOne(int ClientID) { return CmaskAll()^CmaskOne(ClientID); } +inline bool CmaskIsSet(int64_t Mask, int ClientID) { return (Mask&CmaskOne(ClientID)) != 0; } +#endif diff --git a/src/game/server/gamecontroller.cpp b/src/game/server/gamecontroller.cpp new file mode 100644 index 0000000..0018c8c --- /dev/null +++ b/src/game/server/gamecontroller.cpp @@ -0,0 +1,963 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <engine/shared/config.h> +#include <game/mapitems.h> + +#include <game/generated/protocol.h> + +#include "entities/pickup.h" +#include "gamecontroller.h" +#include "gamecontext.h" + +#include "entities/light.h" +#include "entities/dragger.h" +#include "entities/gun.h" +#include "entities/projectile.h" +#include "entities/plasma.h" +#include "entities/door.h" +#include <game/layers.h> + + +IGameController::IGameController(class CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; + m_pServer = m_pGameServer->Server(); + m_pGameType = "unknown"; + + // + DoWarmup(g_Config.m_SvWarmup); + m_GameOverTick = -1; + m_SuddenDeath = 0; + m_RoundStartTick = Server()->Tick(); + m_RoundCount = 0; + m_GameFlags = 0; + //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; + + m_CurrentRecord = 0; +} + +IGameController::~IGameController() +{ +} + +float IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) +{ + float Score = 0.0f; + CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); + for(; pC; pC = (CCharacter *)pC->TypeNext()) + { + // team mates are not as dangerous as enemies + 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++) + { + // check if the position is occupado + CCharacter *aEnts[MAX_CLIENTS]; + int Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); + vec2 Positions[5] = { vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f) }; // start, left, up, right, down + int Result = -1; + for(int Index = 0; Index < 5 && Result == -1; ++Index) + { + Result = Index; + if(!GameServer()->m_World.m_Core.m_Tuning[0].m_PlayerCollision) + break; + for(int c = 0; c < Num; ++c) + if(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i]+Positions[Index]) || + distance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i]+Positions[Index]) <= aEnts[c]->m_ProximityRadius) + { + Result = -1; + break; + } + } + if(Result == -1) + continue; // try next spawn point + + vec2 P = m_aaSpawnPoints[Type][i]+Positions[Result]; + float S = EvaluateSpawnPos(pEval, P); + if(!pEval->m_Got || pEval->m_Score > S) + { + pEval->m_Got = true; + pEval->m_Score = S; + pEval->m_Pos = P; + } + } +} + +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) + { + EvaluateSpawnType(&Eval, 0); + if(!Eval.m_Got) + EvaluateSpawnType(&Eval, 1+((Team+1)&1)); + } + } + else + {*/ + EvaluateSpawnType(&Eval, 0); + EvaluateSpawnType(&Eval, 1); + EvaluateSpawnType(&Eval, 2); + //} + + *pOutPos = Eval.m_Pos; + return Eval.m_Got; +} + + +//bool IGameController::OnEntity(int Index, vec2 Pos) +bool IGameController::OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Number) +{ + if (Index < 0) + return false; + + int Type = -1; + int SubType = 0; + + int x,y; + x=(Pos.x-16.0f)/32.0f; + y=(Pos.y-16.0f)/32.0f; + int sides[8]; + sides[0]=GameServer()->Collision()->Entity(x,y+1, Layer); + sides[1]=GameServer()->Collision()->Entity(x+1,y+1, Layer); + sides[2]=GameServer()->Collision()->Entity(x+1,y, Layer); + sides[3]=GameServer()->Collision()->Entity(x+1,y-1, Layer); + sides[4]=GameServer()->Collision()->Entity(x,y-1, Layer); + sides[5]=GameServer()->Collision()->Entity(x-1,y-1, Layer); + sides[6]=GameServer()->Collision()->Entity(x-1,y, Layer); + sides[7]=GameServer()->Collision()->Entity(x-1,y+1, Layer); + + + if(Index == ENTITY_SPAWN) + m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos; + else if(Index == ENTITY_SPAWN_RED) + m_aaSpawnPoints[1][m_aNumSpawnPoints[1]++] = Pos; + else if(Index == ENTITY_SPAWN_BLUE) + m_aaSpawnPoints[2][m_aNumSpawnPoints[2]++] = Pos; + + else if(Index == ENTITY_DOOR) + { + for(int i = 0; i < 8;i++) + { + if (sides[i] >= ENTITY_LASER_SHORT && sides[i] <= ENTITY_LASER_LONG) + { + new CDoor + ( + &GameServer()->m_World, //GameWorld + Pos, //Pos + pi / 4 * i, //Rotation + 32 * 3 + 32 *(sides[i] - ENTITY_LASER_SHORT) * 3, //Length + Number //Number + ); + } + } + } + else if(Index == ENTITY_CRAZY_SHOTGUN_EX) + { + int Dir; + if(!Flags) + Dir = 0; + else if(Flags == ROTATION_90) + Dir = 1; + else if(Flags == ROTATION_180) + Dir = 2; + else + Dir = 3; + float Deg = Dir * (pi / 2); + CProjectile *bullet = new CProjectile + ( + &GameServer()->m_World, + WEAPON_SHOTGUN, //Type + -1, //Owner + Pos, //Pos + vec2(sin(Deg), cos(Deg)), //Dir + -2, //Span + true, //Freeze + true, //Explosive + 0, //Force + (g_Config.m_SvShotgunBulletSound)?SOUND_GRENADE_EXPLODE:-1,//SoundImpact + WEAPON_SHOTGUN,//Weapon + Layer, + Number + ); + bullet->SetBouncing(2 - (Dir % 2)); + } + else if(Index == ENTITY_CRAZY_SHOTGUN) + { + int Dir; + if(!Flags) + Dir=0; + else if(Flags == (TILEFLAG_ROTATE)) + Dir = 1; + else if(Flags == (TILEFLAG_VFLIP|TILEFLAG_HFLIP)) + Dir = 2; + else + Dir = 3; + float Deg = Dir * ( pi / 2); + CProjectile *bullet = new CProjectile + ( + &GameServer()->m_World, + WEAPON_SHOTGUN, //Type + -1, //Owner + Pos, //Pos + vec2(sin(Deg), cos(Deg)), //Dir + -2, //Span + true, //Freeze + false, //Explosive + 0, + SOUND_GRENADE_EXPLODE, + WEAPON_SHOTGUN, //Weapon + Layer, + Number + ); + bullet->SetBouncing(2 - (Dir % 2)); + } + + if(Index == ENTITY_ARMOR_1) + Type = POWERUP_ARMOR; + else if(Index == ENTITY_HEALTH_1) + Type = POWERUP_HEALTH; + else if(Index == ENTITY_WEAPON_SHOTGUN) + { + Type = POWERUP_WEAPON; + SubType = WEAPON_SHOTGUN; + } + else if(Index == ENTITY_WEAPON_GRENADE) + { + Type = POWERUP_WEAPON; + SubType = WEAPON_GRENADE; + } + else if(Index == ENTITY_WEAPON_RIFLE) + { + Type = POWERUP_WEAPON; + SubType = WEAPON_RIFLE; + } + //else if(Index == ENTITY_POWERUP_NINJA && g_Config.m_SvPowerups) + else if(Index == ENTITY_POWERUP_NINJA) + { + Type = POWERUP_NINJA; + SubType = WEAPON_NINJA; + } + else if(Index >= ENTITY_LASER_FAST_CW && Index <= ENTITY_LASER_FAST_CCW) + { + int sides2[8]; + sides2[0]=GameServer()->Collision()->Entity(x, y + 2, Layer); + sides2[1]=GameServer()->Collision()->Entity(x + 2, y + 2, Layer); + sides2[2]=GameServer()->Collision()->Entity(x + 2, y, Layer); + sides2[3]=GameServer()->Collision()->Entity(x + 2, y - 2, Layer); + sides2[4]=GameServer()->Collision()->Entity(x,y - 2, Layer); + sides2[5]=GameServer()->Collision()->Entity(x - 2, y - 2, Layer); + sides2[6]=GameServer()->Collision()->Entity(x - 2, y, Layer); + sides2[7]=GameServer()->Collision()->Entity(x - 2, y + 2, Layer); + + float AngularSpeed = 0.0; + int Ind=Index-ENTITY_LASER_STOP; + int M; + if( Ind < 0) + { + Ind = -Ind; + M = 1; + } + else if(Ind == 0) + M = 0; + else + M = -1; + + + if(Ind == 0) + AngularSpeed = 0.0f; + else if(Ind == 1) + AngularSpeed = pi / 360; + else if(Ind == 2) + AngularSpeed = pi / 180; + else if(Ind == 3) + AngularSpeed = pi / 90; + AngularSpeed *= M; + + for(int i=0; i<8;i++) + { + if(sides[i] >= ENTITY_LASER_SHORT && sides[i] <= ENTITY_LASER_LONG) + { + CLight *Lgt = new CLight(&GameServer()->m_World, Pos, pi / 4 * i, 32 * 3 + 32 * (sides[i] - ENTITY_LASER_SHORT) * 3, Layer, Number); + Lgt->m_AngularSpeed = AngularSpeed; + if(sides2[i] >= ENTITY_LASER_C_SLOW && sides2[i] <= ENTITY_LASER_C_FAST) + { + Lgt->m_Speed = 1 + (sides2[i] - ENTITY_LASER_C_SLOW) * 2; + Lgt->m_CurveLength = Lgt->m_Length; + } + else if(sides2[i] >= ENTITY_LASER_O_SLOW && sides2[i] <= ENTITY_LASER_O_FAST) + { + Lgt->m_Speed = 1 + (sides2[i] - ENTITY_LASER_O_SLOW) * 2; + Lgt->m_CurveLength = 0; + } + else + Lgt->m_CurveLength = Lgt->m_Length; + } + } + + } + else if(Index >= ENTITY_DRAGGER_WEAK && Index <= ENTITY_DRAGGER_STRONG) + { + CDraggerTeam(&GameServer()->m_World, Pos, Index - ENTITY_DRAGGER_WEAK + 1, false, Layer, Number); + } + else if(Index >= ENTITY_DRAGGER_WEAK_NW && Index <= ENTITY_DRAGGER_STRONG_NW) + { + CDraggerTeam(&GameServer()->m_World, Pos, Index - ENTITY_DRAGGER_WEAK_NW + 1, true, Layer, Number); + } + else if(Index == ENTITY_PLASMAE) + { + new CGun(&GameServer()->m_World, Pos, false, true, Layer, Number); + } + else if(Index == ENTITY_PLASMAF) + { + new CGun(&GameServer()->m_World, Pos, true, false, Layer, Number); + } + else if(Index == ENTITY_PLASMA) + { + new CGun(&GameServer()->m_World, Pos, true, true, Layer, Number); + } + else if(Index == ENTITY_PLASMAU) + { + new CGun(&GameServer()->m_World, Pos, false, false, Layer, Number); + } + + if(Type != -1) + { + //CPickup *pPickup = new CPickup(&GameServer()->m_World, Type, SubType); + CPickup *pPickup = new CPickup(&GameServer()->m_World, Type, SubType, Layer, Number); + pPickup->m_Pos = Pos; + return true; + } + + return false; +} + +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; +} + +void IGameController::ResetGame() +{ + GameServer()->m_World.m_ResetRequested = true; +} + +const char *IGameController::GetTeamName(int Team) +{/* + if(IsTeamplay()) + { + if(Team == TEAM_RED) + return "red team"; + else if(Team == TEAM_BLUE) + return "blue team"; + } + else + { + if(Team == 0) + return "game"; + }*/ + + if(Team == 0) + return "game"; + return "spectators"; +} + +//static bool IsSeparator(char c) { return c == ';' || c == ' ' || c == ',' || c == '\t'; } + +void IGameController::StartRound() +{ + ResetGame(); + + m_RoundStartTick = Server()->Tick(); + m_SuddenDeath = 0; + m_GameOverTick = -1; + GameServer()->m_World.m_Paused = false; + //m_aTeamscore[TEAM_RED] = 0; + //m_aTeamscore[TEAM_BLUE] = 0; + m_ForceBalanced = false; + Server()->DemoRecorder_HandleAutoStart(); + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "start round type='%s' teamplay='%d'", m_pGameType, m_GameFlags&GAMEFLAG_TEAMS); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); +} + +void IGameController::ChangeMap(const char *pToMap) +{ + /*str_copy(m_aMapWish, pToMap, sizeof(m_aMapWish)); + EndRound();*/ + str_copy(g_Config.m_SvMap, pToMap, sizeof(m_aMapWish)); +} + +/*void IGameController::CycleMap() +{ + if(m_aMapWish[0] != 0) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "rotating map to %s", m_aMapWish); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + str_copy(g_Config.m_SvMap, m_aMapWish, sizeof(g_Config.m_SvMap)); + m_aMapWish[0] = 0; + m_RoundCount = 0; + return; + } + if(!str_length(g_Config.m_SvMaprotation)) + return; + + if(m_RoundCount < g_Config.m_SvRoundsPerMap-1) + { + if(g_Config.m_SvRoundSwap) + GameServer()->SwapTeams(); + 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) + { + 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 + char aBuf[512] = {0}; + for(int i = 0; i < 511; i++) + { + aBuf[i] = pNextMap[i]; + if(IsSeparator(pNextMap[i]) || pNextMap[i] == 0) + { + aBuf[i] = 0; + 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); + str_copy(g_Config.m_SvMap, &aBuf[i], sizeof(g_Config.m_SvMap)); +}*/ + +void IGameController::PostReset() +{ + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i]) + { + GameServer()->m_apPlayers[i]->Respawn(); + //GameServer()->m_apPlayers[i]->m_Score = 0; + //GameServer()->m_apPlayers[i]->m_ScoreStartTick = Server()->Tick(); + //GameServer()->m_apPlayers[i]->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; + } + } +} + +/*void IGameController::OnPlayerInfoChange(class CPlayer *pP) +{ + const int aTeamColors[2] = {65387, 10223467}; + if(IsTeamplay()) + { + pP->m_TeeInfos.m_UseCustomColor = 1; + if(pP->GetTeam() >= TEAM_RED && pP->GetTeam() <= TEAM_BLUE) + { + pP->m_TeeInfos.m_ColorBody = aTeamColors[pP->GetTeam()]; + pP->m_TeeInfos.m_ColorFeet = aTeamColors[pP->GetTeam()]; + } + else + { + pP->m_TeeInfos.m_ColorBody = 12895054; + pP->m_TeeInfos.m_ColorFeet = 12895054; + } + } +}*/ + + +int IGameController::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + /*// do scoreing + if(!pKiller || Weapon == WEAPON_GAME) + return 0; + if(pKiller == pVictim->GetPlayer()) + pVictim->GetPlayer()->m_Score--; // suicide + else + { + if(IsTeamplay() && pVictim->GetPlayer()->GetTeam() == pKiller->GetTeam()) + pKiller->m_Score--; // teamkill + else + pKiller->m_Score++; // normal kill + } + if(Weapon == WEAPON_SELF) + pVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f;*/ + return 0; +} + +void IGameController::OnCharacterSpawn(class CCharacter *pChr) +{ + // default health + pChr->IncreaseHealth(10); + + // give default weapons + pChr->GiveWeapon(WEAPON_HAMMER, -1); + pChr->GiveWeapon(WEAPON_GUN, -1); +} + +void IGameController::DoWarmup(int Seconds) +{ + if(Seconds < 0) + m_Warmup = 0; + else + m_Warmup = Seconds*Server()->TickSpeed(); +} + +/*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; +}*/ + +bool IGameController::IsForceBalanced() +{ + /*if(m_ForceBalanced) + { + m_ForceBalanced = false; + return true; + } + else*/ + return false; +} + +bool IGameController::CanBeMovedOnBalance(int ClientID) +{ + return true; +} + +void IGameController::Tick() +{ + // do warmup + if(m_Warmup) + { + m_Warmup--; + if(!m_Warmup) + StartRound(); + } + + if(m_GameOverTick != -1) + { + // game over.. wait for restart + if(Server()->Tick() > m_GameOverTick+Server()->TickSpeed()*10) + { + //CycleMap(); + StartRound(); + m_RoundCount++; + } + } + + /* + // game is Paused + if(GameServer()->m_World.m_Paused) + ++m_RoundStartTick; + + // 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}; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + { + aT[GameServer()->m_apPlayers[i]->GetTeam()]++; + aPScore[i] = GameServer()->m_apPlayers[i]->m_Score*Server()->TickSpeed()*60.0f/ + (Server()->Tick()-GameServer()->m_apPlayers[i]->m_ScoreStartTick); + 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; + float PD = aTScore[M]; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(!GameServer()->m_apPlayers[i] || !CanBeMovedOnBalance(i)) + continue; + // remember the player who would cause lowest score-difference + if(GameServer()->m_apPlayers[i]->GetTeam() == M && (!pP || absolute((aTScore[M^1]+aPScore[i]) - (aTScore[M]-aPScore[i])) < PD)) + { + pP = GameServer()->m_apPlayers[i]; + 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; + } + */ + // check for inactive players + if(g_Config.m_SvInactiveKickTime > 0) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(i >= MAX_CLIENTS-1) + break; + + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !Server()->IsAuthed(i)) + { + if(Server()->Tick() > GameServer()->m_apPlayers[i]->m_LastActionTick+g_Config.m_SvInactiveKickTime*Server()->TickSpeed()*60) + { + switch(g_Config.m_SvInactiveKick) + { + case 0: + { + // move player to spectator + GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); + } + break; + case 1: + { + // move player to spectator if the reserved slots aren't filled yet, kick him otherwise + int Spectators = 0; + for(int j = 0; j < MAX_CLIENTS; ++j) + if(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS) + ++Spectators; + if(Spectators >= g_Config.m_SvSpectatorSlots) + Server()->Kick(i, "Kicked for inactivity"); + else + GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS); + } + break; + case 2: + { + // kick the player + Server()->Kick(i, "Kicked for inactivity"); + } + } + } + } + } + } + + //DoWincheck(); +} + + +/*bool IGameController::IsTeamplay() const +{ + return m_GameFlags&GAMEFLAG_TEAMS; +}*/ + +void IGameController::Snap(int SnappingClient) +{ + CNetObj_GameInfo *pGameInfoObj = (CNetObj_GameInfo *)Server()->SnapNewItem(NETOBJTYPE_GAMEINFO, 0, sizeof(CNetObj_GameInfo)); + if(!pGameInfoObj) + return; + + pGameInfoObj->m_GameFlags = m_GameFlags; + pGameInfoObj->m_GameStateFlags = 0; + if(m_GameOverTick != -1) + pGameInfoObj->m_GameStateFlags |= GAMESTATEFLAG_GAMEOVER; + if(m_SuddenDeath) + pGameInfoObj->m_GameStateFlags |= GAMESTATEFLAG_SUDDENDEATH; + if(GameServer()->m_World.m_Paused) + pGameInfoObj->m_GameStateFlags |= GAMESTATEFLAG_PAUSED; + pGameInfoObj->m_RoundStartTick = m_RoundStartTick; + pGameInfoObj->m_WarmupTimer = m_Warmup; + + //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; + + CCharacter *pChr; + CPlayer *pPlayer = SnappingClient > -1 ? GameServer()->m_apPlayers[SnappingClient] : 0; + CPlayer *pPlayer2; + + if(pPlayer && (pPlayer->m_TimerType == 0 || pPlayer->m_TimerType == 2)) + { + if((pPlayer->GetTeam() == -1 || pPlayer->m_Paused) + && pPlayer->m_SpectatorID != SPEC_FREEVIEW + && (pPlayer2 = GameServer()->m_apPlayers[pPlayer->m_SpectatorID])) + { + if((pChr = pPlayer2->GetCharacter())) + pGameInfoObj->m_RoundStartTick = (pChr->m_DDRaceState == DDRACE_STARTED)?pChr->m_StartTime:m_RoundStartTick; + } + else if((pChr = pPlayer->GetCharacter())) + { + pGameInfoObj->m_RoundStartTick = (pChr->m_DDRaceState == DDRACE_STARTED)?pChr->m_StartTime:m_RoundStartTick; + } + } +} + +// headbot +void IGameController::setTimer(float ms) +{ + m_RoundStartTick = (int)(Server()->Tick() + ((-ms/1000.f) * Server()->TickSpeed())); +} + +float IGameController::getTimer() +{ + return (Server()->Tick() - m_RoundStartTick) / (float)(Server()->TickSpeed()) * 1000.f; +} + +double IGameController::getTimerNoMS() +{ + return static_cast<double>(Server()->Tick() - m_RoundStartTick) / Server()->TickSpeed(); +} + +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++) + { + if(GameServer()->m_apPlayers[i] && i != NotThisID) + { + if(GameServer()->m_apPlayers[i]->GetTeam() >= TEAM_RED && GameServer()->m_apPlayers[i]->GetTeam() <= TEAM_BLUE) + aNumplayers[GameServer()->m_apPlayers[i]->GetTeam()]++; + } + } + + int Team = 0; + //if(IsTeamplay()) + //Team = aNumplayers[TEAM_RED] > aNumplayers[TEAM_BLUE] ? TEAM_BLUE : TEAM_RED; + + if(CanJoinTeam(Team, NotThisID)) + return Team; + return -1; +} + +bool IGameController::CanJoinTeam(int Team, int NotThisID) +{ + if(Team == TEAM_SPECTATORS || (GameServer()->m_apPlayers[NotThisID] && GameServer()->m_apPlayers[NotThisID]->GetTeam() != TEAM_SPECTATORS)) + return true; + + int aNumplayers[2] = {0,0}; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i] && i != NotThisID) + { + if(GameServer()->m_apPlayers[i]->GetTeam() >= TEAM_RED && GameServer()->m_apPlayers[i]->GetTeam() <= TEAM_BLUE) + aNumplayers[GameServer()->m_apPlayers[i]->GetTeam()]++; + } + } + + return (aNumplayers[0] + aNumplayers[1]) < Server()->MaxClients()-g_Config.m_SvSpectatorSlots; +} + +/*bool IGameController::CheckTeamBalance() +{ + if(!IsTeamplay() || !g_Config.m_SvTeambalanceTime) + return true; + + int aT[2] = {0, 0}; + for(int i = 0; i < MAX_CLIENTS; i++) + { + CPlayer *pP = GameServer()->m_apPlayers[i]; + if(pP && pP->GetTeam() != TEAM_SPECTATORS) + aT[pP->GetTeam()]++; + } + + char aBuf[256]; + if(absolute(aT[0]-aT[1]) >= 2) + { + str_format(aBuf, sizeof(aBuf), "Teams are NOT balanced (red=%d blue=%d)", aT[0], aT[1]); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + if(GameServer()->m_pController->m_UnbalancedTick == -1) + GameServer()->m_pController->m_UnbalancedTick = Server()->Tick(); + return false; + } + else + { + str_format(aBuf, sizeof(aBuf), "Teams are balanced (red=%d blue=%d)", aT[0], aT[1]); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); + GameServer()->m_pController->m_UnbalancedTick = -1; + return true; + } +} + +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) + { + // player wants to join team with less players + if ((aT[0] < aT[1] && JoinTeam == TEAM_RED) || (aT[0] > aT[1] && JoinTeam == TEAM_BLUE)) + return true; + else + return false; + } + else + return true; +} + +void IGameController::DoWincheck() +{ + if(m_GameOverTick == -1 && !m_Warmup && !GameServer()->m_World.m_ResetRequested) + { + if(IsTeamplay()) + { + // check score win condition + if((g_Config.m_SvScorelimit > 0 && (m_aTeamscore[TEAM_RED] >= g_Config.m_SvScorelimit || m_aTeamscore[TEAM_BLUE] >= g_Config.m_SvScorelimit)) || + (g_Config.m_SvTimelimit > 0 && (Server()->Tick()-m_RoundStartTick) >= g_Config.m_SvTimelimit*Server()->TickSpeed()*60)) + { + if(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE]) + EndRound(); + else + m_SuddenDeath = 1; + } + } + else + { + // gather some stats + int Topscore = 0; + int TopscoreCount = 0; + for(int i = 0; i < MAX_CLIENTS; i++) + { + if(GameServer()->m_apPlayers[i]) + { + if(GameServer()->m_apPlayers[i]->m_Score > Topscore) + { + Topscore = GameServer()->m_apPlayers[i]->m_Score; + TopscoreCount = 1; + } + else if(GameServer()->m_apPlayers[i]->m_Score == Topscore) + 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)) + { + if(TopscoreCount == 1) + EndRound(); + else + m_SuddenDeath = 1; + } + } + } +} + +*/ +int IGameController::ClampTeam(int Team) +{ + if(Team < 0) + return TEAM_SPECTATORS; + //if(IsTeamplay()) + //return Team&1; + return 0; +} diff --git a/src/game/server/gamecontroller.h b/src/game/server/gamecontroller.h new file mode 100644 index 0000000..fc0b52b --- /dev/null +++ b/src/game/server/gamecontroller.h @@ -0,0 +1,169 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMECONTROLLER_H +#define GAME_SERVER_GAMECONTROLLER_H + +#include <base/vmath.h> + +class CDoor; +#ifdef _MSC_VER +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include <stdint.h> +#endif + +/* + Class: Game Controller + Controls the main game logic. Keeping track of team and player score, + winning conditions and specific game logic. +*/ +class IGameController +{ + friend class CSaveTeam; // need acces to GameServer() and Server() + + 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; } + + struct CSpawnEval + { + CSpawnEval() + { + m_Got = false; + m_FriendlyTeam = -1; + m_Pos = vec2(100,100); + } + + vec2 m_Pos; + bool m_Got; + int m_FriendlyTeam; + float m_Score; + }; + + float EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos); + void EvaluateSpawnType(CSpawnEval *pEval, int Type); + bool EvaluateSpawn(class CPlayer *pP, vec2 *pPos); + + //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; + //bool IsGameOver() const { return m_GameOverTick != -1; } + + IGameController(class CGameContext *pGameServer); + virtual ~IGameController(); + + // virtual void DoWincheck(); + + 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); + virtual bool OnEntity(int Index, vec2 Pos, int Layer, int Flags, int Number = 0); + + /* + 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. + weapon - What weapon that killed it. Can be -1 for undefined + weapon when switching team or player suicides. + */ + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + + + //virtual void OnPlayerInfoChange(class CPlayer *pP); + + // + 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); + //bool CheckTeamBalance(); + //bool CanChangeTeam(CPlayer *pPplayer, int JoinTeam); + int ClampTeam(int Team); + + virtual void PostReset(); + + // DDRace + + float m_CurrentRecord; + + // headbot + void setTimer(float ms); + float getTimer(); + double getTimerNoMS(); // in seconds instead of ms. used for quad envelope stuff +}; + +#endif diff --git a/src/game/server/gamemodes/DDRace.cpp b/src/game/server/gamemodes/DDRace.cpp new file mode 100644 index 0000000..5db8356 --- /dev/null +++ b/src/game/server/gamemodes/DDRace.cpp @@ -0,0 +1,57 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +#include <engine/server.h> +#include <engine/shared/config.h> +#include <game/mapitems.h> +#include <game/server/entities/character.h> +#include <game/server/player.h> +#include <game/server/gamecontext.h> +#include "DDRace.h" +#include "gamemode.h" + +CGameControllerDDRace::CGameControllerDDRace(class CGameContext *pGameServer) : + IGameController(pGameServer), m_Teams(pGameServer) +{ + m_pGameType = g_Config.m_SvTestingCommands ? TEST_NAME : GAME_NAME; + + InitTeleporter(); +} + +CGameControllerDDRace::~CGameControllerDDRace() +{ + // Nothing to clean +} + +void CGameControllerDDRace::Tick() +{ + IGameController::Tick(); +} + +void CGameControllerDDRace::InitTeleporter() +{ + if (!GameServer()->Collision()->Layers()->TeleLayer()) + return; + int Width = GameServer()->Collision()->Layers()->TeleLayer()->m_Width; + int Height = GameServer()->Collision()->Layers()->TeleLayer()->m_Height; + + for (int i = 0; i < Width * Height; i++) + { + if (GameServer()->Collision()->TeleLayer()[i].m_Number > 0) + { + if (GameServer()->Collision()->TeleLayer()[i].m_Type + == TILE_TELEOUT) + { + m_TeleOuts[GameServer()->Collision()->TeleLayer()[i].m_Number + - 1].push_back( + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + } + else if (GameServer()->Collision()->TeleLayer()[i].m_Type + == TILE_TELECHECKOUT) + { + m_TeleCheckOuts[GameServer()->Collision()->TeleLayer()[i].m_Number + - 1].push_back( + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + } + } + } +} diff --git a/src/game/server/gamemodes/DDRace.h b/src/game/server/gamemodes/DDRace.h new file mode 100644 index 0000000..d31c3cc --- /dev/null +++ b/src/game/server/gamemodes/DDRace.h @@ -0,0 +1,26 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef DDRACE_H +#define DDRACE_H +#include <game/server/gamecontroller.h> +#include <game/server/teams.h> +#include <game/server/entities/door.h> + +#include <vector> +#include <map> + +class CGameControllerDDRace: public IGameController +{ +public: + + CGameControllerDDRace(class CGameContext *pGameServer); + ~CGameControllerDDRace(); + + CGameTeams m_Teams; + + std::map<int, std::vector<vec2> > m_TeleOuts; + std::map<int, std::vector<vec2> > m_TeleCheckOuts; + + void InitTeleporter(); + virtual void Tick(); +}; +#endif diff --git a/src/game/server/gamemodes/WarioWare.cpp b/src/game/server/gamemodes/WarioWare.cpp new file mode 100644 index 0000000..2f66f98 --- /dev/null +++ b/src/game/server/gamemodes/WarioWare.cpp @@ -0,0 +1,432 @@ +// WarioWare mod by Headshotnoby + +#include <engine/server.h> +#include <engine/shared/config.h> +#include <game/mapitems.h> +#include <game/server/entities/character.h> +#include <game/server/player.h> +#include <game/server/gamecontext.h> +#include "WarioWare.h" +#include "gamemode.h" + +// microgames +#include "microgames/kamikaze.h" +#include "microgames/math.h" +#include "microgames/hitenemy.h" +#include "microgames/dontmove.h" +#include "microgames/grenadejump.h" +#include "microgames/simon.h" +#include "microgames/gettoend.h" +#include "microgames/blockfight.h" +#include "microgames/train.h" +#include "microgames/superjump.h" +#include "microgames/parachute.h" +#include "microgames/flood.h" +#include "microgames/target.h" + + +CGameControllerWarioWare::CGameControllerWarioWare(class CGameContext *pGameServer) : + IGameController(pGameServer), m_Teams(pGameServer) +{ + m_pGameType = "TeeWare"; + InitTeleporter(); + + srand(time(0)); + m_last_microgame = m_microgame = -1; + + // add all microgames here + m_microgames.push_back(new MGKamikaze(pGameServer, this)); + m_microgames.push_back(new MGMath(pGameServer, this)); + m_microgames.push_back(new MGHitEnemy(pGameServer, this)); + m_microgames.push_back(new MGDontMove(pGameServer, this)); + m_microgames.push_back(new MGGrenadeJump(pGameServer, this)); + m_microgames.push_back(new MGSimon(pGameServer, this)); + m_microgames.push_back(new MGGetToEnd(pGameServer, this)); + m_microgames.push_back(new MGBlockFight(pGameServer, this)); + m_microgames.push_back(new MGTrain(pGameServer, this)); + m_microgames.push_back(new MGSuperJump(pGameServer, this)); + m_microgames.push_back(new MGParachute(pGameServer, this)); + m_microgames.push_back(new MGFlood(pGameServer, this)); + m_microgames.push_back(new MGTarget(pGameServer, this)); +} + +CGameControllerWarioWare::~CGameControllerWarioWare() +{ + while (not m_microgames.empty()) + { + delete m_microgames.back(); + m_microgames.pop_back(); + } + m_microgames.clear(); +} + +void CGameControllerWarioWare::StartRound() +{ + int online = 0; + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->m_apPlayers[i]) continue; + GameServer()->m_apPlayers[i]->m_Score = 0; + if (GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) continue; + + ++online; + } + + m_state = (online < 2) ? WW_WAITING : WW_INGAME; + m_warioState = WW_JINGLING; + m_round = 0; + m_speedUp = false; + finalWinner = -1; + + if (m_state == WW_WAITING) + { + GameServer()->SendBroadcast("Waiting for players...", -1); + int songs1[2] = {g_Config.m_WwSndWaiting1_Offset, g_Config.m_WwSndWaiting2_Offset}; + int songs2[2] = {g_Config.m_WwSndWaiting1_Length, g_Config.m_WwSndWaiting2_Length}; + int ind = rand() % 2; + setPlayerTimers(songs1[ind], songs2[ind]); + } + else + { + GameServer()->SendBroadcast("", -1); + setPlayerTimers(g_Config.m_WwSndJingle_Offset, g_Config.m_WwSndJingle_Length); + } +} + +void CGameControllerWarioWare::setPlayerTimers(float offset, float length) +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->m_apPlayers[i] or not GameServer()->m_apPlayers[i]->GetCharacter()) continue; + CCharacter *Char = GameServer()->m_apPlayers[i]->GetCharacter(); + + Char->setTimer(offset-60); + } + + setTimer(offset-60); + warioTimeLength = offset+length; +} + +void CGameControllerWarioWare::teleportPlayer(int client, int tele_id) +{ + CCharacter *Char = GameServer()->GetPlayerChar(client); + + if (not Char) return; + + int Num = m_TeleOuts[tele_id-1].size(); + if (!Num) + { + printf("not num???\n"); + return; + } + vec2 outPos = m_TeleOuts[tele_id-1][(!Num)?Num:rand() % Num]; + Char->Core()->m_Pos = outPos; + + Char->Core()->m_HookedPlayer = -1; + Char->Core()->m_HookState = HOOK_RETRACTED; + Char->Core()->m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + GameServer()->m_World.ReleaseHooked(client); + Char->Core()->m_Vel = vec2(0,0); + Char->Core()->m_HookPos = Char->Core()->m_Pos; +} + +void CGameControllerWarioWare::teleportPlayerToSpawn(int client) +{ + CPlayer *Player = GameServer()->m_apPlayers[client]; + CCharacter *Char = Player->GetCharacter(); + + vec2 SpawnPos; + if(CanSpawn(Player->GetTeam(), &SpawnPos)) + { + Char->Core()->m_HookedPlayer = -1; + Char->Core()->m_HookState = HOOK_RETRACTED; + Char->Core()->m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + Char->m_Pos = Char->Core()->m_Pos = Char->m_PrevPos = SpawnPos; + GameServer()->m_World.ReleaseHooked(client); + Char->Core()->m_Vel = vec2(0,0); + Char->Core()->m_HookPos = Char->Core()->m_Pos; + } +} + +void CGameControllerWarioWare::nextWarioState() +{ + char aBuf[128]; + + switch(m_warioState) + { + case WW_JINGLING: + rollMicroGame(); + m_warioState = WW_MICROGAME; + break; + + case WW_MICROGAME: // microgame finished + m_round++; + + if (not m_speedUp) + setPlayerTimers(g_Config.m_WwSndLose_Offset, g_Config.m_WwSndLose_Length); + else + setPlayerTimers(g_Config.m_WwSndLoseFast_Offset, g_Config.m_WwSndLoseFast_Length); + onMicroGameEnd(); + + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->m_apPlayers[i]) continue; + + if (GameServer()->m_apPlayers[i]->IsOut()) + GameServer()->m_apPlayers[i]->SetTeam(TEAM_SPECTATORS, false); + + GameServer()->SendBroadcast((g_Complete[i]) ? "You win!" : "You failed...", i); + + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (g_Complete[i]) + { + GameServer()->m_apPlayers[i]->m_Score += (m_round == g_Config.m_WwMaxRounds) ? 5 : 1; + if (Char) Char->setTimer((not m_speedUp) ? g_Config.m_WwSndWin_Offset : g_Config.m_WwSndWinFast_Offset); + } + } + m_warioState = WW_WINLOSE; + break; + + case WW_WINLOSE: // finished showing win/lose text + if (m_round+1 == g_Config.m_WwMaxRounds/2) // speedup + { + GameServer()->SendBroadcast("Speed up!", -1); + setPlayerTimers(g_Config.m_WwSndSpeedUp_Offset, g_Config.m_WwSndSpeedUp_Length); + m_warioState = WW_SPEEDUP; + m_speedUp = true; + break; + } + else if (m_round+1 == g_Config.m_WwMaxRounds) // boss + { + GameServer()->SendBroadcast(" Boss time!\nWorth 5 points", -1); + setPlayerTimers(g_Config.m_WwSndBoss_Offset, g_Config.m_WwSndBoss_Length); + m_warioState = WW_BOSSWARN; + m_speedUp = false; + break; + } + else if (m_round+1 > g_Config.m_WwMaxRounds) + { + doGameOver(); + break; + } + // go to jingle + case WW_SPEEDUP: + case WW_BOSSWARN: + str_format(aBuf, sizeof(aBuf), "Round %d", m_round+1); + GameServer()->SendBroadcast(aBuf, -1); // clear win/lose message + + if (not m_speedUp) + setPlayerTimers(g_Config.m_WwSndJingle_Offset, g_Config.m_WwSndJingle_Length); + else + setPlayerTimers(g_Config.m_WwSndJingleFast_Offset, g_Config.m_WwSndJingleFast_Length); + + m_warioState = WW_JINGLING; + break; + + case WW_GAMEOVER: + for (int i=0; i<MAX_CLIENTS; i++) + if (GameServer()->m_apPlayers[i]) GameServer()->m_apPlayers[i]->m_Score = 0; + + IGameController::StartRound(); + GameServer()->SendBroadcast("", -1); + break; + } +} + +void CGameControllerWarioWare::onMicroGameEnd() +{ + m_microgames[m_microgame]->End(); +} + +void CGameControllerWarioWare::rollMicroGame() +{ + if (g_Config.m_WwForceMicrogame < 0) + { + m_last_microgame = m_microgame; + + do m_microgame = rand() % m_microgames.size(); + while (m_microgame == m_last_microgame and m_microgames.size() > 1); + } + else + m_microgame = g_Config.m_WwForceMicrogame; + + int online = 0; + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->m_apPlayers[i] or GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) continue; + g_Complete[i] = false; + ++online; + } + + m_microgames[m_microgame]->Start(); + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "round %d: '%s'", m_round+1, m_microgames[m_microgame]->m_microgameName); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "TeeWare", aBuf); +} + +void CGameControllerWarioWare::doGameOver() +{ + int highest = 0; + CPlayer *winner; + + for (int i=0; i<MAX_CLIENTS; i++) + { + if (GameServer()->m_apPlayers[i] and GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + { + CPlayer *Player = GameServer()->m_apPlayers[i]; + if (Player->m_Score > highest) + { + finalWinner = i; + winner = Player; + highest = Player->m_Score; + } + } + } + + GameServer()->SendBroadcast("", -1); + char aBuf[128]; + setPlayerTimers(g_Config.m_WwSndFinalLose_Offset, g_Config.m_WwSndFinalLose_Length); + if (winner->GetCharacter()) winner->GetCharacter()->setTimer(g_Config.m_WwSndFinalWin_Offset); + + str_format(aBuf, sizeof(aBuf), "%s wins!", Server()->ClientName(winner->GetCID())); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + + m_warioState = WW_GAMEOVER; +} + +bool CGameControllerWarioWare::onChat(int client, const char *msg) +{ + if (m_state == WW_WAITING or m_warioState != WW_MICROGAME or not GameServer()->m_apPlayers[client]->GetCharacter()) return false; + + return m_microgames[m_microgame]->onChat(client, msg); +} + +void CGameControllerWarioWare::winMicroGame(int client) +{ + CCharacter *Char = GameServer()->GetPlayerChar(client); + if (g_Complete[client] or not Char) return; + + g_Complete[client] = true; + GameServer()->CreateSound(Char->m_Pos, SOUND_HIT); + GameServer()->CreateSoundGlobal(SOUND_CTF_CAPTURE, client); + GameServer()->CreateDeath(Char->m_Pos, client); +} + +int CGameControllerWarioWare::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + if (isInGame() and inMicroGame()) + { + return m_microgames[m_microgame]->OnCharacterDeath(pVictim, pKiller, Weapon); + } + + return 0; +} + +void CGameControllerWarioWare::OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) +{ + if (isInGame() and inMicroGame()) + m_microgames[m_microgame]->OnCharacterDamage(Victim, Killer, Dmg, Weapon); +} + +void CGameControllerWarioWare::Tick() +{ + IGameController::Tick(); + if (getTimer() < 500) return; + else if (getTimer() == 500) StartRound(); + + int online = 0; + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not Server()->ClientIngame(i) or GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) continue; + CPlayer *Player = GameServer()->m_apPlayers[i]; + CCharacter *Char = Player->GetCharacter(); + ++online; + if (not Char) continue; + + // locally (for each player) + switch(m_state) + { + case WW_WAITING: + { + float first_song = g_Config.m_WwSndWaiting1_Offset + g_Config.m_WwSndWaiting1_Length; + float offsettime = (Char->getTimer() < first_song+10) ? g_Config.m_WwSndWaiting1_Offset : g_Config.m_WwSndWaiting2_Offset; + float lengthtime = (Char->getTimer() < first_song+10) ? g_Config.m_WwSndWaiting1_Length : g_Config.m_WwSndWaiting2_Length; + + if (Char->getTimer() >= offsettime + lengthtime) + { + Char->setTimer(offsettime-5); + } + } + break; + } + } + + // globally (for everyone) + switch(m_state) + { + case WW_WAITING: + if (online < 2) + { + if (GameServer()->Server()->Tick() % 150 == 0) GameServer()->SendBroadcast("Waiting for players...", -1); + } + else + { + if (not m_Warmup) DoWarmup(5); + } + break; + + case WW_INGAME: + if (online < 2) + { + GameServer()->SendBroadcast("Waiting for players...", -1); + int songs1[2] = {g_Config.m_WwSndWaiting1_Offset, g_Config.m_WwSndWaiting2_Offset}; + int songs2[2] = {g_Config.m_WwSndWaiting1_Length, g_Config.m_WwSndWaiting2_Length}; + int ind = rand() % 2; + setPlayerTimers(songs1[ind], songs2[ind]); + + m_state = WW_WAITING; + IGameController::StartRound(); + StartRound(); + } + else + { + if (inMicroGame()) + { + m_microgames[m_microgame]->Tick(); + } + + if (getTimer() > warioTimeLength) + nextWarioState(); + } + break; + } +} + +void CGameControllerWarioWare::InitTeleporter() +{ + if (!GameServer()->Collision()->Layers()->TeleLayer()) + return; + int Width = GameServer()->Collision()->Layers()->TeleLayer()->m_Width; + int Height = GameServer()->Collision()->Layers()->TeleLayer()->m_Height; + + for (int i = 0; i < Width * Height; i++) + { + if (GameServer()->Collision()->TeleLayer()[i].m_Number > 0) + { + if (GameServer()->Collision()->TeleLayer()[i].m_Type + == TILE_TELEOUT) + { + m_TeleOuts[GameServer()->Collision()->TeleLayer()[i].m_Number + - 1].push_back( + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + } + else if (GameServer()->Collision()->TeleLayer()[i].m_Type + == TILE_TELECHECKOUT) + { + m_TeleCheckOuts[GameServer()->Collision()->TeleLayer()[i].m_Number + - 1].push_back( + vec2(i % Width * 32 + 16, i / Width * 32 + 16)); + } + } + } +} diff --git a/src/game/server/gamemodes/WarioWare.h b/src/game/server/gamemodes/WarioWare.h new file mode 100644 index 0000000..5ae1c15 --- /dev/null +++ b/src/game/server/gamemodes/WarioWare.h @@ -0,0 +1,82 @@ +// WarioWare mod by Headshotnoby + +#ifndef WARIOWARE_H +#define WARIOWARE_H +#include <game/server/gamecontroller.h> +#include <game/server/teams.h> + +#include <vector> +#include <map> + +class Microgame; +#include "microgame.h" + +enum // m_state +{ + WW_WAITING, + WW_INGAME +}; + +enum +{ + WW_GAMESTART, + WW_JINGLING, + WW_MICROGAME, + WW_WINLOSE, + WW_SPEEDUP, + WW_BOSSWARN, + WW_GAMEOVER +}; + +class CGameControllerWarioWare: public IGameController +{ +public: + + CGameControllerWarioWare(class CGameContext *pGameServer); + ~CGameControllerWarioWare(); + + CGameTeams m_Teams; + + std::map<int, std::vector<vec2> > m_TeleOuts; + std::map<int, std::vector<vec2> > m_TeleCheckOuts; + + void InitTeleporter(); + virtual void Tick(); + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + virtual void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon); + void StartRound(); + + // get values + int getState() { return m_state; } + int getWarioState() { return m_warioState; } + Microgame* getMicroGame() { return m_microgames[m_microgame]; } + int getRound() { return m_round; } + float getTimeLength() const { return warioTimeLength; } + bool isInGame() { return m_state == WW_INGAME; } + bool inMicroGame() { return m_warioState == WW_MICROGAME; } + + // warioware + void rollMicroGame(); + void winMicroGame(int client); + void onMicroGameEnd(); + void nextWarioState(); + void doGameOver(); + bool onChat(int client, const char *msg); + + // player control + void setPlayerTimers(float offset, float length); + void teleportPlayer(int client, int tele_id); + void teleportPlayerToSpawn(int client); + + // wins + bool g_Complete[MAX_CLIENTS]; // which players won a microgame + int finalWinner; // final winner + +private: + int m_state, m_warioState, m_last_microgame, m_microgame, m_round; + bool m_speedUp; + float warioTimeLength; + + std::vector<Microgame*> m_microgames; +}; +#endif diff --git a/src/game/server/gamemodes/gamemode.h b/src/game/server/gamemodes/gamemode.h new file mode 100644 index 0000000..536577f --- /dev/null +++ b/src/game/server/gamemodes/gamemode.h @@ -0,0 +1,8 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* This is used for all NONE Official Builds of DDRace, if you changed the source in anyway change this to something other than DDRace */ +#ifndef GAME_MODE_H +#define GAME_MODE_H + +#define GAME_NAME "DDraceNetwork" +#define TEST_NAME "TestDDraceNetwork" +#endif diff --git a/src/game/server/gamemodes/microgame.h b/src/game/server/gamemodes/microgame.h new file mode 100644 index 0000000..652e418 --- /dev/null +++ b/src/game/server/gamemodes/microgame.h @@ -0,0 +1,70 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_H +#define _MICROGAME_H + +#include "WarioWare.h" +#include <game/server/gamecontext.h> + +/* + The base microgame class + Make your own microgames by inheriting from this class. +*/ + +class CGameControllerWarioWare; + +class Microgame +{ + CGameContext *m_pGameServer; + IServer *m_pServer; + CGameControllerWarioWare* m_pController; + +public: + // (~)Microgame() + // The constructor and destructor. (duh) + // Set up the m_microgameName and m_boss variables on your microgame's constructor. + Microgame(CGameContext* pGameServer, CGameControllerWarioWare* pController) + { + m_pGameServer = pGameServer; + m_pServer = m_pGameServer->Server(); + m_pController = pController; + } + virtual ~Microgame() {}; + + // void Start() + // Called when this microgame starts. + // Set up objects, states etc. + virtual void Start() = 0; + + // void End() + // Called when this microgame ends. + // Clean up objects, states etc. + virtual void End() = 0; + + // void Tick() + // Your microgame's update function. + virtual void Tick() = 0; + + // int OnCharacterDeath(pVictim, pKiller, Weapon) + // Called when a player dies. + virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) = 0; + + // int OnCharacterDamage(Victim, Killer, Dmg, Weapon) + // Called when a player is hurt. + virtual void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) = 0; + + // bool onChat(client, msg) + // Called when a player sends a chat message. + // Returns a boolean: if false, the message is suppressed and not displayed. + virtual bool onChat(int client, const char *msg) = 0; + + const char *m_microgameName; // the microgame name + bool m_boss; // if this microgame is a boss + +protected: + CGameControllerWarioWare *Controller() const { return m_pController; } + CGameContext *GameServer() const { return m_pGameServer; } + IServer *Server() const { return m_pServer; } +}; + +#endif // _MICROGAME_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/blockfight.cpp b/src/game/server/gamemodes/microgames/blockfight.cpp new file mode 100644 index 0000000..55b9d4d --- /dev/null +++ b/src/game/server/gamemodes/microgames/blockfight.cpp @@ -0,0 +1,46 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "blockfight.h" + +MGBlockFight::MGBlockFight(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "blockfight"; + m_boss = false; +} + +void MGBlockFight::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->GetPlayerChar(i)) continue; + + Controller()->g_Complete[i] = true; + Controller()->teleportPlayer(i, 2); + } + + GameServer()->SendBroadcast("Fight and stay alive!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgFightStayAlive_Offset, g_Config.m_WwSndMgFightStayAlive_Length); +} + +void MGBlockFight::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGBlockFight::Tick() +{ + // nothing to tick +} + +int MGBlockFight::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + Controller()->g_Complete[pVictim->GetPlayer()->GetCID()] = false; + return 0; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/blockfight.h b/src/game/server/gamemodes/microgames/blockfight.h new file mode 100644 index 0000000..06198f7 --- /dev/null +++ b/src/game/server/gamemodes/microgames/blockfight.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_BLOCKFIGHT_H +#define _MICROGAME_BLOCKFIGHT_H + +#include "../microgame.h" + +/* + Fight and stay alive. +*/ + +class MGBlockFight : public Microgame +{ +public: + MGBlockFight(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGBlockFight() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_BLOCKFIGHT_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/dontmove.cpp b/src/game/server/gamemodes/microgames/dontmove.cpp new file mode 100644 index 0000000..84fb845 --- /dev/null +++ b/src/game/server/gamemodes/microgames/dontmove.cpp @@ -0,0 +1,47 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "dontmove.h" + +const char *modes[2] = {"Don't move!", "Don't stop moving!"}; + + +MGDontMove::MGDontMove(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "dontmove"; + m_boss = false; +} + +void MGDontMove::Start() +{ + m_Mode = rand() % 2; + GameServer()->SendBroadcast(modes[m_Mode], -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgDontMove_Offset, g_Config.m_WwSndMgDontMove_Length); + for (int i=0; i<MAX_CLIENTS; i++) Controller()->g_Complete[i] = true; +} + +void MGDontMove::End() +{ + // nothing to clean +} + +void MGDontMove::Tick() +{ + float timeLeft = Controller()->getTimeLength() - Controller()->getTimer(); + + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + if (timeLeft < 2500 and timeLeft > 200) + { + if ((not m_Mode and (Char->IsMoving() or Char->GetInput()->m_Hook&1 or Char->GetInput()->m_Fire&1)) or // don't move + (m_Mode and (not Char->IsMoving() and (Char->Core()->m_Vel.x < 1 and Char->Core()->m_Vel.x > -1) and (Char->Core()->m_Vel.y < 1 and Char->Core()->m_Vel.y > -1)))) // don't stop moving + { + Controller()->g_Complete[i] = false; + Char->Die(i, WEAPON_WORLD, timeLeft/1000.f); + } + } + } +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/dontmove.h b/src/game/server/gamemodes/microgames/dontmove.h new file mode 100644 index 0000000..991ddde --- /dev/null +++ b/src/game/server/gamemodes/microgames/dontmove.h @@ -0,0 +1,30 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_DONTMOVE_H +#define _MICROGAME_DONTMOVE_H + +#include "../microgame.h" + +/* + Don't move, or don't stop moving. + (Firing your weapon/hook also counts as moving!) +*/ + +class MGDontMove : public Microgame +{ +public: + MGDontMove(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGDontMove() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} + +private: + int m_Mode; // whether it's "don't move" or "don't stop moving" +}; + +#endif // _MICROGAME_DONTMOVE_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/flood.cpp b/src/game/server/gamemodes/microgames/flood.cpp new file mode 100644 index 0000000..e44d088 --- /dev/null +++ b/src/game/server/gamemodes/microgames/flood.cpp @@ -0,0 +1,45 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "flood.h" + +MGFlood::MGFlood(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "flood"; + m_boss = false; +} + +void MGFlood::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->GetPlayerChar(i)) continue; + + Controller()->g_Complete[i] = true; + Controller()->teleportPlayer(i, 5); + } + + GameServer()->SendBroadcast("Get on a platform!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgGetOnPlatform_Offset, g_Config.m_WwSndMgGetOnPlatform_Length); +} + +void MGFlood::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->GetPlayerChar(i)) continue; + + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGFlood::Tick() +{ + // nothing to tick +} + +int MGFlood::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + Controller()->g_Complete[pVictim->GetPlayer()->GetCID()] = false; + return 0; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/flood.h b/src/game/server/gamemodes/microgames/flood.h new file mode 100644 index 0000000..6a3de3a --- /dev/null +++ b/src/game/server/gamemodes/microgames/flood.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_FLOOD_H +#define _MICROGAME_FLOOD_H + +#include "../microgame.h" + +/* + Get on a platform and avoid the rising acid. +*/ + +class MGFlood : public Microgame +{ +public: + MGFlood(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGFlood() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_HITENEMY_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/gettoend.cpp b/src/game/server/gamemodes/microgames/gettoend.cpp new file mode 100644 index 0000000..49d167d --- /dev/null +++ b/src/game/server/gamemodes/microgames/gettoend.cpp @@ -0,0 +1,46 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "gettoend.h" + +MGGetToEnd::MGGetToEnd(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "gettoend"; + m_boss = false; +} + +void MGGetToEnd::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Controller()->teleportPlayer(i, 1); + Char->SetHookOthers(false); + Char->SetHitOthers(false); + Char->SetCollideOthers(false); + } + + GameServer()->SendBroadcast("Get to the end!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgGetToEnd_Offset, g_Config.m_WwSndMgGetToEnd_Length); +} + +void MGGetToEnd::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(true); + Char->SetHitOthers(true); + Char->SetCollideOthers(true); + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGGetToEnd::Tick() +{ + // nothing to tick +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/gettoend.h b/src/game/server/gamemodes/microgames/gettoend.h new file mode 100644 index 0000000..9c19549 --- /dev/null +++ b/src/game/server/gamemodes/microgames/gettoend.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_GETTOEND_H +#define _MICROGAME_GETTOEND_H + +#include "../microgame.h" + +/* + Avoid the obstacles and get to the goal. +*/ + +class MGGetToEnd : public Microgame +{ +public: + MGGetToEnd(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGGetToEnd() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_GETTOEND_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/grenadejump.cpp b/src/game/server/gamemodes/microgames/grenadejump.cpp new file mode 100644 index 0000000..2bf9dc1 --- /dev/null +++ b/src/game/server/gamemodes/microgames/grenadejump.cpp @@ -0,0 +1,50 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "grenadejump.h" + +MGGrenadeJump::MGGrenadeJump(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "grenadejump"; + m_boss = false; +} + +void MGGrenadeJump::Start() +{ + GameServer()->SendBroadcast("Grenade jump!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgGrenadeJump_Offset, g_Config.m_WwSndMgGrenadeJump_Length); + + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->GiveWeapon(WEAPON_GRENADE, -1); + Char->SetWeapon(WEAPON_GRENADE); + } +} + +void MGGrenadeJump::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetWeaponGot(WEAPON_GRENADE, false); + if (Char->GetActiveWeapon() == WEAPON_GRENADE and Char->GetLastWeapon() != WEAPON_GRENADE) + Char->SetWeapon(Char->GetLastWeapon()); + } +} + +void MGGrenadeJump::Tick() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + if (Char->Core()->m_Vel.y <= -18 and Char->GetActiveWeapon() == WEAPON_GRENADE) + Controller()->winMicroGame(i); + } +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/grenadejump.h b/src/game/server/gamemodes/microgames/grenadejump.h new file mode 100644 index 0000000..2f44580 --- /dev/null +++ b/src/game/server/gamemodes/microgames/grenadejump.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_GRENADEJUMP_H +#define _MICROGAME_GRENADEJUMP_H + +#include "../microgame.h" + +/* + Do a grenade jump to win. +*/ + +class MGGrenadeJump : public Microgame +{ +public: + MGGrenadeJump(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGGrenadeJump() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_GRENADEJUMP_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/hitenemy.cpp b/src/game/server/gamemodes/microgames/hitenemy.cpp new file mode 100644 index 0000000..5f0bd23 --- /dev/null +++ b/src/game/server/gamemodes/microgames/hitenemy.cpp @@ -0,0 +1,40 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "hitenemy.h" + +MGHitEnemy::MGHitEnemy(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "hitenemy"; + m_boss = false; +} + +void MGHitEnemy::Start() +{ + GameServer()->SendBroadcast("Hit an enemy!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgHitEnemy_Offset, g_Config.m_WwSndMgHitEnemy_Length); +} + +void MGHitEnemy::End() +{ + // nothing to clean +} + +void MGHitEnemy::Tick() +{ + // nothing to tick +} + +void MGHitEnemy::OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) +{ + float timeLeft = Controller()->getTimeLength() - Controller()->getTimer(); + + CCharacter *cVictim = GameServer()->GetPlayerChar(Victim); + if (cVictim) cVictim->Die(Killer, Weapon, timeLeft/1000.f); // respawn in secs +} + +int MGHitEnemy::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + Controller()->g_Complete[pKiller->GetCID()] = true; + return 0; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/hitenemy.h b/src/game/server/gamemodes/microgames/hitenemy.h new file mode 100644 index 0000000..86cab4f --- /dev/null +++ b/src/game/server/gamemodes/microgames/hitenemy.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_HITENEMY_H +#define _MICROGAME_HITENEMY_H + +#include "../microgame.h" + +/* + Hit a player with your hammer to win. +*/ + +class MGHitEnemy : public Microgame +{ +public: + MGHitEnemy(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGHitEnemy() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon); + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_HITENEMY_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/kamikaze.cpp b/src/game/server/gamemodes/microgames/kamikaze.cpp new file mode 100644 index 0000000..5f343af --- /dev/null +++ b/src/game/server/gamemodes/microgames/kamikaze.cpp @@ -0,0 +1,85 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "kamikaze.h" + +MGKamikaze::MGKamikaze(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "kamikaze"; + m_boss = false; +} + +void MGKamikaze::Start() +{ + // pick a random ingame player + do m_Victim = rand() % MAX_CLIENTS; + while (not GameServer()->m_apPlayers[m_Victim] or GameServer()->m_apPlayers[m_Victim]->GetTeam() == TEAM_SPECTATORS); + + // change their skin to a bomb + CPlayer *pPlayer = GameServer()->m_apPlayers[m_Victim]; + pPlayer->SetInfoLock(true); // prevent them from changing skins + str_copy(pPlayer->m_TeeInfos.m_SkinName, "bomb", sizeof(pPlayer->m_TeeInfos.m_SkinName)); + pPlayer->m_TeeInfos.m_UseCustomColor = 0; + + // count online players and send broadcast + int online = 0; + for (int i=0; i<MAX_CLIENTS; i++) + { + if (not GameServer()->m_apPlayers[i] or GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS) continue; + online++; + + if (i != m_Victim) + { + Controller()->g_Complete[i] = true; + GameServer()->SendBroadcast("Avoid the kamikaze!", i); + } + } + + char aBuf[128]; + m_Amount = (online <= 6) ? 1 : 2; // exploding 2 players with not enough people online is a challenge. + str_format(aBuf, sizeof(aBuf), "Explode %d %s!", m_Amount, (m_Amount > 1) ? "players" : "player"); + GameServer()->SendBroadcast(aBuf, m_Victim); + + // ddnet 9 gimmick, play map music + Controller()->setPlayerTimers(g_Config.m_WwSndMgKamikaze_Offset, g_Config.m_WwSndMgKamikaze_Length); +} + +void MGKamikaze::End() +{ + CPlayer *Player = GameServer()->m_apPlayers[m_Victim]; + if (Player) // revert skin + { + Player->SetInfoLock(false); + str_copy(Player->m_TeeInfos.m_SkinName, Player->original_skin, sizeof(Player->m_TeeInfos.m_SkinName)); + Player->m_TeeInfos.m_UseCustomColor = Player->original_color; + } +} + +void MGKamikaze::Tick() +{ + float timeLeft = Controller()->getTimeLength() - Controller()->getTimer(); // time in ms + + CCharacter *Char = GameServer()->GetPlayerChar(m_Victim); + if (timeLeft < 600 and timeLeft > 200 and Char) // explode + { + int hits = GameServer()->CreateExplosion(Char->m_Pos, m_Victim, WEAPON_WORLD, false, -1, -1)-1; + GameServer()->CreateSound(Char->m_Pos, SOUND_GRENADE_EXPLODE); + + if (hits >= m_Amount) Controller()->g_Complete[m_Victim] = true; // win + } +} + +void MGKamikaze::OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) +{ + if (Weapon != WEAPON_WORLD) return; + float timeLeft = Controller()->getTimeLength() - Controller()->getTimer(); + + CCharacter *cVictim = GameServer()->GetPlayerChar(Victim); + if (cVictim) cVictim->Die(Killer, Weapon, timeLeft/1000.f); // respawn in secs +} + +int MGKamikaze::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + Controller()->g_Complete[pVictim->GetPlayer()->GetCID()] = false; + return 0; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/kamikaze.h b/src/game/server/gamemodes/microgames/kamikaze.h new file mode 100644 index 0000000..0fa4509 --- /dev/null +++ b/src/game/server/gamemodes/microgames/kamikaze.h @@ -0,0 +1,32 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_KAMIKAZE_H +#define _MICROGAME_KAMIKAZE_H + +#include "../microgame.h" + +/* + Explosive player microgame. + The kamikaze must blow up 1 or 2 players depending on online players. + The rest of the players must avoid the kamikaze. +*/ + +class MGKamikaze : public Microgame +{ +public: + MGKamikaze(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGKamikaze() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon); + bool onChat(int client, const char *msg) {return false;} + +private: + int m_Victim; // randomly selected kamikaze + int m_Amount; // kamikaze must blow up this amount of players +}; + +#endif // _MICROGAME_KAMIKAZE_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/math.cpp b/src/game/server/gamemodes/microgames/math.cpp new file mode 100644 index 0000000..933f198 --- /dev/null +++ b/src/game/server/gamemodes/microgames/math.cpp @@ -0,0 +1,71 @@ +#include <engine/shared/config.h> +#include "math.h" // not the C math lib. + +MGMath::MGMath(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "math"; + m_boss = false; +} + +void MGMath::Start() +{ + char operations[3] = {'+', '-', '*'}; + char aBuf[128]; + m_winFirst = false; + m_operation = operations[rand() % 3]; + + if (m_operation == '*') // easy numbers + { + m_num1 = 2 + (rand() % 9); + m_num2 = 1 + (rand() % 10); + } + else if (m_operation == '-') + { + m_num1 = rand() % 20; + do m_num2 = 1 + (rand() % 10); + while (m_num2 > m_num1); + } + else + { + m_num1 = rand() % 20; + m_num2 = 1 + (rand() % 10); + } + + str_format(aBuf, sizeof(aBuf), "Type the answer!\n %d%c%d = ?", m_num1, m_operation, m_num2); + GameServer()->SendBroadcast(aBuf, -1); + + int snd1[2] = {g_Config.m_WwSndMgAnswer1_Offset, g_Config.m_WwSndMgAnswer2_Offset}; + int snd2[2] = {g_Config.m_WwSndMgAnswer1_Length, g_Config.m_WwSndMgAnswer2_Length}; + int ind = rand() % 2; + Controller()->setPlayerTimers(snd1[ind], snd2[ind]); +} + +void MGMath::End() +{ + // nothing to clean +} + +void MGMath::Tick() +{ + // nothing to tick +} + +bool MGMath::onChat(int client, const char *msg) +{ + int pAnswer = atoi(msg); + if ((m_operation == '+' and m_num1+m_num2 == pAnswer) or + (m_operation == '-' and m_num1-m_num2 == pAnswer) or + (m_operation == '*' and m_num1*m_num2 == pAnswer)) + { + if (not m_winFirst) + { + m_winFirst = true; + char aBuf[128]; + str_format(aBuf, sizeof(aBuf), "%s answered first!", GameServer()->Server()->ClientName(client)); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + Controller()->winMicroGame(client); + return true; + } + return false; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/math.h b/src/game/server/gamemodes/microgames/math.h new file mode 100644 index 0000000..e8d659b --- /dev/null +++ b/src/game/server/gamemodes/microgames/math.h @@ -0,0 +1,31 @@ +#ifndef _MICROGAME_MATH_H +#define _MICROGAME_MATH_H + +#include "../microgame.h" + +/* + Math microgame. + Addition, substraction, multiplication. + 2+2=4-1=3 Quick maths. +*/ + +class MGMath : public Microgame +{ +public: + MGMath(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGMath() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg); + +private: + char m_operation; // one of three arithmetic operations. + int m_num1, m_num2; // two numbers. + bool m_winFirst; // player answered first +}; + +#endif // _MICROGAME_MATH_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/parachute.cpp b/src/game/server/gamemodes/microgames/parachute.cpp new file mode 100644 index 0000000..be1fbaf --- /dev/null +++ b/src/game/server/gamemodes/microgames/parachute.cpp @@ -0,0 +1,47 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "parachute.h" + +MGParachute::MGParachute(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "parachute"; + m_boss = false; +} + +void MGParachute::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(false); + Char->SetHitOthers(false); + Char->SetCollideOthers(false); + Char->Core()->m_Jumped = 0; // reset double jump just in case... + Controller()->teleportPlayer(i, 4); + } + + GameServer()->SendBroadcast("Get on the platform!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgGetOnPlatform2_Offset, g_Config.m_WwSndMgGetOnPlatform2_Length); +} + +void MGParachute::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(true); + Char->SetHitOthers(true); + Char->SetCollideOthers(true); + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGParachute::Tick() +{ + // nothing to tick +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/parachute.h b/src/game/server/gamemodes/microgames/parachute.h new file mode 100644 index 0000000..b2cc6ef --- /dev/null +++ b/src/game/server/gamemodes/microgames/parachute.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_PARACHUTE_H +#define _MICROGAME_PARACHUTE_H + +#include "../microgame.h" + +/* + Land on the platform to win. +*/ + +class MGParachute : public Microgame +{ +public: + MGParachute(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGParachute() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_PARACHUTE_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/simon.cpp b/src/game/server/gamemodes/microgames/simon.cpp new file mode 100644 index 0000000..092bb74 --- /dev/null +++ b/src/game/server/gamemodes/microgames/simon.cpp @@ -0,0 +1,65 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "simon.h" + +const char *simonNames[] = {"Simon", "Someone"}; +const char *simonModes[] = {"Jump", "Look up", "Look down"}; +const float PI = 3.141592653589793f; + +MGSimon::MGSimon(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "simon"; + m_boss = false; +} + +void MGSimon::Start() +{ + m_Someone = rand() % 2; // simon/someone + m_SimonMode = rand() % 3; // simons[] array + + for (int i=0; i<MAX_CLIENTS; i++) + Controller()->g_Complete[i] = (m_Someone) ? true : false; + + char aBuf[96]; + str_format(aBuf, sizeof(aBuf), "%s says: %s!", simonNames[m_Someone], simonModes[m_SimonMode]); + GameServer()->SendBroadcast(aBuf, -1); + + Controller()->setPlayerTimers(g_Config.m_WwSndMgSimonSays_Offset, g_Config.m_WwSndMgSimonSays_Length); +} + +void MGSimon::End() +{ + // nothing to clean +} + +void MGSimon::Tick() +{ + float timeLeft = Controller()->getTimeLength() - Controller()->getTimer(); + + if (timeLeft < 2950 and timeLeft > 200) + { + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + CNetObj_PlayerInput* input = Char->GetInput(); + float angle = -atan2(input->m_TargetY, input->m_TargetX) / PI * 180; + + if ((m_SimonMode == 0 and input->m_Jump&1) or + (m_SimonMode == 1 and angle >= 75 and angle < 105) or // up + (m_SimonMode == 2 and angle <= -75 and angle > -105)) // down + { + if (m_Someone) // simon didn't say it + { + Controller()->g_Complete[i] = false; + Char->Die(i, WEAPON_WORLD, timeLeft/1000.f); + GameServer()->SendChatTarget(i, "Simon didn't say it!..."); + } + else + Controller()->winMicroGame(i); + } + } + } +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/simon.h b/src/game/server/gamemodes/microgames/simon.h new file mode 100644 index 0000000..429c249 --- /dev/null +++ b/src/game/server/gamemodes/microgames/simon.h @@ -0,0 +1,31 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_SIMON_H +#define _MICROGAME_SIMON_H + +#include "../microgame.h" + +/* + If Simon says it, do it. + If someone says it, don't. +*/ + +class MGSimon : public Microgame +{ +public: + MGSimon(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGSimon() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} + +private: + int m_Someone; // if "Someone says" then don't do it + int m_SimonMode; // look up, look down, jump +}; + +#endif // _MICROGAME_SIMON_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/superjump.cpp b/src/game/server/gamemodes/microgames/superjump.cpp new file mode 100644 index 0000000..a8e5614 --- /dev/null +++ b/src/game/server/gamemodes/microgames/superjump.cpp @@ -0,0 +1,45 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "superjump.h" + +MGSuperJump::MGSuperJump(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "superjump"; + m_boss = false; +} + +void MGSuperJump::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(false); + Char->SetCollideOthers(false); + Char->SetSuperJump(true); + } + + GameServer()->SendBroadcast("Touch the sky!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgTouchSky_Offset, g_Config.m_WwSndMgTouchSky_Length); +} + +void MGSuperJump::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(true); + Char->SetCollideOthers(true); + Char->SetSuperJump(false); + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGSuperJump::Tick() +{ + // nothing to tick +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/superjump.h b/src/game/server/gamemodes/microgames/superjump.h new file mode 100644 index 0000000..aaef671 --- /dev/null +++ b/src/game/server/gamemodes/microgames/superjump.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_SUPERJUMP_H +#define _MICROGAME_SUPERJUMP_H + +#include "../microgame.h" + +/* + Touch the sky with infinite jump. +*/ + +class MGSuperJump : public Microgame +{ +public: + MGSuperJump(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGSuperJump() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_SUPERJUMP_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/target.cpp b/src/game/server/gamemodes/microgames/target.cpp new file mode 100644 index 0000000..9a1100a --- /dev/null +++ b/src/game/server/gamemodes/microgames/target.cpp @@ -0,0 +1,62 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "target.h" + +MGTarget::MGTarget(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "target"; + m_boss = false; +} + +void MGTarget::Start() +{ + for (int i=0; i<MAX_CLIENTS-1; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(false); + Char->SetHitOthers(false); + Char->SetCollideOthers(false); + + Char->GiveWeapon(WEAPON_RIFLE, -1); + Char->SetWeapon(WEAPON_RIFLE); + + Controller()->teleportPlayer(i, 6); + } + + // teleport the bot player (the target) + int bot_tele = 7; + int Num = Controller()->m_TeleOuts[bot_tele-1].size(); + Server()->SetClientName(MAX_CLIENTS-1, "HIT ME"); + GameServer()->m_apPlayers[MAX_CLIENTS-1]->SetTeam(0, false); // move to game + GameServer()->m_apPlayers[MAX_CLIENTS-1]->ForceSpawn(Controller()->m_TeleOuts[bot_tele-1][(!Num)?Num:rand() % Num]); + + GameServer()->SendBroadcast("Hit the target!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgHitTheTarget_Offset, g_Config.m_WwSndMgHitTheTarget_Length); +} + +void MGTarget::End() +{ + for (int i=0; i<MAX_CLIENTS-1; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetWeaponGot(WEAPON_RIFLE, false); + if (Char->GetActiveWeapon() == WEAPON_RIFLE and Char->GetLastWeapon() != WEAPON_RIFLE) + Char->SetWeapon(Char->GetLastWeapon()); + + Controller()->teleportPlayerToSpawn(i); + } + + // move bot back to spec + GameServer()->m_apPlayers[MAX_CLIENTS-1]->SetTeam(TEAM_SPECTATORS, false); + Server()->SetClientName(MAX_CLIENTS-1, "bot"); +} + +void MGTarget::Tick() +{ + // nothing to tick +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/target.h b/src/game/server/gamemodes/microgames/target.h new file mode 100644 index 0000000..b37570e --- /dev/null +++ b/src/game/server/gamemodes/microgames/target.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_TARGET_H +#define _MICROGAME_TARGET_H + +#include "../microgame.h" + +/* + Hit the target with your laser to win. +*/ + +class MGTarget : public Microgame +{ +public: + MGTarget(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGTarget() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) {return 0;} + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_TARGET_H \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/train.cpp b/src/game/server/gamemodes/microgames/train.cpp new file mode 100644 index 0000000..9b992b4 --- /dev/null +++ b/src/game/server/gamemodes/microgames/train.cpp @@ -0,0 +1,52 @@ +// WarioWare mod by Headshotnoby + +#include <engine/shared/config.h> +#include "train.h" + +MGTrain::MGTrain(CGameContext* pGameServer, CGameControllerWarioWare* pController) : Microgame(pGameServer, pController) +{ + m_microgameName = "train"; + m_boss = false; +} + +void MGTrain::Start() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(false); + Char->SetHitOthers(false); + Char->SetCollideOthers(false); + Controller()->teleportPlayer(i, 3); + } + + GameServer()->SendBroadcast("Avoid the train!", -1); + Controller()->setPlayerTimers(g_Config.m_WwSndMgAvoidTrain_Offset, g_Config.m_WwSndMgAvoidTrain_Length); +} + +void MGTrain::End() +{ + for (int i=0; i<MAX_CLIENTS; i++) + { + CCharacter *Char = GameServer()->GetPlayerChar(i); + if (not Char) continue; + + Char->SetHookOthers(true); + Char->SetHitOthers(true); + Char->SetCollideOthers(true); + Controller()->teleportPlayerToSpawn(i); + } +} + +void MGTrain::Tick() +{ + // nothing to tick +} + +int MGTrain::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) +{ + Controller()->g_Complete[pVictim->GetPlayer()->GetCID()] = false; + return 0; +} \ No newline at end of file diff --git a/src/game/server/gamemodes/microgames/train.h b/src/game/server/gamemodes/microgames/train.h new file mode 100644 index 0000000..0a3c0eb --- /dev/null +++ b/src/game/server/gamemodes/microgames/train.h @@ -0,0 +1,26 @@ +// WarioWare mod by Headshotnoby + +#ifndef _MICROGAME_TRAIN_H +#define _MICROGAME_TRAIN_H + +#include "../microgame.h" + +/* + Avoid the train. +*/ + +class MGTrain : public Microgame +{ +public: + MGTrain(CGameContext* pGameServer, CGameControllerWarioWare* pController); + ~MGTrain() {} + + void Start(); + void End(); + void Tick(); + int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); + void OnCharacterDamage(int Victim, int Killer, int Dmg, int Weapon) {} + bool onChat(int client, const char *msg) {return false;} +}; + +#endif // _MICROGAME_HITENEMY_H \ No newline at end of file diff --git a/src/game/server/gameworld.cpp b/src/game/server/gameworld.cpp new file mode 100644 index 0000000..07f63f7 --- /dev/null +++ b/src/game/server/gameworld.cpp @@ -0,0 +1,410 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ + +#include "gameworld.h" +#include "entity.h" +#include "gamecontext.h" +#include <algorithm> +#include <utility> +#include <engine/shared/config.h> + +////////////////////////////////////////////////// +// game world +////////////////////////////////////////////////// +CGameWorld::CGameWorld() +{ + m_pGameServer = 0x0; + m_pServer = 0x0; + + m_Paused = false; + m_ResetRequested = false; + for(int i = 0; i < NUM_ENTTYPES; i++) + m_apFirstEntityTypes[i] = 0; +} + +CGameWorld::~CGameWorld() +{ + // delete all entities + for(int i = 0; i < NUM_ENTTYPES; i++) + while(m_apFirstEntityTypes[i]) + delete m_apFirstEntityTypes[i]; +} + +void CGameWorld::SetGameServer(CGameContext *pGameServer) +{ + m_pGameServer = pGameServer; + m_pServer = m_pGameServer->Server(); +} + +CEntity *CGameWorld::FindFirst(int Type) +{ + return Type < 0 || Type >= NUM_ENTTYPES ? 0 : m_apFirstEntityTypes[Type]; +} + +int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type) +{ + if(Type < 0 || Type >= NUM_ENTTYPES) + return 0; + + int Num = 0; + for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) + { + if(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius) + { + if(ppEnts) + ppEnts[Num] = pEnt; + Num++; + if(Num == Max) + break; + } + } + + return Num; +} + +void CGameWorld::InsertEntity(CEntity *pEnt) +{ +#ifdef CONF_DEBUG + for(CEntity *pCur = m_apFirstEntityTypes[pEnt->m_ObjType]; pCur; pCur = pCur->m_pNextTypeEntity) + dbg_assert(pCur != pEnt, "err"); +#endif + + // insert it + if(m_apFirstEntityTypes[pEnt->m_ObjType]) + m_apFirstEntityTypes[pEnt->m_ObjType]->m_pPrevTypeEntity = pEnt; + pEnt->m_pNextTypeEntity = m_apFirstEntityTypes[pEnt->m_ObjType]; + pEnt->m_pPrevTypeEntity = 0x0; + m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt; +} + +void CGameWorld::DestroyEntity(CEntity *pEnt) +{ + pEnt->m_MarkedForDestroy = true; +} + +void CGameWorld::RemoveEntity(CEntity *pEnt) +{ + // not in the list + if(!pEnt->m_pNextTypeEntity && !pEnt->m_pPrevTypeEntity && m_apFirstEntityTypes[pEnt->m_ObjType] != pEnt) + return; + + // remove + if(pEnt->m_pPrevTypeEntity) + pEnt->m_pPrevTypeEntity->m_pNextTypeEntity = pEnt->m_pNextTypeEntity; + else + m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt->m_pNextTypeEntity; + if(pEnt->m_pNextTypeEntity) + pEnt->m_pNextTypeEntity->m_pPrevTypeEntity = pEnt->m_pPrevTypeEntity; + + // keep list traversing valid + if(m_pNextTraverseEntity == pEnt) + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + + pEnt->m_pNextTypeEntity = 0; + pEnt->m_pPrevTypeEntity = 0; +} + +// +void CGameWorld::Snap(int SnappingClient) +{ + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Snap(SnappingClient); + pEnt = m_pNextTraverseEntity; + } +} + +void CGameWorld::Reset() +{ + // reset all entities + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Reset(); + pEnt = m_pNextTraverseEntity; + } + RemoveEntities(); + + GameServer()->m_pController->PostReset(); + RemoveEntities(); + + m_ResetRequested = false; +} + +void CGameWorld::RemoveEntities() +{ + // destroy objects marked for destruction + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + if(pEnt->m_MarkedForDestroy) + { + RemoveEntity(pEnt); + pEnt->Destroy(); + } + pEnt = m_pNextTraverseEntity; + } +} + +bool distCompare(std::pair<float,int> a, std::pair<float,int> b) +{ + return (a.first < b.first); +} + +void CGameWorld::UpdatePlayerMaps() +{ + if (Server()->Tick() % g_Config.m_SvMapUpdateRate != 0) return; + + std::pair<float,int> dist[MAX_CLIENTS]; + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (!Server()->ClientIngame(i)) continue; + int* map = Server()->GetIdMap(i); + + // compute distances + for (int j = 0; j < MAX_CLIENTS; j++) + { + dist[j].second = j; + if (!Server()->ClientIngame(j) || !GameServer()->m_apPlayers[j]) + { + dist[j].first = 1e10; + continue; + } + CCharacter* ch = GameServer()->m_apPlayers[j]->GetCharacter(); + if (!ch) + { + dist[j].first = 1e9; + continue; + } + // copypasted chunk from character.cpp Snap() follows + CCharacter* SnapChar = GameServer()->GetPlayerChar(i); + if(SnapChar && !SnapChar->m_Super && + !GameServer()->m_apPlayers[i]->m_Paused && GameServer()->m_apPlayers[i]->GetTeam() != -1 && + !ch->CanCollide(i) && + (!GameServer()->m_apPlayers[i] || + GameServer()->m_apPlayers[i]->m_ClientVersion == VERSION_VANILLA || + (GameServer()->m_apPlayers[i]->m_ClientVersion >= VERSION_DDRACE && + !GameServer()->m_apPlayers[i]->m_ShowOthers + ) + ) + ) + dist[j].first = 1e8; + else + dist[j].first = 0; + + dist[j].first += distance(GameServer()->m_apPlayers[i]->m_ViewPos, GameServer()->m_apPlayers[j]->GetCharacter()->m_Pos); + } + + // always send the player himself + dist[i].first = 0; + + // compute reverse map + int rMap[MAX_CLIENTS]; + for (int j = 0; j < MAX_CLIENTS; j++) + { + rMap[j] = -1; + } + for (int j = 0; j < VANILLA_MAX_CLIENTS; j++) + { + if (map[j] == -1) continue; + if (dist[map[j]].first > 5e9) map[j] = -1; + else rMap[map[j]] = j; + } + + std::nth_element(&dist[0], &dist[VANILLA_MAX_CLIENTS - 1], &dist[MAX_CLIENTS], distCompare); + + int mapc = 0; + int demand = 0; + for (int j = 0; j < VANILLA_MAX_CLIENTS - 1; j++) + { + int k = dist[j].second; + if (rMap[k] != -1 || dist[j].first > 5e9) continue; + while (mapc < VANILLA_MAX_CLIENTS && map[mapc] != -1) mapc++; + if (mapc < VANILLA_MAX_CLIENTS - 1) + map[mapc] = k; + else + demand++; + } + for (int j = MAX_CLIENTS - 1; j > VANILLA_MAX_CLIENTS - 2; j--) + { + int k = dist[j].second; + if (rMap[k] != -1 && demand-- > 0) + map[rMap[k]] = -1; + } + map[VANILLA_MAX_CLIENTS - 1] = -1; // player with empty name to say chat msgs + } +} + +void CGameWorld::Tick() +{ + if(m_ResetRequested) + Reset(); + + if(!m_Paused) + { + if(GameServer()->m_pController->IsForceBalanced()) + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, "Teams have been balanced"); + // update all objects + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->Tick(); + pEnt = m_pNextTraverseEntity; + } + + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->TickDefered(); + pEnt = m_pNextTraverseEntity; + } + } + else + { + // update all objects + for(int i = 0; i < NUM_ENTTYPES; i++) + for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) + { + m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; + pEnt->TickPaused(); + pEnt = m_pNextTraverseEntity; + } + } + + RemoveEntities(); + + UpdatePlayerMaps(); +} + +// TODO: should be more general +//CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CEntity *pNotThis) +CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CCharacter *pNotThis, int CollideWith, class CCharacter *pThisOnly) +{ + // Find other players + float ClosestLen = distance(Pos0, Pos1) * 100.0f; + CCharacter *pClosest = 0; + + CCharacter *p = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); + for(; p; p = (CCharacter *)p->TypeNext()) + { + if(p == pNotThis) + continue; + + if(CollideWith != -1 && !p->CanCollide(CollideWith)) + 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) + { + Len = distance(Pos0, IntersectPos); + if(Len < ClosestLen) + { + NewPos = IntersectPos; + ClosestLen = Len; + pClosest = p; + } + } + } + + return pClosest; +} + +CCharacter *CGameWorld::IntersectBotCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos) +{ + // Find other players + float ClosestLen = distance(Pos0, Pos1) * 100.0f; + CCharacter *pClosest = 0; + + CCharacter *p = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); + for(; p; p = (CCharacter *)p->TypeNext()) + { + if (p->GetPlayer()->GetCID() < MAX_CLIENTS-1) + 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) + { + Len = distance(Pos0, IntersectPos); + if(Len < ClosestLen) + { + NewPos = IntersectPos; + ClosestLen = Len; + pClosest = p; + } + } + } + + return pClosest; +} + + +CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotThis) +{ + // 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) + { + if(Len < ClosestRange) + { + ClosestRange = Len; + pClosest = p; + } + } + } + + return pClosest; +} + +std::list<class CCharacter *> CGameWorld::IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, class CEntity *pNotThis) +{ + std::list< CCharacter * > listOfChars; + + CCharacter *pChr = (CCharacter *)FindFirst(CGameWorld::ENTTYPE_CHARACTER); + for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) + { + if(pChr == pNotThis) + continue; + + vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, pChr->m_Pos); + float Len = distance(pChr->m_Pos, IntersectPos); + if(Len < pChr->m_ProximityRadius+Radius) + { + pChr->m_Intersection = IntersectPos; + listOfChars.push_back(pChr); + } + } + return listOfChars; +} + +void CGameWorld::ReleaseHooked(int ClientID) +{ + CCharacter *pChr = (CCharacter *)CGameWorld::FindFirst(CGameWorld::ENTTYPE_CHARACTER); + for(; pChr; pChr = (CCharacter *)pChr->TypeNext()) + { + CCharacterCore* Core = pChr->Core(); + if(Core->m_HookedPlayer == ClientID && !pChr->m_Super) + { + Core->m_HookedPlayer = -1; + Core->m_HookState = HOOK_RETRACTED; + Core->m_TriggeredEvents |= COREEVENT_HOOK_RETRACT; + Core->m_HookState = HOOK_RETRACTED; + } + } +} diff --git a/src/game/server/gameworld.h b/src/game/server/gameworld.h new file mode 100644 index 0000000..9d90005 --- /dev/null +++ b/src/game/server/gameworld.h @@ -0,0 +1,175 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_GAMEWORLD_H +#define GAME_SERVER_GAMEWORLD_H + +#include <game/gamecore.h> + +#include <list> + +class CEntity; +class CCharacter; + +/* + Class: Game World + Tracks all entities in the game. Propagates tick and + snap calls to all entities. +*/ +class CGameWorld +{ +public: + enum + { + ENTTYPE_PROJECTILE = 0, + ENTTYPE_LASER, + ENTTYPE_PICKUP, + ENTTYPE_FLAG, + ENTTYPE_CHARACTER, + NUM_ENTTYPES + }; + +private: + void Reset(); + void RemoveEntities(); + + CEntity *m_pNextTraverseEntity; + CEntity *m_apFirstEntityTypes[NUM_ENTTYPES]; + + class CGameContext *m_pGameServer; + class IServer *m_pServer; + + void UpdatePlayerMaps(); + +public: + class CGameContext *GameServer() { return m_pGameServer; } + class IServer *Server() { return m_pServer; } + + 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. + ents - Pointer to a list that should be filled with the pointers + 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: InterserctCharacters + Finds the CCharacters that intersects the line. // made for types lasers=1 and doors=0 + + 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); + class CCharacter *IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CCharacter *pNotThis = 0, int CollideWith = -1, class CCharacter *pThisOnly = 0); + class CCharacter *IntersectBotCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos); + /* + 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. + */ + class CCharacter *ClosestCharacter(vec2 Pos, float Radius, CEntity *ppNotThis); + + /* + Function: insert_entity + Adds an entity to the world. + + Arguments: + entity - Entity to add + */ + void InsertEntity(CEntity *pEntity); + + /* + Function: remove_entity + Removes an entity from the world. + + Arguments: + entity - Entity to remove + */ + void RemoveEntity(CEntity *pEntity); + + /* + 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(); + + // DDRace + + std::list<class CCharacter *> IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis); + void ReleaseHooked(int ClientID); + + + /* + Function: interserct_CCharacters + Finds all CCharacters that intersect 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 list with all Characters on line. + */ + std::list<class CCharacter *> IntersectedCharacters(vec2 Pos0, vec2 Pos1, float Radius, class CEntity *pNotThis = 0); +}; + +#endif diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp new file mode 100644 index 0000000..4a4c045 --- /dev/null +++ b/src/game/server/player.cpp @@ -0,0 +1,712 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#include <new> +#include <engine/shared/config.h> +#include "player.h" + +#include <engine/server.h> +#include <engine/server/server.h> +#include "gamecontext.h" +#include <game/gamecore.h> +#include <game/version.h> +#include <game/server/teams.h> +#include "gamemodes/WarioWare.h" +#include <stdio.h> +#include <time.h> + + +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; + m_ClientID = ClientID; + m_Team = GameServer()->m_pController->ClampTeam(Team); + m_pCharacter = 0; + m_NumInputs = 0; + m_KillMe = 0; + m_LockInfo = false; + Reset(); +} + +CPlayer::~CPlayer() +{ + delete m_pCharacter; + m_pCharacter = 0; +} + +void CPlayer::Reset() +{ + m_DieTick = Server()->Tick() + (Server()->TickSpeed() * 3); + m_JoinTick = Server()->Tick(); + if (m_pCharacter) + delete m_pCharacter; + m_pCharacter = 0; + m_KillMe = 0; + m_SpectatorID = SPEC_FREEVIEW; + m_LastActionTick = Server()->Tick(); + m_TeamChangeTick = Server()->Tick(); + m_WeakHookSpawn = false; + + int* idMap = Server()->GetIdMap(m_ClientID); + for (int i = 1;i < VANILLA_MAX_CLIENTS;i++) + { + idMap[i] = -1; + } + idMap[0] = m_ClientID; + + // DDRace + + m_LastCommandPos = 0; + m_LastPlaytime = time_get(); + m_Sent1stAfkWarning = 0; + m_Sent2ndAfkWarning = 0; + m_ChatScore = 0; + m_EyeEmote = true; + m_TimerType = g_Config.m_SvDefaultTimerType; + m_DefEmote = EMOTE_NORMAL; + m_Afk = false; + m_LastWhisperTo = -1; + m_LastSetSpectatorMode = 0; + m_TimeoutCode[0] = '\0'; + + m_TuneZone = 0; + m_TuneZoneOld = m_TuneZone; + m_Halloween = false; + m_FirstPacket = true; + + m_SendVoteIndex = -1; + + if (g_Config.m_SvEvents) + { + time_t rawtime; + struct tm* timeinfo; + char d[16], m[16], y[16]; + int dd, mm; + time ( &rawtime ); + timeinfo = localtime ( &rawtime ); + strftime (d,sizeof(y),"%d",timeinfo); + strftime (m,sizeof(m),"%m",timeinfo); + strftime (y,sizeof(y),"%Y",timeinfo); + dd = atoi(d); + mm = atoi(m); + if ((mm == 12 && dd == 31) || (mm == 1 && dd == 1)) + { // New Year + m_DefEmote = EMOTE_HAPPY; + } + else if ((mm == 10 && dd == 31) || (mm == 11 && dd == 1)) + { // Halloween + m_DefEmote = EMOTE_ANGRY; + m_Halloween = true; + } + else + { + m_DefEmote = EMOTE_NORMAL; + } + } + m_DefEmoteReset = -1; + + GameServer()->Score()->PlayerData(m_ClientID)->Reset(); + + m_ClientVersion = VERSION_VANILLA; + m_VersionSpam = 0; + m_ShowOthers = g_Config.m_SvShowOthersDefault; + m_ShowAll = g_Config.m_SvShowAllDefault; + m_SpecTeam = 0; + m_NinjaJetpack = false; + + m_Paused = PAUSED_NONE; + m_DND = false; + + m_NextPauseTick = 0; + + // Variable initialized: + m_Last_Team = 0; +#if defined(CONF_SQL) + m_LastSQLQuery = 0; +#endif + + int64 Now = Server()->Tick(); + int64 TickSpeed = Server()->TickSpeed(); + // If the player joins within ten seconds of the server becoming + // non-empty, allow them to vote immediately. This allows players to + // vote after map changes or when they join an empty server. + // + // Otherwise, block voting for 60 seconds after joining. + if(Now > GameServer()->m_NonEmptySince + 10 * TickSpeed) + { + m_FirstVoteTick = Now + 60 * TickSpeed; + } + else + { + m_FirstVoteTick = Now; + } +} + +void CPlayer::Tick() +{ + if(m_ClientID < MAX_CLIENTS-1) + if(!Server()->ClientIngame(m_ClientID)) + return; + + if(m_KillMe != 0) + { + KillCharacter(m_KillMe); + m_KillMe = 0; + return; + } + + if (m_ChatScore > 0) + m_ChatScore--; + + if (m_ForcePauseTime > 0) + m_ForcePauseTime--; + + Server()->SetClientScore(m_ClientID, m_Score); + + // do latency stuff + { + IServer::CClientInfo Info; + if(Server()->GetClientInfo(m_ClientID, &Info)) + { + m_Latency.m_Accum += Info.m_Latency; + m_Latency.m_AccumMax = max(m_Latency.m_AccumMax, Info.m_Latency); + m_Latency.m_AccumMin = min(m_Latency.m_AccumMin, Info.m_Latency); + } + // each second + if(Server()->Tick()%Server()->TickSpeed() == 0) + { + m_Latency.m_Avg = m_Latency.m_Accum/Server()->TickSpeed(); + m_Latency.m_Max = m_Latency.m_AccumMax; + m_Latency.m_Min = m_Latency.m_AccumMin; + m_Latency.m_Accum = 0; + m_Latency.m_AccumMin = 1000; + m_Latency.m_AccumMax = 0; + } + } + + if(((CServer *)Server())->m_NetServer.ErrorString(m_ClientID)[0]) + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "'%s' would have timed out, but can use timeout protection now", Server()->ClientName(m_ClientID)); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + ((CServer *)(Server()))->m_NetServer.ResetErrorString(m_ClientID); + } + + if(!GameServer()->m_World.m_Paused) + { + if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW) + m_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f)); + + if(!m_pCharacter && m_DieTick <= Server()->Tick()) + m_Spawning = true; + + if(m_pCharacter) + { + if(m_pCharacter->IsAlive()) + { + if(m_Paused >= PAUSED_FORCE) + { + if(m_ForcePauseTime == 0) + m_Paused = PAUSED_NONE; + ProcessPause(); + } + else if(m_Paused == PAUSED_PAUSED && m_NextPauseTick < Server()->Tick()) + { + if((!m_pCharacter->GetWeaponGot(WEAPON_NINJA) || m_pCharacter->m_FreezeTime) && m_pCharacter->IsGrounded() && m_pCharacter->m_Pos == m_pCharacter->m_PrevPos) + ProcessPause(); + } + else if(m_NextPauseTick < Server()->Tick()) + { + ProcessPause(); + } + if(!m_Paused) + m_ViewPos = m_pCharacter->m_Pos; + } + else if(!m_pCharacter->IsPaused()) + { + delete m_pCharacter; + m_pCharacter = 0; + } + } + else if(m_Spawning && !m_WeakHookSpawn) + TryRespawn(); + } + else + { + ++m_DieTick; + ++m_JoinTick; + ++m_LastActionTick; + ++m_TeamChangeTick; + } + + m_TuneZoneOld = m_TuneZone; // determine needed tunings with viewpos + int CurrentIndex = GameServer()->Collision()->GetMapIndex(m_ViewPos); + m_TuneZone = GameServer()->Collision()->IsTune(CurrentIndex); + + if (m_TuneZone != m_TuneZoneOld) // dont send tunigs all the time + { + GameServer()->SendTuningParams(m_ClientID, m_TuneZone); + } +} + +void CPlayer::PostTick() +{ + // update latency value + if(m_PlayerFlags&PLAYERFLAG_SCOREBOARD) + { + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) + m_aActLatency[i] = GameServer()->m_apPlayers[i]->m_Latency.m_Min; + } + } + + // update view pos for spectators + if((m_Team == TEAM_SPECTATORS || m_Paused) && m_SpectatorID != SPEC_FREEVIEW && GameServer()->m_apPlayers[m_SpectatorID] && GameServer()->m_apPlayers[m_SpectatorID]->GetCharacter()) + m_ViewPos = GameServer()->m_apPlayers[m_SpectatorID]->GetCharacter()->m_Pos; +} + +void CPlayer::PostPostTick() +{ + if(m_ClientID < MAX_CLIENTS-1) + if(!Server()->ClientIngame(m_ClientID)) + return; + + if(!GameServer()->m_World.m_Paused && !m_pCharacter && m_Spawning && m_WeakHookSpawn) + TryRespawn(); +} + +void CPlayer::Snap(int SnappingClient) +{ + if(m_ClientID < MAX_CLIENTS-1) + if(!Server()->ClientIngame(m_ClientID)) + return; + + int id = m_ClientID; + if (SnappingClient > -1 && !Server()->Translate(id, SnappingClient)) return; + + CNetObj_ClientInfo *pClientInfo = static_cast<CNetObj_ClientInfo *>(Server()->SnapNewItem(NETOBJTYPE_CLIENTINFO, id, sizeof(CNetObj_ClientInfo))); + + if(!pClientInfo) + return; + + StrToInts(&pClientInfo->m_Name0, 4, Server()->ClientName(m_ClientID)); + StrToInts(&pClientInfo->m_Clan0, 3, Server()->ClientClan(m_ClientID)); + pClientInfo->m_Country = Server()->ClientCountry(m_ClientID); + if (m_StolenSkin && SnappingClient != m_ClientID && g_Config.m_SvSkinStealAction == 1) + { + StrToInts(&pClientInfo->m_Skin0, 6, "pinky"); + pClientInfo->m_UseCustomColor = 0; + pClientInfo->m_ColorBody = m_TeeInfos.m_ColorBody; + pClientInfo->m_ColorFeet = m_TeeInfos.m_ColorFeet; + } else + { + StrToInts(&pClientInfo->m_Skin0, 6, m_TeeInfos.m_SkinName); + pClientInfo->m_UseCustomColor = m_TeeInfos.m_UseCustomColor; + pClientInfo->m_ColorBody = m_TeeInfos.m_ColorBody; + pClientInfo->m_ColorFeet = m_TeeInfos.m_ColorFeet; + } + + CNetObj_PlayerInfo *pPlayerInfo = static_cast<CNetObj_PlayerInfo *>(Server()->SnapNewItem(NETOBJTYPE_PLAYERINFO, id, sizeof(CNetObj_PlayerInfo))); + if(!pPlayerInfo) + return; + + pPlayerInfo->m_Latency = SnappingClient == -1 ? m_Latency.m_Min : GameServer()->m_apPlayers[SnappingClient]->m_aActLatency[m_ClientID]; + pPlayerInfo->m_Local = 0; + pPlayerInfo->m_ClientID = id; + pPlayerInfo->m_Team = (m_Paused != PAUSED_SPEC || m_ClientID != SnappingClient) && m_Paused < PAUSED_PAUSED ? m_Team : TEAM_SPECTATORS; + + if(m_ClientID == SnappingClient) + pPlayerInfo->m_Local = 1; + + if(m_ClientID == SnappingClient && (m_Team == TEAM_SPECTATORS || m_Paused)) + { + CNetObj_SpectatorInfo *pSpectatorInfo = static_cast<CNetObj_SpectatorInfo *>(Server()->SnapNewItem(NETOBJTYPE_SPECTATORINFO, m_ClientID, sizeof(CNetObj_SpectatorInfo))); + if(!pSpectatorInfo) + return; + + pSpectatorInfo->m_SpectatorID = m_SpectatorID; + pSpectatorInfo->m_X = m_ViewPos.x; + pSpectatorInfo->m_Y = m_ViewPos.y; + } + + // send 0 if times of others are not shown + if(SnappingClient != m_ClientID && g_Config.m_SvHideScore) + pPlayerInfo->m_Score = -9999; + else + pPlayerInfo->m_Score = m_Score; +} + +void CPlayer::FakeSnap(int SnappingClient) +{ + // This is problematic when it's sent before we know whether it's a non-64-player-client + // Then we can't spectate players at the start + IServer::CClientInfo info; + Server()->GetClientInfo(SnappingClient, &info); + CGameContext *GameContext = (CGameContext *) GameServer(); + if (SnappingClient > -1 && GameContext->m_apPlayers[SnappingClient] && GameContext->m_apPlayers[SnappingClient]->m_ClientVersion >= VERSION_DDNET_OLD) + return; + + int id = VANILLA_MAX_CLIENTS - 1; + + CNetObj_ClientInfo *pClientInfo = static_cast<CNetObj_ClientInfo *>(Server()->SnapNewItem(NETOBJTYPE_CLIENTINFO, id, sizeof(CNetObj_ClientInfo))); + + if(!pClientInfo) + return; + + StrToInts(&pClientInfo->m_Name0, 4, " "); + StrToInts(&pClientInfo->m_Clan0, 3, Server()->ClientClan(m_ClientID)); + StrToInts(&pClientInfo->m_Skin0, 6, m_TeeInfos.m_SkinName); +} + +void CPlayer::OnDisconnect(const char *pReason) +{ + KillCharacter(); + + if(Server()->ClientIngame(m_ClientID)) + { + char aBuf[512]; + if(pReason && *pReason) + str_format(aBuf, sizeof(aBuf), "'%s' left the game (%s)", Server()->ClientName(m_ClientID), pReason); + else + str_format(aBuf, sizeof(aBuf), "'%s' 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)); + GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "game", aBuf); + } + + CGameControllerWarioWare* Controller = (CGameControllerWarioWare*)GameServer()->m_pController; + Controller->m_Teams.SetForceCharacterTeam(m_ClientID, 0); +} + +void CPlayer::OnPredictedInput(CNetObj_PlayerInput *NewInput) +{ + // skip the input if chat is active + if((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)) + return; + + AfkVoteTimer(NewInput); + + m_NumInputs++; + + if(m_pCharacter && !m_Paused) + m_pCharacter->OnPredictedInput(NewInput); + + // Magic number when we can hope that client has successfully identified itself + if(m_NumInputs == 20) + { + if(g_Config.m_SvClientSuggestion[0] != '\0' && m_ClientVersion <= VERSION_DDNET_OLD) + GameServer()->SendBroadcast(g_Config.m_SvClientSuggestion, m_ClientID); + } +} + +void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) +{ + if (AfkTimer(NewInput->m_TargetX, NewInput->m_TargetY)) + return; // we must return if kicked, as player struct is already deleted + AfkVoteTimer(NewInput); + + if(NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) + { + // skip the input if chat is active + if(m_PlayerFlags&PLAYERFLAG_CHATTING) + return; + + // reset input + if(m_pCharacter) + m_pCharacter->ResetInput(); + + m_PlayerFlags = NewInput->m_PlayerFlags; + return; + } + + m_PlayerFlags = NewInput->m_PlayerFlags; + + if(m_pCharacter) + { + if(!m_Paused) + m_pCharacter->OnDirectInput(NewInput); + else + m_pCharacter->ResetInput(); + } + + //if(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1)) + //m_Spawning = true; + + if(((!m_pCharacter && m_Team == TEAM_SPECTATORS) || m_Paused) && m_SpectatorID == SPEC_FREEVIEW) + m_ViewPos = vec2(NewInput->m_TargetX, NewInput->m_TargetY); + + // check for activity + if(NewInput->m_Direction || m_LatestActivity.m_TargetX != NewInput->m_TargetX || + m_LatestActivity.m_TargetY != NewInput->m_TargetY || NewInput->m_Jump || + NewInput->m_Fire&1 || NewInput->m_Hook) + { + m_LatestActivity.m_TargetX = NewInput->m_TargetX; + m_LatestActivity.m_TargetY = NewInput->m_TargetY; + m_LastActionTick = Server()->Tick(); + } +} + +CCharacter *CPlayer::GetCharacter() +{ + if(m_pCharacter && m_pCharacter->IsAlive()) + return m_pCharacter; + return 0; +} + +void CPlayer::ThreadKillCharacter(int Weapon) +{ + m_KillMe = Weapon; +} + +void CPlayer::KillCharacter(int Weapon) +{ + if(m_pCharacter) + { + m_pCharacter->Die(m_ClientID, Weapon); + + delete m_pCharacter; + m_pCharacter = 0; + } +} + +void CPlayer::Respawn(bool WeakHook) +{ + if(m_Team != TEAM_SPECTATORS) + { + m_WeakHookSpawn = WeakHook; + m_Spawning = true; + } +} + +CCharacter* CPlayer::ForceSpawn(vec2 Pos) +{ + m_Spawning = false; + m_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World); + m_pCharacter->Spawn(this, Pos); + m_Team = 0; + return m_pCharacter; +} + +void CPlayer::SetTeam(int Team, bool DoChatMsg) +{ + // clamp the team + Team = GameServer()->m_pController->ClampTeam(Team); + if(m_Team == Team) + return; + + char aBuf[512]; + if(DoChatMsg) + { + 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); + } + + if(Team == TEAM_SPECTATORS) + { + CGameControllerWarioWare* Controller = (CGameControllerWarioWare*)GameServer()->m_pController; + Controller->m_Teams.SetForceCharacterTeam(m_ClientID, 0); + } + + KillCharacter(); + + m_Team = Team; + m_LastSetTeam = Server()->Tick(); + m_LastActionTick = Server()->Tick(); + m_SpectatorID = SPEC_FREEVIEW; + 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) + { + // update spectator modes + for(int i = 0; i < MAX_CLIENTS; ++i) + { + if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID) + GameServer()->m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW; + } + } +} + +void CPlayer::TryRespawn() +{ + vec2 SpawnPos; + + if(!GameServer()->m_pController->CanSpawn(m_Team, &SpawnPos)) + return; + + CGameControllerWarioWare* Controller = (CGameControllerWarioWare*)GameServer()->m_pController; + + m_WeakHookSpawn = false; + m_Spawning = false; + m_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World); + m_pCharacter->Spawn(this, SpawnPos); + GameServer()->CreatePlayerSpawn(SpawnPos, m_pCharacter->Teams()->TeamMask(m_pCharacter->Team(), -1, m_ClientID)); + + if(g_Config.m_SvTeam == 3) + { + int NewTeam = 0; + for(; NewTeam < TEAM_SUPER; NewTeam++) + if(Controller->m_Teams.Count(NewTeam) == 0) + break; + + if(NewTeam == TEAM_SUPER) + NewTeam = 0; + + Controller->m_Teams.SetForceCharacterTeam(GetCID(), NewTeam); + } +} + +bool CPlayer::AfkTimer(int NewTargetX, int NewTargetY) +{ + /* + afk timer (x, y = mouse coordinates) + Since a player has to move the mouse to play, this is a better method than checking + the player's position in the game world, because it can easily be bypassed by just locking a key. + Frozen players could be kicked as well, because they can't move. + It also works for spectators. + returns true if kicked + */ + + if(m_Authed) + return false; // don't kick admins + if(g_Config.m_SvMaxAfkTime == 0) + return false; // 0 = disabled + + if(NewTargetX != m_LastTarget_x || NewTargetY != m_LastTarget_y) + { + m_LastPlaytime = time_get(); + m_LastTarget_x = NewTargetX; + m_LastTarget_y = NewTargetY; + m_Sent1stAfkWarning = 0; // afk timer's 1st warning after 50% of sv_max_afk_time + m_Sent2ndAfkWarning = 0; + + } + else + { + if(!m_Paused) + { + // not playing, check how long + if(m_Sent1stAfkWarning == 0 && m_LastPlaytime < time_get()-time_freq()*(int)(g_Config.m_SvMaxAfkTime*0.5)) + { + sprintf( + m_pAfkMsg, + "You have been afk for %d seconds now. Please note that you get kicked after not playing for %d seconds.", + (int)(g_Config.m_SvMaxAfkTime*0.5), + g_Config.m_SvMaxAfkTime + ); + m_pGameServer->SendChatTarget(m_ClientID, m_pAfkMsg); + m_Sent1stAfkWarning = 1; + } + else if(m_Sent2ndAfkWarning == 0 && m_LastPlaytime < time_get()-time_freq()*(int)(g_Config.m_SvMaxAfkTime*0.9)) + { + sprintf( + m_pAfkMsg, + "You have been afk for %d seconds now. Please note that you get kicked after not playing for %d seconds.", + (int)(g_Config.m_SvMaxAfkTime*0.9), + g_Config.m_SvMaxAfkTime + ); + m_pGameServer->SendChatTarget(m_ClientID, m_pAfkMsg); + m_Sent2ndAfkWarning = 1; + } + else if(m_LastPlaytime < time_get()-time_freq()*g_Config.m_SvMaxAfkTime) + { + CServer* serv = (CServer*)m_pGameServer->Server(); + serv->Kick(m_ClientID,"Away from keyboard"); + return true; + } + } + } + return false; +} + +void CPlayer::AfkVoteTimer(CNetObj_PlayerInput *NewTarget) +{ + if(g_Config.m_SvMaxAfkVoteTime == 0) + return; + + if(mem_comp(NewTarget, &m_LastTarget, sizeof(CNetObj_PlayerInput)) != 0) + { + m_LastPlaytime = time_get(); + mem_copy(&m_LastTarget, NewTarget, sizeof(CNetObj_PlayerInput)); + } + else if(m_LastPlaytime < time_get()-time_freq()*g_Config.m_SvMaxAfkVoteTime) + { + m_Afk = true; + return; + } + + m_Afk = false; +} + +void CPlayer::ProcessPause() +{ + if(!m_pCharacter) + return; + + char aBuf[128]; + if(m_Paused >= PAUSED_PAUSED) + { + if(!m_pCharacter->IsPaused()) + { + m_pCharacter->Pause(true); + if(g_Config.m_SvPauseMessages) + { + str_format(aBuf, sizeof(aBuf), (m_Paused == PAUSED_PAUSED) ? "'%s' paused" : "'%s' was force-paused for %ds", Server()->ClientName(m_ClientID), m_ForcePauseTime/Server()->TickSpeed()); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + GameServer()->CreateDeath(m_pCharacter->m_Pos, m_ClientID, m_pCharacter->Teams()->TeamMask(m_pCharacter->Team(), -1, m_ClientID)); + GameServer()->CreateSound(m_pCharacter->m_Pos, SOUND_PLAYER_DIE, m_pCharacter->Teams()->TeamMask(m_pCharacter->Team(), -1, m_ClientID)); + m_NextPauseTick = Server()->Tick() + g_Config.m_SvPauseFrequency * Server()->TickSpeed(); + } + } + else + { + if(m_pCharacter->IsPaused()) + { + m_pCharacter->Pause(false); + if(g_Config.m_SvPauseMessages) + { + str_format(aBuf, sizeof(aBuf), "'%s' resumed", Server()->ClientName(m_ClientID)); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + GameServer()->CreatePlayerSpawn(m_pCharacter->m_Pos, m_pCharacter->Teams()->TeamMask(m_pCharacter->Team(), -1, m_ClientID)); + m_NextPauseTick = Server()->Tick() + g_Config.m_SvPauseFrequency * Server()->TickSpeed(); + } + } +} + +bool CPlayer::IsPlaying() +{ + if(m_pCharacter && m_pCharacter->IsAlive()) + return true; + return false; +} + +void CPlayer::FindDuplicateSkins() +{ + if (m_TeeInfos.m_UseCustomColor == 0 && !m_StolenSkin) return; + m_StolenSkin = 0; + for (int i = 0; i < MAX_CLIENTS; ++i) + { + if (i == m_ClientID) continue; + if(GameServer()->m_apPlayers[i]) + { + if (GameServer()->m_apPlayers[i]->m_StolenSkin) continue; + if ((GameServer()->m_apPlayers[i]->m_TeeInfos.m_UseCustomColor == m_TeeInfos.m_UseCustomColor) && + (GameServer()->m_apPlayers[i]->m_TeeInfos.m_ColorFeet == m_TeeInfos.m_ColorFeet) && + (GameServer()->m_apPlayers[i]->m_TeeInfos.m_ColorBody == m_TeeInfos.m_ColorBody) && + !str_comp(GameServer()->m_apPlayers[i]->m_TeeInfos.m_SkinName, m_TeeInfos.m_SkinName)) + { + m_StolenSkin = 1; + return; + } + } + } +} diff --git a/src/game/server/player.h b/src/game/server/player.h new file mode 100644 index 0000000..df33d30 --- /dev/null +++ b/src/game/server/player.h @@ -0,0 +1,200 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_SERVER_PLAYER_H +#define GAME_SERVER_PLAYER_H + +// this include should perhaps be removed +#include "entities/character.h" +#include "gamecontext.h" + +// player object +class CPlayer +{ + MACRO_ALLOC_POOL_ID() + + friend class CSaveTee; + +public: + CPlayer(CGameContext *pGameServer, int ClientID, int Team); + ~CPlayer(); + + void Reset(); + + void TryRespawn(); + void Respawn(bool WeakHook = false); // with WeakHook == true the character will be spawned after all calls of Tick from other Players + CCharacter* ForceSpawn(vec2 Pos); // required for loading savegames + void SetTeam(int Team, bool DoChatMsg=true); + int GetTeam() const { return m_Team; }; + int GetCID() const { return m_ClientID; }; + + void Tick(); + void PostTick(); + + // will be called after all Tick and PostTick calls from other players + void PostPostTick(); + void Snap(int SnappingClient); + void FakeSnap(int SnappingClient); + + void OnDirectInput(CNetObj_PlayerInput *NewInput); + void OnPredictedInput(CNetObj_PlayerInput *NewInput); + void OnDisconnect(const char *pReason); + + void ThreadKillCharacter(int Weapon = WEAPON_GAME); + void KillCharacter(int Weapon = WEAPON_GAME); + CCharacter *GetCharacter(); + + void FindDuplicateSkins(); + + //--------------------------------------------------------- + // this is used for snapping so we know how we can clip the view for the player + vec2 m_ViewPos; + int m_TuneZone; + int m_TuneZoneOld; + + // states if the client is chatting, accessing a menu etc. + int m_PlayerFlags; + + // used for snapping to just update latency if the scoreboard is active + int m_aActLatency[MAX_CLIENTS]; + + // used for spectator mode + int m_SpectatorID; + + bool m_IsReady; + + // + int m_Vote; + int m_VotePos; + // + int m_LastVoteCall; + int m_LastVoteTry; + int m_LastChat; + int m_LastSetTeam; + int m_LastSetSpectatorMode; + int m_LastChangeInfo; + int m_LastEmote; + int m_LastKill; + int m_LastCommands[4]; + int m_LastCommandPos; + int m_LastWhisperTo; + + int m_SendVoteIndex; + + // TODO: clean this up + struct + { + char m_SkinName[64]; + int m_UseCustomColor; + int m_ColorBody; + int m_ColorFeet; + } m_TeeInfos; + + int m_DieTick; + int m_Score; + int m_JoinTick; + bool m_ForceBalanced; + int m_LastActionTick; + bool m_StolenSkin; + int m_TeamChangeTick; + struct + { + int m_TargetX; + int m_TargetY; + } m_LatestActivity; + + // network latency calculations + struct + { + int m_Accum; + int m_AccumMin; + int m_AccumMax; + int m_Avg; + int m_Min; + int m_Max; + } m_Latency; + + // headbot + char original_skin[64]; + int original_color; + +private: + CCharacter *m_pCharacter; + int m_NumInputs; + CGameContext *m_pGameServer; + + CGameContext *GameServer() const { return m_pGameServer; } + IServer *Server() const; + + // + bool m_Spawning; + bool m_WeakHookSpawn; + int m_ClientID; + int m_Team; + bool m_voluntarySpectator; + bool m_LockInfo; + + + // DDRace + +public: + enum + { + PAUSED_NONE=0, + PAUSED_SPEC, + PAUSED_PAUSED, + PAUSED_FORCE + }; + + int m_Paused; + bool m_DND; + int64 m_FirstVoteTick; + int64 m_NextPauseTick; + char m_TimeoutCode[64]; + + void ProcessPause(); + int m_ForcePauseTime; + bool IsPlaying(); + int64 m_Last_KickVote; + int64 m_Last_Team; + int m_Authed; + int m_ClientVersion; + int m_VersionSpam; + bool m_ShowOthers; + bool m_ShowAll; + bool m_SpecTeam; + bool m_NinjaJetpack; + bool m_Afk; + int m_KillMe; + + int m_ChatScore; + + bool AfkTimer(int new_target_x, int new_target_y); //returns true if kicked + void AfkVoteTimer(CNetObj_PlayerInput *NewTarget); + int64 m_LastPlaytime; + int64 m_LastEyeEmote; + int m_LastTarget_x; + int m_LastTarget_y; + CNetObj_PlayerInput m_LastTarget; + int m_Sent1stAfkWarning; // afk timer's 1st warning after 50% of sv_max_afk_time + int m_Sent2ndAfkWarning; // afk timer's 2nd warning after 90% of sv_max_afk_time + char m_pAfkMsg[160]; + bool m_EyeEmote; + int m_TimerType; + int m_DefEmote; + int m_DefEmoteReset; + bool m_Halloween; + bool m_FirstPacket; + + // headbot + bool IsOut() { return m_Team == TEAM_SPECTATORS and not m_voluntarySpectator; } + bool IsVoluntarySpectator() const { return m_Team == TEAM_SPECTATORS and m_voluntarySpectator; } + void setVoluntarySpectator(bool on) { m_voluntarySpectator = on; } + bool InfoLocked() const { return m_LockInfo; } + void SetInfoLock(bool on) { m_LockInfo = on; } + +#if defined(CONF_SQL) + int64 m_LastSQLQuery; +#endif +}; + +#endif diff --git a/src/game/server/save.cpp b/src/game/server/save.cpp new file mode 100644 index 0000000..7045a14 --- /dev/null +++ b/src/game/server/save.cpp @@ -0,0 +1,506 @@ +#include <new> +#include <cstdio> + +#include "save.h" +#include "teams.h" +#include <engine/server/server.h> +#include "./gamemodes/DDRace.h" +#include <engine/shared/config.h> + +CSaveTee::CSaveTee() +{ + ; +} + +CSaveTee::~CSaveTee() +{ + ; +} + +void CSaveTee::save(CCharacter* pchr) +{ + str_copy(m_name, pchr->m_pPlayer->Server()->ClientName(pchr->m_pPlayer->GetCID()), sizeof(m_name)); + + m_Alive = pchr->m_Alive; + m_Paused = pchr->m_pPlayer->m_Paused; + m_NeededFaketuning = pchr->m_NeededFaketuning; + + m_TeeFinished = pchr->Teams()->TeeFinished(pchr->m_pPlayer->GetCID()); + m_IsSolo = pchr->Teams()->m_Core.GetSolo(pchr->m_pPlayer->GetCID()); + + for(int i = 0; i< NUM_WEAPONS; i++) + { + m_aWeapons[i].m_AmmoRegenStart = pchr->m_aWeapons[i].m_AmmoRegenStart; + m_aWeapons[i].m_Ammo = pchr->m_aWeapons[i].m_Ammo; + m_aWeapons[i].m_Ammocost = pchr->m_aWeapons[i].m_Ammocost; + m_aWeapons[i].m_Got = pchr->m_aWeapons[i].m_Got; + } + + m_LastWeapon = pchr->m_LastWeapon; + m_QueuedWeapon = pchr->m_QueuedWeapon; + + m_SuperJump = pchr->m_SuperJump; + m_Jetpack = pchr->m_Jetpack; + m_NinjaJetpack = pchr->m_NinjaJetpack; + m_FreezeTime = pchr->m_FreezeTime; + m_FreezeTick = pchr->Server()->Tick() - pchr->m_FreezeTick; + + m_DeepFreeze = pchr->m_DeepFreeze; + m_EndlessHook = pchr->m_EndlessHook; + m_DDRaceState = pchr->m_DDRaceState; + + m_Hit = pchr->m_Hit; + m_TuneZone = pchr->m_TuneZone; + m_TuneZoneOld = pchr->m_TuneZoneOld; + + if(pchr->m_StartTime) + m_Time = pchr->Server()->Tick() - pchr->m_StartTime + 60 * pchr->Server()->TickSpeed(); + + m_Pos = pchr->m_Pos; + m_PrevPos = pchr->m_PrevPos; + m_TeleCheckpoint = pchr->m_TeleCheckpoint; + m_LastPenalty = pchr->m_LastPenalty; + + if(pchr->m_CpTick) + m_CpTime = pchr->Server()->Tick() - pchr->m_CpTick; + + m_CpActive = pchr->m_CpActive; + m_CpLastBroadcast = pchr->m_CpLastBroadcast; + + for(int i = 0; i < 25; i++) + m_CpCurrent[i] = pchr->m_CpCurrent[i]; + + // Core + m_CorePos = pchr->m_Core.m_Pos; + m_Vel = pchr->m_Core.m_Vel; + m_Hook = pchr->m_Core.m_Hook; + m_Collision = pchr->m_Core.m_Collision; + m_ActiveWeapon = pchr->m_Core.m_ActiveWeapon; + m_Jumped = pchr->m_Core.m_Jumped; + m_JumpedTotal = pchr->m_Core.m_JumpedTotal; + m_Jumps = pchr->m_Core.m_Jumps; + m_HookPos = pchr->m_Core.m_HookPos; + m_HookDir = pchr->m_Core.m_HookDir; + m_HookTeleBase = pchr->m_Core.m_HookTeleBase; + + m_HookTick = pchr->m_Core.m_HookTick; + + m_HookState = pchr->m_Core.m_HookState; +} + +void CSaveTee::load(CCharacter* pchr, int Team) +{ + pchr->m_pPlayer->m_Paused = m_Paused; + pchr->m_pPlayer->ProcessPause(); + + pchr->m_Alive = m_Alive; + pchr->m_NeededFaketuning = m_NeededFaketuning; + + pchr->Teams()->SetForceCharacterTeam(pchr->m_pPlayer->GetCID(), Team); + pchr->Teams()->m_Core.SetSolo(pchr->m_pPlayer->GetCID(), m_IsSolo); + pchr->Teams()->SetFinished(pchr->m_pPlayer->GetCID(), m_TeeFinished); + + for(int i = 0; i< NUM_WEAPONS; i++) + { + pchr->m_aWeapons[i].m_AmmoRegenStart = m_aWeapons[i].m_AmmoRegenStart; + pchr->m_aWeapons[i].m_Ammo = m_aWeapons[i].m_Ammo; + pchr->m_aWeapons[i].m_Ammocost = m_aWeapons[i].m_Ammocost; + pchr->m_aWeapons[i].m_Got = m_aWeapons[i].m_Got; + } + + pchr->m_LastWeapon = m_LastWeapon; + pchr->m_QueuedWeapon = m_QueuedWeapon; + + pchr->m_SuperJump = m_SuperJump; + pchr->m_Jetpack = m_Jetpack; + pchr->m_NinjaJetpack = m_NinjaJetpack; + pchr->m_FreezeTime = m_FreezeTime; + pchr->m_FreezeTick = pchr->Server()->Tick() - m_FreezeTick; + + pchr->m_DeepFreeze = m_DeepFreeze; + pchr->m_EndlessHook = m_EndlessHook; + pchr->m_DDRaceState = m_DDRaceState; + + pchr->m_Hit = m_Hit; + pchr->m_TuneZone = m_TuneZone; + pchr->m_TuneZoneOld = m_TuneZoneOld; + + if(m_Time) + pchr->m_StartTime = pchr->Server()->Tick() - m_Time; + + pchr->m_Pos = m_Pos; + pchr->m_PrevPos = m_PrevPos; + pchr->m_TeleCheckpoint = m_TeleCheckpoint; + pchr->m_LastPenalty = m_LastPenalty; + + if(m_CpTime) + pchr->m_CpTick = pchr->Server()->Tick() - m_CpTime; + + pchr->m_CpActive = m_CpActive; + pchr->m_CpLastBroadcast = m_CpLastBroadcast; + + for(int i = 0; i < 25; i++) + pchr->m_CpCurrent[i] = m_CpCurrent[i]; + + // Core + pchr->m_Core.m_Pos = m_CorePos; + pchr->m_Core.m_Vel = m_Vel; + pchr->m_Core.m_Hook = m_Hook; + pchr->m_Core.m_Collision = m_Collision; + pchr->m_Core.m_ActiveWeapon = m_ActiveWeapon; + pchr->m_Core.m_Jumped = m_Jumped; + pchr->m_Core.m_JumpedTotal = m_JumpedTotal; + pchr->m_Core.m_Jumps = m_Jumps; + pchr->m_Core.m_HookPos = m_HookPos; + pchr->m_Core.m_HookDir = m_HookDir; + pchr->m_Core.m_HookTeleBase = m_HookTeleBase; + + pchr->m_Core.m_HookTick = m_HookTick; + + if(m_HookState == HOOK_GRABBED) + { + pchr->m_Core.m_HookState = HOOK_FLYING; + pchr->m_Core.m_HookedPlayer = -1; + } + else + { + pchr->m_Core.m_HookState = m_HookState; + } + + pchr->GameServer()->SendTuningParams(pchr->m_pPlayer->GetCID(), m_TuneZone); +} + +char* CSaveTee::GetString() +{ + str_format(m_String, sizeof(m_String), "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%f\t%f\t%d\t%d\t%d\t%d\t%d\t%d\t%f\t%f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f", m_name, m_Alive, m_Paused, m_NeededFaketuning, m_TeeFinished, m_IsSolo, m_aWeapons[0].m_AmmoRegenStart, m_aWeapons[0].m_Ammo, m_aWeapons[0].m_Ammocost, m_aWeapons[0].m_Got, m_aWeapons[1].m_AmmoRegenStart, m_aWeapons[1].m_Ammo, m_aWeapons[1].m_Ammocost, m_aWeapons[1].m_Got, m_aWeapons[2].m_AmmoRegenStart, m_aWeapons[2].m_Ammo, m_aWeapons[2].m_Ammocost, m_aWeapons[2].m_Got, m_aWeapons[3].m_AmmoRegenStart, m_aWeapons[3].m_Ammo, m_aWeapons[3].m_Ammocost, m_aWeapons[3].m_Got, m_aWeapons[4].m_AmmoRegenStart, m_aWeapons[4].m_Ammo, m_aWeapons[4].m_Ammocost, m_aWeapons[4].m_Got, m_aWeapons[5].m_AmmoRegenStart, m_aWeapons[5].m_Ammo, m_aWeapons[5].m_Ammocost, m_aWeapons[5].m_Got, m_LastWeapon, m_QueuedWeapon, m_SuperJump, m_Jetpack, m_NinjaJetpack, m_FreezeTime, m_FreezeTick, m_DeepFreeze, m_EndlessHook, m_DDRaceState, m_Hit, m_Collision, m_TuneZone, m_TuneZoneOld, m_Hook, m_Time, (int)m_Pos.x, (int)m_Pos.y, (int)m_PrevPos.x, (int)m_PrevPos.y, m_TeleCheckpoint, m_LastPenalty, (int)m_CorePos.x, (int)m_CorePos.y, m_Vel.x, m_Vel.y, m_ActiveWeapon, m_Jumped, m_JumpedTotal, m_Jumps, (int)m_HookPos.x, (int)m_HookPos.y, m_HookDir.x, m_HookDir.y, (int)m_HookTeleBase.x, (int)m_HookTeleBase.y, m_HookTick, m_HookState, m_CpTime, m_CpActive, m_CpLastBroadcast, m_CpCurrent[0], m_CpCurrent[1], m_CpCurrent[2], m_CpCurrent[3], m_CpCurrent[4], m_CpCurrent[5], m_CpCurrent[6], m_CpCurrent[7], m_CpCurrent[8], m_CpCurrent[9], m_CpCurrent[10], m_CpCurrent[11], m_CpCurrent[12], m_CpCurrent[13], m_CpCurrent[14], m_CpCurrent[15], m_CpCurrent[16], m_CpCurrent[17], m_CpCurrent[18], m_CpCurrent[19], m_CpCurrent[20], m_CpCurrent[21], m_CpCurrent[22], m_CpCurrent[23], m_CpCurrent[24]); + return m_String; +} + +int CSaveTee::LoadString(char* String) +{ + int Num; + Num = sscanf(String, "%[^\t]\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%d\t%d\t%f\t%f\t%f\t%f\t%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\t%d\t%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f", m_name, &m_Alive, &m_Paused, &m_NeededFaketuning, &m_TeeFinished, &m_IsSolo, &m_aWeapons[0].m_AmmoRegenStart, &m_aWeapons[0].m_Ammo, &m_aWeapons[0].m_Ammocost, &m_aWeapons[0].m_Got, &m_aWeapons[1].m_AmmoRegenStart, &m_aWeapons[1].m_Ammo, &m_aWeapons[1].m_Ammocost, &m_aWeapons[1].m_Got, &m_aWeapons[2].m_AmmoRegenStart, &m_aWeapons[2].m_Ammo, &m_aWeapons[2].m_Ammocost, &m_aWeapons[2].m_Got, &m_aWeapons[3].m_AmmoRegenStart, &m_aWeapons[3].m_Ammo, &m_aWeapons[3].m_Ammocost, &m_aWeapons[3].m_Got, &m_aWeapons[4].m_AmmoRegenStart, &m_aWeapons[4].m_Ammo, &m_aWeapons[4].m_Ammocost, &m_aWeapons[4].m_Got, &m_aWeapons[5].m_AmmoRegenStart, &m_aWeapons[5].m_Ammo, &m_aWeapons[5].m_Ammocost, &m_aWeapons[5].m_Got, &m_LastWeapon, &m_QueuedWeapon, &m_SuperJump, &m_Jetpack, &m_NinjaJetpack, &m_FreezeTime, &m_FreezeTick, &m_DeepFreeze, &m_EndlessHook, &m_DDRaceState, &m_Hit, &m_Collision, &m_TuneZone, &m_TuneZoneOld, &m_Hook, &m_Time, &m_Pos.x, &m_Pos.y, &m_PrevPos.x, &m_PrevPos.y, &m_TeleCheckpoint, &m_LastPenalty, &m_CorePos.x, &m_CorePos.y, &m_Vel.x, &m_Vel.y, &m_ActiveWeapon, &m_Jumped, &m_JumpedTotal, &m_Jumps, &m_HookPos.x, &m_HookPos.y, &m_HookDir.x, &m_HookDir.y, &m_HookTeleBase.x, &m_HookTeleBase.y, &m_HookTick, &m_HookState, &m_CpTime, &m_CpActive, &m_CpLastBroadcast, &m_CpCurrent[0], &m_CpCurrent[1], &m_CpCurrent[2], &m_CpCurrent[3], &m_CpCurrent[4], &m_CpCurrent[5], &m_CpCurrent[6], &m_CpCurrent[7], &m_CpCurrent[8], &m_CpCurrent[9], &m_CpCurrent[10], &m_CpCurrent[11], &m_CpCurrent[12], &m_CpCurrent[13], &m_CpCurrent[14], &m_CpCurrent[15], &m_CpCurrent[16], &m_CpCurrent[17], &m_CpCurrent[18], &m_CpCurrent[19], &m_CpCurrent[20], &m_CpCurrent[21], &m_CpCurrent[22], &m_CpCurrent[23], &m_CpCurrent[24]); + if (Num == 96) // Don't forget to update this when you save / load more / less. + return 0; + else + { + dbg_msg("Load", "failed to load Tee-string"); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "loaded %d vars", Num); + dbg_msg("Load", aBuf); + return Num+1; // never 0 here + } +} + +CSaveTeam::CSaveTeam(IGameController* Controller) +{ + m_pController = Controller; + m_Switchers = 0; + SavedTees = 0; +} + +CSaveTeam::~CSaveTeam() +{ + if(m_Switchers) + delete[] m_Switchers; + if(SavedTees) + delete[] SavedTees; +} + +int CSaveTeam::save(int Team) +{ + if(g_Config.m_SvTeam == 3 || (Team > 0 && Team < MAX_CLIENTS)) + { + CGameTeams* Teams = &(((CGameControllerDDRace*)m_pController)->m_Teams); + + m_MembersCount = Teams->Count(Team); + if(m_MembersCount <= 0) + { + return 2; + } + + m_TeamState = Teams->GetTeamState(Team); + + if(m_TeamState != CGameTeams::TEAMSTATE_STARTED) + { + return 4; + } + + m_NumSwitchers = m_pController->GameServer()->Collision()->m_NumSwitchers; + m_TeamLocked = Teams->TeamLocked(Team); + + SavedTees = new CSaveTee[m_MembersCount]; + int j = 0; + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(Teams->m_Core.Team(i) == Team) + { + if(m_pController->GameServer()->m_apPlayers[i] && m_pController->GameServer()->m_apPlayers[i]->GetCharacter()) + SavedTees[j].save(m_pController->GameServer()->m_apPlayers[i]->GetCharacter()); + else + return 3; + j++; + } + } + + if(m_pController->GameServer()->Collision()->m_NumSwitchers) + { + m_Switchers = new SSimpleSwitchers[m_pController->GameServer()->Collision()->m_NumSwitchers+1]; + + for(int i=1; i < m_pController->GameServer()->Collision()->m_NumSwitchers+1; i++) + { + m_Switchers[i].m_Status = m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Status[Team]; + if(m_pController->GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team]) + m_Switchers[i].m_EndTime = m_pController->Server()->Tick() - m_pController->GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team]; + else + m_Switchers[i].m_EndTime = 0; + m_Switchers[i].m_Type = m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Type[Team]; + } + } + return 0; + } + else + return 1; +} + +int CSaveTeam::load(int Team) +{ + if(Team <= 0 || Team >= MAX_CLIENTS) + return 1; + + CGameTeams* Teams = &(((CGameControllerDDRace*)m_pController)->m_Teams); + + Teams->ChangeTeamState(Team, m_TeamState); + Teams->SetTeamLock(Team, m_TeamLocked); + + CCharacter* pchr; + + for (int i = 0; i<m_MembersCount; i++) + { + int ID = MatchPlayer(SavedTees[i].GetName()); + if(ID == -1) // first check if team can be loaded / do not load half teams + { + return i+10; // +10 to let space for other return-values + } + else if (m_pController->GameServer()->m_apPlayers[ID] && m_pController->GameServer()->m_apPlayers[ID]->GetCharacter() && m_pController->GameServer()->m_apPlayers[ID]->GetCharacter()->m_DDRaceState) + { + return i+100; // +100 to let space for other return-values + } + } + + for (int i = 0; i<m_MembersCount; i++) + { + pchr = MatchCharacter(SavedTees[i].GetName(), i); + if(pchr) + { + SavedTees[i].load(pchr, Team); + } + } + + if(m_pController->GameServer()->Collision()->m_NumSwitchers) + for(int i=1; i < m_pController->GameServer()->Collision()->m_NumSwitchers+1; i++) + { + m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Status[Team] = m_Switchers[i].m_Status; + if(m_Switchers[i].m_EndTime) + m_pController->GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team] = m_pController->Server()->Tick() - m_Switchers[i].m_EndTime; + m_pController->GameServer()->Collision()->m_pSwitchers[i].m_Type[Team] = m_Switchers[i].m_Type; + } + return 0; +} + +int CSaveTeam::MatchPlayer(char name[16]) +{ + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(str_comp(m_pController->Server()->ClientName(i), name) == 0) + { + return i; + } + } + return -1; +} + +CCharacter* CSaveTeam::MatchCharacter(char name[16], int SaveID) +{ + int ID = MatchPlayer(name); + if(ID >= 0 && m_pController->GameServer()->m_apPlayers[ID]) + { + if(m_pController->GameServer()->m_apPlayers[ID]->GetCharacter()) + return m_pController->GameServer()->m_apPlayers[ID]->GetCharacter(); + else + return m_pController->GameServer()->m_apPlayers[ID]->ForceSpawn(SavedTees[SaveID].GetPos()); + } + + return 0; +} + +char* CSaveTeam::GetString() +{ + str_format(m_String, sizeof(m_String), "%d\t%d\t%d\t%d", m_TeamState, m_MembersCount, m_NumSwitchers, m_TeamLocked); + + for (int i = 0; i<m_MembersCount; i++) + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "\n%s", SavedTees[i].GetString()); + str_append(m_String, aBuf, sizeof(m_String)); + } + + if(m_NumSwitchers) + for(int i=1; i < m_NumSwitchers+1; i++) + { + char aBuf[64]; + if (m_Switchers) + { + str_format(aBuf, sizeof(aBuf), "\n%d\t%d\t%d", m_Switchers[i].m_Status, m_Switchers[i].m_EndTime, m_Switchers[i].m_Type); + str_append(m_String, aBuf, sizeof(m_String)); + } + } + + return m_String; +} + +int CSaveTeam::LoadString(const char* String) +{ + char TeamStats[MAX_CLIENTS]; + char Switcher[64]; + char SaveTee[1024]; + + char* CopyPos; + unsigned int Pos = 0; + unsigned int LastPos = 0; + unsigned int StrSize; + + str_copy(m_String, String, sizeof(m_String)); + + while (m_String[Pos] != '\n' && Pos < sizeof(m_String) && m_String[Pos]) // find next \n or \0 + Pos++; + + CopyPos = m_String + LastPos; + StrSize = Pos - LastPos + 1; + if(m_String[Pos] == '\n') + { + Pos++; // skip \n + LastPos = Pos; + } + + if(StrSize <= 0) + { + dbg_msg("Load", "Savegame: wrong format (couldn't load TeamStats)"); + return 1; + } + + if(StrSize < sizeof(TeamStats)) + { + str_copy(TeamStats, CopyPos, StrSize); + int Num = sscanf(TeamStats, "%d\t%d\t%d\t%d", &m_TeamState, &m_MembersCount, &m_NumSwitchers, &m_TeamLocked); + if(Num != 4) + { + dbg_msg("Load", "failed to load Teamstats"); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "loaded %d vars", Num); + dbg_msg("Load", aBuf); + } + } + else + { + dbg_msg("Load", "Savegame: wrong format (couldn't load TeamStats, too big)"); + return 1; + } + + if(SavedTees) + { + delete [] SavedTees; + SavedTees = 0; + } + + if(m_MembersCount) + SavedTees = new CSaveTee[m_MembersCount]; + + for (int n = 0; n < m_MembersCount; n++) + { + while (m_String[Pos] != '\n' && Pos < sizeof(m_String) && m_String[Pos]) // find next \n or \0 + Pos++; + + CopyPos = m_String + LastPos; + StrSize = Pos - LastPos + 1; + if(m_String[Pos] == '\n') + { + Pos++; // skip \n + LastPos = Pos; + } + + if(StrSize <= 0) + { + dbg_msg("Load", "Savegame: wrong format (couldn't load Tee)"); + return 1; + } + + if(StrSize < sizeof(SaveTee)) + { + str_copy(SaveTee, CopyPos, StrSize); + int Num = SavedTees[n].LoadString(SaveTee); + if(Num) + { + dbg_msg("Load", "failed to load Tee"); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "loaded %d vars", Num-1); + dbg_msg("Load", aBuf); + return 1; + } + } + else + { + dbg_msg("Load", "Savegame: wrong format (couldn't load Tee, too big)"); + return 1; + } + } + + if(m_Switchers) + { + delete [] m_Switchers; + m_Switchers = 0; + } + + if(m_NumSwitchers) + m_Switchers = new SSimpleSwitchers[m_NumSwitchers+1]; + + for (int n = 1; n < m_NumSwitchers+1; n++) + { + while (m_String[Pos] != '\n' && Pos < sizeof(m_String) && m_String[Pos]) // find next \n or \0 + Pos++; + + CopyPos = m_String + LastPos; + StrSize = Pos - LastPos + 1; + if(m_String[Pos] == '\n') + { + Pos++; // skip \n + LastPos = Pos; + } + + if(StrSize <= 0) + { + dbg_msg("Load", "Savegame: wrong format (couldn't load Switcher)"); + return 1; + } + + if(StrSize < sizeof(Switcher)) + { + str_copy(Switcher, CopyPos, StrSize); + int Num = sscanf(Switcher, "%d\t%d\t%d", &(m_Switchers[n].m_Status), &(m_Switchers[n].m_EndTime), &(m_Switchers[n].m_Type)); + if(Num != 3) + { + dbg_msg("Load", "failed to load Switcher"); + char aBuf[32]; + str_format(aBuf, sizeof(aBuf), "loaded %d vars", Num-1); + dbg_msg("Load", aBuf); + } + } + else + { + dbg_msg("Load", "Savegame: wrong format (couldn't load Switcher, too big)"); + return 1; + } + } + + return 0; +} diff --git a/src/game/server/save.h b/src/game/server/save.h new file mode 100644 index 0000000..6c3008e --- /dev/null +++ b/src/game/server/save.h @@ -0,0 +1,117 @@ +#ifndef SAVE_H +#define SAVE_H + +#include "./entities/character.h" +#include <game/server/gamecontroller.h> + +class CSaveTee +{ +public: + CSaveTee(); + ~CSaveTee(); + void save(CCharacter* pchr); + void load(CCharacter* pchr, int Team); + char* GetString(); + int LoadString(char* String); + vec2 GetPos() { return m_Pos; } + char* GetName() { return m_name; } + +private: + + char m_String [2048]; + char m_name [16]; + + int m_Alive; + int m_Paused; + int m_NeededFaketuning; + + // Teamstuff + int m_TeeFinished; + int m_IsSolo; + + struct WeaponStat + { + int m_AmmoRegenStart; + int m_Ammo; + int m_Ammocost; + int m_Got; + + } m_aWeapons[NUM_WEAPONS]; + + int m_LastWeapon; + int m_QueuedWeapon; + + int m_SuperJump; + int m_Jetpack; + int m_NinjaJetpack; + int m_FreezeTime; + int m_FreezeTick; + int m_DeepFreeze; + int m_EndlessHook; + int m_DDRaceState; + + int m_Hit; + int m_Collision; + int m_TuneZone; + int m_TuneZoneOld; + int m_Hook; + int m_Time; + vec2 m_Pos; + vec2 m_PrevPos; + int m_TeleCheckpoint; + int m_LastPenalty; + + int m_CpTime; + int m_CpActive; + int m_CpLastBroadcast; + float m_CpCurrent[25]; + + // Core + vec2 m_CorePos; + vec2 m_Vel; + int m_ActiveWeapon; + int m_Jumped; + int m_JumpedTotal; + int m_Jumps; + vec2 m_HookPos; + vec2 m_HookDir; + vec2 m_HookTeleBase; + int m_HookTick; + int m_HookState; +}; + +class CSaveTeam +{ +public: + CSaveTeam(IGameController* Controller); + ~CSaveTeam(); + char* GetString(); + int GetMembersCount() {return m_MembersCount;} + int LoadString(const char* String); + int save(int Team); + int load(int Team); + CSaveTee* SavedTees; + +private: + int MatchPlayer(char name[16]); + CCharacter* MatchCharacter(char name[16], int SaveID); + + IGameController* m_pController; + + char m_String[65536]; + + struct SSimpleSwitchers + { + int m_Status; + int m_EndTime; + int m_Type; + }; + SSimpleSwitchers* m_Switchers; + + int m_TeamState; + int m_MembersCount; + int m_NumSwitchers; + int m_TeamLocked; +}; + +#endif diff --git a/src/game/server/score.h b/src/game/server/score.h new file mode 100644 index 0000000..e4ab6a7 --- /dev/null +++ b/src/game/server/score.h @@ -0,0 +1,70 @@ +#ifndef GAME_SERVER_INTERFACE_SCORE_H +#define GAME_SERVER_INTERFACE_SCORE_H + +#include "entities/character.h" +#include "gamecontext.h" + +#define NUM_CHECKPOINTS 25 + +class CPlayerData +{ +public: + CPlayerData() + { + Reset(); + } + + void Reset() + { + m_BestTime = 0; + m_CurrentTime = 0; + for(int i = 0; i < NUM_CHECKPOINTS; i++) + m_aBestCpTime[i] = 0; + } + + void Set(float Time, float CpTime[NUM_CHECKPOINTS]) + { + m_BestTime = Time; + for(int i = 0; i < NUM_CHECKPOINTS; i++) + m_aBestCpTime[i] = CpTime[i]; + } + + float m_BestTime; + float m_CurrentTime; + float m_aBestCpTime[NUM_CHECKPOINTS]; +}; + +class IScore +{ + CPlayerData m_aPlayerData[MAX_CLIENTS]; + +public: + virtual ~IScore() {} + + CPlayerData *PlayerData(int ID) { return &m_aPlayerData[ID]; } + + virtual void MapInfo(int ClientID, const char* MapName) = 0; + virtual void MapVote(int ClientID, const char* MapName) = 0; + virtual void CheckBirthday(int ClientID) = 0; + virtual void LoadScore(int ClientID) = 0; + virtual void SaveScore(int ClientID, float Time, float CpTime[NUM_CHECKPOINTS]) = 0; + + virtual void SaveTeamScore(int* ClientIDs, unsigned int Size, float Time) = 0; + + virtual void ShowTop5(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut=1) = 0; + virtual void ShowRank(int ClientID, const char* pName, bool Search=false) = 0; + + virtual void ShowTeamTop5(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut=1) = 0; + virtual void ShowTeamRank(int ClientID, const char* pName, bool Search=false) = 0; + + virtual void ShowTopPoints(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut=1) = 0; + virtual void ShowPoints(int ClientID, const char* pName, bool Search=false) = 0; + + virtual void RandomMap(int ClientID, int stars) = 0; + virtual void RandomUnfinishedMap(int ClientID, int stars) = 0; + + virtual void SaveTeam(int Team, const char* Code, int ClientID, const char* Server) = 0; + virtual void LoadTeam(const char* Code, int ClientID) = 0; +}; + +#endif diff --git a/src/game/server/score/file_score.cpp b/src/game/server/score/file_score.cpp new file mode 100644 index 0000000..1f47ebd --- /dev/null +++ b/src/game/server/score/file_score.cpp @@ -0,0 +1,353 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +/* copyright (c) 2008 rajh and gregwar. Score stuff */ +#include <base/tl/sorted_array.h> + +#include <engine/shared/config.h> +#include <sstream> +#include <fstream> +#include <string.h> +#include "../gamemodes/DDRace.h" +#include "file_score.h" +#include <engine/shared/console.h> + +static LOCK gs_ScoreLock = 0; + +CFileScore::CPlayerScore::CPlayerScore(const char *pName, float Score, + float aCpTime[NUM_CHECKPOINTS]) +{ + str_copy(m_aName, pName, sizeof(m_aName)); + m_Score = Score; + for (int i = 0; i < NUM_CHECKPOINTS; i++) + m_aCpTime[i] = aCpTime[i]; +} + +CFileScore::CFileScore(CGameContext *pGameServer) : + m_pGameServer(pGameServer), m_pServer(pGameServer->Server()) +{ + if (gs_ScoreLock == 0) + gs_ScoreLock = lock_create(); + + Init(); +} + +CFileScore::~CFileScore() +{ + lock_wait(gs_ScoreLock); + + // clear list + m_Top.clear(); + + lock_unlock(gs_ScoreLock); +} + +std::string SaveFile() +{ + std::ostringstream oss; + char aBuf[256]; + str_copy(aBuf, g_Config.m_SvMap, sizeof(aBuf)); + for(int i = 0; i < 256; i++) if(aBuf[i] == '/') aBuf[i] = '-'; + if (g_Config.m_SvScoreFolder[0]) + oss << g_Config.m_SvScoreFolder << "/" << aBuf << "_record.dtb"; + else + oss << g_Config.m_SvMap << "_record.dtb"; + return oss.str(); +} + +void CFileScore::MapInfo(int ClientID, const char* MapName) +{ + // TODO: implement +} + +void CFileScore::MapVote(int ClientID, const char* MapName) +{ + // TODO: implement +} + +void CFileScore::SaveScoreThread(void *pUser) +{ + CFileScore *pSelf = (CFileScore *) pUser; + lock_wait(gs_ScoreLock); + std::fstream f; + f.open(SaveFile().c_str(), std::ios::out); + if (!f.fail()) + { + int t = 0; + for (sorted_array<CPlayerScore>::range r = pSelf->m_Top.all(); + !r.empty(); r.pop_front()) + { + f << r.front().m_aName << std::endl << r.front().m_Score + << std::endl; + if (g_Config.m_SvCheckpointSave) + { + for (int c = 0; c < NUM_CHECKPOINTS; c++) + f << r.front().m_aCpTime[c] << " "; + f << std::endl; + } + t++; + if (t % 50 == 0) + thread_sleep(1); + } + } + f.close(); + lock_unlock(gs_ScoreLock); +} + +void CFileScore::Save() +{ + void *pSaveThread = thread_init(SaveScoreThread, this); + thread_detach(pSaveThread); +} + +void CFileScore::Init() +{ + lock_wait(gs_ScoreLock); + + // create folder if not exist + if (g_Config.m_SvScoreFolder[0]) + fs_makedir(g_Config.m_SvScoreFolder); + + std::fstream f; + f.open(SaveFile().c_str(), std::ios::in); + + while (!f.eof() && !f.fail()) + { + std::string TmpName, TmpScore, TmpCpLine; + std::getline(f, TmpName); + if (!f.eof() && TmpName != "") + { + std::getline(f, TmpScore); + float aTmpCpTime[NUM_CHECKPOINTS] = + { 0 }; + if (g_Config.m_SvCheckpointSave) + { + std::getline(f, TmpCpLine); + char *pTime = strtok((char*) TmpCpLine.c_str(), " "); + int i = 0; + while (pTime != NULL && i < NUM_CHECKPOINTS) + { + aTmpCpTime[i] = atof(pTime); + pTime = strtok(NULL, " "); + i++; + } + } + m_Top.add( + *new CPlayerScore(TmpName.c_str(), atof(TmpScore.c_str()), + aTmpCpTime)); + } + } + f.close(); + lock_unlock(gs_ScoreLock); + + // save the current best score + if (m_Top.size()) + ((CGameControllerDDRace*) GameServer()->m_pController)->m_CurrentRecord = + m_Top[0].m_Score; +} + +CFileScore::CPlayerScore *CFileScore::SearchName(const char *pName, + int *pPosition, bool NoCase) +{ + CPlayerScore *pPlayer = 0; + int Pos = 1; + int Found = 0; + for (sorted_array<CPlayerScore>::range r = m_Top.all(); !r.empty(); + r.pop_front()) + { + if (str_find_nocase(r.front().m_aName, pName)) + { + if (pPosition) + *pPosition = Pos; + if (NoCase) + { + Found++; + pPlayer = &r.front(); + } + if (!strcmp(r.front().m_aName, pName)) + return &r.front(); + } + Pos++; + } + if (Found > 1) + { + if (pPosition) + *pPosition = -1; + return 0; + } + return pPlayer; +} + +void CFileScore::UpdatePlayer(int ID, float Score, + float aCpTime[NUM_CHECKPOINTS]) +{ + const char *pName = Server()->ClientName(ID); + + lock_wait(gs_ScoreLock); + CPlayerScore *pPlayer = SearchScore(ID, 0); + + if (pPlayer) + { + for (int c = 0; c < NUM_CHECKPOINTS; c++) + pPlayer->m_aCpTime[c] = aCpTime[c]; + + pPlayer->m_Score = Score; + str_copy(pPlayer->m_aName, pName, sizeof(pPlayer->m_aName)); + + sort(m_Top.all()); + } + else + m_Top.add(*new CPlayerScore(pName, Score, aCpTime)); + + lock_unlock(gs_ScoreLock); + Save(); +} + +void CFileScore::CheckBirthday(int ClientID) +{ + // TODO: implement +} + +void CFileScore::LoadScore(int ClientID) +{ + CPlayerScore *pPlayer = SearchScore(ClientID, 0); + if (pPlayer) + { + lock_wait(gs_ScoreLock); + lock_unlock(gs_ScoreLock); + Save(); + } + + // set score + if (pPlayer) + PlayerData(ClientID)->Set(pPlayer->m_Score, pPlayer->m_aCpTime); +} + +void CFileScore::SaveTeamScore(int* ClientIDs, unsigned int Size, float Time) +{ + dbg_msg("FileScore", "SaveTeamScore not implemented for FileScore"); +} + +void CFileScore::SaveScore(int ClientID, float Time, + float CpTime[NUM_CHECKPOINTS]) +{ + CConsole* pCon = (CConsole*) GameServer()->Console(); + if (!pCon->m_Cheated || g_Config.m_SvRankCheats) + UpdatePlayer(ClientID, Time, CpTime); +} + +void CFileScore::ShowTop5(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut) +{ + CGameContext *pSelf = (CGameContext *) pUserData; + char aBuf[512]; + pSelf->SendChatTarget(ClientID, "----------- Top 5 -----------"); + for (int i = 0; i < 5; i++) + { + if (i + Debut > m_Top.size()) + break; + CPlayerScore *r = &m_Top[i + Debut - 1]; + str_format(aBuf, sizeof(aBuf), + "%d. %s Time: %d minute(s) %5.2f second(s)", i + Debut, + r->m_aName, (int) r->m_Score / 60, + r->m_Score - ((int) r->m_Score / 60 * 60)); + pSelf->SendChatTarget(ClientID, aBuf); + } + pSelf->SendChatTarget(ClientID, "------------------------------"); +} + +void CFileScore::ShowRank(int ClientID, const char* pName, bool Search) +{ + CPlayerScore *pScore; + int Pos; + char aBuf[512]; + + if (!Search) + pScore = SearchScore(ClientID, &Pos); + else + pScore = SearchName(pName, &Pos, 1); + + if (pScore && Pos > -1) + { + float Time = pScore->m_Score; + char aClientName[128]; + str_format(aClientName, sizeof(aClientName), " (%s)", + Server()->ClientName(ClientID)); + if (g_Config.m_SvHideScore) + str_format(aBuf, sizeof(aBuf), + "Your time: %d minute(s) %5.2f second(s)", (int) Time / 60, + Time - ((int) Time / 60 * 60)); + else + str_format(aBuf, sizeof(aBuf), + "%d. %s Time: %d minute(s) %5.2f second(s), requested by (%s)", Pos, + pScore->m_aName, (int) Time / 60, + Time - ((int) Time / 60 * 60), aClientName); + if (!Search) + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, ClientID); + else + GameServer()->SendChatTarget(ClientID, aBuf); + return; + } + else if (Pos == -1) + str_format(aBuf, sizeof(aBuf), "Several players were found."); + else + str_format(aBuf, sizeof(aBuf), "%s is not ranked", + Search ? pName : Server()->ClientName(ClientID)); + + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::ShowTeamTop5(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Team ranks not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::ShowTeamRank(int ClientID, const char* pName, bool Search) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Team ranks not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::ShowTopPoints(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Team ranks not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::ShowPoints(int ClientID, const char* pName, bool Search) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Points not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::RandomMap(int ClientID, int stars) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Random map not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::RandomUnfinishedMap(int ClientID, int stars) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Random unfinished map not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::SaveTeam(int Team, const char* Code, int ClientID, const char* Server) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Save-function not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} + +void CFileScore::LoadTeam(const char* Code, int ClientID) +{ + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Save-function not supported in file based servers"); + GameServer()->SendChatTarget(ClientID, aBuf); +} diff --git a/src/game/server/score/file_score.h b/src/game/server/score/file_score.h new file mode 100644 index 0000000..ed79894 --- /dev/null +++ b/src/game/server/score/file_score.h @@ -0,0 +1,89 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +/* copyright (c) 2008 rajh and gregwar. Score stuff */ +#ifndef GAME_SERVER_FILESCORE_H +#define GAME_SERVER_FILESCORE_H + +#include <base/tl/sorted_array.h> + +#include "../score.h" + +class CFileScore: public IScore +{ + CGameContext *m_pGameServer; + IServer *m_pServer; + + class CPlayerScore + { + public: + char m_aName[MAX_NAME_LENGTH]; + float m_Score; + float m_aCpTime[NUM_CHECKPOINTS]; + + CPlayerScore() + { + } + ; + CPlayerScore(const char *pName, float Score, + float aCpTime[NUM_CHECKPOINTS]); + + bool operator<(const CPlayerScore& other) + { + return (this->m_Score < other.m_Score); + } + }; + + sorted_array<CPlayerScore> m_Top; + + CGameContext *GameServer() + { + return m_pGameServer; + } + IServer *Server() + { + return m_pServer; + } + + CPlayerScore *SearchScore(int ID, int *pPosition) + { + return SearchName(Server()->ClientName(ID), pPosition, 0); + } + ; + + CPlayerScore *SearchName(const char *pName, int *pPosition, bool MatchCase); + void UpdatePlayer(int ID, float Score, float aCpTime[NUM_CHECKPOINTS]); + + void Init(); + void Save(); + static void SaveScoreThread(void *pUser); + +public: + + CFileScore(CGameContext *pGameServer); + ~CFileScore(); + + virtual void CheckBirthday(int ClientID); + virtual void LoadScore(int ClientID); + virtual void MapInfo(int ClientID, const char* MapName); + virtual void MapVote(int ClientID, const char* MapName); + virtual void SaveScore(int ClientID, float Time, + float CpTime[NUM_CHECKPOINTS]); + virtual void SaveTeamScore(int* ClientIDs, unsigned int Size, float Time); + + virtual void ShowTop5(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut = 1); + virtual void ShowRank(int ClientID, const char* pName, bool Search = false); + + virtual void ShowTeamTop5(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut = 1); + virtual void ShowTeamRank(int ClientID, const char* pName, bool Search = false); + + virtual void ShowTopPoints(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut); + virtual void ShowPoints(int ClientID, const char* pName, bool Search); + virtual void RandomMap(int ClientID, int stars); + virtual void RandomUnfinishedMap(int ClientID, int stars); + virtual void SaveTeam(int Team, const char* Code, int ClientID, const char* Server); + virtual void LoadTeam(const char* Code, int ClientID); +}; + +#endif diff --git a/src/game/server/score/sql_score.cpp b/src/game/server/score/sql_score.cpp new file mode 100644 index 0000000..28b351d --- /dev/null +++ b/src/game/server/score/sql_score.cpp @@ -0,0 +1,1927 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +/* CSqlScore class by Sushi */ +#if defined(CONF_SQL) +#include <string.h> +#include <fstream> +#include <algorithm> + +#include <engine/shared/config.h> +#include "../entities/character.h" +#include "../gamemodes/DDRace.h" +#include "sql_score.h" +#include <engine/shared/console.h> +#include "../save.h" + +static LOCK gs_SqlLock = 0; + +CSqlScore::CSqlScore(CGameContext *pGameServer) : m_pGameServer(pGameServer), + m_pServer(pGameServer->Server()), + m_pDatabase(g_Config.m_SvSqlDatabase), + m_pPrefix(g_Config.m_SvSqlPrefix), + m_pUser(g_Config.m_SvSqlUser), + m_pPass(g_Config.m_SvSqlPw), + m_pIp(g_Config.m_SvSqlIp), + m_Port(g_Config.m_SvSqlPort) +{ + m_pDriver = NULL; + str_copy(m_aMap, g_Config.m_SvMap, sizeof(m_aMap)); + ClearString(m_aMap); + + if(gs_SqlLock == 0) + gs_SqlLock = lock_create(); + + Init(); +} + +CSqlScore::~CSqlScore() +{ + lock_wait(gs_SqlLock); + lock_unlock(gs_SqlLock); + + try + { + delete m_pStatement; + delete m_pConnection; + dbg_msg("SQL", "SQL connection disconnected"); + } + catch (sql::SQLException &e) + { + dbg_msg("SQL", "ERROR: No SQL connection"); + } +} + +bool CSqlScore::Connect() +{ + if (m_pDriver != NULL && m_pConnection != NULL) + { + try + { + // Connect to specific database + m_pConnection->setSchema(m_pDatabase); + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + + dbg_msg("SQL", "ERROR: SQL connection failed"); + return false; + } + return true; + } + + try + { + char aBuf[256]; + + m_pDriver = 0; + m_pConnection = 0; + m_pStatement = 0; + + sql::ConnectOptionsMap connection_properties; + connection_properties["hostName"] = sql::SQLString(m_pIp); + connection_properties["port"] = m_Port; + connection_properties["userName"] = sql::SQLString(m_pUser); + connection_properties["password"] = sql::SQLString(m_pPass); + connection_properties["OPT_RECONNECT"] = true; + + // Create connection + m_pDriver = get_driver_instance(); + m_pConnection = m_pDriver->connect(connection_properties); + + // Create Statement + m_pStatement = m_pConnection->createStatement(); + + // Create database if not exists + if(g_Config.m_SvSqlCreateTables) + { + str_format(aBuf, sizeof(aBuf), "CREATE DATABASE IF NOT EXISTS %s", m_pDatabase); + m_pStatement->execute(aBuf); + } + + // Connect to specific database + m_pConnection->setSchema(m_pDatabase); + dbg_msg("SQL", "SQL connection established"); + return true; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + + dbg_msg("SQL", "ERROR: SQL connection failed"); + return false; + } + catch (const std::exception& ex) + { + // ... + dbg_msg("SQL", "1 %s",ex.what()); + + } + catch (const std::string& ex) + { + // ... + dbg_msg("SQL", "2 %s",ex.c_str()); + } + catch( int ) + { + dbg_msg("SQL", "3 %s"); + } + catch( float ) + { + dbg_msg("SQL", "4 %s"); + } + + catch( char[] ) + { + dbg_msg("SQL", "5 %s"); + } + + catch( char ) + { + dbg_msg("SQL", "6 %s"); + } + catch (...) + { + dbg_msg("SQL", "Unknown Error cause by the MySQL/C++ Connector, my advice compile server_debug and use it"); + + dbg_msg("SQL", "ERROR: SQL connection failed"); + return false; + } + return false; +} + +void CSqlScore::Disconnect() +{ +} + +// create tables... should be done only once +void CSqlScore::Init() +{ + // create connection + if(Connect()) + { + try + { + char aBuf[1024]; + // create tables + if(g_Config.m_SvSqlCreateTables) + { + str_format(aBuf, sizeof(aBuf), "CREATE TABLE IF NOT EXISTS %s_race (Map VARCHAR(128) BINARY NOT NULL, Name VARCHAR(%d) BINARY NOT NULL, Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , Time FLOAT DEFAULT 0, Server CHAR(4), cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, cp25 FLOAT DEFAULT 0, KEY (Map, Name)) CHARACTER SET utf8 ;", m_pPrefix, MAX_NAME_LENGTH); + m_pStatement->execute(aBuf); + + str_format(aBuf, sizeof(aBuf), "CREATE TABLE IF NOT EXISTS %s_teamrace (Map VARCHAR(128) BINARY NOT NULL, Name VARCHAR(%d) BINARY NOT NULL, Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, Time FLOAT DEFAULT 0, ID VARBINARY(16) NOT NULL, KEY Map (Map)) CHARACTER SET utf8 ;", m_pPrefix, MAX_NAME_LENGTH); + m_pStatement->execute(aBuf); + + str_format(aBuf, sizeof(aBuf), "CREATE TABLE IF NOT EXISTS %s_maps (Map VARCHAR(128) BINARY NOT NULL, Server VARCHAR(32) BINARY NOT NULL, Mapper VARCHAR(128) BINARY NOT NULL, Points INT DEFAULT 0, Stars INT DEFAULT 0, Timestamp TIMESTAMP, UNIQUE KEY Map (Map)) CHARACTER SET utf8 ;", m_pPrefix); + m_pStatement->execute(aBuf); + + str_format(aBuf, sizeof(aBuf), "CREATE TABLE IF NOT EXISTS %s_saves (Savegame TEXT CHARACTER SET utf8 BINARY NOT NULL, Map VARCHAR(128) BINARY NOT NULL, Code VARCHAR(128) BINARY NOT NULL, Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, Server CHAR(4), UNIQUE KEY (Map, Code)) CHARACTER SET utf8 ;", m_pPrefix); + m_pStatement->execute(aBuf); + + str_format(aBuf, sizeof(aBuf), "CREATE TABLE IF NOT EXISTS %s_points (Name VARCHAR(%d) BINARY NOT NULL, Points INT DEFAULT 0, UNIQUE KEY Name (Name)) CHARACTER SET utf8 ;", m_pPrefix, MAX_NAME_LENGTH); + m_pStatement->execute(aBuf); + + dbg_msg("SQL", "Tables were created successfully"); + } + + // get the best time + str_format(aBuf, sizeof(aBuf), "SELECT Time FROM %s_race WHERE Map='%s' ORDER BY `Time` ASC LIMIT 0, 1;", m_pPrefix, m_aMap); + m_pResults = m_pStatement->executeQuery(aBuf); + + if(m_pResults->next()) + { + ((CGameControllerDDRace*)GameServer()->m_pController)->m_CurrentRecord = (float)m_pResults->getDouble("Time"); + + dbg_msg("SQL", "Getting best time on server done"); + } + + // delete statement + delete m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Tables were NOT created"); + } + + // disconnect from database + Disconnect(); + } +} + +void CSqlScore::CheckBirthdayThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check strings + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + char aBuf[512]; + + str_format(aBuf, sizeof(aBuf), "select year(Current) - year(Stamp) as YearsAgo from (select CURRENT_TIMESTAMP as Current, min(Timestamp) as Stamp from %s_race WHERE Name='%s') as l where dayofmonth(Current) = dayofmonth(Stamp) and month(Current) = month(Stamp) and year(Current) > year(Stamp);", pData->m_pSqlData->m_pPrefix, pData->m_aName); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + if(pData->m_pSqlData->m_pResults->next()) + { + int yearsAgo = (int)pData->m_pSqlData->m_pResults->getInt("YearsAgo"); + str_format(aBuf, sizeof(aBuf), "Happy DDNet birthday to %s for finishing their first map %d year%s ago!", originalName, yearsAgo, yearsAgo > 1 ? "s" : ""); + pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); + } + + dbg_msg("SQL", "Checking birthday done"); + + // delete statement and results + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not check birthday"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::CheckBirthday(int ClientID) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, Server()->ClientName(ClientID), MAX_NAME_LENGTH); + Tmp->m_pSqlData = this; + + void *CheckThread = thread_init(CheckBirthdayThread, Tmp); + thread_detach(CheckThread); +} + + +// update stuff +void CSqlScore::LoadScoreThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check strings + pData->m_pSqlData->ClearString(pData->m_aName); + + char aBuf[512]; + + str_format(aBuf, sizeof(aBuf), "SELECT * FROM %s_race WHERE Map='%s' AND Name='%s' ORDER BY time ASC LIMIT 1;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + if(pData->m_pSqlData->m_pResults->next()) + { + // get the best time + float time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + pData->m_pSqlData->PlayerData(pData->m_ClientID)->m_BestTime = time; + pData->m_pSqlData->PlayerData(pData->m_ClientID)->m_CurrentTime = time; + if(pData->m_pSqlData->m_pGameServer->m_apPlayers[pData->m_ClientID]) + pData->m_pSqlData->m_pGameServer->m_apPlayers[pData->m_ClientID]->m_Score = -time; + + char aColumn[8]; + if(g_Config.m_SvCheckpointSave) + { + for(int i = 0; i < NUM_CHECKPOINTS; i++) + { + str_format(aColumn, sizeof(aColumn), "cp%d", i+1); + pData->m_pSqlData->PlayerData(pData->m_ClientID)->m_aBestCpTime[i] = (float)pData->m_pSqlData->m_pResults->getDouble(aColumn); + } + } + } + + dbg_msg("SQL", "Getting best time done"); + + // delete statement and results + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not update account"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::LoadScore(int ClientID) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, Server()->ClientName(ClientID), MAX_NAME_LENGTH); + Tmp->m_pSqlData = this; + + void *LoadThread = thread_init(LoadScoreThread, Tmp); + thread_detach(LoadThread); +} + +void CSqlScore::SaveTeamScoreThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlTeamScoreData *pData = (CSqlTeamScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char aBuf[2300]; + char aUpdateID[17]; + aUpdateID[0] = 0; + + for(unsigned int i = 0; i < pData->m_Size; i++) + { + pData->m_pSqlData->ClearString(pData->m_aNames[i]); + } + + str_format(aBuf, sizeof(aBuf), "SELECT Name, l.ID, Time FROM ((SELECT ID FROM %s_teamrace WHERE Map = '%s' AND Name = '%s') as l) LEFT JOIN %s_teamrace as r ON l.ID = r.ID ORDER BY ID;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aNames[0], pData->m_pSqlData->m_pPrefix); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if (pData->m_pSqlData->m_pResults->rowsCount() > 0) + { + char aID[17]; + char aID2[17]; + char aName[64]; + unsigned int Count = 0; + bool ValidNames = true; + + pData->m_pSqlData->m_pResults->first(); + float Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + strcpy(aID, pData->m_pSqlData->m_pResults->getString("ID").c_str()); + + do + { + strcpy(aID2, pData->m_pSqlData->m_pResults->getString("ID").c_str()); + strcpy(aName, pData->m_pSqlData->m_pResults->getString("Name").c_str()); + pData->m_pSqlData->ClearString(aName); + if (str_comp(aID, aID2) != 0) + { + if (ValidNames && Count == pData->m_Size) + { + if (pData->m_Time < Time) + strcpy(aUpdateID, aID); + else + goto end; + break; + } + + Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + ValidNames = true; + Count = 0; + strcpy(aID, aID2); + } + + if (!ValidNames) + continue; + + ValidNames = false; + + for(unsigned int i = 0; i < pData->m_Size; i++) + { + if (str_comp(aName, pData->m_aNames[i]) == 0) + { + ValidNames = true; + Count++; + break; + } + } + } while (pData->m_pSqlData->m_pResults->next()); + + if (ValidNames && Count == pData->m_Size) + { + if (pData->m_Time < Time) + strcpy(aUpdateID, aID); + else + goto end; + } + } + + if (aUpdateID[0]) + { + str_format(aBuf, sizeof(aBuf), "UPDATE %s_teamrace SET Time='%.2f' WHERE ID = '%s';", pData->m_pSqlData->m_pPrefix, pData->m_Time, aUpdateID); + dbg_msg("SQL", aBuf); + pData->m_pSqlData->m_pStatement->execute(aBuf); + } + else + { + pData->m_pSqlData->m_pStatement->execute("SET @id = UUID();"); + + for(unsigned int i = 0; i < pData->m_Size; i++) + { + // if no entry found... create a new one + str_format(aBuf, sizeof(aBuf), "INSERT IGNORE INTO %s_teamrace(Map, Name, Timestamp, Time, ID) VALUES ('%s', '%s', CURRENT_TIMESTAMP(), '%.2f', @id);", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aNames[i], pData->m_Time); + dbg_msg("SQL", aBuf); + pData->m_pSqlData->m_pStatement->execute(aBuf); + } + } + + end: + dbg_msg("SQL", "Updating team time done"); + + // delete results statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not update time"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::MapVote(int ClientID, const char* MapName) +{ + CSqlMapData *Tmp = new CSqlMapData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aMap, MapName, 128); + Tmp->m_pSqlData = this; + + void *VoteThread = thread_init(MapVoteThread, Tmp); + thread_detach(VoteThread); +} + +void CSqlScore::MapVoteThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlMapData *pData = (CSqlMapData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + char originalMap[128]; + strcpy(originalMap,pData->m_aMap); + pData->m_pSqlData->ClearString(pData->m_aMap); + char clearMap[128]; + strcpy(clearMap,pData->m_aMap); + pData->m_pSqlData->FuzzyString(pData->m_aMap); + + try + { + char aBuf[768]; + str_format(aBuf, sizeof(aBuf), "SELECT Map, Server FROM %s_maps WHERE Map LIKE '%s' COLLATE utf8_general_ci ORDER BY CASE WHEN Map = '%s' THEN 0 ELSE 1 END, CASE WHEN Map LIKE '%s%%' THEN 0 ELSE 1 END, LENGTH(Map), Map LIMIT 1;", pData->m_pSqlData->m_pPrefix, pData->m_aMap, clearMap, clearMap); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + CPlayer *pPlayer = pData->m_pSqlData->m_pGameServer->m_apPlayers[pData->m_ClientID]; + + int64 Now = pData->m_pSqlData->Server()->Tick(); + int Timeleft = 0; + + if(!pPlayer) + goto end; + + Timeleft = pPlayer->m_LastVoteCall + pData->m_pSqlData->Server()->TickSpeed()*g_Config.m_SvVoteDelay - Now; + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + str_format(aBuf, sizeof(aBuf), "No map like \"%s\" found. Try adding a '%%' at the start if you don't know the first character. Example: /map %%castle for \"Out of Castle\"", originalMap); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else if(pPlayer->m_LastVoteCall && Timeleft > 0) + { + char aChatmsg[512] = {0}; + str_format(aChatmsg, sizeof(aChatmsg), "You must wait %d seconds before making another vote", (Timeleft/pData->m_pSqlData->Server()->TickSpeed())+1); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aChatmsg); + } + else if(time_get() < pData->m_pSqlData->GameServer()->m_LastMapVote + (time_freq() * g_Config.m_SvVoteMapTimeDelay)) + { + char chatmsg[512] = {0}; + str_format(chatmsg, sizeof(chatmsg), "There's a %d second delay between map-votes, please wait %d seconds.", g_Config.m_SvVoteMapTimeDelay,((pData->m_pSqlData->GameServer()->m_LastMapVote+(g_Config.m_SvVoteMapTimeDelay * time_freq()))/time_freq())-(time_get()/time_freq())); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, chatmsg); + } + else + { + pData->m_pSqlData->m_pResults->next(); + char aMap[128]; + strcpy(aMap, pData->m_pSqlData->m_pResults->getString("Map").c_str()); + char aServer[32]; + strcpy(aServer, pData->m_pSqlData->m_pResults->getString("Server").c_str()); + + for(char *p = aServer; *p; p++) + *p = tolower(*p); + + char aCmd[256]; + str_format(aCmd, sizeof(aCmd), "sv_reset_file types/%s/flexreset.cfg; change_map \"%s\"", aServer, aMap); + char aChatmsg[512]; + str_format(aChatmsg, sizeof(aChatmsg), "'%s' called vote to change server option '%s' (%s)", pData->m_pSqlData->GameServer()->Server()->ClientName(pData->m_ClientID), aMap, "/map"); + + pData->m_pSqlData->GameServer()->m_VoteKick = false; + pData->m_pSqlData->GameServer()->m_VoteSpec = false; + pData->m_pSqlData->GameServer()->m_LastMapVote = time_get(); + pData->m_pSqlData->GameServer()->CallVote(pData->m_ClientID, aMap, aCmd, "/map", aChatmsg); + } + + end: + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not update time"); + } + + pData->m_pSqlData->Disconnect(); + } + + delete pData; + lock_unlock(gs_SqlLock); +} + +void CSqlScore::MapInfo(int ClientID, const char* MapName) +{ + CSqlMapData *Tmp = new CSqlMapData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aMap, MapName, 128); + Tmp->m_pSqlData = this; + + void *InfoThread = thread_init(MapInfoThread, Tmp); + thread_detach(InfoThread); +} + +void CSqlScore::MapInfoThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlMapData *pData = (CSqlMapData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + char originalMap[128]; + strcpy(originalMap,pData->m_aMap); + pData->m_pSqlData->ClearString(pData->m_aMap); + char clearMap[128]; + strcpy(clearMap,pData->m_aMap); + pData->m_pSqlData->FuzzyString(pData->m_aMap); + + try + { + char aBuf[1024]; + str_format(aBuf, sizeof(aBuf), "SELECT l.Map, l.Server, Mapper, Points, Stars, (select count(Name) from %s_race where Map = l.Map) as Finishes, (select count(distinct Name) from %s_race where Map = l.Map) as Finishers, (select round(avg(Time)) from %s_race where Map = l.Map) as Average, UNIX_TIMESTAMP(l.Timestamp) as Stamp, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(l.Timestamp) as Ago FROM (SELECT * FROM %s_maps WHERE Map LIKE '%s' COLLATE utf8_general_ci ORDER BY CASE WHEN Map = '%s' THEN 0 ELSE 1 END, CASE WHEN Map LIKE '%s%%' THEN 0 ELSE 1 END, LENGTH(Map), Map LIMIT 1) as l;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_pPrefix, pData->m_aMap, clearMap, clearMap); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + str_format(aBuf, sizeof(aBuf), "No map like \"%s\" found.", originalMap); + } + else + { + pData->m_pSqlData->m_pResults->next(); + int points = (int)pData->m_pSqlData->m_pResults->getInt("Points"); + int stars = (int)pData->m_pSqlData->m_pResults->getInt("Stars"); + int finishes = (int)pData->m_pSqlData->m_pResults->getInt("Finishes"); + int finishers = (int)pData->m_pSqlData->m_pResults->getInt("Finishers"); + int average = (int)pData->m_pSqlData->m_pResults->getInt("Average"); + char aMap[128]; + strcpy(aMap, pData->m_pSqlData->m_pResults->getString("Map").c_str()); + char aServer[32]; + strcpy(aServer, pData->m_pSqlData->m_pResults->getString("Server").c_str()); + char aMapper[128]; + strcpy(aMapper, pData->m_pSqlData->m_pResults->getString("Mapper").c_str()); + int stamp = (int)pData->m_pSqlData->m_pResults->getInt("Stamp"); + int ago = (int)pData->m_pSqlData->m_pResults->getInt("Ago"); + + char pAgoString[40] = "\0"; + char pReleasedString[60] = "\0"; + if(stamp != 0) + { + agoTimeToString(ago, pAgoString); + str_format(pReleasedString, sizeof(pReleasedString), ", released %s ago", pAgoString); + } + + char pAverageString[60] = "\0"; + if(average > 0) + { + str_format(pAverageString, sizeof(pAverageString), " in %d:%02d average", average / 60, average % 60); + } + + char aStars[20]; + switch(stars) + { + case 0: strcpy(aStars, "✰✰✰✰✰"); break; + case 1: strcpy(aStars, "★✰✰✰✰"); break; + case 2: strcpy(aStars, "★★✰✰✰"); break; + case 3: strcpy(aStars, "★★★✰✰"); break; + case 4: strcpy(aStars, "★★★★✰"); break; + case 5: strcpy(aStars, "★★★★★"); break; + default: aStars[0] = '\0'; + } + + str_format(aBuf, sizeof(aBuf), "\"%s\" by %s on %s (%s, %d %s, %d %s by %d %s%s%s)", aMap, aMapper, aServer, aStars, points, points == 1 ? "point" : "points", finishes, finishes == 1 ? "finish" : "finishes", finishers, finishers == 1 ? "tee" : "tees", pAverageString, pReleasedString); + } + + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not update time"); + } + + pData->m_pSqlData->Disconnect(); + } + + delete pData; + lock_unlock(gs_SqlLock); +} + +void CSqlScore::SaveScoreThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char aBuf[768]; + + // check strings + pData->m_pSqlData->ClearString(pData->m_aName); + + str_format(aBuf, sizeof(aBuf), "SELECT * FROM %s_race WHERE Map='%s' AND Name='%s' ORDER BY time ASC LIMIT 1;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + if(!pData->m_pSqlData->m_pResults->next()) + { + delete pData->m_pSqlData->m_pResults; + + str_format(aBuf, sizeof(aBuf), "SELECT Points FROM %s_maps WHERE Map ='%s'", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() == 1) + { + pData->m_pSqlData->m_pResults->next(); + int points = (int)pData->m_pSqlData->m_pResults->getInt("Points"); + if (points == 1) + str_format(aBuf, sizeof(aBuf), "You earned %d point for finishing this map!", points); + else + str_format(aBuf, sizeof(aBuf), "You earned %d points for finishing this map!", points); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + + str_format(aBuf, sizeof(aBuf), "INSERT INTO %s_points(Name, Points) VALUES ('%s', '%d') ON duplicate key UPDATE Name=VALUES(Name), Points=Points+VALUES(Points);", pData->m_pSqlData->m_pPrefix, pData->m_aName, points); + pData->m_pSqlData->m_pStatement->execute(aBuf); + } + } + + delete pData->m_pSqlData->m_pResults; + + // if no entry found... create a new one + str_format(aBuf, sizeof(aBuf), "INSERT IGNORE INTO %s_race(Map, Name, Timestamp, Time, Server, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, cp21, cp22, cp23, cp24, cp25) VALUES ('%s', '%s', CURRENT_TIMESTAMP(), '%.2f', '%s', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f', '%.2f');", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName, pData->m_Time, g_Config.m_SvSqlServerName, pData->m_aCpCurrent[0], pData->m_aCpCurrent[1], pData->m_aCpCurrent[2], pData->m_aCpCurrent[3], pData->m_aCpCurrent[4], pData->m_aCpCurrent[5], pData->m_aCpCurrent[6], pData->m_aCpCurrent[7], pData->m_aCpCurrent[8], pData->m_aCpCurrent[9], pData->m_aCpCurrent[10], pData->m_aCpCurrent[11], pData->m_aCpCurrent[12], pData->m_aCpCurrent[13], pData->m_aCpCurrent[14], pData->m_aCpCurrent[15], pData->m_aCpCurrent[16], pData->m_aCpCurrent[17], pData->m_aCpCurrent[18], pData->m_aCpCurrent[19], pData->m_aCpCurrent[20], pData->m_aCpCurrent[21], pData->m_aCpCurrent[22], pData->m_aCpCurrent[23], pData->m_aCpCurrent[24]); + dbg_msg("SQL", aBuf); + pData->m_pSqlData->m_pStatement->execute(aBuf); + + dbg_msg("SQL", "Updating time done"); + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not update time"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::SaveScore(int ClientID, float Time, float CpTime[NUM_CHECKPOINTS]) +{ + CConsole* pCon = (CConsole*)GameServer()->Console(); + if(pCon->m_Cheated) + return; + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, Server()->ClientName(ClientID), MAX_NAME_LENGTH); + Tmp->m_Time = Time; + for(int i = 0; i < NUM_CHECKPOINTS; i++) + Tmp->m_aCpCurrent[i] = CpTime[i]; + Tmp->m_pSqlData = this; + + void *SaveThread = thread_init(SaveScoreThread, Tmp); + thread_detach(SaveThread); +} + +void CSqlScore::SaveTeamScore(int* aClientIDs, unsigned int Size, float Time) +{ + CConsole* pCon = (CConsole*)GameServer()->Console(); + if(pCon->m_Cheated) + return; + CSqlTeamScoreData *Tmp = new CSqlTeamScoreData(); + for(unsigned int i = 0; i < Size; i++) + { + Tmp->m_aClientIDs[i] = aClientIDs[i]; + str_copy(Tmp->m_aNames[i], Server()->ClientName(aClientIDs[i]), MAX_NAME_LENGTH); + } + Tmp->m_Size = Size; + Tmp->m_Time = Time; + Tmp->m_pSqlData = this; + + void *SaveTeamThread = thread_init(SaveTeamScoreThread, Tmp); + thread_detach(SaveTeamThread); +} + +void CSqlScore::ShowTeamRankThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check strings + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + // check sort methode + char aBuf[600]; + char aNames[2300]; + aNames[0] = '\0'; + + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + str_format(aBuf, sizeof(aBuf), "SELECT Rank, Name, Time FROM (SELECT Rank, l2.ID FROM ((SELECT ID, (@pos := @pos+1) pos, (@rank := IF(@prev = Time,@rank,@pos)) rank, (@prev := Time) Time FROM (SELECT ID, Time FROM %s_teamrace WHERE Map = '%s' GROUP BY ID ORDER BY Time) as ll) as l2) LEFT JOIN %s_teamrace as r2 ON l2.ID = r2.ID WHERE Map = '%s' AND Name = '%s' ORDER BY Rank LIMIT 1) as l LEFT JOIN %s_teamrace as r ON l.ID = r.ID ORDER BY Name;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName, pData->m_pSqlData->m_pPrefix); + + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + int Rows = pData->m_pSqlData->m_pResults->rowsCount(); + + if(Rows < 1) + { + str_format(aBuf, sizeof(aBuf), "%s has no team ranks", originalName); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + pData->m_pSqlData->m_pResults->first(); + + float Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + int Rank = (int)pData->m_pSqlData->m_pResults->getInt("Rank"); + + for(int Row = 0; Row < Rows; Row++) + { + strcat(aNames, pData->m_pSqlData->m_pResults->getString("Name").c_str()); + pData->m_pSqlData->m_pResults->next(); + + if (Row < Rows - 2) + strcat(aNames, ", "); + else if (Row < Rows - 1) + strcat(aNames, " & "); + } + + pData->m_pSqlData->m_pResults->first(); + + if(g_Config.m_SvHideScore) + { + str_format(aBuf, sizeof(aBuf), "Your team time: %02d:%05.02f", (int)(Time/60), Time-((int)Time/60*60)); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + str_format(aBuf, sizeof(aBuf), "%d. %s Team time: %02d:%05.02f, requested by %s", Rank, aNames, (int)(Time/60), Time-((int)Time/60*60), pData->m_aRequestingPlayer); + pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); + } + } + + dbg_msg("SQL", "Showing teamrank done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show team rank"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowTeamTop5Thread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check sort methode + char aBuf[512]; + + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @previd := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + str_format(aBuf, sizeof(aBuf), "SELECT ID, Name, Time, rank FROM (SELECT r.ID, Name, rank, l.Time FROM ((SELECT ID, rank, Time FROM (SELECT ID, (@pos := IF(@previd = ID,@pos,@pos+1)) pos, (@previd := ID), (@rank := IF(@prev = Time,@rank,@pos)) rank, (@prev := Time) Time FROM (SELECT ID, MIN(Time) as Time FROM %s_teamrace WHERE Map = '%s' GROUP BY ID ORDER BY `Time` ASC) as all_top_times) as a LIMIT %d, 5) as l) LEFT JOIN %s_teamrace as r ON l.ID = r.ID ORDER BY Time ASC, r.ID, Name ASC) as a;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_Num-1, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + // show teamtop5 + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "------- Team Top 5 -------"); + + int Rows = pData->m_pSqlData->m_pResults->rowsCount(); + + if (Rows >= 1) { + char aID[17]; + char aID2[17]; + char aNames[2300]; + int Rank = 0; + float Time = 0; + int aCuts[320]; // 64 * 5 + int CutPos = 0; + + aNames[0] = '\0'; + aCuts[0] = -1; + + pData->m_pSqlData->m_pResults->first(); + strcpy(aID, pData->m_pSqlData->m_pResults->getString("ID").c_str()); + for(int Row = 0; Row < Rows; Row++) + { + strcpy(aID2, pData->m_pSqlData->m_pResults->getString("ID").c_str()); + if (str_comp(aID, aID2) != 0) + { + strcpy(aID, aID2); + aCuts[CutPos++] = Row - 1; + } + pData->m_pSqlData->m_pResults->next(); + } + aCuts[CutPos] = Rows - 1; + + CutPos = 0; + pData->m_pSqlData->m_pResults->first(); + for(int Row = 0; Row < Rows; Row++) + { + strcat(aNames, pData->m_pSqlData->m_pResults->getString("Name").c_str()); + + if (Row < aCuts[CutPos] - 1) + strcat(aNames, ", "); + else if (Row < aCuts[CutPos]) + strcat(aNames, " & "); + + Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + Rank = (float)pData->m_pSqlData->m_pResults->getInt("rank"); + + if (Row == aCuts[CutPos]) + { + str_format(aBuf, sizeof(aBuf), "%d. %s Team Time: %02d:%05.2f", Rank, aNames, (int)(Time/60), Time-((int)Time/60*60)); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + CutPos++; + aNames[0] = '\0'; + } + + pData->m_pSqlData->m_pResults->next(); + } + } + + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "-------------------------------"); + + dbg_msg("SQL", "Showing teamtop5 done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show teamtop5"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowRankThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check strings + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + // check sort methode + char aBuf[600]; + + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + str_format(aBuf, sizeof(aBuf), "SELECT Rank, Name, Time FROM (SELECT Name, (@pos := @pos+1) pos, (@rank := IF(@prev = Time,@rank, @pos)) rank, (@prev := Time) Time FROM (SELECT Name, min(Time) as Time FROM %s_race WHERE Map = '%s' GROUP BY Name ORDER BY `Time` ASC) as a) as b WHERE Name = '%s';", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName); + + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + str_format(aBuf, sizeof(aBuf), "%s is not ranked", originalName); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + pData->m_pSqlData->m_pResults->next(); + + float Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + int Rank = (int)pData->m_pSqlData->m_pResults->getInt("Rank"); + if(g_Config.m_SvHideScore) + { + str_format(aBuf, sizeof(aBuf), "Your time: %02d:%05.2f", (int)(Time/60), Time-((int)Time/60*60)); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + str_format(aBuf, sizeof(aBuf), "%d. %s Time: %02d:%05.2f, requested by %s", Rank, pData->m_pSqlData->m_pResults->getString("Name").c_str(), (int)(Time/60), Time-((int)Time/60*60), pData->m_aRequestingPlayer); + pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); + } + } + + dbg_msg("SQL", "Showing rank done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show rank"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowTeamRank(int ClientID, const char* pName, bool Search) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, pName, MAX_NAME_LENGTH); + Tmp->m_Search = Search; + str_format(Tmp->m_aRequestingPlayer, sizeof(Tmp->m_aRequestingPlayer), "%s", Server()->ClientName(ClientID)); + Tmp->m_pSqlData = this; + + void *TeamRankThread = thread_init(ShowTeamRankThread, Tmp); + thread_detach(TeamRankThread); +} + +void CSqlScore::ShowRank(int ClientID, const char* pName, bool Search) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, pName, MAX_NAME_LENGTH); + Tmp->m_Search = Search; + str_format(Tmp->m_aRequestingPlayer, sizeof(Tmp->m_aRequestingPlayer), "%s", Server()->ClientName(ClientID)); + Tmp->m_pSqlData = this; + + void *RankThread = thread_init(ShowRankThread, Tmp); + thread_detach(RankThread); +} + +void CSqlScore::ShowTop5Thread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check sort methode + char aBuf[512]; + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + str_format(aBuf, sizeof(aBuf), "SELECT Name, Time, rank FROM (SELECT Name, (@pos := @pos+1) pos, (@rank := IF(@prev = Time,@rank, @pos)) rank, (@prev := Time) Time FROM (SELECT Name, min(Time) as Time FROM %s_race WHERE Map = '%s' GROUP BY Name ORDER BY `Time` ASC) as a) as b LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_Num-1); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + // show top5 + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "----------- Top 5 -----------"); + + int Rank = 0; + float Time = 0; + while(pData->m_pSqlData->m_pResults->next()) + { + Time = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + Rank = (float)pData->m_pSqlData->m_pResults->getInt("rank"); + str_format(aBuf, sizeof(aBuf), "%d. %s Time: %02d:%05.2f", Rank, pData->m_pSqlData->m_pResults->getString("Name").c_str(), (int)(Time/60), Time-((int)Time/60*60)); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + //Rank++; + } + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "-------------------------------"); + + dbg_msg("SQL", "Showing top5 done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show top5"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowTimesThread(void *pUser) +{ + lock_wait(gs_SqlLock); + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + char aBuf[512]; + + if(pData->m_Search) // last 5 times of a player + str_format(aBuf, sizeof(aBuf), "SELECT Time, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(Timestamp) as Ago, UNIX_TIMESTAMP(Timestamp) as Stamp FROM %s_race WHERE Map = '%s' AND Name = '%s' ORDER BY Ago ASC LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_aName, pData->m_Num-1); + else// last 5 times of server + str_format(aBuf, sizeof(aBuf), "SELECT Name, Time, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(Timestamp) as Ago, UNIX_TIMESTAMP(Timestamp) as Stamp FROM %s_race WHERE Map = '%s' ORDER BY Ago ASC LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_aMap, pData->m_Num-1); + + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + // show top5 + if(pData->m_pSqlData->m_pResults->rowsCount() == 0) + { + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "There are no times in the specified range"); + goto end; + } + + str_format(aBuf, sizeof(aBuf), "------------ Last Times No %d - %d ------------",pData->m_Num,pData->m_Num + pData->m_pSqlData->m_pResults->rowsCount() - 1); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + + float pTime = 0; + int pSince = 0; + int pStamp = 0; + + while(pData->m_pSqlData->m_pResults->next()) + { + char pAgoString[40] = "\0"; + pSince = (int)pData->m_pSqlData->m_pResults->getInt("Ago"); + pStamp = (int)pData->m_pSqlData->m_pResults->getInt("Stamp"); + pTime = (float)pData->m_pSqlData->m_pResults->getDouble("Time"); + + agoTimeToString(pSince,pAgoString); + + if(pData->m_Search) // last 5 times of a player + { + if(pStamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet + str_format(aBuf, sizeof(aBuf), "%d min %.2f sec, don't know how long ago", (int)(pTime/60), pTime-((int)pTime/60*60)); + else + str_format(aBuf, sizeof(aBuf), "%s ago, %d min %.2f sec", pAgoString,(int)(pTime/60), pTime-((int)pTime/60*60)); + } + else // last 5 times of the server + { + if(pStamp == 0) // stamp is 00:00:00 cause it's an old entry from old times where there where no stamps yet + str_format(aBuf, sizeof(aBuf), "%s, %02d:%05.02f s, don't know when", pData->m_pSqlData->m_pResults->getString("Name").c_str(), (int)(pTime/60), pTime-((int)pTime/60*60)); + else + str_format(aBuf, sizeof(aBuf), "%s, %s ago, %02d:%05.02f s", pData->m_pSqlData->m_pResults->getString("Name").c_str(), pAgoString, (int)(pTime/60), pTime-((int)pTime/60*60)); + } + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "----------------------------------------------------"); + + dbg_msg("SQL", "Showing times done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show times"); + } + end: + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowTeamTop5(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = Debut; + Tmp->m_ClientID = ClientID; + Tmp->m_pSqlData = this; + + void *TeamTop5Thread = thread_init(ShowTeamTop5Thread, Tmp); + thread_detach(TeamTop5Thread); +} + +void CSqlScore::ShowTop5(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = Debut; + Tmp->m_ClientID = ClientID; + Tmp->m_pSqlData = this; + + void *Top5Thread = thread_init(ShowTop5Thread, Tmp); + thread_detach(Top5Thread); +} + +void CSqlScore::ShowTimes(int ClientID, int Debut) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = Debut; + Tmp->m_ClientID = ClientID; + Tmp->m_pSqlData = this; + Tmp->m_Search = false; + + void *TimesThread = thread_init(ShowTimesThread, Tmp); + thread_detach(TimesThread); +} + +void CSqlScore::ShowTimes(int ClientID, const char* pName, int Debut) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = Debut; + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, pName, MAX_NAME_LENGTH); + Tmp->m_pSqlData = this; + Tmp->m_Search = true; + + void *TimesThread = thread_init(ShowTimesThread, Tmp); + thread_detach(TimesThread); +} + +void CSqlScore::FuzzyString(char *pString) +{ + char newString[32*4-1]; + int pos = 0; + + for(int i=0;i<64;i++) + { + if(!pString[i]) + break; + + newString[pos++] = pString[i]; + if (pString[i] != '\\' && str_utf8_isstart(pString[i+1])) + newString[pos++] = '%'; + } + + newString[pos] = '\0'; + strcpy(pString, newString); +} + +// anti SQL injection +void CSqlScore::ClearString(char *pString, int size) +{ + char *newString = (char *)malloc(size * 2 - 1); + int pos = 0; + + for(int i=0;i<size;i++) + { + if(pString[i] == '\\') + { + newString[pos++] = '\\'; + newString[pos++] = '\\'; + } + else if(pString[i] == '\'') + { + newString[pos++] = '\\'; + newString[pos++] = '\''; + } + else if(pString[i] == '"') + { + newString[pos++] = '\\'; + newString[pos++] = '"'; + } + else + { + newString[pos++] = pString[i]; + } + } + + newString[pos] = '\0'; + + strcpy(pString,newString); + free(newString); +} + +void CSqlScore::agoTimeToString(int agoTime, char agoString[]) +{ + char aBuf[20]; + int times[7] = + { + 60 * 60 * 24 * 365 , + 60 * 60 * 24 * 30 , + 60 * 60 * 24 * 7, + 60 * 60 * 24 , + 60 * 60 , + 60 , + 1 + }; + char names[7][6] = + { + "year", + "month", + "week", + "day", + "hour", + "min", + "sec" + }; + + int seconds = 0; + char name[6]; + int count = 0; + int i = 0; + + // finding biggest match + for(i = 0; i<7; i++) + { + seconds = times[i]; + strcpy(name,names[i]); + + count = floor((float)agoTime/(float)seconds); + if(count != 0) + { + break; + } + } + + if(count == 1) + { + str_format(aBuf, sizeof(aBuf), "%d %s", 1 , name); + } + else + { + str_format(aBuf, sizeof(aBuf), "%d %ss", count , name); + } + strcat(agoString,aBuf); + + if (i + 1 < 7) + { + // getting second piece now + int seconds2 = times[i+1]; + char name2[6]; + strcpy(name2,names[i+1]); + + // add second piece if it's greater than 0 + int count2 = floor((float)(agoTime - (seconds * count)) / (float)seconds2); + + if (count2 != 0) + { + if(count2 == 1) + { + str_format(aBuf, sizeof(aBuf), " and %d %s", 1 , name2); + } + else + { + str_format(aBuf, sizeof(aBuf), " and %d %ss", count2 , name2); + } + strcat(agoString,aBuf); + } + } +} + +void CSqlScore::ShowPointsThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + // check strings + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "select Rank, Name, Points from (select (@pos := @pos+1) pos, (@rank := IF(@prev = Points,@rank,@pos)) Rank, Points, Name from (select (@prev := Points) Points, Name from %s_points order by Points desc) as ll) as l where Name = '%s';", pData->m_pSqlData->m_pPrefix, pData->m_aName); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + str_format(aBuf, sizeof(aBuf), "%s has not collected any points so far", originalName); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + pData->m_pSqlData->m_pResults->next(); + int count = (int)pData->m_pSqlData->m_pResults->getInt("Points"); + int rank = (int)pData->m_pSqlData->m_pResults->getInt("rank"); + str_format(aBuf, sizeof(aBuf), "%d. %s Points: %d, requested by %s", rank, pData->m_pSqlData->m_pResults->getString("Name").c_str(), count, pData->m_aRequestingPlayer); + pData->m_pSqlData->GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf, pData->m_ClientID); + } + + dbg_msg("SQL", "Showing points done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show points"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowPoints(int ClientID, const char* pName, bool Search) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, pName, MAX_NAME_LENGTH); + Tmp->m_Search = Search; + str_format(Tmp->m_aRequestingPlayer, sizeof(Tmp->m_aRequestingPlayer), "%s", Server()->ClientName(ClientID)); + Tmp->m_pSqlData = this; + + void *PointsThread = thread_init(ShowPointsThread, Tmp); + thread_detach(PointsThread); +} + +void CSqlScore::ShowTopPointsThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char aBuf[512]; + pData->m_pSqlData->m_pStatement->execute("SET @prev := NULL;"); + pData->m_pSqlData->m_pStatement->execute("SET @rank := 1;"); + pData->m_pSqlData->m_pStatement->execute("SET @pos := 0;"); + str_format(aBuf, sizeof(aBuf), "select Rank, Name, Points from (select (@pos := @pos+1) pos, (@rank := IF(@prev = Points,@rank,@pos)) Rank, Points, Name from (select (@prev := Points) Points, Name from %s_points order by Points desc) as ll) as l LIMIT %d, 5;", pData->m_pSqlData->m_pPrefix, pData->m_Num-1); + + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + // show top points + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "-------- Top Points --------"); + + while(pData->m_pSqlData->m_pResults->next()) + { + str_format(aBuf, sizeof(aBuf), "%d. %s Points: %d", pData->m_pSqlData->m_pResults->getInt("rank"), pData->m_pSqlData->m_pResults->getString("Name").c_str(), pData->m_pSqlData->m_pResults->getInt("Points")); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "-------------------------------"); + + dbg_msg("SQL", "Showing toppoints done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not show toppoints"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::ShowTopPoints(IConsole::IResult *pResult, int ClientID, void *pUserData, int Debut) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = Debut; + Tmp->m_ClientID = ClientID; + Tmp->m_pSqlData = this; + + void *TopPointsThread = thread_init(ShowTopPointsThread, Tmp); + thread_detach(TopPointsThread); +} + +void CSqlScore::RandomMapThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char aBuf[512]; + if(pData->m_Num) + str_format(aBuf, sizeof(aBuf), "select * from %s_maps where Server = \"%s\" and Stars = \"%d\" order by RAND() limit 1;", pData->m_pSqlData->m_pPrefix, g_Config.m_SvServerType, pData->m_Num); + else + str_format(aBuf, sizeof(aBuf), "select * from %s_maps where Server = \"%s\" order by RAND() limit 1;", pData->m_pSqlData->m_pPrefix, g_Config.m_SvServerType); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "No maps found on this server!"); + } + else + { + pData->m_pSqlData->m_pResults->next(); + char aMap[128]; + strcpy(aMap, pData->m_pSqlData->m_pResults->getString("Map").c_str()); + + str_format(aBuf, sizeof(aBuf), "change_map \"%s\"", aMap); + pData->m_pSqlData->GameServer()->Console()->ExecuteLine(aBuf); + } + + dbg_msg("SQL", "Voting random map done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not vote random map"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::RandomUnfinishedMapThread(void *pUser) +{ + lock_wait(gs_SqlLock); + + CSqlScoreData *pData = (CSqlScoreData *)pUser; + + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char originalName[MAX_NAME_LENGTH]; + strcpy(originalName,pData->m_aName); + pData->m_pSqlData->ClearString(pData->m_aName); + + char aBuf[512]; + if(pData->m_Num) + str_format(aBuf, sizeof(aBuf), "select * from %s_maps where Server = \"%s\" and Stars = \"%d\" and not exists (select * from %s_race where Name = \"%s\" and %s_race.Map = %s_maps.Map) order by RAND() limit 1;", pData->m_pSqlData->m_pPrefix, g_Config.m_SvServerType, pData->m_Num, pData->m_pSqlData->m_pPrefix, pData->m_aName, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_pPrefix); + else + str_format(aBuf, sizeof(aBuf), "select * from %s_maps where Server = \"%s\" and not exists (select * from %s_race where Name = \"%s\" and %s_race.Map = %s_maps.Map) order by RAND() limit 1;", pData->m_pSqlData->m_pPrefix, g_Config.m_SvServerType, pData->m_pSqlData->m_pPrefix, pData->m_aName, pData->m_pSqlData->m_pPrefix, pData->m_pSqlData->m_pPrefix); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if(pData->m_pSqlData->m_pResults->rowsCount() != 1) + { + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "You have no unfinished maps on this server!"); + } + else + { + pData->m_pSqlData->m_pResults->next(); + char aMap[128]; + strcpy(aMap, pData->m_pSqlData->m_pResults->getString("Map").c_str()); + + str_format(aBuf, sizeof(aBuf), "change_map \"%s\"", aMap); + pData->m_pSqlData->GameServer()->Console()->ExecuteLine(aBuf); + } + + dbg_msg("SQL", "Voting random unfinished map done"); + + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf); + dbg_msg("SQL", "ERROR: Could not vote random unfinished map"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + + delete pData; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::RandomMap(int ClientID, int stars) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = stars; + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, GameServer()->Server()->ClientName(ClientID), MAX_NAME_LENGTH); + Tmp->m_pSqlData = this; + + void *RandomThread = thread_init(RandomMapThread, Tmp); + thread_detach(RandomThread); +} + +void CSqlScore::RandomUnfinishedMap(int ClientID, int stars) +{ + CSqlScoreData *Tmp = new CSqlScoreData(); + Tmp->m_Num = stars; + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_aName, GameServer()->Server()->ClientName(ClientID), MAX_NAME_LENGTH); + Tmp->m_pSqlData = this; + + void *RandomUnfinishedThread = thread_init(RandomUnfinishedMapThread, Tmp); + thread_detach(RandomUnfinishedThread); +} + +void CSqlScore::SaveTeam(int Team, const char* Code, int ClientID, const char* Server) +{ + if((g_Config.m_SvTeam == 3 || (Team > 0 && Team < MAX_CLIENTS)) && ((CGameControllerDDRace*)(GameServer()->m_pController))->m_Teams.Count(Team) > 0) + { + if(((CGameControllerDDRace*)(GameServer()->m_pController))->m_Teams.GetSaving(Team)) + return; + ((CGameControllerDDRace*)(GameServer()->m_pController))->m_Teams.SetSaving(Team, true); + } + else + { + GameServer()->SendChatTarget(ClientID, "You have to be in a Team (from 1-63)"); + return; + } + + CSqlTeamSave *Tmp = new CSqlTeamSave(); + Tmp->m_Team = Team; + Tmp->m_ClientID = ClientID; + str_copy(Tmp->m_Code, Code, 32); + str_copy(Tmp->m_Server, Server, sizeof(Tmp->m_Server)); + Tmp->m_pSqlData = this; + + void *SaveThread = thread_init(SaveTeamThread, Tmp); + thread_detach(SaveThread); +} + +void CSqlScore::SaveTeamThread(void *pUser) +{ + CSaveTeam* SavedTeam = 0; + CSqlTeamSave *pData = (CSqlTeamSave *)pUser; + + char TeamString[65536]; + int Team = pData->m_Team; + char OriginalCode[32]; + str_copy(OriginalCode, pData->m_Code, sizeof(OriginalCode)); + pData->m_pSqlData->ClearString(pData->m_Code, sizeof(pData->m_Code)); + char Map[128]; + str_copy(Map, g_Config.m_SvMap, 128); + pData->m_pSqlData->ClearString(Map, sizeof(Map)); + + int Num = -1; + + if((g_Config.m_SvTeam == 3 || (Team > 0 && Team < MAX_CLIENTS)) && ((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.Count(Team) > 0) + { + SavedTeam = new CSaveTeam(pData->m_pSqlData->GameServer()->m_pController); + Num = SavedTeam->save(Team); + switch (Num) + { + case 1: + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "You have to be in a Team (from 1-63)"); + break; + case 2: + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "Could not find your Team"); + break; + case 3: + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "Unable to find all Characters"); + break; + case 4: + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "Your team is not started yet"); + break; + } + if(!Num) + { + str_copy(TeamString, SavedTeam->GetString(), sizeof(TeamString)); + pData->m_pSqlData->ClearString(TeamString, sizeof(TeamString)); + } + } + else + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "You have to be in a Team (from 1-63)"); + + lock_wait(gs_SqlLock); + // Connect to database + if(!Num && pData->m_pSqlData->Connect()) + { + try + { + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "select Savegame from %s_saves where Code = '%s' and Map = '%s';", pData->m_pSqlData->m_pPrefix, pData->m_Code, Map); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if (pData->m_pSqlData->m_pResults->rowsCount() == 0) + { + // delete results and statement + delete pData->m_pSqlData->m_pResults; + + char aBuf[65536]; + str_format(aBuf, sizeof(aBuf), "INSERT IGNORE INTO %s_saves(Savegame, Map, Code, Timestamp, Server) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP(), '%s')", pData->m_pSqlData->m_pPrefix, TeamString, Map, pData->m_Code, pData->m_Server); + dbg_msg("SQL", aBuf); + pData->m_pSqlData->m_pStatement->execute(aBuf); + + char aBuf2[256]; + str_format(aBuf2, sizeof(aBuf2), "Team successfully saved. Use '/load %s' to continue", OriginalCode); + pData->m_pSqlData->GameServer()->SendChatTeam(Team, aBuf2); + ((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.KillSavedTeam(Team); + } + else + { + dbg_msg("SQL", "ERROR: This save-code already exists"); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "This save-code already exists"); + } + } + catch (sql::SQLException &e) + { + char aBuf2[256]; + str_format(aBuf2, sizeof(aBuf2), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf2); + dbg_msg("SQL", "ERROR: Could not save the team"); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "MySQL Error: Could not save the team"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + else if(!Num) + { + dbg_msg("SQL", "connection failed"); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "ERROR: Unable to connect to SQL-Server"); + } + + ((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.SetSaving(Team, false); + + delete pData; + if(SavedTeam) + delete SavedTeam; + + lock_unlock(gs_SqlLock); +} + +void CSqlScore::LoadTeam(const char* Code, int ClientID) +{ + CSqlTeamLoad *Tmp = new CSqlTeamLoad(); + str_copy(Tmp->m_Code, Code, 32); + Tmp->m_ClientID = ClientID; + Tmp->m_pSqlData = this; + + void *LoadThread = thread_init(LoadTeamThread, Tmp); + thread_detach(LoadThread); +} + +void CSqlScore::LoadTeamThread(void *pUser) +{ + CSaveTeam* SavedTeam; + CSqlTeamLoad *pData = (CSqlTeamLoad *)pUser; + + SavedTeam = new CSaveTeam(pData->m_pSqlData->GameServer()->m_pController); + + pData->m_pSqlData->ClearString(pData->m_Code, sizeof(pData->m_Code)); + char Map[128]; + str_copy(Map, g_Config.m_SvMap, 128); + pData->m_pSqlData->ClearString(Map, sizeof(Map)); + int Num; + + lock_wait(gs_SqlLock); + // Connect to database + if(pData->m_pSqlData->Connect()) + { + try + { + char aBuf[768]; + str_format(aBuf, sizeof(aBuf), "select Savegame, Server, UNIX_TIMESTAMP(CURRENT_TIMESTAMP)-UNIX_TIMESTAMP(Timestamp) as Ago from %s_saves where Code = '%s' and Map = '%s';", pData->m_pSqlData->m_pPrefix, pData->m_Code, Map); + pData->m_pSqlData->m_pResults = pData->m_pSqlData->m_pStatement->executeQuery(aBuf); + + if (pData->m_pSqlData->m_pResults->rowsCount() > 0) + { + pData->m_pSqlData->m_pResults->first(); + char ServerName[5]; + str_copy(ServerName, pData->m_pSqlData->m_pResults->getString("Server").c_str(), sizeof(ServerName)); + if(str_comp(ServerName, g_Config.m_SvSqlServerName)) + { + str_format(aBuf, sizeof(aBuf), "You have to be on the '%s' server to load this savegame", ServerName); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + goto end; + } + + pData->m_pSqlData->m_pResults->getInt("Ago"); + int since = (int)pData->m_pSqlData->m_pResults->getInt("Ago"); + + if(since < g_Config.m_SvSaveGamesDelay) + { + str_format(aBuf, sizeof(aBuf), "You have to wait %d seconds until you can load this savegame", g_Config.m_SvSaveGamesDelay - since); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + goto end; + } + + Num = SavedTeam->LoadString(pData->m_pSqlData->m_pResults->getString("Savegame").c_str()); + + if(Num) + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "Unable to load savegame: data corrupted"); + else + { + + bool found = false; + for (int i = 0; i < SavedTeam->GetMembersCount(); i++) + { + if(str_comp(SavedTeam->SavedTees[i].GetName(), pData->m_pSqlData->Server()->ClientName(pData->m_ClientID)) == 0) + { found = true; break; } + } + if (!found) + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "You don't belong to this team"); + else + { + + int n; + for(n = 1; n<64; n++) + { + if(((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.Count(n) == 0) + break; + } + + if(((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.Count(n) > 0) + { + n = ((CGameControllerDDRace*)(pData->m_pSqlData->GameServer()->m_pController))->m_Teams.m_Core.Team(pData->m_ClientID); // if all Teams are full your the only one in your team + } + + Num = SavedTeam->load(n); + + if(Num == 1) + { + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "You have to be in a team (from 1-63)"); + } + else if(Num >= 10 && Num < 100) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "Unable to find player: '%s'", SavedTeam->SavedTees[Num-10].GetName()); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else if(Num >= 100) + { + char aBuf[256]; + str_format(aBuf, sizeof(aBuf), "%s is racing right now, Team can't be loaded if a Tee is racing already", SavedTeam->SavedTees[Num-100].GetName()); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, aBuf); + } + else + { + pData->m_pSqlData->GameServer()->SendChatTeam(n, "Loading successfully done"); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "DELETE from %s_saves where Code='%s' and Map='%s';", pData->m_pSqlData->m_pPrefix, pData->m_Code, Map); + pData->m_pSqlData->m_pStatement->execute(aBuf); + } + } + } + } + else + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "No such savegame for this map"); + end: + // delete results and statement + delete pData->m_pSqlData->m_pResults; + } + catch (sql::SQLException &e) + { + char aBuf2[256]; + str_format(aBuf2, sizeof(aBuf2), "MySQL Error: %s", e.what()); + dbg_msg("SQL", aBuf2); + dbg_msg("SQL", "ERROR: Could not load the team"); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "MySQL Error: Could not load the team"); + } + + // disconnect from database + pData->m_pSqlData->Disconnect(); + } + else + { + dbg_msg("SQL", "connection failed"); + pData->m_pSqlData->GameServer()->SendChatTarget(pData->m_ClientID, "ERROR: Unable to connect to SQL-Server"); + } + + delete pData; + delete SavedTeam; + + lock_unlock(gs_SqlLock); +} + +#endif diff --git a/src/game/server/score/sql_score.h b/src/game/server/score/sql_score.h new file mode 100644 index 0000000..3fa68c0 --- /dev/null +++ b/src/game/server/score/sql_score.h @@ -0,0 +1,160 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +/* Based on Race mod stuff and tweaked by GreYFoX@GTi and others to fit our DDRace needs. */ +/* CSqlScore Class by Sushi Tee*/ +#ifndef GAME_SERVER_SQLSCORE_H +#define GAME_SERVER_SQLSCORE_H + +#include <mysql_connection.h> + +#include <cppconn/driver.h> +#include <cppconn/exception.h> +#include <cppconn/statement.h> + +#include "../score.h" + +class CSqlScore: public IScore +{ + CGameContext *m_pGameServer; + IServer *m_pServer; + + sql::Driver *m_pDriver; + sql::Connection *m_pConnection; + sql::Statement *m_pStatement; + sql::ResultSet *m_pResults; + + // copy of config vars + const char* m_pDatabase; + const char* m_pPrefix; + const char* m_pUser; + const char* m_pPass; + const char* m_pIp; + char m_aMap[64]; + int m_Port; + + CGameContext *GameServer() + { + return m_pGameServer; + } + IServer *Server() + { + return m_pServer; + } + + static void MapInfoThread(void *pUser); + static void MapVoteThread(void *pUser); + static void CheckBirthdayThread(void *pUser); + static void LoadScoreThread(void *pUser); + static void SaveScoreThread(void *pUser); + static void SaveTeamScoreThread(void *pUser); + static void ShowRankThread(void *pUser); + static void ShowTop5Thread(void *pUser); + static void ShowTeamRankThread(void *pUser); + static void ShowTeamTop5Thread(void *pUser); + static void ShowTimesThread(void *pUser); + static void ShowPointsThread(void *pUser); + static void ShowTopPointsThread(void *pUser); + static void RandomMapThread(void *pUser); + static void RandomUnfinishedMapThread(void *pUser); + static void SaveTeamThread(void *pUser); + static void LoadTeamThread(void *pUser); + + void Init(); + + bool Connect(); + void Disconnect(); + + void FuzzyString(char *pString); + // anti SQL injection + void ClearString(char *pString, int size = 32); + + void NormalizeMapname(char *pString); + +public: + + CSqlScore(CGameContext *pGameServer); + ~CSqlScore(); + + virtual void CheckBirthday(int ClientID); + virtual void LoadScore(int ClientID); + virtual void MapInfo(int ClientID, const char* MapName); + virtual void MapVote(int ClientID, const char* MapName); + virtual void SaveScore(int ClientID, float Time, + float CpTime[NUM_CHECKPOINTS]); + virtual void SaveTeamScore(int* aClientIDs, unsigned int Size, float Time); + virtual void ShowRank(int ClientID, const char* pName, bool Search = false); + virtual void ShowTeamRank(int ClientID, const char* pName, bool Search = false); + virtual void ShowTimes(int ClientID, const char* pName, int Debut = 1); + virtual void ShowTimes(int ClientID, int Debut = 1); + virtual void ShowTop5(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut = 1); + virtual void ShowTeamTop5(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut = 1); + virtual void ShowPoints(int ClientID, const char* pName, bool Search = false); + virtual void ShowTopPoints(IConsole::IResult *pResult, int ClientID, + void *pUserData, int Debut = 1); + virtual void RandomMap(int ClientID, int stars); + virtual void RandomUnfinishedMap(int ClientID, int stars); + virtual void SaveTeam(int Team, const char* Code, int ClientID, const char* Server); + virtual void LoadTeam(const char* Code, int ClientID); + static void agoTimeToString(int agoTime, char agoString[]); +}; + +struct CSqlMapData +{ + CSqlScore *m_pSqlData; + int m_ClientID; + char m_aMap[128]; +}; + +struct CSqlScoreData +{ + CSqlScore *m_pSqlData; + int m_ClientID; +#if defined(CONF_FAMILY_WINDOWS) + char m_aName[16]; // Don't edit this, or all your teeth will fall http://bugs.mysql.com/bug.php?id=50046 +#else + char m_aName[MAX_NAME_LENGTH * 2 - 1]; +#endif + + float m_Time; + float m_aCpCurrent[NUM_CHECKPOINTS]; + int m_Num; + bool m_Search; + char m_aRequestingPlayer[MAX_NAME_LENGTH]; +}; + +struct CSqlTeamScoreData +{ + CSqlScore *m_pSqlData; + unsigned int m_Size; + int m_aClientIDs[MAX_CLIENTS]; +#if defined(CONF_FAMILY_WINDOWS) + char m_aNames[16][MAX_CLIENTS]; // Don't edit this, or all your teeth will fall http://bugs.mysql.com/bug.php?id=50046 +#else + char m_aNames[MAX_NAME_LENGTH * 2 - 1][MAX_CLIENTS]; +#endif + + float m_Time; + float m_aCpCurrent[NUM_CHECKPOINTS]; + int m_Num; + bool m_Search; + char m_aRequestingPlayer[MAX_NAME_LENGTH]; +}; + +struct CSqlTeamSave +{ + int m_Team; + int m_ClientID; + char m_Code[128]; + char m_Server[5]; + CSqlScore *m_pSqlData; +}; + +struct CSqlTeamLoad +{ + char m_Code[128]; + int m_ClientID; + CSqlScore *m_pSqlData; +}; + +#endif diff --git a/src/game/server/teams.cpp b/src/game/server/teams.cpp new file mode 100644 index 0000000..fea019d --- /dev/null +++ b/src/game/server/teams.cpp @@ -0,0 +1,670 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "teams.h" +#include <engine/shared/config.h> +#include <engine/server/server.h> + +CGameTeams::CGameTeams(CGameContext *pGameContext) : + m_pGameContext(pGameContext) +{ + Reset(); +} + +void CGameTeams::Reset() +{ + m_Core.Reset(); + for (int i = 0; i < MAX_CLIENTS; ++i) + { + m_TeamState[i] = TEAMSTATE_EMPTY; + m_TeeFinished[i] = false; + m_MembersCount[i] = 0; + m_LastChat[i] = 0; + m_TeamLocked[i] = false; + m_IsSaving[i] = false; + } +} + +void CGameTeams::OnCharacterStart(int ClientID) +{ + int Tick = Server()->Tick(); + CCharacter* pStartingChar = Character(ClientID); + if (!pStartingChar) + return; + if (m_Core.Team(ClientID) != TEAM_FLOCK && pStartingChar->m_DDRaceState == DDRACE_FINISHED) + return; + if (m_Core.Team(ClientID) == TEAM_FLOCK + || m_Core.Team(ClientID) == TEAM_SUPER) + { + pStartingChar->m_DDRaceState = DDRACE_STARTED; + pStartingChar->m_StartTime = Tick; + } + else + { + bool Waiting = false; + for (int i = 0; i < MAX_CLIENTS; ++i) + { + if (m_Core.Team(ClientID) == m_Core.Team(i)) + { + CPlayer* pPlayer = GetPlayer(i); + if (pPlayer && pPlayer->IsPlaying() + && GetDDRaceState(pPlayer) == DDRACE_FINISHED) + { + Waiting = true; + pStartingChar->m_DDRaceState = DDRACE_NONE; + + if (m_LastChat[ClientID] + Server()->TickSpeed() + + g_Config.m_SvChatDelay < Tick) + { + char aBuf[128]; + str_format( + aBuf, + sizeof(aBuf), + "%s has finished and didn't go through start yet, wait for him or join another team.", + Server()->ClientName(i)); + GameServer()->SendChatTarget(ClientID, aBuf); + m_LastChat[ClientID] = Tick; + } + if (m_LastChat[i] + Server()->TickSpeed() + + g_Config.m_SvChatDelay < Tick) + { + char aBuf[128]; + str_format( + aBuf, + sizeof(aBuf), + "%s wants to start a new round, kill or walk to start.", + Server()->ClientName(ClientID)); + GameServer()->SendChatTarget(i, aBuf); + m_LastChat[i] = Tick; + } + } + } + } + + if (m_TeamState[m_Core.Team(ClientID)] < TEAMSTATE_STARTED && !Waiting) + { + ChangeTeamState(m_Core.Team(ClientID), TEAMSTATE_STARTED); + for (int i = 0; i < MAX_CLIENTS; ++i) + { + if (m_Core.Team(ClientID) == m_Core.Team(i)) + { + CPlayer* pPlayer = GetPlayer(i); + // TODO: THE PROBLEM IS THAT THERE IS NO CHARACTER SO START TIME CAN'T BE SET! + if (pPlayer && (pPlayer->IsPlaying() || TeamLocked(m_Core.Team(ClientID)))) + { + SetDDRaceState(pPlayer, DDRACE_STARTED); + SetStartTime(pPlayer, Tick); + } + } + } + } + } +} + +void CGameTeams::OnCharacterFinish(int ClientID) +{ + if (m_Core.Team(ClientID) == TEAM_FLOCK + || m_Core.Team(ClientID) == TEAM_SUPER) + { + CPlayer* pPlayer = GetPlayer(ClientID); + if (pPlayer && pPlayer->IsPlaying()) + OnFinish(pPlayer); + } + else + { + m_TeeFinished[ClientID] = true; + + CheckTeamFinished(m_Core.Team(ClientID)); + } +} + +void CGameTeams::CheckTeamFinished(int Team) +{ + if (TeamFinished(Team)) + { + CPlayer *TeamPlayers[MAX_CLIENTS]; + unsigned int PlayersCount = 0; + + for (int i = 0; i < MAX_CLIENTS; ++i) + { + if (Team == m_Core.Team(i)) + { + CPlayer* pPlayer = GetPlayer(i); + if (pPlayer && pPlayer->IsPlaying()) + { + OnFinish(pPlayer); + m_TeeFinished[i] = false; + + TeamPlayers[PlayersCount++] = pPlayer; + } + } + } + + if (PlayersCount > 0) + { + ChangeTeamState(Team, TEAMSTATE_FINISHED); //TODO: Make it better + //ChangeTeamState(Team, TEAMSTATE_OPEN); + OnTeamFinish(TeamPlayers, PlayersCount); + } + } +} + +bool CGameTeams::SetCharacterTeam(int ClientID, int Team) +{ + //Check on wrong parameters. +1 for TEAM_SUPER + if (ClientID < 0 || ClientID >= MAX_CLIENTS || Team < 0 + || Team >= MAX_CLIENTS + 1) + return false; + //You can join to TEAM_SUPER at any time, but any other group you cannot if it started + if (Team != TEAM_SUPER && m_TeamState[Team] > TEAMSTATE_OPEN) + return false; + //No need to switch team if you there + if (m_Core.Team(ClientID) == Team) + return false; + if (!Character(ClientID)) + return false; + //You cannot be in TEAM_SUPER if you not super + if (Team == TEAM_SUPER && !Character(ClientID)->m_Super) + return false; + //if you begin race + if (Character(ClientID)->m_DDRaceState != DDRACE_NONE && Team != TEAM_SUPER) + return false; + + SetForceCharacterTeam(ClientID, Team); + + //GameServer()->CreatePlayerSpawn(Character(id)->m_Core.m_Pos, TeamMask()); + return true; +} + +void CGameTeams::SetForceCharacterTeam(int ClientID, int Team) +{ + int OldTeam = m_Core.Team(ClientID); + + if (Team != m_Core.Team(ClientID)) + ForceLeaveTeam(ClientID); + else + { + m_TeeFinished[ClientID] = false; + if (Count(m_Core.Team(ClientID)) > 0) + m_MembersCount[m_Core.Team(ClientID)]--; + } + + m_Core.Team(ClientID, Team); + + if (m_Core.Team(ClientID) != TEAM_SUPER) + m_MembersCount[m_Core.Team(ClientID)]++; + if (Team != TEAM_SUPER && (m_TeamState[Team] == TEAMSTATE_EMPTY || m_TeamLocked[Team])) + { + if (!m_TeamLocked[Team]) + ChangeTeamState(Team, TEAMSTATE_OPEN); + + if (GameServer()->Collision()->m_NumSwitchers > 0) { + for (int i = 0; i < GameServer()->Collision()->m_NumSwitchers+1; ++i) + { + GameServer()->Collision()->m_pSwitchers[i].m_Status[Team] = GameServer()->Collision()->m_pSwitchers[i].m_Initial; + GameServer()->Collision()->m_pSwitchers[i].m_EndTick[Team] = 0; + GameServer()->Collision()->m_pSwitchers[i].m_Type[Team] = TILE_SWITCHOPEN; + } + } + } + + if (OldTeam != Team) + for (int LoopClientID = 0; LoopClientID < MAX_CLIENTS; ++LoopClientID) + if (GetPlayer(LoopClientID)) + SendTeamsState(LoopClientID); +} + +void CGameTeams::ForceLeaveTeam(int ClientID) +{ + m_TeeFinished[ClientID] = false; + + if (m_Core.Team(ClientID) != TEAM_FLOCK + && m_Core.Team(ClientID) != TEAM_SUPER + && m_TeamState[m_Core.Team(ClientID)] != TEAMSTATE_EMPTY) + { + bool NoOneInOldTeam = true; + for (int i = 0; i < MAX_CLIENTS; ++i) + if (i != ClientID && m_Core.Team(ClientID) == m_Core.Team(i)) + { + NoOneInOldTeam = false; //all good exists someone in old team + break; + } + if (NoOneInOldTeam) + { + m_TeamState[m_Core.Team(ClientID)] = TEAMSTATE_EMPTY; + + // unlock team when last player leaves + SetTeamLock(m_Core.Team(ClientID), false); + } + } + + if (Count(m_Core.Team(ClientID)) > 0) + m_MembersCount[m_Core.Team(ClientID)]--; +} + +int CGameTeams::Count(int Team) const +{ + if (Team == TEAM_SUPER) + return -1; + return m_MembersCount[Team]; +} + +void CGameTeams::ChangeTeamState(int Team, int State) +{ + int OldState = m_TeamState[Team]; + m_TeamState[Team] = State; + onChangeTeamState(Team, State, OldState); +} + +void CGameTeams::onChangeTeamState(int Team, int State, int OldState) +{ + if (OldState != State && State == TEAMSTATE_STARTED) + { + // OnTeamStateStarting + } + if (OldState != State && State == TEAMSTATE_FINISHED) + { + // OnTeamStateFinishing + } +} + +bool CGameTeams::TeamFinished(int Team) +{ + for (int i = 0; i < MAX_CLIENTS; ++i) + if (m_Core.Team(i) == Team && !m_TeeFinished[i]) + return false; + return true; +} + +int64_t CGameTeams::TeamMask(int Team, int ExceptID, int Asker) +{ + int64_t Mask = 0; + + for (int i = 0; i < MAX_CLIENTS; ++i) + { + if (i == ExceptID) + continue; // Explicitly excluded + if (!GetPlayer(i)) + continue; // Player doesn't exist + + if (!(GetPlayer(i)->GetTeam() == -1 || GetPlayer(i)->m_Paused)) + { // Not spectator + if (i != Asker) + { // Actions of other players + if (!Character(i)) + continue; // Player is currently dead + if (!GetPlayer(i)->m_ShowOthers) + { + if (m_Core.GetSolo(Asker)) + continue; // When in solo part don't show others + if (m_Core.GetSolo(i)) + continue; // When in solo part don't show others + if (m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) + continue; // In different teams + } // ShowOthers + } // See everything of yourself + } + else if (GetPlayer(i)->m_SpectatorID != SPEC_FREEVIEW) + { // Spectating specific player + if (GetPlayer(i)->m_SpectatorID != Asker) + { // Actions of other players + if (!Character(GetPlayer(i)->m_SpectatorID)) + continue; // Player is currently dead + if (!GetPlayer(i)->m_ShowOthers) + { + if (m_Core.GetSolo(Asker)) + continue; // When in solo part don't show others + if (m_Core.GetSolo(GetPlayer(i)->m_SpectatorID)) + continue; // When in solo part don't show others + if (m_Core.Team(GetPlayer(i)->m_SpectatorID) != Team && m_Core.Team(GetPlayer(i)->m_SpectatorID) != TEAM_SUPER) + continue; // In different teams + } // ShowOthers + } // See everything of player you're spectating + } + else + { // Freeview + if (GetPlayer(i)->m_SpecTeam) + { // Show only players in own team when spectating + if (m_Core.Team(i) != Team && m_Core.Team(i) != TEAM_SUPER) + continue; // in different teams + } + } + + Mask |= 1LL << i; + } + return Mask; +} + +void CGameTeams::SendTeamsState(int ClientID) +{ + if (g_Config.m_SvTeam == 3) + return; + + if (!m_pGameContext->m_apPlayers[ClientID] || m_pGameContext->m_apPlayers[ClientID]->m_ClientVersion <= VERSION_DDRACE) + return; + + CMsgPacker Msg(NETMSGTYPE_SV_TEAMSSTATE); + + for(unsigned i = 0; i < MAX_CLIENTS; i++) + Msg.AddInt(m_Core.Team(i)); + + Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); +} + +int CGameTeams::GetDDRaceState(CPlayer* Player) +{ + if (!Player) + return DDRACE_NONE; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + return pChar->m_DDRaceState; + return DDRACE_NONE; +} + +void CGameTeams::SetDDRaceState(CPlayer* Player, int DDRaceState) +{ + if (!Player) + return; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + pChar->m_DDRaceState = DDRaceState; +} + +int CGameTeams::GetStartTime(CPlayer* Player) +{ + if (!Player) + return 0; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + return pChar->m_StartTime; + return 0; +} + +void CGameTeams::SetStartTime(CPlayer* Player, int StartTime) +{ + if (!Player) + return; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + pChar->m_StartTime = StartTime; +} + +void CGameTeams::SetCpActive(CPlayer* Player, int CpActive) +{ + if (!Player) + return; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + pChar->m_CpActive = CpActive; +} + +float *CGameTeams::GetCpCurrent(CPlayer* Player) +{ + if (!Player) + return NULL; + + CCharacter* pChar = Player->GetCharacter(); + if (pChar) + return pChar->m_CpCurrent; + return NULL; +} + +void CGameTeams::OnTeamFinish(CPlayer** Players, unsigned int Size) +{ + float time = (float) (Server()->Tick() - GetStartTime(Players[0])) + / ((float) Server()->TickSpeed()); + if (time < 0.000001f) + return; + + bool CallSaveScore = false; + +#if defined(CONF_SQL) + CallSaveScore = g_Config.m_SvUseSQL; +#endif + + int PlayerCIDs[MAX_CLIENTS]; + + for(unsigned int i = 0; i < Size; i++) + { + PlayerCIDs[i] = Players[i]->GetCID(); + + if(g_Config.m_SvRejoinTeam0 && g_Config.m_SvTeam != 3 && (m_Core.Team(Players[i]->GetCID()) >= TEAM_SUPER || !m_TeamLocked[m_Core.Team(Players[i]->GetCID())])) + { + SetForceCharacterTeam(Players[i]->GetCID(), 0); + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "%s joined team 0", + GameServer()->Server()->ClientName(Players[i]->GetCID())); + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + } + + if (CallSaveScore && Size >= 2) + GameServer()->Score()->SaveTeamScore(PlayerCIDs, Size, time); +} + +void CGameTeams::OnFinish(CPlayer* Player) +{ + if (!Player || !Player->IsPlaying()) + return; + //TODO:DDRace:btd: this ugly + float time = (float) (Server()->Tick() - GetStartTime(Player)) + / ((float) Server()->TickSpeed()); + if (time < 0.000001f) + return; + CPlayerData *pData = GameServer()->Score()->PlayerData(Player->GetCID()); + char aBuf[128]; + SetCpActive(Player, -2); + str_format(aBuf, sizeof(aBuf), + "%s finished in: %d minute(s) %5.2f second(s)", + Server()->ClientName(Player->GetCID()), (int) time / 60, + time - ((int) time / 60 * 60)); + if (g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) + GameServer()->SendChatTarget(Player->GetCID(), aBuf); + else + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + + float diff = fabs(time - pData->m_BestTime); + + if (time - pData->m_BestTime < 0) + { + // new record \o/ + Server()->SaveDemo(Player->GetCID(), time); + + if (diff >= 60) + str_format(aBuf, sizeof(aBuf), "New record: %d minute(s) %5.2f second(s) better.", + (int) diff / 60, diff - ((int) diff / 60 * 60)); + else + str_format(aBuf, sizeof(aBuf), "New record: %5.2f second(s) better.", + diff); + if (g_Config.m_SvHideScore || !g_Config.m_SvSaveWorseScores) + GameServer()->SendChatTarget(Player->GetCID(), aBuf); + else + GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf); + } + else if (pData->m_BestTime != 0) // tee has already finished? + { + Server()->StopRecord(Player->GetCID()); + + if (diff <= 0.005) + { + GameServer()->SendChatTarget(Player->GetCID(), + "You finished with your best time."); + } + else + { + if (diff >= 60) + str_format(aBuf, sizeof(aBuf), "%d minute(s) %5.2f second(s) worse, better luck next time.", + (int) diff / 60, diff - ((int) diff / 60 * 60)); + else + str_format(aBuf, sizeof(aBuf), + "%5.2f second(s) worse, better luck next time.", + diff); + GameServer()->SendChatTarget(Player->GetCID(), aBuf); //this is private, sent only to the tee + } + } + else + { + Server()->SaveDemo(Player->GetCID(), time); + } + + bool CallSaveScore = false; +#if defined(CONF_SQL) + CallSaveScore = g_Config.m_SvUseSQL && g_Config.m_SvSaveWorseScores; +#endif + + if (!pData->m_BestTime || time < pData->m_BestTime) + { + // update the score + pData->Set(time, GetCpCurrent(Player)); + CallSaveScore = true; + } + + if (CallSaveScore) + if (g_Config.m_SvNamelessScore || str_comp_num(Server()->ClientName(Player->GetCID()), "nameless tee", + 12) != 0) + GameServer()->Score()->SaveScore(Player->GetCID(), time, + GetCpCurrent(Player)); + + bool NeedToSendNewRecord = false; + // update server best time + if (GameServer()->m_pController->m_CurrentRecord == 0 + || time < GameServer()->m_pController->m_CurrentRecord) + { + // check for nameless + if (g_Config.m_SvNamelessScore || str_comp_num(Server()->ClientName(Player->GetCID()), "nameless tee", + 12) != 0) + { + GameServer()->m_pController->m_CurrentRecord = time; + //dbg_msg("character", "Finish"); + NeedToSendNewRecord = true; + } + } + + SetDDRaceState(Player, DDRACE_FINISHED); + // set player score + if (!pData->m_CurrentTime || pData->m_CurrentTime > time) + { + pData->m_CurrentTime = time; + NeedToSendNewRecord = true; + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (GetPlayer(i) && GetPlayer(i)->m_ClientVersion >= VERSION_DDRACE) + { + if (!g_Config.m_SvHideScore || i == Player->GetCID()) + { + CNetMsg_Sv_PlayerTime Msg; + Msg.m_Time = time * 100.0; + Msg.m_ClientID = Player->GetCID(); + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, i); + } + } + } + } + + if (NeedToSendNewRecord && Player->m_ClientVersion >= VERSION_DDRACE) + { + for (int i = 0; i < MAX_CLIENTS; i++) + { + if (GameServer()->m_apPlayers[i] + && GameServer()->m_apPlayers[i]->m_ClientVersion >= VERSION_DDRACE) + { + GameServer()->SendRecord(i); + } + } + } + + if (Player->m_ClientVersion >= VERSION_DDRACE) + { + CNetMsg_Sv_DDRaceTime Msg; + Msg.m_Time = (int) (time * 100.0f); + Msg.m_Check = 0; + Msg.m_Finish = 1; + + if (pData->m_BestTime) + { + float Diff = (time - pData->m_BestTime) * 100; + Msg.m_Check = (int) Diff; + } + + Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, Player->GetCID()); + } +} + +void CGameTeams::OnCharacterSpawn(int ClientID) +{ + m_Core.SetSolo(ClientID, false); + + if (m_Core.Team(ClientID) >= TEAM_SUPER || !m_TeamLocked[m_Core.Team(ClientID)]) + SetForceCharacterTeam(ClientID, 0); +} + +void CGameTeams::OnCharacterDeath(int ClientID, int Weapon) +{ + m_Core.SetSolo(ClientID, false); + + int Team = m_Core.Team(ClientID); + bool Locked = TeamLocked(Team) && Weapon != WEAPON_GAME; + + if (!Locked) + { + SetForceCharacterTeam(ClientID, 0); + CheckTeamFinished(Team); + } + else + { + SetForceCharacterTeam(ClientID, Team); + + if (GetTeamState(Team) != TEAMSTATE_OPEN) + { + ChangeTeamState(Team, CGameTeams::TEAMSTATE_OPEN); + + char aBuf[512]; + str_format(aBuf, sizeof(aBuf), "Everyone in your locked team was killed because you %s.", Weapon == WEAPON_SELF ? "killed" : "died"); + GameServer()->SendChatTarget(ClientID, aBuf); + str_format(aBuf, sizeof(aBuf), "Everyone in your locked team was killed because '%s' %s.", Server()->ClientName(ClientID), Weapon == WEAPON_SELF ? "killed" : "died"); + + for (int i = 0; i < MAX_CLIENTS; i++) + if(m_Core.Team(i) == Team && i != ClientID && GameServer()->m_apPlayers[i]) + { + GameServer()->m_apPlayers[i]->KillCharacter(WEAPON_SELF); + if (Weapon == WEAPON_SELF) + GameServer()->m_apPlayers[i]->Respawn(true); // spawn the rest of team with weak hook on the killer + GameServer()->SendChatTarget(i, aBuf); + } + } + } +} + +void CGameTeams::SetTeamLock(int Team, bool Lock) +{ + if(Team > TEAM_FLOCK && Team < TEAM_SUPER) + m_TeamLocked[Team] = Lock; +} + +void CGameTeams::KillSavedTeam(int Team) +{ + // Set so that no finish is accidentally given to some of the players + ChangeTeamState(Team, CGameTeams::TEAMSTATE_OPEN); + + for (int i = 0; i < MAX_CLIENTS; i++) + { + if(m_Core.Team(i) == Team && GameServer()->m_apPlayers[i]) + { + // Set so that no finish is accidentally given to some of the players + GameServer()->m_apPlayers[i]->GetCharacter()->m_DDRaceState = DDRACE_NONE; + m_TeeFinished[i] = false; + } + } + + for (int i = 0; i < MAX_CLIENTS; i++) + if(m_Core.Team(i) == Team && GameServer()->m_apPlayers[i]) + GameServer()->m_apPlayers[i]->ThreadKillCharacter(-2); + + ChangeTeamState(Team, CGameTeams::TEAMSTATE_EMPTY); + + // unlock team when last player leaves + SetTeamLock(Team, false); +} diff --git a/src/game/server/teams.h b/src/game/server/teams.h new file mode 100644 index 0000000..ac542e7 --- /dev/null +++ b/src/game/server/teams.h @@ -0,0 +1,120 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_SERVER_TEAMS_H +#define GAME_SERVER_TEAMS_H + +#include <game/teamscore.h> +#include <game/server/gamecontext.h> + +class CGameTeams +{ + int m_TeamState[MAX_CLIENTS]; + int m_MembersCount[MAX_CLIENTS]; + bool m_TeeFinished[MAX_CLIENTS]; + bool m_TeamLocked[MAX_CLIENTS]; + bool m_IsSaving[MAX_CLIENTS]; + + class CGameContext * m_pGameContext; + +public: + enum + { + TEAMSTATE_EMPTY, TEAMSTATE_OPEN, TEAMSTATE_STARTED, TEAMSTATE_FINISHED + }; + + CTeamsCore m_Core; + + CGameTeams(CGameContext *pGameContext); + + //helper methods + CCharacter* Character(int ClientID) + { + return GameServer()->GetPlayerChar(ClientID); + } + CPlayer* GetPlayer(int ClientID) + { + return GameServer()->m_apPlayers[ClientID]; + } + + class CGameContext *GameServer() + { + return m_pGameContext; + } + class IServer *Server() + { + return m_pGameContext->Server(); + } + + void OnCharacterStart(int ClientID); + void OnCharacterFinish(int ClientID); + void OnCharacterSpawn(int ClientID); + void OnCharacterDeath(int ClientID, int Weapon); + + void CheckTeamFinished(int ClientID); + bool SetCharacterTeam(int ClientID, int Team); + + void ChangeTeamState(int Team, int State); + void onChangeTeamState(int Team, int State, int OldState); + + bool TeamFinished(int Team); + + int64_t TeamMask(int Team, int ExceptID = -1, int Asker = -1); + + int Count(int Team) const; + + //need to be very carefull using this method + void SetForceCharacterTeam(int id, int Team); + void ForceLeaveTeam(int id); + + void Reset(); + + void SendTeamsState(int Cid); + void SetTeamLock(int Team, bool Lock); + + int m_LastChat[MAX_CLIENTS]; + + int GetDDRaceState(CPlayer* Player); + int GetStartTime(CPlayer* Player); + float *GetCpCurrent(CPlayer* Player); + void SetDDRaceState(CPlayer* Player, int DDRaceState); + void SetStartTime(CPlayer* Player, int StartTime); + void SetRefreshTime(CPlayer* Player, int RefreshTime); + void SetCpActive(CPlayer* Player, int CpActive); + void OnTeamFinish(CPlayer** Players, unsigned int Size); + void OnFinish(CPlayer* Player); + void KillSavedTeam(int Team); + + bool TeeFinished(int ClientID) + { + return m_TeeFinished[ClientID]; + } + + int GetTeamState(int Team) + { + return m_TeamState[Team]; + } + + bool TeamLocked(int Team) + { + if (Team <= TEAM_FLOCK || Team >= TEAM_SUPER) + return false; + + return m_TeamLocked[Team]; + } + + void SetFinished(int ClientID, bool finished) + { + m_TeeFinished[ClientID] = finished; + } + + void SetSaving(int TeamID, bool Value) + { + m_IsSaving[TeamID] = Value; + } + + bool GetSaving(int TeamID) + { + return m_IsSaving[TeamID]; + } +}; + +#endif diff --git a/src/game/teamscore.cpp b/src/game/teamscore.cpp new file mode 100644 index 0000000..8b227bd --- /dev/null +++ b/src/game/teamscore.cpp @@ -0,0 +1,51 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#include "teamscore.h" + +CTeamsCore::CTeamsCore() +{ + Reset(); +} + +bool CTeamsCore::SameTeam(int ClientID1, int ClientID2) +{ + return m_Team[ClientID1] == m_Team[ClientID2]; +} + +int CTeamsCore::Team(int ClientID) +{ + return m_Team[ClientID]; +} + +void CTeamsCore::Team(int ClientID, int Team) +{ + m_Team[ClientID] = Team; +} + +bool CTeamsCore::CanKeepHook(int ClientID1, int ClientID2) +{ + if (m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) + || ClientID1 == ClientID2) + return true; + return m_Team[ClientID1] == m_Team[ClientID2]; +} + +bool CTeamsCore::CanCollide(int ClientID1, int ClientID2) +{ + if (m_Team[ClientID1] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) || m_Team[ClientID2] == (m_IsDDRace16 ? VANILLA_TEAM_SUPER : TEAM_SUPER) + || ClientID1 == ClientID2) + return true; + if (m_IsSolo[ClientID1] || m_IsSolo[ClientID2]) + return false; + return m_Team[ClientID1] == m_Team[ClientID2]; +} + +void CTeamsCore::Reset() +{ + m_IsDDRace16 = false; + + for (int i = 0; i < MAX_CLIENTS; ++i) + { + m_Team[i] = TEAM_FLOCK; + m_IsSolo[i] = false; + } +} diff --git a/src/game/teamscore.h b/src/game/teamscore.h new file mode 100644 index 0000000..440b1f2 --- /dev/null +++ b/src/game/teamscore.h @@ -0,0 +1,42 @@ +/* (c) Shereef Marzouk. See "licence DDRace.txt" and the readme.txt in the root of the distribution for more information. */ +#ifndef GAME_TEAMSCORE_H +#define GAME_TEAMSCORE_H + +#include <engine/shared/protocol.h> + +enum +{ + TEAM_FLOCK = 0, TEAM_SUPER = MAX_CLIENTS, VANILLA_TEAM_SUPER = VANILLA_MAX_CLIENTS +}; + +class CTeamsCore +{ + int m_Team[MAX_CLIENTS]; + bool m_IsSolo[MAX_CLIENTS]; +public: + bool m_IsDDRace16; + + CTeamsCore(void); + + bool SameTeam(int ClientID1, int ClientID2); + + bool CanKeepHook(int ClientID1, int ClientID2); + bool CanCollide(int ClientID1, int ClientID2); + + int Team(int ClientID); + void Team(int ClientID, int Team); + + void Reset(); + void SetSolo(int ClientID, bool Value) + { + m_IsSolo[ClientID] = Value; + } + + bool GetSolo(int ClientID) + { + return m_IsSolo[ClientID]; + } + ; +}; + +#endif diff --git a/src/game/tuning.h b/src/game/tuning.h new file mode 100644 index 0000000..59a177b --- /dev/null +++ b/src/game/tuning.h @@ -0,0 +1,62 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_TUNING_H +#define GAME_TUNING_H +#undef GAME_TUNING_H // this file will be included several times + +// physics tuning +MACRO_TUNING_PARAM(GroundControlSpeed, ground_control_speed, 10.0f, "Max speed the tee can get on ground") +MACRO_TUNING_PARAM(GroundControlAccel, ground_control_accel, 100.0f / TicksPerSecond, "Acceleration speed on the ground") +MACRO_TUNING_PARAM(GroundFriction, ground_friction, 0.5f, "Friction on the ground") +MACRO_TUNING_PARAM(GroundJumpImpulse, ground_jump_impulse, 13.2f, "Impulse when jumping on ground") +MACRO_TUNING_PARAM(AirJumpImpulse, air_jump_impulse, 12.0f, "Impulse when jumping in air") +MACRO_TUNING_PARAM(AirControlSpeed, air_control_speed, 250.0f / TicksPerSecond, "Max speed the tee can get in the air") +MACRO_TUNING_PARAM(AirControlAccel, air_control_accel, 1.5f, "Acceleration speed in air") +MACRO_TUNING_PARAM(AirFriction, air_friction, 0.95f, "Friction in the air") +MACRO_TUNING_PARAM(HookLength, hook_length, 380.0f, "Length of the hook") +MACRO_TUNING_PARAM(HookFireSpeed, hook_fire_speed, 80.0f, "How fast the hook is fired") +MACRO_TUNING_PARAM(HookDragAccel, hook_drag_accel, 3.0f, "Acceleration when hook is stuck") +MACRO_TUNING_PARAM(HookDragSpeed, hook_drag_speed, 15.0f, "Drag speed of the hook") +MACRO_TUNING_PARAM(Gravity, gravity, 0.5f, "Gravity of the teeworld") + +MACRO_TUNING_PARAM(VelrampStart, velramp_start, 550, "Velocity ramp start") +MACRO_TUNING_PARAM(VelrampRange, velramp_range, 2000, "Velocity ramp range") +MACRO_TUNING_PARAM(VelrampCurvature, velramp_curvature, 1.4f, "Velocity ramp curvature") + +// weapon tuning +MACRO_TUNING_PARAM(GunCurvature, gun_curvature, 1.25f, "Gun curvature") +MACRO_TUNING_PARAM(GunSpeed, gun_speed, 2200.0f, "Gun speed") +MACRO_TUNING_PARAM(GunLifetime, gun_lifetime, 2.0f, "Gun lifetime") + +MACRO_TUNING_PARAM(ShotgunCurvature, shotgun_curvature, 1.25f, "Shotgun curvature") +MACRO_TUNING_PARAM(ShotgunSpeed, shotgun_speed, 2750.0f, "Shotgun speed") +MACRO_TUNING_PARAM(ShotgunSpeeddiff, shotgun_speeddiff, 0.8f, "(UNUSED) Speed difference between shotgun bullets") +MACRO_TUNING_PARAM(ShotgunLifetime, shotgun_lifetime, 0.20f, "Shotgun lifetime") + +MACRO_TUNING_PARAM(GrenadeCurvature, grenade_curvature, 7.0f, "Grenade curvature") +MACRO_TUNING_PARAM(GrenadeSpeed, grenade_speed, 1000.0f, "Grenade speed") +MACRO_TUNING_PARAM(GrenadeLifetime, grenade_lifetime, 2.0f, "Grenade lifetime") + +MACRO_TUNING_PARAM(LaserReach, laser_reach, 800.0f, "How long the laser can reach") +MACRO_TUNING_PARAM(LaserBounceDelay, laser_bounce_delay, 150, "When bouncing, stop the laser this long") +MACRO_TUNING_PARAM(LaserBounceNum, laser_bounce_num, 1000, "How many times the laser can bounce") +MACRO_TUNING_PARAM(LaserBounceCost, laser_bounce_cost, 0, "Remove this much from reach when laser is bouncing") +MACRO_TUNING_PARAM(LaserDamage, laser_damage, 5, "Laser damage") + +MACRO_TUNING_PARAM(PlayerCollision, player_collision, 1, "Enable player collisions") +MACRO_TUNING_PARAM(PlayerHooking, player_hooking, 1, "Enable player vs player hooking") + +//ddnet tuning +MACRO_TUNING_PARAM(JetpackStrength, jetpack_strength, 400.0f, "Jetpack pistol strength") +MACRO_TUNING_PARAM(ShotgunStrength, shotgun_strength, 10.0f, "Shotgun pull strength") +MACRO_TUNING_PARAM(ExplosionStrength, explosion_strength, 6.0f, "Explosion strength (grenade for example)") +MACRO_TUNING_PARAM(HammerStrength, hammer_strength, 1.0f, "Hammer strength") +MACRO_TUNING_PARAM(HookDuration, hook_duration, 1.25f, "Hook duration") + +MACRO_TUNING_PARAM(HammerFireDelay, hammer_fire_delay, 125, "Delay of hammering") +MACRO_TUNING_PARAM(GunFireDelay, gun_fire_delay, 125, "Delay of firing gun" ) +MACRO_TUNING_PARAM(ShotgunFireDelay, shotgun_fire_delay, 500, "Delay of firing shotgun") +MACRO_TUNING_PARAM(GrenadeFireDelay, grenade_fire_delay, 500, "Delay of firing grenade") +MACRO_TUNING_PARAM(LaserFireDelay, laser_fire_delay, 800, "Delay of firing laser rifle") +MACRO_TUNING_PARAM(NinjaFireDelay, ninja_fire_delay, 800, "Delay of firing ninja") +#endif diff --git a/src/game/variables.h b/src/game/variables.h new file mode 100644 index 0000000..10067a6 --- /dev/null +++ b/src/game/variables.h @@ -0,0 +1,238 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VARIABLES_H +#define GAME_VARIABLES_H +#undef GAME_VARIABLES_H // this file will be included several times + +// client +MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict client movements") +MACRO_CONFIG_INT(ClAntiPingLimit, cl_antiping_limit, 0, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Antiping limit (0 to disable)") +MACRO_CONFIG_INT(ClAntiPing, cl_antiping, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Enable antiping, i. e. more aggressive prediction.") +MACRO_CONFIG_INT(ClAntiPingPlayers, cl_antiping_players, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict other player's movement more aggressively (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClAntiPingGrenade, cl_antiping_grenade, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict grenades (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClAntiPingWeapons, cl_antiping_weapons, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict weapon projectiles (only enabled if cl_antiping is set to 1)") +MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show name plates") +MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show name plates disregarding of distance") +MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use team colors for name plates") +MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the name plates from 0 to 100%") +MACRO_CONFIG_INT(ClNameplatesClan, cl_nameplates_clan, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show clan in name plates") +MACRO_CONFIG_INT(ClNameplatesClanSize, cl_nameplates_clan_size, 30, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the clan plates from 0 to 100%") +MACRO_CONFIG_INT(ClTextEntities, cl_text_entities, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Render textual entity data") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup") +MACRO_CONFIG_INT(ClAutoswitchWeaponsOutOfAmmo, cl_autoswitch_weapons_out_of_ammo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon when out of ammo") +#else +MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup") +MACRO_CONFIG_INT(ClAutoswitchWeaponsOutOfAmmo, cl_autoswitch_weapons_out_of_ammo, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon when out of ammo") +#endif + +MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD") +MACRO_CONFIG_INT(ClShowhudHealthAmmo, cl_showhud_healthammo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD (Health + Ammo)") +MACRO_CONFIG_INT(ClShowhudScore, cl_showhud_score, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD (Score)") +MACRO_CONFIG_INT(ClShowRecord, cl_showrecord, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show old style DDRace client records") +MACRO_CONFIG_INT(ClShowChat, cl_showchat, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show chat") +MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show only chat messages from friends") +MACRO_CONFIG_INT(ClShowKillMessages, cl_showkillmessages, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show kill messages") +MACRO_CONFIG_INT(ClShowVotesAfterVoting, cl_show_votes_after_voting, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show votes window after voting") +MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter") +MACRO_CONFIG_INT(ClEyeWheel, cl_eye_wheel, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show eye wheel along together with emotes") +MACRO_CONFIG_INT(ClEyeDuration, cl_eye_duration, 999999, 1, 999999, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long the eyes emotes last") + +MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Load sound files threaded") + +MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Warn about team balance") + +#if defined(__ANDROID__) +MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 800, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") // Disable dynamic camera on Android, screen becomes jerky when you tap joystick +#else +MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 300, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +#endif +MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +#if defined(__ANDROID__) +MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 400, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") // Prevent crosshair from moving out of screen on Android +#else +MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 800, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +#endif + +MACRO_CONFIG_INT(ClDyncam, cl_dyncam, 0, 0, 1, CFGFLAG_CLIENT, "Enable dyncam") +MACRO_CONFIG_INT(ClDyncamMaxDistance, cl_dyncam_max_distance, 1000, 0, 2000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Maximal dynamic camera distance") +MACRO_CONFIG_INT(ClDyncamMousesens, cl_dyncam_mousesens, 0, 0, 100000, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Mouse sens used when dyncam is toggled on") +MACRO_CONFIG_INT(ClDyncamDeadzone, cl_dyncam_deadzone, 300, 1, 1300, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dynamic camera dead zone") +MACRO_CONFIG_INT(ClDyncamFollowFactor, cl_dyncam_follow_factor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dynamic camera follow factor") + +MACRO_CONFIG_INT(EdZoomTarget, ed_zoom_target, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Zoom to the current mouse target") +MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") + +//MACRO_CONFIG_INT(ClFlow, cl_flow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") + +MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") +MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long to show the server message of the day") + +MACRO_CONFIG_STR(ClVersionServer, cl_version_server, 100, "version.teeworlds.com", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to check for new versions") +MACRO_CONFIG_STR(ClDDNetVersionServer, cl_ddnet_version_server, 100, "version.ddnet.tw", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to check for new ddnet versions") +MACRO_CONFIG_STR(ClDDNetUpdateServer, cl_ddnet_update_server, 100, "update.ddnet.tw", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to update new ddnet versions") +MACRO_CONFIG_STR(ClDDNetMapServer, cl_ddnet_maps_server, 100, "maps.ddnet.tw", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to download maps") + +MACRO_CONFIG_STR(ClLanguagefile, cl_languagefile, 255, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "What language file to use") +MACRO_CONFIG_INT(ClVanillaSkinsOnly, cl_vanilla_skins_only, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Only show skins available in Vanilla Teeworlds") +MACRO_CONFIG_INT(ClAutoStatboardScreenshot, cl_auto_statboard_screenshot, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Automatically take game over statboard screenshot") +MACRO_CONFIG_INT(ClAutoStatboardScreenshotMax, cl_auto_statboard_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically created statboard screenshots (0 = no limit)") + +MACRO_CONFIG_INT(ClDefaultZoom, cl_default_zoom, 10, 0, 20, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Default zoom level (10 default, min 0, max 20)") + +MACRO_CONFIG_INT(ClPlayerUseCustomColor, player_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors") +MACRO_CONFIG_INT(ClPlayerColorBody, player_color_body, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player body color") +MACRO_CONFIG_INT(ClPlayerColorFeet, player_color_feet, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player feet color") +MACRO_CONFIG_STR(ClPlayerSkin, player_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin") + +MACRO_CONFIG_INT(UiPage, ui_page, 6, 0, 11, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page") +MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toolbox page") +MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address") +MACRO_CONFIG_INT(UiScale, ui_scale, 100, 50, 150, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface scale") +MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor") + +MACRO_CONFIG_INT(UiColorHue, ui_color_hue, 160, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color hue") +MACRO_CONFIG_INT(UiColorSat, ui_color_sat, 70, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color saturation") +MACRO_CONFIG_INT(UiColorLht, ui_color_lht, 175, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface color lightness") +MACRO_CONFIG_INT(UiColorAlpha, ui_color_alpha, 228, 0, 255, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface alpha") + +MACRO_CONFIG_INT(UiColorizePing, ui_colorize_ping, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Highlight ping") +MACRO_CONFIG_INT(UiColorizeGametype, ui_colorize_gametype, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Highlight gametype") + +MACRO_CONFIG_STR(UiDemoSelected, ui_demo_selected, 256, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Selected demo file") + +MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable clipping") + +// dummy +MACRO_CONFIG_STR(ClDummyName, dummy_name, 16, "brainless tee", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Name of the Dummy") +MACRO_CONFIG_STR(ClDummyClan, dummy_clan, 12, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clan of the Dummy") +MACRO_CONFIG_INT(ClDummyCountry, dummy_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Country of the Dummy") +MACRO_CONFIG_INT(ClDummyUseCustomColor, dummy_use_custom_color, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors") +MACRO_CONFIG_INT(ClDummyColorBody, dummy_color_body, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dummy body color") +MACRO_CONFIG_INT(ClDummyColorFeet, dummy_color_feet, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dummy feet color") +MACRO_CONFIG_STR(ClDummySkin, dummy_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Dummy skin") +MACRO_CONFIG_INT(ClDummy, cl_dummy, 0, 0, 1, CFGFLAG_CLIENT, "0 - player / 1 - dummy") +MACRO_CONFIG_INT(ClDummyHammer, cl_dummy_hammer, 0, 0, 1, CFGFLAG_CLIENT, "Whether dummy is hammering for a hammerfly") +MACRO_CONFIG_INT(ClDummyResetOnSwitch, cl_dummy_resetonswitch, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Whether dummy should stop pressing keys when you switch") +MACRO_CONFIG_INT(ClDummyCopyMoves, cl_dummy_copy_moves, 0, 0, 1, CFGFLAG_CLIENT, "Wether dummy should copy your moves") + +// curl http download +MACRO_CONFIG_INT(ClHTTPConnectTimeoutMs, cl_http_connect_timeout_ms, 2000, 0, 100000, CFGFLAG_CLIENT, "HTTP downloads: timeout for the connect phase in milliseconds (0 to disable)") +MACRO_CONFIG_INT(ClHTTPLowSpeedLimit, cl_http_low_speed_limit, 500, 0, 100000, CFGFLAG_CLIENT, "HTTP downloads: Set low speed limit in bytes per second (0 to disable)") +MACRO_CONFIG_INT(ClHTTPLowSpeedTime, cl_http_low_speed_time, 5, 0, 100000, CFGFLAG_CLIENT, "HTTP downloads: Set low speed limit time period (0 to disable)") + +// headbot +MACRO_CONFIG_INT(ClWeirdControls, cl_weird_controls, 0, 0, 2, CFGFLAG_CLIENT, "0 = normal, 1 = android phone touchscreen, 2 = 180 spin on fire") +MACRO_CONFIG_INT(ClAutoFire, cl_autofire, 0, 0, 2, CFGFLAG_CLIENT, "1 = fire, 2 = hook") +MACRO_CONFIG_INT(ClClientVersionNr, cl_client_version_nr, 19012, 0, 2147483647, CFGFLAG_CLIENT, "client version") +MACRO_CONFIG_INT(ClSpamVersion, cl_spam_version, 0, 0, 1, CFGFLAG_CLIENT, "spam client version") + +// server +MACRO_CONFIG_INT(SvWarmup, sv_warmup, 0, 0, 0, CFGFLAG_SERVER, "Number of seconds to do warmup before round starts") +MACRO_CONFIG_STR(SvMotd, sv_motd, 900, "", CFGFLAG_SERVER, "Message of the day to display for the clients") +MACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SERVER, "Team damage") +MACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, "", CFGFLAG_SERVER, "Maps to rotate between") +MACRO_CONFIG_INT(SvRoundsPerMap, sv_rounds_per_map, 1, 1, 100, CFGFLAG_SERVER, "Number of rounds on each map before rotating") +MACRO_CONFIG_INT(SvRoundSwap, sv_round_swap, 1, 0, 1, CFGFLAG_SERVER, "Swap teams between rounds") +MACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SERVER, "Allow powerups like ninja") +MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 20, 0, 1000, CFGFLAG_SERVER, "Score limit (0 disables)") +MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SERVER, "Time limit in minutes (0 disables)") +MACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 1, CFGFLAG_SERVER, "Tournament mode. When enabled, players joins the server as spectator") +MACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SERVER, "Spam protection") + +MACRO_CONFIG_INT(SvRespawnDelayTDM, sv_respawn_delay_tdm, 3, 0, 10, CFGFLAG_SERVER, "Time needed to respawn after death in tdm gametype") + +MACRO_CONFIG_INT(SvSpectatorSlots, sv_spectator_slots, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Number of slots to reserve for spectators") +MACRO_CONFIG_INT(SvTeambalanceTime, sv_teambalance_time, 1, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before autobalancing teams") +MACRO_CONFIG_INT(SvInactiveKickTime, sv_inactivekick_time, 0, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before taking care of inactive players") +MACRO_CONFIG_INT(SvInactiveKick, sv_inactivekick, 0, 0, 2, CFGFLAG_SERVER, "How to deal with inactive players (0=move to spectator, 1=move to free spectator slot/kick, 2=kick)") + +MACRO_CONFIG_INT(SvStrictSpectateMode, sv_strict_spectate_mode, 0, 0, 1, CFGFLAG_SERVER, "Restricts information in spectator mode") +MACRO_CONFIG_INT(SvVoteSpectate, sv_vote_spectate, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to move players to spectators") +MACRO_CONFIG_INT(SvVoteSpectateRejoindelay, sv_vote_spectate_rejoindelay, 3, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before a player can rejoin after being moved to spectators by vote") +MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to kick players") +MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Minimum number of players required to start a kick vote") +MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time in seconds to ban a player if kicked by vote. 0 makes it just use kick") +MACRO_CONFIG_INT(SvJoinVoteDelay, sv_join_vote_delay, 1, 0, 1, CFGFLAG_SERVER, "Add a delay before recently joined players can vote") +MACRO_CONFIG_INT(SvOldTeleportWeapons, sv_old_teleport_weapons, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Teleporting of all weapons (deprecated, use special entities instead)"); +MACRO_CONFIG_INT(SvOldTeleportHook, sv_old_teleport_hook, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Hook through teleporter (deprecated, use special entities instead)"); +MACRO_CONFIG_INT(SvTeleportHoldHook, sv_teleport_hold_hook, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Hold hook when teleported"); +MACRO_CONFIG_INT(SvTeleportLoseWeapons, sv_teleport_lose_weapons, 0, 0, 1, CFGFLAG_SERVER|CFGFLAG_GAME, "Lose weapons when teleported (useful for some race maps)"); + +MACRO_CONFIG_INT(SvMapUpdateRate, sv_mapupdaterate, 5, 1, 100, CFGFLAG_SERVER, "64 player id <-> vanilla id players map update rate") + +MACRO_CONFIG_INT(SvSkinStealAction, sv_skinstealaction, 0, 0, 1, CFGFLAG_SERVER, "How to punish skin stealing (currently only 1 = force pinky)") + +MACRO_CONFIG_STR(SvServerType, sv_server_type, 64, "none", CFGFLAG_SERVER, "Type of the server (novice, moderate, ...)") + +MACRO_CONFIG_INT(SvSendVotesPerTick, sv_send_votes_per_tick, 5, 1, 15, CFGFLAG_SERVER, "Number of vote options being send per tick") + +MACRO_CONFIG_INT(SvRescue, sv_rescue, 0, 0, 1, CFGFLAG_SERVER, "Allow /rescue command so players can teleport themselves out of freeze") +MACRO_CONFIG_INT(SvRescueDelay, sv_rescue_delay, 5, 0, 1000, CFGFLAG_SERVER, "Number of seconds inbetween two rescues") + +// WarioWare +MACRO_CONFIG_INT(WwForceMicrogame, ww_force_microgame, -1, -1, 12, CFGFLAG_SERVER, "force a specific microgame to always play") +MACRO_CONFIG_INT(WwMaxRounds, ww_max_rounds, 20, 1, 200, CFGFLAG_SERVER, "maximum microgame rounds, speedup halfway there, boss stage on final round") + +MACRO_CONFIG_INT(WwSndWaiting1_Offset, ww_snd_waiting1_offset, 1000, 0, 2147483647, CFGFLAG_SERVER, "'waiting for players 1' music offset in ms") +MACRO_CONFIG_INT(WwSndWaiting1_Length, ww_snd_waiting1_length, 48000, 0, 2147483647, CFGFLAG_SERVER, "'waiting for players 1' music length in ms") +MACRO_CONFIG_INT(WwSndWaiting2_Offset, ww_snd_waiting2_offset, 51000, 0, 2147483647, CFGFLAG_SERVER, "'waiting for players 2' music offset in ms") +MACRO_CONFIG_INT(WwSndWaiting2_Length, ww_snd_waiting2_length, 57500, 0, 2147483647, CFGFLAG_SERVER, "'waiting for players 2' music length in ms") +MACRO_CONFIG_INT(WwSndJingle_Offset, ww_snd_jingle_offset, 111000, 0, 2147483647, CFGFLAG_SERVER, "jingle music offset in ms") +MACRO_CONFIG_INT(WwSndJingle_Length, ww_snd_jingle_length, 2000, 0, 2147483647, CFGFLAG_SERVER, "jingle music length in ms") +MACRO_CONFIG_INT(WwSndWin_Offset, ww_snd_win_offset, 115000, 0, 2147483647, CFGFLAG_SERVER, "win music offset in ms") +MACRO_CONFIG_INT(WwSndWin_Length, ww_snd_win_length, 2000, 0, 2147483647, CFGFLAG_SERVER, "win music length in ms") +MACRO_CONFIG_INT(WwSndLose_Offset, ww_snd_lose_offset, 119000, 0, 2147483647, CFGFLAG_SERVER, "lose music offset in ms") +MACRO_CONFIG_INT(WwSndLose_Length, ww_snd_lose_length, 2000, 0, 2147483647, CFGFLAG_SERVER, "lose music length in ms") +MACRO_CONFIG_INT(WwSndSpeedUp_Offset, ww_snd_speedup_offset, 123000, 0, 2147483647, CFGFLAG_SERVER, "speed up music offset in ms") +MACRO_CONFIG_INT(WwSndSpeedUp_Length, ww_snd_speedup_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "speed up music length in ms") +MACRO_CONFIG_INT(WwSndJingleFast_Offset, ww_snd_jinglefast_offset, 129000, 0, 2147483647, CFGFLAG_SERVER, "fast jingle music offset in ms") +MACRO_CONFIG_INT(WwSndJingleFast_Length, ww_snd_jinglefast_length, 1800, 0, 2147483647, CFGFLAG_SERVER, "fast jingle music length in ms") +MACRO_CONFIG_INT(WwSndWinFast_Offset, ww_snd_winfast_offset, 132000, 0, 2147483647, CFGFLAG_SERVER, "fast win music offset in ms") +MACRO_CONFIG_INT(WwSndWinFast_Length, ww_snd_winfast_length, 1800, 0, 2147483647, CFGFLAG_SERVER, "fast win music length in ms") +MACRO_CONFIG_INT(WwSndLoseFast_Offset, ww_snd_losefast_offset, 135000, 0, 2147483647, CFGFLAG_SERVER, "fast lose music offset in ms") +MACRO_CONFIG_INT(WwSndLoseFast_Length, ww_snd_losefast_length, 1800, 0, 2147483647, CFGFLAG_SERVER, "fast lose music length in ms") +MACRO_CONFIG_INT(WwSndBoss_Offset, ww_snd_boss_offset, 138000, 0, 2147483647, CFGFLAG_SERVER, "fast lose music offset in ms") +MACRO_CONFIG_INT(WwSndBoss_Length, ww_snd_boss_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "fast lose music length in ms") +MACRO_CONFIG_INT(WwSndFinalLose_Offset, ww_snd_finallose_offset, 500000, 0, 2147483647, CFGFLAG_SERVER, "fast lose music offset in ms") +MACRO_CONFIG_INT(WwSndFinalLose_Length, ww_snd_finallose_length, 9800, 0, 2147483647, CFGFLAG_SERVER, "fast lose music length in ms") +MACRO_CONFIG_INT(WwSndFinalWin_Offset, ww_snd_finalwin_offset, 510000, 0, 2147483647, CFGFLAG_SERVER, "fast lose music offset in ms") +MACRO_CONFIG_INT(WwSndFinalWin_Length, ww_snd_finalwin_length, 9800, 0, 2147483647, CFGFLAG_SERVER, "fast lose music length in ms") + +MACRO_CONFIG_INT(WwSndMgKamikaze_Offset, ww_snd_mg_kamikaze_offset, 154000, 0, 2147483647, CFGFLAG_SERVER, "kamikaze microgame music offset in ms") +MACRO_CONFIG_INT(WwSndMgKamikaze_Length, ww_snd_mg_kamikaze_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "kamikaze microgame music length in ms") +MACRO_CONFIG_INT(WwSndMgAnswer1_Offset, ww_snd_mg_answer1_offset, 160000, 0, 2147483647, CFGFLAG_SERVER, "math answer 1 music offset in ms") +MACRO_CONFIG_INT(WwSndMgAnswer1_Length, ww_snd_mg_answer1_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "math answer 1 music length in ms") +MACRO_CONFIG_INT(WwSndMgAnswer2_Offset, ww_snd_mg_answer2_offset, 166000, 0, 2147483647, CFGFLAG_SERVER, "math answer 2 music offset in ms") +MACRO_CONFIG_INT(WwSndMgAnswer2_Length, ww_snd_mg_answer2_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "math answer 2 music length in ms") +MACRO_CONFIG_INT(WwSndMgDontMove_Offset, ww_snd_mg_dontmove_offset, 172000, 0, 2147483647, CFGFLAG_SERVER, "'don't move' microgame music offset in ms") +MACRO_CONFIG_INT(WwSndMgDontMove_Length, ww_snd_mg_dontmove_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "'don't move' microgame music length in ms") +MACRO_CONFIG_INT(WwSndMgHitEnemy_Offset, ww_snd_mg_hitenemy_offset, 178000, 0, 2147483647, CFGFLAG_SERVER, "hit an enemy music offset in ms") +MACRO_CONFIG_INT(WwSndMgHitEnemy_Length, ww_snd_mg_hitenemy_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "hit an enemy music length in ms") +MACRO_CONFIG_INT(WwSndMgGrenadeJump_Offset, ww_snd_mg_grenadejump_offset, 184000, 0, 2147483647, CFGFLAG_SERVER, "grenade jump music offset in ms") +MACRO_CONFIG_INT(WwSndMgGrenadeJump_Length, ww_snd_mg_grenadejump_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "grenade jump music length in ms") +MACRO_CONFIG_INT(WwSndMgSimonSays_Offset, ww_snd_mg_simonsays_offset, 190000, 0, 2147483647, CFGFLAG_SERVER, "simon says music offset in ms") +MACRO_CONFIG_INT(WwSndMgSimonSays_Length, ww_snd_mg_simonsays_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "simon says music length in ms") +MACRO_CONFIG_INT(WwSndMgGetToEnd_Offset, ww_snd_mg_gettoend_offset, 196000, 0, 2147483647, CFGFLAG_SERVER, "get to end music offset in ms") +MACRO_CONFIG_INT(WwSndMgGetToEnd_Length, ww_snd_mg_gettoend_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "get to end music length in ms") +MACRO_CONFIG_INT(WwSndMgFightStayAlive_Offset, ww_snd_mg_fightstayalive_offset, 202000, 0, 2147483647, CFGFLAG_SERVER, "fight and stay alive music offset in ms") +MACRO_CONFIG_INT(WwSndMgFightStayAlive_Length, ww_snd_mg_fightstayalive_length, 15000, 0, 2147483647, CFGFLAG_SERVER, "fight and stay alive music length in ms") +MACRO_CONFIG_INT(WwSndMgAvoidTrain_Offset, ww_snd_mg_avoidtrain_offset, 220000, 0, 2147483647, CFGFLAG_SERVER, "avoid the train music offset in ms") +MACRO_CONFIG_INT(WwSndMgAvoidTrain_Length, ww_snd_mg_avoidtrain_length, 5500, 0, 2147483647, CFGFLAG_SERVER, "avoid the train music length in ms") +MACRO_CONFIG_INT(WwSndMgTouchSky_Offset, ww_snd_mg_touchsky_offset, 196000, 0, 2147483647, CFGFLAG_SERVER, "touch the sky microgame music offset in ms") +MACRO_CONFIG_INT(WwSndMgTouchSky_Length, ww_snd_mg_touchsky_length, 10000, 0, 2147483647, CFGFLAG_SERVER, "touch the sky microgame music length in ms") +MACRO_CONFIG_INT(WwSndMgGetOnPlatform_Offset, ww_snd_mg_getonplatform_offset, 1000, 0, 2147483647, CFGFLAG_SERVER, "get on a platform music offset in ms") +MACRO_CONFIG_INT(WwSndMgGetOnPlatform_Length, ww_snd_mg_getonplatform_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "get on a platform music length in ms") +MACRO_CONFIG_INT(WwSndMgGetOnPlatform2_Offset, ww_snd_mg_getonplatform2_offset, 196000, 0, 2147483647, CFGFLAG_SERVER, "get on the platform music offset in ms") +MACRO_CONFIG_INT(WwSndMgGetOnPlatform2_Length, ww_snd_mg_getonplatform2_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "get on the platform music length in ms") +MACRO_CONFIG_INT(WwSndMgHitTheTarget_Offset, ww_snd_mg_hitthetarget_offset, 1000, 0, 2147483647, CFGFLAG_SERVER, "hit the target music offset in ms") +MACRO_CONFIG_INT(WwSndMgHitTheTarget_Length, ww_snd_mg_hitthetarget_length, 4000, 0, 2147483647, CFGFLAG_SERVER, "hit the target music length in ms") +MACRO_CONFIG_INT(WwSndMgTileColors_Offset, ww_snd_mg_tilecolors_offset, 1000, 0, 2147483647, CFGFLAG_SERVER, "tile colors music offset in ms") +MACRO_CONFIG_INT(WwSndMgTileColors_Length, ww_snd_mg_tilecolors_length, 8000, 0, 2147483647, CFGFLAG_SERVER, "tile colors music length in ms") + +// debug + +MACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, "") +MACRO_CONFIG_INT(DbgTuning, dbg_tuning, 0, 0, 1, CFGFLAG_CLIENT, "") +#endif diff --git a/src/game/version.h b/src/game/version.h new file mode 100644 index 0000000..a5ec750 --- /dev/null +++ b/src/game/version.h @@ -0,0 +1,9 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VERSION_H +#define GAME_VERSION_H +#include "generated/nethash.cpp" +#define GAME_VERSION "0.6.3, 9.3.1" +#define GAME_NETVERSION "0.6 626fce9a778df4d4" +static const char GAME_RELEASE_VERSION[8] = "9.3.1"; +#endif diff --git a/src/game/voting.h b/src/game/voting.h new file mode 100644 index 0000000..61d8614 --- /dev/null +++ b/src/game/voting.h @@ -0,0 +1,30 @@ +/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ +/* If you are missing that file, acquire a complete release at teeworlds.com. */ +#ifndef GAME_VOTING_H +#define GAME_VOTING_H + +enum +{ + VOTE_DESC_LENGTH=64, + VOTE_CMD_LENGTH=512, + VOTE_REASON_LENGTH=16, + + MAX_VOTE_OPTIONS=8192, +}; + +struct CVoteOptionClient +{ + CVoteOptionClient *m_pNext; + CVoteOptionClient *m_pPrev; + char m_aDescription[VOTE_DESC_LENGTH]; +}; + +struct CVoteOptionServer +{ + CVoteOptionServer *m_pNext; + CVoteOptionServer *m_pPrev; + char m_aDescription[VOTE_DESC_LENGTH]; + char m_aCommand[1]; +}; + +#endif diff --git a/src/osx/notification.h b/src/osx/notification.h new file mode 100644 index 0000000..ce32f9b --- /dev/null +++ b/src/osx/notification.h @@ -0,0 +1,10 @@ +#ifndef NOTIFICATION_H +#define NOTIFICATION_H + +class CNotification +{ + public: + static void notify(const char *pTitle, const char *pMsg); +}; + +#endif // NOTIFICATION_H diff --git a/src/osx/notification.m b/src/osx/notification.m new file mode 100644 index 0000000..e0aa39e --- /dev/null +++ b/src/osx/notification.m @@ -0,0 +1,19 @@ +#import <Foundation/Foundation.h> +#import <Foundation/NSUserNotification.h> +#import <Cocoa/Cocoa.h> +#import "notification.h" + +void CNotification::notify(const char *pTitle, const char *pMsg) +{ + NSString* title = [NSString stringWithCString:pTitle encoding:NSUTF8StringEncoding]; + NSString* msg = [NSString stringWithCString:pMsg encoding:NSUTF8StringEncoding]; + + NSUserNotification *notification = [[NSUserNotification alloc] autorelease]; + notification.title = title; + notification.informativeText = msg; + notification.soundName = NSUserNotificationDefaultSoundName; + + [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; + + [NSApp requestUserAttention:NSInformationalRequest]; // use NSCriticalRequest to annoy the user (doesn't stop bouncing) +} diff --git a/src/osxlaunch/client.h b/src/osxlaunch/client.h new file mode 100644 index 0000000..450b854 --- /dev/null +++ b/src/osxlaunch/client.h @@ -0,0 +1,14 @@ +#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> + + Feel free to customize this file to suit your needs +*/ + +#import <Cocoa/Cocoa.h> + +@interface SDLMain : NSObject +@end +#endif diff --git a/src/osxlaunch/client.m b/src/osxlaunch/client.m new file mode 100644 index 0000000..0513381 --- /dev/null +++ b/src/osxlaunch/client.m @@ -0,0 +1,372 @@ +/* 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 +*/ + +#import <SDL.h> +#import "client.h" +#import <sys/param.h> /* for MAXPATHLEN */ +#import <unistd.h> + +/* For some reaon, Apple removed setAppleMenu from the headers in 10.4, + but the method still is there and works. To avoid warnings, we declare + it ourselves here. */ +@interface NSApplication(SDL_Missing_Methods) +- (void)setAppleMenu:(NSMenu *)menu; +@end + +/* Use this flag to determine whether we use SDLMain.nib or not */ +#define SDL_USE_NIB_FILE 0 + +/* Use this flag to determine whether we use CPS (docking) or not */ +#define SDL_USE_CPS 1 +#ifdef SDL_USE_CPS +/* Portions of CPS.h */ +typedef struct CPSProcessSerNum +{ + UInt32 lo; + UInt32 hi; +} CPSProcessSerNum; + +extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); +extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); +extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); + +#endif /* SDL_USE_CPS */ + +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; +} + +#if SDL_USE_NIB_FILE +/* A helper category for NSString */ +@interface NSString (ReplaceSubString) +- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString; +@end +#endif + +@interface SDLApplication : NSApplication +@end + +@implementation SDLApplication +/* 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); +} +@end + +/* The main class of the application, the application's delegate */ +@implementation SDLMain + +/* Set the working directory to the .app's parent directory */ +- (void) setupWorkingDirectory:(BOOL)shouldChdir +{ + NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; + [[NSFileManager defaultManager] changeCurrentDirectoryPath:resourcePath]; +} + +#if SDL_USE_NIB_FILE + +/* 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 ]; +} + +#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]; +} + +/* 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]; +} + +/* Replacement for NSApplicationMain */ +static void CustomApplicationMain (int argc, char **argv) +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + SDLMain *sdlMain; + + /* 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]; + } +#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]; +} + +#endif + + +/* + * 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. + * + * 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]. + * + * This message may be received multiple times to open several docs on launch. + * + * This message is ignored once the app's mainline has been called. + */ +- (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; +} + + +/* Called when the internal event loop has just started running */ +- (void) applicationDidFinishLaunching: (NSNotification *) note +{ + int status; + + /* 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()]; +#endif + + /* Hand off to main application code */ + gCalledAppMainline = TRUE; + status = SDL_main (gArgc, gArgv); + + /* We're done, thank you for playing */ + exit(status); +} +@end + + +@implementation NSString (ReplaceSubString) + +- (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; +} + +@end + +#ifdef 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; + } + +#if SDL_USE_NIB_FILE + [SDLApplication poseAsClass:[NSApplication class]]; + NSApplicationMain (argc, argv); +#else + CustomApplicationMain (argc, argv); +#endif + + return 0; +} diff --git a/src/osxlaunch/server.m b/src/osxlaunch/server.m new file mode 100644 index 0000000..e542ff1 --- /dev/null +++ b/src/osxlaunch/server.m @@ -0,0 +1,112 @@ +#import <Cocoa/Cocoa.h> + +@interface ServerView : NSTextView +{ + NSTask *task; + NSFileHandle *file; +} +- (void)listenTo: (NSTask*)t; +@end + +@implementation ServerView +- (void)listenTo: (NSTask*)t; +{ + NSPipe *pipe; + task = t; + pipe = [NSPipe pipe]; + [task setStandardOutput: pipe]; + file = [pipe fileHandleForReading]; + + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; + + [file readInBackgroundAndNotify]; +} + +- (void) outputNotification: (NSNotification *) notification +{ + NSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain]; + NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; + NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string]; + + [[self textStorage] appendAttributedString: attrstr]; + int length = [[self textStorage] length]; + NSRange range = NSMakeRange(length, 0); + [self scrollRangeToVisible: range]; + + [attrstr release]; + [string release]; + [file readInBackgroundAndNotify]; +} + +-(void)windowWillClose:(NSNotification *)notification +{ + [task terminate]; + [NSApp terminate:self]; +} +@end + +void runServer() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSApp = [NSApplication sharedApplication]; + NSBundle* mainBundle = [NSBundle mainBundle]; + NSTask *task; + task = [[NSTask alloc] init]; + [task setCurrentDirectoryPath: [mainBundle resourcePath]]; + + // get a server config + NSOpenPanel* openDlg = [NSOpenPanel openPanel]; + [openDlg setCanChooseFiles:YES]; + + if([openDlg runModalForDirectory:nil file:nil] != NSOKButton) + return; + + NSArray* filenames = [openDlg filenames]; + if([filenames count] != 1) + return; + + NSString* filename = [filenames objectAtIndex: 0]; + NSArray* arguments = [NSArray arrayWithObjects: @"-f", filename, nil]; + + // run server + NSWindow *window; + ServerView *view; + NSRect graphicsRect; + + graphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0); + + window = [[NSWindow alloc] + initWithContentRect: graphicsRect + styleMask: NSTitledWindowMask + | NSClosableWindowMask + | NSMiniaturizableWindowMask + backing: NSBackingStoreBuffered + defer: NO]; + + [window setTitle: @"DDNet Server"]; + + view = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease]; + [view setEditable: NO]; + [view setRulerVisible: YES]; + + [window setContentView: view]; + [window setDelegate: view]; + [window makeKeyAndOrderFront: nil]; + + [view listenTo: task]; + [task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @"DDNet-Server"]]; + [task setArguments: arguments]; + [task launch]; + [NSApp run]; + [task terminate]; + + [NSApp release]; + [pool release]; +} + +int main (int argc, char **argv) +{ + runServer(); + + return 0; +} diff --git a/src/osxlaunch/server_mysql.m b/src/osxlaunch/server_mysql.m new file mode 100644 index 0000000..1a553d7 --- /dev/null +++ b/src/osxlaunch/server_mysql.m @@ -0,0 +1,112 @@ +#import <Cocoa/Cocoa.h> + +@interface ServerView : NSTextView +{ + NSTask *task; + NSFileHandle *file; +} +- (void)listenTo: (NSTask*)t; +@end + +@implementation ServerView +- (void)listenTo: (NSTask*)t; +{ + NSPipe *pipe; + task = t; + pipe = [NSPipe pipe]; + [task setStandardOutput: pipe]; + file = [pipe fileHandleForReading]; + + [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; + + [file readInBackgroundAndNotify]; +} + +- (void) outputNotification: (NSNotification *) notification +{ + NSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain]; + NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; + NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string]; + + [[self textStorage] appendAttributedString: attrstr]; + int length = [[self textStorage] length]; + NSRange range = NSMakeRange(length, 0); + [self scrollRangeToVisible: range]; + + [attrstr release]; + [string release]; + [file readInBackgroundAndNotify]; +} + +-(void)windowWillClose:(NSNotification *)notification +{ + [task terminate]; + [NSApp terminate:self]; +} +@end + +void runServer() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSApp = [NSApplication sharedApplication]; + NSBundle* mainBundle = [NSBundle mainBundle]; + NSTask *task; + task = [[NSTask alloc] init]; + [task setCurrentDirectoryPath: [mainBundle resourcePath]]; + + // get a server config + NSOpenPanel* openDlg = [NSOpenPanel openPanel]; + [openDlg setCanChooseFiles:YES]; + + if([openDlg runModalForDirectory:nil file:nil] != NSOKButton) + return; + + NSArray* filenames = [openDlg filenames]; + if([filenames count] != 1) + return; + + NSString* filename = [filenames objectAtIndex: 0]; + NSArray* arguments = [NSArray arrayWithObjects: @"-f", filename, nil]; + + // run server + NSWindow *window; + ServerView *view; + NSRect graphicsRect; + + graphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0); + + window = [[NSWindow alloc] + initWithContentRect: graphicsRect + styleMask: NSTitledWindowMask + | NSClosableWindowMask + | NSMiniaturizableWindowMask + backing: NSBackingStoreBuffered + defer: NO]; + + [window setTitle: @"DDNet Server"]; + + view = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease]; + [view setEditable: NO]; + [view setRulerVisible: YES]; + + [window setContentView: view]; + [window setDelegate: view]; + [window makeKeyAndOrderFront: nil]; + + [view listenTo: task]; + [task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @"DDNet-Server_sql"]]; + [task setArguments: arguments]; + [task launch]; + [NSApp run]; + [task terminate]; + + [NSApp release]; + [pool release]; +} + +int main (int argc, char **argv) +{ + runServer(); + + return 0; +} diff --git a/src/tools/config_common.h b/src/tools/config_common.h new file mode 100644 index 0000000..acf735e --- /dev/null +++ b/src/tools/config_common.h @@ -0,0 +1,37 @@ +#include <base/system.h> +#include <engine/storage.h> + +int main(int argc, const char **argv) +{ + dbg_logger_stdout(); + IStorage *pStorage = CreateLocalStorage(); + if(argc == 1) + { + dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]); + return -1; + } + for(int i = 1; i < argc; i++) + { + char aConfig[2048]; + + size_t Len = str_length(argv[i]) + 1; // including '\0' + if(Len > sizeof(aConfig)) + { + dbg_msg("config_common", "can't process overlong filename '%s'", argv[i]); + continue; + } + + if(Len < sizeof(".map") || str_comp(argv[i] + Len - sizeof(".map"), ".map") != 0) + { + dbg_msg("config_common", "can't process non-map file '%s'", argv[i]); + continue; + } + + str_copy(aConfig, argv[i], sizeof(aConfig)); + aConfig[Len - sizeof(".map")] = 0; + str_append(aConfig, ".cfg", sizeof(aConfig)); + dbg_msg("config_common", "processing '%s'", argv[i]); + Process(pStorage, argv[i], aConfig); + } + return 0; +} diff --git a/storage.cfg b/storage.cfg new file mode 100644 index 0000000..15f4ab1 --- /dev/null +++ b/storage.cfg @@ -0,0 +1,31 @@ +#### +# This specifies where and in which order Teeworlds looks +# for its data (sounds, skins, ...). The search goes top +# down which means the first path has the highest priority. +# Furthermore the top entry also defines the save path where +# all data (settings.cfg, screenshots, ...) are stored. +# There are 3 special paths available: +# $USERDIR +# - ~/.appname on UNIX based systems +# - ~/Library/Applications Support/appname on Mac OS X +# - %APPDATA%/Appname on Windows based systems +# $DATADIR +# - the 'data' directory which is part of an official +# release +# $CURRENTDIR +# - current working directory +# +# +# The default file has the following entries: +# add_path $USERDIR +# add_path $DATADIR +# add_path $CURRENTDIR +# +# A customised one could look like this: +# add_path user +# add_path mods/mymod +#### + +add_path $USERDIR +add_path $DATADIR +add_path $CURRENTDIR