diff --git a/.gitignore b/.gitignore
index 8b73f04f5..7f8d56035 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,16 +13,17 @@ Win32_LIB_ASM_Release
*.dgb
*.debug
*.debug.txt
-/bin/VC10/
-/objs/VC10/
*.user
*.db
*.opendb
/.vs
/debian
/assets/debian
-compile.sh
-*.gz
-.vscode/
-out
-build
+/make
+/bin
+/build
+/build/*
+/CMakeUserPresets.json
+/out
+/objs/VC10
+*.kate-swp
diff --git a/LUASTUFF.md b/LUASTUFF.md
index 8960fad48..83ec76545 100644
--- a/LUASTUFF.md
+++ b/LUASTUFF.md
@@ -161,6 +161,37 @@ Duration is in milliseconds and is optional to set, default value is 84ms.
Exactly same as P_CheckSight but uses cheaper algorithm, useful for things like nametags. Doesn't work exactly
like P_CheckSight so don't use it for anything gameplay-related.
+## musicdef_t
+
+Userdata structure representing a musicdef. Fields:
+
+`musicdef.name` - song identifier ("kmap01" for example).
+
+`musicdef.usage`, `musicdef.source` - fields from vanilla MUSICDEFS lump.
+
+`musicdef.filename` - unused for now.
+
+`musicdef.title`, `musicdef.alttitle`, `musicdef.authors` - fields from MUSCINFO lump.
+
+`#musicdef` - returns integer id for musicdef (which can be used as index in `musicdefs`).
+
+All fields are read-only.
+
+## S_FindMusicCredit(name)
+
+Returns musicdef corresponding to music with given identifier. For example, `S_FindMusicCredit("kmap01")` will return
+musicdef for green hills music.
+
+## musicdefs
+
+Global table for all musicdefs, similar to mobjinfo, states, etc. Can take either integer indices,
+from `0` to `#musicdefs-1`, or string indices (which is equal to calling `S_FindMusicCredit`).
+
+## addHook("MusicCredit", function(musicdef))
+
+Hook is called whenever `S_ShowMusicCredit` (either from game or mod) is called. Takes musicdef as only argument, returning true
+will overwrite vanilla behavior (not show music credit), can be used to implement custom music credit pop-ups.
+
# Other changes
## P_PlayRinglossSound(source, damager)
diff --git a/bin/FreeBSD/Debug/.gitignore b/bin/FreeBSD/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/bin/FreeBSD/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/bin/FreeBSD/Release/.gitignore b/bin/FreeBSD/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/bin/FreeBSD/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/bin/Linux/Debug/.gitignore b/bin/Linux/Debug/.gitignore
deleted file mode 100644
index 56dee6f95..000000000
--- a/bin/Linux/Debug/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/lsdlsrb2
diff --git a/bin/Linux/Release/.gitignore b/bin/Linux/Release/.gitignore
deleted file mode 100644
index 5b5c54a54..000000000
--- a/bin/Linux/Release/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/lsdlsrb2
-/pnd
-/*.mo
diff --git a/bin/Linux64/Debug/.gitignore b/bin/Linux64/Debug/.gitignore
deleted file mode 100644
index 56dee6f95..000000000
--- a/bin/Linux64/Debug/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/lsdlsrb2
diff --git a/bin/Linux64/Release/.gitignore b/bin/Linux64/Release/.gitignore
deleted file mode 100644
index c63fd53bc..000000000
--- a/bin/Linux64/Release/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/lsdl2srb2kart
diff --git a/bin/Mingw/Debug/.gitignore b/bin/Mingw/Debug/.gitignore
deleted file mode 100644
index 3458ff764..000000000
--- a/bin/Mingw/Debug/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-*.exe
-*.mo
-r_opengl.dll
-*.bat
diff --git a/bin/Mingw/Release/.gitignore b/bin/Mingw/Release/.gitignore
deleted file mode 100644
index 3458ff764..000000000
--- a/bin/Mingw/Release/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-*.exe
-*.mo
-r_opengl.dll
-*.bat
diff --git a/bin/Mingw64/Debug/.gitignore b/bin/Mingw64/Debug/.gitignore
deleted file mode 100644
index e431dca5d..000000000
--- a/bin/Mingw64/Debug/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/srb2sdl.exe
-/srb2win.exe
-/r_opengl.dll
diff --git a/bin/Mingw64/Release/.gitignore b/bin/Mingw64/Release/.gitignore
deleted file mode 100644
index b2443f38d..000000000
--- a/bin/Mingw64/Release/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-*.exe
-*.mo
-r_opengl.dll
-*.bat
\ No newline at end of file
diff --git a/bin/SDL/Debug/.gitignore b/bin/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/bin/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/bin/SDL/Release/.gitignore b/bin/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/bin/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/bin/dummy/.gitignore b/bin/dummy/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/bin/dummy/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/.gitignore b/objs/.gitignore
deleted file mode 100644
index 35ecd6def..000000000
--- a/objs/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-#All folders
-SRB2.res
-depend.dep
-depend.ped
-*.o
-#VC9 folder only
-/VC9/Win32
-/VC9/x64
diff --git a/objs/FreeBSD/SDL/Debug/.gitignore b/objs/FreeBSD/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/FreeBSD/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/FreeBSD/SDL/Release/.gitignore b/objs/FreeBSD/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/FreeBSD/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Linux/SDL/Debug/.gitignore b/objs/Linux/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Linux/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Linux/SDL/Release/.gitignore b/objs/Linux/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Linux/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Linux64/SDL/Debug/.gitignore b/objs/Linux64/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Linux64/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Linux64/SDL/Release/.gitignore b/objs/Linux64/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Linux64/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/MasterClient/.gitignore b/objs/MasterClient/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/MasterClient/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/MasterServer/.gitignore b/objs/MasterServer/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/MasterServer/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw/Debug/.gitignore b/objs/Mingw/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw/Release/.gitignore b/objs/Mingw/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw/SDL/Debug/.gitignore b/objs/Mingw/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw/SDL/Release/.gitignore b/objs/Mingw/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw64/Debug/.gitignore b/objs/Mingw64/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw64/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw64/Release/.gitignore b/objs/Mingw64/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw64/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw64/SDL/Debug/.gitignore b/objs/Mingw64/SDL/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw64/SDL/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/Mingw64/SDL/Release/.gitignore b/objs/Mingw64/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/Mingw64/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/SDL/Release/.gitignore b/objs/SDL/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/SDL/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/cygwin/Debug/.gitignore b/objs/cygwin/Debug/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/cygwin/Debug/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/cygwin/Release/.gitignore b/objs/cygwin/Release/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/cygwin/Release/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/objs/dummy/.gitignore b/objs/dummy/.gitignore
deleted file mode 100644
index 42c6dc2c6..000000000
--- a/objs/dummy/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-# DON'T REMOVE
-# This keeps the folder from disappearing
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 729b5896a..4ce38953d 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -228,6 +228,14 @@ set(SRB2_CONFIG_STATIC_OPENGL OFF CACHE BOOL
"Use statically linked OpenGL. NOT RECOMMENDED.")
set(SRB2_CONFIG_USE_FBO_OGL ON CACHE BOOL
"Enable OpenGL FBO Downsampling support.")
+set(SRB2_CONFIG_DEDICATED OFF CACHE BOOL
+ "Build a dedicated server.")
+
+if(${SRB2_CONFIG_DEDICATED})
+ set(SRB2_CONFIG_HAVE_GME NO)
+ set(SRB2_CONFIG_HAVE_OPENMPT NO)
+ set(SRB2_CONFIG_HWRENDER NO)
+endif()
### use internal libraries?
if(${CMAKE_SYSTEM} MATCHES "Windows") ###set on Windows only
@@ -554,7 +562,11 @@ add_definitions(-DCMAKECONFIG)
# ${SRB2_BLUA_HEADERS}
#)
-add_subdirectory(sdl)
+if(${SRB2_CONFIG_DEDICATED})
+ add_subdirectory(dedicated)
+else()
+ add_subdirectory(sdl)
+endif()
if(NOT ${SRB2_SDL2_AVAILABLE} AND NOT ${SRB2_WIN32_AVAILABLE})
message(FATAL_ERROR "There are no targets available to build an SRB2Kart executable. :(")
diff --git a/src/Makefile b/src/Makefile
index ffac773ef..f97fa7e62 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -1,769 +1,418 @@
-
-# GNU Make makefile for SRB2
-#############################################################################
-# Copyright (C) 1998-2000 by DooM Legacy Team.
-# Copyright (C) 2003-2018 by Sonic Team Junior.
+# GNU Makefile for SRB2
+# the poly3 Makefile adapted over and over...
+#
+# Copyright 1998-2000 DooM Legacy Team.
+# Copyright 2020-2023 James R.
+# Copyright 2003-2023 Sonic Team Junior.
#
# This program is free software distributed under the
# terms of the GNU General Public License, version 2.
# See the 'LICENSE' file for more details.
#
-# -DLINUX -> use for the GNU/Linux specific
-# -DHAVE_SDL -> use for the SDL interface
+# Special targets:
#
-# Sets:
-# Compile the Mingw version with 'make MINGW=1'
-# Compile the SDL/Mingw version with 'make MINGW=1 SDL=1'
-# Compile the SDL/Linux version with 'make LINUX=1'
-# Compile the SDL/Solaris version with 'make SOLARIS=1'
-# Compile the SDL/FreeBSD version with 'gmake FREEBSD=1'
-# Compile the SDL/Cygwin version with 'make CYGWIN32=1'
-# Compile the SDL/other version try with 'make SDL=1'
+# clean - remove executables and objects for this build
+# cleandep - remove dependency files for this build
+# distclean - remove entire executable, object and
+# dependency file directory structure.
+# dump - disassemble executable
+# info - print settings
#
-# 'Targets':
-# clean
-# Remove all object files
-# cleandep
-# Remove depend.dep
-# dll
-# compile primary HW render DLL/SO
-# all_dll
-# compile all HW render and 3D sound DLLs for the set
-# opengl_dll
-# Pure Mingw only, compile OpenGL HW render DLL
+# This Makefile can automatically detect the host system
+# as well as the compiler version. If system or compiler
+# version cannot be detected, you may need to set a flag
+# manually.
#
#
-# Addon:
-# To Cross-Compile, CC=gcc-version make * PREFIX=
-# Compile with GCC 2.97 version, add 'GCC29=1'
-# Compile with GCC 4.0x version, add 'GCC40=1'
-# Compile with GCC 4.1x version, add 'GCC41=1'
-# Compile with GCC 4.2x version, add 'GCC42=1'
-# Compile with GCC 4.3x version, add 'GCC43=1'
-# Compile with GCC 4.4x version, add 'GCC44=1'
-# Compile with GCC 4.5x version, add 'GCC45=1'
-# Compile with GCC 4.6x version, add 'GCC46=1'
-# Compile a profile version, add 'PROFILEMODE=1'
-# Compile a debug version, add 'DEBUGMODE=1'
-# Compile with less warnings, add 'RELAXWARNINGS=1'
-# Generate compiler errors for most compiler warnings, add 'ERRORMODE=1'
-# Compile without 3D hardware support, add 'NOHW=1'
-# Compile with GDBstubs, add 'RDB=1'
-# Compile without PNG, add 'NOPNG=1'
-# Compile without zlib, add 'NOZLIB=1'
+# Platform/system flags:
#
-# Addon for SDL:
-# To Cross-Compile, add 'SDL_CONFIG=/usr/*/bin/sdl-config'
-# Compile without SDL_Mixer, add 'NOMIXER=1'
-# Compile without BSD API, add 'NONET=1'
-# Compile without IPX/SPX, add 'NOIPX=1'
-# Compile without libopenmpt, add 'NOOPENMPT=1'
-# To link with the whole SDL_Image lib to load Icons, add 'SDL_IMAGE=1' but it isn't not realy needed
-# To link with SDLMain to hide console or make on a console-less binary, add 'SDLMAIN=1'
+# LINUX=1, LINUX64=1
+# MINGW=1, MINGW64=1 - Windows (MinGW toolchain)
+# UNIX=1 - Generic Unix like system
+# FREEBSD=1
+# SDL=1 - Use SDL backend. SDL is the only implemented backend though.
+# If disabled, a dummy backend will be used.
#
-#############################################################################
+# A list of supported GCC versions can be found in
+# Makefile.d/detect.mk -- search 'gcc_versions'.
+#
+# Feature flags:
+#
+# Safe to use online
+# ------------------
+# NOHW=1 - Disable OpenGL renderer.
+# NOSCREENFBO=1 - Disable screen FBO for downsampling in OpenGL.
+# NOSATURNPAK=1 - Disable handling the special Saturn packet and resynch system
+# NOSATURNJOIN=1 - Disable the seperate Saturn allowjoin toggle
+# ZDEBUG=1 - Enable more detailed memory debugging
+# HAVE_MINIUPNPC=1 - Enable automated port forwarding.
+# Already enabled by default for 32-bit
+# Windows.
+# NOCURL=1 - Disable libcurl--HTTP capability.
+# NOGME=1 - Disable game music emu, retro VGM support.
+# NOOPENMPT=1 - Disable module (tracker) music support.
+# NOMIXER=1 - Disable SDL Mixer (audio playback).
+# NOTHREADS=1 - Disable multithreading.
+#
+# Netplay incompatible
+# --------------------
+# NOMD5=1 - Disable MD5 checksum (validation tool).
+# NOPOSTPROCESSING=1 - ?
+# MOBJCONSISTANCY=1 - ??
+# PACKETDROP=1 - ??
+# NOEXECINFO=1 - Disable stack trace dump support
+# DEBUGMODE=1 - Enable various debugging capabilities.
+# Also disables optimizations.
+#
+# Development flags:
+#
+# VALGRIND=1 - Enable Valgrind memory debugging support.
+# PROFILEMODE=1 - Enable performance profiling (gprof).
+# USEASAN=1 - Enable building with Address Sanitizer.
+# NOLIBBACKTRACE=1 - Disable using Libbacktrace for crashlog traces.
+#
+# General flags for building:
+#
+# STATIC=1 - Use static linking.
+# DISTCC=1
+# CCACHE=1
+# UPX= - UPX command to use for compressing final
+# executable.
+# WINDOWSHELL=1 - Use Windows commands.
+# PREFIX= - Prefix to many commands, for cross compiling.
+# STABS=1 - ?
+# ECHO=1 - Print out each command in the build process.
+# NOECHOFILENAMES=1 - Don't print out each that is being
+# worked on.
+# SILENT=1 - Print absolutely nothing except errors.
+# RELAXWARNINGS=1 - Use less compiler warnings/errors.
+# ERRORMODE=1 - Treat most compiler warnings as errors.
+# NOCASTALIGNWARN=1 - ?
+# NOLDWARNING=1 - ?
+# NOSDLMAIN=1 - ?
+# SDLMAIN=1 - ?
+# USELTO=1 - Enable building with LTO.
+#
+# Library configuration flags:
+# Everything here is an override.
+#
+# PNG_PKGCONFIG= - libpng-config command.
+# PNG_CFLAGS=, PNG_LDFLAGS=
+#
+# CURLCONFIG= - curl-config command.
+# CURL_CFLAGS=, CURL_LDFLAGS=
+#
+# VALGRIND_PKGCONFIG= - pkg-config package name.
+# VALGRIND_CFLAGS=, VALGRIND_LDFLAGS=
+#
+# LIBGME_PKGCONFIG=, LIBGME_CFLAGS=, LIBGME_LDFLAGS=
-ALL_SYSTEMS=\
- PANDORA\
- LINUX64\
- MINGW64\
- HAIKU\
- MINGW\
- UNIX\
- LINUX\
- SOLARIS\
- FREEBSD\
- MACOSX\
- SDL\
+# LIBOPENMPT_PKGCONFIG=
+# LIBOPENMPT_CFLAGS=, LIBOPENMPT_LDFLAGS=
+#
+# ZLIB_PKGCONFIG=, ZLIB_CFLAGS=, ZLIB_LDFLAGS=
+#
+# SDL_PKGCONFIG=
+# SDL_CONFIG= - sdl-config command.
+# SDL_CFLAGS=, SDL_LDFLAGS=
-# check for user specified system
-ifeq (,$(filter $(ALL_SYSTEMS),$(.VARIABLES)))
-ifeq ($(OS),Windows_NT) # all windows are Windows_NT...
+clean_targets=cleandep clean distclean info
- ifeq ($(shell uname -s | grep -o MINGW64),MINGW64) # 64-bit MinGW
- $(info Detected a Windows system, compiling for 64-bit MinGW SDL2...)
- MINGW64=1
- else # 32-bit MinGW
- $(info Detected a Windows system, compiling for 32-bit MinGW SDL2...)
- MINGW=1
- endif
+.PHONY : $(clean_targets) all
- SDL=1
- WINDOWSHELL=1
- NOOBJDUMP=1
+goals:=$(or $(MAKECMDGOALS),all)
+cleanonly:=$(filter $(clean_targets),$(goals))
+destructive:=$(filter-out info,$(cleanonly))
-else # if you on the *nix
- system:=$(shell uname -s)
-
- ifeq ($(system),Linux)
- new_system=LINUX
- else
-
- $(error \
- Could not automatically detect your system,\
- try specifying a system manually)
-
- endif
-
- ifeq ($(shell getconf LONG_BIT),64)
- system+=64-bit
- new_system:=$(new_system)64
- endif
-
- $(info Detected $(system) ($(new_system))...)
- $(new_system)=1
-
-endif
+ifndef cleanonly
+include Makefile.d/old.mk
endif
-NOUPX=1
+include Makefile.d/util.mk
-# SRB2 data files
-D_DIR?=../bin/Resources
-D_FILES=$(D_DIR)/srb2.srb \
- $(D_DIR)/patch.dta \
- #$(D_DIR)/music.dta \
- $(D_DIR)/gfx.kart \
- $(D_DIR)/textures.kart \
- $(D_DIR)/chars.kart \
- $(D_DIR)/maps.kart \
- $(D_DIR)/sounds.kart \
- $(D_DIR)/patch.kart \
- $(D_DIR)/music.kart \
-
-PKG_CONFIG?=pkg-config
-
-ifdef PANDORA
-LINUX=1
-endif
-
-ifdef LINUX64
-LINUX=1
-NONX86=1
-# LINUX64 does not imply X86_64=1; could mean ARM64 or Itanium
-endif
-
-ifdef MINGW64
-MINGW=1
-NONX86=1
-# MINGW64 should not necessarily imply X86_64=1, but we make that assumption elsewhere
-# Once that changes, remove this
-X86_64=1
-endif #ifdef MINGW64
-
-ifdef HAIKU
-SDL=1
-endif
-
-include Makefile.cfg
-
-ifdef HAIKU
-NOIPX=1
-ifndef NONET
-LIBS=-lnetwork
-endif
-CFLAGS+=-DUNIXCOMMON
-PNG_CFLAGS?=
-PNG_LDFLAGS?=-lpng
-endif
-
-ifdef PANDORA
-NONX86=1
-NOHW=1
-endif
-
-ifndef NOOPENMPT
-HAVE_OPENMPT=1
-endif
-
-ifndef NOHW
-ifndef NOSCREENFBO
-USE_FBO_OGL=1
-endif
-endif
-
-ifndef NONET
-ifndef NOSATURNJOIN
-DOSATURNJOIN=1
-endif
-ifndef NOSATURNPAK
-DOSATURNPAK=1
-endif
-endif
-
-ifdef MINGW
-include win32/Makefile.cfg
-endif #ifdef MINGW
-
-ifdef UNIX
-UNIXCOMMON=1
-endif
-
-ifdef LINUX
-UNIXCOMMON=1
-NOOBJDUMP=1
-ifndef NOGME
-HAVE_LIBGME=1
-endif
-endif
-
-ifdef SOLARIS
-UNIXCOMMON=1
-endif
-
-ifdef FREEBSD
-UNIXCOMMON=1
-endif
-
-ifdef MACOSX
-UNIXCOMMON=1
-endif
-
-ifdef SDL
- include sdl/Makefile.cfg
-endif #ifdef SDL
-
-ifdef DISTCC
- CC:=distcc $(CC)
-endif
-
-ifdef CCACHE
- CC:=ccache $(CC)
-endif
-
-MSGFMT?=msgfmt
-
-ifndef ECHO
- REMOVE:=@$(REMOVE)
- CC:=@$(CC)
- CXX:=@$(CXX)
- OBJCOPY:=@$(OBJCOPY)
- OBJDUMP:=@$(OBJDUMP)
- STRIP:=@$(STRIP)
- WINDRES:=@$(WINDRES)
- CP:=@$(CP)
- MKDIR:=@$(MKDIR)
- MKISOFS:=@$(MKISOFS)
- DD:=@$(DD)
- NDSTOOL:=@$(NDSTOOL)
- GZIP:=@$(GZIP)
- MSGFMT:=@$(MSGFMT)
- UPX:=@$(UPX)
- UPX_OPTS+=-q
-endif
-
-ifdef NONET
- OPTS+=-DNONET
- NOCURL=1
-else
-ifdef NO_IPV6
- OPTS+=-DNO_IPV6
-endif
-endif
-
-ifdef NOHW
- OPTS+=-DNOHW
-else
- OPTS+=-DHWRENDER
- OBJS+=$(OBJDIR)/hw_bsp.o $(OBJDIR)/hw_draw.o \
- $(OBJDIR)/hw_main.o $(OBJDIR)/hw_clip.o $(OBJDIR)/hw_md2.o $(OBJDIR)/hw_cache.o $(OBJDIR)/hw_portal.o\
- $(OBJDIR)/hw_md2load.o $(OBJDIR)/hw_md3load.o $(OBJDIR)/hw_model.o $(OBJDIR)/u_list.o $(OBJDIR)/hw_batching.o $(OBJDIR)/hw_shaders.o
-endif
-
-OPTS += -DCOMPVERSION
-
-ifndef NONX86
-ifndef GCC29
- ARCHOPTS?=-msse3 -mfpmath=sse
-else
- ARCHOPTS?=-mpentium
-endif
-else
-ifdef X86_64
- ARCHOPTS?=-march=nocona
-endif
-endif
-
-# apparently MingW just completely ignores everything so just always force this shit
-# FIXME: we should port our code to c24
-CFLAGS+=-std=gnu17
-CPPFLAGS+=-std=gnu17
-
-ifndef NOPNG
-OPTS+=-DHAVE_PNG
-
-ifdef PNG_PKGCONFIG
-PNG_CFLAGS?=$(shell $(PKG_CONFIG) $(PNG_PKGCONFIG) --cflags)
-PNG_LDFLAGS?=$(shell $(PKG_CONFIG) $(PNG_PKGCONFIG) --libs)
-else
ifdef PREFIX
-PNG_CONFIG?=$(PREFIX)-libpng-config
+CC:=$(PREFIX)-gcc
+CXX:=$(PREFIX)-g++
+endif
+
+OBJDUMP_OPTS?=--wide --source --line-numbers
+
+OBJCOPY?=$(call Prefix,objcopy)
+OBJDUMP?=$(call Prefix,objdump)
+WINDRES?=$(call Prefix,windres)
+
+GZIP?=gzip
+GZIP_OPTS?=-9 -f -n
+ifdef WINDOWSHELL
+GZIP_OPTS+=--rsyncable
+endif
+
+UPX_OPTS?=--best --preserve-build-id
+ifndef ECHO
+UPX_OPTS+=-qq
+endif
+
+include Makefile.d/detect.mk
+
+# make would try to remove the implicitly made directories
+.PRECIOUS : %/ comptime.c
+
+sources:=
+makedir:=../make
+
+# -DCOMPVERSION: flag to use comptime.h
+opts:=-DCOMPVERSION -g
+libs:=
+
+# This is a list of variables names, of which if defined,
+# also defines the name as a macro to the compiler.
+passthru_opts:=
+
+include Makefile.d/platform.mk
+include Makefile.d/features.mk
+include Makefile.d/versions.mk
+
+ifdef DEBUGMODE
+makedir:=$(makedir)/debug
+endif
+
+depdir:=$(makedir)/deps
+objdir:=$(makedir)/objs
+
+# very sophisticated dependency
+sources+=\
+ $(call List,Sourcefile)\
+ $(call List,core/Sourcefile)
+
+sources+=\
+ $(call List,blua/Sourcefile)
+
+depends:=$(basename $(filter %.c %.cpp %.s,$(sources)))
+objects:=$(basename $(filter %.c %.cpp %.s %.nas,$(sources)))
+
+depends:=$(depends:%=$(depdir)/%.d)
+
+# comptime.o added directly to objects instead of thru
+# sources because comptime.c includes comptime.h, but
+# comptime.h may not exist yet. It's a headache so this is
+# easier.
+objects:=$(objects:=.o) comptime.o
+
+# windows resource file
+rc_file:=$(basename $(filter %.rc,$(sources)))
+ifdef rc_file
+objects+=$(rc_file:=.res)
+endif
+
+objects:=$(addprefix $(objdir)/,$(objects))
+
+ifdef DEBUGMODE
+bin:=../bin/debug
else
-PNG_CONFIG?=libpng-config
+bin:=../bin
endif
-ifdef PNG_STATIC
-PNG_CFLAGS?=$(shell $(PNG_CONFIG) --static --cflags)
-PNG_LDFLAGS?=$(shell $(PNG_CONFIG) --static --ldflags)
-else
-PNG_CFLAGS?=$(shell $(PNG_CONFIG) --cflags)
-PNG_LDFLAGS?=$(shell $(PNG_CONFIG) --ldflags)
-endif
-endif
+# default EXENAME (usually set by platform)
+EXENAME?=srb2kart
+DBGNAME?=$(EXENAME).debug
-ifdef LINUX
-PNG_CFLAGS+=-D_LARGEFILE64_SOURCE
-endif
+exe:=$(bin)/$(EXENAME)
+dbg:=$(bin)/$(DBGNAME)
-LIBS+=$(PNG_LDFLAGS)
-CFLAGS+=$(PNG_CFLAGS)
+build_done==== Build is done, look for \
+ $( $@
+ $(.)$(GZIP) $(GZIP_OPTS) $@
+
+# '::' means run unconditionally
+# this really updates comptime.h
+comptime.c ::
ifdef WINDOWSHELL
-$(.)..\comptime.bat .
else
-$(.)../comptime.sh .
endif
-clean: cleandep
- $(REMOVE) *~ *.flc
- $(REMOVE) $(OBJDIR)/*.o
+# I wish I could make dependencies out of rc files :(
+$(objdir)/win32/Srb2win.res : \
+ win32/afxres.h win32/resource.h
-ifdef MINGW
- $(REMOVE) $(OBJDIR)/*.res
-endif
-
-ifdef CYGWIN32
- $(REMOVE) $(OBJDIR)/*.res
-endif
-
-
-# executable
-
-$(BIN)/$(EXENAME): $(POS) $(OBJS)
- -$(MKDIR) $(BIN)
- @echo Linking $(EXENAME)...
- $(LD) $(LDFLAGS) $(OBJS) -o $(BIN)/$(EXENAME) $(LIBS)
-ifndef VALGRIND
-ifndef NOOBJDUMP
- @echo Dumping debugging info
- $(OBJDUMP) $(OBJDUMP_OPTS) $(BIN)/$(EXENAME) > $(BIN)/$(DBGNAME).txt
- -$(GZIP) $(GZIP_OPTS) $(BIN)/$(DBGNAME).txt
+# dependency recipe template
+# 1: source file suffix
+# 2: extra flags to gcc
+define _recipe =
+$(depdir)/%.d : %.$(1) | $$$$(@D)/
ifndef WINDOWSHELL
- -$(GZIP) $(GZIP_OPT2) $(BIN)/$(DBGNAME).txt
+ifdef Echo_name
+ @printf '%-20.20s\r' $$<
endif
endif
+ $(.)$(cc) -MM -MF $$@ -MT $(objdir)/$$*.o $(2) $$<
+endef
-# mac os x lsdlsrb2 does not like objcopy
-ifndef MACOSX
- $(OBJCOPY) $(BIN)/$(EXENAME) $(BIN)/$(DBGNAME)
- $(OBJCOPY) --strip-debug $(BIN)/$(EXENAME)
- -$(OBJCOPY) --add-gnu-debuglink=$(BIN)/$(DBGNAME) $(BIN)/$(EXENAME)
-endif
-ifndef NOUPX
- -$(UPX) $(UPX_OPTS) $(BIN)/$(EXENAME)
-endif
-endif
+$(eval $(call _recipe,c))
+$(eval $(call _recipe,cpp))
+$(eval $(call _recipe,s,$(asflags)))
-ifdef APPIMAGE
- @echo Building AppImage...
-ifdef APPIMAGE_NOASSETS
- $(.)../AppImage_build.sh --small --quiet $(BIN)/
+# compiling recipe template
+# 1: target file suffix
+# 2: source file suffix
+# 3: compile command
+define _recipe =
+$(objdir)/%.$(1) : %.$(2) | $$$$(@D)/
+ $(call Echo_name,$$<)
+ $(.)$(3)
+endef
+
+$(eval $(call _recipe,o,c,$(cc) -c -o $$@ $$<))
+$(eval $(call _recipe,o,cpp,$(cxx) -c -o $$@ $$<))
+$(eval $(call _recipe,o,s,$(cc) $(asflags) -c -o $$@ $$<))
+$(eval $(call _recipe,res,rc,$(windres) -i $$< -o $$@))
+
+_rm=$(.)$(rmrf) $(call Windows_path,$(1))
+
+cleandep :
+ $(call _rm,$(depends) comptime.h)
+
+clean :
+ $(call _rm,$(exe) $(dbg) $(dbg).txt $(objects))
+
+distclean :
+ $(call _rm,../bin ../objs ../dep ../make comptime.h)
+
+info:
+ifdef WINDOWSHELL
+ @REM
else
- $(.)../AppImage_build.sh -q $(BIN)/
-endif
- @echo AppImage build complete, please look for $(EXENAME).AppImage in $(BIN)
+ @:
endif
- @echo Build is done, please look for $(EXENAME) in $(BIN), \(checking for post steps\)
-
-reobjdump:
- @echo Redumping debugging info
- $(OBJDUMP) $(OBJDUMP_OPTS) $(BIN)/$(DBGNAME) > $(BIN)/$(DBGNAME).txt
- -$(GZIP) $(GZIP_OPTS) $(BIN)/$(DBGNAME).txt
-ifndef WINDOWSHELL
- -$(GZIP) $(GZIP_OPT2) $(BIN)/$(DBGNAME).txt
-endif
-
-$(OBJDIR):
- -$(MKDIR) $(OBJDIR)
-
-ifndef SDL
-ifdef NOHW
-dll :
-else
-dll : opengl_dll
-endif
-ifdef MINGW
-all_dll: opengl_dll
-
-opengl_dll: $(BIN)/r_opengl.dll
-$(BIN)/r_opengl.dll: $(OBJDIR)/ogl_win.o $(OBJDIR)/r_opengl.o
- -$(MKDIR) $(BIN)
- @echo Linking R_OpenGL.dll...
- $(CC) --shared $^ -o $@ -g -Wl,--add-stdcall-alias -lgdi32 -static-libgcc
-ifndef NOUPX
- -$(UPX) $(UPX_OPTS) $@
-endif
-endif
-
-else
-ifdef SDL
-ifdef MINGW
-$(OBJDIR)/r_opengl.o: hardware/r_opengl/r_opengl.c hardware/r_opengl/r_opengl.h \
- doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_gl.h screen.h \
- command.h hardware/hw_data.h hardware/hw_defs.h hardware/hw_md2.h \
- hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h hardware/hw_portal.h\
- hardware/hw_md2load.h hardware/hw_md3load.h hardware/hw_model.h hardware/u_list.h \
- am_map.h d_event.h d_player.h p_pspr.h m_fixed.h tables.h info.h d_think.h \
- p_mobj.h doomdata.h d_ticcmd.h r_defs.h hardware/hw_dll.h
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-else
-$(OBJDIR)/r_opengl.o: hardware/r_opengl/r_opengl.c hardware/r_opengl/r_opengl.h \
- doomdef.h doomtype.h g_state.h m_swap.h hardware/hw_gl.h screen.h \
- command.h hardware/hw_data.h hardware/hw_defs.h hardware/hw_md2.h \
- hardware/hw_glob.h hardware/hw_main.h hardware/hw_clip.h hardware/hw_portal.h \
- hardware/hw_md2load.h hardware/hw_md3load.h hardware/hw_model.h hardware/u_list.h \
- am_map.h d_event.h d_player.h p_pspr.h m_fixed.h tables.h info.h d_think.h \
- p_mobj.h doomdata.h d_ticcmd.h r_defs.h hardware/hw_dll.h
- $(CC) $(CFLAGS) $(WFLAGS) -I/usr/X11R6/include -c $< -o $@
-endif
-endif
-
-endif
-
-#dependecy made by gcc itself !
-$(OBJS):
--include $(OBJDIR)/depend.dep
-
-$(OBJDIR)/depend.dep:
- @echo "Creating dependency file, depend.dep"
- @echo > comptime.h
- -$(MKDIR) $(OBJDIR)
- $(CC) $(CFLAGS) -MM *.c > $(OBJDIR)/depend.ped
- $(CC) $(CFLAGS) -MM $(INTERFACE)/*.c >> $(OBJDIR)/depend.ped
-ifndef NOHW
- $(CC) $(CFLAGS) -MM hardware/*.c >> $(OBJDIR)/depend.ped
-endif
-
- $(CC) $(CFLAGS) -MM blua/*.c >> $(OBJDIR)/depend.ped
-
- @sed -e 's,\(.*\)\.o: ,$(subst /,\/,$(OBJDIR))\/&,g' < $(OBJDIR)/depend.ped > $(OBJDIR)/depend.dep
- $(REMOVE) $(OBJDIR)/depend.ped
- @echo "Created dependency file, depend.dep"
-
-ifdef VALGRIND
-$(OBJDIR)/z_zone.o: z_zone.c
- $(CC) $(CFLAGS) $(WFLAGS) -DHAVE_VALGRIND $(VALGRIND_CFLAGS) -c $< -o $@
-endif
-
-$(OBJDIR)/comptime.o: comptime.c pre-build
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-
-$(OBJDIR)/%.o: %.c
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-
-$(OBJDIR)/%.o: $(INTERFACE)/%.c
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-
-ifdef MACOSX
-$(OBJDIR)/%.o: sdl/macosx/%.c
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-endif
-
-$(OBJDIR)/%.o: hardware/%.c
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-
-$(OBJDIR)/%.o: blua/%.c
- $(CC) $(CFLAGS) $(LUA_CFLAGS) $(WFLAGS) -c $< -o $@
-
-$(OBJDIR)/%.o: %.s
- $(CC) $(OPTS) -x assembler-with-cpp -c $< -o $@
-
-$(OBJDIR)/SRB2.res: win32/Srb2win.rc win32/afxres.h win32/resource.h
- $(WINDRES) -i $< -O rc $(WINDRESFLAGS) --include-dir=win32 -o $@ -O coff
-
-ifdef SDL
-ifdef MINGW
-$(OBJDIR)/win_dbg.o: win32/win_dbg.c
- $(CC) $(CFLAGS) $(WFLAGS) -c $< -o $@
-endif
-endif
-
-#############################################################
-#
-#############################################################
+#$(warning The handwritten GNU Makefile for SRB2 is deprecated, and may be removed in the future. Please consider switching to CMake.)
diff --git a/src/Makefile.cfg b/src/Makefile.cfg
deleted file mode 100644
index 2e407ac3f..000000000
--- a/src/Makefile.cfg
+++ /dev/null
@@ -1,589 +0,0 @@
-# vim: ft=make
-#
-# Makefile.cfg for SRB2
-#
-
-#
-# GNU compiler & tools' flags
-# and other things
-#
-
-# See the following variable don't start with 'GCC'. This is
-# to avoid a false positive with the version detection...
-
-SUPPORTED_GCC_VERSIONS:=\
- 151 150 15\
- 142 141 140 14\
- 132 131 130 13\
- 123 122 121 120 12\
- 114 113 112 111 110 11\
- 105 104 103 102 101 100 10\
- 95 94 93 92 91 90\
- 85 84 83 82 81 80\
- 75 74 73 72 71 70\
- 64 63 62 61 60\
- 55 54 53 52 51 50\
- 49 48 47 46 45 44 43 42 41 40
-
-LATEST_GCC_VERSION=14.2.1
-
-# gcc or g++
-ifdef PREFIX
- CC:=$(PREFIX)-gcc
- CXX:=$(PREFIX)-g++
- OBJCOPY?=$(PREFIX)-objcopy
- OBJDUMP?=$(PREFIX)-objdump
- STRIP?=$(PREFIX)-strip
- WINDRES?=$(PREFIX)-windres
-else
- OBJCOPY?=objcopy
- OBJDUMP?=objdump
- STRIP?=strip
- WINDRES?=windres
-endif
-
-# because Apple screws with us on this
-# need to get bintools from homebrew
-ifdef MACOSX
- CC=clang
- CXX=clang
- OBJCOPY=gobjcopy
- OBJDUMP=gobjdump
-endif
-
-# Automatically set version flag, but not if one was manually set
-ifeq (,$(filter GCC%,$(.VARIABLES)))
- version:=$(shell $(CC) --version)
- # check if this is in fact GCC
- ifneq (,$(or $(findstring gcc,$(version)),$(findstring GCC,$(version))))
- shellversion:=$(shell $(CC) -dumpversion)
-
- # Try to remove "-win32"
- version:=$(subst -win32,.0,$(shellversion))
-
- # Turn version into words of major, minor
- v:=$(subst ., ,$(version))
- # concat. major minor
- v:=$(word 1,$(v))$(word 2,$(v))
-
- # If this version is not in the list, default to the latest supported
- ifeq (,$(filter $(v),$(SUPPORTED_GCC_VERSIONS)))
- $(info\
- Your compiler version, GCC $(version), is not supported by the Makefile.\
- The Makefile will assume GCC $(LATEST_GCC_VERSION).)
- GCC$(subst .,,$(LATEST_GCC_VERSION))=1
- else
- $(info Detected GCC $(version) (GCC$(v)))
- GCC$(v)=1
- endif
- endif
-endif
-
-ifdef GCC151
-GCC150=1
-endif
-
-ifdef GCC15
-GCC150=1
-endif
-
-ifdef GCC150
-GCC142=1
-endif
-
-ifdef GCC142
-GCC141=1
-endif
-
-ifdef GCC141
-GCC140=1
-endif
-
-ifdef GCC14
-GCC140=1
-endif
-
-ifdef GCC140
-GCC132=1
-endif
-
-ifdef GCC132
-GCC131=1
-endif
-
-ifdef GCC131
-GCC130=1
-endif
-
-ifdef GCC13
-GCC130=1
-endif
-
-ifdef GCC130
-GCC123=1
-endif
-
-ifdef GCC123
-GCC122=1
-endif
-
-ifdef GCC122
-GCC121=1
-endif
-
-ifdef GCC121
-GCC120=1
-endif
-
-ifdef GCC12
-GCC120=1
-endif
-
-ifdef GCC120
-GCC114=1
-endif
-
-ifdef GCC114
-GCC113=1
-endif
-
-ifdef GCC113
-GCC112=1
-endif
-
-ifdef GCC112
-GCC111=1
-endif
-
-ifdef GCC111
-GCC110=1
-endif
-
-ifdef GCC11
-GCC110=1
-endif
-
-ifdef GCC110
-GCC105=1
-endif
-
-ifdef GCC105
-GCC104=1
-endif
-
-ifdef GCC104
-GCC103=1
-endif
-
-ifdef GCC103
-GCC102=1
-endif
-
-ifdef GCC102
-GCC101=1
-endif
-
-ifdef GCC101
-GCC100=1
-endif
-
-ifdef GCC10
-GCC100=1
-endif
-
-ifdef GCC100
-GCC93=1
-endif
-
-ifdef GCC95
-GCC94=1
-endif
-
-ifdef GCC94
-GCC93=1
-endif
-
-ifdef GCC93
-GCC92=1
-endif
-
-ifdef GCC92
-GCC91=1
-endif
-
-ifdef GCC91
-GCC90=1
-endif
-
-ifdef GCC90
-GCC85=1
-endif
-
-ifdef GCC85
-GCC84=1
-endif
-
-ifdef GCC84
-GCC83=1
-endif
-
-ifdef GCC83
-GCC82=1
-endif
-
-ifdef GCC82
-GCC81=1
-endif
-
-ifdef GCC81
-GCC80=1
-endif
-
-ifdef GCC80
-GCC75=1
-endif
-
-ifdef GCC75
-GCC74=1
-endif
-
-ifdef GCC74
-GCC73=1
-endif
-
-ifdef GCC73
-GCC72=1
-endif
-
-ifdef GCC72
-GCC71=1
-endif
-
-ifdef GCC71
-GCC70=1
-endif
-
-ifdef GCC70
-GCC64=1
-endif
-
-ifdef GCC64
-GCC63=1
-endif
-
-ifdef GCC63
-GCC62=1
-endif
-
-ifdef GCC62
-GCC61=1
-endif
-
-ifdef GCC61
-GCC60=1
-endif
-
-ifdef GCC60
-GCC55=1
-endif
-
-ifdef GCC55
-GCC54=1
-endif
-
-ifdef GCC54
-GCC53=1
-endif
-
-ifdef GCC53
-GCC52=1
-endif
-
-ifdef GCC52
-GCC51=1
-endif
-
-ifdef GCC51
-GCC50=1
-endif
-
-ifdef GCC50
-GCC49=1
-endif
-
-ifdef GCC49
-GCC48=1
-endif
-
-ifdef GCC48
-GCC47=1
-endif
-
-ifdef GCC47
-GCC46=1
-endif
-
-ifdef GCC46
-GCC45=1
-endif
-
-ifdef GCC45
-GCC44=1
-endif
-
-ifdef GCC44
-GCC43=1
-endif
-
-ifdef GCC43
-GCC42=1
-endif
-
-ifdef GCC42
-GCC41=1
-endif
-
-ifdef GCC41
-GCC40=1
-VCHELP=1
-endif
-
-ifdef GCC295
-GCC29=1
-endif
-
-OLDWFLAGS:=$(WFLAGS)
-# -W -Wno-unused
-WFLAGS=-Wall
-ifndef GCC295
-#WFLAGS+=-Wno-packed
-endif
-ifndef RELAXWARNINGS
- WFLAGS+=-W
-#WFLAGS+=-Wno-sign-compare
-ifndef GCC295
- WFLAGS+=-Wno-div-by-zero
-endif
-#WFLAGS+=-Wsystem-headers
-WFLAGS+=-Wfloat-equal
-#WFLAGS+=-Wtraditional
-ifdef VCHELP
- #WFLAGS+=-Wdeclaration-after-statement
- WFLAGS+=-Wno-error=declaration-after-statement
-endif
- WFLAGS+=-Wundef
-ifndef GCC295
- WFLAGS+=-Wendif-labels
-endif
-ifdef GCC41
- WFLAGS+=-Wshadow
-endif
-#WFLAGS+=-Wlarger-than-%len%
- WFLAGS+=-Wpointer-arith -Wbad-function-cast
-ifdef GCC45
-#WFLAGS+=-Wc++-compat
-endif
- WFLAGS+=-Wcast-qual
-ifndef NOCASTALIGNWARN
- WFLAGS+=-Wcast-align
-endif
- WFLAGS+=-Wwrite-strings
-ifndef ERRORMODE
-#WFLAGS+=-Wconversion
-ifdef GCC43
- #WFLAGS+=-Wno-sign-conversion
-endif
-endif
- WFLAGS+=-Wsign-compare
-ifdef GCC45
- WFLAGS+=-Wlogical-op
-endif
- WFLAGS+=-Waggregate-return
-ifdef HAIKU
-ifdef GCC41
- #WFLAGS+=-Wno-attributes
-endif
-endif
-#WFLAGS+=-Wstrict-prototypes
-ifdef GCC40
- WFLAGS+=-Wold-style-definition
-endif
- WFLAGS+=-Wmissing-prototypes -Wmissing-declarations
-ifdef GCC40
- WFLAGS+=-Wmissing-field-initializers
-endif
- WFLAGS+=-Wmissing-noreturn
-#WFLAGS+=-Wmissing-format-attribute
-#WFLAGS+=-Wno-multichar
-#WFLAGS+=-Wno-deprecated-declarations
-#WFLAGS+=-Wpacked
-#WFLAGS+=-Wpadded
-#WFLAGS+=-Wredundant-decls
- WFLAGS+=-Wnested-externs
-#WFLAGS+=-Wunreachable-code
- WFLAGS+=-Winline
-ifdef GCC43
- WFLAGS+=-funit-at-a-time
- WFLAGS+=-Wlogical-op
-endif
-ifndef GCC295
- WFLAGS+=-Wdisabled-optimization
-endif
-endif
-WFLAGS+=-Wformat-y2k
-ifdef GCC71
-WFLAGS+=-Wno-error=format-overflow=2
-endif
-WFLAGS+=-Wformat-security
-ifndef GCC29
-#WFLAGS+=-Winit-self
-endif
-ifdef GCC46
-WFLAGS+=-Wno-suggest-attribute=noreturn
-endif
-
-ifdef NOLDWARNING
-LDFLAGS+=-Wl,--as-needed
-endif
-
-ifdef ERRORMODE
-WFLAGS+=-Werror
-endif
-
-WFLAGS+=$(OLDWFLAGS)
-
-ifdef GCC43
- #WFLAGS+=-Wno-error=clobbered
-endif
-ifdef GCC44
- WFLAGS+=-Wno-error=array-bounds
-endif
-ifdef GCC46
- WFLAGS+=-Wno-error=suggest-attribute=noreturn
-endif
-ifdef GCC54
- WFLAGS+=-Wno-logical-op -Wno-error=logical-op
-endif
-ifdef GCC61
- WFLAGS+=-Wno-tautological-compare -Wno-error=tautological-compare
-endif
-ifdef GCC71
- WFLAGS+=-Wno-error=implicit-fallthrough
- WFLAGS+=-Wno-implicit-fallthrough
- WFLAGS+=-Wno-format-truncation
-endif
-ifdef GCC81
- WFLAGS+=-Wno-error=format-overflow
- WFLAGS+=-Wno-error=stringop-truncation
- WFLAGS+=-Wno-error=stringop-overflow
- WFLAGS+=-Wno-format-overflow
- WFLAGS+=-Wno-stringop-truncation
- WFLAGS+=-Wno-stringop-overflow
- WFLAGS+=-Wno-error=multistatement-macros
-endif
-
-#indicate platform and what interface use with
-ifndef LINUX
-ifndef FREEBSD
-ifndef CYGWIN32
-ifndef MINGW
-ifndef MINGW64
-ifndef SDL
-$(error No interface or platform flag defined)
-endif
-endif
-endif
-endif
-endif
-endif
-
-#determine the interface directory (where you put all i_*.c)
-i_net_o=$(OBJDIR)/i_net.o
-i_system_o=$(OBJDIR)/i_system.o
-i_sound_o=$(OBJDIR)/i_sound.o
-i_main_o=$(OBJDIR)/i_main.o
-#set OBJDIR and BIN's starting place
-OBJDIR=../objs
-BIN=../bin
-REMOVE?=rm -f
-CP?=cp
-MKDIR?=mkdir -p
-MKISOFS?=mkisofs
-DD?=dd
-GZIP?=gzip
-GZIP_OPTS?=-9 -f -n
-GZIP_OPT2=$(GZIP_OPTS) --rsyncable
-UPX?=upx
-UPX_OPTS?=--best --preserve-build-id
-ifndef ECHO
-UPX_OPTS+=-q
-endif
-
-#Interface Setup
-ifdef LINUX
- SDL=1
-ifdef LINUX64
- OBJDIR:=$(OBJDIR)/Linux64
- BIN:=$(BIN)/Linux64
-else
- OBJDIR:=$(OBJDIR)/Linux
- BIN:=$(BIN)/Linux
-endif
-else
-ifdef FREEBSD
- INTERFACE=sdl
- SDL=1
-
- OBJDIR:=$(OBJDIR)/FreeBSD
- BIN:=$(BIN)/FreeBSD
-else
-ifdef SOLARIS
- INTERFACE=sdl
- SDL=1
-
- OBJDIR:=$(OBJDIR)/Solaris
- BIN:=$(BIN)/Solaris
-else
-ifdef CYGWIN32
- INTERFACE=sdl
- SDL=1
-
- OBJDIR:=$(OBJDIR)/cygwin
- BIN:=$(BIN)/Cygwin
-else
-ifdef MINGW64
- INTERFACE=win32
- OBJDIR:=$(OBJDIR)/Mingw64
- BIN:=$(BIN)/Mingw64
-else
-ifdef MINGW
- INTERFACE=win32
- OBJDIR:=$(OBJDIR)/Mingw
- BIN:=$(BIN)/Mingw
-endif
-endif
-endif
-endif
-endif
-endif
-
-ifdef ARCHNAME
- OBJDIR:=$(OBJDIR)/$(ARCHNAME)
- BIN:=$(BIN)/$(ARCHNAME)
-endif
-
-OBJDUMP_OPTS?=--wide --source --line-numbers
-LD=$(CC)
-
-ifdef SDL
- INTERFACE=sdl
- OBJDIR:=$(OBJDIR)/SDL
-endif
-
-ifdef DEBUGMODE
- OBJDIR:=$(OBJDIR)/Debug
- BIN:=$(BIN)/Debug
-else
- OBJDIR:=$(OBJDIR)/Release
- BIN:=$(BIN)/Release
-endif
diff --git a/src/Makefile.d/dedicated.mk b/src/Makefile.d/dedicated.mk
new file mode 100644
index 000000000..a421b465d
--- /dev/null
+++ b/src/Makefile.d/dedicated.mk
@@ -0,0 +1,19 @@
+makedir:=$(makedir)/Dedicated
+
+sources+=$(call List,dedicated/Sourcefile)
+
+opts+=-DDEDICATED
+
+ifdef MINGW
+libs+=-mconsole
+endif
+
+ifndef NOTHREADS
+opts+=-DHAVE_THREADS
+sources+=dedicated/i_threads.c
+endif
+
+NOOPENMPT=1
+NOGME=1
+NOHW=1
+NOUPNP=1
diff --git a/src/Makefile.d/detect.mk b/src/Makefile.d/detect.mk
new file mode 100644
index 000000000..dd31d2f3e
--- /dev/null
+++ b/src/Makefile.d/detect.mk
@@ -0,0 +1,124 @@
+#
+# Detect the host system and compiler version.
+#
+
+# Previously featured:\
+ PANDORA\
+ DUMMY\
+ DJGPPDOS\
+ SOLARIS\
+ MACOSX\
+
+all_systems:=\
+ LINUX64\
+ MINGW64\
+ MINGW\
+ UNIX\
+ LINUX\
+ FREEBSD\
+ HAIKU\
+
+# check for user specified system
+ifeq (,$(filter $(all_systems),$(.VARIABLES)))
+ifeq ($(OS),Windows_NT) # all windows are Windows_NT...
+
+ ifeq ($(shell uname -s | grep -o MINGW64),MINGW64) # 64-bit MinGW
+ _m=Detected a Windows system,\
+ compiling for 64-bit MinGW SDL...)
+ $(call Print,$(_m))
+ MINGW64=1
+ else # 32-bit MinGW
+ _m=Detected a Windows system,\
+ compiling for 32-bit MinGW SDL...)
+ $(call Print,$(_m))
+ MINGW=1
+ endif
+
+ NOOBJDUMP=1
+else # if you on the *nix
+
+system:=$(shell uname -s)
+
+ifeq ($(system),Linux)
+new_system:=LINUX
+else ifeq ($(system),Haiku)
+new_system:=HAIKU
+else
+
+$(error \
+ Could not automatically detect your system,\
+ try specifying a system manually)
+
+endif
+
+ifeq ($(shell getconf LONG_BIT),64)
+system+=64-bit
+new_system:=$(new_system)64
+endif
+
+$(call Print,Detected $(system) ($(new_system))...)
+$(new_system):=1
+
+endif
+endif
+
+# This must have high to low order.
+gcc_versions:=\
+ 151 150 15\
+ 142 141 140 14\
+ 132 131 130 13\
+ 123 122 121 120 12\
+ 114 113 112 111 110 11\
+ 105 104 103 102 101 100 10\
+ 95 94 93 92 91 90\
+ 85 84 83 82 81 80\
+ 75 74 73 72 71 70\
+ 64 63 62 61 60\
+ 55 54 53 52 51 50\
+ 49 48 47 46 45 44 43 42 41 40
+
+latest_gcc_version:=15.1.1
+
+# Automatically set version flag, but not if one was
+# manually set. And don't bother if this is a clean only
+# run.
+ifeq (,$(call Wildvar,GCC% destructive))
+
+# can't use $(CC) --version here since that uses argv[0] to display the name
+# also gcc outputs the information to stderr, so I had to do 2>&1
+# this program really doesn't like identifying itself
+shellversion:=$(shell $(CC) -v 2>&1)
+# Try to remove "-win32"
+version:=$(subst -win32,.0,$(shellversion))
+
+# check if this is in fact GCC
+ifneq (,$(findstring gcc version,$(version)))
+
+# in stark contrast to the name, gcc will give me a nicely formatted version number for free
+shellversion:=$(shell $(CC) -dumpfullversion)
+
+# Try to remove "-win32"
+version:=$(subst -win32,.0,$(shellversion))
+
+# Turn version into words of major, minor
+v:=$(subst ., ,$(version))
+# concat. major minor
+v:=$(word 1,$(v))$(word 2,$(v))
+
+# If this version is not in the list,
+# default to the latest supported
+ifeq (,$(filter $(v),$(gcc_versions)))
+define line =
+Your compiler version, GCC $(version), \
+is not supported by the Makefile.
+The Makefile will assume GCC $(latest_gcc_version).
+endef
+$(call Print,$(line))
+GCC$(subst .,,$(latest_gcc_version)):=1
+else
+$(call Print,Detected GCC $(version) (GCC$(v)))
+GCC$(v):=1
+endif
+
+endif
+endif
diff --git a/src/Makefile.d/features.mk b/src/Makefile.d/features.mk
new file mode 100644
index 000000000..71624241f
--- /dev/null
+++ b/src/Makefile.d/features.mk
@@ -0,0 +1,104 @@
+#
+# Makefile for feature flags.
+#
+
+passthru_opts+=\
+ NOHW NOMD5 NOPOSTPROCESSING\
+ MOBJCONSISTANCY PACKETDROP ZDEBUG\
+ HAVE_MINIUPNPC\
+ HAVE_DISCORDRPC DEVELOP\
+ NOBLUAJIT
+
+# build with debugging information
+ifdef DEBUGMODE
+PACKETDROP=1
+opts+=-DPARANOIA -DRANGECHECK
+endif
+
+ifndef NOHW
+opts+=-DHWRENDER
+
+ifndef NOSCREENFBO
+opts+=-DUSE_FBO_OGL
+endif
+
+sources+=$(call List,hardware/Sourcefile)
+endif
+
+ifndef NOMD5
+sources+=md5.c
+endif
+
+ifndef NONET
+ifndef NOSATURNJOIN
+opts+=-DDOSATURNJOIN
+endif
+ifndef NOSATURNPAK
+opts+=-DDOSATURNPAK
+endif
+endif
+
+ifndef NOZLIB
+ifndef NOPNG
+ifdef PNG_PKGCONFIG
+$(eval $(call Use_pkg_config,PNG_PKGCONFIG))
+else
+PNG_CONFIG?=$(call Prefix,libpng-config)
+$(eval $(call Configure,PNG,$(PNG_CONFIG) \
+ $(if $(PNG_STATIC),--static),,--ldflags))
+endif
+ifdef LINUX
+opts+=-D_LARGEFILE64_SOURCE
+endif
+opts+=-DHAVE_PNG
+sources+=apng.c
+endif
+endif
+
+ifndef NOCURL
+CURLCONFIG?=curl-config
+$(eval $(call Configure,CURL,$(CURLCONFIG)))
+opts+=-DHAVE_CURL
+endif
+
+ifdef HAVE_MINIUPNPC
+MINIUPNPC_PKGCONFIG?=miniupnpc
+$(eval $(call Use_pkg_config,MINIUPNPC))
+HAVE_MINIUPNPC=1
+opts+=-DHAVE_MINIUPNPC
+endif
+
+ifndef NOLIBBACKTRACE
+libs+=-lbacktrace
+opts+=-DHAVE_LIBBACKTRACE
+endif
+
+#windoze hack
+ifdef MINGW
+ifndef NODISCORDRPC
+HAVE_DISCORDRPC=1
+endif
+endif
+
+ifdef HAVE_DISCORDRPC
+libs+=-ldiscord-rpc
+opts+=-DUSE_STUN
+sources+=discord.c stun.c
+endif
+
+# (Valgrind is a memory debugger.)
+ifdef VALGRIND
+VALGRIND_PKGCONFIG?=valgrind
+VALGRIND_LDFLAGS=
+$(eval $(call Use_pkg_config,VALGRIND))
+ZDEBUG=1
+opts+=-DHAVE_VALGRIND
+endif
+
+default_packages:=\
+ GME/libgme/LIBGME\
+ OPENMPT/libopenmpt/LIBOPENMPT\
+ ZLIB/zlib\
+
+$(foreach p,$(default_packages),\
+ $(eval $(call Check_pkg_config,$(p))))
diff --git a/src/Makefile.d/haiku.mk b/src/Makefile.d/haiku.mk
new file mode 100644
index 000000000..6742ec75b
--- /dev/null
+++ b/src/Makefile.d/haiku.mk
@@ -0,0 +1,71 @@
+#
+# Makefile options for Haiku
+#
+
+opts+=-DUNIXCOMMON -DLUA_USE_POSIX
+
+ifndef DEDICATED
+ifndef DUMMY
+SDL?=1
+DEDICATED?=0
+endif
+endif
+
+NOEXECINFO=1
+
+ifeq (${SDL},1)
+EXENAME?=srb2haiku
+else ifeq (${DEDICATED},1)
+EXENAME?=srb2haikud
+endif
+
+ifndef NONET
+libs+=-lnetwork
+endif
+
+define _set =
+$(1)_CFLAGS?=$($(1)_opts)
+$(1)_LDFLAGS?=$($(1)_libs)
+endef
+
+lib:=../libs/gme
+LIBGME_opts:=-I$(lib)/include
+LIBGME_libs:=-l:libgme.so.0
+$(eval $(call _set,LIBGME))
+
+lib:=../libs/libopenmpt
+LIBOPENMPT_opts:=-I$(lib)/inc
+LIBOPENMPT_libs:=-l:libopenmpt.so.0
+$(eval $(call _set,LIBOPENMPT))
+
+ifdef SDL
+lib:=../libs/SDL2_mixer
+mixer_opts:=-I$(lib)/include
+mixer_libs:=-l:libSDL2_mixer-2.0.so.0
+
+lib:=../libs/SDL2
+SDL_opts:=-I$(lib)/include $(mixer_opts)
+SDL_libs:=$(mixer_libs) -l:libSDL2-2.0.so.0
+$(eval $(call _set,SDL))
+endif
+
+lib:=../libs/zlib
+ZLIB_opts:=-I$(lib)
+ZLIB_libs:=-l:libz.so.1
+$(eval $(call _set,ZLIB))
+
+ifndef PNG_CONFIG
+PNG_opts:=
+PNG_libs:=-l:libpng16.so.16
+$(eval $(call _set,PNG))
+endif
+
+lib:=../libs/curl
+CURL_opts:=-I$(lib)/include
+CURL_libs:=-l:libcurl.so.4
+$(eval $(call _set,CURL))
+
+lib:=../libs/miniupnpc
+MINIUPNPC_opts:=-I$(lib)/include
+MINIUPNPC_libs:=-l:libminiupnpc.so.17
+$(eval $(call _set,MINIUPNPC))
diff --git a/src/Makefile.d/nix.mk b/src/Makefile.d/nix.mk
new file mode 100644
index 000000000..7135f258b
--- /dev/null
+++ b/src/Makefile.d/nix.mk
@@ -0,0 +1,47 @@
+#
+# Makefile options for unices (linux, bsd...)
+#
+
+
+opts+=-DUNIXCOMMON -DLUA_USE_POSIX
+# Use -rdynamic so a backtrace log shows function names
+# instead of addresses
+libs+=-lm -rdynamic
+
+ifndef NOHW
+opts+=-I/usr/X11R6/include
+libs+=-L/usr/X11R6/lib
+endif
+
+ifndef DEDICATED
+SDL?=1
+DEDICATED?=0
+endif
+
+ifeq (${SDL},1)
+EXENAME?=lsdl2srb2kart
+endif
+
+ifeq (${DEDICATED},1)
+EXENAME?=lsrb2kartd
+endif
+
+# In common usage.
+ifdef LINUX
+libs+=-lrt
+passthru_opts+=NOTERMIOS
+endif
+
+# Tested by Steel, as of release 2.2.8.
+ifdef FREEBSD
+opts+=-I/usr/X11R6/include -DLINUX -DFREEBSD
+libs+=-L/usr/X11R6/lib -lkvm -lexecinfo
+endif
+
+# FIXME: UNTESTED
+#ifdef SOLARIS
+#NOIPX=1
+#opts+=-I/usr/local/include -I/opt/sfw/include \
+# -DSOLARIS -DINADDR_NONE=INADDR_ANY -DBSD_COMP
+#libs+=-L/opt/sfw/lib -lsocket -lnsl
+#endif
diff --git a/src/Makefile.d/old.mk b/src/Makefile.d/old.mk
new file mode 100644
index 000000000..ec9b6d776
--- /dev/null
+++ b/src/Makefile.d/old.mk
@@ -0,0 +1,16 @@
+#
+# Warn about old build directories and offer to purge.
+#
+
+_old:=$(wildcard $(addprefix ../bin/,FreeBSD Linux \
+ Linux64 Mingw Mingw64 SDL dummy) ../objs ../dep)
+
+ifdef _old
+$(foreach v,$(_old),$(info $(abspath $(v))))
+$(info )
+$(info These directories are no longer\
+ required and should be removed.)
+$(info You may remove them manually or\
+ by using 'make distclean')
+$(error )
+endif
diff --git a/src/Makefile.d/platform.mk b/src/Makefile.d/platform.mk
new file mode 100644
index 000000000..d5423a397
--- /dev/null
+++ b/src/Makefile.d/platform.mk
@@ -0,0 +1,76 @@
+#
+# Platform specific options.
+#
+
+PKG_CONFIG?=pkg-config
+
+ifdef WINDOWSHELL
+rmrf=-2>NUL DEL /S /Q
+mkdir=-2>NUL MD
+cat=TYPE
+else
+rmrf=rm -rf
+mkdir=mkdir -p
+cat=cat
+endif
+
+ifdef LINUX64
+LINUX=1
+endif
+
+ifdef MINGW64
+MINGW=1
+endif
+
+ifdef LINUX
+UNIX=1
+ifdef LINUX64
+NONX86=1
+# LINUX64 does not imply X86_64=1;
+# could mean ARM64 or Itanium
+platform=linux/64
+else
+platform=linux
+endif
+else ifdef FREEBSD
+UNIX=1
+platform=freebsd
+else ifdef HAIKU
+# Give Haiku its own configuration, since it
+# isn't actually UNIX.
+include Makefile.d/haiku.mk
+else ifdef SOLARIS # FIXME: UNTESTED
+UNIX=1
+platform=solaris
+else ifdef CYGWIN32 # FIXME: UNTESTED
+platform=cygwin
+else ifdef MINGW
+ifdef MINGW64
+NONX86=1
+NOASM=1
+# MINGW64 should not necessarily imply X86_64=1,
+# but we make that assumption elsewhere
+# Once that changes, remove this
+X86_64=1
+platform=mingw/64
+else
+platform=mingw
+endif
+include Makefile.d/win32.mk
+endif
+
+ifdef platform
+makedir:=$(makedir)/$(platform)
+endif
+
+ifdef UNIX
+include Makefile.d/nix.mk
+endif
+
+ifeq ($(SDL), 1)
+include Makefile.d/sdl.mk
+else ifeq ($(DEDICATED), 1)
+include Makefile.d/dedicated.mk
+else
+include Makefile.d/dummy.mk
+endif
diff --git a/src/Makefile.d/sdl.mk b/src/Makefile.d/sdl.mk
new file mode 100644
index 000000000..c704a83eb
--- /dev/null
+++ b/src/Makefile.d/sdl.mk
@@ -0,0 +1,71 @@
+#
+# Makefile options for SDL2 backend.
+#
+
+#
+# SDL...., *looks at Alam*, THIS IS A MESS!
+#
+# ...a little bird flexes its muscles...
+#
+
+makedir:=$(makedir)/SDL
+
+opts+=-DDIRECTFULLSCREEN -DHAVE_SDL
+sources+=$(call List,sdl/Sourcefile)
+
+NOUPNP=1
+
+# FIXME: UNTESTED
+#ifdef PANDORA
+#include sdl/SRB2Pandora/Makefile.cfg
+#endif #ifdef PANDORA
+
+# FIXME: UNTESTED
+#ifdef CYGWIN32
+#include sdl/MakeCYG.cfg
+#endif #ifdef CYGWIN32
+
+ifndef NOHW
+sources+=sdl/ogl_sdl.c
+endif
+
+ifdef NOMIXER
+sources+=sdl/sdl_sound.c
+else
+opts+=-DHAVE_MIXER
+sources+=sdl/mixer_sound.c
+
+ ifndef HAIKU # Haiku has a special import path
+ libs+=-lSDL2_mixer
+ endif
+endif
+
+ifndef NOTHREADS
+opts+=-DHAVE_THREADS
+sources+=sdl/i_threads.c
+endif
+
+ifdef SDL_PKGCONFIG
+$(eval $(call Use_pkg_config,SDL))
+else
+SDL_CONFIG?=$(call Prefix,sdl2-config)
+SDL_CFLAGS?=$(shell $(SDL_CONFIG) --cflags)
+SDL_LDFLAGS?=$(shell $(SDL_CONFIG) \
+ $(if $(STATIC),--static-libs,--libs))
+$(eval $(call Propogate_flags,SDL))
+endif
+
+ifdef MINGW
+ifndef NOSDLMAIN
+SDLMAIN=1
+endif
+endif
+
+ifdef SDLMAIN
+opts+=-DSDLMAIN
+else
+ifdef MINGW
+opts+=-Umain
+libs+=-mconsole
+endif
+endif
diff --git a/src/Makefile.d/util.mk b/src/Makefile.d/util.mk
new file mode 100644
index 000000000..bda68df13
--- /dev/null
+++ b/src/Makefile.d/util.mk
@@ -0,0 +1,93 @@
+#
+# Utility macros for the rest of the Makefiles.
+#
+
+Ifnot=$(if $(1),$(3),$(2))
+Ifndef=$(call Ifnot,$($(1)),$(2),$(3))
+
+# Match and expand a list of variables by pattern.
+Wildvar=$(foreach v,$(filter $(1),$(.VARIABLES)),$($(v)))
+
+# Read a list of words from file and prepend each with the
+# directory of the file.
+_cat=$(shell $(cat) $(call Windows_path,$(1)))
+List=$(addprefix $(dir $(1)),$(call _cat,$(1)))
+
+# Convert path separators to backslash on Windows.
+Windows_path=$(if $(WINDOWSHELL),$(subst /,\,$(1)),$(1))
+
+define Propogate_flags =
+opts+=$$($(1)_CFLAGS)
+libs+=$$($(1)_LDFLAGS)
+endef
+
+# Set library's _CFLAGS and _LDFLAGS from some command.
+# Automatically propogates the flags too.
+# 1: variable prefix (e.g. CURL)
+# 2: start of command (e.g. curl-config)
+# --- optional ----
+# 3: CFLAGS command arguments, default '--cflags'
+# 4: LDFLAGS command arguments, default '--libs'
+# 5: common command arguments at the end of command
+define Configure =
+$(1)_CFLAGS?=$$(shell $(2) $(or $(3),--cflags) $(5))
+$(1)_LDFLAGS?=$$(shell $(2) $(or $(4),--libs) $(5))
+$(call Propogate_flags,$(1))
+endef
+
+# Configure library with pkg-config. The package name is
+# taken from a _PKGCONFIG variable.
+# 1: variable prefix
+#
+# LIBGME_PKGCONFIG=libgme
+# $(eval $(call Use_pkg_config,LIBGME))
+define Use_pkg_config =
+$(call Configure,$(1),$(PKG_CONFIG),,,$($(1)_PKGCONFIG))
+endef
+
+# Check disabling flag and configure package in one step
+# according to delimited argument.
+# (There is only one argument, but it split by slash.)
+# 1/: short form library name (uppercase). This is
+# prefixed with 'NO' and 'HAVE_'. E.g. NOGME, HAVE_GME
+# /2: package name (e.g. libgme)
+# /3: variable prefix
+#
+# The following example would check if NOGME is not
+# defined before attempting to define LIBGME_CFLAGS and
+# LIBGME_LDFLAGS as with Use_pkg_config.
+#
+# $(eval $(call Check_pkg_config,GME/libgme/LIBGME))
+define Check_pkg_config =
+_p:=$(subst /, ,$(1))
+_v1:=$$(word 1,$$(_p))
+_v2:=$$(or $$(word 3,$$(_p)),$$(_v1))
+ifndef NO$$(_v1)
+$$(_v2)_PKGCONFIG?=$$(word 2,$$(_p))
+$$(eval $$(call Use_pkg_config,$$(_v2)))
+opts+=-DHAVE_$$(_v1)
+endif
+endef
+
+# $(call Prefix,gcc)
+Prefix=$(if $(PREFIX),$(PREFIX)-)$(1)
+
+Echo=
+Echo_name=
+Print=
+
+ifndef SILENT
+Echo=@echo $(1)
+ifndef ECHO
+ifndef NOECHOFILENAMES
+Echo_name=$(call Echo,-- $(1) ...)
+endif
+endif
+ifndef MAKE_RESTARTS
+ifndef destructive
+Print=$(info $(1))
+endif
+endif
+endif
+
+.=$(call Ifndef,ECHO,@)
diff --git a/src/Makefile.d/versions.mk b/src/Makefile.d/versions.mk
new file mode 100644
index 000000000..ce23c3e4e
--- /dev/null
+++ b/src/Makefile.d/versions.mk
@@ -0,0 +1,181 @@
+#
+# Flags to put a sock in GCC!
+#
+
+# See the versions list in detect.mk
+# This will define all version flags going backward.
+# Yes, it's magic.
+define _predecessor =
+ifdef GCC$(firstword $(1))
+GCC$(lastword $(1)):=1
+endif
+endef
+_n:=$(words $(gcc_versions))
+$(foreach v,$(join $(wordlist 2,$(_n),- $(gcc_versions)),\
+ $(addprefix =,$(wordlist 2,$(_n),$(gcc_versions)))),\
+ $(and $(findstring =,$(v)),\
+ $(eval $(call _predecessor,$(subst =, ,$(v))))))
+
+# aggregate returns seem to happen alot in c++ so just supress em lel
+CXXFLAGS+= -Wno-aggregate-return
+
+# -W -Wno-unused
+
+ifdef GCC150
+ opts+=-std=gnu17
+endif
+WFLAGS:=-Wall -Wno-trigraphs
+ifndef GCC295
+#WFLAGS+=-Wno-packed
+endif
+ifndef RELAXWARNINGS
+ WFLAGS+=-W
+#WFLAGS+=-Wno-sign-compare
+ifndef GCC295
+ WFLAGS+=-Wno-div-by-zero
+endif
+#WFLAGS+=-Wsystem-headers
+WFLAGS+=-Wfloat-equal
+#WFLAGS+=-Wtraditional
+ WFLAGS+=-Wundef
+ifndef GCC295
+ WFLAGS+=-Wendif-labels
+endif
+ifdef GCC41
+ WFLAGS+=-Wshadow
+endif
+#WFLAGS+=-Wlarger-than-%len%
+ WFLAGS+=-Wpointer-arith -Wbad-function-cast
+ifdef GCC45
+#WFLAGS+=-Wc++-compat
+endif
+ WFLAGS+=-Wcast-qual
+ifndef NOCASTALIGNWARN
+ WFLAGS+=-Wcast-align
+endif
+ WFLAGS+=-Wwrite-strings
+ifndef ERRORMODE
+#WFLAGS+=-Wconversion
+ifdef GCC43
+ #WFLAGS+=-Wno-sign-conversion
+endif
+endif
+ WFLAGS+=-Wsign-compare
+ifdef GCC91
+ WFLAGS+=-Wno-error=address-of-packed-member
+endif
+ifdef GCC45
+ WFLAGS+=-Wlogical-op
+endif
+ WFLAGS+=-Waggregate-return
+ifdef HAIKU
+ifdef GCC41
+ #WFLAGS+=-Wno-attributes
+endif
+endif
+#WFLAGS+=-Wstrict-prototypes
+ifdef GCC40
+ WFLAGS+=-Wold-style-definition
+endif
+ WFLAGS+=-Wmissing-prototypes -Wmissing-declarations
+ifdef GCC40
+ WFLAGS+=-Wmissing-field-initializers
+endif
+ WFLAGS+=-Wmissing-noreturn
+#WFLAGS+=-Wmissing-format-attribute
+#WFLAGS+=-Wno-multichar
+#WFLAGS+=-Wno-deprecated-declarations
+#WFLAGS+=-Wpacked
+#WFLAGS+=-Wpadded
+#WFLAGS+=-Wredundant-decls
+ WFLAGS+=-Wnested-externs
+#WFLAGS+=-Wunreachable-code
+ WFLAGS+=-Winline
+ifdef DEBUGMODE
+ WFLAGS+=-Wno-error=inline
+endif
+ifdef GCC43
+ WFLAGS+=-funit-at-a-time
+ WFLAGS+=-Wlogical-op
+endif
+ifndef GCC295
+ WFLAGS+=-Wdisabled-optimization
+endif
+endif
+WFLAGS+=-Wformat-y2k
+ifdef GCC71
+WFLAGS+=-Wno-error=format-overflow=2
+endif
+WFLAGS+=-Wformat-security
+ifndef GCC29
+#WFLAGS+=-Winit-self
+endif
+ifdef GCC46
+WFLAGS+=-Wno-suggest-attribute=noreturn
+endif
+
+ifdef NOLDWARNING
+LDFLAGS+=-Wl,--as-needed
+endif
+
+ifdef ERRORMODE
+WFLAGS+=-Werror
+endif
+
+ifdef GCC43
+ #WFLAGS+=-Wno-error=clobbered
+endif
+ifdef GCC44
+#WFLAGS+=-Wno-error=array-bounds
+endif
+ifdef GCC46
+ WFLAGS+=-Wno-error=suggest-attribute=noreturn
+endif
+ifdef GCC54
+ WFLAGS+=-Wno-logical-op -Wno-error=logical-op
+endif
+ifdef GCC61
+ WFLAGS+=-Wno-tautological-compare -Wno-error=tautological-compare
+endif
+ifdef GCC71
+ WFLAGS+=-Wimplicit-fallthrough=4
+endif
+ifdef GCC81
+ WFLAGS+=-Wno-error=format-overflow
+ WFLAGS+=-Wno-format-overflow
+ WFLAGS+=-Wno-error=multistatement-macros
+endif
+
+ifdef NONX86
+ ifdef X86_64 # yeah that SEEMS contradictory
+ opts+=-march=nocona
+ endif
+else
+ ifndef GCC29
+ opts+=-msse3 -mfpmath=sse
+ else
+ opts+=-mpentium
+ endif
+endif
+
+ifdef DEBUGMODE
+ifdef GCC48
+opts+=-Og
+else
+opts+=-O0
+endif
+endif
+
+ifdef VALGRIND
+ifdef GCC46
+WFLAGS+=-Wno-error=unused-but-set-variable
+WFLAGS+=-Wno-unused-but-set-variable
+endif
+endif
+
+# Lua
+ifdef GCC43
+ifndef GCC44
+WFLAGS+=-Wno-logical-op
+endif
+endif
diff --git a/src/Makefile.d/win32.mk b/src/Makefile.d/win32.mk
new file mode 100644
index 000000000..4946c4ca2
--- /dev/null
+++ b/src/Makefile.d/win32.mk
@@ -0,0 +1,124 @@
+#
+# Mingw, if you don't know, that's Win32/Win64
+#
+
+ifndef MINGW64
+EXENAME?=srb2kart-saturn_32bit.exe
+else
+EXENAME?=srb2kart-saturn_64bit.exe
+endif
+
+# disable dynamicbase if under msys2
+ifdef MSYSTEM
+libs+=-Wl,--disable-dynamicbase
+endif
+
+sources+=win32/Srb2win.rc
+opts+=-DSTDC_HEADERS
+libs+=-ladvapi32 -lkernel32 -lmsvcrt -luser32
+
+ifndef DEDICATED
+ifndef DUMMY
+SDL?=1
+endif
+endif
+
+ifndef NOHW
+opts+=-DUSE_WGL_SWAP
+endif
+
+ifdef MINGW64
+libs+=-lws2_32
+else
+#ifndef HAVE_IPV6
+#libs+=-lwsock32
+#else
+libs+=-lws2_32
+#endif
+endif
+
+ifndef MINGW64
+libs+=-Wl,--large-address-aware
+NOLIBBACKTRACE=1
+endif
+
+ifndef MINGW64
+32=32
+x86=x86
+i686=i686
+else
+32=64
+x86=x86_64
+i686=x86_64
+endif
+
+mingw:=$(i686)-w64-mingw32
+
+define _set =
+$(1)_CFLAGS?=$($(1)_opts)
+$(1)_LDFLAGS?=$($(1)_libs)
+endef
+
+lib:=../libs/gme
+LIBGME_opts:=-I$(lib)/include
+LIBGME_libs:=-L$(lib)/win$(32) -lgme
+$(eval $(call _set,LIBGME))
+
+lib:=../libs/libopenmpt
+LIBOPENMPT_opts:=-I$(lib)/inc
+LIBOPENMPT_libs:=-L$(lib)/lib/$(x86)/mingw -lopenmpt
+$(eval $(call _set,LIBOPENMPT))
+
+lib:=../libs/SDL2_mixer/$(mingw)
+
+ifdef SDL
+mixer_opts:=-I$(lib)/include/SDL2
+mixer_libs:=-L$(lib)/lib
+
+lib:=../libs/SDL2/$(mingw)
+SDL_opts:=-I$(lib)/include/SDL2\
+ $(mixer_opts) -Dmain=SDL_main
+SDL_libs:=-L$(lib)/lib $(mixer_libs)\
+ -lmingw32 -lSDL2main -lSDL2 -mwindows
+$(eval $(call _set,SDL))
+endif
+
+ifdef MINGW64
+lib:=../libs/libbacktrace
+LIBBACKTRACE_opts:=-I$(lib)/include
+LIBBACKTRACE_libs:=-L$(lib)/lib/x86_64 -lbacktrace
+$(eval $(call _set,LIBBACKTRACE))
+else
+lib:=../libs/drmingw
+opts+=-I$(lib)/include
+libs+=-L$(lib)/lib/win32 -lmgwhelp -lexchndl
+endif
+
+lib:=../libs/zlib
+ZLIB_opts:=-I$(lib)
+ZLIB_libs:=-L$(lib)/win32 -l:libz$(32).a
+$(eval $(call _set,ZLIB))
+
+ifndef PNG_CONFIG
+lib:=../libs/libpng-src
+PNG_opts:=-I$(lib)
+PNG_libs:=-L$(lib)/projects -lpng$(32)
+$(eval $(call _set,PNG))
+endif
+
+lib:=../libs/curl
+CURL_opts:=-I$(lib)/include
+CURL_libs:=-L$(lib)/lib$(32) -lcurl
+$(eval $(call _set,CURL))
+
+ifndef MINGW64 # miniupnc is broken with MINGW64
+lib:=../libs/miniupnpc
+MINIUPNPC_opts:=-I$(lib)/include -DMINIUPNP_STATICLIB
+MINIUPNPC_libs:=-L$(lib)/mingw$(32) -lminiupnpc -lws2_32 -liphlpapi
+$(eval $(call _set,MINIUPNPC))
+endif
+
+lib:=../libs/discord-rpc/win$(32)-dynamic
+DISCORDRPC_opts+=-I$(lib)/include
+DISCORDRPC_libs+=-L$(lib)/lib -ldiscord-rpc
+$(eval $(call _set,DISCORDRPC))
diff --git a/src/Sourcefile b/src/Sourcefile
new file mode 100644
index 000000000..f3cc487c1
--- /dev/null
+++ b/src/Sourcefile
@@ -0,0 +1,99 @@
+am_map.c
+b_bot.c
+command.c
+console.c
+d_clisrv.c
+d_main.c
+d_net.c
+d_netcmd.c
+d_netfil.c
+d_protocol.c
+dehacked.c
+f_finale.c
+f_wipe.c
+filesrch.c
+g_game.c
+g_demo.c
+g_input.c
+hu_stuff.c
+i_tcp.c
+i_time.c
+info.c
+lzf.c
+m_aatree.c
+m_anigif.c
+m_argv.c
+m_bbox.c
+m_cheat.c
+m_cond.c
+m_fixed.c
+m_menu.c
+m_textinput.c
+m_misc.c
+m_perfstats.c
+m_queue.c
+m_random.c
+mserv.c
+http-mserv.c
+qs22j.c
+s_sound.c
+screen.c
+sounds.c
+st_stuff.c
+string.c
+tables.c
+v_video.c
+w_wad.c
+y_inter.c
+z_zone.c
+r_bsp.c
+r_data.c
+r_draw.c
+r_fps.c
+r_main.cpp
+r_patch.c
+r_patchrotation.c
+r_plane.cpp
+r_segs.cpp
+r_skins.c
+r_sky.c
+r_splats.c
+r_things.cpp
+r_portal.c
+p_ceilng.c
+p_enemy.c
+p_floor.c
+p_inter.c
+p_lights.c
+p_map.c
+p_maputl.c
+p_mobj.c
+p_polyobj.c
+p_saveg.c
+p_setup.c
+p_sight.c
+p_slopes.c
+p_spec.c
+p_telept.c
+p_tick.c
+p_user.c
+k_director.c
+k_kart.c
+k_hud.c
+k_stats.c
+lua_baselib.c
+lua_blockmaplib.c
+lua_consolelib.c
+lua_hooklib.c
+lua_hudlib.c
+lua_hudlib_drawlist.c
+lua_infolib.c
+lua_maplib.c
+lua_mathlib.c
+lua_mobjlib.c
+lua_playerlib.c
+lua_script.c
+lua_skinlib.c
+lua_thinkerlib.c
+lua_udatalib.c
+lua_glib.c
diff --git a/src/am_map.c b/src/am_map.c
index f91273e8b..fe0b5e9a5 100644
--- a/src/am_map.c
+++ b/src/am_map.c
@@ -197,7 +197,7 @@ static fixed_t scale_mtof = (fixed_t)INITSCALEMTOF;
// used by FTOM to scale from frame-buffer-to-map coords (=1/scale_mtof)
static fixed_t scale_ftom;
-static player_t *plr; // the player represented by an arrow
+static player_t *plr = NULL; // the player represented by an arrow
static boolean followplayer = true; // specifies whether to follow the player around
@@ -237,7 +237,7 @@ static inline void AM_restoreScaleAndLoc(void)
m_x = old_m_x;
m_y = old_m_y;
}
- else
+ else if (plr && plr->mo)
{
m_x = (plr->mo->x >> FRACTOMAPBITS) - m_w/2;
m_y = (plr->mo->y >> FRACTOMAPBITS) - m_h/2;
@@ -318,7 +318,8 @@ static void AM_initVariables(void)
break;
plr = &players[pnum];
- if (plr != NULL && plr->mo != NULL)
+
+ if (plr && plr->mo)
{
m_x = (plr->mo->x >> FRACTOMAPBITS) - m_w/2;
m_y = (plr->mo->y >> FRACTOMAPBITS) - m_h/2;
@@ -340,7 +341,7 @@ static void AM_FrameBufferInit(void)
f_x = f_y = 0;
f_w = vid.width;
f_h = vid.height;
- am_buf = screens[0];
+ am_buf = vid.screens[0];
}
//
@@ -597,6 +598,9 @@ static inline void AM_changeWindowScale(void)
static inline void AM_doFollowPlayer(void)
{
+ if (!plr || !plr->mo)
+ return;
+
if (f_oldloc.x != plr->mo->x || f_oldloc.y != plr->mo->y)
{
m_x = FTOM(MTOF(plr->mo->x >> FRACTOMAPBITS)) - m_w/2;
diff --git a/src/android/i_video.c b/src/android/i_video.c
index 8b4bee314..4db66afe0 100644
--- a/src/android/i_video.c
+++ b/src/android/i_video.c
@@ -46,7 +46,6 @@ INT32 VID_SetMode(INT32 modenum)
vid.modenum = 0;
vid.width = 320;
vid.height = 240;
- vid.bpp = 1;
vid.buffer = android_surface;
return 0;
}
diff --git a/src/blua/Makefile.cfg b/src/blua/Makefile.cfg
deleted file mode 100644
index f3d38fb70..000000000
--- a/src/blua/Makefile.cfg
+++ /dev/null
@@ -1,55 +0,0 @@
-ifdef UNIXCOMMON
-LUA_CFLAGS+=-DLUA_USE_POSIX
-endif
-ifdef LINUX
-LUA_CFLAGS+=-DLUA_USE_POSIX
-endif
-ifdef GCC43
-ifndef GCC44
-WFLAGS+=-Wno-logical-op
-endif
-endif
-
-OBJS:=$(OBJS) \
- $(OBJDIR)/lapi.o \
- $(OBJDIR)/lbaselib.o \
- $(OBJDIR)/ldo.o \
- $(OBJDIR)/ldblib.o \
- $(OBJDIR)/lfunc.o \
- $(OBJDIR)/linit.o \
- $(OBJDIR)/liolib.o \
- $(OBJDIR)/llex.o \
- $(OBJDIR)/lmem.o \
- $(OBJDIR)/lobject.o \
- $(OBJDIR)/lstate.o \
- $(OBJDIR)/lstrlib.o \
- $(OBJDIR)/ltablib.o \
- $(OBJDIR)/lundump.o \
- $(OBJDIR)/lzio.o \
- $(OBJDIR)/lauxlib.o \
- $(OBJDIR)/lcode.o \
- $(OBJDIR)/ldebug.o \
- $(OBJDIR)/ldump.o \
- $(OBJDIR)/lgc.o \
- $(OBJDIR)/lopcodes.o \
- $(OBJDIR)/lparser.o \
- $(OBJDIR)/lstring.o \
- $(OBJDIR)/ltable.o \
- $(OBJDIR)/ltm.o \
- $(OBJDIR)/lvm.o \
- $(OBJDIR)/lua_script.o \
- $(OBJDIR)/lua_baselib.o \
- $(OBJDIR)/lua_blockmaplib.o \
- $(OBJDIR)/lua_mathlib.o \
- $(OBJDIR)/lua_hooklib.o \
- $(OBJDIR)/lua_consolelib.o \
- $(OBJDIR)/lua_infolib.o \
- $(OBJDIR)/lua_mobjlib.o \
- $(OBJDIR)/lua_playerlib.o \
- $(OBJDIR)/lua_skinlib.o \
- $(OBJDIR)/lua_thinkerlib.o \
- $(OBJDIR)/lua_maplib.o \
- $(OBJDIR)/lua_hudlib.o \
- $(OBJDIR)/lua_hudlib_drawlist.o \
- $(OBJDIR)/lua_udatalib.o \
- $(OBJDIR)/lua_glib.o
diff --git a/src/blua/Sourcefile b/src/blua/Sourcefile
new file mode 100644
index 000000000..da89f45a4
--- /dev/null
+++ b/src/blua/Sourcefile
@@ -0,0 +1,26 @@
+lapi.c
+lauxlib.c
+lbaselib.c
+ldblib.c
+lcode.c
+ldebug.c
+ldo.c
+ldump.c
+lfunc.c
+lgc.c
+linit.c
+liolib.c
+llex.c
+lmem.c
+lobject.c
+lopcodes.c
+lparser.c
+lstate.c
+lstring.c
+lstrlib.c
+ltable.c
+ltablib.c
+ltm.c
+lundump.c
+lvm.c
+lzio.c
diff --git a/src/byteptr.h b/src/byteptr.h
index 0345038b8..205884acc 100644
--- a/src/byteptr.h
+++ b/src/byteptr.h
@@ -28,6 +28,7 @@
#define WRITEUINT8(p,b) do { UINT8 *p_tmp = (void *)p; const UINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITESINT8(p,b) do { SINT8 *p_tmp = (void *)p; const SINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEINT16(p,b) do { INT16 *p_tmp = (void *)p; const INT16 tv = ( INT16)(b); memcpy(p, &tv, sizeof( INT16)); p_tmp++; p = (void *)p_tmp; } while (0)
+#define WRITEINT16_2(p,b) do { INT16 *p_tmp = ( INT16 *)p; const INT16 tv = ( INT16)(b); memcpy(p, &tv, sizeof( INT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) // dumb hack for mumble
#define WRITEUINT16(p,b) do { UINT16 *p_tmp = (void *)p; const UINT16 tv = ( UINT16)(b); memcpy(p, &tv, sizeof( UINT16)); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEINT32(p,b) do { INT32 *p_tmp = (void *)p; const INT32 tv = ( INT32)(b); memcpy(p, &tv, sizeof( INT32)); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEUINT32(p,b) do { UINT32 *p_tmp = (void *)p; const UINT32 tv = ( UINT32)(b); memcpy(p, &tv, sizeof( UINT32)); p_tmp++; p = (void *)p_tmp; } while (0)
@@ -38,6 +39,7 @@
#define WRITEUINT8(p,b) do { UINT8 *p_tmp = ( UINT8 *)p; *p_tmp = ( UINT8)(b); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITESINT8(p,b) do { SINT8 *p_tmp = ( SINT8 *)p; *p_tmp = ( SINT8)(b); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEINT16(p,b) do { INT16 *p_tmp = ( INT16 *)p; *p_tmp = ( INT16)(b); p_tmp++; p = (void *)p_tmp; } while (0)
+#define WRITEINT16_2(p,b) do { INT16 *p_tmp = ( INT16 *)p; *p_tmp = ( INT16)(b); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) // dumb hack for mumble
#define WRITEUINT16(p,b) do { UINT16 *p_tmp = ( UINT16 *)p; *p_tmp = ( UINT16)(b); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEINT32(p,b) do { INT32 *p_tmp = ( INT32 *)p; *p_tmp = ( INT32)(b); p_tmp++; p = (void *)p_tmp; } while (0)
#define WRITEUINT32(p,b) do { UINT32 *p_tmp = ( UINT32 *)p; *p_tmp = ( UINT32)(b); p_tmp++; p = (void *)p_tmp; } while (0)
diff --git a/src/command.c b/src/command.c
index e7dd9cc01..3881246c1 100644
--- a/src/command.c
+++ b/src/command.c
@@ -240,7 +240,6 @@ void COM_ImmedExecute(const char *ptext)
while (i < strlen(ptext))
{
-
quotes = 0;
for (j = 0; i < strlen(ptext); i++,j++)
{
@@ -817,12 +816,17 @@ static void COM_Help_f(void)
cvar = CV_FindVar(help);
if (cvar)
{
+ boolean floatmode = false;
+ const char *cvalue = NULL;
CONS_Printf("\x82""Variable %s:\n", cvar->name);
CONS_Printf(M_GetText(" flags: "));
if (cvar->flags & CV_SAVE)
CONS_Printf("AUTOSAVE ");
if (cvar->flags & CV_FLOAT)
+ {
CONS_Printf("FLOAT ");
+ floatmode = true;
+ }
if (cvar->flags & CV_NETVAR)
CONS_Printf("NETVAR ");
if (cvar->flags & CV_CALL)
@@ -832,30 +836,43 @@ static void COM_Help_f(void)
CONS_Printf("\n");
if (cvar->PossibleValue)
{
- if (!stricmp(cvar->PossibleValue[0].strvalue, "MIN") && !stricmp(cvar->PossibleValue[1].strvalue, "MAX"))
{
- CONS_Printf(" range from %d to %d\n", cvar->PossibleValue[0].value,
- cvar->PossibleValue[1].value);
- i = 2;
- }
+ if (!stricmp(cvar->PossibleValue[0].strvalue, "MIN") && !stricmp(cvar->PossibleValue[1].strvalue, "MAX"))
+ {
+ if (floatmode)
+ {
+ float fu = FIXED_TO_FLOAT(cvar->PossibleValue[0].value);
+ float ck = FIXED_TO_FLOAT(cvar->PossibleValue[1].value);
+ CONS_Printf(" range from %ld%s to %ld%s\n",
+ (long)fu, M_Ftrim(fu),
+ (long)ck, M_Ftrim(ck));
+ }
+ else
+ CONS_Printf(" range from %d to %d\n", cvar->PossibleValue[0].value,
+ cvar->PossibleValue[1].value);
+ i = 2;
+ }
- {
- const char *cvalue = NULL;
//CONS_Printf(M_GetText(" possible value : %s\n"), cvar->name);
while (cvar->PossibleValue[i].strvalue)
{
- CONS_Printf(" %-2d : %s\n", cvar->PossibleValue[i].value,
- cvar->PossibleValue[i].strvalue);
+ if (floatmode)
+ CONS_Printf(" %-2f : %s\n", FIXED_TO_FLOAT(cvar->PossibleValue[i].value),
+ cvar->PossibleValue[i].strvalue);
+ else
+ CONS_Printf(" %-2d : %s\n", cvar->PossibleValue[i].value,
+ cvar->PossibleValue[i].strvalue);
if (cvar->PossibleValue[i].value == cvar->value)
cvalue = cvar->PossibleValue[i].strvalue;
i++;
}
- if (cvalue)
- CONS_Printf(" Current value: %s\n", cvalue);
- else
- CONS_Printf(" Current value: %d\n", cvar->value);
}
}
+
+ if (cvalue)
+ CONS_Printf(" Current value: %s\n", cvalue);
+ else if (cvar->string)
+ CONS_Printf(" Current value: %s\n", cvar->string);
else
CONS_Printf(" Current value: %d\n", cvar->value);
}
@@ -1026,7 +1043,10 @@ static void COM_Add_f(void)
}
if (( cvar->flags & CV_FLOAT ))
- CV_Set(cvar, va("%f", FIXED_TO_FLOAT (cvar->value) + atof(COM_Argv(2))));
+ {
+ float n =FIXED_TO_FLOAT (cvar->value) + atof(COM_Argv(2));
+ CV_Set(cvar, va("%ld%s", (long)n, M_Ftrim(n)));
+ }
else
CV_AddValue(cvar, atoi(COM_Argv(2)));
}
diff --git a/src/command.h b/src/command.h
index 2276a0ae2..6d1944f9a 100644
--- a/src/command.h
+++ b/src/command.h
@@ -13,6 +13,10 @@
#ifndef __COMMAND_H__
#define __COMMAND_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include
#include "doomdef.h"
@@ -189,4 +193,8 @@ UINT8 CV_CheatsEnabled(void);
// Returns cvar by name. Exposed here for Lua.
consvar_t *CV_FindVar(const char *name);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // __COMMAND_H__
diff --git a/src/console.c b/src/console.c
index 8c1824456..bb86d444b 100644
--- a/src/console.c
+++ b/src/console.c
@@ -1321,13 +1321,6 @@ void CONS_Debug(INT32 debugflags, const char *fmt, ...)
//
void CONS_Error(const char *msg)
{
-#ifdef RPC_NO_WINDOWS_H
- if (!graphics_started)
- {
- MessageBoxA(vid.WndParent, msg, "SRB2Kart Warning", MB_OK);
- return;
- }
-#endif
CONS_Printf("\x82%s", msg); // write error msg in different colour
CONS_Printf(M_GetText("Press ENTER to continue\n"));
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
new file mode 100644
index 000000000..db8bc5a15
--- /dev/null
+++ b/src/core/CMakeLists.txt
@@ -0,0 +1 @@
+target_sourcefile(cpp)
diff --git a/src/core/Sourcefile b/src/core/Sourcefile
new file mode 100644
index 000000000..e8701d507
--- /dev/null
+++ b/src/core/Sourcefile
@@ -0,0 +1,2 @@
+memory.cpp
+thread_pool.cpp
diff --git a/src/core/memory.cpp b/src/core/memory.cpp
new file mode 100644
index 000000000..e75cf91f7
--- /dev/null
+++ b/src/core/memory.cpp
@@ -0,0 +1,71 @@
+// BLANKART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2024 by Ronald "Eidolon" Kinard
+// Copyright (C) 2024 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+
+#include "memory.h"
+
+#include
+#include
+
+#include "../z_zone.h"
+
+namespace
+{
+
+class LinearMemory
+{
+ size_t size_;
+ size_t height_;
+ void* memory_;
+
+public:
+ constexpr explicit LinearMemory(size_t size) noexcept;
+
+ void* allocate(size_t size);
+ void reset() noexcept;
+};
+
+constexpr LinearMemory::LinearMemory(size_t size) noexcept : size_(size), height_{0}, memory_{nullptr} {}
+
+void* LinearMemory::allocate(size_t size)
+{
+ size_t aligned_size = (size + 15) & ~15;
+ if (height_ + aligned_size > size_)
+ {
+ throw std::bad_alloc();
+ }
+
+ if (memory_ == nullptr)
+ {
+ memory_ = Z_Malloc(size_, PU_STATIC, nullptr);
+ }
+
+ void* ptr = (void*)((uintptr_t)(memory_) + height_);
+ height_ += aligned_size;
+ return ptr;
+}
+
+void LinearMemory::reset() noexcept
+{
+ height_ = 0;
+}
+
+} // namespace
+
+static LinearMemory g_frame_memory {4 * 1024 * 1024};
+
+void* Z_Frame_Alloc(size_t size)
+{
+ return g_frame_memory.allocate(size);
+}
+
+void Z_Frame_Reset()
+{
+ g_frame_memory.reset();
+}
diff --git a/src/core/memory.h b/src/core/memory.h
new file mode 100644
index 000000000..ba49e3d51
--- /dev/null
+++ b/src/core/memory.h
@@ -0,0 +1,32 @@
+// BLANKART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2024 by Ronald "Eidolon" Kinard
+// Copyright (C) 2024 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+
+#ifndef __SRB2_CORE_MEMORY_H__
+#define __SRB2_CORE_MEMORY_H__
+
+#include
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cpluspplus
+
+/// @brief Allocate a block of memory with a lifespan of the current main-thread frame.
+/// This function is NOT thread-safe, but the allocated memory may be used across threads.
+/// @return a pointer to a block of memory aligned with libc malloc alignment, or null if allocation fails
+void* Z_Frame_Alloc(size_t size);
+
+/// @brief Resets per-frame memory. Not thread safe.
+void Z_Frame_Reset(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+#endif // __SRB2_CORE_MEMORY_H__
diff --git a/src/core/spmc_queue.hpp b/src/core/spmc_queue.hpp
new file mode 100644
index 000000000..d85e1300d
--- /dev/null
+++ b/src/core/spmc_queue.hpp
@@ -0,0 +1,192 @@
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
+ */
+
+// This class is derived from Conor Williams' implementation of a concurrent deque
+// https://github.com/ConorWilliams/ConcurrentDeque
+// Copyright (C) 2021 Conor Williams
+
+// The original version was for C++23. This one has been shrunk slightly and adapted to our conventions.
+
+#ifndef __SRB2_CORE_SPMC_QUEUE_HPP__
+#define __SRB2_CORE_SPMC_QUEUE_HPP__
+
+#include
+#include
+#include
+#include
+#include
+
+//#include
+
+#include "../cxxutil.hpp"
+
+namespace srb2
+{
+
+template
+class SpMcQueue
+{
+ struct RingBuff {
+ public:
+ explicit RingBuff(int64_t cap) : _cap{cap}, _mask{cap - 1}
+ {
+ SRB2_ASSERT(cap && (!(cap & (cap - 1))) && "Capacity must be buf power of 2!");
+ _buff = std::unique_ptr(new T[_cap]);
+ }
+
+ std::int64_t capacity() const noexcept { return _cap; }
+
+ // Store (copy) at modulo index
+ void store(int64_t i, T&& x) noexcept
+ {
+ _buff[i & _mask] = std::move(x);
+ }
+
+ // Load (copy) at modulo index
+ T load(int64_t i) const noexcept
+ {
+ return _buff[i & _mask];
+ }
+
+ // Allocates and returns a new ring buffer, copies elements in range [b, t) into the new buffer.
+ RingBuff* resize(std::int64_t b, std::int64_t t) const
+ {
+ //ZoneScoped;
+ RingBuff* ptr = new RingBuff{2 * _cap};
+ for (std::int64_t i = t; i != b; ++i) {
+ ptr->store(i, load(i));
+ }
+ return ptr;
+ }
+
+ private:
+ int64_t _cap; // Capacity of the buffer
+ int64_t _mask; // Bit mask to perform modulo capacity operations
+
+ std::unique_ptr _buff;
+ };
+
+ alignas(64) std::atomic bottom_;
+ alignas(64) std::atomic top_;
+ alignas(64) std::atomic buffer_;
+
+ std::vector> garbage_;
+
+public:
+ SpMcQueue(size_t capacity) : bottom_(0), top_(0), buffer_(new RingBuff(capacity))
+ {
+ garbage_.reserve(32);
+ }
+ ~SpMcQueue() noexcept
+ {
+ delete buffer_.load(std::memory_order_relaxed);
+ };
+
+ size_t size() const noexcept
+ {
+ int64_t bottom = bottom_.load(std::memory_order_relaxed);
+ int64_t top = top_.load(std::memory_order_relaxed);
+ return static_cast(bottom >= top ? bottom - top : 0);
+ }
+
+ bool empty() const noexcept
+ {
+ return size() == 0;
+ }
+
+ void push(T&& v) noexcept
+ {
+ int64_t bottom = bottom_.load(std::memory_order_relaxed);
+ int64_t top = top_.load(std::memory_order_acquire);
+ RingBuff* buf = buffer_.load(std::memory_order_relaxed);
+
+ if (buf->capacity() < (bottom - top) + 1)
+ {
+ // Queue is full, build a new one
+ RingBuff* newbuf = buf->resize(bottom, top);
+ garbage_.emplace_back(buf);
+ buffer_.store(newbuf, std::memory_order_relaxed);
+ buf = newbuf;
+ }
+
+ // Construct new object, this does not have to be atomic as no one can steal this item until after we
+ // store the new value of bottom, ordering is maintained by surrounding atomics.
+ buf->store(bottom, std::move(v));
+
+ std::atomic_thread_fence(std::memory_order_release);
+ bottom_.store(bottom + 1, std::memory_order_relaxed);
+ }
+
+ std::optional pop() noexcept
+ {
+ int64_t bottom = bottom_.load(std::memory_order_relaxed) - 1;
+ RingBuff* buf = buffer_.load(std::memory_order_relaxed);
+
+ bottom_.store(bottom, std::memory_order_relaxed); // Stealers can no longer steal
+
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+ int64_t top = top_.load(std::memory_order_relaxed);
+
+ if (top <= bottom)
+ {
+ // Non-empty deque
+ if (top == bottom)
+ {
+ // The last item could get stolen, by a stealer that loaded bottom before our write above
+ if (!top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed))
+ {
+ // Failed race, thief got the last item.
+ bottom_.store(bottom + 1, std::memory_order_relaxed);
+ return std::nullopt;
+ }
+ bottom_.store(bottom + 1, std::memory_order_relaxed);
+ }
+
+ // Can delay load until after acquiring slot as only this thread can push(), this load is not
+ // required to be atomic as we are the exclusive writer.
+ return buf->load(bottom);
+
+ }
+ else
+ {
+ bottom_.store(bottom + 1, std::memory_order_relaxed);
+ return std::nullopt;
+ }
+ }
+
+ std::optional steal() noexcept
+ {
+ int64_t top = top_.load(std::memory_order_acquire);
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+ int64_t bottom = bottom_.load(std::memory_order_acquire);
+
+ if (top < bottom)
+ {
+ // Must load *before* acquiring the slot as slot may be overwritten immediately after acquiring.
+ // This load is NOT required to be atomic even-though it may race with an overrite as we only
+ // return the value if we win the race below garanteeing we had no race during our read. If we
+ // loose the race then 'x' could be corrupt due to read-during-write race but as T is trivially
+ // destructible this does not matter.
+ T x = buffer_.load(std::memory_order_consume)->load(top);
+
+ if (!top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed))
+ {
+ return std::nullopt;
+ }
+
+ return x;
+
+ }
+ else
+ {
+ return std::nullopt;
+ }
+ }
+};
+
+} // namespace srb2
+
+#endif // __SRB2_CORE_SPMC_QUEUE_HPP__
diff --git a/src/core/static_vec.hpp b/src/core/static_vec.hpp
new file mode 100644
index 000000000..a5a529564
--- /dev/null
+++ b/src/core/static_vec.hpp
@@ -0,0 +1,255 @@
+// BLANKART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2024 by Ronald "Eidolon" Kinard
+// Copyright (C) 2024 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+
+#ifndef __SRB2_CORE_STATIC_VEC_HPP__
+#define __SRB2_CORE_STATIC_VEC_HPP__
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "../cxxutil.hpp"
+
+namespace srb2
+{
+
+template
+class StaticVec;
+
+template
+class StaticVec
+{
+ std::array arr_ {{}};
+ size_t size_ = 0;
+
+public:
+ using value_type = T;
+
+ constexpr StaticVec() {}
+
+ StaticVec(const StaticVec& rhs)
+ {
+ for (size_t i = size_; i > 0; i--)
+ {
+ arr_[i] = T();
+ }
+ size_ = rhs.size();
+ for (size_t i = 0; i < size_; i++)
+ {
+ arr_[i] = rhs.arr_[i];
+ }
+ }
+
+ StaticVec(StaticVec&& rhs) noexcept(std::is_nothrow_move_assignable_v)
+ {
+ for (size_t i = size_; i > 0; i--)
+ {
+ arr_[i] = T();
+ }
+ size_ = rhs.size();
+ for (size_t i = 0; i < size_; i++)
+ {
+ arr_[i] = std::move(rhs.arr_[i]);
+ }
+ while (rhs.size() > 0)
+ {
+ rhs.pop_back();
+ }
+ }
+
+ constexpr StaticVec(std::initializer_list list) noexcept(std::is_nothrow_move_assignable_v)
+ {
+ size_ = list.size();
+ size_t i = 0;
+ for (auto itr = list.begin(); itr != list.end(); itr++)
+ {
+ arr_[i] = *itr;
+ i++;
+ }
+ }
+
+ ~StaticVec() = default;
+
+ StaticVec& operator=(const StaticVec& rhs)
+ {
+ for (size_t i = size_; i > 0; i--)
+ {
+ arr_[i] = T();
+ }
+ size_ = rhs.size();
+ for (size_t i = 0; i < size_; i++)
+ {
+ arr_[i] = rhs.arr_[i];
+ }
+ return *this;
+ }
+
+ StaticVec& operator=(StaticVec&& rhs) noexcept(std::is_nothrow_move_constructible_v)
+ {
+ for (size_t i = size_; i > 0; i--)
+ {
+ arr_[i] = T();
+ }
+ size_ = rhs.size();
+ for (size_t i = 0; i < size_; i++)
+ {
+ arr_[i] = std::move(rhs.arr_[i]);
+ }
+ while (rhs.size() > 0)
+ {
+ rhs.pop_back();
+ }
+ return *this;
+ }
+
+ void push_back(const T& value) { arr_[size_++] = value; }
+
+ void pop_back() { arr_[--size_] = T(); }
+
+ void resize(size_t size, T value = T())
+ {
+ if (size >= Limit)
+ {
+ throw std::length_error("new size >= Capacity");
+ }
+
+ if (size == size_)
+ {
+ return;
+ }
+ else if (size < size_)
+ {
+ while (size_ > size)
+ {
+ pop_back();
+ }
+ }
+ else
+ {
+ while (size_ < size)
+ {
+ push_back(value);
+ }
+ }
+ }
+
+ void clear()
+ {
+ arr_ = {{}};
+ size_ = 0;
+ }
+
+ using iterator = typename std::array::iterator;
+ using const_iterator = typename std::array::const_iterator;
+
+ constexpr iterator begin() noexcept { return arr_.begin(); }
+
+ constexpr const_iterator begin() const noexcept { return arr_.cbegin(); }
+
+ constexpr const_iterator cbegin() const noexcept { return arr_.cbegin(); }
+
+ constexpr iterator end() noexcept { return std::next(arr_.begin(), size_); }
+
+ constexpr const_iterator end() const noexcept { return cend(); }
+
+ constexpr const_iterator cend() const noexcept { return std::next(arr_.cbegin(), size_); }
+
+ constexpr std::reverse_iterator rbegin() noexcept { return std::reverse_iterator(this->end()); }
+
+ constexpr std::reverse_iterator crbegin() const noexcept { return std::reverse_iterator(this->cend()); }
+
+ constexpr std::reverse_iterator rend() noexcept { return std::reverse_iterator(this->begin()); }
+
+ constexpr std::reverse_iterator crend() const noexcept { return std::reverse_iterator(this->cbegin()); }
+
+ constexpr bool empty() const noexcept { return size_ == 0; }
+
+ constexpr size_t size() const noexcept { return size_; }
+
+ constexpr size_t capacity() const noexcept { return Limit; }
+
+ constexpr size_t max_size() const noexcept { return Limit; }
+
+ constexpr T& operator[](size_t index) noexcept { return arr_[index]; }
+
+ T& at(size_t index)
+ {
+ if (index >= size_)
+ {
+ throw std::out_of_range("index >= size");
+ }
+ return this[index];
+ }
+
+ constexpr const T& operator[](size_t index) const noexcept { return arr_[index]; }
+
+ const T& at(size_t index) const
+ {
+ if (index >= size_)
+ {
+ throw std::out_of_range("index >= size");
+ }
+ return this[index];
+ }
+
+ T& front() { return *arr_[0]; }
+
+ T& back() { return *arr_[size_ - 1]; }
+};
+
+} // namespace srb2
+
+template
+bool operator==(const srb2::StaticVec& lhs, const srb2::StaticVec& rhs)
+{
+ const size_t size = lhs.size();
+ if (size != rhs.size())
+ {
+ return false;
+ }
+ for (size_t i = 0; i < lhs; i++)
+ {
+ if (rhs[i] != lhs[i])
+ {
+ return false;
+ }
+ }
+ return true;
+}
+
+template
+bool operator!=(const srb2::StaticVec& lhs, const srb2::StaticVec& rhs)
+{
+ return !(lhs == rhs);
+}
+
+template
+struct std::hash>
+{
+ size_t operator()(const srb2::StaticVec& input) const
+ {
+ constexpr size_t prime = sizeof(size_t) == 8 ? 0x00000100000001B3 : 0x01000193;
+ constexpr size_t basis = sizeof(size_t) == 8 ? 0xcbf29ce484222325 : 0x811c9dc5;
+
+ size_t ret = basis;
+ for (auto itr = input.begin(); itr != input.end(); itr++)
+ {
+ ret = (ret * prime) ^ std::hash(*itr);
+ }
+ return ret;
+ }
+};
+
+#endif // __SRB2_CORE_STATIC_VEC_HPP__
diff --git a/src/core/thread_pool.cpp b/src/core/thread_pool.cpp
new file mode 100644
index 000000000..11aa6f1bb
--- /dev/null
+++ b/src/core/thread_pool.cpp
@@ -0,0 +1,346 @@
+// BLANKART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2024 by Ronald "Eidolon" Kinard
+// Copyright (C) 2024 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+
+#include "thread_pool.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+//#include
+//#include
+
+#include "../cxxutil.hpp"
+#include "../m_argv.h"
+
+using namespace srb2;
+
+static void do_work(ThreadPool::Task& work)
+{
+ try
+ {
+ //ZoneScoped;
+ (work.thunk)(work.raw.data());
+ }
+ catch (...)
+ {
+ // can't do anything
+ }
+
+ (work.deleter)(work.raw.data());
+ if (work.pseudosema)
+ {
+ work.pseudosema->fetch_sub(1, std::memory_order_relaxed);
+ }
+}
+
+static void pool_executor(
+ //int thread_index,
+ std::shared_ptr> pool_alive,
+ std::shared_ptr worker_ready_mutex,
+ std::shared_ptr worker_ready_condvar,
+ std::shared_ptr my_wq,
+ std::vector> other_wqs
+)
+{
+ {
+ //std::string thread_name = fmt::format("Thread Pool Thread {}", thread_index);
+ //tracy::SetThreadName(thread_name.c_str());
+ }
+
+ int spins = 0;
+ while (true)
+ {
+ std::optional work = my_wq->steal();
+ bool did_work = false;
+ if (work)
+ {
+ do_work(*work);
+
+ did_work = true;
+ spins = 0;
+ }
+ else
+ {
+ for (auto& q : other_wqs)
+ {
+ work = q->steal();
+ if (work)
+ {
+ do_work(*work);
+
+ did_work = true;
+ spins = 0;
+
+ // We only want to steal one work item at a time, to prioritize our own queue
+ break;
+ }
+ }
+ }
+
+ if (!did_work)
+ {
+ // Spin a few loops to avoid yielding, then wait for the ready lock
+ spins += 1;
+ if (spins > 100)
+ {
+ std::unique_lock ready_lock {*worker_ready_mutex};
+ while (my_wq->empty() && pool_alive->load())
+ {
+ worker_ready_condvar->wait(ready_lock);
+ }
+
+ if (!pool_alive->load())
+ {
+ break;
+ }
+ }
+ }
+ }
+}
+
+ThreadPool::ThreadPool()
+{
+ immediate_mode_ = true;
+}
+
+ThreadPool::ThreadPool(size_t threads)
+{
+ next_queue_index_ = 0;
+ pool_alive_ = std::make_shared>(true);
+
+ for (size_t i = 0; i < threads; i++)
+ {
+ std::shared_ptr wsq = std::make_shared(2048);
+ work_queues_.push_back(wsq);
+
+ std::shared_ptr mutex = std::make_shared();
+ worker_ready_mutexes_.push_back(std::move(mutex));
+ std::shared_ptr condvar = std::make_shared();
+ worker_ready_condvars_.push_back(std::move(condvar));
+ }
+
+ for (size_t i = 0; i < threads; i++)
+ {
+ std::shared_ptr my_queue = work_queues_[i];
+ std::vector> other_queues;
+ for (size_t j = 0; j < threads; j++)
+ {
+ // Order the other queues starting from the next adjacent worker
+ // i.e. if this is worker 2 of 8, then other queues is 3, 4, 5, 6, 7, 0, 1
+ // This tries to balance out work stealing behavior
+
+ size_t other_index = j + i;
+ if (other_index >= threads)
+ {
+ other_index -= threads;
+ }
+
+ if (other_index != i)
+ {
+ other_queues.push_back(work_queues_[other_index]);
+ }
+ }
+
+ std::thread thread;
+ try
+ {
+ thread = std::thread
+ {
+ pool_executor,
+ //i,
+ pool_alive_,
+ worker_ready_mutexes_[i],
+ worker_ready_condvars_[i],
+ my_queue,
+ other_queues
+ };
+ }
+ catch (const std::system_error& error)
+ {
+ // Safe shutdown and rethrow
+ pool_alive_->store(false);
+ for (auto& t : threads_)
+ {
+ t.join();
+ }
+ throw error;
+ }
+
+ threads_.push_back(std::move(thread));
+ }
+}
+
+ThreadPool::ThreadPool(ThreadPool&&) = default;
+ThreadPool::~ThreadPool() = default;
+
+ThreadPool& ThreadPool::operator=(ThreadPool&&) = default;
+
+void ThreadPool::begin_sema()
+{
+ sema_begun_ = true;
+}
+
+ThreadPool::Sema ThreadPool::end_sema()
+{
+ Sema ret = Sema(std::move(cur_sema_));
+ cur_sema_ = nullptr;
+ sema_begun_ = false;
+ return ret;
+}
+
+void ThreadPool::notify()
+{
+ for (size_t i = 0; i < work_queues_.size(); i++)
+ {
+ auto& q = work_queues_[i];
+ size_t count = q->size();
+ if (count > 0)
+ {
+ worker_ready_condvars_[i]->notify_one();
+ }
+ }
+}
+
+void ThreadPool::notify_sema(const ThreadPool::Sema& sema)
+{
+ if (!sema.pseudosema_)
+ {
+ return;
+ }
+ notify();
+}
+
+void ThreadPool::wait_idle()
+{
+ if (immediate_mode_)
+ {
+ return;
+ }
+
+ //ZoneScoped;
+
+ for (size_t i = 0; i < work_queues_.size(); i++)
+ {
+ auto& q = work_queues_[i];
+
+ std::optional work;
+ while ((work = q->pop()).has_value())
+ {
+ do_work(*work);
+ }
+ }
+}
+
+void ThreadPool::wait_sema(const Sema& sema)
+{
+ if (!sema.pseudosema_)
+ {
+ return;
+ }
+
+ //ZoneScoped;
+
+ while (sema.pseudosema_->load(std::memory_order_seq_cst) > 0)
+ {
+ // spin to win
+ for (size_t i = 0; i < work_queues_.size(); i++)
+ {
+ auto& q = work_queues_[i];
+
+ std::optional work;
+ if ((work = q->pop()).has_value())
+ {
+ do_work(*work);
+ break;
+ }
+ }
+ }
+
+ if (sema.pseudosema_->load(std::memory_order_seq_cst) != 0)
+ {
+ throw std::exception();
+ }
+}
+
+void ThreadPool::shutdown()
+{
+ if (immediate_mode_)
+ {
+ return;
+ }
+
+ wait_idle();
+
+ pool_alive_->store(false);
+
+ for (auto& condvar : worker_ready_condvars_)
+ {
+ condvar->notify_all();
+ }
+ for (auto& t : threads_)
+ {
+ t.join();
+ }
+}
+
+std::unique_ptr srb2::g_main_threadpool;
+
+void I_ThreadPoolInit(void)
+{
+ SRB2_ASSERT(g_main_threadpool == nullptr);
+ size_t thread_count = std::min(static_cast(9), std::thread::hardware_concurrency());
+ if (thread_count > 1)
+ {
+ // The main thread will act as a worker when waiting for pool idle
+ // Make one less worker thread to avoid unnecessary context switching
+ thread_count -= 1;
+ }
+
+ if (M_CheckParm("-singlethreaded"))
+ {
+ g_main_threadpool = std::make_unique();
+ }
+ else
+ {
+ g_main_threadpool = std::make_unique(thread_count);
+ }
+}
+
+void I_ThreadPoolShutdown(void)
+{
+ if (!g_main_threadpool)
+ {
+ return;
+ }
+
+ g_main_threadpool->shutdown();
+ g_main_threadpool = nullptr;
+}
+
+void I_ThreadPoolSubmit(srb2cthunk_t thunk, void* data)
+{
+ SRB2_ASSERT(g_main_threadpool != nullptr);
+
+ g_main_threadpool->schedule([=]() {
+ (thunk)(data);
+ });
+ g_main_threadpool->notify();
+}
+
+void I_ThreadPoolWaitIdle(void)
+{
+ SRB2_ASSERT(g_main_threadpool != nullptr);
+
+ g_main_threadpool->wait_idle();
+}
diff --git a/src/core/thread_pool.h b/src/core/thread_pool.h
new file mode 100644
index 000000000..75961614e
--- /dev/null
+++ b/src/core/thread_pool.h
@@ -0,0 +1,163 @@
+// BLANKART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2024 by Ronald "Eidolon" Kinard
+// Copyright (C) 2024 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+
+#ifndef __SRB2_CORE_THREAD_POOL_H__
+#define __SRB2_CORE_THREAD_POOL_H__
+
+#include
+
+#ifdef __cplusplus
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "spmc_queue.hpp"
+
+namespace srb2
+{
+
+class ThreadPool
+{
+public:
+ struct Task
+ {
+ void (*thunk)(void*);
+ void (*deleter)(void*);
+ std::shared_ptr> pseudosema;
+ std::array>)> raw;
+ };
+
+ using Queue = SpMcQueue;
+
+ class Sema
+ {
+ std::shared_ptr> pseudosema_;
+
+ explicit Sema(std::shared_ptr> sema) : pseudosema_(sema) {}
+
+ friend class ThreadPool;
+ public:
+ Sema() = default;
+ };
+
+private:
+ std::shared_ptr> pool_alive_;
+ std::vector> worker_ready_mutexes_;
+ std::vector> worker_ready_condvars_;
+ std::vector> work_queues_;
+ std::vector threads_;
+ size_t next_queue_index_ = 0;
+ std::shared_ptr> cur_sema_;
+
+ bool immediate_mode_ = false;
+ bool sema_begun_ = false;
+
+public:
+ ThreadPool();
+ explicit ThreadPool(size_t threads);
+ ThreadPool(const ThreadPool&) = delete;
+ ThreadPool(ThreadPool&&);
+ ~ThreadPool();
+
+ ThreadPool& operator=(const ThreadPool&) = delete;
+ ThreadPool& operator=(ThreadPool&&);
+
+ void begin_sema();
+ ThreadPool::Sema end_sema();
+
+ /// Enqueue but don't notify
+ template void schedule(T&& thunk);
+ /// Notify threads after several schedules
+ void notify();
+ void notify_sema(const Sema& sema);
+ void wait_idle();
+ void wait_sema(const Sema& sema);
+ void shutdown();
+};
+
+extern std::unique_ptr g_main_threadpool;
+
+template
+void callable_caller(F* f)
+{
+ (*f)();
+}
+
+template
+void callable_destroyer(F* f)
+{
+ f->~F();
+}
+
+template
+void ThreadPool::schedule(T&& thunk)
+{
+ static_assert(sizeof(T) <= sizeof(std::declval().raw));
+
+ if (immediate_mode_)
+ {
+ (thunk)();
+ return;
+ }
+
+ if (sema_begun_)
+ {
+ if (cur_sema_ == nullptr)
+ {
+ cur_sema_ = std::make_shared>(0);
+ }
+ cur_sema_->fetch_add(1, std::memory_order_relaxed);
+ }
+
+ size_t qi = next_queue_index_;
+
+ {
+ std::shared_ptr q = work_queues_[qi];
+ Task task;
+ task.thunk = reinterpret_cast(callable_caller);
+ task.deleter = reinterpret_cast(callable_destroyer);
+ task.pseudosema = cur_sema_;
+ new (reinterpret_cast(task.raw.data())) T(std::move(thunk));
+
+ q->push(std::move(task));
+ }
+ // worker_ready_condvars_[qi]->notify_one();
+
+ next_queue_index_ += 1;
+ if (next_queue_index_ >= threads_.size())
+ {
+ next_queue_index_ = 0;
+ }
+}
+
+} // namespace srb2
+
+extern "C" {
+
+#endif // __cplusplus
+
+typedef void (*srb2cthunk_t)(void*);
+
+void I_ThreadPoolInit(void);
+void I_ThreadPoolShutdown(void);
+void I_ThreadPoolSubmit(srb2cthunk_t thunk, void* data);
+void I_ThreadPoolWaitIdle(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // __SRB2_CORE_THREAD_POOL_H__
diff --git a/src/cxxutil.hpp b/src/cxxutil.hpp
new file mode 100644
index 000000000..545d38dfd
--- /dev/null
+++ b/src/cxxutil.hpp
@@ -0,0 +1,152 @@
+#ifndef __SRB2_CXXUTIL_HPP__
+#define __SRB2_CXXUTIL_HPP__
+
+#include
+#include
+#include
+
+#include "doomdef.h"
+
+namespace srb2 {
+
+template
+class Finally {
+public:
+ explicit Finally(const F& f) noexcept : f_(f) {}
+ explicit Finally(F&& f) noexcept : f_(f) {}
+
+ Finally(Finally&& from) noexcept : f_(std::move(from.f_)), call_(std::exchange(from.call_, false)) {}
+
+ Finally(const Finally& from) = delete;
+ void operator=(const Finally& from) = delete;
+ void operator=(Finally&& from) = delete;
+
+ ~Finally() noexcept {
+ if (call_)
+ f_();
+ }
+
+private:
+ F f_;
+ bool call_ = true;
+};
+
+template
+Finally> finally(F&& f) noexcept {
+ return Finally {std::forward(f)};
+}
+
+struct SourceLocation {
+ const char* file_name;
+ unsigned int line_number;
+};
+
+#define SRB2_SOURCE_LOCATION \
+ srb2::SourceLocation { __FILE__, __LINE__ }
+
+#ifndef SRB2_ASSERT_HANDLER
+#define SRB2_ASSERT_HANDLER srb2::IErrorAssertHandler
+#endif
+
+#if !defined(NDEBUG) || defined(PARANOIA)
+// An assertion level of 2 will activate all invocations of the SRB2_ASSERT macro
+#define SRB2_ASSERTION_LEVEL 2
+#else
+// The minimum assertion level is 1
+#define SRB2_ASSERTION_LEVEL 1
+#endif
+
+/// Assert a precondition expression in debug builds.
+#define SRB2_ASSERT(expr) srb2::do_assert<2, SRB2_ASSERT_HANDLER>([&] { return (expr); }, SRB2_SOURCE_LOCATION, #expr)
+
+class IErrorAssertHandler {
+public:
+ static void handle(const SourceLocation& source_location, const char* expression) {
+ I_Error("Assertion failed at %s:%u: %s != true",
+ source_location.file_name,
+ source_location.line_number,
+ expression);
+ }
+};
+
+class NoOpAssertHandler {
+public:
+ static void handle(const SourceLocation& source_location, const char* expression) {(void)source_location; (void)expression;}
+};
+
+/// @brief Assert a precondition expression, aborting the application if it fails.
+/// @tparam Expr
+/// @tparam Level the level of this assertion; if it is less than or equal to SRB2_ASSERTION_LEVEL, this overload will
+/// activate.
+/// @param expr a callable which returns a bool
+/// @param source_location a struct containing the source location of the assertion, e.g. SRB2_SOURCE_LOCATION
+/// @param expression the expression evaluated in the expression callable
+/// @param message an optional message to display for the assertion
+template
+std::enable_if_t<(Level <= SRB2_ASSERTION_LEVEL), void>
+do_assert(const Expr& expr, const SourceLocation& source_location, const char* expression = "") noexcept {
+ static_assert(Level > 0, "level of an assertion must not be 0");
+ if (!expr()) {
+ Handler::handle(source_location, expression);
+ std::abort();
+ }
+}
+
+template
+std::enable_if_t<(Level > SRB2_ASSERTION_LEVEL), void>
+do_assert(const Expr&, const SourceLocation&, const char* = "") noexcept {
+}
+
+template
+class NotNull final {
+ T ptr_;
+
+public:
+ static_assert(std::is_convertible_v() != nullptr), bool>,
+ "T is not comparable with nullptr_t");
+
+ /// @brief Move-construct from the pointer value U, asserting that it is not null. Allows construction of a
+ /// NotNull from any compatible pointer U, for example with polymorphic classes.
+ template >>
+ constexpr NotNull(U&& rhs) : ptr_(std::forward(rhs)) {
+ SRB2_ASSERT(ptr_ != nullptr);
+ }
+
+ /// @brief Wrap the pointer type T, asserting that the pointer is not null.
+ template >>
+ constexpr NotNull(T rhs) : ptr_(std::move(rhs)) {
+ SRB2_ASSERT(ptr_ != nullptr);
+ }
+
+ /// @brief Copy construction from NotNull of convertible type U. Only if the incoming pointer is NotNull already.
+ template >>
+ constexpr NotNull(const NotNull& rhs) : NotNull(rhs.get()) {
+ // Value is guaranteed to be not null by construction; no assertion necessary
+ }
+
+ NotNull(const NotNull& rhs) = default;
+ NotNull& operator=(const NotNull& rhs) = default;
+
+ /// @brief Get the stored pointer.
+ constexpr T get() const { return ptr_; }
+
+ /// @brief Convert to T (the pointer type).
+ constexpr operator T() const { return get(); }
+
+ /// @brief Arrow-dereference to *T (the actual value pointed to).
+ constexpr decltype(auto) operator->() const { return get(); }
+
+ /// @brief Dereference to *T (the actual value pointed to).
+ constexpr decltype(auto) operator*() const { return *get(); }
+
+ // It is not allowed to construct NotNull with nullptr regardless of T.
+ NotNull(std::nullptr_t) = delete;
+ NotNull& operator=(std::nullptr_t) = delete;
+};
+
+template
+NotNull(T) -> NotNull;
+
+} // namespace srb2
+
+#endif // __SRB2_CXXUTIL_HPP__
diff --git a/src/d_clisrv.c b/src/d_clisrv.c
index 9625934fc..da864f151 100644
--- a/src/d_clisrv.c
+++ b/src/d_clisrv.c
@@ -87,6 +87,9 @@ boolean serverrunning = false;
INT32 serverplayer = 0;
char motd[254], server_context[8]; // Message of the Day, Unique Context (even without Mumble support)
+plrinfo playerinfo[MAXPLAYERS];
+SINT8 joinnode = 0; // used for CL_VIEWSERVER
+
// Server specific vars
UINT8 playernode[MAXPLAYERS];
@@ -95,7 +98,7 @@ UINT8 playernode[MAXPLAYERS];
tic_t jointimeout = (3*TICRATE);
static boolean sendingsavegame[MAXNETNODES]; // Are we sending the savegame?
#ifdef SATURNPAK
-static boolean resendingsavegame[MAXNETNODES]; // Are we resending the savegame?
+static tic_t resendingsavegame[MAXNETNODES]; // Are we resending the savegame?
static tic_t savegameresendcooldown[MAXNETNODES]; // How long before we can resend again?
#endif
static tic_t freezetimeout[MAXNETNODES]; // Until when can this node freeze the server before getting a timeout?
@@ -1068,6 +1071,7 @@ static void SV_RequireResynch(INT32 node)
// Initial setup
memset(resynch_sent[node], 0, MAXPLAYERS);
+
for (i = 0; i < MAXPLAYERS; ++i)
{
if (!playeringame[i]) // Player not in game so just drop it from required synch
@@ -1184,6 +1188,7 @@ typedef enum
#endif
CL_CONNECTED,
CL_ABORTED,
+ CL_VIEWSERVER,
CL_ASKFULLFILELIST,
CL_CONFIRMCONNECT,
#ifdef HAVE_CURL
@@ -1247,7 +1252,7 @@ static inline void CL_DrawConnectionStatus(void)
if (!menuactive) // menu already draws its own fade
V_DrawFadeScreen(0xFF00, 16); // force default
- if (cl_mode != CL_DOWNLOADFILES && cl_mode != CL_LOADFILES && cl_mode != CL_CHECKFILES
+ if (cl_mode != CL_DOWNLOADFILES && cl_mode != CL_LOADFILES && cl_mode != CL_CHECKFILES && cl_mode != CL_VIEWSERVER
#ifdef HAVE_CURL
&& cl_mode != CL_DOWNLOADHTTPFILES
#endif
@@ -1367,6 +1372,78 @@ static inline void CL_DrawConnectionStatus(void)
V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE|MENUCAPS,
va(" %2u/%2u Files",loadcompletednum,fileneedednum));
}
+ else if (cl_mode == CL_VIEWSERVER)
+ {
+ V_DrawFill(8, 16, BASEVIDWIDTH - 16, 54, 239);
+
+ V_DrawThinString(12 + 80, 18, V_ALLOWLOWERCASE, va("%s", serverlist[joinnode].info.servername));
+
+ const char *map = va("%sP", serverlist[joinnode].info.mapname);
+ patch_t *current_map = W_LumpExists(map) ? W_CachePatchName(map, PU_CACHE) : W_CachePatchName("BLANKLVL", PU_CACHE);
+ V_DrawSmallScaledPatch(10, 18, 0, current_map);
+
+ V_DrawThinString(12 + 80, 38, V_ALLOWLOWERCASE, va("%s", serverlist[joinnode].info.maptitle));
+ V_DrawThinString(12 + 80, 48, V_ALLOWLOWERCASE, va("%s", Gametype_Names[serverlist[joinnode].info.gametype]));
+
+ if (fileneedednum > 0)
+ {
+ V_DrawThinString(12 + 80, 58, V_ALLOWLOWERCASE|V_ORANGEMAP, va("%i Addons", fileneedednum));
+ }
+ else
+ {
+ V_DrawThinString(12 + 80, 58, V_ALLOWLOWERCASE|V_YELLOWMAP, "Vanilla");
+ }
+
+ if (serverlist[joinnode].info.cheatsenabled)
+ {
+ V_DrawRightAlignedThinString(BASEVIDWIDTH - 12, 58, V_ALLOWLOWERCASE|V_GREENMAP, "Cheats");
+ }
+
+ V_DrawFill(8, 72, BASEVIDWIDTH - 16, 112, 239);
+
+ V_DrawString(12, 74, V_ALLOWLOWERCASE|V_YELLOWMAP, "Players");
+ V_DrawRightAlignedString(BASEVIDWIDTH - 12, 74, V_ALLOWLOWERCASE|V_YELLOWMAP, va("%i / %i", serverlist[joinnode].info.numberofplayer, serverlist[joinnode].info.maxplayer));
+
+ INT32 i;
+ INT32 count = 0;
+ INT32 x = 14;
+ INT32 y = 84;
+ INT32 statuscolor = 1;
+ char player_name[MAXPLAYERNAME+1];
+ if (serverlist[joinnode].info.numberofplayer > 0)
+ {
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (playerinfo[i].node < 255)
+ {
+ strncpy(player_name, playerinfo[i].name, MAXPLAYERNAME);
+ V_DrawThinString(x + 10, y, V_ALLOWLOWERCASE|V_6WIDTHSPACE, player_name);
+
+ if (playerinfo[i].team == 0) { statuscolor = 184; } // playing
+ if (playerinfo[i].data & 0x20) { statuscolor = 86; } // tag IT
+ if (playerinfo[i].team == 1) { statuscolor = 128; } // ctf red team
+ if (playerinfo[i].team == 2) { statuscolor = 232; } // ctf blue team
+ if (playerinfo[i].team == 255) { statuscolor = 16; } // spectator or non-team
+
+ V_DrawFill(x, y, 7, 7, 31);
+ V_DrawFill(x, y, 6, 6, statuscolor);
+
+ y += 9;
+ count++;
+ if ((count == 11) || (count == 22))
+ {
+ x += 104;
+ y = 84;
+ }
+ }
+ }
+ }
+
+ // Buttons
+ V_DrawFill(8, BASEVIDHEIGHT - 14, BASEVIDWIDTH - 16, 12, 239);
+ V_DrawThinString(16, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sESC%s] = Abort", "\x82", "\x80"));
+ V_DrawRightAlignedThinString(BASEVIDWIDTH - 12, BASEVIDHEIGHT - 12, V_ALLOWLOWERCASE, va("[%sENTER%s] = Join", "\x82", "\x80"));
+ }
else if (filedownload.current != -1)
{
INT32 dldlength;
@@ -1687,13 +1764,7 @@ static void SV_SendPlayerInfo(INT32 node)
for (i = 0; i < MSCOMPAT_MAXPLAYERS; i++)
{
- if (i >= MAXPLAYERS)
- {
- netbuffer->u.playerinfo[i].node = 255;
- continue;
- }
-
- if (playeringame[i] == UINT8_MAX || !playeringame[i])
+ if ((i >= MAXPLAYERS) || !playeringame[i])
{
netbuffer->u.playerinfo[i].node = 255; // This slot is empty.
continue;
@@ -1778,8 +1849,6 @@ static boolean SV_SendServerConfig(INT32 node)
memset(netbuffer->u.servercfg.playerskins, 0xFF, sizeof(netbuffer->u.servercfg.playerskins));
memset(netbuffer->u.servercfg.playercolor, 0xFF, sizeof(netbuffer->u.servercfg.playercolor));
- memset(netbuffer->u.servercfg.adminplayers, -1, sizeof(netbuffer->u.servercfg.adminplayers));
-
for (i = 0; i < MAXPLAYERS; i++)
{
netbuffer->u.servercfg.adminplayers[i] = (SINT8)adminplayers[i];
@@ -2476,6 +2545,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent)
if (i < 0)
return true;
}
+ joinnode = i;
// Quit here rather than downloading files and being refused later.
if (serverlist[i].info.numberofplayer >= serverlist[i].info.maxplayer)
@@ -2502,7 +2572,7 @@ static boolean CL_ServerConnectionSearchTicker(tic_t *asksent)
return true;
}
- cl_mode = CL_CHECKFILES;
+ cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES;
}
else
{
@@ -2556,7 +2626,7 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic
case CL_ASKFULLFILELIST:
if (cl_lastcheckedfilecount == UINT16_MAX) // All files retrieved
- cl_mode = CL_CHECKFILES;
+ cl_mode = (cv_serverinfoscreen.value) ? CL_VIEWSERVER : CL_CHECKFILES;
else if (fileneedednum != cl_lastcheckedfilecount || I_GetTime() >= *asksent)
{
if (CL_AskFileList(fileneedednum))
@@ -2722,6 +2792,15 @@ static boolean CL_ServerConnectionTicker(const char *tmpsave, tic_t *oldtic, tic
D_ProcessEvents(); //needed for menu system to receive inputs
key = I_GetKey();
+
+ if (cl_mode == CL_VIEWSERVER)
+ {
+ if (key == KEY_ENTER || key == KEY_JOY1)
+ cl_mode = CL_CHECKFILES;
+ else if (key == KEY_ESCAPE || key == KEY_JOY1+1)
+ cl_mode = CL_ABORTED;
+ }
+
// Only ESC and non-keyboard keys abort connection
if (!modeattacking && (key == KEY_ESCAPE || key == KEY_JOY1+1 || cl_mode == CL_ABORTED))
{
@@ -3275,7 +3354,7 @@ void CL_ClearPlayer(INT32 playernum)
P_RemoveMobj(players[playernum].mo);
}
- memset(&players[playernum], 0, sizeof (player_t));
+ memset(&players[playernum], 0, sizeof(player_t));
}
//
@@ -4149,6 +4228,8 @@ consvar_t cv_downloadspeed = {"downloadspeed", "300", CV_SAVE, downloadspeed_con
static CV_PossibleValue_t connectawaittime_cons_t[] = {{1, "MIN"}, {60, "MAX"}, {0, "Inf"}, {0, NULL}};
consvar_t cv_connectawaittime = {"connectawaittime", "5", CV_SAVE, connectawaittime_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_serverinfoscreen = {"serverinfoscreen", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
static void Got_AddPlayer(UINT8 **p, INT32 playernum);
static void Got_RemovePlayer(UINT8 **p, INT32 playernum);
@@ -4251,7 +4332,7 @@ static void ResetNode(INT32 node)
// SATURN
#ifdef SATURNPAK
is_client_saturn[node] = false;
- resendingsavegame[node] = false;
+ resendingsavegame[node] = 0;
savegameresendcooldown[node] = 0;
gamestate_resend_counter[node] = 0;
#endif
@@ -4284,14 +4365,14 @@ void SV_ResetServer(void)
sprintf(player_names[i], "Player %d", i + 1);
}
- memset(player_name_changes, 0, sizeof player_name_changes);
+ memset(player_name_changes, 0, sizeof(player_name_changes));
- memset(playeringame, false, sizeof playeringame);
- memset(playernode, UINT8_MAX, sizeof playernode);
+ memset(playeringame, false, sizeof(playeringame));
+ memset(playernode, UINT8_MAX, sizeof(playernode));
pingmeasurecount = 1;
- memset(realpingtable, 0, sizeof realpingtable);
- memset(playerpingtable, 0, sizeof playerpingtable);
+ memset(realpingtable, 0, sizeof(realpingtable));
+ memset(playerpingtable, 0, sizeof(playerpingtable));
ClearAdminPlayers();
@@ -4916,6 +4997,16 @@ static void HandleServerInfo(SINT8 node)
if (client && cl_mode > CL_SEARCHING && node == servernode)
memcpy(connectedservername, netbuffer->u.serverinfo.servername, MAXSERVERNAME);
}
+
+
+static void HandlePlayerInfo(SINT8 node)
+{
+ (void)node;
+
+ INT32 i;
+ for (i = 0; i < MAXPLAYERS; i++)
+ playerinfo[i] = netbuffer->u.playerinfo[i];
+}
#endif
#ifdef SATURNPAK
@@ -4952,7 +5043,7 @@ static void PT_CanReceiveGamestate(SINT8 node)
CONS_Printf(M_GetText("Resending game state to %s...\n"), player_names[nodetoplayer[node]]);
SV_SendSaveGame(node, true); // Resend a complete game state
- resendingsavegame[node] = true;
+ resendingsavegame[node] = 1;
}
#endif
@@ -5204,6 +5295,10 @@ static void HandlePacketFromAwayNode(SINT8 node)
case PT_CLIENTCMD:
break; // This is not an "unknown packet"
+
+ case PT_PLAYERINFO:
+ HandlePlayerInfo(node);
+ break;
case PT_SERVERTICS:
// Do not remove my own server (we have just get a out of order packet)
@@ -5324,18 +5419,18 @@ static void HandlePacketFromPlayer(SINT8 node)
/// \todo Use a separate cvar for that kind of timeout?
freezetimeout[node] = I_GetTime() + connectiontimeout;
- // If we've alredy received a ticcmd for this tic, just submit it for the next one.
- tic_t faketic = maketic;
- if ((!!(netcmds[maketic % TICQUEUE][netconsole].angleturn & TICCMD_RECEIVED))
- && (maketic - firstticstosend < TICQUEUE - 1))
- faketic++;
-
// Don't do anything for packets of type NODEKEEPALIVE?
// Sryder 2018/07/01: Update the freezetimeout still!
if (netbuffer->packettype == PT_NODEKEEPALIVE
|| netbuffer->packettype == PT_NODEKEEPALIVEMIS)
break;
+ // If we've alredy received a ticcmd for this tic, just submit it for the next one.
+ tic_t faketic = maketic;
+ if ((!!(netcmds[maketic % TICQUEUE][netconsole].angleturn & TICCMD_RECEIVED))
+ && (maketic - firstticstosend < TICQUEUE - 1))
+ faketic++;
+
// Copy ticcmd
G_MoveTiccmd(&netcmds[faketic%TICQUEUE][netconsole], &netbuffer->u.clientpak.cmd, 1);
@@ -5395,11 +5490,11 @@ static void HandlePacketFromPlayer(SINT8 node)
// Check player consistancy during the level
if (gamestate == GS_LEVEL
- && (realstart > gametic - TICQUEUE+1 && realstart <= gametic)
+ && (realstart <= gametic && realstart + TICQUEUE - 1 > gametic)
&& consistancy[realstart%TICQUEUE] != SHORT(netbuffer->u.clientpak.consistancy)
&& (!UseSaturnSynch(node) || (!resendingsavegame[node] && savegameresendcooldown[node] <= I_GetTime() && !SV_ResendingSavegameToAnyone())))
{
- resendingsavegame[node] = false; // reset this before just in case
+ resendingsavegame[node] = 0; // reset this before just in case
// Check if a client is saturn before sending ANYTHING!
// this way we only send stuff to clients we know can use the gamestate resend
@@ -5409,7 +5504,7 @@ static void HandlePacketFromPlayer(SINT8 node)
// Tell the client we are about to resend them the gamestate
netbuffer->packettype = PT_WILLRESENDGAMESTATE;
HSendPacket(node, true, 0, 0);
- resendingsavegame[node] = true;
+ resendingsavegame[node] = 1;
}
else if (UseVanillaSynch(node))
{
@@ -5425,10 +5520,13 @@ static void HandlePacketFromPlayer(SINT8 node)
}
if (cv_blamecfail.value)
+ {
CONS_Printf(M_GetText("Synch failure for player %d (%s); expected %hd, got %hd\n"),
netconsole+1, player_names[netconsole],
consistancy[realstart%TICQUEUE],
SHORT(netbuffer->u.clientpak.consistancy));
+ }
+
DEBFILE(va("Restoring player %d (synch failure) [%update] %d!=%d\n",
netconsole, realstart, consistancy[realstart%TICQUEUE],
SHORT(netbuffer->u.clientpak.consistancy)));
@@ -5700,7 +5798,7 @@ static void HandlePacketFromPlayer(SINT8 node)
break;
}
- //Update client ping table from the server.
+ // Update client ping table from the server.
if (client)
{
UINT8 i;
@@ -5736,7 +5834,7 @@ static void HandlePacketFromPlayer(SINT8 node)
break;
case PT_RECEIVEDGAMESTATE:
sendingsavegame[node] = false;
- resendingsavegame[node] = false;
+ resendingsavegame[node] = 0;
savegameresendcooldown[node] = I_GetTime() + cv_resynchcooldown.value * TICRATE; // I_GetTime() + 5 * TICRATE;
break;
case PT_WILLRESENDGAMESTATE:
@@ -5796,8 +5894,9 @@ static void GetPackets(void)
}
#endif
- if (netbuffer->packettype == PT_PLAYERINFO)
- continue; // We do nothing with PLAYERINFO, that's for the MS browser.
+ /*if (netbuffer->packettype == PT_PLAYERINFO)
+ continue; // We do nothing with PLAYERINFO, that's for the MS browser. Not quite true anymore :p*/
+
// We also count unknown packets, hence "<="
if (netbuffer->packettype <= NUMPACKETTYPE)
@@ -6366,10 +6465,35 @@ static void SV_Maketic(void)
maketic++;
}
+#ifdef SATURNPAK
+static void SV_UpdateResendGamestateTimeout(void)
+{
+ for (INT32 i = 0; i < MAXNETNODES; ++i)
+ {
+ if (!resendingsavegame[i])
+ continue;
+
+ resendingsavegame[i]++;
+
+ // Resending savegame took too long
+ if (resendingsavegame[i] > (tic_t)TICRATE*cv_pingtimeout.value)
+ {
+ resendingsavegame[i] = 0;
+ SendKick(i, KICK_MSG_CON_FAIL);
+ }
+ }
+}
+#endif
+
boolean TryRunTics(tic_t realtics)
{
boolean ticking;
+#ifdef SATURNPAK
+ if (server)
+ SV_UpdateResendGamestateTimeout();
+#endif
+
// the machine has lagged but it is not so bad
if (realtics > TICRATE/7) // FIXME: consistency failure!!
{
@@ -6510,7 +6634,6 @@ static inline void PingUpdate(void)
if (pingtimeout[i] > 0)
pingtimeout[i]--;
}
-
}
//kick lagging players... unless everyone but the server's ping sucks.
diff --git a/src/d_clisrv.h b/src/d_clisrv.h
index 6202c8c52..7ba47cfd6 100644
--- a/src/d_clisrv.h
+++ b/src/d_clisrv.h
@@ -13,6 +13,10 @@
#ifndef __D_CLISRV__
#define __D_CLISRV__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "d_ticcmd.h"
#include "d_net.h"
#include "d_netcmd.h"
@@ -577,6 +581,9 @@ extern boolean acceptnewnode;
extern SINT8 servernode;
extern char connectedservername[MAXSERVERNAME+1];
+extern plrinfo playerinfo[MAXPLAYERS];
+extern SINT8 joinnode;
+
void Command_Ping_f(void);
extern tic_t connectiontimeout;
extern tic_t jointimeout;
@@ -608,6 +615,8 @@ extern consvar_t cv_connectawaittime;
extern consvar_t cv_discordinvites;
+extern consvar_t cv_serverinfoscreen;
+
// Used in d_net, the only dependence
//tic_t ExpandTics(INT32 low, tic_t basetic);
void D_ClientServerInit(void);
@@ -689,4 +698,9 @@ typedef struct rewind_s {
void CL_ClearRewinds(void);
rewind_t *CL_SaveRewindPoint(size_t demopos);
rewind_t *CL_RewindToTime(tic_t time);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/d_main.c b/src/d_main.c
index 101ef4adb..ca1ea4989 100644
--- a/src/d_main.c
+++ b/src/d_main.c
@@ -72,6 +72,9 @@
#include "d_protocol.h"
#include "m_perfstats.h"
#include "k_kart.h"
+#include "k_hud.h"
+
+#include "core/memory.h"
#include "lua_script.h"
@@ -197,12 +200,10 @@ static void D_PadMenuScrollInput(UINT8 input)
// and pass it to the eventlist
static void D_GamePadMenuScrollTicker(void)
{
+ UINT8 i;
static UINT8 menuInputDelayTimer = 0;
- if (dedicated)
- return;
-
- for (UINT8 i = 0; i < 4; i++)
+ for (i = 0; i < MAXSPLITSCREENPLAYERS; i++)
{
if (dpadscrollstate[i])
{
@@ -222,10 +223,10 @@ static void D_GamePadMenuScrollTicker(void)
static void D_DeviceLEDTick(void)
{
UINT8 i;
- static UINT16 color[MAXSPLITSCREENPLAYERS] = {0, 0, 0, 0};
- static UINT16 curcolor[MAXSPLITSCREENPLAYERS] = {0, 0, 0, 0};
+ static UINT16 color[MAXSPLITSCREENPLAYERS] = {0};
+ static UINT16 curcolor[MAXSPLITSCREENPLAYERS] = {0};
- if (dedicated || numcontrollers == 0)
+ if (numcontrollers == 0)
{
return;
}
@@ -252,7 +253,6 @@ static void D_DeviceLEDTick(void)
void D_ProcessEvents(void)
{
event_t *ev;
-
boolean eaten;
for (; eventtail != eventhead; eventtail = (eventtail+1) & (MAXEVENTS-1))
@@ -291,8 +291,10 @@ void D_ProcessEvents(void)
// Demo input:
if (demo.playback)
+ {
if (M_DemoResponder(ev))
continue; // demo ate the event
+ }
// console input
#ifdef HAVE_THREADS
@@ -317,6 +319,110 @@ void D_ProcessEvents(void)
// draw current display, possibly wiping it from the previous
//
+static void D_Renderview(void)
+{
+ UINT8 i;
+
+ if (automapactive)
+ return;
+
+ R_ApplyLevelInterpolators(rendertimefrac);
+
+ if (rendermode == render_soft)
+ {
+ // if this is display player 1
+ if (cv_homremoval.value)
+ {
+ if (cv_homremoval.value == 1)
+ {
+ // Clear the software screen buffer to remove HOM
+ memset(vid.screens[0], 31, vid.width * vid.height);
+ }
+ else if (cv_homremoval.value == 2)
+ {
+ //'development' HOM removal -- makes it blindingly obvious if HOM is spotted.
+ memset(vid.screens[0], 32+(timeinmap&15), vid.width * vid.height);
+ }
+ }
+ }
+
+ // Draw over the fourth screen so you don't have to stare at a HOM :V
+ if (splitscreen == 2)
+ {
+ // V_DrawPatchFill, but for the fourth screen only
+ patch_t *pat = W_CachePatchName("SRB2BACK", PU_CACHE);
+ INT32 dupz = (vid.dupx < vid.dupy ? vid.dupx : vid.dupy);
+ INT32 x, y, pw = SHORT(pat->width) * dupz, ph = SHORT(pat->height) * dupz;
+
+ for (x = vid.width>>1; x < vid.width; x += pw)
+ {
+ for (y = vid.height>>1; y < vid.height; y += ph)
+ V_DrawScaledPatch(x, y, V_NOSCALESTART, pat);
+ }
+ }
+
+ for (i = 0; i <= splitscreen; i++)
+ {
+ const boolean issplitscreen = (i > 0);
+
+ if (!P_MobjWasRemoved(players[displayplayers[i]].mo) || players[displayplayers[i]].playerstate == PST_DEAD)
+ {
+ viewssnum = i;
+
+ if (!issplitscreen) // Initialize for P1
+ {
+ viewwindowy = viewwindowx = 0;
+ objectsdrawn = 0;
+ }
+
+#ifdef HWRENDER
+ if (rendermode == render_opengl)
+ {
+ HWR_RenderPlayerView();
+ R_RestoreLevelInterpolators();
+ continue;
+ }
+#endif
+ if (issplitscreen) // Splitscreen-specific
+ {
+ switch (i)
+ {
+ case 1:
+ if (splitscreen > 1)
+ {
+ viewwindowx = viewwidth;
+ viewwindowy = 0;
+ }
+ else
+ {
+ viewwindowx = 0;
+ viewwindowy = viewheight;
+ }
+ break;
+ case 2:
+ viewwindowx = 0;
+ viewwindowy = viewheight;
+ break;
+ case 3:
+ viewwindowx = viewwidth;
+ viewwindowy = viewheight;
+ default:
+ break;
+ }
+ }
+
+ R_RenderPlayerView(&players[displayplayers[i]]);
+ }
+
+ if (!issplitscreen)
+ R_ApplyViewMorph();
+
+ V_DoPostProcessor(i, postimgparam[i]);
+ }
+
+ R_RestoreLevelInterpolators();
+}
+
// wipegamestate can be set to -1 to force a wipe on the next draw
// added comment : there is a wipe eatch change of the gamestate
gamestate_t wipegamestate = GS_LEVEL;
@@ -327,7 +433,6 @@ static boolean D_Display(void)
boolean forcerefresh = false;
static boolean wipe = false;
INT32 wipedefindex = 0;
- UINT8 i;
if (!dedicated)
{
@@ -366,6 +471,7 @@ static boolean D_Display(void)
{
// set for all later
wipedefindex = gamestate; // wipe_xxx_toblack
+
if (gamestate == GS_TITLESCREEN && wipegamestate != GS_INTRO)
wipedefindex = wipe_timeattack_toblack;
else if (gamestate == GS_INTERMISSION)
@@ -378,26 +484,28 @@ static boolean D_Display(void)
if (!dedicated)
{
- // Fade to black first
- if (gamestate != GS_LEVEL // fades to black on its own timing, always
- && wipedefs[wipedefindex] != UINT8_MAX)
+ if (gamestate != GS_LEVEL)
{
- F_WipeStartScreen();
- V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31);
- F_WipeEndScreen();
- F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
- ranwipe = true;
- }
+ // Fade to black first
+ if (wipedefs[wipedefindex] != UINT8_MAX) // fades to black on its own timing, always
+ {
+ F_WipeStartScreen();
+ V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31);
+ F_WipeEndScreen();
+ F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
+ ranwipe = true;
+ }
- if (gamestate != GS_LEVEL && rendermode != render_none)
- {
- V_SetPaletteLump("PLAYPAL"); // Reset the palette
- R_ReInitColormaps(0, LUMPERROR);
+ if (rendermode != render_none)
+ {
+ V_SetPaletteLump("PLAYPAL"); // Reset the palette
+ R_ReInitColormaps(0, LUMPERROR);
+ }
}
F_WipeStartScreen();
}
- else //dedicated servers
+ else // dedicated servers
{
F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
ranwipe = true;
@@ -405,7 +513,7 @@ static boolean D_Display(void)
}
}
- if (dedicated) //bail out after wipe logic
+ if (dedicated) // bail out after wipe logic
return false;
// do buffered drawing
@@ -430,9 +538,6 @@ static boolean D_Display(void)
HU_Drawer();
break;
- case GS_TIMEATTACK:
- break;
-
case GS_INTRO:
F_IntroDrawer();
if (wipegamestate == (gamestate_t)-1)
@@ -484,6 +589,7 @@ static boolean D_Display(void)
HU_Erase();
HU_Drawer();
}
+ case GS_TIMEATTACK:
case GS_DEDICATEDSERVER:
case GS_NULL:
break;
@@ -492,89 +598,10 @@ static boolean D_Display(void)
if (gamestate == GS_LEVEL)
{
// draw the view directly
- if (cv_renderview.value && !automapactive)
+ if (cv_renderview.value)
{
PS_START_TIMING(ps_rendercalltime);
-
- R_ApplyLevelInterpolators(rendertimefrac);
-
- for (i = 0; i <= splitscreen; i++)
- {
- if (!P_MobjWasRemoved(players[displayplayers[i]].mo) || players[displayplayers[i]].playerstate == PST_DEAD)
- {
- viewssnum = i;
-
- if (i == 0) // Initialize for P1
- {
- viewwindowy = 0;
- viewwindowx = 0;
-
- topleft = screens[0] + viewwindowy*vid.width + viewwindowx;
- objectsdrawn = 0;
- }
-
-#ifdef HWRENDER
- if (rendermode == render_opengl)
- HWR_RenderPlayerView();
- else
-#endif
- if (rendermode != render_none)
- {
- if (i > 0) // Splitscreen-specific
- {
- switch (i)
- {
- case 1:
- if (splitscreen > 1)
- {
- viewwindowx = viewwidth;
- viewwindowy = 0;
- }
- else
- {
- viewwindowx = 0;
- viewwindowy = viewheight;
- }
- M_Memcpy(ylookup, ylookup2, viewheight*sizeof (ylookup[0]));
- break;
- case 2:
- viewwindowx = 0;
- viewwindowy = viewheight;
- M_Memcpy(ylookup, ylookup3, viewheight*sizeof (ylookup[0]));
- break;
- case 3:
- viewwindowx = viewwidth;
- viewwindowy = viewheight;
- M_Memcpy(ylookup, ylookup4, viewheight*sizeof (ylookup[0]));
- default:
- break;
- }
-
-
- topleft = screens[0] + viewwindowy*vid.width + viewwindowx;
- }
-
- R_RenderPlayerView(&players[displayplayers[i]]);
-
- if (i > 0)
- M_Memcpy(ylookup, ylookup1, viewheight*sizeof (ylookup[0]));
- }
- }
- }
-
- if (rendermode == render_soft)
- {
- if (!splitscreen)
- R_ApplyViewMorph();
-
- for (i = 0; i <= splitscreen; i++)
- {
- V_DoPostProcessor(i, postimgparam[i]);
- }
- }
-
- R_RestoreLevelInterpolators();
-
+ D_Renderview();
PS_STOP_TIMING(ps_rendercalltime);
}
@@ -582,8 +609,9 @@ static boolean D_Display(void)
{
if (rendermode == render_soft)
{
- VID_BlitLinearScreen(screens[0], screens[1], vid.width*vid.bpp, vid.height, vid.width*vid.bpp, vid.rowbytes);
+ VID_BlitLinearScreen(vid.screens[0], vid.screens[1], vid.width, vid.height, vid.width, vid.rowbytes);
}
+
lastdraw = false;
}
@@ -606,13 +634,8 @@ static boolean D_Display(void)
// draw pause pic
if (paused && cv_showhud.value && !demo.playback)
{
- INT32 py;
- patch_t *patch;
- if (automapactive)
- py = 4;
- else
- py = viewwindowy + 4;
- patch = W_CachePatchName("M_PAUSE", PU_PATCH);
+ INT32 py = (automapactive) ? 4 : (viewwindowy + 4);
+ patch_t *patch = W_CachePatchName("M_PAUSE", PU_PATCH);
V_DrawScaledPatch(viewwindowx + (BASEVIDWIDTH - patch->width)/2, py, V_SNAPTOTOP, patch);
}
@@ -620,7 +643,7 @@ static boolean D_Display(void)
V_DrawFadeScreen(TC_RAINBOW, (leveltime & 0x20) ? SKINCOLOR_PASTEL : SKINCOLOR_MOONSLAM);
// vid size change is now finished if it was on...
- vid.recalc = 0;
+ vid.recalc = false;
#ifdef HAVE_THREADS
I_lock_mutex(&m_menu_mutex);
@@ -752,9 +775,11 @@ void D_SRB2Loop(void)
precise_t enterprecise = I_GetPreciseTime();
precise_t finishprecise = enterprecise;
+ Z_Frame_Reset();
+
// Casting the return value of a function is bad practice (apparently)
double budget = ((R_GetFramerateCap() == 0) ? 0.0 : round((1.0 / R_GetFramerateCap()) * I_GetPrecisePrecision()));
- capbudget = (precise_t) budget;
+ capbudget = (precise_t)budget;
boolean ranwipe = false;
@@ -824,12 +849,15 @@ void D_SRB2Loop(void)
doDisplay = true;
}
- if (menuactive)
+ if (!dedicated)
{
- D_GamePadMenuScrollTicker();
- }
+ if (menuactive)
+ {
+ D_GamePadMenuScrollTicker();
+ }
- D_DeviceLEDTick();
+ D_DeviceLEDTick();
+ }
}
if (interp)
@@ -841,7 +869,9 @@ void D_SRB2Loop(void)
ps_interp_frac.value.p = (precise_t)((FIXED_TO_FLOAT(g_time.timefrac)) * 1000.0f);
ps_interp_lag.value.p = (precise_t)((deltasecs) * 1000.0f);
- if (!(paused || P_AutoPause()) && deltatics < 1.0 && !hu_stopped)
+ const boolean lagging = ((deltatics >= 1.0) || hu_stopped);
+
+ if (!(paused || P_AutoPause()) && !lagging)
{
rendertimefrac = g_time.timefrac;
}
@@ -850,7 +880,7 @@ void D_SRB2Loop(void)
rendertimefrac = FRACUNIT;
}
- if ((deltatics < 1.0) && !hu_stopped)
+ if (!lagging)
{
rendertimefrac_unpaused = g_time.timefrac;
}
@@ -923,7 +953,7 @@ void D_SRB2Loop(void)
if ((elapsed > 0) && ((INT64)capbudget > elapsed) && !vsync_with_match_refresh)
{
- I_SleepDuration(capbudget - (finishprecise - enterprecise));
+ I_SleepDuration(capbudget - elapsed);
}
}
// Capture the time once more to get the real delta time.
@@ -1213,32 +1243,32 @@ static boolean AddIWAD(void)
}
// extra graphic patches for saturn specific thingies
-boolean found_extra_kart = false;
+boolean found_extra_kart = false;
boolean found_extra2_kart = false;
boolean found_extra3_kart = false;
-boolean xtra_speedo = false; // extra speedometer check
-boolean xtra_speedo_clr = false; // extra speedometer colour check
-boolean xtra_speedo3 = false; // 80x 11 extra speedometer check
-boolean xtra_speedo_clr3 = false; // 80x 11 extra speedometer colour check
-boolean achi_speedo = false; // achiiro speedometer check
-boolean achi_speedo_clr = false; // extra speedometer colour check
-boolean dial_speedo = false; // dial speedometer check
-boolean dial_speedo_clr = false; // dial speedometer colour check
-boolean kartz_speedo = false; // kartZ speedo
+boolean xtra_speedo = false; // extra speedometer check
+boolean xtra_speedo_clr = false; // extra speedometer colour check
+boolean xtra_speedo3 = false; // 80x 11 extra speedometer check
+boolean xtra_speedo_clr3 = false; // 80x 11 extra speedometer colour check
+boolean achi_speedo = false; // achiiro speedometer check
+boolean achi_speedo_clr = false; // extra speedometer colour check
+boolean dial_speedo = false; // dial speedometer check
+boolean dial_speedo_clr = false; // dial speedometer colour check
+boolean kartz_speedo = false; // kartZ speedo
boolean kartz_speedo_smol = false; // kartZ speedo but smol
-boolean clr_hud = false; // colour hud check
+boolean clr_hud = false; // colour hud check
boolean driftgaugegfx_clr = false; // driftgauge colour check
-boolean big_lap = false; // bigger lap counter
-boolean big_lap_color = false; // bigger lap counter but colour
-boolean statdp = false; // stat display for extended player setup
-boolean nametaggfx = false; // Nametag stuffs
-boolean driftgaugegfx = false; // Driftgauge stuffs
-boolean multiitem_icon = false; // Extra icons for Sneakers, Banana and Jawz
-boolean joystickicon = false; // Extra icons for the joystick input display
-boolean minidoticon = false; // Dot graphic for minimap player angle display
-boolean minilighticon = false; // mkwii-style minimap headlight
+boolean big_lap = false; // bigger lap counter
+boolean big_lap_color = false; // bigger lap counter but colour
+boolean statdp = false; // stat display for extended player setup
+boolean nametaggfx = false; // Nametag stuffs
+boolean driftgaugegfx = false; // Driftgauge stuffs
+boolean multiitem_icon = false; // Extra icons for Sneakers, Banana and Jawz
+boolean joystickicon = false; // Extra icons for the joystick input display
+boolean minidoticon = false; // Dot graphic for minimap player angle display
+boolean minilighticon = false; // mkwii-style minimap headlight
//
static void IdentifyVersion(void)
@@ -1602,7 +1632,9 @@ void D_SRB2Main(void)
#endif
// for dedicated server
+#if !defined (DEDICATED)
dedicated = M_CheckParm("-dedicated") != 0;
+#endif
strcpy(title, "SRB2Kart");
strcpy(srb2, "SRB2Kart");
@@ -1804,7 +1836,7 @@ void D_SRB2Main(void)
{
name = lumpinfo->name;
- if (name[0] == 'M' && name[1] == 'A' && name[2] == 'P') // Ignore the headers
+ if (memcmp(name, "MAP", 3) == 0) // Ignore the headers
{
INT16 num;
if (name[5] != '\0')
@@ -1834,7 +1866,7 @@ void D_SRB2Main(void)
{
name = lumpinfo->name;
- if (name[0] == 'M' && name[1] == 'A' && name[2] == 'P') // Ignore the headers
+ if (memcmp(name, "MAP", 3) == 0) // Ignore the headers
{
INT16 num;
if (name[5] != '\0')
diff --git a/src/d_main.h b/src/d_main.h
index cb4049e54..1e2de572d 100644
--- a/src/d_main.h
+++ b/src/d_main.h
@@ -14,6 +14,10 @@
#ifndef __D_MAIN__
#define __D_MAIN__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "d_event.h"
#include "w_wad.h" // for MAX_WADFILES
@@ -90,4 +94,8 @@ const char *D_Home(void);
//
void D_StartTitle(void);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif //__D_MAIN__
diff --git a/src/d_net.h b/src/d_net.h
index 1b6cd905c..caeb3c83f 100644
--- a/src/d_net.h
+++ b/src/d_net.h
@@ -18,6 +18,10 @@
#ifndef __D_NET__
#define __D_NET__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
// Max computers in a game
// 127 is probably as high as this can go, because
// SINT8 is used for nodes sometimes >:(
@@ -43,8 +47,6 @@ extern SINT8 nodetoplayer4[MAXNETNODES]; // Say the numplayer for this node if a
extern UINT8 playerpernode[MAXNETNODES]; // Used specially for splitscreen
extern boolean nodeingame[MAXNETNODES]; // Set false as nodes leave game
-extern boolean serverrunning;
-
void Net_AckTicker(void);
// If reliable return true if packet sent, 0 else
@@ -65,4 +67,8 @@ void Net_SendAcks(INT32 node);
void Net_WaitAllAckReceived(UINT32 timeout);
const char *Net_GetPacketName(UINT8 packettype);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/d_netcmd.c b/src/d_netcmd.c
index 5b8a8c18b..8a4e12ebf 100644
--- a/src/d_netcmd.c
+++ b/src/d_netcmd.c
@@ -204,11 +204,6 @@ static void Command_Archivetest_f(void);
// CLIENT VARIABLES
// =========================================================================
-void SendWeaponPref(void);
-void SendWeaponPref2(void);
-void SendWeaponPref3(void);
-void SendWeaponPref4(void);
-
static CV_PossibleValue_t usemouse_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Force"}, {0, NULL}};
static CV_PossibleValue_t autobalance_cons_t[] = {{0, "MIN"}, {4, "MAX"}, {0, NULL}};
@@ -216,11 +211,8 @@ static CV_PossibleValue_t teamscramble_cons_t[] = {{0, "Off"}, {1, "Random"}, {2
static CV_PossibleValue_t startingliveslimit_cons_t[] = {{1, "MIN"}, {99, "MAX"}, {0, NULL}};
static CV_PossibleValue_t sleeping_cons_t[] = {{0, "MIN"}, {1000/TICRATE, "MAX"}, {0, NULL}};
-static CV_PossibleValue_t competitionboxes_cons_t[] = {{0, "Normal"}, {1, "Random"}, {2, "Teleports"},
- {3, "None"}, {0, NULL}};
-
-static CV_PossibleValue_t matchboxes_cons_t[] = {{0, "Normal"}, {1, "Random"}, {2, "Non-Random"},
- {3, "None"}, {0, NULL}};
+static CV_PossibleValue_t competitionboxes_cons_t[] = {{0, "Normal"}, {1, "Random"}, {2, "Teleports"}, {3, "None"}, {0, NULL}};
+static CV_PossibleValue_t matchboxes_cons_t[] = {{0, "Normal"}, {1, "Random"}, {2, "Non-Random"}, {3, "None"}, {0, NULL}};
//static CV_PossibleValue_t chances_cons_t[] = {{0, "MIN"}, {9, "MAX"}, {0, NULL}};
static CV_PossibleValue_t match_scoring_cons_t[] = {{0, "Normal"}, {1, "Classic"}, {0, NULL}};
@@ -305,14 +297,12 @@ consvar_t cv_verticallook[MAXSPLITSCREENPLAYERS] = {
{"verticallook4", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}
};
-#if defined(HAVE_SDL) || defined(_WINDOWS) //joystick 1 and 2
consvar_t cv_usejoystick[MAXSPLITSCREENPLAYERS] = {
{"use_joystick", "1", CV_SAVE|CV_CALL, NULL, I_InitJoystick1, 0, NULL, NULL, 0, 0, NULL},
{"use_joystick2", "2", CV_SAVE|CV_CALL, NULL, I_InitJoystick2, 0, NULL, NULL, 0, 0, NULL},
{"use_joystick3", "3", CV_SAVE|CV_CALL, NULL, I_InitJoystick3, 0, NULL, NULL, 0, 0, NULL},
{"use_joystick4", "4", CV_SAVE|CV_CALL, NULL, I_InitJoystick4, 0, NULL, NULL, 0, 0, NULL}
};
-#endif
#if defined (HAVE_SDL)
consvar_t cv_joyscale[MAXSPLITSCREENPLAYERS] = {
@@ -905,6 +895,7 @@ void D_RegisterClientCommands(void)
CV_RegisterVar(&cv_netticbuffer);
CV_RegisterVar(&cv_mindelay);
CV_RegisterVar(&cv_gentlemens);
+ CV_RegisterVar(&cv_serverinfoscreen);
#ifdef NETGAME_DEVMODE
CV_RegisterVar(&cv_fishcake);
@@ -1034,6 +1025,8 @@ void D_RegisterClientCommands(void)
CV_RegisterVar(&cv_scr_width);
CV_RegisterVar(&cv_scr_height);
+ CV_RegisterVar(&cv_parallelsoftware);
+
CV_RegisterVar(&cv_soundtest);
CV_RegisterVar(&cv_perfstats);
@@ -1055,7 +1048,9 @@ void D_RegisterClientCommands(void)
CV_RegisterVar(&cv_verticallook[i]);
}
+ CV_RegisterVar(&cv_resyncdemo);
CV_RegisterVar(&cv_demodateformat);
+
CV_RegisterVar(&cv_showspecstuff);
// ingame object placing
@@ -2777,7 +2772,7 @@ static void Command_Map_f(void)
// G_TOLFlag handles both multiplayer gametype and ignores it for !multiplayer
else
{
- if (!mapheaderinfo[newmapnum-1] || mapheaderinfo[newmapnum-1] == NULL)
+ if (!mapheaderinfo[newmapnum-1])
{
CONS_Alert(CONS_WARNING, M_GetText("Invalid mapheaderinfo for Course %s (%s)\n"), realmapname, G_BuildMapName(newmapnum));
Z_Free(realmapname);
@@ -3031,9 +3026,14 @@ static void Command_ReplayMarker(void)
adjustedleveltime = 0;
char *title = G_BuildMapTitle(gamemap);
- snprintf(demo.titlename, 64, "%s [%i:%02d/%.5s]", title, G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername);
+
if (title)
+ {
+ snprintf(demo.titlename, 64, "%s [%i:%02d/%.5s]", title, G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername);
Z_Free(title);
+ }
+ else
+ snprintf(demo.titlename, 64, "[%i:%02d/%.5s]", G_TicsToMinutes(adjustedleveltime, false), G_TicsToSeconds(adjustedleveltime), modeattacking ? "Record Attack" : connectedservername);
CONS_Printf("Replay will be saved!\n");
}
diff --git a/src/d_netcmd.h b/src/d_netcmd.h
index b4ee22d93..657686af4 100644
--- a/src/d_netcmd.h
+++ b/src/d_netcmd.h
@@ -15,8 +15,17 @@
#ifndef __D_NETCMD__
#define __D_NETCMD__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "command.h"
+void SendWeaponPref(void);
+void SendWeaponPref2(void);
+void SendWeaponPref3(void);
+void SendWeaponPref4(void);
+
// console vars
extern consvar_t cv_playername;
extern consvar_t cv_playercolor;
@@ -318,4 +327,8 @@ void D_SetPassword(const char *pw);
// used for the player setup menu
UINT8 CanChangeSkin(INT32 playernum);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/d_netfil.c b/src/d_netfil.c
index 0650f3c34..d45570a0e 100644
--- a/src/d_netfil.c
+++ b/src/d_netfil.c
@@ -111,7 +111,9 @@ static fileused_t transferFiles[UINT8_MAX + 1];
// Receiver structure
INT32 fileneedednum; // Number of files needed to join the server
fileneeded_t fileneeded[MAX_WADFILES]; // List of needed files
+#ifdef HAVE_THREADS
static I_mutex downloadmutex;
+#endif
char downloaddir[512] = "DOWNLOAD";
file_download_t filedownload;
@@ -1351,14 +1353,18 @@ void CURLAbortFile(void)
{
filedownload.http_running = false;
+#ifdef HAVE_THREADS
// lock and unlock to wait for the download thread to exit
I_lock_mutex(&downloadmutex);
I_unlock_mutex(downloadmutex);
+#endif
}
void CURLGetFile(void)
{
+#ifdef HAVE_THREADS
I_lock_mutex(&downloadmutex);
+#endif
CURLMcode mc; /* return code used by curl_multi_wait() */
CURLcode easyres; /* Return from easy interface */
CURLMsg *m; /* for picking up messages with the transfer status */
@@ -1453,7 +1459,9 @@ void CURLGetFile(void)
}
filedownload.http_running = false;
+#ifdef HAVE_THREADS
I_unlock_mutex(downloadmutex);
+#endif
}
HTTP_login *
diff --git a/src/d_netfil.h b/src/d_netfil.h
index 464d885b3..b84c83391 100644
--- a/src/d_netfil.h
+++ b/src/d_netfil.h
@@ -13,6 +13,10 @@
#ifndef __D_NETFIL__
#define __D_NETFIL__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "d_clisrv.h"
#include "w_wad.h"
@@ -125,4 +129,8 @@ HTTP_login * CURLGetLogin (const char *url, HTTP_login ***return_prev_next);
size_t curlwrite_data(void *ptr, size_t size, size_t nmemb, FILE *stream);
#endif
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // __D_NETFIL__
diff --git a/src/dedicated/CMakeLists.txt b/src/dedicated/CMakeLists.txt
new file mode 100644
index 000000000..36f670251
--- /dev/null
+++ b/src/dedicated/CMakeLists.txt
@@ -0,0 +1,108 @@
+# Declare dedicated interface sources
+
+target_sourcefile(c)
+
+target_sources(SRB2SDL2 PRIVATE)
+
+if(${CMAKE_SYSTEM} MATCHES Windows)
+ target_sources(SRB2SDL2 PRIVATE
+ ../win32/win_dbg.c
+ ../win32/Srb2win.rc)
+endif()
+
+if(${CMAKE_SYSTEM} MATCHES Windows)
+ set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2legacy)
+elseif(${CMAKE_SYSTEM} MATCHES Linux)
+ set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME lsrb2dlegacy)
+else()
+ set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME srb2legacy)
+endif()
+
+if(${CMAKE_SYSTEM} MATCHES Darwin)
+ find_library(CORE_LIB CoreFoundation)
+ target_link_libraries(SRB2SDL2 PRIVATE
+ ${CORE_LIB}
+ ${PNG_LIBRARIES}
+ ${ZLIB_LIBRARIES}
+ )
+ set_target_properties(SRB2SDL2 PROPERTIES OUTPUT_NAME "${CPACK_PACKAGE_DESCRIPTION_SUMMARY}")
+else()
+ target_link_libraries(SRB2SDL2 PRIVATE
+ ${PNG_LIBRARIES}
+ ${ZLIB_LIBRARIES}
+ )
+
+ if(${CMAKE_SYSTEM} MATCHES Linux)
+ target_link_libraries(SRB2SDL2 PRIVATE
+ m
+ rt
+ )
+ endif()
+endif()
+
+#target_link_libraries(SRB2SDL2 PRIVATE SRB2Core)
+
+set_target_properties(SRB2SDL2 PROPERTIES VERSION ${SRB2_VERSION})
+
+if(${CMAKE_SYSTEM} MATCHES Windows)
+ target_link_libraries(SRB2SDL2 PRIVATE
+ ws2_32
+ )
+ target_compile_options(SRB2SDL2 PRIVATE
+ -U_WINDOWS
+ )
+endif()
+
+target_include_directories(SRB2SDL2 PRIVATE
+ ${PNG_INCLUDE_DIRS}
+ ${ZLIB_INCLUDE_DIRS}
+)
+
+target_compile_definitions(SRB2SDL2 PRIVATE
+ -DDEDICATED
+)
+
+## strip debug symbols into separate file when using gcc
+if(CMAKE_COMPILER_IS_GNUCC)
+ if(${CMAKE_BUILD_TYPE} MATCHES Debug)
+ message(STATUS "Will make separate debug symbols in *.debug")
+ add_custom_command(TARGET SRB2SDL2 POST_BUILD
+ COMMAND ${OBJCOPY} --only-keep-debug $ $.debug
+ COMMAND ${OBJCOPY} --strip-debug $
+ COMMAND ${OBJCOPY} --add-gnu-debuglink=$.debug $
+ )
+ endif()
+endif()
+
+#### Installation ####
+if(${CMAKE_SYSTEM} MATCHES Darwin)
+ install(TARGETS SRB2SDL2
+ BUNDLE DESTINATION .
+ )
+else()
+ install(TARGETS SRB2SDL2 SRB2SDL2
+ RUNTIME DESTINATION .
+ )
+endif()
+
+# Mac bundle fixup
+# HACK: THIS IS IMPORTANT! See the escaped \${CMAKE_INSTALL_PREFIX}? This
+# makes it so that var is evaluated LATER during cpack, not right now!
+# This fixes the quirk where the bundled libraries don't land in the final package
+# https://cmake.org/pipermail/cmake/2011-March/043532.html
+#
+# HOWEVER: ${CPACK_PACKAGE_DESCRIPTION_SUMMARY} is NOT escaped, because that var
+# is only available to us at this step. Read the link: ${CMAKE_INSTALL_PREFIX} at
+# this current step points to the CMAKE build folder, NOT the folder that CPACK uses.
+# Therefore, it makes sense to escape that var, but not the other.
+if(${CMAKE_SYSTEM} MATCHES Darwin)
+ install(CODE "
+ include(BundleUtilities)
+ fixup_bundle(\"\${CMAKE_INSTALL_PREFIX}/${CPACK_PACKAGE_DESCRIPTION_SUMMARY}.app\"
+ \"\"
+ /Library/Frameworks
+ )"
+ )
+endif()
+
+set(SRB2_SDL2_AVAILABLE YES PARENT_SCOPE)
diff --git a/src/dedicated/Sourcefile b/src/dedicated/Sourcefile
new file mode 100644
index 000000000..176e60a96
--- /dev/null
+++ b/src/dedicated/Sourcefile
@@ -0,0 +1,7 @@
+i_system.c
+i_main.c
+i_video.c
+i_sound.c
+i_threads.c
+dosstr.c
+endtxt.c
diff --git a/src/dedicated/dosstr.c b/src/dedicated/dosstr.c
new file mode 100644
index 000000000..f9bbee9b4
--- /dev/null
+++ b/src/dedicated/dosstr.c
@@ -0,0 +1,38 @@
+// Emacs style mode select -*- C++ -*-
+//-----------------------------------------------------------------------------
+//
+// This file is in the public domain.
+// (Re)written by Graue in 2006.
+//
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief String uppercasing/lowercasing functions for non-DOS non-Win32
+/// systems
+
+#include "../doomtype.h"
+
+#ifndef HAVE_DOSSTR_FUNCS
+
+#include
+
+int strupr(char *n)
+{
+ while (*n != '\0')
+ {
+ *n = toupper(*n);
+ n++;
+ }
+ return 1;
+}
+
+int strlwr(char *n)
+{
+ while (*n != '\0')
+ {
+ *n = tolower(*n);
+ n++;
+ }
+ return 1;
+}
+
+#endif
diff --git a/src/dedicated/endtxt.c b/src/dedicated/endtxt.c
new file mode 100644
index 000000000..1e72ca9a8
--- /dev/null
+++ b/src/dedicated/endtxt.c
@@ -0,0 +1,234 @@
+/*
+ * Function to write the SRB2 end message text
+ *
+ * Copyright (C) 1998 by Udo Munk
+ *
+ * This code is provided AS IS and there are no guarantees, none.
+ * Feel free to share and modify.
+ */
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief Support to show ENDOOM text
+///
+/// Loads the lump ENDOOM, set up the console to print
+/// out the colors and text
+
+#include
+#include
+
+// need this 19990118 by Kin
+#include "../doomdef.h"
+#include "../w_wad.h"
+#include "../z_zone.h"
+#include "endtxt.h"
+/** \brief The ShowEndTxt function
+
+
+ Prints out the ENDOOM the way DOOM.EXE/DOOM2.EXE did for Win32 or Linux/GNU
+
+ \return void
+
+
+*/
+
+void ShowEndTxt(void)
+{
+ INT32 i;
+ UINT16 j, att = 0;
+ INT32 nlflag = 1;
+#ifdef _WIN32
+ HANDLE co = GetStdHandle(STD_OUTPUT_HANDLE);
+ DWORD mode, bytesWritten;
+ CONSOLE_SCREEN_BUFFER_INFO backupcon;
+ COORD resizewin = {80,-1};
+ CHAR let = 0;
+#endif
+ UINT16 *ptext;
+ void *data;
+ lumpnum_t endoomnum = W_GetNumForName("ENDOOM");
+ //char *col;
+
+ /* if the xterm has more then 80 columns we need to add nl's */
+ /* doesn't work, COLUMNS is not in the environment at this time ???
+ col = I_getenv("COLUMNS");
+ if (col) {
+ if (atoi(col) > 80)
+ nlflag++;
+ }
+ */
+
+ /* get the lump with the text */
+ data = ptext = W_CacheLumpNum(endoomnum, PU_CACHE);
+
+#ifdef _WIN32
+ if (co == INVALID_HANDLE_VALUE || GetFileType(co) != FILE_TYPE_CHAR || !GetConsoleMode(co, &mode)) // test if it a good handle
+ {
+ Z_Free(data);
+ return;
+ }
+
+ backupcon.wAttributes = FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE; // Just in case
+ GetConsoleScreenBufferInfo(co, &backupcon); //Store old state
+ resizewin.Y = backupcon.dwSize.Y;
+ if (backupcon.dwSize.X < resizewin.X)
+ SetConsoleScreenBufferSize(co, resizewin);
+
+ for (i=1; i<=80*25; i++) // print 80x25 text and deal with the attributes too
+ {
+ j = (UINT16)(*ptext >> 8); // attribute first
+ let = (char)(*ptext & 0xff); // text second
+ if (j != att) // attribute changed?
+ {
+ att = j; // save current attribute
+ SetConsoleTextAttribute(co, j); //set fg and bg color for buffer
+ }
+
+ WriteConsoleA(co, &let, 1, &bytesWritten, NULL); // now the text
+
+ if (nlflag && !(i % 80) && backupcon.dwSize.X > resizewin.X) // do we need a nl?
+ {
+ att = backupcon.wAttributes;
+ SetConsoleTextAttribute(co, att); // all attributes off
+ WriteConsoleA(co, "\n", 1, &bytesWritten, NULL); // newline to console
+ }
+ ptext++;
+ }
+ SetConsoleTextAttribute(co, backupcon.wAttributes); // all attributes off
+#else
+ /* print 80x25 text and deal with the attributes too */
+ for (i=1; i<=80*25; i++) {
+ /* attribute first */
+ /* attribute changed? */
+ if ((j = *ptext >> 8) != att) {
+ /* save current attribute */
+ att = j;
+ /* set new attribute, forground color first */
+ printf("\033[");
+ switch (j & 0x0f) {
+ case 0: /* black */
+ printf("30");
+ break;
+ case 1: /* blue */
+ printf("34");
+ break;
+ case 2: /* green */
+ printf("32");
+ break;
+ case 3: /* cyan */
+ printf("36");
+ break;
+ case 4: /* red */
+ printf("31");
+ break;
+ case 5: /* magenta */
+ printf("35");
+ break;
+ case 6: /* brown */
+ printf("33");
+ break;
+ case 7: /* bright grey */
+ printf("37");
+ break;
+ case 8: /* dark grey */
+ printf("1;30");
+ break;
+ case 9: /* bright blue */
+ printf("1;34");
+ break;
+ case 10: /* bright green */
+ printf("1;32");
+ break;
+ case 11: /* bright cyan */
+ printf("1;36");
+ break;
+ case 12: /* bright red */
+ printf("1;31");
+ break;
+ case 13: /* bright magenta */
+ printf("1;35");
+ break;
+ case 14: /* yellow */
+ printf("1;33");
+ break;
+ case 15: /* white */
+ printf("1;37");
+ break;
+ }
+ printf("m");
+ /* now background color */
+ printf("\033[");
+ switch ((j >> 4) & 0x0f) {
+ case 0: /* black */
+ printf("40");
+ break;
+ case 1: /* blue */
+ printf("44");
+ break;
+ case 2: /* green */
+ printf("42");
+ break;
+ case 3: /* cyan */
+ printf("46");
+ break;
+ case 4: /* red */
+ printf("41");
+ break;
+ case 5: /* magenta */
+ printf("45");
+ break;
+ case 6: /* brown */
+ printf("43");
+ break;
+ case 7: /* bright grey */
+ printf("47");
+ break;
+ case 8: /* dark grey */
+ printf("1;40");
+ break;
+ case 9: /* bright blue */
+ printf("1;44");
+ break;
+ case 10: /* bright green */
+ printf("1;42");
+ break;
+ case 11: /* bright cyan */
+ printf("1;46");
+ break;
+ case 12: /* bright red */
+ printf("1;41");
+ break;
+ case 13: /* bright magenta */
+ printf("1;45");
+ break;
+ case 14: /* yellow */
+ printf("1;43");
+ break;
+ case 15: /* white */
+ printf("1;47");
+ break;
+ }
+ printf("m");
+ }
+
+ /* now the text */
+ printf("%c",*ptext++ & 0xff);
+
+ /* do we need a nl? */
+ if (nlflag)
+ {
+ if (!(i % 80))
+ {
+ printf("\033[0m");
+ att = 0;
+ printf("\n");
+ }
+ }
+ }
+ /* all attributes off */
+ printf("\033[0m");
+#endif
+ if (nlflag)
+ printf("\n");
+
+ Z_Free(data);
+}
diff --git a/src/dedicated/endtxt.h b/src/dedicated/endtxt.h
new file mode 100644
index 000000000..41f8e51ad
--- /dev/null
+++ b/src/dedicated/endtxt.h
@@ -0,0 +1,24 @@
+// Emacs style mode select -*- C++ -*-
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) 1998-2000 by DooM Legacy Team.
+//
+// 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; either version 2
+// of the License, or (at your option) any later version.
+//
+// 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.
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief Support to show ENDOOM text
+
+#ifndef __ENDTXT__
+#define __ENDTXT__
+
+void ShowEndTxt (void);
+
+#endif
diff --git a/src/dedicated/i_main.c b/src/dedicated/i_main.c
new file mode 100644
index 000000000..911e356d0
--- /dev/null
+++ b/src/dedicated/i_main.c
@@ -0,0 +1,238 @@
+// Emacs style mode select -*- C++ -*-
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) 1993-1996 by id Software, Inc.
+// Copyright (C) 1998-2000 by DooM Legacy Team.
+//
+// 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; either version 2
+// of the License, or (at your option) any later version.
+//
+// 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.
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief Main program, simply calls D_SRB2Main and D_SRB2Loop, the high level loop.
+
+#include "../doomdef.h"
+#include "../m_argv.h"
+#include "../d_main.h"
+#include "../m_misc.h" /* path shit */
+#include "../i_system.h"
+#include "../d_clisrv.h"
+
+#if defined (__GNUC__) || defined (__unix__)
+#include
+#endif
+
+#ifdef __unix__
+#include
+#endif
+
+#include "time.h" // For log timestamps
+
+#ifdef HAVE_TTF
+#include "i_ttf.h"
+#endif
+
+#ifdef HAVE_LIBBACKTRACE
+#include
+
+struct backtrace_state *bt_state = NULL;
+#endif
+
+#ifdef LOGMESSAGES
+FILE *logstream = NULL;
+char logfilename[1024];
+#endif
+
+#ifndef DOXYGEN
+#ifndef O_TEXT
+#define O_TEXT 0
+#endif
+
+#ifndef O_SEQUENTIAL
+#define O_SEQUENTIAL 0
+#endif
+#endif
+
+#ifdef _WIN32
+#ifndef _AMD64_
+#include "exchndl.h"
+#define DRMINGW
+#endif
+#endif
+
+#if defined (_WIN32)
+#include "../win32/win_dbg.h"
+typedef BOOL (WINAPI *p_IsDebuggerPresent)(VOID);
+#endif
+
+#ifdef _WIN32
+static void
+ChDirToExe (void)
+{
+ CHAR path[MAX_PATH];
+ if (GetModuleFileNameA(NULL, path, MAX_PATH) > 0)
+ {
+ strrchr(path, '\\')[0] = '\0';
+ SetCurrentDirectoryA(path);
+ }
+}
+#endif
+
+/** \brief The main function
+
+ \param argc number of arg
+ \param *argv string table
+
+ \return int
+*/
+#if defined (__GNUC__) && (__GNUC__ >= 4)
+#pragma GCC diagnostic ignored "-Wmissing-noreturn"
+#endif
+
+#ifdef LOGMESSAGES
+static void InitLogging(void)
+{
+ const char *logdir = NULL;
+ time_t my_time;
+ struct tm * timeinfo;
+ const char *format;
+ const char *reldir;
+ int left;
+ boolean fileabs;
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+ const char *link;
+#endif
+
+ logdir = D_Home();
+
+ my_time = time(NULL);
+ timeinfo = localtime(&my_time);
+
+ if (M_CheckParm("-logfile") && M_IsNextParm())
+ {
+ format = M_GetNextParm();
+ fileabs = M_IsPathAbsolute(format);
+ }
+ else
+ {
+ format = "log-%Y-%m-%d_%H-%M-%S.txt";
+ fileabs = false;
+ }
+
+ if (fileabs)
+ {
+ strftime(logfilename, sizeof logfilename, format, timeinfo);
+ }
+ else
+ {
+ if (M_CheckParm("-logdir") && M_IsNextParm())
+ reldir = M_GetNextParm();
+ else
+ reldir = "logs";
+
+ if (M_IsPathAbsolute(reldir))
+ {
+ left = snprintf(logfilename, sizeof logfilename,
+ "%s"PATHSEP, reldir);
+ }
+ else
+#ifdef DEFAULTDIR
+ if (logdir)
+ {
+ left = snprintf(logfilename, sizeof logfilename,
+ "%s"PATHSEP DEFAULTDIR PATHSEP"%s"PATHSEP, logdir, reldir);
+ }
+ else
+#endif/*DEFAULTDIR*/
+ {
+ left = snprintf(logfilename, sizeof logfilename,
+ "."PATHSEP"%s"PATHSEP, reldir);
+ }
+
+ strftime(&logfilename[left], sizeof logfilename - left,
+ format, timeinfo);
+ }
+
+ M_MkdirEachUntil(logfilename,
+ M_PathParts(logdir) - 1,
+ M_PathParts(logfilename) - 1, 0755);
+
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+ logstream = fopen(logfilename, "w");
+#ifdef DEFAULTDIR
+ if (logdir)
+ link = va("%s/"DEFAULTDIR"/latest-log.txt", logdir);
+ else
+#endif/*DEFAULTDIR*/
+ link = "latest-log.txt";
+ unlink(link);
+ if (symlink(logfilename, link) == -1)
+ {
+ I_OutputMsg("Error symlinking latest-log.txt: %s\n", strerror(errno));
+ }
+#else/*defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)*/
+ logstream = fopen("latest-log.txt", "wt+");
+#endif/*defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)*/
+}
+#endif
+
+int main(int argc, char **argv)
+{
+ myargc = argc;
+ myargv = argv; /// \todo pull out path to exe from this string
+
+ dedicated = true;
+
+#ifdef HAVE_LIBBACKTRACE
+ bt_state = backtrace_create_state(
+ argv[0],
+#ifdef HAVE_THREADS
+ 1,
+#else
+ 0,
+#endif
+ NULL,
+ NULL
+ );
+#endif
+
+#ifdef _WIN32
+ ChDirToExe();
+#endif
+
+#ifdef LOGMESSAGES
+ if (!M_CheckParm("-nolog"))
+ InitLogging();
+#endif/*LOGMESSAGES*/
+
+ //I_OutputMsg("I_StartupSystem() ...\n");
+ I_StartupSystem();
+#if defined (_WIN32)
+ {
+#ifdef DRMINGW
+ ExcHndlInit();
+#endif
+ }
+#endif
+
+ // startup SRB2
+ CONS_Printf("Setting up SRB2Kart...\n");
+ D_SRB2Main();
+ CONS_Printf("Entering main game loop...\n");
+ // never return
+ D_SRB2Loop();
+
+#ifdef BUGTRAP
+ // This is safe even if BT didn't start.
+ ShutdownBugTrap();
+#endif
+
+ // return to OS
+ return 0;
+}
diff --git a/src/dedicated/i_sound.c b/src/dedicated/i_sound.c
new file mode 100644
index 000000000..de43aab85
--- /dev/null
+++ b/src/dedicated/i_sound.c
@@ -0,0 +1,339 @@
+// Emacs style mode select -*- C++ -*-
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) 1993-1996 by id Software, Inc.
+//
+// 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; either version 2
+// of the License, or (at your option) any later version.
+//
+// The source 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.
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief SDL interface for sound
+
+#include
+#include "../doomdef.h"
+#include "../i_sound.h"
+#include "../s_sound.h"
+
+/** \brief Sound subsystem runing and waiting
+*/
+UINT8 sound_started = false;
+
+/** \brief The I_GetSfx function
+
+ \param sfx sfx to setup
+
+ \return data for sfx
+*/
+void *I_GetSfx(sfxinfo_t *sfx)
+{
+ (void)sfx;
+ return NULL;
+}
+
+/** \brief The I_FreeSfx function
+
+ \param sfx sfx to be freed up
+
+ \return void
+*/
+void I_FreeSfx(sfxinfo_t *sfx)
+{
+ (void)sfx;
+}
+
+/** \brief Init at program start...
+*/
+void I_StartupSound(void){}
+
+/** \brief ... shut down and relase at program termination.
+*/
+void I_ShutdownSound(void){}
+
+/// ------------------------
+/// SFX I/O
+/// ------------------------
+
+/** \brief Starts a sound in a particular sound channel.
+ \param id sfxid
+ \param vol volume for sound
+ \param sep left-right balancle
+ \param pitch not used
+ \param priority not used
+
+ \return sfx handle
+*/
+INT32 I_StartSound(sfxenum_t id, UINT8 vol, UINT8 sep, UINT8 pitch, UINT8 priority, INT32 channel)
+{
+ (void)id;
+ (void)vol;
+ (void)sep;
+ (void)pitch;
+ (void)priority;
+ (void)channel;
+ return 0;
+}
+
+/** \brief Stops a sound channel.
+
+ \param handle stop sfx handle
+
+ \return void
+*/
+void I_StopSound(INT32 handle)
+{
+ (void)handle;
+}
+
+/** \brief Some digital sound drivers need this.
+*/
+void I_UpdateSound(void){}
+
+/** \brief Called by S_*() functions to see if a channel is still playing.
+
+ \param handle sfx handle
+
+ \return 0 if no longer playing, 1 if playing.
+*/
+boolean I_SoundIsPlaying(INT32 handle)
+{
+ (void)handle;
+ return false;
+}
+
+/** \brief Updates the sfx handle
+
+ \param handle sfx handle
+ \param vol volume
+ \param sep separation
+ \param pitch ptich
+
+ \return void
+*/
+void I_UpdateSoundParams(INT32 handle, UINT8 vol, UINT8 sep, UINT8 pitch)
+{
+ (void)handle;
+ (void)vol;
+ (void)sep;
+ (void)pitch;
+}
+
+/** \brief The I_SetSfxVolume function
+
+ \param volume volume to set at
+
+ \return void
+*/
+void I_SetSfxVolume(UINT8 volume)
+{
+ (void)volume;
+}
+
+/// ------------------------
+// MUSIC SYSTEM
+/// ------------------------
+
+/** \brief Init the music systems
+*/
+void I_InitMusic(void){}
+
+/** \brief Shutdown the music systems
+*/
+void I_ShutdownMusic(void){}
+
+/// ------------------------
+// MUSIC PROPERTIES
+/// ------------------------
+
+musictype_t I_SongType(void)
+{
+ return MU_NONE;
+}
+
+boolean I_SongPlaying(void)
+{
+ return false;
+}
+
+boolean I_SongPaused(void)
+{
+ return false;
+}
+
+/// ------------------------
+// MUSIC EFFECTS
+/// ------------------------
+
+boolean I_SetSongSpeed(float speed)
+{
+ (void)speed;
+ return false;
+}
+
+/// ------------------------
+// MUSIC SEEKING
+/// ------------------------
+
+UINT32 I_GetSongLength(void)
+{
+ return 0;
+}
+
+boolean I_SetSongLoopPoint(UINT32 looppoint)
+{
+ (void)looppoint;
+ return false;
+}
+
+UINT32 I_GetSongLoopPoint(void)
+{
+ return 0;
+}
+
+boolean I_SetSongPosition(UINT32 position)
+{
+ (void)position;
+ return false;
+}
+
+UINT32 I_GetSongPosition(void)
+{
+ return 0;
+}
+
+/// ------------------------
+// MUSIC PLAYBACK
+/// ------------------------
+
+/** \brief Registers a song handle to song data.
+
+ \param data pointer to song data
+ \param len len of data
+
+ \return song handle
+
+ \todo Remove this
+*/
+boolean I_LoadSong(char *data, size_t len)
+{
+ (void)data;
+ (void)len;
+ return false;
+}
+
+/** \brief See ::I_LoadSong, then think backwards
+
+ \param handle song handle
+
+ \sa I_LoadSong
+ \todo remove midi handle
+*/
+void I_UnloadSong(void){}
+
+/** \brief Called by anything that wishes to start music
+
+ \param handle Song handle
+ \param looping looping it if true
+
+ \return if true, it's playing the song
+
+ \todo pass music name, not handle
+*/
+boolean I_PlaySong(boolean looping)
+{
+ (void)looping;
+ return false;
+}
+
+/** \brief Stops a song over 3 seconds
+
+ \param handle Song handle
+ \return void
+
+ /todo drop handle
+*/
+void I_StopSong(void){}
+
+/** \brief PAUSE game handling.
+
+ \param handle song handle
+
+ \return void
+*/
+void I_PauseSong(void){}
+
+/** \brief RESUME game handling
+
+ \param handle song handle
+
+ \return void
+*/
+void I_ResumeSong(void){}
+
+/** \brief The I_SetMusicVolume function
+
+ \param volume volume to set at
+
+ \return void
+*/
+void I_SetMusicVolume(UINT8 volume)
+{
+ (void)volume;
+}
+
+boolean I_SetSongTrack(INT32 track)
+{
+ (void)track;
+ return false;
+}
+
+/// ------------------------
+/// MUSIC FADING
+/// ------------------------
+
+void I_SetInternalMusicVolume(UINT8 volume)
+{
+ (void)volume;
+}
+
+void I_StopFadingSong(void){}
+
+boolean I_FadeSongFromVolume(UINT8 target_volume, UINT8 source_volume, UINT32 ms, void (*callback)(void))
+{
+ (void)target_volume;
+ (void)source_volume;
+ (void)ms;
+ (void)callback;
+ return false;
+}
+
+boolean I_FadeSong(UINT8 target_volume, UINT32 ms, void (*callback)(void))
+{
+ (void)target_volume;
+ (void)ms;
+ (void)callback;
+ return false;
+}
+
+boolean I_FadeOutStopSong(UINT32 ms)
+{
+ (void)ms;
+ return false;
+}
+
+boolean I_FadeInPlaySong(UINT32 ms, boolean looping)
+{
+ (void)ms;
+ (void)looping;
+ return false;
+}
+
+void I_UpdateSongLagThreshold(void)
+{
+}
diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c
new file mode 100644
index 000000000..6ab748f86
--- /dev/null
+++ b/src/dedicated/i_system.c
@@ -0,0 +1,2223 @@
+// Emacs style mode select -*- C++ -*-
+//
+// SONIC ROBO BLAST 2
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) 1993-1996 by id Software, Inc.
+// Portions Copyright (C) 1998-2000 by DooM Legacy Team.
+// Copyright (C) 2014-2018 by Sonic Team Junior.
+//
+// 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; either version 2
+// of the License, or (at your option) any later version.
+//
+// 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.
+//
+// Changes by Graue are in the public domain.
+//
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief SRB2 system stuff for dedicated
+
+#ifdef CMAKECONFIG
+#include "config.h"
+#else
+#include "../config.h.in"
+#endif
+
+#include
+
+// A little more than the minimum sleep duration on Windows.
+// May be incorrect for other platforms, but we don't currently have a way to
+// query the scheduler granularity. SDL will do what's needed to make this as
+// low as possible though.
+#define MIN_SLEEP_DURATION_MS 2.1
+
+#ifdef _WIN32
+#define RPC_NO_WINDOWS_H
+#include
+#include "../doomtype.h"
+typedef BOOL (WINAPI *p_GetDiskFreeSpaceExA)(LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
+typedef BOOL (WINAPI *p_IsProcessorFeaturePresent) (DWORD);
+typedef DWORD (WINAPI *p_timeGetTime) (void);
+typedef UINT (WINAPI *p_timeEndPeriod) (UINT);
+typedef HANDLE (WINAPI *p_OpenFileMappingA) (DWORD, BOOL, LPCSTR);
+typedef LPVOID (WINAPI *p_MapViewOfFile) (HANDLE, DWORD, DWORD, DWORD, SIZE_T);
+#endif
+
+#include
+#include
+#include
+#ifdef __GNUC__
+#include
+#elif defined (_MSC_VER)
+#include
+#endif
+#if defined (__unix__) || defined (UNIXCOMMON)
+#include
+#endif
+
+#include
+#ifdef _WIN32
+#include
+#endif
+
+#ifdef _MSC_VER
+#pragma warning(disable : 4214 4244)
+#endif
+
+#if defined (__unix__) || defined(__APPLE__) || (defined (UNIXCOMMON) && !defined (__HAIKU__))
+#include
+#if defined (__linux__)
+#include
+#else
+#include
+#include
+/*For meminfo*/
+#include
+#ifdef FREEBSD
+#include
+#endif
+#include
+#include
+#endif
+#endif
+
+#if defined (__linux__) || (defined (UNIXCOMMON) && !defined (__HAIKU__))
+#ifndef NOTERMIOS
+#include
+#include // ioctl
+#define HAVE_TERMIOS
+#endif
+#endif
+
+#if defined (__unix__) || (defined (UNIXCOMMON) && !defined (__APPLE__))
+#include
+#include
+#include
+#define NEWSIGNALHANDLER
+#endif
+
+#ifndef NOMUMBLE
+#ifdef __linux__ // need -lrt
+#include
+#ifdef MAP_FAILED
+#define HAVE_SHM
+#endif
+#include
+#endif
+
+#ifdef _WIN32
+#define HAVE_MUMBLE
+#define WINMUMBLE
+#elif defined (HAVE_SHM)
+#define HAVE_MUMBLE
+#endif
+#endif // NOMUMBLE
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+#ifdef __APPLE__
+#include "macosx/mac_resources.h"
+#endif
+
+#ifndef errno
+#include
+#endif
+
+#include
+
+// Locations for searching the srb2.srb
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+#define DEFAULTWADLOCATION1 "/usr/local/share/games/SRB2Kart"
+#define DEFAULTWADLOCATION2 "/usr/local/games/SRB2Kart"
+#define DEFAULTWADLOCATION3 "/usr/share/games/SRB2Kart"
+#define DEFAULTWADLOCATION4 "/usr/games/SRB2Kart"
+#define DEFAULTSEARCHPATH1 "/usr/local/games"
+#define DEFAULTSEARCHPATH2 "/usr/games"
+#define DEFAULTSEARCHPATH3 "/usr/local"
+#endif
+
+/** \brief WAD file to look for
+*/
+#define WADKEYWORD1 "srb2.srb"
+#define WADKEYWORD2 "srb2.wad"
+/** \brief holds wad path
+*/
+static char returnWadPath[256];
+
+#include "../doomdef.h"
+#include "../m_misc.h"
+#include "../i_video.h"
+#include "../i_sound.h"
+#include "../i_system.h"
+#include "../screen.h" //vid.WndParent
+#include "../d_net.h"
+#include "../g_game.h"
+#include "../filesrch.h"
+#include "../z_zone.h" // Z_Free
+#include "endtxt.h"
+
+#include "../i_joy.h"
+
+#include "../m_argv.h"
+
+#ifdef MAC_ALERT
+#include "macosx/mac_alert.h"
+#endif
+
+#include "../d_main.h"
+
+#if !defined(NOMUMBLE) && defined(HAVE_MUMBLE)
+// Mumble context string
+#include "../d_clisrv.h"
+#include "../byteptr.h"
+#endif
+
+#ifdef HAVE_LIBBACKTRACE
+#include
+// TODO - move this to some header file instead
+extern struct backtrace_state *bt_state;
+
+typedef struct bt_crash_reason_s {
+ enum {
+ BTCRASH_SIGNAL,
+ BTCRASH_ERRORMSG,
+ } type;
+
+ union {
+ INT32 signal;
+ const char *errormsg;
+ } value;
+} bt_crash_reason_t;
+
+#define BT_CRASH_REASON_SIGNAL(num) (bt_crash_reason_t){ .type = BTCRASH_SIGNAL, .value = { .signal = num } }
+#define BT_CRASH_REASON_ERRORMSG(msg) (bt_crash_reason_t){ .type = BTCRASH_ERRORMSG, .value = { .errormsg = msg } }
+
+static void printsignal(FILE *fp, INT32 num)
+{
+ switch (num)
+ {
+ case SIGILL:
+ fprintf(fp, "SIGILL - illegal instruction - invalid function image");
+ break;
+ case SIGFPE:
+ fprintf(fp, "SIGFPE - mathematical exception");
+ break;
+ case SIGSEGV:
+ fprintf(fp, "SIGSEGV - segment violation");
+ break;
+ case SIGABRT:
+ fprintf(fp, "SIGABRT - abnormal termination triggered by abort call");
+ break;
+ default:
+ fprintf(fp, "Signal number %d", num);
+ }
+}
+
+typedef struct bt_out_buf_s {
+ boolean error;
+ char *pos;
+ size_t size;
+} bt_out_buf_t;
+
+static void bt_syminfo_cb(void *data, uintptr_t pc, const char *symname, uintptr_t symval, uintptr_t symsize)
+{
+ (void)symval;
+ (void)symsize;
+
+ bt_out_buf_t *buf = (bt_out_buf_t*)data;
+
+ if (!symname)
+ symname = "???";
+
+ int n = snprintf(buf->pos, buf->size, "%p %s\n", (void*)pc, symname);
+
+ if (n <= 0)
+ {
+ buf->size = 0;
+ return;
+ }
+
+ buf->pos += n;
+ buf->size -= n;
+}
+
+static int bt_simple_cb(void *data, uintptr_t pc)
+{
+ bt_out_buf_t *buf = (bt_out_buf_t*)data;
+
+ backtrace_syminfo(bt_state, pc, bt_syminfo_cb, NULL, data);
+
+ if (!buf->size) return 1;
+
+ return 0;
+}
+
+static int bt_full_cb(void *data, uintptr_t pc, const char *filename, int lineno, const char *function)
+{
+ bt_out_buf_t *buf = (bt_out_buf_t*)data;
+
+ if (!filename) filename = "???";
+ if (!function) function = "???";
+
+ int n = snprintf(buf->pos, buf->size, "%p %s\n\t%s:%d\n", (void*)pc, function, filename, lineno);
+
+ if (n <= 0) return 1;
+
+ buf->pos += n;
+ buf->size -= n;
+
+ if (!buf->size) return 1;
+
+ return 0;
+}
+
+static void bt_error_cb(void *data, const char *msg, int errnum)
+{
+ (void)msg; // We don't need this
+
+ bt_out_buf_t *buf = (bt_out_buf_t*)data;
+
+ // No debug info
+ if (errnum == -1)
+ buf->error = true;
+}
+
+static void write_backtrace(bt_crash_reason_t reason)
+{
+ FILE *out = fopen(va("%s" PATHSEP "%s", srb2home, "srb2kart-crash-log.txt"), "a");
+
+ time_t rawtime;
+ struct tm *timeinfo;
+
+ const size_t BUFSIZE = 8192;
+ char backtrace[BUFSIZE];
+
+ bt_out_buf_t buf;
+ buf.error = false;
+ buf.pos = backtrace;
+ buf.size = BUFSIZE;
+
+
+ if (!out)
+ {
+ fprintf(stderr, "\nWARNING: Couldn't open crash log for writing! Make sure your permissions are correct. Please save the below report!\n");
+ out = stderr;
+ }
+
+ // Get the current time as a string.
+ time(&rawtime);
+ timeinfo = localtime(&rawtime);
+
+ fprintf(out, "------------------------\n\n");
+
+ fprintf(out, "Program name: %s %s\n", SRB2APPLICATION, VERSIONSTRING);
+
+ if (compdate && comptime && comprevision && compbranch)
+ fprintf(out, "Compiled: %s %s, commit %s, branch %s\n", compdate, comptime, comprevision, compbranch);
+
+ if (gamestate == GS_LEVEL)
+ {
+ char *title = G_BuildMapTitle(gamemap);
+
+ if (title)
+ {
+ fprintf(out, "Game map: %s (%s)\n", title, G_BuildMapName(gamemap));
+ Z_Free(title);
+ }
+ else
+ fprintf(out, "Game map: %s\n", G_BuildMapName(gamemap));
+ }
+
+ fprintf(out, "Time of crash: %s\n", asctime(timeinfo));
+
+ fprintf(out, "Caused by: ");
+
+ switch (reason.type)
+ {
+ case BTCRASH_SIGNAL:
+ printsignal(out, reason.value.signal);
+ break;
+
+ case BTCRASH_ERRORMSG:
+ fprintf(out, "%s", reason.value.errormsg);
+ break;
+ }
+
+ fprintf(out, "\nBacktrace:\n");
+
+ // Try to get full backtrace, it will print files and line numbers
+ backtrace_full(bt_state, 2, bt_full_cb, bt_error_cb, (void*)&buf);
+
+ if (buf.error)
+ {
+ // Fall back to simple backtrace, only prints function names
+ backtrace_simple(bt_state, 2, bt_simple_cb, NULL, (void*)&buf);
+ }
+
+ fputs(backtrace, out);
+
+ if (out != stderr)
+ {
+ fclose(out);
+ fprintf(stderr, "Crash report created, find srb2kart-crash-log.txt in your SRB2Kart directory\n");
+ }
+}
+
+#endif
+
+boolean consolevent = false;
+boolean framebuffer = false;
+
+boolean g_in_exiting_signal_handler = false;
+
+UINT8 keyboard_started = false;
+
+static void I_ReportSignal(int num, int coredumped)
+{
+ //static char msg[] = "oh no! back to reality!\r\n";
+ const char * sigmsg;
+ char msg[256];
+
+ switch (num)
+ {
+// case SIGINT:
+// sigmsg = "SIGINT - interrupted";
+// break;
+ case SIGILL:
+ sigmsg = "SIGILL - illegal instruction - invalid function image";
+ break;
+ case SIGFPE:
+ sigmsg = "SIGFPE - mathematical exception";
+ break;
+ case SIGSEGV:
+ sigmsg = "SIGSEGV - segment violation";
+ break;
+// case SIGTERM:
+// sigmsg = "SIGTERM - Software termination signal from kill";
+// break;
+// case SIGBREAK:
+// sigmsg = "SIGBREAK - Ctrl-Break sequence";
+// break;
+ case SIGABRT:
+ sigmsg = "SIGABRT - abnormal termination triggered by abort call";
+ break;
+ default:
+ sprintf(msg,"signal number %d", num);
+ if (coredumped)
+ sigmsg = 0;
+ else
+ sigmsg = msg;
+ }
+
+ if (coredumped)
+ {
+ if (sigmsg)
+ sprintf(msg, "%s (core dumped)", sigmsg);
+ else
+ strcat(msg, " (core dumped)");
+ }
+ else
+ {
+ sprintf(msg, "%s", sigmsg);
+ }
+
+#ifdef HAVE_LIBBACKTRACE
+ strncat(msg, "\n\nCrash report has been saved into srb2kart-crash-log.txt", 255);
+#elif defined(_WIN32) && !defined(__MINGW64__)
+ strncat(msg, "\n\nCrash report has been saved into srb2kart.rpt", 255);
+#endif
+
+ I_OutputMsg("\nProcess killed by signal: %s\n\n", sigmsg);
+}
+
+#ifndef NEWSIGNALHANDLER
+FUNCNORETURN static ATTRNORETURN void signal_handler(INT32 num)
+{
+ g_in_exiting_signal_handler = true;
+
+ D_QuitNetGame(); // Fix server freezes
+
+#ifdef HAVE_LIBBACKTRACE
+ write_backtrace(BT_CRASH_REASON_SIGNAL(num));
+#endif
+
+ if (demo.recording)
+ G_SaveDemo();
+
+ I_ReportSignal(num, 0);
+ I_ShutdownSystem();
+ signal(num, SIG_DFL); //default signal action
+ raise(num);
+ I_Quit();
+}
+#endif
+
+FUNCNORETURN static ATTRNORETURN void quit_handler(int num)
+{
+ signal(num, SIG_DFL); //default signal action
+ raise(num);
+ I_Quit();
+}
+
+#ifdef HAVE_TERMIOS
+// TERMIOS console code from Quake3: thank you!
+boolean stdin_active = true;
+
+typedef struct
+{
+ size_t cursor;
+ char buffer[256];
+} feild_t;
+
+feild_t tty_con;
+
+// lock to prevent clearing partial lines, since not everything
+// printed ends on a newline.
+static boolean ttycon_ateol = true;
+// some key codes that the terminal may be using
+// TTimo NOTE: I'm not sure how relevant this is
+static INT32 tty_erase;
+static INT32 tty_eof;
+
+static struct termios tty_tc;
+
+// =============================================================
+// tty console routines
+// NOTE: if the user is editing a line when something gets printed to the early console then it won't look good
+// so we provide tty_Clear and tty_Show to be called before and after a stdout or stderr output
+// =============================================================
+
+// flush stdin, I suspect some terminals are sending a LOT of garbage
+// FIXME TTimo relevant?
+#if 0
+static inline void tty_FlushIn(void)
+{
+ char key;
+ while (read(STDIN_FILENO, &key, 1)!=-1);
+}
+#endif
+
+// do a backspace
+// TTimo NOTE: it seems on some terminals just sending '\b' is not enough
+// so for now, in any case we send "\b \b" .. yeah well ..
+// (there may be a way to find out if '\b' alone would work though)
+// Hanicef NOTE: using \b this way is unreliable because of terminal state,
+// it's better to use \r to reset the cursor to the beginning of the
+// line and clear from there.
+static void tty_Back(void)
+{
+ write(STDOUT_FILENO, "\r", 1);
+ if (tty_con.cursor>0)
+ {
+ write(STDOUT_FILENO, tty_con.buffer, tty_con.cursor);
+ }
+ write(STDOUT_FILENO, " \b", 2);
+}
+
+static void tty_Clear(void)
+{
+ size_t i;
+ write(STDOUT_FILENO, "\r", 1);
+ if (tty_con.cursor>0)
+ {
+ for (i=0; i 0)
+ {
+ tty_con.cursor--;
+ tty_con.buffer[tty_con.cursor] = '\0';
+ tty_Back();
+ }
+ ev.data1 = KEY_BACKSPACE;
+ }
+ else if (key < ' ') // check if this is a control char
+ {
+ if (key == '\n')
+ {
+ tty_Clear();
+ tty_con.cursor = 0;
+ ev.data1 = KEY_ENTER;
+ }
+ else if (key == 0x4) // ^D, aka EOF
+ {
+ // shut down, most unix programs behave this way
+ I_Quit();
+ }
+ else continue;
+ }
+ else if (tty_con.cursor < sizeof(tty_con.buffer))
+ {
+ // push regular character
+ ev.data1 = tty_con.buffer[tty_con.cursor] = key;
+ tty_con.cursor++;
+ // print the current line (this is differential)
+ write(STDOUT_FILENO, &key, 1);
+ }
+ if (ev.data1) D_PostEvent(&ev);
+ }
+}
+
+#elif defined (_WIN32)
+static BOOL I_ReadyConsole(HANDLE ci)
+{
+ DWORD gotinput;
+ if (ci == INVALID_HANDLE_VALUE) return FALSE;
+ if (WaitForSingleObject(ci,0) != WAIT_OBJECT_0) return FALSE;
+ if (GetFileType(ci) != FILE_TYPE_CHAR) return FALSE;
+ if (!GetConsoleMode(ci, &gotinput)) return FALSE;
+ return (GetNumberOfConsoleInputEvents(ci, &gotinput) && gotinput);
+}
+
+static boolean entering_con_command = false;
+
+static void Impl_HandleKeyboardConsoleEvent(KEY_EVENT_RECORD evt, HANDLE co)
+{
+ event_t event;
+ CONSOLE_SCREEN_BUFFER_INFO CSBI;
+ DWORD t;
+
+ memset(&event,0x00,sizeof (event));
+
+ if (evt.bKeyDown)
+ {
+ event.type = ev_console;
+ entering_con_command = true;
+ switch (evt.wVirtualKeyCode)
+ {
+ case VK_ESCAPE:
+ case VK_TAB:
+ event.data1 = KEY_NULL;
+ break;
+ case VK_RETURN:
+ entering_con_command = false;
+ // Fall through.
+ default:
+ //event.data1 = MapVirtualKey(evt.wVirtualKeyCode,2); // convert in to char
+ event.data1 = evt.uChar.AsciiChar;
+ }
+ if (co != INVALID_HANDLE_VALUE && GetFileType(co) == FILE_TYPE_CHAR && GetConsoleMode(co, &t))
+ {
+ if (event.data1 && event.data1 != KEY_LSHIFT && event.data1 != KEY_RSHIFT)
+ {
+#ifdef _UNICODE
+ WriteConsole(co, &evt.uChar.UnicodeChar, 1, &t, NULL);
+#else
+ WriteConsole(co, &evt.uChar.AsciiChar, 1 , &t, NULL);
+#endif
+ }
+ if (evt.wVirtualKeyCode == VK_BACK
+ && GetConsoleScreenBufferInfo(co,&CSBI))
+ {
+ WriteConsoleOutputCharacterA(co, " ",1, CSBI.dwCursorPosition, &t);
+ }
+ }
+ }
+ if (event.data1) D_PostEvent(&event);
+}
+
+void I_GetConsoleEvents(void)
+{
+ HANDLE ci = GetStdHandle(STD_INPUT_HANDLE);
+ HANDLE co = GetStdHandle(STD_OUTPUT_HANDLE);
+ INPUT_RECORD input;
+ DWORD t;
+
+ while (I_ReadyConsole(ci) && ReadConsoleInput(ci, &input, 1, &t) && t)
+ {
+ switch (input.EventType)
+ {
+ case KEY_EVENT:
+ Impl_HandleKeyboardConsoleEvent(input.Event.KeyEvent, co);
+ break;
+ case MOUSE_EVENT:
+ case WINDOW_BUFFER_SIZE_EVENT:
+ case MENU_EVENT:
+ case FOCUS_EVENT:
+ break;
+ }
+ }
+}
+
+static void I_StartupConsole(void)
+{
+ HANDLE ci, co;
+ const INT32 ded = M_CheckParm("-dedicated");
+ BOOL gotConsole = FALSE;
+ if (M_CheckParm("-console") || ded)
+ gotConsole = AllocConsole();
+#ifdef _DEBUG
+ else if (M_CheckParm("-noconsole") && !ded)
+#else
+ else if (!M_CheckParm("-console") && !ded)
+#endif
+ {
+ FreeConsole();
+ gotConsole = FALSE;
+ }
+
+ if (gotConsole)
+ {
+ SetConsoleTitleA("SRB2Kart Console");
+ consolevent = true;
+ }
+
+ //Let get the real console HANDLE, because Mingw's Bash is bad!
+ ci = CreateFile(TEXT("CONIN$") , GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ co = CreateFile(TEXT("CONOUT$"), GENERIC_WRITE|GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (ci != INVALID_HANDLE_VALUE)
+ {
+ const DWORD CM = ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT;
+ SetStdHandle(STD_INPUT_HANDLE, ci);
+ if (GetFileType(ci) == FILE_TYPE_CHAR)
+ SetConsoleMode(ci, CM); //default mode but no ENABLE_MOUSE_INPUT
+ }
+ if (co != INVALID_HANDLE_VALUE)
+ {
+ SetStdHandle(STD_OUTPUT_HANDLE, co);
+ SetStdHandle(STD_ERROR_HANDLE, co);
+ }
+}
+static inline void I_ShutdownConsole(void){}
+#else
+void I_GetConsoleEvents(void){}
+static inline void I_StartupConsole(void)
+{
+#ifdef _DEBUG
+ consolevent = !M_CheckParm("-noconsole");
+#else
+ consolevent = M_CheckParm("-console");
+#endif
+
+ framebuffer = M_CheckParm("-framebuffer");
+
+ if (framebuffer)
+ consolevent = false;
+}
+static inline void I_ShutdownConsole(void){}
+#endif
+
+//
+// StartupKeyboard
+//
+static void I_RegisterSignals (void)
+{
+#ifdef SIGINT
+ signal(SIGINT , quit_handler);
+#endif
+#ifdef SIGBREAK
+ signal(SIGBREAK , quit_handler);
+#endif
+#ifdef SIGTERM
+ signal(SIGTERM , quit_handler);
+#endif
+
+ // If these defines don't exist,
+ // then compilation would have failed above us...
+#ifndef NEWSIGNALHANDLER
+ signal(SIGILL , signal_handler);
+ signal(SIGSEGV , signal_handler);
+ signal(SIGABRT , signal_handler);
+ signal(SIGFPE , signal_handler);
+#endif
+}
+
+#ifdef NEWSIGNALHANDLER
+static void signal_handler_child(INT32 num)
+{
+#ifdef HAVE_LIBBACKTRACE
+ write_backtrace(BT_CRASH_REASON_SIGNAL(num));
+#endif
+
+ if (demo.recording)
+ G_SaveDemo();
+
+ signal(num, SIG_DFL); //default signal action
+ raise(num);
+}
+
+static void I_RegisterChildSignals(void)
+{
+ // If these defines don't exist,
+ // then compilation would have failed above us...
+ signal(SIGILL , signal_handler_child);
+ signal(SIGSEGV , signal_handler_child);
+ signal(SIGABRT , signal_handler_child);
+ signal(SIGFPE , signal_handler_child);
+}
+#endif
+
+//
+//I_OutputMsg
+//
+void I_OutputMsg(const char *fmt, ...)
+{
+ size_t len;
+ char *txt;
+ va_list argptr;
+
+ va_start(argptr,fmt);
+ len = vsnprintf(NULL, 0, fmt, argptr);
+ va_end(argptr);
+ if (len == 0)
+ return;
+
+ txt = malloc(len+1);
+ va_start(argptr,fmt);
+ vsprintf(txt, fmt, argptr);
+ va_end(argptr);
+
+#ifdef HAVE_TTF
+ if (TTF_WasInit()) I_TTFDrawText(currentfont, solid, DEFAULTFONTFGR, DEFAULTFONTFGG, DEFAULTFONTFGB, DEFAULTFONTFGA,
+ DEFAULTFONTBGR, DEFAULTFONTBGG, DEFAULTFONTBGB, DEFAULTFONTBGA, txt);
+#endif
+
+#if defined (_WIN32) && defined (_MSC_VER)
+ OutputDebugStringA(txt);
+#endif
+
+ len = strlen(txt);
+
+#ifdef LOGMESSAGES
+ if (logstream)
+ {
+ size_t d = fwrite(txt, len, 1, logstream);
+ fflush(logstream);
+ (void)d;
+ }
+#endif
+
+#if defined (_WIN32)
+#ifdef DEBUGFILE
+ if (debugfile != stderr)
+#endif
+ {
+ HANDLE co = GetStdHandle(STD_OUTPUT_HANDLE);
+ DWORD bytesWritten;
+
+ if (co == INVALID_HANDLE_VALUE)
+ {
+ free(txt);
+ return;
+ }
+
+ if (GetFileType(co) == FILE_TYPE_CHAR && GetConsoleMode(co, &bytesWritten))
+ {
+ static COORD coordNextWrite = {0,0};
+ LPVOID oldLines = NULL;
+ INT oldLength;
+ CONSOLE_SCREEN_BUFFER_INFO csbi;
+
+ // Save the lines that we're going to obliterate.
+ GetConsoleScreenBufferInfo(co, &csbi);
+ oldLength = csbi.dwSize.X * (csbi.dwCursorPosition.Y - coordNextWrite.Y) + csbi.dwCursorPosition.X - coordNextWrite.X;
+
+ if (oldLength > 0)
+ {
+ LPVOID blank = malloc(oldLength);
+ if (!blank)
+ {
+ free(txt);
+ return;
+ }
+ memset(blank, ' ', oldLength); // Blank out.
+ oldLines = malloc(oldLength*sizeof(TCHAR));
+ if (!oldLines)
+ {
+ free(txt);
+ free(blank);
+ return;
+ }
+
+ ReadConsoleOutputCharacter(co, oldLines, oldLength, coordNextWrite, &bytesWritten);
+
+ // Move to where we what to print - which is where we would've been,
+ // had console input not been in the way,
+ SetConsoleCursorPosition(co, coordNextWrite);
+
+ WriteConsoleA(co, blank, oldLength, &bytesWritten, NULL);
+ free(blank);
+
+ // And back to where we want to print again.
+ SetConsoleCursorPosition(co, coordNextWrite);
+ }
+
+ // Actually write the string now!
+ WriteConsoleA(co, txt, (DWORD)len, &bytesWritten, NULL);
+
+ // Next time, output where we left off.
+ GetConsoleScreenBufferInfo(co, &csbi);
+ coordNextWrite = csbi.dwCursorPosition;
+
+ // Restore what was overwritten.
+ if (oldLines && entering_con_command)
+ WriteConsole(co, oldLines, oldLength, &bytesWritten, NULL);
+ if (oldLines) free(oldLines);
+ }
+ else // Redirected to a file.
+ WriteFile(co, txt, (DWORD)len, &bytesWritten, NULL);
+ }
+#else
+#ifdef HAVE_TERMIOS
+ if (consolevent && ttycon_ateol)
+ {
+ tty_Clear();
+ ttycon_ateol = false;
+ }
+#endif
+
+ if (!framebuffer)
+ fprintf(stderr, "%s", txt);
+#ifdef HAVE_TERMIOS
+ if (consolevent && txt[len-1] == '\n')
+ {
+ write(STDOUT_FILENO, tty_con.buffer, tty_con.cursor);
+ ttycon_ateol = true;
+ }
+#endif
+
+ // 2004-03-03 AJR Since not all messages end in newline, some were getting displayed late.
+ if (!framebuffer)
+ fflush(stderr);
+
+#endif
+ free(txt);
+}
+
+//
+// I_GetKey
+//
+INT32 I_GetKey (void)
+{
+ // Warning: I_GetKey empties the event queue till next keypress
+ event_t *ev;
+ INT32 rc = 0;
+
+ // return the first keypress from the event queue
+ for (; eventtail != eventhead; eventtail = (eventtail+1)&(MAXEVENTS-1))
+ {
+ ev = &events[eventtail];
+ if (ev->type == ev_keydown || ev->type == ev_console)
+ {
+ rc = ev->data1;
+ continue;
+ }
+ }
+
+ return rc;
+}
+
+//
+// I_JoyScale
+//
+void I_JoyScale(void)
+{
+}
+
+void I_JoyScale2(void)
+{
+}
+
+void I_JoyScale3(void)
+{
+}
+
+void I_JoyScale4(void)
+{
+}
+
+/** \brief Shuts down joystick 1
+
+
+ \return void
+
+
+*/
+void I_ShutdownJoystick(void)
+{
+}
+
+void I_GetJoystickEvents(UINT8 index)
+{
+ (void)index;
+}
+
+//
+// I_InitJoystick
+//
+void I_InitJoystick(UINT8 index)
+{
+ (void)index;
+}
+
+void I_InitJoystick1(void)
+{
+}
+
+void I_InitJoystick2(void)
+{
+}
+
+void I_InitJoystick3(void)
+{
+}
+
+void I_InitJoystick4(void)
+{
+}
+
+INT32 I_NumJoys(void)
+{
+ return 0;
+}
+
+const char *I_GetJoyName(INT32 joyindex)
+{
+ (void)joyindex;
+ return NULL;
+}
+
+void I_GamepadRumble(INT32 playernum, UINT16 low_strength, UINT16 high_strength, UINT32 duration)
+{
+ (void)playernum;
+ (void)low_strength;
+ (void)high_strength;
+ (void)duration;
+}
+
+void I_SetGamepadIndicatorColor(INT32 playernum, UINT8 red, UINT8 green, UINT8 blue)
+{
+ (void)playernum;
+ (void)red;
+ (void)green;
+ (void)blue;
+}
+
+#ifndef NOMUMBLE
+#ifdef HAVE_MUMBLE
+// Best Mumble positional audio settings:
+// Minimum distance 3.0 m
+// Bloom 175%
+// Maximum distance 80.0 m
+// Minimum volume 50%
+#define DEG2RAD (0.017453292519943295769236907684883l) // TAU/360 or PI/180
+#define MUMBLEUNIT (64.0f) // FRACUNITS in a Meter
+
+static struct {
+#ifdef WINMUMBLE
+ UINT32 uiVersion;
+ DWORD uiTick;
+#else
+ UINT32 uiVersion;
+ UINT32 uiTick;
+#endif
+ float fAvatarPosition[3];
+ float fAvatarFront[3];
+ float fAvatarTop[3]; // defaults to Y-is-up (only used for leaning)
+ wchar_t name[256]; // game name
+ float fCameraPosition[3];
+ float fCameraFront[3];
+ float fCameraTop[3]; // defaults to Y-is-up (only used for leaning)
+ wchar_t identity[256]; // player id
+#ifdef WINMUMBLE
+ UINT32 context_len;
+#else
+ UINT32 context_len;
+#endif
+ unsigned char context[256]; // server/team
+ wchar_t description[2048]; // game description
+} *mumble = NULL;
+#endif // HAVE_MUMBLE
+
+static void I_SetupMumble(void)
+{
+#ifdef WINMUMBLE
+ HANDLE hMap = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, L"MumbleLink");
+ if (!hMap)
+ return;
+
+ mumble = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(*mumble));
+ if (!mumble)
+ CloseHandle(hMap);
+#elif defined (HAVE_SHM)
+ int shmfd;
+ char memname[256];
+
+ snprintf(memname, 256, "/MumbleLink.%d", getuid());
+ shmfd = shm_open(memname, O_RDWR, S_IRUSR | S_IWUSR);
+
+ if(shmfd < 0)
+ return;
+
+ mumble = mmap(NULL, sizeof(*mumble), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
+ if (mumble == MAP_FAILED)
+ mumble = NULL;
+#endif
+}
+
+void I_UpdateMumble(const mobj_t *mobj, const listener_t listener)
+{
+#ifdef HAVE_MUMBLE
+ double angle;
+ fixed_t anglef;
+
+ if (!mumble)
+ return;
+
+ if (mumble->uiVersion != 2) {
+ wcsncpy(mumble->name, L"SRB2Kart "VERSIONSTRINGW, 256);
+ wcsncpy(mumble->description, L"Sonic Robo Blast 2 Kart with integrated Mumble Link support.", 2048);
+ mumble->uiVersion = 2;
+ }
+ mumble->uiTick++;
+
+ if (!netgame || gamestate != GS_LEVEL) { // Zero out, but never delink.
+ mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f;
+ mumble->fAvatarFront[0] = 1.0f;
+ mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f;
+ mumble->fCameraPosition[0] = mumble->fCameraPosition[1] = mumble->fCameraPosition[2] = 0.0f;
+ mumble->fCameraFront[0] = 1.0f;
+ mumble->fCameraFront[1] = mumble->fCameraFront[2] = 0.0f;
+ return;
+ }
+
+ {
+ UINT8 *p = mumble->context;
+ WRITEMEM(p, server_context, 8);
+ WRITEINT16(p, gamemap);
+ mumble->context_len = (UINT32)(p - mumble->context);
+ }
+
+ if (mobj) {
+ mumble->fAvatarPosition[0] = FIXED_TO_FLOAT(mobj->x) / MUMBLEUNIT;
+ mumble->fAvatarPosition[1] = FIXED_TO_FLOAT(mobj->z) / MUMBLEUNIT;
+ mumble->fAvatarPosition[2] = FIXED_TO_FLOAT(mobj->y) / MUMBLEUNIT;
+
+ anglef = AngleFixed(mobj->angle);
+ angle = FIXED_TO_FLOAT(anglef)*DEG2RAD;
+ mumble->fAvatarFront[0] = (float)cos(angle);
+ mumble->fAvatarFront[1] = 0.0f;
+ mumble->fAvatarFront[2] = (float)sin(angle);
+ } else {
+ mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f;
+ mumble->fAvatarFront[0] = 1.0f;
+ mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f;
+ }
+
+ mumble->fCameraPosition[0] = FIXED_TO_FLOAT(listener.x) / MUMBLEUNIT;
+ mumble->fCameraPosition[1] = FIXED_TO_FLOAT(listener.z) / MUMBLEUNIT;
+ mumble->fCameraPosition[2] = FIXED_TO_FLOAT(listener.y) / MUMBLEUNIT;
+
+ anglef = AngleFixed(listener.angle);
+ angle = FIXED_TO_FLOAT(anglef)*DEG2RAD;
+ mumble->fCameraFront[0] = (float)cos(angle);
+ mumble->fCameraFront[1] = 0.0f;
+ mumble->fCameraFront[2] = (float)sin(angle);
+#else
+ (void)mobj;
+ (void)listener;
+#endif // HAVE_MUMBLE
+}
+#undef WINMUMBLE
+#endif // NOMUMBLE
+
+
+/** \brief empty ticcmd for player 1
+*/
+static ticcmd_t emptycmd;
+
+ticcmd_t *I_BaseTiccmd(void)
+{
+ return &emptycmd;
+}
+
+/** \brief empty ticcmd for player 2
+*/
+static ticcmd_t emptycmd2;
+
+ticcmd_t *I_BaseTiccmd2(void)
+{
+ return &emptycmd2;
+}
+
+/** \brief empty ticcmd for player 3
+ */
+static ticcmd_t emptycmd3;
+
+ticcmd_t *I_BaseTiccmd3(void)
+{
+ return &emptycmd3;
+}
+
+/** \brief empty ticcmd for player 4
+ */
+static ticcmd_t emptycmd4;
+
+ticcmd_t *I_BaseTiccmd4(void)
+{
+ return &emptycmd4;
+}
+
+//
+// I_GetTime
+// returns time in 1/TICRATE second tics
+//
+
+precise_t I_GetPreciseTime(void)
+{
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (precise_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
+#elif defined (_WIN32)
+ LARGE_INTEGER counter;
+ QueryPerformanceCounter(&counter);
+ return (precise_t)counter.QuadPart;
+#else
+ return 0;
+#endif
+}
+
+UINT64 I_GetPrecisePrecision(void)
+{
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+ return 1000000000;
+#elif defined (_WIN32)
+ LARGE_INTEGER frequency;
+ QueryPerformanceFrequency(&frequency);
+ return (UINT64)frequency.QuadPart;
+#else
+ return 1000000;
+#endif
+}
+
+void I_StartupTimer(void){}
+
+void I_Sleep(UINT32 ms)
+{
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+ struct timespec ts = {
+ .tv_sec = ms / 1000,
+ .tv_nsec = ms % 1000 * 1000000,
+ };
+ int status;
+ do status = clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts);
+ while (status == EINTR);
+#elif defined (_WIN32)
+ Sleep(ms);
+#else
+ (void)ms;
+#warning No sleep function for this system!
+#endif
+}
+
+void I_SleepDuration(precise_t duration)
+{
+#if defined(__linux__) || defined(__FreeBSD__) || defined(__HAIKU__)
+ UINT64 precision = I_GetPrecisePrecision();
+ struct timespec ts = {
+ .tv_sec = duration / precision,
+ .tv_nsec = duration * 1000000000 / precision % 1000000000,
+ };
+ int status;
+ do status = clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &ts);
+ while (status == EINTR);
+#elif defined (MIN_SLEEP_DURATION_MS)
+ UINT64 precision = I_GetPrecisePrecision();
+ INT32 sleepvalue = cv_sleep.value;
+ UINT64 delaygranularity;
+ precise_t cur;
+ precise_t dest;
+
+ {
+ double gran = round(((double)(precision / 1000) * sleepvalue * MIN_SLEEP_DURATION_MS));
+ delaygranularity = (UINT64)gran;
+ }
+
+ cur = I_GetPreciseTime();
+ dest = cur + duration;
+
+ // the reason this is not dest > cur is because the precise counter may wrap
+ // two's complement arithmetic is our friend here, though!
+ // e.g. cur 0xFFFFFFFFFFFFFFFE = -2, dest 0x0000000000000001 = 1
+ // 0x0000000000000001 - 0xFFFFFFFFFFFFFFFE = 3
+ while ((INT64)(dest - cur) > 0)
+ {
+ // If our cv_sleep value exceeds the remaining sleep duration, use the
+ // hard sleep function.
+ if (sleepvalue > 0 && (dest - cur) > delaygranularity)
+ {
+ I_Sleep(sleepvalue);
+ }
+
+ // Otherwise, this is a spinloop.
+
+ cur = I_GetPreciseTime();
+ }
+#endif
+}
+
+#ifdef NEWSIGNALHANDLER
+FUNCNORETURN static ATTRNORETURN void newsignalhandler_Warn(const char *pr)
+{
+ char text[128];
+
+ snprintf(text, sizeof text,
+ "Error while setting up signal reporting: %s: %s",
+ pr,
+ strerror(errno)
+ );
+
+ I_OutputMsg("%s\n", text);
+
+ I_ShutdownConsole();
+ exit(-1);
+}
+
+static void I_Fork(void)
+{
+ int child;
+ int status;
+ int signum;
+ int c;
+
+ child = fork();
+
+ switch (child)
+ {
+ case -1:
+ newsignalhandler_Warn("fork()");
+ break;
+ case 0:
+ I_RegisterChildSignals();
+ break;
+ default:
+ if (logstream)
+ fclose(logstream);/* the child has this */
+
+ c = wait(&status);
+
+#ifdef LOGMESSAGES
+ /* By the way, exit closes files. */
+ logstream = fopen(logfilename, "at");
+#else
+ logstream = 0;
+#endif
+
+ if (c == -1)
+ {
+ kill(child, SIGKILL);
+ newsignalhandler_Warn("wait()");
+ }
+ else
+ {
+ if (WIFSIGNALED (status))
+ {
+ signum = WTERMSIG (status);
+#ifdef WCOREDUMP
+ I_ReportSignal(signum, WCOREDUMP (status));
+#else
+ I_ReportSignal(signum, 0);
+#endif
+ status = 128 + signum;
+ }
+ else if (WIFEXITED (status))
+ {
+ status = WEXITSTATUS (status);
+ }
+
+ I_ShutdownConsole();
+ exit(status);
+ }
+ }
+}
+#endif/*NEWSIGNALHANDLER*/
+
+INT32 I_StartupSystem(void)
+{
+ I_StartupConsole();
+#ifdef NEWSIGNALHANDLER
+ // This is useful when debugging. It lets GDB attach to
+ // the correct process easily.
+ if (!M_CheckParm("-nofork"))
+ I_Fork();
+#endif
+#ifdef HAVE_THREADS
+ I_start_threads();
+ I_AddExitFunc(I_stop_threads);
+#endif
+ I_RegisterSignals();
+#ifndef NOMUMBLE
+ I_SetupMumble();
+#endif
+ return 0;
+}
+
+//
+// I_Quit
+//
+void I_Quit(void)
+{
+ static boolean quiting = false;
+
+ /* prevent recursive I_Quit() */
+ if (quiting) goto death;
+ quiting = false;
+ I_ShutdownConsole();
+ M_SaveConfig(NULL); //save game config, cvars..
+#ifndef NONET
+ D_SaveBan(); // save the ban list
+#endif
+ G_SaveGameData(false); // Tails 12-08-2002
+ //added:16-02-98: when recording a demo, should exit using 'q' key,
+ // but sometimes we forget and use 'F10'.. so save here too.
+
+ if (demo.recording)
+ G_CheckDemoStatus();
+ if (metalrecording)
+ G_StopMetalRecording();
+
+ D_QuitNetGame();
+ I_ShutdownMusic();
+ I_ShutdownSound();
+ // use this for 1.28 19990220 by Kin
+ I_ShutdownGraphics();
+ I_ShutdownSystem();
+ /* if option -noendtxt is set, don't print the text */
+ if (!M_CheckParm("-noendtxt") && W_CheckNumForName("ENDOOM") != LUMPERROR)
+ {
+ printf("\r");
+ ShowEndTxt();
+ }
+ if (myargmalloc)
+ free(myargv); // Deallocate allocated memory
+death:
+ W_Shutdown();
+ exit(0);
+}
+
+void I_WaitVBL(INT32 count)
+{
+ count = 1;
+ I_Sleep(count);
+}
+
+void I_BeginRead(void)
+{
+}
+
+void I_EndRead(void)
+{
+}
+
+//
+// I_Error
+//
+/** \brief phuck recursive errors
+*/
+static INT32 errorcount = 0;
+
+/** \brief recursive error detecting
+*/
+static boolean shutdowning = false;
+
+void I_Error(const char *error, ...)
+{
+ va_list argptr;
+ char buffer[8192];
+
+ // recursive error detecting
+ if (shutdowning)
+ {
+ errorcount++;
+ // try to shutdown each subsystem separately
+ if (errorcount == 1)
+ I_ShutdownMusic();
+ if (errorcount == 2)
+ I_ShutdownSound();
+ if (errorcount == 3)
+ I_ShutdownGraphics();
+ if (errorcount == 4)
+ I_ShutdownSystem();
+ if (errorcount == 5)
+ {
+ M_SaveConfig(NULL);
+ G_SaveGameData(false);
+ }
+ if (errorcount > 20)
+ {
+ va_start(argptr, error);
+ vsprintf(buffer, error, argptr);
+ va_end(argptr);
+
+ I_OutputMsg("SRB2Kart %s Recursive Error", buffer);
+
+ W_Shutdown();
+ exit(-1); // recursive errors detected
+ }
+ }
+
+ shutdowning = true;
+
+ // Display error message in the console before we start shutting it down
+ va_start(argptr, error);
+ vsprintf(buffer, error, argptr);
+ va_end(argptr);
+ I_OutputMsg("\nI_Error(): %s\n", buffer);
+
+#ifdef HAVE_LIBBACKTRACE
+ write_backtrace(BT_CRASH_REASON_ERRORMSG(buffer));
+#endif
+ // ---
+
+ I_ShutdownConsole();
+
+ M_SaveConfig(NULL); // save game config, cvars..
+#ifndef NONET
+ D_SaveBan(); // save the ban list
+#endif
+ G_SaveGameData(false); // Tails 12-08-2002
+
+ // Shutdown. Here might be other errors.
+ if (demo.recording)
+ G_CheckDemoStatus();
+ if (metalrecording)
+ G_StopMetalRecording();
+
+ D_QuitNetGame();
+ I_ShutdownMusic();
+ I_ShutdownSound();
+ // use this for 1.28 19990220 by Kin
+ I_ShutdownGraphics();
+ I_ShutdownSystem();
+
+ W_Shutdown();
+
+#if defined (PARANOIA) && defined (__CYGWIN__)
+ *(INT32 *)2 = 4; //Alam: Debug!
+#endif
+
+ exit(-1);
+}
+
+/** \brief quit function table
+*/
+static quitfuncptr quit_funcs[MAX_QUIT_FUNCS]; /* initialized to all bits 0 */
+
+//
+// Adds a function to the list that need to be called by I_SystemShutdown().
+//
+void I_AddExitFunc(void (*func)())
+{
+ INT32 c;
+
+ for (c = 0; c < MAX_QUIT_FUNCS; c++)
+ {
+ if (!quit_funcs[c])
+ {
+ quit_funcs[c] = func;
+ break;
+ }
+ }
+}
+
+
+//
+// Removes a function from the list that need to be called by
+// I_SystemShutdown().
+//
+void I_RemoveExitFunc(void (*func)())
+{
+ INT32 c;
+
+ for (c = 0; c < MAX_QUIT_FUNCS; c++)
+ {
+ if (quit_funcs[c] == func)
+ {
+ while (c < MAX_QUIT_FUNCS-1)
+ {
+ quit_funcs[c] = quit_funcs[c+1];
+ c++;
+ }
+ quit_funcs[MAX_QUIT_FUNCS-1] = NULL;
+ break;
+ }
+ }
+}
+
+#if !(defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON))
+static void Shittycopyerror(const char *name)
+{
+ I_OutputMsg(
+ "Error copying log file: %s: %s\n",
+ name,
+ strerror(errno)
+ );
+}
+
+static void Shittylogcopy(void)
+{
+ char buf[8192];
+ FILE *fp;
+ size_t r;
+ if (fseek(logstream, 0, SEEK_SET) == -1)
+ {
+ Shittycopyerror("fseek");
+ }
+ else if (( fp = fopen(logfilename, "wt") ))
+ {
+ while (( r = fread(buf, 1, sizeof buf, logstream) ))
+ {
+ if (fwrite(buf, 1, r, fp) < r)
+ {
+ Shittycopyerror("fwrite");
+ break;
+ }
+ }
+ if (ferror(logstream))
+ {
+ Shittycopyerror("fread");
+ }
+ fclose(fp);
+ }
+ else
+ {
+ Shittycopyerror(logfilename);
+ }
+}
+#endif/*!(defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON))*/
+
+//
+// Closes down everything. This includes restoring the initial
+// palette and video mode, and removing whatever mouse, keyboard, and
+// timer routines have been installed.
+//
+// NOTE: Shutdown user funcs are effectively called in reverse order.
+//
+void I_ShutdownSystem(void)
+{
+ INT32 c;
+
+#ifndef NEWSIGNALHANDLER
+ I_ShutdownConsole();
+#endif
+
+ for (c = MAX_QUIT_FUNCS-1; c >= 0; c--)
+ if (quit_funcs[c])
+ (*quit_funcs[c])();
+#ifdef LOGMESSAGES
+ if (logstream)
+ {
+ I_OutputMsg("I_ShutdownSystem(): end of logstream.\n");
+#if !(defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON))
+ Shittylogcopy();
+#endif
+ fclose(logstream);
+ logstream = NULL;
+ }
+#endif
+}
+
+void I_GetDiskFreeSpace(INT64 *freespace)
+{
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON)
+#if defined (SOLARIS) || defined (__HAIKU__)
+ *freespace = INT32_MAX;
+ return;
+#else // Both Linux and BSD have this, apparently.
+ struct statfs stfs;
+ if (statfs(".", &stfs) == -1)
+ {
+ *freespace = INT32_MAX;
+ return;
+ }
+ *freespace = stfs.f_bavail * stfs.f_bsize;
+#endif
+#elif defined (_WIN32)
+ static p_GetDiskFreeSpaceExA pfnGetDiskFreeSpaceEx = NULL;
+ static boolean testwin95 = false;
+ ULARGE_INTEGER usedbytes, lfreespace;
+
+ if (!testwin95)
+ {
+ pfnGetDiskFreeSpaceEx = (p_GetDiskFreeSpaceExA)(LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetDiskFreeSpaceExA");
+ testwin95 = true;
+ }
+ if (pfnGetDiskFreeSpaceEx)
+ {
+ if (pfnGetDiskFreeSpaceEx(NULL, &lfreespace, &usedbytes, NULL))
+ *freespace = lfreespace.QuadPart;
+ else
+ *freespace = INT32_MAX;
+ }
+ else
+ {
+ DWORD SectorsPerCluster, BytesPerSector, NumberOfFreeClusters, TotalNumberOfClusters;
+ GetDiskFreeSpace(NULL, &SectorsPerCluster, &BytesPerSector,
+ &NumberOfFreeClusters, &TotalNumberOfClusters);
+ *freespace = BytesPerSector*SectorsPerCluster*NumberOfFreeClusters;
+ }
+#else // Dummy for platform independent; 1GB should be enough
+ *freespace = 1024*1024*1024;
+#endif
+}
+
+char *I_GetUserName(void)
+{
+ static char username[MAXPLAYERNAME+1];
+ char *p;
+#ifdef _WIN32
+ DWORD i = MAXPLAYERNAME;
+
+ if (!GetUserNameA(username, &i))
+#endif
+ {
+ p = I_GetEnv("USER");
+ if (!p)
+ {
+ p = I_GetEnv("user");
+ if (!p)
+ {
+ p = I_GetEnv("USERNAME");
+ if (!p)
+ {
+ p = I_GetEnv("username");
+ if (!p)
+ {
+ return NULL;
+ }
+ }
+ }
+ }
+ strncpy(username, p, MAXPLAYERNAME);
+ }
+
+
+ if (strcmp(username, "") != 0)
+ return username;
+ return NULL; // dummy for platform independent version
+}
+
+INT32 I_mkdir(const char *dirname, INT32 unixright)
+{
+//[segabor]
+#if defined (__unix__) || defined(__APPLE__) || defined (UNIXCOMMON) || defined (__CYGWIN__) || defined (__OS2__)
+ return mkdir(dirname, unixright);
+#elif defined (_WIN32)
+ UNREFERENCED_PARAMETER(unixright); /// \todo should implement ntright under nt...
+ return CreateDirectoryA(dirname, NULL);
+#else
+ (void)dirname;
+ (void)unixright;
+ return false;
+#endif
+}
+
+char *I_GetEnv(const char *name)
+{
+ return getenv(name);
+}
+
+INT32 I_PutEnv(char *variable)
+{
+ return putenv(variable);
+}
+
+INT32 I_ClipboardCopy(const char *data, size_t size)
+{
+ (void)data;
+ (void)size;
+ return -1;
+}
+
+const char *I_ClipboardPaste(void)
+{
+ return NULL;
+}
+
+/** \brief The isWadPathOk function
+
+ \param path string path to check
+
+ \return if true, wad file found
+
+
+*/
+static boolean isWadPathOk(const char *path)
+{
+ char *wad3path = malloc(256);
+
+ if (!wad3path)
+ return false;
+
+ sprintf(wad3path, pandf, path, WADKEYWORD1);
+
+ if (FIL_ReadFileOK(wad3path))
+ {
+ free(wad3path);
+ return true;
+ }
+
+ sprintf(wad3path, pandf, path, WADKEYWORD2);
+
+ if (FIL_ReadFileOK(wad3path))
+ {
+ free(wad3path);
+ return true;
+ }
+
+ free(wad3path);
+ return false;
+}
+
+static void pathonly(char *s)
+{
+ size_t j;
+
+ for (j = strlen(s); j != (size_t)-1; j--)
+ if ((s[j] == '\\') || (s[j] == ':') || (s[j] == '/'))
+ {
+ if (s[j] == ':') s[j+1] = 0;
+ else s[j] = 0;
+ return;
+ }
+}
+
+/** \brief search for srb2.srb in the given path
+
+ \param searchDir starting path
+
+ \return WAD path if not NULL
+
+
+*/
+static const char *searchWad(const char *searchDir)
+{
+ static char tempsw[256] = "";
+ filestatus_t fstemp;
+
+ strcpy(tempsw, WADKEYWORD1);
+ fstemp = filesearch(tempsw,searchDir,NULL,true,20);
+ if (fstemp == FS_FOUND)
+ {
+ pathonly(tempsw);
+ return tempsw;
+ }
+
+ strcpy(tempsw, WADKEYWORD2);
+ fstemp = filesearch(tempsw, searchDir, NULL, true, 20);
+ if (fstemp == FS_FOUND)
+ {
+ pathonly(tempsw);
+ return tempsw;
+ }
+ return NULL;
+}
+
+/** \brief go through all possible paths and look for srb2.srb
+
+ \return path to srb2.srb if any
+*/
+static const char *locateWad(void)
+{
+ const char *envstr;
+ const char *WadPath;
+
+ I_OutputMsg("SRB2WADDIR");
+ // does SRB2WADDIR exist?
+ if (((envstr = I_GetEnv("SRB2WADDIR")) != NULL) && isWadPathOk(envstr))
+ return envstr;
+
+#ifndef NOCWD
+ I_OutputMsg(",.");
+ // examine current dir
+ strcpy(returnWadPath, ".");
+ if (isWadPathOk(returnWadPath))
+ return NULL;
+#endif
+
+
+#ifdef DEFAULTDIR
+ I_OutputMsg(",HOME/" DEFAULTDIR);
+ // examine user jart directory
+ if ((envstr = I_GetEnv("HOME")) != NULL)
+ {
+ sprintf(returnWadPath, "%s" PATHSEP DEFAULTDIR, envstr);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+ }
+#endif
+
+
+#ifdef CMAKECONFIG
+#ifndef NDEBUG
+ I_OutputMsg(","CMAKE_ASSETS_DIR);
+ strcpy(returnWadPath, CMAKE_ASSETS_DIR);
+ if (isWadPathOk(returnWadPath))
+ {
+ return returnWadPath;
+ }
+#endif
+#endif
+
+#ifdef __APPLE__
+ OSX_GetResourcesPath(returnWadPath);
+ I_OutputMsg(",%s", returnWadPath);
+ if (isWadPathOk(returnWadPath))
+ {
+ return returnWadPath;
+ }
+#endif
+
+ // examine default dirs
+#ifdef DEFAULTWADLOCATION1
+ I_OutputMsg(","DEFAULTWADLOCATION1);
+ strcpy(returnWadPath, DEFAULTWADLOCATION1);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION2
+ I_OutputMsg(","DEFAULTWADLOCATION2);
+ strcpy(returnWadPath, DEFAULTWADLOCATION2);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION3
+ I_OutputMsg(","DEFAULTWADLOCATION3);
+ strcpy(returnWadPath, DEFAULTWADLOCATION3);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION4
+ I_OutputMsg(","DEFAULTWADLOCATION4);
+ strcpy(returnWadPath, DEFAULTWADLOCATION4);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION5
+ I_OutputMsg(","DEFAULTWADLOCATION5);
+ strcpy(returnWadPath, DEFAULTWADLOCATION5);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION6
+ I_OutputMsg(","DEFAULTWADLOCATION6);
+ strcpy(returnWadPath, DEFAULTWADLOCATION6);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifdef DEFAULTWADLOCATION7
+ I_OutputMsg(","DEFAULTWADLOCATION7);
+ strcpy(returnWadPath, DEFAULTWADLOCATION7);
+ if (isWadPathOk(returnWadPath))
+ return returnWadPath;
+#endif
+#ifndef NOHOME
+ // find in $HOME
+ I_OutputMsg(",HOME/" DEFAULTDIR);
+ if ((envstr = I_GetEnv("HOME")) != NULL)
+ {
+ char *tmp = malloc(strlen(envstr) + sizeof(PATHSEP) + sizeof(DEFAULTDIR));
+ strcpy(tmp, envstr);
+ strcat(tmp, PATHSEP);
+ strcat(tmp, DEFAULTDIR);
+ WadPath = searchWad(tmp);
+ free(tmp);
+ if (WadPath)
+ return WadPath;
+ }
+#endif
+#ifdef DEFAULTSEARCHPATH1
+ // find in /usr/local
+ I_OutputMsg(", in:"DEFAULTSEARCHPATH1);
+ WadPath = searchWad(DEFAULTSEARCHPATH1);
+ if (WadPath)
+ return WadPath;
+#endif
+#ifdef DEFAULTSEARCHPATH2
+ // find in /usr/games
+ I_OutputMsg(", in:"DEFAULTSEARCHPATH2);
+ WadPath = searchWad(DEFAULTSEARCHPATH2);
+ if (WadPath)
+ return WadPath;
+#endif
+#ifdef DEFAULTSEARCHPATH3
+ // find in ???
+ I_OutputMsg(", in:"DEFAULTSEARCHPATH3);
+ WadPath = searchWad(DEFAULTSEARCHPATH3);
+ if (WadPath)
+ return WadPath;
+#endif
+ // if nothing was found
+ return NULL;
+}
+
+const char *I_LocateWad(void)
+{
+ const char *waddir;
+
+ I_OutputMsg("Looking for WADs in: ");
+ waddir = locateWad();
+ I_OutputMsg("\n");
+
+ if (waddir)
+ {
+ // change to the directory where we found srb2.srb
+#if defined (_WIN32)
+ SetCurrentDirectoryA(waddir);
+#else
+ if (chdir(waddir) == -1)
+ I_OutputMsg("Couldn't change working directory\n");
+#endif
+ }
+ return waddir;
+}
+
+#ifdef __linux__
+#define MEMINFO_FILE "/proc/meminfo"
+#define MEMTOTAL "MemTotal:"
+#define MEMAVAILABLE "MemAvailable:"
+#define MEMFREE "MemFree:"
+#define CACHED "Cached:"
+#define BUFFERS "Buffers:"
+#define SHMEM "Shmem:"
+
+/* Parse the contents of /proc/meminfo (in buf), return value of "name"
+ * (example: MemTotal) */
+static long get_entry(const char* name, const char* buf)
+{
+ long val;
+ char* hit = strstr(buf, name);
+ if (hit == NULL) {
+ return -1;
+ }
+
+ errno = 0;
+ val = strtol(hit + strlen(name), NULL, 10);
+ if (errno != 0) {
+ CONS_Alert(CONS_ERROR, M_GetText("get_entry: strtol() failed: %s\n"), strerror(errno));
+ return -1;
+ }
+ return val;
+}
+#endif
+
+size_t I_GetFreeMem(size_t *total)
+{
+#ifdef FREEBSD
+ u_int v_free_count, v_page_size, v_page_count;
+ size_t size = sizeof(v_free_count);
+ sysctlbyname("vm.stats.vm.v_free_count", &v_free_count, &size, NULL, 0);
+ size = sizeof(v_page_size);
+ sysctlbyname("vm.stats.vm.v_page_size", &v_page_size, &size, NULL, 0);
+ size = sizeof(v_page_count);
+ sysctlbyname("vm.stats.vm.v_page_count", &v_page_count, &size, NULL, 0);
+
+ if (total)
+ *total = v_page_count * v_page_size;
+ return v_free_count * v_page_size;
+#elif defined (SOLARIS)
+ /* Just guess */
+ if (total)
+ *total = 32 << 20;
+ return 32 << 20;
+#elif defined (_WIN32)
+ MEMORYSTATUS info;
+
+ info.dwLength = sizeof (MEMORYSTATUS);
+ GlobalMemoryStatus( &info );
+ if (total)
+ *total = (size_t)info.dwTotalPhys;
+ return (size_t)info.dwAvailPhys;
+#elif defined (__OS2__)
+ UINT32 pr_arena;
+
+ if (total)
+ DosQuerySysInfo( QSV_TOTPHYSMEM, QSV_TOTPHYSMEM,
+ (PVOID) total, sizeof (UINT32));
+ DosQuerySysInfo( QSV_MAXPRMEM, QSV_MAXPRMEM,
+ (PVOID) &pr_arena, sizeof (UINT32));
+
+ return pr_arena;
+#elif defined (__linux__)
+ /* Linux */
+ char buf[1024];
+ char *memTag;
+ size_t freeKBytes;
+ size_t totalKBytes;
+ INT32 n;
+ INT32 meminfo_fd = -1;
+ long Cached;
+ long MemFree;
+ long Buffers;
+ long Shmem;
+ long MemAvailable = -1;
+
+ meminfo_fd = open(MEMINFO_FILE, O_RDONLY);
+ n = read(meminfo_fd, buf, 1023);
+ close(meminfo_fd);
+
+ if (n < 0)
+ {
+ // Error
+ if (total)
+ *total = 0L;
+ return 0;
+ }
+
+ buf[n] = '\0';
+ if ((memTag = strstr(buf, MEMTOTAL)) == NULL)
+ {
+ // Error
+ if (total)
+ *total = 0L;
+ return 0;
+ }
+
+ memTag += sizeof (MEMTOTAL);
+ totalKBytes = (size_t)atoi(memTag);
+
+ if ((memTag = strstr(buf, MEMAVAILABLE)) == NULL)
+ {
+ Cached = get_entry(CACHED, buf);
+ MemFree = get_entry(MEMFREE, buf);
+ Buffers = get_entry(BUFFERS, buf);
+ Shmem = get_entry(SHMEM, buf);
+ MemAvailable = Cached + MemFree + Buffers - Shmem;
+
+ if (MemAvailable == -1)
+ {
+ // Error
+ if (total)
+ *total = 0L;
+ return 0;
+ }
+ freeKBytes = MemAvailable;
+ }
+ else
+ {
+ memTag += sizeof (MEMAVAILABLE);
+ freeKBytes = atoi(memTag);
+ }
+
+ if (total)
+ *total = totalKBytes << 10;
+ return freeKBytes << 10;
+#else
+ // Guess 48 MB.
+ if (total)
+ *total = 48<<20;
+ return 48<<20;
+#endif
+}
+
+// note CPUAFFINITY code used to reside here
+void I_RegisterSysCommands(void) {}
+
+boolean I_InitNetwork(void)
+{
+ // this must exist, but this is actually handled in i_tcp.c
+ return false;
+}
diff --git a/src/dedicated/i_threads.c b/src/dedicated/i_threads.c
new file mode 100644
index 000000000..f981fa961
--- /dev/null
+++ b/src/dedicated/i_threads.c
@@ -0,0 +1,364 @@
+// SONIC ROBO BLAST 2
+//-----------------------------------------------------------------------------
+// Copyright (C) 2020-2023 by James R.
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+/// \file i_threads.c
+/// \brief Multithreading abstraction
+
+#if defined (__unix__) || (!defined(__APPLE__) && defined (UNIXCOMMON))
+
+#include
+
+#include "../i_threads.h"
+#include "../doomdef.h"
+
+typedef struct thread_s thread_t;
+
+struct thread_s
+{
+ thread_t *next;
+ void *userdata;
+ I_thread_fn func;
+ pthread_t thread;
+};
+
+// we use a linked list to avoid moving memory blocks when allocating new threads.
+static thread_t *thread_list;
+static pthread_mutex_t thread_lock = PTHREAD_MUTEX_INITIALIZER;
+
+static void *HandleThread(void *data)
+{
+ thread_t *thread = data;
+ thread->func(thread->userdata);
+
+ pthread_mutex_lock(&thread_lock);
+ thread->func = NULL;
+ pthread_mutex_unlock(&thread_lock);
+ return NULL;
+}
+
+void
+I_spawn_thread (
+ const char * name,
+ I_thread_fn entry,
+ void * userdata
+)
+{
+ thread_t *thread;
+ (void)name;
+
+ pthread_mutex_lock(&thread_lock);
+ thread = thread_list;
+ while (thread != NULL)
+ {
+ if (thread->func == NULL)
+ {
+ // join with the exited thread to release it's resources.
+ pthread_join(thread->thread, NULL);
+ break;
+ }
+ thread = thread->next;
+ }
+ if (thread == NULL)
+ {
+ thread = malloc(sizeof(thread_t));
+ thread->next = thread_list;
+ thread_list = thread;
+ }
+
+ thread->func = entry;
+ thread->userdata = userdata;
+ pthread_create(&thread->thread, NULL, HandleThread, thread);
+ pthread_mutex_unlock(&thread_lock);
+}
+
+int I_thread_is_stopped(void)
+{
+ thread_t *thread;
+ pthread_mutex_lock(&thread_lock);
+ thread = thread_list;
+ while (thread != NULL)
+ {
+ if (thread->func != NULL)
+ {
+ pthread_mutex_unlock(&thread_lock);
+ return false;
+ }
+ thread = thread->next;
+ }
+ pthread_mutex_unlock(&thread_lock);
+ return true;
+}
+
+void I_start_threads(void)
+{
+}
+
+void I_stop_threads(void)
+{
+ thread_t *thread = thread_list;
+ while (thread != NULL)
+ {
+ // join with all threads here, since finished threads haven't been awaited yet.
+ pthread_join(thread->thread, NULL);
+ thread = thread->next;
+ }
+}
+
+void I_lock_mutex(I_mutex *anchor)
+{
+ pthread_mutex_lock(&thread_lock);
+ if (*anchor == NULL)
+ {
+ pthread_mutexattr_t attr;
+ pthread_mutexattr_init(&attr);
+
+ // SRB2 relies on lock recursion, so we need a mutex configured for that.
+ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+ *anchor = malloc(sizeof(pthread_mutex_t));
+ pthread_mutex_init(*anchor, &attr);
+ pthread_mutexattr_destroy(&attr);
+ }
+ pthread_mutex_unlock(&thread_lock);
+ pthread_mutex_lock(*anchor);
+}
+
+void I_unlock_mutex(I_mutex id)
+{
+ pthread_mutex_unlock(id);
+}
+
+void I_hold_cond(I_cond *cond_anchor, I_mutex mutex_id)
+{
+ I_Assert(mutex_id != NULL);
+ pthread_mutex_lock(&thread_lock);
+ if (*cond_anchor == NULL)
+ {
+ *cond_anchor = malloc(sizeof(pthread_cond_t));
+ pthread_cond_init(*cond_anchor, NULL);
+ }
+ pthread_mutex_unlock(&thread_lock);
+ pthread_cond_wait(*cond_anchor, mutex_id);
+}
+
+void I_wake_one_cond(I_cond *anchor)
+{
+ pthread_mutex_lock(&thread_lock);
+ if (*anchor == NULL)
+ {
+ *anchor = malloc(sizeof(pthread_cond_t));
+ pthread_cond_init(*anchor, NULL);
+ }
+ pthread_mutex_unlock(&thread_lock);
+ pthread_cond_signal(*anchor);
+}
+
+void I_wake_all_cond(I_cond *anchor)
+{
+ pthread_mutex_lock(&thread_lock);
+ if (*anchor == NULL)
+ {
+ *anchor = malloc(sizeof(pthread_cond_t));
+ pthread_cond_init(*anchor, NULL);
+ }
+ pthread_mutex_unlock(&thread_lock);
+ pthread_cond_broadcast(*anchor);
+}
+#elif defined (_WIN32)
+#include
+
+#include "../i_threads.h"
+#include "../doomdef.h"
+#include "../doomtype.h"
+
+typedef struct thread_s thread_t;
+
+struct thread_s
+{
+ thread_t *next;
+ void *userdata;
+ I_thread_fn func;
+ HANDLE thread;
+ DWORD thread_id;
+};
+
+// we use a linked list to avoid moving memory blocks when allocating new threads.
+static thread_t *thread_list;
+static CRITICAL_SECTION thread_lock;
+
+static DWORD __stdcall HandleThread(void *data)
+{
+ thread_t *thread = data;
+ thread->func(thread->userdata);
+
+ EnterCriticalSection(&thread_lock);
+ thread->func = NULL;
+ LeaveCriticalSection(&thread_lock);
+ return 0;
+}
+
+void I_spawn_thread(const char *name, I_thread_fn entry, void *userdata)
+{
+ thread_t *thread;
+ (void)name;
+ EnterCriticalSection(&thread_lock);
+ thread = thread_list;
+ while (thread != NULL)
+ {
+ if (thread->func == NULL)
+ {
+ CloseHandle(thread->thread);
+ break;
+ }
+ thread = thread->next;
+ }
+ if (thread == NULL)
+ {
+ thread = malloc(sizeof(thread_t));
+ thread->next = thread_list;
+ thread_list = thread;
+ }
+
+ thread->func = entry;
+ thread->userdata = userdata;
+ thread->thread = CreateThread(NULL, 0, HandleThread, thread, 0, &thread->thread_id);
+ LeaveCriticalSection(&thread_lock);
+}
+
+int I_thread_is_stopped(void)
+{
+ thread_t *thread;
+ EnterCriticalSection(&thread_lock);
+ thread = thread_list;
+ while (thread != NULL)
+ {
+ if (thread->func != NULL)
+ {
+ LeaveCriticalSection(&thread_lock);
+ return false;
+ }
+ thread = thread->next;
+ }
+ LeaveCriticalSection(&thread_lock);
+ return true;
+}
+
+void I_start_threads(void)
+{
+ InitializeCriticalSection(&thread_lock);
+}
+
+void I_stop_threads(void)
+{
+ thread_t *thread = thread_list;
+ while (thread != NULL)
+ {
+ WaitForSingleObject(thread->thread, INFINITE);
+ CloseHandle(thread->thread);
+ thread = thread->next;
+ }
+ DeleteCriticalSection(&thread_lock);
+}
+
+void I_lock_mutex(I_mutex *anchor)
+{
+ EnterCriticalSection(&thread_lock);
+ if (*anchor == NULL)
+ {
+ *anchor = malloc(sizeof(CRITICAL_SECTION));
+ InitializeCriticalSection(*anchor);
+ }
+ LeaveCriticalSection(&thread_lock);
+ EnterCriticalSection(*anchor);
+}
+
+void I_unlock_mutex(I_mutex id)
+{
+ LeaveCriticalSection(id);
+}
+
+void I_hold_cond(I_cond *cond_anchor, I_mutex mutex_id)
+{
+ I_Assert(mutex_id != NULL);
+ EnterCriticalSection(&thread_lock);
+ if (*cond_anchor == NULL)
+ {
+ *cond_anchor = malloc(sizeof(CONDITION_VARIABLE));
+ InitializeConditionVariable(*cond_anchor);
+ }
+ LeaveCriticalSection(&thread_lock);
+ SleepConditionVariableCS(*cond_anchor, mutex_id, INFINITE);
+}
+
+void I_wake_one_cond(I_cond *anchor)
+{
+ EnterCriticalSection(&thread_lock);
+ if (*anchor == NULL)
+ {
+ *anchor = malloc(sizeof(CONDITION_VARIABLE));
+ InitializeConditionVariable(*anchor);
+ }
+ LeaveCriticalSection(&thread_lock);
+ WakeConditionVariable(*anchor);
+}
+
+void I_wake_all_cond(I_cond *anchor)
+{
+ EnterCriticalSection(&thread_lock);
+ if (*anchor == NULL)
+ {
+ *anchor = malloc(sizeof(CONDITION_VARIABLE));
+ InitializeConditionVariable(*anchor);
+ }
+ LeaveCriticalSection(&thread_lock);
+ WakeAllConditionVariable(*anchor);
+}
+#else
+void I_spawn_thread(const char *name, I_thread_fn entry, void *userdata)
+{
+ (void)name;
+ entry(userdata);
+}
+
+int I_thread_is_stopped(void)
+{
+}
+
+void I_start_threads(void)
+{
+}
+
+void I_stop_threads(void)
+{
+}
+
+void I_lock_mutex(I_mutex *anchor)
+{
+ (void)anchor;
+}
+
+void I_unlock_mutex(I_mutex id)
+{
+ (void)id;
+}
+
+void I_hold_cond(I_cond *cond_anchor, I_mutex mutex_id)
+{
+ (void)cond_anchor;
+ (void)mutex_id;
+}
+
+void I_wake_one_cond(I_cond *anchor)
+{
+ (void)anchor;
+}
+
+void I_wake_all_cond(I_cond *anchor)
+{
+ (void)anchor;
+}
+#endif
diff --git a/src/dedicated/i_video.c b/src/dedicated/i_video.c
new file mode 100644
index 000000000..6c0b6644a
--- /dev/null
+++ b/src/dedicated/i_video.c
@@ -0,0 +1,154 @@
+// Emacs style mode select -*- C++ -*-
+// SONIC ROBO BLAST 2
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) 1993-1996 by id Software, Inc.
+// Portions Copyright (C) 1998-2000 by DooM Legacy Team.
+// Copyright (C) 2014-2018 by Sonic Team Junior.
+//
+// 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; either version 2
+// of the License, or (at your option) any later version.
+//
+// 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.
+//-----------------------------------------------------------------------------
+/// \file
+/// \brief SRB2 graphics stuff for dedicated
+
+#include "../doomdef.h"
+#include "../i_system.h"
+#include "../i_video.h"
+#include "../console.h"
+#include "../command.h"
+#include "../i_system.h"
+#include "../screen.h"
+
+rendermode_t rendermode = render_none;
+
+boolean highcolor = false;
+
+// synchronize page flipping with screen refresh
+consvar_t cv_vidwait = {"vid_wait", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t keyboardlayout_cons_t[] = {{1,"Default US"}, {2, "Native"}, {3, "AZERTY"}, {0, NULL}};
+consvar_t cv_keyboardlayout = {"keyboardlayout", "Default US", CV_SAVE, keyboardlayout_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_alwaysgrabmouse = {"alwaysgrabmouse", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+INT32 numcontrollers = 0;
+
+UINT8 graphics_started = 0; // Is used in console.c and screen.c
+
+// To disable fullscreen at startup; is set in VID_PrepareModeList
+boolean allow_fullscreen = false;
+UINT16 realwidth = BASEVIDWIDTH;
+UINT16 realheight = BASEVIDHEIGHT;
+
+extern boolean consolevent;
+
+void I_GetConsoleEvents(void);
+
+void I_GetEvent(void)
+{
+}
+
+void I_StartupMouse(void)
+{
+}
+
+//
+// I_OsPolling
+//
+void I_OsPolling(void)
+{
+ if (consolevent)
+ I_GetConsoleEvents();
+}
+
+//
+// I_UpdateNoBlit
+//
+void I_UpdateNoBlit(void)
+{
+}
+
+//
+// I_FinishUpdate
+//
+void I_FinishUpdate(void)
+{
+}
+
+//
+// I_UpdateNoVsync
+//
+void I_UpdateNoVsync(void)
+{
+}
+
+//
+// I_ReadScreen
+//
+void I_ReadScreen(UINT8 *scr)
+{
+ (void)scr;
+}
+
+//
+// I_SetPalette
+//
+void I_SetPalette(RGBA_t *palette)
+{
+ (void)palette;
+}
+
+// return number of fullscreen + X11 modes
+INT32 VID_NumModes(void)
+{
+ return 0;
+}
+
+const char *VID_GetModeName(INT32 modenum)
+{
+ (void)modenum;
+ return NULL;
+}
+
+INT32 VID_GetModeForSize(INT32 w, INT32 h)
+{
+ (void)w;
+ (void)h;
+ return -1;
+}
+
+void VID_PrepareModeList(void)
+{
+}
+
+INT32 VID_SetMode(INT32 modeNum)
+{
+ (void)modeNum;
+ return true;
+}
+
+void I_StartupGraphics(void)
+{
+}
+
+void I_ShutdownGraphics(void)
+{
+}
+
+UINT32 I_GetRefreshRate(void)
+{
+ return 0;
+}
+
+boolean I_UseNativeKeyboard(void)
+{
+ return false;
+}
diff --git a/src/discord.c b/src/discord.c
index cd7dafa8f..207a249a6 100644
--- a/src/discord.c
+++ b/src/discord.c
@@ -388,7 +388,7 @@ static void DRPC_GotServerIP(UINT32 address)
--------------------------------------------------*/
static const char *DRPC_GetServerIP(void)
{
- const char *address;
+ const char *address;
// If you're connected
if (I_GetNodeAddress && (address = I_GetNodeAddress(servernode)) != NULL)
@@ -489,7 +489,7 @@ void DRPC_UpdatePresence(void)
{
#endif
discordPresence.state = "Private";
-#ifdef MASTERSERVER
+#ifdef MASTERSERVER
}
#endif
@@ -571,9 +571,15 @@ void DRPC_UpdatePresence(void)
{
// Map name on tool tip
char *title = G_BuildMapTitle(gamemap);
- snprintf(mapname, 48, "Map: %s", title);
+ if (title)
+ {
+ snprintf(mapname, 48, "Map: %s", title);
+ Z_Free(title);
+ }
+ else
+ snprintf(mapname, 48, "Map: UNKNOWN");
+
discordPresence.largeImageText = mapname;
- Z_Free(title);
}
if (gamestate == GS_LEVEL && Playing())
diff --git a/src/doomdef.h b/src/doomdef.h
index cb6a91d17..e81f43429 100644
--- a/src/doomdef.h
+++ b/src/doomdef.h
@@ -58,6 +58,9 @@
// warning C4152: nonstandard extension, function/data pointer conversion in expression
// warning C4213: nonstandard extension used : cast on l-value
+#ifdef __cplusplus
+extern "C" {
+#endif
#include "doomtype.h"
@@ -513,12 +516,15 @@ UINT32 quickncasehash (const char *p, size_t n)
return x;
}
+#ifndef __cplusplus
#ifndef min // Double-Check with WATTCP-32's cdefs.h
#define min(x, y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef max // Double-Check with WATTCP-32's cdefs.h
#define max(x, y) (((x) > (y)) ? (x) : (y))
#endif
+#endif
+
#ifndef CLAMP
#define CLAMP(x, y, z) ((x) < (y) ? (y) : ((x) > (z) ? (z) : (x)))
#endif
@@ -549,6 +555,14 @@ UINT32 quickncasehash (const char *p, size_t n)
#define UNLIKELY(x) (x)
#endif
+#ifdef __cplusplus
+#if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER)
+ #define restrict __restrict
+#else
+ #define restrict
+#endif
+#endif
+
// An assert-type mechanism.
#ifdef PARANOIA
#define I_Assert(e) ((e) ? (void)0 : I_Error("assert failed: %s, file %s, line %d", #e, __FILE__, __LINE__))
@@ -646,4 +660,8 @@ extern const char *compdate, *comptime, *comprevision, *compbranch;
#undef UPDATE_ALERT
#endif
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // __DOOMDEF__
diff --git a/src/doomstat.h b/src/doomstat.h
index f8a3899ca..171b49edc 100644
--- a/src/doomstat.h
+++ b/src/doomstat.h
@@ -125,7 +125,7 @@ extern boolean lastdraw;
extern INT32 postimgparam[MAXSPLITSCREENPLAYERS];
extern INT32 viewwindowx, viewwindowy;
-extern INT32 viewwidth, scaledviewwidth;
+extern INT32 viewwidth;
extern boolean gamedataloaded;
diff --git a/src/doomtype.h b/src/doomtype.h
index 174bba5b1..ac41a4413 100644
--- a/src/doomtype.h
+++ b/src/doomtype.h
@@ -17,6 +17,10 @@
#ifndef __DOOMTYPE__
#define __DOOMTYPE__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#if defined (_WIN32)
//#define WIN32_LEAN_AND_MEAN
#define RPC_NO_WINDOWS_H
@@ -100,8 +104,10 @@ typedef long ssize_t;
#define strnicmp(x,y,n) strncasecmp(x,y,n)
#endif
+#ifndef __cplusplus
char *strcasestr(const char *in, const char *what);
#define stristr strcasestr
+#endif
#if defined (macintosh) //|| defined (__APPLE__) //skip all boolean/Boolean crap
#define true 1
@@ -156,22 +162,19 @@ size_t strlcpy(char *dst, const char *src, size_t siz);
/* Boolean type definition */
-// \note __BYTEBOOL__ used to be set above if "macintosh" was defined,
-// if macintosh's version of boolean type isn't needed anymore, then isn't this macro pointless now?
-#ifndef __BYTEBOOL__
- #define __BYTEBOOL__
-
- //faB: clean that up !!
- #if defined( _MSC_VER) && (_MSC_VER >= 1800) // MSVC 2013 and forward
- #include "stdbool.h"
- #elif defined (_WIN32)
- #define false FALSE // use windows types
- #define true TRUE
- #define boolean BOOL
- #else
- typedef enum {false, true} boolean;
- #endif
-#endif // __BYTEBOOL__
+#ifndef _WIN32
+#include
+// dont use stdbools _BOOL type
+// its smaller (1 byte) than the old interger bool (4 bytes)
+// which results in packed struct sizes being mismatched between vanilla and this
+// however we gotta still include stdbool cause since c23 true and false are keywords
+// which we cant use as enumeration constants
+typedef int32_t boolean;
+#else
+#define false FALSE
+#define true TRUE
+#define boolean BOOL
+#endif
/* 7.18.2.1 Limits of exact-width integer types */
#ifndef INT8_MIN
@@ -385,4 +388,8 @@ unset_bit_array (bitarray_t * const array, const int value)
typedef UINT64 precise_t;
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif //__DOOMTYPE__
diff --git a/src/f_finale.c b/src/f_finale.c
index dd024ecd0..b98570b48 100644
--- a/src/f_finale.c
+++ b/src/f_finale.c
@@ -531,8 +531,8 @@ static const char *credits[] = {
"\"Xyzzy\"",
"\"Chearii\"",
" ",
- "\"Sunflower\" aka \"AnimeSonic\"",
- "\"Yuz\" aka \"Yuzler\"",
+ "\"Sunflower\"",
+ "\"Yuz\"",
"\"Democrab\"",
"\"EXpand\"",
"\"Nexit\"",
@@ -543,6 +543,7 @@ static const char *credits[] = {
"\"Achii\"",
"\"Anonimus\"",
"\"scizor300\"",
+ "\"Lugent\"",
"",
"\1Special Thanks",
"SEGA",
diff --git a/src/f_wipe.c b/src/f_wipe.c
index 1523ca1d3..cbb411b8b 100644
--- a/src/f_wipe.c
+++ b/src/f_wipe.c
@@ -313,7 +313,7 @@ void F_WipeStartScreen(void)
return;
}
#endif
- wipe_scr_start = screens[3];
+ wipe_scr_start = vid.screens[3];
I_ReadScreen(wipe_scr_start);
#endif
}
@@ -330,7 +330,7 @@ void F_WipeEndScreen(void)
return;
}
#endif
- wipe_scr_end = screens[4];
+ wipe_scr_end = vid.screens[4];
I_ReadScreen(wipe_scr_end);
V_DrawBlock(0, 0, 0, vid.width, vid.height, wipe_scr_start);
#endif
@@ -353,7 +353,7 @@ void F_RunWipe(UINT8 wipetype, boolean drawMenu)
// Init the wipe
WipeInAction = true;
- wipe_scr = screens[0];
+ wipe_scr = vid.screens[0];
// lastwipetic should either be 0 or the tic we last wiped
// on for fade-to-black
diff --git a/src/filesrch.h b/src/filesrch.h
index 76d5700c0..075895cb0 100644
--- a/src/filesrch.h
+++ b/src/filesrch.h
@@ -4,6 +4,10 @@
#ifndef __FILESRCH_H__
#define __FILESRCH_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "doomdef.h"
#include "d_netfil.h"
#include "m_menu.h" // MAXSTRINGLENGTH
@@ -96,4 +100,8 @@ void closefilemenu(boolean validsize);
void searchfilemenu(char *tempname);
boolean preparefilemenu(boolean samedepth, boolean replayhut);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // __FILESRCH_H__
diff --git a/src/g_demo.c b/src/g_demo.c
new file mode 100644
index 000000000..820ef45fb
--- /dev/null
+++ b/src/g_demo.c
@@ -0,0 +1,4070 @@
+// SONIC ROBO BLAST 2 KART
+//-----------------------------------------------------------------------------
+// Copyright (C) 1993-1996 by id Software, Inc.
+// Copyright (C) 1998-2000 by DooM Legacy Team.
+// Copyright (C) 1999-2020 by Sonic Team Junior.
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+/// \file g_demo.c
+/// \brief Demo recording and playback
+
+#include "doomdef.h"
+#include "console.h"
+#include "d_main.h"
+#include "d_clisrv.h"
+#include "d_player.h"
+#include "f_finale.h"
+#include "filesrch.h" // for refreshdirmenu
+#include "p_setup.h"
+#include "p_saveg.h"
+#include "i_time.h"
+#include "i_system.h"
+#include "am_map.h"
+#include "m_random.h"
+#include "p_local.h"
+#include "r_draw.h"
+#include "r_main.h"
+#include "s_sound.h"
+#include "g_game.h"
+#include "m_cheat.h"
+#include "m_misc.h"
+#include "m_menu.h"
+#include "m_argv.h"
+#include "hu_stuff.h"
+#include "st_stuff.h"
+#include "z_zone.h"
+#include "i_video.h"
+#include "byteptr.h"
+#include "i_joy.h"
+#include "r_local.h"
+#include "r_things.h"
+#include "y_inter.h"
+#include "v_video.h"
+#include "dehacked.h" // get_number (for ghost thok)
+#include "lua_script.h" // LUA_ArchiveDemo and LUA_UnArchiveDemo
+#include "lua_hook.h"
+#include "lua_libs.h" // gL (Lua state)
+#include "b_bot.h"
+#include "m_cond.h" // condition sets
+#include "md5.h" // demo checksums
+#include "k_director.h" // SRB2kart
+#include "k_kart.h" // SRB2kart
+#include "k_stats.h" // SRB2kart
+#include "r_fps.h" // frame interpolation/uncapped
+
+#ifdef HAVE_DISCORDRPC
+#include "discord.h"
+#endif
+
+// for replay dates
+#include
+#include
+
+// menu demo things
+UINT8 numDemos = 0; //3; -- i'm FED UP of losing my skincolour to a broken demo. change this back when we make new ones
+UINT32 demoDelayTime = 15*TICRATE;
+UINT32 demoIdleTime = 3*TICRATE;
+
+boolean nodrawers; // for comparative timing purposes
+boolean noblit; // for comparative timing purposes
+static tic_t demostarttime; // for comparative timing purposes
+
+//@TODO put these all in a struct for namespacing purposes?
+static char demoname[128];
+savebuffer_t demobuf;
+static UINT8 *demotime_p, *demoinfo_p;
+static UINT8 *demoend;
+static UINT8 demoflags;
+static boolean demosynced = true; // console warning message
+
+struct demovars_s demo;
+
+boolean metalrecording; // recording as metal sonic
+mobj_t *metalplayback;
+static UINT8 *metalbuffer = NULL;
+static UINT8 *metal_p;
+static UINT16 metalversion;
+
+consvar_t cv_resyncdemo = {"resyncdemo", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+// extra data stuff (events registered this frame while recording)
+static struct {
+ UINT8 flags; // EZT flags
+
+ // EZT_COLOR
+ UINT8 color, lastcolor;
+
+ // EZT_SCALE
+ fixed_t scale, lastscale;
+
+ // EZT_KART
+ INT32 kartitem, kartamount, kartbumpers;
+
+ UINT8 desyncframes; // Don't try to resync unless we've been off for two frames, to monkeypatch a few trouble spots
+
+ // EZT_HIT
+ UINT16 hits;
+ mobj_t **hitlist;
+} ghostext[MAXPLAYERS];
+
+// Your naming conventions are stupid and useless.
+// There is no conflict here.
+demoghost *ghosts = NULL;
+
+static CV_PossibleValue_t recordmultiplayerdemos_cons_t[] = {{0, "Disabled"}, {1, "Manual Save"}, {2, "Auto Save"}, {0, NULL}};
+consvar_t cv_recordmultiplayerdemos = {"netdemo_record", "Manual Save", CV_SAVE, recordmultiplayerdemos_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t netdemosyncquality_cons_t[] = {{1, "MIN"}, {35, "MAX"}, {0, NULL}};
+consvar_t cv_netdemosyncquality = {"netdemo_syncquality", "1", CV_SAVE, netdemosyncquality_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+// Units are MiB.
+static CV_PossibleValue_t maxdemosize_cons_t[] = {{10, "MIN"}, {100, "MAX"}, {0, NULL}};
+consvar_t cv_maxdemosize = {"maxdemosize", "10", CV_SAVE, maxdemosize_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t demochangemap_cons_t[] = {{0, "Disabled"}, {1, "Diff Map"}, {2, "Always"}, {0, NULL}};
+consvar_t cv_demochangemap = {"netdemo_savemapchange", "Disabled", CV_SAVE, demochangemap_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t demodateformat_cons_t[] = {{0, "Automatic"}, {1, "EU"}, {2, "US"}, {0, NULL}};
+consvar_t cv_demodateformat = {"netdemo_dateformat", "Automatic", CV_SAVE, demodateformat_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+#define DEMOVERSION 0x0002
+#define DEMOHEADER "\xF0" "KartReplay" "\x0F"
+
+#define DF_GHOST 0x01 // This demo contains ghost data too!
+#define DF_RECORDATTACK 0x02 // This demo is from record attack and contains its final completion time!
+#define DF_NIGHTSATTACK 0x04 // This demo is from NiGHTS attack and contains its time left, score, and mares!
+#define DF_ATTACKMASK 0x06 // This demo is from ??? attack and contains ???
+
+#define DF_LUAVARS 0x20 // this demo contains extra lua vars; this is mostly used for backwards compability
+
+#define DF_ATTACKSHIFT 1
+#define DF_ENCORE 0x40
+#define DF_MULTIPLAYER 0x80 // This demo was recorded in multiplayer mode!
+
+#ifdef DEMO_COMPAT_100
+#define DF_FILELIST 0x08 // This demo contains an extra files list
+#define DF_GAMETYPEMASK 0x30
+#define DF_GAMESHIFT 4
+#endif
+
+#define DEMO_SPECTATOR 0x40
+
+// For demos
+#define ZT_FWD 0x01
+#define ZT_SIDE 0x02
+#define ZT_ANGLE 0x04
+#define ZT_BUTTONS 0x08
+#define ZT_AIMING 0x10
+#define ZT_DRIFT 0x20
+#define ZT_LATENCY 0x40
+#define DEMOMARKER 0x80 // demoend
+
+UINT8 demo_extradata[MAXPLAYERS];
+UINT8 demo_writerng; // 0=no, 1=yes, 2=yes but on a timeout
+static ticcmd_t oldcmd[MAXPLAYERS];
+
+#define DW_END 0xFF // End of extradata block
+#define DW_RNG 0xFE // Check RNG seed!
+
+#define DW_EXTRASTUFF 0xFE // Numbers below this are reserved for writing player slot data
+
+// Below consts are only used for demo extrainfo sections
+#define DW_STANDING 0x00
+
+// For Metal Sonic and time attack ghosts
+#define GZT_XYZ 0x01
+#define GZT_MOMXY 0x02
+#define GZT_MOMZ 0x04
+#define GZT_ANGLE 0x08
+// Not used for Metal Sonic
+#define GZT_SPRITE 0x10 // Animation frame
+#define GZT_EXTRA 0x20
+#define GZT_NIGHTS 0x40 // NiGHTS Mode stuff!
+
+// GZT_EXTRA flags
+#define EZT_THOK 0x01 // Spawned a thok object
+#define EZT_SPIN 0x02 // Because one type of thok object apparently wasn't enough
+#define EZT_REV 0x03 // And two types wasn't enough either yet
+#define EZT_THOKMASK 0x03
+#define EZT_COLOR 0x04 // Changed color (Super transformation, Mario fireflowers/invulnerability, etc.)
+#define EZT_FLIP 0x08 // Reversed gravity
+#define EZT_SCALE 0x10 // Changed size
+#define EZT_HIT 0x20 // Damaged a mobj
+#define EZT_SPRITE 0x40 // Changed sprite set completely out of PLAY (NiGHTS, SOCs, whatever)
+#define EZT_KART 0x80 // SRB2Kart: Changed current held item/quantity and bumpers for battle
+
+static mobj_t oldmetal, oldghost[MAXPLAYERS];
+
+static void G_ResetDemoPlayback(char *pdemoname);
+
+void G_SaveMetal(UINT8 **buffer)
+{
+ I_Assert(buffer != NULL && *buffer != NULL);
+
+ WRITEUINT32(*buffer, metal_p - metalbuffer);
+}
+
+void G_LoadMetal(UINT8 **buffer)
+{
+ I_Assert(buffer != NULL && *buffer != NULL);
+
+ G_DoPlayMetal();
+ metal_p = metalbuffer + READUINT32(*buffer);
+}
+
+ticcmd_t *G_CopyTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n)
+{
+ return M_Memcpy(dest, src, n*sizeof(*src));
+}
+
+ticcmd_t *G_MoveTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n)
+{
+ size_t i;
+ for (i = 0; i < n; i++)
+ {
+ dest[i].forwardmove = src[i].forwardmove;
+ dest[i].sidemove = src[i].sidemove;
+ dest[i].angleturn = SHORT(src[i].angleturn);
+ dest[i].aiming = (INT16)SHORT(src[i].aiming);
+ dest[i].buttons = (UINT16)SHORT(src[i].buttons);
+ dest[i].driftturn = (INT16)SHORT(src[i].driftturn);
+ dest[i].latency = (INT16)SHORT(src[i].latency);
+ }
+ return dest;
+}
+
+// Finds a skin with the closest stats if the expected skin doesn't exist.
+static INT32 GetSkinNumClosestToStats(UINT8 kartspeed, UINT8 kartweight)
+{
+ INT32 i, closest_skin = 0;
+ UINT8 closest_stats = UINT8_MAX, stat_diff;
+
+ for (i = 0; i < numskins; i++)
+ {
+ stat_diff = abs(skins[i].kartspeed - kartspeed) + abs(skins[i].kartweight - kartweight);
+ if (stat_diff < closest_stats)
+ {
+ closest_stats = stat_diff;
+ closest_skin = i;
+ }
+ }
+
+ return closest_skin;
+}
+
+static void FindClosestSkinForStats(UINT32 p, UINT8 kartspeed, UINT8 kartweight)
+{
+ INT32 closest_skin = GetSkinNumClosestToStats(kartspeed, kartweight);
+
+ //CONS_Printf("Using %s instead...\n", skins[closest_skin].name);
+ SetPlayerSkinByNum(p, closest_skin);
+}
+
+void G_ReadDemoExtraData(void)
+{
+ INT32 p, extradata, i;
+ char name[17];
+
+ if (leveltime > starttime)
+ {
+ rewind_t *rewind = CL_SaveRewindPoint(demobuf.p - demobuf.buffer);
+ if (rewind)
+ {
+ memcpy(rewind->oldcmd, oldcmd, sizeof (oldcmd));
+ memcpy(rewind->oldghost, oldghost, sizeof (oldghost));
+ }
+ }
+
+ memset(name, '\0', 17);
+
+ p = READUINT8(demobuf.p);
+
+ while (p < DW_EXTRASTUFF)
+ {
+ extradata = READUINT8(demobuf.p);
+
+ if (extradata & DXD_RESPAWN)
+ {
+ if (players[p].mo)
+ P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL); // Is this how this should work..?
+ }
+ if (extradata & DXD_SKIN)
+ {
+ UINT8 kartspeed, kartweight;
+
+ // Skin
+ M_Memcpy(name, demobuf.p, 16);
+ demobuf.p += 16;
+ SetPlayerSkin(p, name);
+
+ kartspeed = READUINT8(demobuf.p);
+ kartweight = READUINT8(demobuf.p);
+
+ if (stricmp(skins[players[p].skin].name, name) != 0)
+ FindClosestSkinForStats(p, kartspeed, kartweight);
+
+ players[p].kartspeed = kartspeed;
+ players[p].kartweight = kartweight;
+ }
+ if (extradata & DXD_COLOR)
+ {
+ // Color
+ M_Memcpy(name, demobuf.p, 16);
+ demobuf.p += 16;
+ for (i = 0; i < MAXSKINCOLORS; i++)
+ if (!stricmp(KartColor_Names[i], name)) // SRB2kart
+ {
+ players[p].skincolor = i;
+ if (players[p].mo)
+ players[p].mo->color = i;
+ break;
+ }
+ }
+ if (extradata & DXD_NAME)
+ {
+ // Name
+ M_Memcpy(player_names[p],demobuf.p,16);
+ demobuf.p += 16;
+ }
+ if (extradata & DXD_PLAYSTATE)
+ {
+ extradata = READUINT8(demobuf.p);
+
+ switch (extradata) {
+ case DXD_PST_PLAYING:
+ players[p].pflags |= PF_WANTSTOJOIN; // fuck you
+ break;
+
+ case DXD_PST_SPECTATING:
+ players[p].pflags &= ~PF_WANTSTOJOIN; // double-fuck you
+ if (!playeringame[p])
+ {
+ CL_ClearPlayer(p);
+ playeringame[p] = true;
+ G_AddPlayer(p);
+ players[p].spectator = true;
+
+ // There's likely an off-by-one error in timing recording or playback of joins. This hacks around it so I don't have to find out where that is. \o/
+ if (oldcmd[p].forwardmove)
+ P_RandomByte();
+ }
+ else
+ {
+ players[p].spectator = true;
+ if (players[p].mo)
+ P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL);
+ else
+ players[p].playerstate = PST_REBORN;
+ }
+ break;
+
+ case DXD_PST_LEFT:
+ CL_RemovePlayer(p, 0);
+ break;
+ }
+
+ G_ResetViews();
+
+ // maybe these are necessary?
+ if (G_BattleGametype())
+ K_CheckBumpers(); // SRB2Kart
+ else if (G_RaceGametype())
+ P_CheckRacers(); // also SRB2Kart
+ }
+
+
+ p = READUINT8(demobuf.p);
+ }
+
+ while (p != DW_END)
+ {
+ UINT32 rng;
+ UINT32 checkrng;
+
+ switch (p)
+ {
+ case DW_RNG:
+ rng = READUINT32(demobuf.p);
+ checkrng = P_GetRandSeed();
+ if (checkrng != rng)
+ {
+ if (demosynced)
+ {
+ CONS_Alert(CONS_WARNING, M_GetText("Demo playback has desynced (RNG)!\n"));
+ CONS_Printf("expected rng %d got %d\n", rng, checkrng);
+ }
+ demosynced = false;
+
+ P_SetRandSeed(rng);
+ }
+ }
+
+ p = READUINT8(demobuf.p);
+ }
+
+ if (!(demoflags & DF_GHOST) && *demobuf.p == DEMOMARKER)
+ {
+ // end of demo data stream
+ G_CheckDemoStatus();
+ return;
+ }
+}
+
+void G_WriteDemoExtraData(void)
+{
+ INT32 i;
+ char name[17];
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (demo_extradata[i])
+ {
+ WRITEUINT8(demobuf.p, i);
+ WRITEUINT8(demobuf.p, demo_extradata[i]);
+
+ //if (demo_extradata[i] & DXD_RESPAWN) has no extra data
+ if (demo_extradata[i] & DXD_SKIN)
+ {
+ // Skin
+ memset(name, 0, 16);
+ strncpy(name, skins[players[i].skin].name, 16);
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+
+ WRITEUINT8(demobuf.p, skins[players[i].skin].kartspeed);
+ WRITEUINT8(demobuf.p, skins[players[i].skin].kartweight);
+ }
+ if (demo_extradata[i] & DXD_COLOR)
+ {
+ // Color
+ memset(name, 0, 16);
+ strncpy(name, KartColor_Names[players[i].skincolor], 16);
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+ }
+ if (demo_extradata[i] & DXD_NAME)
+ {
+ // Name
+ memset(name, 0, 16);
+ memcpy(name, player_names[i], 15); // Keeping 1 null byte for safety, sorry players with name containing more than 15 characters
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+ }
+ if (demo_extradata[i] & DXD_PLAYSTATE)
+ {
+ demo_writerng = 1;
+ if (!playeringame[i])
+ WRITEUINT8(demobuf.p, DXD_PST_LEFT);
+ else if (
+ players[i].spectator &&
+ !(players[i].pflags & PF_WANTSTOJOIN) // <= fuck you specifically
+ )
+ WRITEUINT8(demobuf.p, DXD_PST_SPECTATING);
+ else
+ WRITEUINT8(demobuf.p, DXD_PST_PLAYING);
+ }
+ }
+
+ demo_extradata[i] = 0;
+ }
+
+ // May not be necessary, but might as well play it safe...
+ if ((leveltime & 255) == 128)
+ demo_writerng = 1;
+
+ {
+ static UINT8 timeout = 0;
+
+ if (timeout) timeout--;
+
+ if (demo_writerng == 1 || (demo_writerng == 2 && timeout == 0))
+ {
+ demo_writerng = 0;
+ timeout = 16;
+ WRITEUINT8(demobuf.p, DW_RNG);
+ WRITEUINT32(demobuf.p, P_GetRandSeed());
+ }
+ }
+
+ WRITEUINT8(demobuf.p, DW_END);
+}
+
+void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum)
+{
+ UINT8 ziptic;
+
+ if (!demobuf.p || !demo.deferstart)
+ return;
+ ziptic = READUINT8(demobuf.p);
+
+ if (ziptic & ZT_FWD)
+ oldcmd[playernum].forwardmove = READSINT8(demobuf.p);
+ if (ziptic & ZT_SIDE)
+ oldcmd[playernum].sidemove = READSINT8(demobuf.p);
+ if (ziptic & ZT_ANGLE)
+ oldcmd[playernum].angleturn = READINT16(demobuf.p);
+ if (ziptic & ZT_BUTTONS)
+ oldcmd[playernum].buttons = READUINT16(demobuf.p);
+ if (ziptic & ZT_AIMING)
+ oldcmd[playernum].aiming = READINT16(demobuf.p);
+ if (ziptic & ZT_DRIFT)
+ oldcmd[playernum].driftturn = READINT16(demobuf.p);
+ if (ziptic & ZT_LATENCY)
+ oldcmd[playernum].latency = READUINT8(demobuf.p);
+
+ G_CopyTiccmd(cmd, &oldcmd[playernum], 1);
+
+ // SRB2kart: Copy-pasted from ticcmd building, removes that crappy demo cam
+ if (((players[displayplayers[0]].mo && players[displayplayers[0]].speed > 0) // Moving
+ || (leveltime > starttime && (cmd->buttons & BT_ACCELERATE && cmd->buttons & BT_BRAKE)) // Rubber-burn turn
+ || (players[displayplayers[0]].kartstuff[k_respawn]) // Respawning
+ || (players[displayplayers[0]].spectator || objectplacing)) // Not a physical player
+ && !(players[displayplayers[0]].kartstuff[k_spinouttimer] && players[displayplayers[0]].kartstuff[k_sneakertimer])) // Spinning and boosting cancels out spinout
+ localangle[0] += (cmd->angleturn<<16);
+
+ if (!(demoflags & DF_GHOST) && *demobuf.p == DEMOMARKER)
+ {
+ // end of demo data stream
+ G_CheckDemoStatus();
+ return;
+ }
+}
+
+void G_WriteDemoTiccmd(ticcmd_t *cmd, INT32 playernum)
+{
+ char ziptic = 0;
+ UINT8 *ziptic_p;
+
+ if (!demobuf.p)
+ return;
+
+ ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
+
+ if (cmd->forwardmove != oldcmd[playernum].forwardmove)
+ {
+ WRITEUINT8(demobuf.p,cmd->forwardmove);
+ oldcmd[playernum].forwardmove = cmd->forwardmove;
+ ziptic |= ZT_FWD;
+ }
+
+ if (cmd->sidemove != oldcmd[playernum].sidemove)
+ {
+ WRITEUINT8(demobuf.p,cmd->sidemove);
+ oldcmd[playernum].sidemove = cmd->sidemove;
+ ziptic |= ZT_SIDE;
+ }
+
+ if (cmd->angleturn != oldcmd[playernum].angleturn)
+ {
+ WRITEINT16(demobuf.p,cmd->angleturn);
+ oldcmd[playernum].angleturn = cmd->angleturn;
+ ziptic |= ZT_ANGLE;
+ }
+
+ if (cmd->buttons != oldcmd[playernum].buttons)
+ {
+ WRITEUINT16(demobuf.p,cmd->buttons);
+ oldcmd[playernum].buttons = cmd->buttons;
+ ziptic |= ZT_BUTTONS;
+ }
+
+ if (cmd->aiming != oldcmd[playernum].aiming)
+ {
+ WRITEINT16(demobuf.p,cmd->aiming);
+ oldcmd[playernum].aiming = cmd->aiming;
+ ziptic |= ZT_AIMING;
+ }
+
+ if (cmd->driftturn != oldcmd[playernum].driftturn)
+ {
+ WRITEINT16(demobuf.p,cmd->driftturn);
+ oldcmd[playernum].driftturn = cmd->driftturn;
+ ziptic |= ZT_DRIFT;
+ }
+
+ if (cmd->latency != oldcmd[playernum].latency)
+ {
+ WRITEUINT8(demobuf.p,cmd->latency);
+ oldcmd[playernum].latency = cmd->latency;
+ ziptic |= ZT_LATENCY;
+ }
+
+ *ziptic_p = ziptic;
+
+ // attention here for the ticcmd size!
+ // latest demos with mouse aiming byte in ticcmd
+ if (!(demoflags & DF_GHOST) && ziptic_p > demoend - 9)
+ {
+ G_CheckDemoStatus(); // no more space
+ return;
+ }
+}
+
+void G_GhostAddThok(INT32 playernum)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_THOK;
+}
+
+void G_GhostAddSpin(INT32 playernum)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_SPIN;
+}
+
+void G_GhostAddRev(INT32 playernum)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_REV;
+}
+
+void G_GhostAddFlip(INT32 playernum)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ ghostext[playernum].flags |= EZT_FLIP;
+}
+
+void G_GhostAddColor(INT32 playernum, ghostcolor_t color)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ if (ghostext[playernum].lastcolor == (UINT8)color)
+ {
+ ghostext[playernum].flags &= ~EZT_COLOR;
+ return;
+ }
+
+ ghostext[playernum].flags |= EZT_COLOR;
+ ghostext[playernum].color = (UINT8)color;
+}
+
+void G_GhostAddScale(INT32 playernum, fixed_t scale)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ if (ghostext[playernum].lastscale == scale)
+ {
+ ghostext[playernum].flags &= ~EZT_SCALE;
+ return;
+ }
+
+ ghostext[playernum].flags |= EZT_SCALE;
+ ghostext[playernum].scale = scale;
+}
+
+void G_GhostAddHit(INT32 playernum, mobj_t *victim)
+{
+ if (!demo.recording || !(demoflags & DF_GHOST))
+ return;
+
+ ghostext[playernum].flags |= EZT_HIT;
+ ghostext[playernum].hits++;
+ ghostext[playernum].hitlist = Z_Realloc(ghostext[playernum].hitlist, ghostext[playernum].hits * sizeof(mobj_t *), PU_LEVEL, &ghostext[playernum].hitlist);
+ P_SetTarget(ghostext[playernum].hitlist + (ghostext[playernum].hits-1), victim);
+}
+
+void G_WriteAllGhostTics(void)
+{
+ if (!demobuf.p)
+ return;
+
+ UINT8 *save_demo_p = demobuf.p;
+#define CHECKSPACE(num) if (demobuf.p+(num) > demoend) { demobuf.p = save_demo_p; G_CheckDemoStatus(); return; }
+
+ boolean toobig = false;
+ INT32 i, counter = leveltime;
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (!playeringame[i] || players[i].spectator)
+ continue;
+
+ if (P_MobjWasRemoved(players[i].mo))
+ continue;
+
+ counter++;
+
+ if (multiplayer && ((counter % cv_netdemosyncquality.value) != 0)) // Only write 1 in this many ghost datas per tic to cut down on multiplayer replay size.
+ continue;
+
+ if (((ghostext[i].flags && (ghostext[i].flags & EZT_HIT)) || ghostext[i].hits)
+ && !ghostext[i].hitlist) // hitlist might be freed during resynch, beware PU_LEVEL!
+ {
+ ghostext[i].hits = 0;
+ continue;
+ }
+
+ CHECKSPACE(1);
+
+ WRITEUINT8(demobuf.p, i);
+ G_WriteGhostTic(players[i].mo, i);
+
+ // attention here for the ticcmd size!
+ // latest demos with mouse aiming byte in ticcmd
+ if (demobuf.p >= demoend - (13 + 9 + 9))
+ {
+ toobig = true;
+ break;
+ }
+ }
+
+ CHECKSPACE(1);
+ WRITEUINT8(demobuf.p, 0xFF);
+
+ if (toobig)
+ {
+ G_CheckDemoStatus(); // no more space
+ return;
+ }
+
+#undef CHECKSPACE
+}
+
+void G_WriteGhostTic(mobj_t *ghost, INT32 playernum)
+{
+ char ziptic = 0;
+ UINT8 *ziptic_p;
+ UINT32 i;
+ UINT8 sprite;
+ UINT8 frame;
+
+ if (!demobuf.p)
+ return;
+
+ UINT8 *save_demo_p = demobuf.p;
+#define CHECKSPACE(num) if (demobuf.p+(num) > demoend) { demobuf.p = save_demo_p; G_CheckDemoStatus(); return; }
+
+ if (!(demoflags & DF_GHOST))
+ return; // No ghost data to write.
+
+ if (ghost->player && ghost->player->pflags & PF_NIGHTSMODE && ghost->tracer)
+ {
+ // We're talking about the NiGHTS thing, not the normal platforming thing!
+ ziptic |= GZT_NIGHTS;
+ ghost = ghost->tracer;
+ }
+
+ ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
+
+#define MAXMOM (0x7FFF<<8)
+
+ // GZT_XYZ is only useful if you've moved 256 FRACUNITS or more in a single tic.
+ if (abs(ghost->x-oldghost[playernum].x) > MAXMOM
+ || abs(ghost->y-oldghost[playernum].y) > MAXMOM
+ || abs(ghost->z-oldghost[playernum].z) > MAXMOM
+ || ((UINT8)(leveltime & 255) > 0 && (UINT8)(leveltime & 255) <= (UINT8)cv_netdemosyncquality.value)) // Hack to enable slightly nicer resyncing
+ {
+ oldghost[playernum].x = ghost->x;
+ oldghost[playernum].y = ghost->y;
+ oldghost[playernum].z = ghost->z;
+ ziptic |= GZT_XYZ;
+
+ CHECKSPACE(sizeof(fixed_t)*3);
+ WRITEFIXED(demobuf.p, oldghost[playernum].x);
+ WRITEFIXED(demobuf.p, oldghost[playernum].y);
+ WRITEFIXED(demobuf.p, oldghost[playernum].z);
+ }
+ else
+ {
+ // For moving normally:
+ // Store one full byte of movement, plus one byte of fractional movement.
+ INT16 momx = (INT16)((ghost->x-oldghost[playernum].x + (1<<4))>>8);
+ INT16 momy = (INT16)((ghost->y-oldghost[playernum].y + (1<<4))>>8);
+
+ if (momx != oldghost[playernum].momx
+ || momy != oldghost[playernum].momy)
+ {
+ oldghost[playernum].momx = momx;
+ oldghost[playernum].momy = momy;
+ ziptic |= GZT_MOMXY;
+
+ CHECKSPACE(4);
+
+ WRITEINT16(demobuf.p, momx);
+ WRITEINT16(demobuf.p, momy);
+ }
+
+ momx = (INT16)((ghost->z-oldghost[playernum].z + (1<<4))>>8);
+
+ if (momx != oldghost[playernum].momz)
+ {
+ oldghost[playernum].momz = momx;
+ ziptic |= GZT_MOMZ;
+
+ CHECKSPACE(2);
+
+ WRITEINT16(demobuf.p, momx);
+ }
+
+ // This SHOULD set oldghost.x/y/z to match ghost->x/y/z
+ // but it keeps the fractional loss of one byte,
+ // so it will hopefully be made up for in future tics.
+ oldghost[playernum].x += oldghost[playernum].momx<<8;
+ oldghost[playernum].y += oldghost[playernum].momy<<8;
+ oldghost[playernum].z += oldghost[playernum].momz<<8;
+ }
+
+#undef MAXMOM
+
+ // Only store the 8 most relevant bits of angle
+ // because exact values aren't too easy to discern to begin with when only 8 angles have different sprites
+ // and it does not affect this mode of movement at all anyway.
+ if (ghost->angle>>24 != oldghost[playernum].angle)
+ {
+ oldghost[playernum].angle = ghost->angle>>24;
+ ziptic |= GZT_ANGLE;
+
+ CHECKSPACE(1);
+
+ WRITEUINT8(demobuf.p, oldghost[playernum].angle);
+ }
+
+ // Store the sprite frame.
+ frame = ghost->frame & 0xFF;
+ if (frame != oldghost[playernum].frame)
+ {
+ oldghost[playernum].frame = frame;
+ ziptic |= GZT_SPRITE;
+
+ CHECKSPACE(1);
+
+ WRITEUINT8(demobuf.p, oldghost[playernum].frame);
+ }
+
+ // Check for sprite set changes
+ sprite = ghost->sprite;
+ if (sprite != oldghost[playernum].sprite)
+ {
+ oldghost[playernum].sprite = sprite;
+ ghostext[playernum].flags |= EZT_SPRITE;
+ }
+
+ if (ghost->player)
+ {
+ if (
+ ghostext[playernum].kartitem != ghost->player->kartstuff[k_itemtype] ||
+ ghostext[playernum].kartamount != ghost->player->kartstuff[k_itemamount] ||
+ ghostext[playernum].kartbumpers != ghost->player->kartstuff[k_bumper]
+ )
+ {
+ ghostext[playernum].flags |= EZT_KART;
+ ghostext[playernum].kartitem = ghost->player->kartstuff[k_itemtype];
+ ghostext[playernum].kartamount = ghost->player->kartstuff[k_itemamount];
+ ghostext[playernum].kartbumpers = ghost->player->kartstuff[k_bumper];
+
+ }
+ }
+
+ if (ghostext[playernum].color == ghostext[playernum].lastcolor)
+ ghostext[playernum].flags &= ~EZT_COLOR;
+
+ if (ghostext[playernum].scale == ghostext[playernum].lastscale)
+ ghostext[playernum].flags &= ~EZT_SCALE;
+
+ if (ghostext[playernum].flags)
+ {
+ ziptic |= GZT_EXTRA;
+ WRITEUINT8(demobuf.p, ghostext[playernum].flags);
+
+ if (ghostext[playernum].flags & EZT_COLOR)
+ {
+ CHECKSPACE(1);
+ WRITEUINT8(demobuf.p, ghostext[playernum].color);
+ ghostext[playernum].lastcolor = ghostext[playernum].color;
+ }
+
+ if (ghostext[playernum].flags & EZT_SCALE)
+ {
+ CHECKSPACE(sizeof(fixed_t));
+ WRITEFIXED(demobuf.p, ghostext[playernum].scale);
+ ghostext[playernum].lastscale = ghostext[playernum].scale;
+ }
+
+ if (ghostext[playernum].flags & EZT_HIT)
+ {
+ CHECKSPACE(2);
+ WRITEUINT16(demobuf.p, ghostext[playernum].hits);
+
+ for (i = 0; i < ghostext[playernum].hits; i++)
+ {
+ mobj_t *mo = ghostext[playernum].hitlist[i];
+
+ CHECKSPACE(4+4+2+sizeof(fixed_t)*3+sizeof(angle_t));
+
+ WRITEUINT32(demobuf.p, UINT32_MAX); // reserved for some method of determining exactly which mobj this is. (mobjnum doesn't work here.)
+ WRITEUINT32(demobuf.p, mo->type);
+ WRITEUINT16(demobuf.p, (UINT16)mo->health);
+ WRITEFIXED(demobuf.p, mo->x);
+ WRITEFIXED(demobuf.p, mo->y);
+ WRITEFIXED(demobuf.p, mo->z);
+ WRITEANGLE(demobuf.p, mo->angle);
+ P_SetTarget(ghostext[playernum].hitlist+i, NULL);
+ }
+
+ ghostext[playernum].hits = 0;
+ }
+
+ if (ghostext[playernum].flags & EZT_SPRITE)
+ {
+ CHECKSPACE(1);
+ WRITEUINT8(demobuf.p, sprite);
+ }
+
+ if (ghostext[playernum].flags & EZT_KART)
+ {
+ CHECKSPACE(12);
+ WRITEINT32(demobuf.p, ghostext[playernum].kartitem);
+ WRITEINT32(demobuf.p, ghostext[playernum].kartamount);
+ WRITEINT32(demobuf.p, ghostext[playernum].kartbumpers);
+ }
+
+ ghostext[playernum].flags = 0;
+ }
+
+ *ziptic_p = ziptic;
+#undef CHECKSPACE
+}
+
+void G_ConsAllGhostTics(void)
+{
+ UINT8 p;
+
+ if (!demobuf.p || !demo.deferstart)
+ return;
+
+ p = READUINT8(demobuf.p);
+
+ while (p != 0xFF)
+ {
+ G_ConsGhostTic(p);
+ p = READUINT8(demobuf.p);
+ }
+
+ if (*demobuf.p == DEMOMARKER)
+ {
+ // end of demo data stream
+ G_CheckDemoStatus();
+ return;
+ }
+}
+
+// Uses ghost data to do consistency checks on your position.
+// This fixes desynchronising demos when fighting eggman.
+void G_ConsGhostTic(INT32 playernum)
+{
+ UINT8 ziptic;
+ fixed_t px,py,pz,gx,gy,gz;
+ mobj_t *testmo;
+ fixed_t syncleeway;
+ boolean nightsfail = false;
+
+ if (!(demoflags & DF_GHOST))
+ return; // No ghost data to use.
+
+ testmo = players[playernum].mo;
+
+ // Grab ghost data.
+ ziptic = READUINT8(demobuf.p);
+
+ if (ziptic & GZT_XYZ)
+ {
+ oldghost[playernum].x = READFIXED(demobuf.p);
+ oldghost[playernum].y = READFIXED(demobuf.p);
+ oldghost[playernum].z = READFIXED(demobuf.p);
+ syncleeway = 0;
+ }
+ else
+ {
+ if (ziptic & GZT_MOMXY)
+ {
+ oldghost[playernum].momx = READINT16(demobuf.p)<<8;
+ oldghost[playernum].momy = READINT16(demobuf.p)<<8;
+ }
+
+ if (ziptic & GZT_MOMZ)
+ oldghost[playernum].momz = READINT16(demobuf.p)<<8;
+
+ oldghost[playernum].x += oldghost[playernum].momx;
+ oldghost[playernum].y += oldghost[playernum].momy;
+ oldghost[playernum].z += oldghost[playernum].momz;
+ syncleeway = FRACUNIT;
+ }
+
+ if (ziptic & GZT_ANGLE)
+ demobuf.p++;
+
+ if (ziptic & GZT_SPRITE)
+ demobuf.p++;
+
+ if (ziptic & GZT_NIGHTS)
+ {
+ if (!testmo || !testmo->player || !(testmo->player->pflags & PF_NIGHTSMODE) || !testmo->tracer)
+ nightsfail = true;
+ else
+ testmo = testmo->tracer;
+ }
+
+ if (ziptic & GZT_EXTRA)
+ { // But wait, there's more!
+ ziptic = READUINT8(demobuf.p);
+ if (ziptic & EZT_COLOR)
+ demobuf.p++;
+
+ if (ziptic & EZT_SCALE)
+ demobuf.p += sizeof(fixed_t);
+
+ if (ziptic & EZT_HIT)
+ { // Resync mob damage.
+ UINT16 i, count = READUINT16(demobuf.p);
+ thinker_t *th;
+ mobj_t *mobj;
+
+ UINT32 type;
+ UINT16 health;
+ fixed_t x;
+ fixed_t y;
+ fixed_t z;
+
+ for (i = 0; i < count; i++)
+ {
+ demobuf.p += 4; // reserved.
+ type = READUINT32(demobuf.p);
+ health = READUINT16(demobuf.p);
+ x = READFIXED(demobuf.p);
+ y = READFIXED(demobuf.p);
+ z = READFIXED(demobuf.p);
+ demobuf.p += sizeof(angle_t); // angle, unnecessary for cons.
+
+ mobj = NULL;
+ for (th = thinkercap.next; th != &thinkercap; th = th->next)
+ {
+ if (th->function.acp1 != (actionf_p1)P_MobjThinker)
+ continue;
+ mobj = (mobj_t *)th;
+ if (mobj->type == (mobjtype_t)type && mobj->x == x && mobj->y == y && mobj->z == z)
+ break;
+ mobj = NULL; // wasn't this one, keep searching.
+ }
+
+ if (mobj && mobj->health != health) // Wasn't damaged?! This is desync! Fix it!
+ {
+ if (demosynced)
+ {
+ CONS_Alert(CONS_WARNING, M_GetText("Demo playback has desynced (health)!\n"));
+ CONS_Printf("expected health %d got %d\n", health, mobj->health);
+ }
+
+ demosynced = false;
+ P_DamageMobj(mobj, players[0].mo, players[0].mo, 1);
+ }
+ }
+ }
+
+ if (ziptic & EZT_SPRITE)
+ demobuf.p++;
+
+ if (ziptic & EZT_KART)
+ {
+ ghostext[playernum].kartitem = READINT32(demobuf.p);
+ ghostext[playernum].kartamount = READINT32(demobuf.p);
+ ghostext[playernum].kartbumpers = READINT32(demobuf.p);
+ }
+ }
+
+ if (testmo)
+ {
+ // Re-synchronise
+ px = testmo->x;
+ py = testmo->y;
+ pz = testmo->z;
+ gx = oldghost[playernum].x;
+ gy = oldghost[playernum].y;
+ gz = oldghost[playernum].z;
+
+ if (nightsfail || abs(px-gx) > syncleeway || abs(py-gy) > syncleeway || abs(pz-gz) > syncleeway)
+ {
+ ghostext[playernum].desyncframes++;
+
+ if (ghostext[playernum].desyncframes >= 2)
+ {
+ if (demosynced)
+ CONS_Alert(CONS_WARNING, "Demo playback has desynced (player %s)!\n", player_names[playernum]);
+ demosynced = false;
+
+ if (cv_resyncdemo.value)
+ {
+ P_UnsetThingPosition(testmo);
+ testmo->x = oldghost[playernum].x;
+ testmo->y = oldghost[playernum].y;
+ P_SetThingPosition(testmo);
+ testmo->z = oldghost[playernum].z;
+ }
+
+ if (abs(testmo->z - testmo->floorz) < 4*FRACUNIT)
+ testmo->z = testmo->floorz; // Sync players to the ground when they're likely supposed to be there...
+
+ ghostext[playernum].desyncframes = 2;
+ }
+ }
+ else
+ ghostext[playernum].desyncframes = 0;
+
+ if (
+#ifdef DEMO_COMPAT_100
+ demo.version != 0x0001 &&
+#endif
+ (
+ players[playernum].kartstuff[k_itemtype] != ghostext[playernum].kartitem ||
+ players[playernum].kartstuff[k_itemamount] != ghostext[playernum].kartamount ||
+ players[playernum].kartstuff[k_bumper] != ghostext[playernum].kartbumpers
+ )
+ )
+ {
+ if (demosynced)
+ {
+ CONS_Alert(CONS_WARNING, "Demo playback has desynced (item/bumpers)!(player %s)!\n", player_names[playernum]);
+ CONS_Printf("expected item type %d got %d\n", ghostext[playernum].kartitem, players[playernum].kartstuff[k_itemtype]);
+ CONS_Printf("expected item amount %d got %d\n", ghostext[playernum].kartamount, players[playernum].kartstuff[k_itemamount]);
+ }
+ demosynced = false;
+
+ players[playernum].kartstuff[k_itemtype] = ghostext[playernum].kartitem;
+ players[playernum].kartstuff[k_itemamount] = ghostext[playernum].kartamount;
+ players[playernum].kartstuff[k_bumper] = ghostext[playernum].kartbumpers;
+ }
+ }
+
+ if (*demobuf.p == DEMOMARKER)
+ {
+ // end of demo data stream
+ G_CheckDemoStatus();
+ return;
+ }
+}
+
+void G_GhostTicker(void)
+{
+ demoghost *g,*p;
+
+ for (g = ghosts, p = NULL; g; g = g->next)
+ {
+ // Skip normal demo data.
+ UINT8 ziptic = READUINT8(g->p);
+
+#ifdef DEMO_COMPAT_100
+ if (g->version != 0x0001)
+ {
+#endif
+ while (ziptic != DW_END) // Get rid of extradata stuff
+ {
+ if (ziptic == 0) // Only support player 0 info for now
+ {
+ ziptic = READUINT8(g->p);
+ if (ziptic & DXD_SKIN)
+ g->p += 18; // We _could_ read this info, but it shouldn't change anything in record attack...
+ if (ziptic & DXD_COLOR)
+ g->p += 16; // Same tbh
+ if (ziptic & DXD_NAME)
+ g->p += 16; // yea
+ if (ziptic & DXD_PLAYSTATE && READUINT8(g->p) != DXD_PST_PLAYING)
+ I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
+ }
+ else if (ziptic == DW_RNG)
+ g->p += 4; // RNG seed
+ else
+ I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
+
+ ziptic = READUINT8(g->p);
+ }
+
+ ziptic = READUINT8(g->p); // Back to actual ziptic stuff
+#ifdef DEMO_COMPAT_100
+ }
+#endif
+
+ if (ziptic & ZT_FWD)
+ g->p++;
+ if (ziptic & ZT_SIDE)
+ g->p++;
+ if (ziptic & ZT_ANGLE)
+ g->p += 2;
+ if (ziptic & ZT_BUTTONS)
+ g->p += 2;
+ if (ziptic & ZT_AIMING)
+ g->p += 2;
+ if (ziptic & ZT_DRIFT)
+ g->p += 2;
+ if (ziptic & ZT_LATENCY)
+ g->p += 1;
+
+ // Grab ghost data.
+ ziptic = READUINT8(g->p);
+
+#ifdef DEMO_COMPAT_100
+ if (g->version != 0x0001)
+ {
+#endif
+ if (ziptic == 0xFF)
+ goto skippedghosttic; // Didn't write ghost info this frame
+ else if (ziptic != 0)
+ I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
+ ziptic = READUINT8(g->p);
+#ifdef DEMO_COMPAT_100
+ }
+#endif
+ if (ziptic & GZT_XYZ)
+ {
+ g->oldmo.x = READFIXED(g->p);
+ g->oldmo.y = READFIXED(g->p);
+ g->oldmo.z = READFIXED(g->p);
+ }
+ else
+ {
+ if (ziptic & GZT_MOMXY)
+ {
+ g->oldmo.momx = READINT16(g->p)<<8;
+ g->oldmo.momy = READINT16(g->p)<<8;
+ }
+ if (ziptic & GZT_MOMZ)
+ g->oldmo.momz = READINT16(g->p)<<8;
+ g->oldmo.x += g->oldmo.momx;
+ g->oldmo.y += g->oldmo.momy;
+ g->oldmo.z += g->oldmo.momz;
+ }
+ if (ziptic & GZT_ANGLE)
+ g->oldmo.angle = READUINT8(g->p)<<24;
+ if (ziptic & GZT_SPRITE)
+ g->oldmo.frame = READUINT8(g->p);
+
+ // Update ghost
+ P_UnsetThingPosition(g->mo);
+ g->mo->x = g->oldmo.x;
+ g->mo->y = g->oldmo.y;
+ g->mo->z = g->oldmo.z;
+ P_SetThingPosition(g->mo);
+ g->mo->angle = g->oldmo.angle;
+ g->mo->frame = g->oldmo.frame | tr_trans30<p);
+ if (ziptic & EZT_COLOR)
+ {
+ g->color = READUINT8(g->p);
+ switch(g->color)
+ {
+ default:
+ case GHC_NORMAL: // Go back to skin color
+ g->mo->color = g->oldmo.color;
+ break;
+ // Handled below
+ case GHC_SUPER:
+ case GHC_INVINCIBLE:
+ break;
+ case GHC_FIREFLOWER: // Fireflower
+ g->mo->color = SKINCOLOR_WHITE;
+ break;
+ }
+ }
+ if (ziptic & EZT_FLIP)
+ g->mo->eflags ^= MFE_VERTICALFLIP;
+ if (ziptic & EZT_SCALE)
+ {
+ g->mo->destscale = READFIXED(g->p);
+ if (g->mo->destscale != g->mo->scale)
+ P_SetScale(g->mo, g->mo->destscale);
+ }
+ if (ziptic & EZT_THOKMASK)
+ { // Let's only spawn ONE of these per frame, thanks.
+ mobj_t *mobj;
+ INT32 type = -1;
+ if (g->mo->skin)
+ {
+ switch (ziptic & EZT_THOKMASK)
+ {
+ case EZT_THOK:
+ type = (UINT32)mobjinfo[MT_PLAYER].painchance;
+ break;
+ case EZT_SPIN:
+ type = (UINT32)mobjinfo[MT_PLAYER].damage;
+ break;
+ case EZT_REV:
+ type = (UINT32)mobjinfo[MT_PLAYER].raisestate;
+ break;
+ }
+ }
+ if (type != -1)
+ {
+ if (type == MT_GHOST)
+ {
+ mobj = P_SpawnGhostMobj(g->mo); // does a large portion of the work for us
+ mobj->frame = (mobj->frame & ~FF_FRAMEMASK)|tr_trans60<mo->x, g->mo->y, g->mo->z - FixedDiv(FixedMul(g->mo->info->height, g->mo->scale) - g->mo->height,3*FRACUNIT), MT_THOK);
+ mobj->sprite = states[mobjinfo[type].spawnstate].sprite;
+ mobj->frame = (states[mobjinfo[type].spawnstate].frame & FF_FRAMEMASK) | tr_trans60<tics = -1; // nope.
+ mobj->color = g->mo->color;
+ if (g->mo->eflags & MFE_VERTICALFLIP)
+ {
+ mobj->flags2 |= MF2_OBJECTFLIP;
+ mobj->eflags |= MFE_VERTICALFLIP;
+ }
+ P_SetScale(mobj, g->mo->scale);
+ mobj->destscale = g->mo->scale;
+ }
+ mobj->floorz = mobj->z;
+ mobj->ceilingz = mobj->z+mobj->height;
+ P_UnsetThingPosition(mobj);
+ mobj->flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY; // make an ATTEMPT to curb crazy SOCs fucking stuff up...
+ P_SetThingPosition(mobj);
+ mobj->fuse = 8;
+ P_SetTarget(&mobj->target, g->mo);
+ }
+ }
+ if (ziptic & EZT_HIT)
+ { // Spawn hit poofs for killing things!
+ UINT16 i, count = READUINT16(g->p), health;
+ //UINT32 type;
+ fixed_t x,y,z;
+ angle_t angle;
+ mobj_t *poof;
+ for (i = 0; i < count; i++)
+ {
+ g->p += 4; // reserved
+ g->p += 4; // backwards compat., type used to be here
+ health = READUINT16(g->p);
+ x = READFIXED(g->p);
+ y = READFIXED(g->p);
+ z = READFIXED(g->p);
+ angle = READANGLE(g->p);
+ if (health != 0 || i >= 4) // only spawn for the first 4 hits per frame, to prevent ghosts from splode-spamming too bad.
+ continue;
+ poof = P_SpawnMobj(x, y, z, MT_GHOST);
+ poof->angle = angle;
+ poof->flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY; // make an ATTEMPT to curb crazy SOCs fucking stuff up...
+ poof->health = 0;
+ P_SetMobjStateNF(poof, S_XPLD1);
+ }
+ }
+ if (ziptic & EZT_SPRITE)
+ g->mo->sprite = READUINT8(g->p);
+ if (ziptic & EZT_KART)
+ g->p += 12; // kartitem, kartamount, kartbumpers
+ }
+
+#ifdef DEMO_COMPAT_100
+ if (g->version != 0x0001)
+ {
+#endif
+ if (READUINT8(g->p) != 0xFF) // Make sure there isn't other ghost data here.
+ I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
+#ifdef DEMO_COMPAT_100
+ }
+#endif
+
+skippedghosttic:
+ // Tick ghost colors (Super and Mario Invincibility flashing)
+ switch(g->color)
+ {
+ case GHC_SUPER: // Super Sonic (P_DoSuperStuff)
+ g->mo->color = SKINCOLOR_SUPER1;
+ g->mo->color += abs( ( (signed)( (unsigned)leveltime >> 1 ) % 9) - 4);
+ break;
+ case GHC_INVINCIBLE: // Mario invincibility (P_CheckInvincibilityTimer)
+ g->mo->color = (UINT8)(leveltime % MAXSKINCOLORS);
+ break;
+ default:
+ break;
+ }
+
+ // Demo ends after ghost data.
+ if (*g->p == DEMOMARKER)
+ {
+ g->mo->momx = g->mo->momy = g->mo->momz = 0;
+ if (p)
+ p->next = g->next;
+ else
+ ghosts = g->next;
+ Z_Free(g);
+ continue;
+ }
+ p = g;
+ }
+}
+
+// Demo rewinding functions
+typedef struct rewindinfo_s {
+ tic_t leveltime;
+
+ struct {
+ boolean ingame;
+ player_t player;
+ mobj_t mobj;
+ } playerinfo[MAXPLAYERS];
+
+ struct rewindinfo_s *prev;
+} rewindinfo_t;
+
+static tic_t currentrewindnum;
+static rewindinfo_t *rewindhead = NULL; // Reverse chronological order
+
+void G_InitDemoRewind(void)
+{
+ CL_ClearRewinds();
+
+ while (rewindhead)
+ {
+ rewindinfo_t *p = rewindhead->prev;
+ Z_Free(rewindhead);
+ rewindhead = p;
+ }
+
+ currentrewindnum = 0;
+}
+
+void G_StoreRewindInfo(void)
+{
+ static UINT8 timetolog = 8;
+ rewindinfo_t *info;
+ size_t i;
+
+ if (timetolog-- > 0)
+ return;
+ timetolog = 8;
+
+ info = Z_Calloc(sizeof(rewindinfo_t), PU_STATIC, NULL);
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (!playeringame[i] || players[i].spectator)
+ {
+ info->playerinfo[i].ingame = false;
+ continue;
+ }
+
+ info->playerinfo[i].ingame = true;
+ memcpy(&info->playerinfo[i].player, &players[i], sizeof(player_t));
+ if (players[i].mo)
+ memcpy(&info->playerinfo[i].mobj, players[i].mo, sizeof(mobj_t));
+ }
+
+ info->leveltime = leveltime;
+ info->prev = rewindhead;
+ rewindhead = info;
+}
+
+void G_PreviewRewind(tic_t previewtime)
+{
+ SINT8 i;
+ size_t j;
+ fixed_t tweenvalue = 0;
+ rewindinfo_t *info = rewindhead, *next_info = rewindhead;
+
+ if (!info)
+ return;
+
+ while (info->leveltime > previewtime && info->prev)
+ {
+ next_info = info;
+ info = info->prev;
+ }
+ if (info != next_info)
+ tweenvalue = FixedDiv(previewtime - info->leveltime, next_info->leveltime - info->leveltime);
+
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (!playeringame[i] || players[i].spectator)
+ {
+ if (info->playerinfo[i].player.mo)
+ {
+ //@TODO spawn temp object to act as a player display
+ }
+
+ continue;
+ }
+
+ if (!info->playerinfo[i].ingame || !info->playerinfo[i].player.mo)
+ {
+ if (players[i].mo)
+ players[i].mo->flags2 |= MF2_DONTDRAW;
+
+ continue;
+ }
+
+ if (!players[i].mo)
+ continue; //@TODO spawn temp object to act as a player display
+
+ players[i].mo->flags2 &= ~MF2_DONTDRAW;
+
+ P_UnsetThingPosition(players[i].mo);
+#define TWEEN(pr) info->playerinfo[i].mobj.pr + FixedMul((INT32) (next_info->playerinfo[i].mobj.pr - info->playerinfo[i].mobj.pr), tweenvalue)
+ players[i].mo->x = TWEEN(x);
+ players[i].mo->y = TWEEN(y);
+ players[i].mo->z = TWEEN(z);
+ players[i].mo->angle = TWEEN(angle);
+#undef TWEEN
+ P_SetThingPosition(players[i].mo);
+
+ players[i].frameangle = info->playerinfo[i].player.frameangle + FixedMul((INT32) (next_info->playerinfo[i].player.frameangle - info->playerinfo[i].player.frameangle), tweenvalue);
+
+ players[i].mo->sprite = info->playerinfo[i].mobj.sprite;
+ players[i].mo->frame = info->playerinfo[i].mobj.frame;
+
+ players[i].realtime = info->playerinfo[i].player.realtime;
+ for (j = 0; j < NUMKARTSTUFF; j++)
+ players[i].kartstuff[j] = info->playerinfo[i].player.kartstuff[j];
+ }
+
+ for (i = splitscreen; i >= 0; i--)
+ P_ResetCamera(&players[displayplayers[i]], &camera[i]);
+}
+
+void G_ConfirmRewind(tic_t rewindtime)
+{
+ SINT8 i;
+ tic_t j;
+ boolean oldmenuactive = menuactive, oldsounddisabled = sound_disabled;
+
+ INT32 olddp1 = displayplayers[0], olddp2 = displayplayers[1], olddp3 = displayplayers[2], olddp4 = displayplayers[3];
+ UINT8 oldss = splitscreen;
+
+ menuactive = false; // Prevent loops
+
+ CV_StealthSetValue(&cv_renderview, 0);
+
+ if (rewindtime <= starttime)
+ {
+ demo.rewinding = false;
+ G_DoPlayDemo(NULL); // Restart the current demo
+ }
+ else
+ {
+ rewind_t *rewind;
+ sound_disabled = true; // Prevent sound spam
+ demo.rewinding = true;
+
+ rewind = CL_RewindToTime(rewindtime);
+
+ if (rewind)
+ {
+ demobuf.p = demobuf.buffer + rewind->demopos;
+ memcpy(oldcmd, rewind->oldcmd, sizeof (oldcmd));
+ memcpy(oldghost, rewind->oldghost, sizeof (oldghost));
+ paused = false;
+ }
+ else
+ {
+ demo.rewinding = true;
+ G_DoPlayDemo(NULL); // Restart the current demo
+ }
+ }
+
+ for (j = 0; j < rewindtime && leveltime < rewindtime; j++)
+ {
+ G_Ticker((j % NEWTICRATERATIO) == 0);
+ }
+
+ demo.rewinding = false;
+ menuactive = oldmenuactive; // Bring the menu back up
+ sound_disabled = oldsounddisabled; // Re-enable SFX
+
+ wipegamestate = gamestate; // No fading back in!
+
+ COM_BufInsertText("renderview on\n");
+
+ splitscreen = oldss;
+ displayplayers[0] = olddp1;
+ displayplayers[1] = olddp2;
+ displayplayers[2] = olddp3;
+ displayplayers[3] = olddp4;
+ R_ExecuteSetViewSize();
+ G_ResetViews();
+
+ for (i = splitscreen; i >= 0; i--)
+ P_ResetCamera(&players[displayplayers[i]], &camera[i]);
+}
+
+void G_ReadMetalTic(mobj_t *metal)
+{
+ UINT8 ziptic;
+ UINT16 speed;
+ UINT8 statetype;
+
+ if (!metal_p)
+ return;
+ ziptic = READUINT8(metal_p);
+
+ // Read changes from the tic
+ if (ziptic & GZT_XYZ)
+ {
+ oldmetal.x = READFIXED(metal_p);
+ oldmetal.y = READFIXED(metal_p);
+ oldmetal.z = READFIXED(metal_p);
+ P_MoveOrigin(metal, oldmetal.x, oldmetal.y, oldmetal.z);
+ oldmetal.x = metal->x;
+ oldmetal.y = metal->y;
+ oldmetal.z = metal->z;
+ }
+ else
+ {
+ if (ziptic & GZT_MOMXY)
+ {
+ oldmetal.momx = READINT16(metal_p)<<8;
+ oldmetal.momy = READINT16(metal_p)<<8;
+ }
+ if (ziptic & GZT_MOMZ)
+ oldmetal.momz = READINT16(metal_p)<<8;
+ oldmetal.x += oldmetal.momx;
+ oldmetal.y += oldmetal.momy;
+ oldmetal.z += oldmetal.momz;
+ }
+ if (ziptic & GZT_ANGLE)
+ oldmetal.angle = READUINT8(metal_p)<<24;
+ if (ziptic & GZT_SPRITE)
+ metal_p++; // Currently unused. (Metal Sonic figures out what he's doing his own damn self.)
+
+ // Set movement, position, and angle
+ // oldmetal contains where you're supposed to be.
+ metal->momx = oldmetal.momx;
+ metal->momy = oldmetal.momy;
+ metal->momz = oldmetal.momz;
+ P_UnsetThingPosition(metal);
+ metal->x = oldmetal.x;
+ metal->y = oldmetal.y;
+ metal->z = oldmetal.z;
+ P_SetThingPosition(metal);
+ metal->angle = oldmetal.angle;
+
+ if (ziptic & GZT_EXTRA)
+ { // But wait, there's more!
+ ziptic = READUINT8(metal_p);
+ if (ziptic & EZT_FLIP)
+ metal->eflags ^= MFE_VERTICALFLIP;
+ if (ziptic & EZT_SCALE)
+ {
+ metal->destscale = READFIXED(metal_p);
+ if (metal->destscale != metal->scale)
+ P_SetScale(metal, metal->destscale);
+ }
+ }
+
+ // Calculates player's speed based on distance-of-a-line formula
+ speed = FixedDiv(P_AproxDistance(oldmetal.momx, oldmetal.momy), metal->scale)>>FRACBITS;
+
+ // Use speed to decide an appropriate state
+ if (speed > 20) // default skin runspeed
+ statetype = 2;
+ else if (speed > 1) // stopspeed
+ statetype = 1;
+ else
+ statetype = 0;
+
+ // Set state
+ if (statetype != metal->threshold)
+ {
+ switch (statetype)
+ {
+ case 2: // run
+ P_SetMobjState(metal,metal->info->meleestate);
+ break;
+ case 1: // walk
+ P_SetMobjState(metal,metal->info->seestate);
+ break;
+ default: // stand
+ P_SetMobjState(metal,metal->info->spawnstate);
+ break;
+ }
+ metal->threshold = statetype;
+ }
+
+ // TODO: Modify state durations based on movement speed, similar to players?
+
+ if (*metal_p == DEMOMARKER)
+ {
+ // end of demo data stream
+ G_StopMetalDemo();
+ return;
+ }
+}
+
+void G_WriteMetalTic(mobj_t *metal)
+{
+ UINT8 ziptic = 0;
+ UINT8 *ziptic_p;
+
+ if (!demobuf.p) // demobuf.p will be NULL until the race start linedef executor is triggered!
+ return;
+
+ ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
+
+ #define MAXMOM (0xFFFF<<8)
+
+ // GZT_XYZ is only useful if you've moved 256 FRACUNITS or more in a single tic.
+ if (abs(metal->x-oldmetal.x) > MAXMOM
+ || abs(metal->y-oldmetal.y) > MAXMOM
+ || abs(metal->z-oldmetal.z) > MAXMOM)
+ {
+ oldmetal.x = metal->x;
+ oldmetal.y = metal->y;
+ oldmetal.z = metal->z;
+ WRITEFIXED(demobuf.p,oldmetal.x);
+ WRITEFIXED(demobuf.p,oldmetal.y);
+ WRITEFIXED(demobuf.p,oldmetal.z);
+ ziptic |= GZT_XYZ;
+ }
+ else
+ {
+ // For moving normally:
+ // Store one full byte of movement, plus one byte of fractional movement.
+ INT16 momx = (INT16)((metal->x-oldmetal.x)>>8);
+ INT16 momy = (INT16)((metal->y-oldmetal.y)>>8);
+ if (momx != oldmetal.momx
+ || momy != oldmetal.momy)
+ {
+ oldmetal.momx = momx;
+ oldmetal.momy = momy;
+ WRITEINT16(demobuf.p,momx);
+ WRITEINT16(demobuf.p,momy);
+ ziptic |= GZT_MOMXY;
+ }
+ momx = (INT16)((metal->z-oldmetal.z)>>8);
+ if (momx != oldmetal.momz)
+ {
+ oldmetal.momz = momx;
+ WRITEINT16(demobuf.p,momx);
+ ziptic |= GZT_MOMZ;
+ }
+
+ // This SHOULD set oldmetal.x/y/z to match metal->x/y/z
+ // but it keeps the fractional loss of one byte,
+ // so it will hopefully be made up for in future tics.
+ oldmetal.x += oldmetal.momx<<8;
+ oldmetal.y += oldmetal.momy<<8;
+ oldmetal.z += oldmetal.momz<<8;
+ }
+
+ #undef MAXMOM
+
+ // Only store the 8 most relevant bits of angle
+ // because exact values aren't too easy to discern to begin with when only 8 angles have different sprites
+ // and it does not affect movement at all anyway.
+ if (metal->angle>>24 != oldmetal.angle)
+ {
+ oldmetal.angle = metal->angle>>24;
+ WRITEUINT8(demobuf.p,oldmetal.angle);
+ ziptic |= GZT_ANGLE;
+ }
+
+ // Metal Sonic does not need our state changes.
+ // ... currently.
+
+ {
+ UINT8 *exttic_p = NULL;
+ UINT8 exttic = 0;
+ if ((metal->eflags & MFE_VERTICALFLIP) != (oldmetal.eflags & MFE_VERTICALFLIP))
+ {
+ if (!exttic_p)
+ exttic_p = demobuf.p++;
+ exttic |= EZT_FLIP;
+ oldmetal.eflags ^= MFE_VERTICALFLIP;
+ }
+ if (metal->scale != oldmetal.scale)
+ {
+ if (!exttic_p)
+ exttic_p = demobuf.p++;
+ exttic |= EZT_SCALE;
+ WRITEFIXED(demobuf.p,metal->scale);
+ oldmetal.scale = metal->scale;
+ }
+ if (exttic_p)
+ {
+ *exttic_p = exttic;
+ ziptic |= GZT_EXTRA;
+ }
+ }
+
+ *ziptic_p = ziptic;
+
+ // attention here for the ticcmd size!
+ // latest demos with mouse aiming byte in ticcmd
+ if (demobuf.p >= demoend - 32)
+ {
+ G_StopMetalRecording(); // no more space
+ return;
+ }
+}
+
+//
+// G_RecordDemo
+//
+void G_RecordDemo(const char *name)
+{
+ INT32 maxsize;
+
+ demobuf.p = NULL;
+ G_ResetDemoRecording();
+ demoend = NULL;
+
+ if (cv_recordmultiplayerdemos.value)
+ {
+ CONS_Printf("Recording demo %s.lmp\n", name);
+
+ strcpy(demoname, name);
+ strcat(demoname, ".lmp");
+
+ maxsize = cv_maxdemosize.value*1024*1024;
+
+ demobuf.buffer = Z_Malloc(maxsize + 100*1024, PU_STATIC, NULL);
+ demoend = demobuf.buffer + maxsize;
+
+ if (demobuf.buffer)
+ demo.recording = true;
+ else
+ CONS_Alert(CONS_ERROR, "Failed to allocate demo buffer\n");
+ }
+}
+
+void G_RecordMetal(void)
+{
+ INT32 maxsize;
+ maxsize = cv_maxdemosize.value*1024*1024;
+ if (demobuf.buffer)
+ Z_Free(demobuf.buffer);
+ demobuf.p = NULL;
+ metalrecording = false;
+ demobuf.buffer = Z_Malloc(maxsize + 100*1024, PU_STATIC, NULL);
+ demoend = demobuf.buffer + maxsize;
+
+ if (demobuf.buffer)
+ metalrecording = true;
+ else
+ CONS_Alert(CONS_ERROR, "Failed to allocate demo buffer\n");
+}
+
+void G_BeginRecording(void)
+{
+ UINT8 i, p;
+ char name[17];
+ player_t *player = &players[consoleplayer];
+
+ char *filename;
+ UINT8 totalfiles;
+ UINT8 *m;
+
+ if (!cv_recordmultiplayerdemos.value)
+ {
+ G_ResetDemoRecording();
+ return;
+ }
+
+ if (demobuf.buffer == NULL)
+ {
+ CONS_Alert(CONS_ERROR, "No demo buffer allocated\n");
+ G_ResetDemoRecording();
+ return;
+ }
+
+ if (demobuf.p)
+ {
+ G_ResetDemoRecording();
+ return;
+ }
+
+ memset(name,0,sizeof(name));
+
+ demobuf.p = demobuf.buffer;
+ demoflags = DF_GHOST|(multiplayer ? DF_MULTIPLAYER : (modeattacking<important)
+ {
+ nameonly(( filename = va("%s", wadfiles[i]->filename) ));
+ WRITESTRINGL(demobuf.p, filename, MAX_WADPATH);
+ WRITEMEM(demobuf.p, wadfiles[i]->md5sum, 16);
+
+ totalfiles++;
+ }
+
+ WRITEUINT8(m, totalfiles);
+
+ switch ((demoflags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
+ {
+ case ATTACKING_NONE: // 0
+ break;
+ case ATTACKING_RECORD: // 1
+ demotime_p = demobuf.p;
+ WRITEUINT32(demobuf.p,UINT32_MAX); // time
+ WRITEUINT32(demobuf.p,UINT32_MAX); // lap
+ break;
+ default: // 3
+ break;
+ }
+
+ WRITEUINT32(demobuf.p, P_GetInitSeed());
+
+ // Reserved for extrainfo location from start of file
+ demoinfo_p = demobuf.p;
+ WRITEUINT32(demobuf.p, 0);
+
+ // Save netvars
+ CV_SaveNetVars(&demobuf.p, true);
+
+ // Now store some info for each in-game player
+ for (p = 0; p < MAXPLAYERS; p++)
+ {
+ if (!playeringame[p])
+ continue;
+
+ player = &players[p];
+
+ WRITEUINT8(demobuf.p, p | (player->spectator ? DEMO_SPECTATOR : 0));
+
+ // Name
+ memset(name, 0, 16);
+ memcpy(name, player_names[p], 15);
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+
+ // Skin
+ memset(name, 0, 16);
+ strncpy(name, skins[player->skin].name, 16);
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+
+ // Color
+ memset(name, 0, 16);
+ strncpy(name, KartColor_Names[player->skincolor], 16);
+ M_Memcpy(demobuf.p,name,16);
+ demobuf.p += 16;
+
+ // Score, since Kart uses this to determine where you start on the map
+ WRITEUINT32(demobuf.p, player->score);
+
+ // Kart speed and weight
+ WRITEUINT8(demobuf.p, skins[player->skin].kartspeed);
+ WRITEUINT8(demobuf.p, skins[player->skin].kartweight);
+ }
+
+ WRITEUINT8(demobuf.p, 0xFF); // Denote the end of the player listing
+
+ // player lua vars, always saved even if empty... Unless it's record attack.
+ if (demoflags & DF_LUAVARS)
+ LUA_Archive(&demobuf, false);
+
+ memset(&oldcmd,0,sizeof(oldcmd));
+ memset(&oldghost,0,sizeof(oldghost));
+ memset(&ghostext,0,sizeof(ghostext));
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ ghostext[i].lastcolor = ghostext[i].color = GHC_NORMAL;
+ ghostext[i].lastscale = ghostext[i].scale = FRACUNIT;
+
+ if (players[i].mo)
+ {
+ oldghost[i].x = players[i].mo->x;
+ oldghost[i].y = players[i].mo->y;
+ oldghost[i].z = players[i].mo->z;
+ oldghost[i].angle = players[i].mo->angle;
+
+ // preticker started us gravity flipped
+ if (players[i].mo->eflags & MFE_VERTICALFLIP)
+ ghostext[i].flags |= EZT_FLIP;
+ }
+ }
+}
+
+void G_BeginMetal(void)
+{
+ mobj_t *mo = players[consoleplayer].mo;
+
+ if (demobuf.buffer == NULL)
+ {
+ CONS_Alert(CONS_ERROR, "No metal demo buffer allocated\n");
+ metalrecording = false;
+ return;
+ }
+
+ if (demobuf.p)
+ {
+ Z_Free(demobuf.buffer);
+ demobuf.buffer = NULL;
+ metalrecording = false;
+ return;
+ }
+
+ demobuf.p = demobuf.buffer;
+
+ // Write header.
+ M_Memcpy(demobuf.p, DEMOHEADER, 12); demobuf.p += 12;
+ WRITEUINT8(demobuf.p,VERSION);
+ WRITEUINT8(demobuf.p,SUBVERSION);
+ WRITEUINT16(demobuf.p,DEMOVERSION);
+
+ // demo checksum
+ demobuf.p += 16;
+
+ M_Memcpy(demobuf.p, "METL", 4); demobuf.p += 4;
+
+ // Set up our memory.
+ memset(&oldmetal,0,sizeof(oldmetal));
+ oldmetal.x = mo->x;
+ oldmetal.y = mo->y;
+ oldmetal.z = mo->z;
+ oldmetal.angle = mo->angle;
+}
+
+void G_WriteStanding(UINT8 ranking, char *name, INT32 skinnum, UINT8 color, UINT32 val)
+{
+ char temp[17];
+
+ if (!demobuf.p)
+ return;
+
+ if (demoinfo_p && *(UINT32 *)demoinfo_p == 0 && demobuf.buffer != NULL)
+ {
+ WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
+ *(UINT32 *)demoinfo_p = demobuf.p - demobuf.buffer;
+ }
+
+ WRITEUINT8(demobuf.p, DW_STANDING);
+ WRITEUINT8(demobuf.p, ranking);
+
+ // Name
+ memset(temp, 0, 16);
+ strncpy(temp, name, 16);
+ M_Memcpy(demobuf.p,temp,16);
+ demobuf.p += 16;
+
+ // Skin
+ memset(temp, 0, 16);
+ strncpy(temp, skins[skinnum].name, 16);
+ M_Memcpy(demobuf.p,temp,16);
+ demobuf.p += 16;
+
+ // Color
+ memset(temp, 0, 16);
+ strncpy(temp, KartColor_Names[color], 16);
+ M_Memcpy(demobuf.p,temp,16);
+ demobuf.p += 16;
+
+ // Score/time/whatever
+ WRITEUINT32(demobuf.p, val);
+}
+
+void G_SetDemoTime(UINT32 ptime, UINT32 plap)
+{
+ if (!demo.recording || !demotime_p)
+ return;
+ if (demoflags & DF_RECORDATTACK)
+ {
+ WRITEUINT32(demotime_p, ptime);
+ WRITEUINT32(demotime_p, plap);
+ demotime_p = NULL;
+ }
+}
+
+static void G_LoadDemoExtraFiles(UINT8 **pp)
+{
+ UINT8 totalfiles;
+ char filename[MAX_WADPATH];
+ UINT8 md5sum[16];
+ filestatus_t ncs = FS_NOTFOUND;
+ boolean toomany = false;
+ boolean alreadyloaded;
+ UINT8 i, j;
+
+ totalfiles = READUINT8((*pp));
+ for (i = 0; i < totalfiles; ++i)
+ {
+ if (toomany)
+ SKIPSTRING((*pp));
+ else
+ {
+ strlcpy(filename, (char *)(*pp), sizeof filename);
+ SKIPSTRING((*pp));
+ }
+ READMEM((*pp), md5sum, 16);
+
+ if (!toomany)
+ {
+ alreadyloaded = false;
+
+ for (j = 0; j < numwadfiles; ++j)
+ {
+ if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0)
+ {
+ alreadyloaded = true;
+ break;
+ }
+ }
+
+ if (alreadyloaded)
+ continue;
+
+ if (numwadfiles >= MAX_WADFILES)
+ toomany = true;
+ else
+ ncs = findfile(filename, md5sum, false);
+
+ if (toomany)
+ {
+ CONS_Alert(CONS_WARNING, M_GetText("Too many files loaded to add anymore for demo playback\n"));
+ if (!CON_Ready())
+ M_StartMessage(M_GetText("There are too many files loaded to add this demo's addons.\n\nDemo playback may desync.\n\nPress ESC\n"), NULL, MM_NOTHING);
+ }
+ else if (ncs != FS_FOUND)
+ {
+ if (ncs == FS_NOTFOUND)
+ CONS_Alert(CONS_NOTICE, M_GetText("You do not have a copy of %s\n"), filename);
+ else if (ncs == FS_MD5SUMBAD)
+ CONS_Alert(CONS_NOTICE, M_GetText("Checksum mismatch on %s\n"), filename);
+ else
+ CONS_Alert(CONS_NOTICE, M_GetText("Unknown error finding file %s\n"), filename);
+
+ if (!CON_Ready())
+ M_StartMessage(M_GetText("There were errors trying to add this demo's addons. Check the console for more information.\n\nDemo playback may desync.\n\nPress ESC\n"), NULL, MM_NOTHING);
+ }
+ else
+ {
+ P_PartialAddWadFile(filename, false);
+ }
+ }
+ }
+
+ if (P_PartialAddGetStage() >= 0)
+ P_MultiSetupWadFiles(true); // in case any partial adds were done
+}
+
+static void G_SkipDemoExtraFiles(UINT8 **pp)
+{
+ UINT8 totalfiles;
+ UINT8 i;
+
+ totalfiles = READUINT8((*pp));
+ for (i = 0; i < totalfiles; ++i)
+ {
+ SKIPSTRING((*pp));// file name
+ (*pp) += 16;// md5
+ }
+}
+
+// G_CheckDemoExtraFiles: checks if our loaded WAD list matches the demo's.
+// Enabling quick prevents filesystem checks to see if needed files are available to load.
+static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick)
+{
+ UINT8 totalfiles, filesloaded, nmusfilecount;
+ char filename[MAX_WADPATH];
+ UINT8 md5sum[16];
+ boolean toomany = false;
+ boolean alreadyloaded;
+ UINT8 i, j;
+ UINT8 error = 0;
+
+ totalfiles = READUINT8((*pp));
+ filesloaded = 0;
+ for (i = 0; i < totalfiles; ++i)
+ {
+ if (toomany)
+ SKIPSTRING((*pp));
+ else
+ {
+ strlcpy(filename, (char *)(*pp), sizeof filename);
+ SKIPSTRING((*pp));
+ }
+ READMEM((*pp), md5sum, 16);
+
+ if (!toomany)
+ {
+ alreadyloaded = false;
+ nmusfilecount = 0;
+
+ for (j = 0; j < numwadfiles; ++j)
+ {
+ if (wadfiles[j]->important && j > mainwads)
+ nmusfilecount++;
+ else
+ continue;
+
+ if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0)
+ {
+ alreadyloaded = true;
+
+ if (i != nmusfilecount-1 && error < DFILE_ERROR_OUTOFORDER)
+ error |= DFILE_ERROR_OUTOFORDER;
+
+ break;
+ }
+ }
+
+ if (alreadyloaded)
+ {
+ filesloaded++;
+ continue;
+ }
+
+ if (numwadfiles >= MAX_WADFILES)
+ error = DFILE_ERROR_CANNOTLOAD;
+ else if (!quick && findfile(filename, md5sum, false) != FS_FOUND)
+ error = DFILE_ERROR_CANNOTLOAD;
+ else if (error < DFILE_ERROR_INCOMPLETEOUTOFORDER)
+ error |= DFILE_ERROR_NOTLOADED;
+ } else
+ error = DFILE_ERROR_CANNOTLOAD;
+ }
+
+ // Get final file count
+ nmusfilecount = 0;
+
+ for (j = 0; j < numwadfiles; ++j)
+ if (wadfiles[j]->important && j > mainwads)
+ nmusfilecount++;
+
+ if (!error && filesloaded < nmusfilecount)
+ error = DFILE_ERROR_EXTRAFILES;
+
+ return error;
+}
+
+// Returns bitfield:
+// 1 == new demo has lower time
+// 2 == new demo has higher score
+// 4 == new demo has higher rings
+UINT8 G_CmpDemoTime(char *oldname, char *newname)
+{
+ UINT8 *buffer,*p;
+ UINT8 flags;
+ UINT32 oldtime, newtime, oldlap, newlap;
+ UINT16 oldversion;
+ size_t bufsize ATTRUNUSED;
+ UINT8 c;
+ UINT16 s ATTRUNUSED;
+ UINT8 aflags = 0;
+
+ // load the new file
+ FIL_DefaultExtension(newname, ".lmp");
+ bufsize = FIL_ReadFile(newname, &buffer);
+ I_Assert(bufsize != 0);
+ p = buffer;
+
+ // read demo header
+ I_Assert(!memcmp(p, DEMOHEADER, 12));
+ p += 12; // DEMOHEADER
+ c = READUINT8(p); // VERSION
+ I_Assert(c == VERSION);
+ c = READUINT8(p); // SUBVERSION
+ I_Assert(c == SUBVERSION);
+ s = READUINT16(p);
+ I_Assert(s == DEMOVERSION);
+ p += 64; // full demo title
+ p += 16; // demo checksum
+ I_Assert(!memcmp(p, "PLAY", 4));
+ p += 4; // PLAY
+ p += 2; // gamemap
+ p += 16; // map md5
+ flags = READUINT8(p); // demoflags
+ p++; // gametype
+ G_SkipDemoExtraFiles(&p);
+
+ aflags = flags & (DF_RECORDATTACK|DF_NIGHTSATTACK);
+ I_Assert(aflags);
+ if (flags & DF_RECORDATTACK)
+ {
+ newtime = READUINT32(p);
+ newlap = READUINT32(p);
+ }
+ else // appease compiler
+ return 0;
+
+ Z_Free(buffer);
+
+ // load old file
+ FIL_DefaultExtension(oldname, ".lmp");
+ if (!FIL_ReadFile(oldname, &buffer))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), oldname);
+ return UINT8_MAX;
+ }
+ p = buffer;
+
+ // read demo header
+ if (memcmp(p, DEMOHEADER, 12))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
+ Z_Free(buffer);
+ return UINT8_MAX;
+ } p += 12; // DEMOHEADER
+ p++; // VERSION
+ p++; // SUBVERSION
+ oldversion = READUINT16(p);
+ switch(oldversion) // demoversion
+ {
+ case DEMOVERSION: // latest always supported
+ p += 64; // full demo title
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ // Old replays gotta go :]
+ CONS_Alert(CONS_NOTICE, M_GetText("File '%s' outdated version. It will be overwritten. Nyeheheh.\n"), oldname);
+ Z_Free(buffer);
+ return UINT8_MAX;
+#endif
+ // too old, cannot support.
+ default:
+ CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
+ Z_Free(buffer);
+ return UINT8_MAX;
+ }
+ p += 16; // demo checksum
+ if (memcmp(p, "PLAY", 4))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
+ Z_Free(buffer);
+ return UINT8_MAX;
+ } p += 4; // "PLAY"
+ p += 2; // gamemap
+ p += 16; // mapmd5
+ flags = READUINT8(p);
+ p++; // gametype
+ G_SkipDemoExtraFiles(&p);
+ if (!(flags & aflags))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("File '%s' not from same game mode. It will be overwritten.\n"), oldname);
+ Z_Free(buffer);
+ return UINT8_MAX;
+ }
+ if (flags & DF_RECORDATTACK)
+ {
+ oldtime = READUINT32(p);
+ oldlap = READUINT32(p);
+ }
+ else // appease compiler
+ return UINT8_MAX;
+
+ Z_Free(buffer);
+
+ c = 0;
+ if (newtime < oldtime
+ || (newtime == oldtime && (newlap < oldlap)))
+ c |= 1; // Better time
+ if (newlap < oldlap
+ || (newlap == oldlap && newtime < oldtime))
+ c |= 1<<1; // Better lap time
+ return c;
+}
+
+void G_LoadDemoInfo(menudemo_t *pdemo)
+{
+ UINT8 *infobuffer, *info_p, *extrainfo_p;
+ UINT8 version, subversion, pdemoflags;
+ UINT16 pdemoversion, count;
+
+ if (!FIL_ReadFile(pdemo->filepath, &infobuffer))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath);
+ pdemo->type = MD_INVALID;
+ sprintf(pdemo->title, "INVALID REPLAY");
+
+ return;
+ }
+
+ info_p = infobuffer;
+
+ if (memcmp(info_p, DEMOHEADER, 12))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath);
+ pdemo->type = MD_INVALID;
+ sprintf(pdemo->title, "INVALID REPLAY");
+ Z_Free(infobuffer);
+ return;
+ }
+
+ pdemo->type = MD_LOADED;
+
+ info_p += 12; // DEMOHEADER
+
+ version = READUINT8(info_p);
+ subversion = READUINT8(info_p);
+ pdemoversion = READUINT16(info_p);
+
+ memset(pdemo->version, 0, sizeof(pdemo->version));
+ snprintf(pdemo->version, sizeof(pdemo->version), "v%d.%d", version, subversion);
+
+ switch(pdemoversion)
+ {
+ case DEMOVERSION: // latest always supported
+ // demo title
+ M_Memcpy(pdemo->title, info_p, 64);
+ info_p += 64;
+
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ pdemo->type = MD_OUTDATED;
+ sprintf(pdemo->title, "Legacy Replay");
+ break;
+#endif
+ // too old, cannot support.
+ default:
+ CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath);
+ pdemo->type = MD_INVALID;
+ sprintf(pdemo->title, "INVALID REPLAY");
+ Z_Free(infobuffer);
+ return;
+ }
+
+ if (version != VERSION || subversion != SUBVERSION)
+ pdemo->type = MD_OUTDATED;
+
+ info_p += 16; // demo checksum
+ if (memcmp(info_p, "PLAY", 4))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemo->filepath);
+ pdemo->type = MD_INVALID;
+ sprintf(pdemo->title, "INVALID REPLAY");
+ Z_Free(infobuffer);
+ return;
+ }
+ info_p += 4; // "PLAY"
+ pdemo->map = READINT16(info_p);
+ info_p += 16; // mapmd5
+
+ pdemoflags = READUINT8(info_p);
+
+ // temp?
+ if (!(pdemoflags & DF_MULTIPLAYER))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("%s is not a multiplayer replay and can't be listed on this menu fully yet.\n"), pdemo->filepath);
+ Z_Free(infobuffer);
+ return;
+ }
+#ifdef DEMO_COMPAT_100
+ else if (pdemoversion == 0x0001)
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("%s is a legacy multiplayer replay and cannot be played.\n"), pdemo->filepath);
+ pdemo->type = MD_INVALID;
+ sprintf(pdemo->title, "INVALID REPLAY");
+ Z_Free(infobuffer);
+ return;
+ }
+#endif
+
+ pdemo->gametype = READUINT8(info_p);
+
+ pdemo->addonstatus = G_CheckDemoExtraFiles(&info_p, true);
+ info_p += 4; // RNG seed
+
+ extrainfo_p = infobuffer + READUINT32(info_p);
+
+ // Pared down version of CV_LoadNetVars to find the kart speed
+ pdemo->kartspeed = 1; // Default to normal speed
+ count = READUINT16(info_p);
+ while (count--)
+ {
+ UINT16 netid;
+ char *svalue;
+
+ netid = READUINT16(info_p);
+ svalue = (char *)info_p;
+ SKIPSTRING(info_p);
+ info_p++; // stealth
+
+ if (netid == cv_kartspeed.netid)
+ {
+ UINT8 j;
+ for (j = 0; kartspeed_cons_t[j].strvalue; j++)
+ if (!stricmp(kartspeed_cons_t[j].strvalue, svalue))
+ pdemo->kartspeed = kartspeed_cons_t[j].value;
+ }
+ else if (netid == cv_basenumlaps.netid && pdemo->gametype == GT_RACE)
+ pdemo->numlaps = atoi(svalue);
+ }
+
+ if (pdemoflags & DF_ENCORE)
+ pdemo->kartspeed |= DF_ENCORE;
+
+ // Read standings!
+ count = 0;
+
+ while (READUINT8(extrainfo_p) == DW_STANDING) // Assume standings are always first in the extrainfo
+ {
+ INT32 i;
+ char temp[16];
+
+ pdemo->standings[count].ranking = READUINT8(extrainfo_p);
+
+ // Name
+ M_Memcpy(pdemo->standings[count].name, extrainfo_p, 16);
+ extrainfo_p += 16;
+
+ // Skin
+ M_Memcpy(temp,extrainfo_p,16);
+ extrainfo_p += 16;
+ pdemo->standings[count].skin = UINT8_MAX;
+ for (i = 0; i < numskins; i++)
+ if (stricmp(skins[i].name, temp) == 0)
+ {
+ pdemo->standings[count].skin = i;
+ break;
+ }
+
+ // Color
+ M_Memcpy(temp,extrainfo_p,16);
+ extrainfo_p += 16;
+ for (i = 0; i < MAXSKINCOLORS; i++)
+ if (!stricmp(KartColor_Names[i],temp)) // SRB2kart
+ {
+ pdemo->standings[count].color = i;
+ break;
+ }
+
+ // Score/time/whatever
+ pdemo->standings[count].timeorscore = READUINT32(extrainfo_p);
+
+ count++;
+
+ if (count >= MAXPLAYERS)
+ break; //@TODO still cycle through the rest of these if extra demo data is ever used
+ }
+
+ // I think that's everything we need?
+ Z_Free(infobuffer);
+}
+
+#if defined (_WIN32)
+// return the file creation time
+// useful for demos that were renamed
+static long G_GetCreationTime(char *filepath)
+{
+ struct stat fileinfo;
+
+ if (stat(filepath, &fileinfo) == 0)
+ return fileinfo.st_ctime;
+
+ return 0;
+}
+#endif
+
+static char *G_GetDemoDate(menudemo_t *pdemo)
+{
+ char *datetime;
+ datetime = malloc(sizeof(pdemo->date)); // mallocma balls
+
+ // no mallocma balls... :c
+ if (!datetime)
+ {
+ return NULL;
+ }
+
+ time_t file_time = 0;
+
+ // get le filepath
+ char *filename;
+ filename = strdup(pdemo->filepath);
+
+#if defined (_WIN32)
+ if (!filename)
+ {
+ // if we cant get a filename try just getting the file create time
+ file_time = G_GetCreationTime(pdemo->filepath);
+ goto skipfilenametime;
+ }
+#else
+ if (!filename)
+ {
+ free(datetime);
+ return NULL;
+ }
+#endif
+
+ // get the actual filename Zzz...
+ nameonly(filename);
+
+ // convert it to long Zzz....
+ file_time = strtol(filename, NULL, 10);
+ free(filename); // dont need this anymore a
+
+#if defined (_WIN32)
+skipfilenametime:
+#endif
+
+ // then throw it into localtime to get an actual human readable format lmao
+ struct tm *tm_buf = NULL;
+ tm_buf = localtime(&file_time);
+
+ // cant believe we ended up in 1970
+ if (tm_buf == NULL || tm_buf->tm_year <= 110)
+ {
+#if defined (_WIN32)
+ // uh ohh, we got an invalid time
+ // try one more time getting the creation time
+ file_time = G_GetCreationTime(pdemo->filepath);
+ tm_buf = localtime(&file_time);
+
+ if (tm_buf == NULL || tm_buf->tm_year <= 110)
+ {
+ free(datetime);
+ return NULL;
+ }
+
+ goto gotcreationtime;
+#else
+ free(datetime);
+ return NULL;
+#endif
+ }
+
+#if defined (_WIN32)
+gotcreationtime:
+#endif
+
+ const char *format;
+
+ // US ppl are special (:
+ if (cv_demodateformat.value == 2)
+ format = "%m.%d.%Y";
+ else if (cv_demodateformat.value == 1)
+ format = "%d.%m.%Y";
+ else
+ format = strstr(setlocale(LC_TIME, NULL), "en_US") ? "%m.%d.%Y" : "%d.%m.%Y";
+
+ strftime(datetime, sizeof(pdemo->date), format, tm_buf);
+
+ return datetime;
+}
+
+void G_LoadDemoTitle(menudemo_t *pdemo)
+{
+ UINT8 infobuffer[96], *info_p;
+ UINT16 pdemoversion;
+ size_t count;
+
+ FILE *handle = fopen(pdemo->filepath, "rb");
+
+ if (!handle)
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath);
+ sprintf(pdemo->title, "INVALID REPLAY");
+ return;
+ }
+
+ count = fread(infobuffer, 1, 96, handle);
+ fclose(handle);
+ info_p = infobuffer;
+
+ // First check isn't too accurate technically, but well, valid replays should be larger than that anyway
+ if (count < 96 || memcmp(info_p, DEMOHEADER, 12))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath);
+ sprintf(pdemo->title, "INVALID REPLAY");
+ return;
+ }
+
+ info_p += 12; // DEMOHEADER
+
+ READUINT8(info_p);
+ READUINT8(info_p);
+ pdemoversion = READUINT16(info_p);
+
+ memset(pdemo->date, 0, sizeof(pdemo->date));
+
+ switch(pdemoversion)
+ {
+ case DEMOVERSION: // latest always supported
+ // demo title
+ M_Memcpy(pdemo->title, info_p, 64);
+
+ // demo date
+ char *demodate;
+ demodate = G_GetDemoDate(pdemo);
+ if (demodate)
+ strncpy(pdemo->date, demodate, sizeof(pdemo->date));
+ free(demodate);
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ sprintf(pdemo->title, "Legacy Replay");
+ break;
+#endif
+ // too old, cannot support.
+ default:
+ CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath);
+ sprintf(pdemo->title, "INVALID REPLAY");
+ }
+}
+
+//
+// G_PlayDemo
+//
+void G_DeferedPlayDemo(const char *name)
+{
+ COM_BufAddText("playdemo \"");
+ COM_BufAddText(name);
+ COM_BufAddText("\" -addfiles\n");
+}
+
+//
+// Start a demo from a .LMP file or from a wad resource
+//
+#define SKIPERRORS
+void G_DoPlayDemo(char *defdemoname)
+{
+ UINT8 i, p;
+ lumpnum_t l;
+ char skin[17],color[17],*n,*pdemoname;
+ UINT8 version,subversion;
+ UINT32 randseed;
+ char msg[1024];
+#if defined(SKIPERRORS) && !defined(DEVELOP)
+ boolean skiperrors = false;
+#endif
+ boolean spectator;
+ UINT8 slots[MAXPLAYERS], kartspeed[MAXPLAYERS], kartweight[MAXPLAYERS], numslots = 0;
+
+ G_InitDemoRewind();
+
+ skin[16] = '\0';
+ color[16] = '\0';
+
+ // No demo name means we're restarting the current demo
+ if (defdemoname == NULL)
+ {
+ demobuf.p = demobuf.buffer;
+ pdemoname = ZZ_Alloc(1); // Easier than adding checks for this everywhere it's freed
+ }
+ else
+ {
+ n = defdemoname+strlen(defdemoname);
+ while (*n != '/' && *n != '\\' && n != defdemoname)
+ n--;
+ if (n != defdemoname)
+ n++;
+ pdemoname = ZZ_Alloc(strlen(n)+1);
+ strcpy(pdemoname,n);
+
+ M_SetPlaybackMenuPointer();
+
+ // Internal if no extension, external if one exists
+ if (FIL_CheckExtension(defdemoname))
+ {
+ //FIL_DefaultExtension(defdemoname, ".lmp");
+ if (!FIL_ReadFile(defdemoname, &demobuf.buffer))
+ {
+ snprintf(msg, 1024, M_GetText("Failed to read file '%s'.\n"), defdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ gameaction = ga_nothing;
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ return;
+ }
+ demobuf.p = demobuf.buffer;
+ }
+ // load demo resource from WAD
+ else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR)
+ {
+ snprintf(msg, 1024, M_GetText("Failed to read lump '%s'.\n"), defdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ gameaction = ga_nothing;
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ return;
+ }
+ else // it's an internal demo
+ {
+ demobuf.buffer = demobuf.p = W_CacheLumpNum(l, PU_STATIC);
+#if defined(SKIPERRORS) && !defined(DEVELOP)
+ skiperrors = true; // SRB2Kart: Don't print warnings for staff ghosts, since they'll inevitably happen when we make bugfixes/changes...
+#endif
+ }
+ }
+
+ // read demo header
+ gameaction = ga_nothing;
+ demo.playback = true;
+ if (memcmp(demobuf.p, DEMOHEADER, 12))
+ {
+ snprintf(msg, 1024, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ demobuf.p += 12; // DEMOHEADER
+
+ version = READUINT8(demobuf.p);
+ subversion = READUINT8(demobuf.p);
+ demo.version = READUINT16(demobuf.p);
+ switch(demo.version)
+ {
+ case DEMOVERSION: // latest always supported
+ // demo title
+ M_Memcpy(demo.titlename, demobuf.p, 64);
+ demobuf.p += 64;
+
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ break;
+#endif
+ // too old, cannot support.
+ default:
+ snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ demobuf.p += 16; // demo checksum
+ if (memcmp(demobuf.p, "PLAY", 4))
+ {
+ snprintf(msg, 1024, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ demobuf.p += 4; // "PLAY"
+ gamemap = READINT16(demobuf.p);
+ demobuf.p += 16; // mapmd5
+
+ demoflags = READUINT8(demobuf.p);
+#ifdef DEMO_COMPAT_100
+ if (demo.version == 0x0001)
+ {
+ if (demoflags & DF_MULTIPLAYER)
+ {
+ snprintf(msg, 1024, M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ }
+ else
+ {
+#endif
+ gametype = READUINT8(demobuf.p);
+
+ if (demo.title) // Titledemos should always play and ought to always be compatible with whatever wadlist is running.
+ G_SkipDemoExtraFiles(&demobuf.p);
+ else if (demo.loadfiles)
+ G_LoadDemoExtraFiles(&demobuf.p);
+ else if (demo.ignorefiles)
+ G_SkipDemoExtraFiles(&demobuf.p);
+ else
+ {
+ UINT8 error = G_CheckDemoExtraFiles(&demobuf.p, false);
+
+ if (error)
+ {
+ switch (error)
+ {
+ case DFILE_ERROR_NOTLOADED:
+ snprintf(msg, 1024,
+ M_GetText("Required files for this demo are not loaded.\n\nUse\n\"playdemo %s -addfiles\"\nto load them and play the demo.\n"),
+ pdemoname);
+ break;
+
+ case DFILE_ERROR_OUTOFORDER:
+ snprintf(msg, 1024,
+ M_GetText("Required files for this demo are loaded out of order.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
+ pdemoname);
+ break;
+
+ case DFILE_ERROR_INCOMPLETEOUTOFORDER:
+ snprintf(msg, 1024,
+ M_GetText("Required files for this demo are not loaded, and some are out of order.\n\nUse\n\"playdemo %s -addfiles\"\nto load needed files and play the demo.\n"),
+ pdemoname);
+ break;
+
+ case DFILE_ERROR_CANNOTLOAD:
+ snprintf(msg, 1024,
+ M_GetText("Required files for this demo cannot be loaded.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
+ pdemoname);
+ break;
+
+ case DFILE_ERROR_EXTRAFILES:
+ snprintf(msg, 1024,
+ M_GetText("You have additional files loaded beyond the demo's file list.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
+ pdemoname);
+ break;
+ }
+
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ if (!CON_Ready()) // In the console they'll just see the notice there! No point pulling them out.
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ }
+#ifdef DEMO_COMPAT_100
+ }
+#endif
+
+ modeattacking = (demoflags & DF_ATTACKMASK)>>DF_ATTACKSHIFT;
+ multiplayer = !!(demoflags & DF_MULTIPLAYER);
+ CON_ToggleOff();
+
+ hu_demotime = UINT32_MAX;
+ hu_demolap = UINT32_MAX;
+
+ switch (modeattacking)
+ {
+ case ATTACKING_NONE: // 0
+ break;
+ case ATTACKING_RECORD: // 1
+ hu_demotime = READUINT32(demobuf.p);
+ hu_demolap = READUINT32(demobuf.p);
+ break;
+ default: // 3
+ modeattacking = ATTACKING_NONE;
+ break;
+ }
+
+ // Random seed
+ randseed = READUINT32(demobuf.p);
+#ifdef DEMO_COMPAT_100
+ if (demo.version != 0x0001)
+#endif
+ demobuf.p += 4; // Extrainfo location
+
+#ifdef DEMO_COMPAT_100
+ if (demo.version == 0x0001)
+ {
+ // Player name
+ M_Memcpy(player_names[0],demobuf.p,16);
+ demobuf.p += 16;
+
+ // Skin
+ M_Memcpy(skin,demobuf.p,16);
+ demobuf.p += 16;
+
+ // Color
+ M_Memcpy(color,demobuf.p,16);
+ demobuf.p += 16;
+
+ demobuf.p += 5; // Backwards compat - some stats
+ // SRB2kart
+ kartspeed[0] = READUINT8(demobuf.p);
+ kartweight[0] = READUINT8(demobuf.p);
+ //
+ demobuf.p += 9; // Backwards compat - more stats
+
+ // Skin not loaded?
+ if (!SetPlayerSkin(0, skin))
+ {
+ snprintf(msg, 1024, M_GetText("%s features a character that is not currently loaded.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+
+ // ...*map* not loaded?
+ if (!gamemap || (gamemap > NUMMAPS) || !mapheaderinfo[gamemap-1] || !(mapheaderinfo[gamemap-1]->menuflags & LF2_EXISTSHACK))
+ {
+ snprintf(msg, 1024, M_GetText("%s features a course that is not currently loaded.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+
+ // Set color
+ for (i = 0; i < MAXSKINCOLORS; i++)
+ if (!stricmp(KartColor_Names[i],color)) // SRB2kart
+ {
+ players[0].skincolor = i;
+ break;
+ }
+
+ // net var data
+ CV_LoadNetVars(&demobuf.p);
+
+ // Sigh ... it's an empty demo.
+ if (*demobuf.p == DEMOMARKER)
+ {
+ snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+
+ Z_Free(pdemoname);
+
+ memset(&oldcmd,0,sizeof(oldcmd));
+ memset(&oldghost,0,sizeof(oldghost));
+ memset(&ghostext,0,sizeof(ghostext));
+
+ CONS_Alert(CONS_WARNING, M_GetText("Demo version does not match game version. Desyncs may occur.\n"));
+
+ // console warning messages
+#if defined(SKIPERRORS) && !defined(DEVELOP)
+ demosynced = (!skiperrors);
+#else
+ demosynced = true;
+#endif
+
+ // didn't start recording right away.
+ demo.deferstart = false;
+
+ consoleplayer = 0;
+ memset(displayplayers, 0, sizeof(displayplayers));
+ memset(playeringame, 0, sizeof(playeringame));
+ playeringame[0] = true;
+
+ goto post_compat;
+ }
+#endif
+
+ // net var data
+ CV_LoadNetVars(&demobuf.p);
+
+ // Sigh ... it's an empty demo.
+ if (*demobuf.p == DEMOMARKER)
+ {
+ snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+
+ Z_Free(pdemoname);
+
+ memset(&oldcmd,0,sizeof(oldcmd));
+ memset(&oldghost,0,sizeof(oldghost));
+ memset(&ghostext,0,sizeof(ghostext));
+
+#if defined(SKIPERRORS) && !defined(DEVELOP)
+ if ((VERSION != version || SUBVERSION != subversion) && !skiperrors)
+#else
+ if (VERSION != version || SUBVERSION != subversion)
+#endif
+ CONS_Alert(CONS_WARNING, M_GetText("Demo version does not match game version. Desyncs may occur.\n"));
+
+ // console warning messages
+#if defined(SKIPERRORS) && !defined(DEVELOP)
+ demosynced = (!skiperrors);
+#else
+ demosynced = true;
+#endif
+
+ // didn't start recording right away.
+ demo.deferstart = false;
+
+ //LUA_HookInt(gamemap, HOOK(MapChange));
+
+ consoleplayer = 0;
+ memset(playeringame, 0, sizeof(playeringame));
+ memset(displayplayers, 0, sizeof(displayplayers));
+ memset(camera, 0, sizeof(camera)); // reset freecam
+
+ // Load players that were in-game when the map started
+ p = READUINT8(demobuf.p);
+
+ while (p != 0xFF)
+ {
+ spectator = false;
+ if (p & DEMO_SPECTATOR)
+ {
+ spectator = true;
+ p &= ~DEMO_SPECTATOR;
+
+ if (modeattacking)
+ {
+ snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+ }
+ slots[numslots] = p; numslots++;
+
+ if (modeattacking && numslots > 1)
+ {
+ snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname);
+ CONS_Alert(CONS_ERROR, "%s", msg);
+ M_StartMessage(msg, NULL, MM_NOTHING);
+ G_ResetDemoPlayback(pdemoname);
+ return;
+ }
+
+ if (!playeringame[displayplayers[0]] || players[displayplayers[0]].spectator)
+ displayplayers[0] = consoleplayer = serverplayer = p;
+
+ playeringame[p] = true;
+ players[p].spectator = spectator;
+
+ // Name
+ M_Memcpy(player_names[p],demobuf.p,16);
+ demobuf.p += 16;
+
+ // Skin
+ M_Memcpy(skin,demobuf.p,16);
+ demobuf.p += 16;
+ SetPlayerSkin(p, skin);
+
+ // Color
+ M_Memcpy(color,demobuf.p,16);
+ demobuf.p += 16;
+ for (i = 0; i < MAXSKINCOLORS; i++)
+ if (!stricmp(KartColor_Names[i],color)) // SRB2kart
+ {
+ players[p].skincolor = i;
+ break;
+ }
+
+ // Score, since Kart uses this to determine where you start on the map
+ players[p].score = READUINT32(demobuf.p);
+
+ // Kart stats, temporarily
+ kartspeed[p] = READUINT8(demobuf.p);
+ kartweight[p] = READUINT8(demobuf.p);
+
+ if (stricmp(skins[players[p].skin].name, skin) != 0)
+ FindClosestSkinForStats(p, kartspeed[p], kartweight[p]);
+
+ // Look for the next player
+ p = READUINT8(demobuf.p);
+ }
+
+ // end of player read (the 0xFF marker)
+ // so this is where we are to read our lua variables (if possible!)
+ if (demoflags & DF_LUAVARS) // again, used for compability, lua shit will be saved to replays regardless of if it's even been loaded
+ {
+ if (!gL) // No Lua state! ...I guess we'll just start one...
+ LUA_ClearState();
+
+ // No modeattacking check, DF_LUAVARS won't be present here.
+ LUA_UnArchive(&demobuf, false);
+ }
+
+ splitscreen = 0;
+
+ if (demo.title)
+ {
+ splitscreen = M_RandomKey(6)-1;
+ splitscreen = min(min(3, numslots-1), splitscreen); // Bias toward 1p and 4p views
+
+ for (p = 0; p <= splitscreen; p++)
+ G_ResetView(p+1, slots[M_RandomKey(numslots)], false);
+ }
+
+ R_ExecuteSetViewSize();
+
+#ifdef DEMO_COMPAT_100
+post_compat:
+#endif
+
+ P_SetRandSeed(randseed);
+ G_InitNew(demoflags & DF_ENCORE, G_BuildMapName(gamemap), true, true); // Doesn't matter whether you reset or not here, given changes to resetplayer.
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (players[i].mo)
+ {
+ players[i].mo->color = players[i].skincolor;
+ oldghost[i].x = players[i].mo->x;
+ oldghost[i].y = players[i].mo->y;
+ oldghost[i].z = players[i].mo->z;
+ }
+
+ // Set saved attribute values
+ // No cheat checking here, because even if they ARE wrong...
+ // it would only break the replay if we clipped them.
+ players[i].kartspeed = kartspeed[i];
+ players[i].kartweight = kartweight[i];
+ }
+
+ if (cv_director.value)
+ CV_SetValue(&cv_director, 0);
+
+ demo.deferstart = true;
+}
+#undef SKIPERRORS
+
+void G_AddGhost(char *defdemoname)
+{
+ INT32 i;
+ lumpnum_t l;
+ char name[17],skin[17],color[17],*n,*pdemoname,md5[16];
+ demoghost *gh;
+ UINT8 flags;
+ UINT8 *buffer,*p;
+ mapthing_t *mthing;
+ UINT16 count, ghostversion;
+ skin_t *ghskin = &skins[0];
+ UINT8 kartspeed = UINT8_MAX, kartweight = UINT8_MAX;
+
+ name[16] = '\0';
+ skin[16] = '\0';
+ color[16] = '\0';
+
+ n = defdemoname+strlen(defdemoname);
+ while (*n != '/' && *n != '\\' && n != defdemoname)
+ n--;
+ if (n != defdemoname)
+ n++;
+ pdemoname = ZZ_Alloc(strlen(n)+1);
+ strcpy(pdemoname,n);
+
+ // Internal if no extension, external if one exists
+ if (FIL_CheckExtension(defdemoname))
+ {
+ //FIL_DefaultExtension(defdemoname, ".lmp");
+ if (!FIL_ReadFileTag(defdemoname, &buffer, PU_LEVEL))
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), defdemoname);
+ Z_Free(pdemoname);
+ return;
+ }
+ p = buffer;
+ }
+ // load demo resource from WAD
+ else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR)
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to read lump '%s'.\n"), defdemoname);
+ Z_Free(pdemoname);
+ return;
+ }
+ else // it's an internal demo
+ buffer = p = W_CacheLumpNum(l, PU_LEVEL);
+
+ // read demo header
+ if (memcmp(p, DEMOHEADER, 12))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Not a SRB2Kart replay.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+ p += 12; // DEMOHEADER
+ p++; // VERSION
+ p++; // SUBVERSION
+
+ ghostversion = READUINT16(p);
+ switch(ghostversion)
+ {
+ case DEMOVERSION: // latest always supported
+ p += 64; // title
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ break;
+#endif
+ // too old, cannot support.
+ default:
+ CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo version incompatible.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+ M_Memcpy(md5, p, 16); p += 16; // demo checksum
+ for (gh = ghosts; gh; gh = gh->next)
+ if (!memcmp(md5, gh->checksum, 16)) // another ghost in the game already has this checksum?
+ { // Don't add another one, then!
+ CONS_Debug(DBG_SETUP, "Rejecting duplicate ghost %s (MD5 was matched)\n", pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+ if (memcmp(p, "PLAY", 4))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo format unacceptable.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+ p += 4; // "PLAY"
+ p += 2; // gamemap
+ p += 16; // mapmd5 (possibly check for consistency?)
+
+ flags = READUINT8(p);
+
+ if (!(flags & DF_GHOST))
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: No ghost data in this demo.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion != 0x0001)
+#endif
+ p++; // gametype
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion != 0x0001)
+#endif
+ G_SkipDemoExtraFiles(&p); // Don't wanna modify the file list for ghosts.
+ switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
+ {
+ case ATTACKING_NONE: // 0
+ break;
+ case ATTACKING_RECORD: // 1
+ p += 8; // demo time, lap
+ break;
+ default: // 3
+ break;
+ }
+
+ p += 4; // random seed
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion == 0x0001)
+ {
+ // Player name (TODO: Display this somehow if it doesn't match cv_playername!)
+ M_Memcpy(name, p,16);
+ p += 16;
+
+ // Skin
+ M_Memcpy(skin, p,16);
+ p += 16;
+
+ // Color
+ M_Memcpy(color, p,16);
+ p += 16;
+
+ // Ghosts do not have a player structure to put this in.
+ p++; // charability
+ p++; // charability2
+ p++; // actionspd
+ p++; // mindash
+ p++; // maxdash
+ // SRB2kart
+ p++; // kartspeed
+ p++; // kartweight
+ //
+ p++; // normalspeed
+ p++; // runspeed
+ p++; // thrustfactor
+ p++; // accelstart
+ p++; // acceleration
+ p += 4; // jumpfactor
+ }
+ else
+#endif
+ p += 4; // Extra data location reference
+
+ // net var data
+ count = READUINT16(p);
+ while (count--)
+ {
+ p += 2;
+ SKIPSTRING(p);
+ p++;
+ }
+
+ if (*p == DEMOMARKER)
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Replay is empty.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion != 0x0001)
+ {
+#endif
+ if (READUINT8(p) != 0)
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+
+ // Player name (TODO: Display this somehow if it doesn't match cv_playername!)
+ M_Memcpy(name, p, 16);
+ p += 16;
+
+ // Skin
+ M_Memcpy(skin, p, 16);
+ p += 16;
+
+ // Color
+ M_Memcpy(color, p, 16);
+ p += 16;
+
+ p += 4; // score
+
+ kartspeed = READUINT8(p);
+ kartweight = READUINT8(p);
+
+ if (READUINT8(p) != 0xFF)
+ {
+ CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname);
+ Z_Free(pdemoname);
+ Z_Free(buffer);
+ return;
+ }
+#ifdef DEMO_COMPAT_100
+ }
+#endif
+
+ for (i = 0; i < numskins; i++)
+ if (!stricmp(skins[i].name,skin))
+ {
+ ghskin = &skins[i];
+ break;
+ }
+
+ if (i == numskins)
+ {
+ if (kartspeed != UINT8_MAX && kartweight != UINT8_MAX)
+ ghskin = &skins[GetSkinNumClosestToStats(kartspeed, kartweight)];
+
+ CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Invalid character. Falling back to %s.\n"), pdemoname, ghskin->name);
+ }
+
+ gh = Z_Calloc(sizeof(demoghost), PU_LEVEL, NULL);
+ gh->next = ghosts;
+ gh->buffer = buffer;
+ M_Memcpy(gh->checksum, md5, 16);
+ gh->p = p;
+
+ ghosts = gh;
+
+ gh->version = ghostversion;
+ mthing = playerstarts[0];
+ I_Assert(mthing);
+ { // A bit more complex than P_SpawnPlayer because ghosts aren't solid and won't just push themselves out of the ceiling.
+ fixed_t z,f,c;
+ gh->mo = P_SpawnMobj(mthing->x << FRACBITS, mthing->y << FRACBITS, 0, MT_GHOST);
+ gh->mo->angle = FixedAngle(mthing->angle*FRACUNIT);
+ f = gh->mo->floorz;
+ c = gh->mo->ceilingz - mobjinfo[MT_PLAYER].height;
+ if (!!(mthing->options & MTF_AMBUSH) ^ !!(mthing->options & MTF_OBJECTFLIP))
+ {
+ z = c;
+ if (mthing->options >> ZSHIFT)
+ z -= ((mthing->options >> ZSHIFT) << FRACBITS);
+ if (z < f)
+ z = f;
+ }
+ else
+ {
+ z = f;
+ if (mthing->options >> ZSHIFT)
+ z += ((mthing->options >> ZSHIFT) << FRACBITS);
+ if (z > c)
+ z = c;
+ }
+ gh->mo->z = z;
+ }
+ gh->mo->state = states+S_KART_STND1; // SRB2kart - was S_PLAY_STND
+ gh->mo->sprite = gh->mo->state->sprite;
+ gh->mo->frame = (gh->mo->state->frame & FF_FRAMEMASK) | tr_trans20<mo->tics = -1;
+
+ gh->oldmo.x = gh->mo->x;
+ gh->oldmo.y = gh->mo->y;
+ gh->oldmo.z = gh->mo->z;
+
+ // Set skin
+ gh->mo->skin = gh->oldmo.skin = ghskin;
+
+ // Set color
+ gh->mo->color = ((skin_t*)gh->mo->skin)->prefcolor;
+ for (i = 0; i < MAXSKINCOLORS; i++)
+ if (!stricmp(KartColor_Names[i],color)) // SRB2kart
+ {
+ gh->mo->color = (UINT8)i;
+ break;
+ }
+ gh->oldmo.color = gh->mo->color;
+
+ CONS_Printf(M_GetText("Added ghost %s from %s\n"), name, pdemoname);
+ Z_Free(pdemoname);
+}
+
+// A simplified version of G_AddGhost...
+void G_UpdateStaffGhostName(lumpnum_t l)
+{
+ UINT8 *buffer,*p;
+ UINT16 ghostversion;
+ UINT8 flags;
+
+ buffer = p = W_CacheLumpNum(l, PU_CACHE);
+
+ // read demo header
+ if (memcmp(p, DEMOHEADER, 12))
+ {
+ goto fail;
+ }
+
+ p += 12; // DEMOHEADER
+ p++; // VERSION
+ p++; // SUBVERSION
+
+ ghostversion = READUINT16(p);
+ switch(ghostversion)
+ {
+ case DEMOVERSION: // latest always supported
+ p += 64; // full demo title
+ break;
+
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ break;
+#endif
+
+ // too old, cannot support.
+ default:
+ goto fail;
+ }
+
+ p += 16; // demo checksum
+
+ if (memcmp(p, "PLAY", 4))
+ {
+ goto fail;
+ }
+
+ p += 4; // "PLAY"
+ p += 2; // gamemap
+ p += 16; // mapmd5 (possibly check for consistency?)
+
+ flags = READUINT8(p);
+ if (!(flags & DF_GHOST))
+ {
+ goto fail; // we don't NEED to do it here, but whatever
+ }
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion != 0x0001)
+#endif
+ p++; // Gametype
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion != 0x0001)
+#endif
+ G_SkipDemoExtraFiles(&p);
+
+ switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
+ {
+ case ATTACKING_NONE: // 0
+ break;
+ case ATTACKING_RECORD: // 1
+ p += 8; // demo time, lap
+ break;
+ default: // 3
+ break;
+ }
+
+ p += 4; // random seed
+
+
+#ifdef DEMO_COMPAT_100
+ if (ghostversion == 0x0001)
+ {
+ // Player name
+ M_Memcpy(dummystaffname, p,16);
+ dummystaffname[16] = '\0';
+ goto fail; // Not really a failure but whatever
+ }
+#endif
+
+ p += 4; // Extrainfo location marker
+
+ // Ehhhh don't need ghostversion here (?) so I'll reuse the var here
+ ghostversion = READUINT16(p);
+ while (ghostversion--)
+ {
+ p += 2;
+ SKIPSTRING(p);
+ p++; // stealth
+ }
+
+ // Assert first player is in and then read name
+ if (READUINT8(p) != 0)
+ goto fail;
+ M_Memcpy(dummystaffname, p,16);
+ dummystaffname[16] = '\0';
+
+ // Ok, no longer any reason to care, bye
+fail:
+ Z_Free(buffer);
+ return;
+}
+
+//
+// G_TimeDemo
+// NOTE: name is a full filename for external demos
+//
+static INT32 restorecv_vidwait;
+
+void G_TimeDemo(const char *name)
+{
+ nodrawers = M_CheckParm("-nodraw");
+ noblit = M_CheckParm("-noblit");
+ restorecv_vidwait = cv_vidwait.value;
+ if (cv_vidwait.value)
+ CV_Set(&cv_vidwait, "0");
+ demo.timing = true;
+ singletics = true;
+ framecount = 0;
+ demostarttime = I_GetTime();
+ G_DeferedPlayDemo(name);
+}
+
+void G_DoPlayMetal(void)
+{
+ lumpnum_t l;
+ mobj_t *mo = NULL;
+ thinker_t *th;
+
+ // it's an internal demo
+ if ((l = W_CheckNumForName(va("%sMS",G_BuildMapName(gamemap)))) == LUMPERROR)
+ {
+ CONS_Alert(CONS_WARNING, M_GetText("No bot recording for this map.\n"));
+ return;
+ }
+ else
+ metalbuffer = metal_p = W_CacheLumpNum(l, PU_STATIC);
+
+ // find metal sonic
+ for (th = thinkercap.next; th != &thinkercap; th = th->next)
+ {
+ if (th->function.acp1 != (actionf_p1)P_MobjThinker)
+ continue;
+
+ mo = (mobj_t *)th;
+ if (mo->type == MT_METALSONIC_RACE)
+ break;
+ }
+ if (!mo)
+ {
+ CONS_Alert(CONS_ERROR, M_GetText("Failed to find bot entity.\n"));
+ Z_Free(metalbuffer);
+ return;
+ }
+
+ // read demo header
+ metal_p += 12; // DEMOHEADER
+ metal_p++; // VERSION
+ metal_p++; // SUBVERSION
+ metalversion = READUINT16(metal_p);
+ switch(metalversion)
+ {
+ case DEMOVERSION: // latest always supported
+ break;
+#ifdef DEMO_COMPAT_100
+ case 0x0001:
+ I_Error("You need to implement demo compat here, doofus! %s:%d", __FILE__, __LINE__);
+#endif
+ // too old, cannot support.
+ default:
+ CONS_Alert(CONS_WARNING, M_GetText("Failed to load bot recording for this map, format version incompatible.\n"));
+ Z_Free(metalbuffer);
+ return;
+ }
+ metal_p += 16; // demo checksum
+ if (memcmp(metal_p, "METL", 4))
+ {
+ CONS_Alert(CONS_WARNING, M_GetText("Failed to load bot recording for this map, wasn't recorded in Metal format.\n"));
+ Z_Free(metalbuffer);
+ return;
+ } metal_p += 4; // "METL"
+
+ // read initial tic
+ memset(&oldmetal,0,sizeof(oldmetal));
+ oldmetal.x = mo->x;
+ oldmetal.y = mo->y;
+ oldmetal.z = mo->z;
+ oldmetal.angle = mo->angle;
+ metalplayback = mo;
+}
+
+void G_DoneLevelLoad(void)
+{
+ CONS_Printf(M_GetText("Loaded level in %f sec\n"), (double)(I_GetTime() - demostarttime) / TICRATE);
+ framecount = 0;
+ demostarttime = I_GetTime();
+}
+
+/*
+===================
+=
+= G_CheckDemoStatus
+=
+= Called after a death or level completion to allow demos to be cleaned up
+= Returns true if a new demo loop action will take place
+===================
+*/
+
+// Stops metal sonic's demo. Separate from other functions because metal + replays can coexist
+void G_StopMetalDemo(void)
+{
+ // Metal Sonic finishing doesn't end the game, dammit.
+ Z_Free(metalbuffer);
+ metalbuffer = NULL;
+ metalplayback = NULL;
+ metal_p = NULL;
+}
+
+// Stops metal sonic recording.
+ATTRNORETURN void FUNCNORETURN G_StopMetalRecording(void)
+{
+ boolean saved = false;
+ if (demobuf.p && demobuf.buffer != NULL)
+ {
+ UINT8 *p = demobuf.buffer+16; // checksum position
+#ifdef NOMD5
+ UINT8 i;
+ WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
+ for (i = 0; i < 16; i++, p++)
+ *p = P_RandomByte(); // This MD5 was chosen by fair dice roll and most likely < 50% correct.
+#else
+ WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
+ md5_buffer((char *)p+16, demobuf.p - (p+16), (void *)p); // make a checksum of everything after the checksum in the file.
+#endif
+ saved = FIL_WriteFile(va("%sMS.LMP", G_BuildMapName(gamemap)), demobuf.buffer, demobuf.p - demobuf.buffer); // finally output the file.
+ }
+ Z_Free(demobuf.buffer);
+ demobuf.buffer = NULL;
+ metalrecording = false;
+ if (saved)
+ I_Error("Saved to %sMS.LMP", G_BuildMapName(gamemap));
+ I_Error("Failed to save demo!");
+}
+
+// reset engine variable set for the demos
+// called from stopdemo command, map command, and g_checkdemoStatus.
+void G_StopDemo(void)
+{
+ Z_Free(demobuf.buffer);
+ demobuf.buffer = NULL;
+ demo.playback = false;
+ if (demo.title)
+ modeattacking = ATTACKING_NONE;
+ demo.title = false;
+ demo.timing = false;
+ singletics = false;
+
+ UINT8 i;
+ for (i = 0; i < MAXSPLITSCREENPLAYERS; ++i)
+ {
+ camera[i].freecam = false;
+ camera[i].localangle = 0;
+ camera[i].localaiming = 0;
+ }
+
+ CV_SetValue(&cv_playbackspeed, 1);
+ demo.rewinding = false;
+ CL_ClearRewinds();
+
+ if (gamestate == GS_LEVEL && rendermode != render_none)
+ {
+ V_SetPaletteLump("PLAYPAL"); // Reset the palette
+ R_ReInitColormaps(0, LUMPERROR);
+ }
+ if (gamestate == GS_INTERMISSION)
+ Y_EndIntermission(); // cleanup
+ if (gamestate == GS_VOTING)
+ Y_EndVote();
+
+ M_ClearMenus(true);
+
+ G_SetGamestate(GS_NULL);
+ wipegamestate = GS_NULL;
+ SV_StopServer();
+ SV_ResetServer();
+}
+
+// Stops timing a demo.
+static void G_StopTimingDemo(void)
+{
+ INT32 demotime;
+ double f1, f2;
+ demotime = I_GetTime() - demostarttime;
+ if (!demotime)
+ return;
+ G_StopDemo();
+ demo.timing = false;
+ f1 = (double)demotime;
+ f2 = (double)framecount*TICRATE;
+
+ CONS_Printf(M_GetText("timed %u gametics in %d realtics - %u frames\n%f seconds, %f avg fps\n"),
+ leveltime, demotime, (UINT32)framecount, f1/TICRATE, f2/f1);
+
+ if (restorecv_vidwait != cv_vidwait.value)
+ CV_SetValue(&cv_vidwait, restorecv_vidwait);
+
+ D_StartTitle();
+}
+
+
+boolean G_CheckDemoStatus(void)
+{
+ while (ghosts)
+ {
+ demoghost *next = ghosts->next;
+ Z_Free(ghosts);
+ ghosts = next;
+ }
+ ghosts = NULL;
+
+ // DO NOT end metal sonic demos here
+
+ if (demo.timing)
+ {
+ G_StopTimingDemo();
+ return true;
+ }
+
+ if (demo.playback)
+ {
+ if (demo.quitafterplaying)
+ I_Quit();
+
+ if (multiplayer && !demo.title)
+ {
+ G_ExitLevel();
+ }
+ else if (modeattacking && !demo.title) // nooo dont crash our titledemos
+ {
+ G_StopDemo();
+ M_EndModeAttackRun();
+ }
+ else
+ {
+ G_StopDemo();
+ D_StartTitle();
+ }
+
+ return true;
+ }
+
+ if (!demo.recording)
+ return false;
+
+ if (modeattacking || demo.savemode != DSM_NOTSAVING)
+ {
+ G_SaveDemo();
+ return true;
+ }
+
+ G_ResetDemoRecording();
+
+ return false;
+}
+
+void G_ResetDemoRecording(void)
+{
+ if (demobuf.buffer)
+ Z_Free(demobuf.buffer);
+ demobuf.buffer = NULL;
+ demo.recording = false;
+}
+
+static void G_ResetDemoPlayback(char *pdemoname)
+{
+ if (pdemoname)
+ Z_Free(pdemoname);
+ if (demobuf.buffer)
+ Z_Free(demobuf.buffer);
+ demobuf.buffer = NULL;
+ demo.playback = false;
+ if (demo.title)
+ modeattacking = ATTACKING_NONE;
+ demo.title = false;
+}
+
+void G_SaveDemo(void)
+{
+ if (!demobuf.p)
+ {
+ CONS_Alert(CONS_ERROR, "Failed to save Demo. No Demo pointer exists!\n");
+ // reset the demo buffer
+ G_ResetDemoRecording();
+ return;
+ }
+
+ if (demobuf.buffer == NULL)
+ {
+ CONS_Alert(CONS_ERROR, "Failed to save Demo. No Demo buffer allocated!\n");
+ // reset the demo buffer
+ G_ResetDemoRecording();
+ return;
+ }
+
+ UINT8 *p = demobuf.buffer+16; // after version
+ UINT32 length;
+
+ // Ensure extrainfo pointer is always available, even if no info is present.
+ if (demoinfo_p && *(UINT32 *)demoinfo_p == 0)
+ {
+ WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
+ *(UINT32 *)demoinfo_p = demobuf.p - demobuf.buffer;
+ }
+ WRITEUINT8(demobuf.p, DW_END); // Mark end of demo extra data.
+
+ M_Memcpy(p, demo.titlename, 64); // Write demo title here
+ p += 64;
+
+ if (multiplayer)
+ {
+ // Change the demo's name to be a slug of the title
+ char demo_slug[128];
+ char *writepoint;
+ size_t i, strindex = 0;
+ boolean dash = true;
+
+ for (i = 0; demo.titlename[i] && i < 127; i++)
+ {
+ if ((demo.titlename[i] >= 'a' && demo.titlename[i] <= 'z') ||
+ (demo.titlename[i] >= '0' && demo.titlename[i] <= '9'))
+ {
+ demo_slug[strindex] = demo.titlename[i];
+ strindex++;
+ dash = false;
+ }
+ else if (demo.titlename[i] >= 'A' && demo.titlename[i] <= 'Z')
+ {
+ demo_slug[strindex] = demo.titlename[i] + 'a' - 'A';
+ strindex++;
+ dash = false;
+ }
+ else if (!dash)
+ {
+ demo_slug[strindex] = '-';
+ strindex++;
+ dash = true;
+ }
+ }
+
+ demo_slug[strindex] = 0;
+ if (dash) demo_slug[strindex-1] = 0;
+
+ writepoint = strstr(demoname, "-") + 1;
+ demo_slug[128 - (writepoint - demoname) - 4] = 0;
+ sprintf(writepoint, "%s.lmp", demo_slug);
+ }
+
+ length = *(UINT32 *)demoinfo_p;
+ WRITEUINT32(demoinfo_p, length);
+#ifdef NOMD5
+ for (UINT8 k = 0; k < 16; k++, p++)
+ *p = M_RandomByte(); // This MD5 was chosen by fair dice roll and most likely < 50% correct.
+#else
+ // Make a checksum of everything after the checksum in the file up to the end of the standard data. Extrainfo is freely modifiable.
+ md5_buffer((char *)p+16, (demobuf.buffer + length) - (p+16), p);
+#endif
+
+
+ if (FIL_WriteFile(va(pandf, srb2home, demoname), demobuf.buffer, demobuf.p - demobuf.buffer)) // finally output the file.
+ demo.savemode = DSM_SAVED;
+
+ G_ResetDemoRecording();
+
+ if (modeattacking != ATTACKING_RECORD)
+ {
+ if (demo.savemode == DSM_SAVED)
+ CONS_Printf(M_GetText("Demo %s recorded\n"), demoname);
+ else
+ CONS_Alert(CONS_WARNING, M_GetText("Demo %s not saved\n"), demoname);
+ }
+}
+
+boolean G_DemoTitleResponder(event_t *ev)
+{
+ INT32 ch;
+
+ if (ev->type != ev_keydown)
+ return false;
+
+ ch = (INT32)ev->data1;
+
+ // Only ESC and non-keyboard keys abort connection
+ if (ch == KEY_ESCAPE)
+ {
+ demo.savemode = (cv_recordmultiplayerdemos.value == 2) ? DSM_WILLAUTOSAVE : DSM_NOTSAVING;
+ return true;
+ }
+
+ if (ch == KEY_ENTER || ch >= KEY_MOUSE1)
+ {
+ demo.savemode = DSM_WILLSAVE;
+ return true;
+ }
+
+ M_TextInputHandle(&demo.titlenameinput, ch);
+
+ return true;
+}
diff --git a/src/g_demo.h b/src/g_demo.h
new file mode 100644
index 000000000..de1495e91
--- /dev/null
+++ b/src/g_demo.h
@@ -0,0 +1,191 @@
+// SONIC ROBO BLAST 2 KART
+//-----------------------------------------------------------------------------
+// Copyright (C) 1993-1996 by id Software, Inc.
+// Copyright (C) 1998-2000 by DooM Legacy Team.
+// Copyright (C) 1999-2020 by Sonic Team Junior.
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+/// \file g_demo.h
+/// \brief Demo recording and playback
+
+#ifndef __G_DEMO__
+#define __G_DEMO__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "doomdef.h"
+#include "doomstat.h"
+#include "d_event.h"
+#include "p_saveg.h"
+#include "m_textinput.h"
+
+extern savebuffer_t demobuf;
+
+// demoplaying back and demo recording
+extern consvar_t cv_recordmultiplayerdemos, cv_netdemosyncquality, cv_maxdemosize, cv_demochangemap;
+extern consvar_t cv_demodateformat;
+extern consvar_t cv_resyncdemo;
+
+// Publicly-accessible demo vars
+struct demovars_s {
+ char titlename[65];
+ textinput_t titlenameinput;
+ boolean recording, playback, timing;
+ UINT16 version; // Current file format of the demo being played
+ boolean title; // Title Screen demo can be cancelled by any key
+ boolean rewinding; // Rewind in progress
+
+ boolean loadfiles, ignorefiles; // Demo file loading options
+ boolean fromtitle; // SRB2Kart: Don't stop the music
+ boolean inreplayhut; // Go back to replayhut after demos
+ boolean quitafterplaying; // quit after playing a demo from cmdline
+ boolean deferstart; // don't start playing demo right away
+
+ tic_t savebutton; // Used to determine when the local player can choose to save the replay while the race is still going
+ enum {
+ DSM_NOTSAVING,
+ DSM_WILLAUTOSAVE,
+ DSM_TITLEENTRY,
+ DSM_WILLSAVE,
+ DSM_SAVED
+ } savemode;
+};
+
+extern struct demovars_s demo;
+
+typedef enum {
+ MD_NOTLOADED,
+ MD_LOADED,
+ MD_SUBDIR,
+ MD_OUTDATED,
+ MD_INVALID
+} menudemotype_e;
+
+typedef struct menudemo_s {
+ char filepath[256];
+ menudemotype_e type;
+
+ char title[65]; // Null-terminated for string prints
+ char date[11]; // date when replay was recorded
+ char version[12]; // combined version and subversion
+ UINT16 map;
+ UINT8 addonstatus; // What do we need to do addon-wise to play this demo?
+ UINT8 gametype;
+ UINT8 kartspeed; // Add OR DF_ENCORE for encore mode, idk
+ UINT8 numlaps;
+
+ struct {
+ UINT8 ranking;
+ char name[17];
+ UINT8 skin, color;
+ UINT32 timeorscore;
+ } standings[MAXPLAYERS];
+} menudemo_t;
+
+extern mobj_t *metalplayback;
+
+// Only called by startup code.
+void G_RecordDemo(const char *name);
+void G_RecordMetal(void);
+void G_BeginRecording(void);
+void G_BeginMetal(void);
+
+// Only called by shutdown code.
+void G_WriteStanding(UINT8 ranking, char *name, INT32 skinnum, UINT8 color, UINT32 val);
+void G_SetDemoTime(UINT32 ptime, UINT32 plap);
+UINT8 G_CmpDemoTime(char *oldname, char *newname);
+
+void G_LoadDemoInfo(menudemo_t *pdemo);
+void G_LoadDemoTitle(menudemo_t *pdemo); // For use in replay search feature
+void G_DeferedPlayDemo(const char *demo);
+
+typedef enum
+{
+ GHC_NORMAL = 0,
+ GHC_SUPER,
+ GHC_FIREFLOWER,
+ GHC_INVINCIBLE
+} ghostcolor_t;
+
+extern UINT8 demo_extradata[MAXPLAYERS];
+extern UINT8 demo_writerng;
+#define DXD_RESPAWN 0x01 // "respawn" command in console
+#define DXD_SKIN 0x02 // skin changed
+#define DXD_NAME 0x04 // name changed
+#define DXD_COLOR 0x08 // color changed
+#define DXD_PLAYSTATE 0x10 // state changed between playing, spectating, or not in-game
+
+#define DXD_PST_PLAYING 0x01
+#define DXD_PST_SPECTATING 0x02
+#define DXD_PST_LEFT 0x03
+
+// Record/playback tics
+void G_ReadDemoExtraData(void);
+void G_WriteDemoExtraData(void);
+void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum);
+void G_WriteDemoTiccmd(ticcmd_t *cmd, INT32 playernum);
+void G_GhostAddThok(INT32 playernum);
+void G_GhostAddSpin(INT32 playernum);
+void G_GhostAddRev(INT32 playernum);
+void G_GhostAddColor(INT32 playernum, ghostcolor_t color);
+void G_GhostAddFlip(INT32 playernum);
+void G_GhostAddScale(INT32 playernum, fixed_t scale);
+void G_GhostAddHit(INT32 playernum, mobj_t *victim);
+void G_WriteAllGhostTics(void);
+void G_WriteGhostTic(mobj_t *ghost, INT32 playernum);
+void G_ConsAllGhostTics(void);
+void G_ConsGhostTic(INT32 playernum);
+void G_GhostTicker(void);
+
+void G_InitDemoRewind(void);
+void G_StoreRewindInfo(void);
+void G_PreviewRewind(tic_t previewtime);
+void G_ConfirmRewind(tic_t rewindtime);
+
+void G_ReadMetalTic(mobj_t *metal);
+void G_WriteMetalTic(mobj_t *metal);
+void G_SaveMetal(UINT8 **buffer);
+void G_LoadMetal(UINT8 **buffer);
+
+// Your naming conventions are stupid and useless.
+// There is no conflict here.
+typedef struct demoghost {
+ UINT8 checksum[16];
+ UINT8 *buffer, *p, color;
+ UINT16 version;
+ mobj_t oldmo, *mo;
+ struct demoghost *next;
+} demoghost;
+extern demoghost *ghosts;
+
+// G_CheckDemoExtraFiles: checks if our loaded WAD list matches the demo's.
+#define DFILE_ERROR_NOTLOADED 0x01 // Files are not loaded, but can be without a restart.
+#define DFILE_ERROR_OUTOFORDER 0x02 // Files are loaded, but out of order.
+#define DFILE_ERROR_INCOMPLETEOUTOFORDER 0x03 // Some files are loaded out of order, but others are not.
+#define DFILE_ERROR_CANNOTLOAD 0x04 // Files are missing and cannot be loaded.
+#define DFILE_ERROR_EXTRAFILES 0x05 // Extra files outside of the replay's file list are loaded.
+
+void G_ResetDemoRecording(void);
+void G_DoPlayDemo(char *defdemoname);
+void G_TimeDemo(const char *name);
+void G_AddGhost(char *defdemoname);
+void G_UpdateStaffGhostName(lumpnum_t l);
+void G_DoPlayMetal(void);
+void G_DoneLevelLoad(void);
+void G_StopMetalDemo(void);
+ATTRNORETURN void FUNCNORETURN G_StopMetalRecording(void);
+void G_StopDemo(void);
+boolean G_CheckDemoStatus(void);
+void G_SaveDemo(void);
+boolean G_DemoTitleResponder(event_t *ev);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // __G_DEMO__
diff --git a/src/g_game.c b/src/g_game.c
index 200ce7834..bedec3335 100644
--- a/src/g_game.c
+++ b/src/g_game.c
@@ -59,10 +59,6 @@
#include "discord.h"
#endif
-// for replay dates
-#include
-#include
-
gameaction_t gameaction;
gamestate_t gamestate = GS_NULL;
UINT8 ultimatemode = false;
@@ -87,8 +83,6 @@ static void G_DoContinued(void);
static void G_DoWorldDone(void);
static void G_DoStartVote(void);
-static void G_ResetDemoPlayback(char *pdemoname);
-
music_t mapmusic;
INT16 gamemap = 1;
@@ -108,15 +102,6 @@ UINT8 modeattacking = ATTACKING_NONE;
boolean imcontinuing = false;
boolean runemeraldmanager = false;
-// menu demo things
-UINT8 numDemos = 0; //3; -- i'm FED UP of losing my skincolour to a broken demo. change this back when we make new ones
-UINT32 demoDelayTime = 15*TICRATE;
-UINT32 demoIdleTime = 3*TICRATE;
-
-boolean nodrawers; // for comparative timing purposes
-boolean noblit; // for comparative timing purposes
-static tic_t demostarttime; // for comparative timing purposes
-
boolean netgame; // only true if packets are broadcast
boolean multiplayer;
boolean playeringame[MAXPLAYERS];
@@ -290,64 +275,8 @@ UINT32 timesBeaten;
UINT32 timesBeatenWithEmeralds;
//UINT32 timesBeatenUltimate;
-//@TODO put these all in a struct for namespacing purposes?
-static char demoname[128];
-savebuffer_t demobuf;
-static UINT8 *demotime_p, *demoinfo_p;
-static UINT8 *demoend;
-static UINT8 demoflags;
-static boolean demosynced = true; // console warning message
-
-struct demovars_s demo;
-
-boolean metalrecording; // recording as metal sonic
-mobj_t *metalplayback;
-static UINT8 *metalbuffer = NULL;
-static UINT8 *metal_p;
-static UINT16 metalversion;
-
-// extra data stuff (events registered this frame while recording)
-static struct {
- UINT8 flags; // EZT flags
-
- // EZT_COLOR
- UINT8 color, lastcolor;
-
- // EZT_SCALE
- fixed_t scale, lastscale;
-
- // EZT_KART
- INT32 kartitem, kartamount, kartbumpers;
-
- UINT8 desyncframes; // Don't try to resync unless we've been off for two frames, to monkeypatch a few trouble spots
-
- // EZT_HIT
- UINT16 hits;
- mobj_t **hitlist;
-} ghostext[MAXPLAYERS];
-
-// Your naming conventions are stupid and useless.
-// There is no conflict here.
-demoghost *ghosts = NULL;
-
INT16 prevmap, nextmap;
-static CV_PossibleValue_t recordmultiplayerdemos_cons_t[] = {{0, "Disabled"}, {1, "Manual Save"}, {2, "Auto Save"}, {0, NULL}};
-consvar_t cv_recordmultiplayerdemos = {"netdemo_record", "Manual Save", CV_SAVE, recordmultiplayerdemos_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
-
-static CV_PossibleValue_t netdemosyncquality_cons_t[] = {{1, "MIN"}, {35, "MAX"}, {0, NULL}};
-consvar_t cv_netdemosyncquality = {"netdemo_syncquality", "1", CV_SAVE, netdemosyncquality_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
-
-// Units are MiB.
-static CV_PossibleValue_t maxdemosize_cons_t[] = {{10, "MIN"}, {100, "MAX"}, {0, NULL}};
-consvar_t cv_maxdemosize = {"maxdemosize", "10", CV_SAVE, maxdemosize_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
-
-static CV_PossibleValue_t demochangemap_cons_t[] = {{0, "Disabled"}, {1, "Diff Map"}, {2, "Always"}, {0, NULL}};
-consvar_t cv_demochangemap = {"netdemo_savemapchange", "Disabled", CV_SAVE, demochangemap_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
-
-static CV_PossibleValue_t demodateformat_cons_t[] = {{0, "Automatic"}, {1, "EU"}, {2, "US"}, {0, NULL}};
-consvar_t cv_demodateformat = {"netdemo_dateformat", "Automatic", CV_SAVE, demodateformat_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
-
// Analog Control
void SendWeaponPref(void);
void SendWeaponPref2(void);
@@ -385,7 +314,8 @@ consvar_t cv_consolechat = {"chatmode", "Window", CV_SAVE, consolechat_cons_t, N
consvar_t cv_pauseifunfocused = {"pauseifunfocused", "Yes", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL};
// Display song credits
-consvar_t cv_songcredits = {"songcredits", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+static CV_PossibleValue_t songcredits_cons_t[] = {{0, "Off"}, {1, "Default"}, {2, "Box"}, {0, NULL}};
+consvar_t cv_songcredits = {"songcredits", "Default", CV_SAVE, songcredits_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
// Show "FREE PLAY" when you're alone. :(
consvar_t cv_showfreeplay = { "showfreeplay", "Yes", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL};
@@ -3998,7 +3928,6 @@ void G_InitNew(UINT8 pencoremode, const char *mapname, boolean resetplayer, bool
}
}
-
char *G_BuildMapTitle(INT32 mapnum)
{
char *title = NULL;
@@ -4290,3939 +4219,6 @@ INT32 G_FindMapByNameOrCode(const char *mapname, char **realmapnamep)
return newmapnum;
}
-//
-// DEMO RECORDING
-//
-
-#define DEMOVERSION 0x0002
-#define DEMOHEADER "\xF0" "KartReplay" "\x0F"
-
-#define DF_GHOST 0x01 // This demo contains ghost data too!
-#define DF_RECORDATTACK 0x02 // This demo is from record attack and contains its final completion time!
-#define DF_NIGHTSATTACK 0x04 // This demo is from NiGHTS attack and contains its time left, score, and mares!
-#define DF_ATTACKMASK 0x06 // This demo is from ??? attack and contains ???
-
-#define DF_LUAVARS 0x20 // this demo contains extra lua vars; this is mostly used for backwards compability
-
-#define DF_ATTACKSHIFT 1
-#define DF_ENCORE 0x40
-#define DF_MULTIPLAYER 0x80 // This demo was recorded in multiplayer mode!
-
-#ifdef DEMO_COMPAT_100
-#define DF_FILELIST 0x08 // This demo contains an extra files list
-#define DF_GAMETYPEMASK 0x30
-#define DF_GAMESHIFT 4
-#endif
-
-#define DEMO_SPECTATOR 0x40
-
-// For demos
-#define ZT_FWD 0x01
-#define ZT_SIDE 0x02
-#define ZT_ANGLE 0x04
-#define ZT_BUTTONS 0x08
-#define ZT_AIMING 0x10
-#define ZT_DRIFT 0x20
-#define ZT_LATENCY 0x40
-#define DEMOMARKER 0x80 // demoend
-
-UINT8 demo_extradata[MAXPLAYERS];
-UINT8 demo_writerng; // 0=no, 1=yes, 2=yes but on a timeout
-static ticcmd_t oldcmd[MAXPLAYERS];
-
-#define DW_END 0xFF // End of extradata block
-#define DW_RNG 0xFE // Check RNG seed!
-
-#define DW_EXTRASTUFF 0xFE // Numbers below this are reserved for writing player slot data
-
-// Below consts are only used for demo extrainfo sections
-#define DW_STANDING 0x00
-
-// For Metal Sonic and time attack ghosts
-#define GZT_XYZ 0x01
-#define GZT_MOMXY 0x02
-#define GZT_MOMZ 0x04
-#define GZT_ANGLE 0x08
-// Not used for Metal Sonic
-#define GZT_SPRITE 0x10 // Animation frame
-#define GZT_EXTRA 0x20
-#define GZT_NIGHTS 0x40 // NiGHTS Mode stuff!
-
-// GZT_EXTRA flags
-#define EZT_THOK 0x01 // Spawned a thok object
-#define EZT_SPIN 0x02 // Because one type of thok object apparently wasn't enough
-#define EZT_REV 0x03 // And two types wasn't enough either yet
-#define EZT_THOKMASK 0x03
-#define EZT_COLOR 0x04 // Changed color (Super transformation, Mario fireflowers/invulnerability, etc.)
-#define EZT_FLIP 0x08 // Reversed gravity
-#define EZT_SCALE 0x10 // Changed size
-#define EZT_HIT 0x20 // Damaged a mobj
-#define EZT_SPRITE 0x40 // Changed sprite set completely out of PLAY (NiGHTS, SOCs, whatever)
-#define EZT_KART 0x80 // SRB2Kart: Changed current held item/quantity and bumpers for battle
-
-static mobj_t oldmetal, oldghost[MAXPLAYERS];
-
-void G_SaveMetal(UINT8 **buffer)
-{
- I_Assert(buffer != NULL && *buffer != NULL);
-
- WRITEUINT32(*buffer, metal_p - metalbuffer);
-}
-
-void G_LoadMetal(UINT8 **buffer)
-{
- I_Assert(buffer != NULL && *buffer != NULL);
-
- G_DoPlayMetal();
- metal_p = metalbuffer + READUINT32(*buffer);
-}
-
-ticcmd_t *G_CopyTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n)
-{
- return M_Memcpy(dest, src, n*sizeof(*src));
-}
-
-ticcmd_t *G_MoveTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n)
-{
- size_t i;
- for (i = 0; i < n; i++)
- {
- dest[i].forwardmove = src[i].forwardmove;
- dest[i].sidemove = src[i].sidemove;
- dest[i].angleturn = SHORT(src[i].angleturn);
- dest[i].aiming = (INT16)SHORT(src[i].aiming);
- dest[i].buttons = (UINT16)SHORT(src[i].buttons);
- dest[i].driftturn = (INT16)SHORT(src[i].driftturn);
- dest[i].latency = (INT16)SHORT(src[i].latency);
- }
- return dest;
-}
-
-// Finds a skin with the closest stats if the expected skin doesn't exist.
-static INT32 GetSkinNumClosestToStats(UINT8 kartspeed, UINT8 kartweight)
-{
- INT32 i, closest_skin = 0;
- UINT8 closest_stats = UINT8_MAX, stat_diff;
-
- for (i = 0; i < numskins; i++)
- {
- stat_diff = abs(skins[i].kartspeed - kartspeed) + abs(skins[i].kartweight - kartweight);
- if (stat_diff < closest_stats)
- {
- closest_stats = stat_diff;
- closest_skin = i;
- }
- }
-
- return closest_skin;
-}
-
-static void FindClosestSkinForStats(UINT32 p, UINT8 kartspeed, UINT8 kartweight)
-{
- INT32 closest_skin = GetSkinNumClosestToStats(kartspeed, kartweight);
-
- //CONS_Printf("Using %s instead...\n", skins[closest_skin].name);
- SetPlayerSkinByNum(p, closest_skin);
-}
-
-void G_ReadDemoExtraData(void)
-{
- INT32 p, extradata, i;
- char name[17];
-
- if (leveltime > starttime)
- {
- rewind_t *rewind = CL_SaveRewindPoint(demobuf.p - demobuf.buffer);
- if (rewind)
- {
- memcpy(rewind->oldcmd, oldcmd, sizeof (oldcmd));
- memcpy(rewind->oldghost, oldghost, sizeof (oldghost));
- }
- }
-
- memset(name, '\0', 17);
-
- p = READUINT8(demobuf.p);
-
- while (p < DW_EXTRASTUFF)
- {
- extradata = READUINT8(demobuf.p);
-
- if (extradata & DXD_RESPAWN)
- {
- if (players[p].mo)
- P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL); // Is this how this should work..?
- }
- if (extradata & DXD_SKIN)
- {
- UINT8 kartspeed, kartweight;
-
- // Skin
- M_Memcpy(name, demobuf.p, 16);
- demobuf.p += 16;
- SetPlayerSkin(p, name);
-
- kartspeed = READUINT8(demobuf.p);
- kartweight = READUINT8(demobuf.p);
-
- if (stricmp(skins[players[p].skin].name, name) != 0)
- FindClosestSkinForStats(p, kartspeed, kartweight);
-
- players[p].kartspeed = kartspeed;
- players[p].kartweight = kartweight;
- }
- if (extradata & DXD_COLOR)
- {
- // Color
- M_Memcpy(name, demobuf.p, 16);
- demobuf.p += 16;
- for (i = 0; i < MAXSKINCOLORS; i++)
- if (!stricmp(KartColor_Names[i], name)) // SRB2kart
- {
- players[p].skincolor = i;
- if (players[p].mo)
- players[p].mo->color = i;
- break;
- }
- }
- if (extradata & DXD_NAME)
- {
- // Name
- M_Memcpy(player_names[p],demobuf.p,16);
- demobuf.p += 16;
- }
- if (extradata & DXD_PLAYSTATE)
- {
- extradata = READUINT8(demobuf.p);
-
- switch (extradata) {
- case DXD_PST_PLAYING:
- players[p].pflags |= PF_WANTSTOJOIN; // fuck you
- break;
-
- case DXD_PST_SPECTATING:
- players[p].pflags &= ~PF_WANTSTOJOIN; // double-fuck you
- if (!playeringame[p])
- {
- CL_ClearPlayer(p);
- playeringame[p] = true;
- G_AddPlayer(p);
- players[p].spectator = true;
-
- // There's likely an off-by-one error in timing recording or playback of joins. This hacks around it so I don't have to find out where that is. \o/
- if (oldcmd[p].forwardmove)
- P_RandomByte();
- }
- else
- {
- players[p].spectator = true;
- if (players[p].mo)
- P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL);
- else
- players[p].playerstate = PST_REBORN;
- }
- break;
-
- case DXD_PST_LEFT:
- CL_RemovePlayer(p, 0);
- break;
- }
-
- G_ResetViews();
-
- // maybe these are necessary?
- if (G_BattleGametype())
- K_CheckBumpers(); // SRB2Kart
- else if (G_RaceGametype())
- P_CheckRacers(); // also SRB2Kart
- }
-
-
- p = READUINT8(demobuf.p);
- }
-
- while (p != DW_END)
- {
- UINT32 rng;
- UINT32 checkrng;
-
- switch (p)
- {
- case DW_RNG:
- rng = READUINT32(demobuf.p);
- checkrng = P_GetRandSeed();
- if (checkrng != rng)
- {
- if (demosynced)
- {
- CONS_Alert(CONS_WARNING, M_GetText("Demo playback has desynced (RNG)!\n"));
- CONS_Printf("expected rng %d got %d\n", rng, checkrng);
- }
- demosynced = false;
-
- P_SetRandSeed(rng);
- }
- }
-
- p = READUINT8(demobuf.p);
- }
-
- if (!(demoflags & DF_GHOST) && *demobuf.p == DEMOMARKER)
- {
- // end of demo data stream
- G_CheckDemoStatus();
- return;
- }
-}
-
-void G_WriteDemoExtraData(void)
-{
- INT32 i;
- char name[17];
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- if (demo_extradata[i])
- {
- WRITEUINT8(demobuf.p, i);
- WRITEUINT8(demobuf.p, demo_extradata[i]);
-
- //if (demo_extradata[i] & DXD_RESPAWN) has no extra data
- if (demo_extradata[i] & DXD_SKIN)
- {
- // Skin
- memset(name, 0, 16);
- strncpy(name, skins[players[i].skin].name, 16);
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
-
- WRITEUINT8(demobuf.p, skins[players[i].skin].kartspeed);
- WRITEUINT8(demobuf.p, skins[players[i].skin].kartweight);
- }
- if (demo_extradata[i] & DXD_COLOR)
- {
- // Color
- memset(name, 0, 16);
- strncpy(name, KartColor_Names[players[i].skincolor], 16);
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
- }
- if (demo_extradata[i] & DXD_NAME)
- {
- // Name
- memset(name, 0, 16);
- memcpy(name, player_names[i], 15); // Keeping 1 null byte for safety, sorry players with name containing more than 15 characters
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
- }
- if (demo_extradata[i] & DXD_PLAYSTATE)
- {
- demo_writerng = 1;
- if (!playeringame[i])
- WRITEUINT8(demobuf.p, DXD_PST_LEFT);
- else if (
- players[i].spectator &&
- !(players[i].pflags & PF_WANTSTOJOIN) // <= fuck you specifically
- )
- WRITEUINT8(demobuf.p, DXD_PST_SPECTATING);
- else
- WRITEUINT8(demobuf.p, DXD_PST_PLAYING);
- }
- }
-
- demo_extradata[i] = 0;
- }
-
- // May not be necessary, but might as well play it safe...
- if ((leveltime & 255) == 128)
- demo_writerng = 1;
-
- {
- static UINT8 timeout = 0;
-
- if (timeout) timeout--;
-
- if (demo_writerng == 1 || (demo_writerng == 2 && timeout == 0))
- {
- demo_writerng = 0;
- timeout = 16;
- WRITEUINT8(demobuf.p, DW_RNG);
- WRITEUINT32(demobuf.p, P_GetRandSeed());
- }
- }
-
- WRITEUINT8(demobuf.p, DW_END);
-}
-
-void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum)
-{
- UINT8 ziptic;
-
- if (!demobuf.p || !demo.deferstart)
- return;
- ziptic = READUINT8(demobuf.p);
-
- if (ziptic & ZT_FWD)
- oldcmd[playernum].forwardmove = READSINT8(demobuf.p);
- if (ziptic & ZT_SIDE)
- oldcmd[playernum].sidemove = READSINT8(demobuf.p);
- if (ziptic & ZT_ANGLE)
- oldcmd[playernum].angleturn = READINT16(demobuf.p);
- if (ziptic & ZT_BUTTONS)
- oldcmd[playernum].buttons = READUINT16(demobuf.p);
- if (ziptic & ZT_AIMING)
- oldcmd[playernum].aiming = READINT16(demobuf.p);
- if (ziptic & ZT_DRIFT)
- oldcmd[playernum].driftturn = READINT16(demobuf.p);
- if (ziptic & ZT_LATENCY)
- oldcmd[playernum].latency = READUINT8(demobuf.p);
-
- G_CopyTiccmd(cmd, &oldcmd[playernum], 1);
-
- // SRB2kart: Copy-pasted from ticcmd building, removes that crappy demo cam
- if (((players[displayplayers[0]].mo && players[displayplayers[0]].speed > 0) // Moving
- || (leveltime > starttime && (cmd->buttons & BT_ACCELERATE && cmd->buttons & BT_BRAKE)) // Rubber-burn turn
- || (players[displayplayers[0]].kartstuff[k_respawn]) // Respawning
- || (players[displayplayers[0]].spectator || objectplacing)) // Not a physical player
- && !(players[displayplayers[0]].kartstuff[k_spinouttimer] && players[displayplayers[0]].kartstuff[k_sneakertimer])) // Spinning and boosting cancels out spinout
- localangle[0] += (cmd->angleturn<<16);
-
- if (!(demoflags & DF_GHOST) && *demobuf.p == DEMOMARKER)
- {
- // end of demo data stream
- G_CheckDemoStatus();
- return;
- }
-}
-
-void G_WriteDemoTiccmd(ticcmd_t *cmd, INT32 playernum)
-{
- char ziptic = 0;
- UINT8 *ziptic_p;
-
- if (!demobuf.p)
- return;
-
- ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
-
- if (cmd->forwardmove != oldcmd[playernum].forwardmove)
- {
- WRITEUINT8(demobuf.p,cmd->forwardmove);
- oldcmd[playernum].forwardmove = cmd->forwardmove;
- ziptic |= ZT_FWD;
- }
-
- if (cmd->sidemove != oldcmd[playernum].sidemove)
- {
- WRITEUINT8(demobuf.p,cmd->sidemove);
- oldcmd[playernum].sidemove = cmd->sidemove;
- ziptic |= ZT_SIDE;
- }
-
- if (cmd->angleturn != oldcmd[playernum].angleturn)
- {
- WRITEINT16(demobuf.p,cmd->angleturn);
- oldcmd[playernum].angleturn = cmd->angleturn;
- ziptic |= ZT_ANGLE;
- }
-
- if (cmd->buttons != oldcmd[playernum].buttons)
- {
- WRITEUINT16(demobuf.p,cmd->buttons);
- oldcmd[playernum].buttons = cmd->buttons;
- ziptic |= ZT_BUTTONS;
- }
-
- if (cmd->aiming != oldcmd[playernum].aiming)
- {
- WRITEINT16(demobuf.p,cmd->aiming);
- oldcmd[playernum].aiming = cmd->aiming;
- ziptic |= ZT_AIMING;
- }
-
- if (cmd->driftturn != oldcmd[playernum].driftturn)
- {
- WRITEINT16(demobuf.p,cmd->driftturn);
- oldcmd[playernum].driftturn = cmd->driftturn;
- ziptic |= ZT_DRIFT;
- }
-
- if (cmd->latency != oldcmd[playernum].latency)
- {
- WRITEUINT8(demobuf.p,cmd->latency);
- oldcmd[playernum].latency = cmd->latency;
- ziptic |= ZT_LATENCY;
- }
-
- *ziptic_p = ziptic;
-
- // attention here for the ticcmd size!
- // latest demos with mouse aiming byte in ticcmd
- if (!(demoflags & DF_GHOST) && ziptic_p > demoend - 9)
- {
- G_CheckDemoStatus(); // no more space
- return;
- }
-}
-
-void G_GhostAddThok(INT32 playernum)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_THOK;
-}
-
-void G_GhostAddSpin(INT32 playernum)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_SPIN;
-}
-
-void G_GhostAddRev(INT32 playernum)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- ghostext[playernum].flags = (ghostext[playernum].flags & ~EZT_THOKMASK) | EZT_REV;
-}
-
-void G_GhostAddFlip(INT32 playernum)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- ghostext[playernum].flags |= EZT_FLIP;
-}
-
-void G_GhostAddColor(INT32 playernum, ghostcolor_t color)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- if (ghostext[playernum].lastcolor == (UINT8)color)
- {
- ghostext[playernum].flags &= ~EZT_COLOR;
- return;
- }
-
- ghostext[playernum].flags |= EZT_COLOR;
- ghostext[playernum].color = (UINT8)color;
-}
-
-void G_GhostAddScale(INT32 playernum, fixed_t scale)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- if (ghostext[playernum].lastscale == scale)
- {
- ghostext[playernum].flags &= ~EZT_SCALE;
- return;
- }
-
- ghostext[playernum].flags |= EZT_SCALE;
- ghostext[playernum].scale = scale;
-}
-
-void G_GhostAddHit(INT32 playernum, mobj_t *victim)
-{
- if (!demo.recording || !(demoflags & DF_GHOST))
- return;
-
- ghostext[playernum].flags |= EZT_HIT;
- ghostext[playernum].hits++;
- ghostext[playernum].hitlist = Z_Realloc(ghostext[playernum].hitlist, ghostext[playernum].hits * sizeof(mobj_t *), PU_LEVEL, &ghostext[playernum].hitlist);
- P_SetTarget(ghostext[playernum].hitlist + (ghostext[playernum].hits-1), victim);
-}
-
-void G_WriteAllGhostTics(void)
-{
- if (!demobuf.p)
- return;
-
- UINT8 *save_demo_p = demobuf.p;
-#define CHECKSPACE(num) if (demobuf.p+(num) > demoend) { demobuf.p = save_demo_p; G_CheckDemoStatus(); return; }
-
- boolean toobig = false;
- INT32 i, counter = leveltime;
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- if (!playeringame[i] || players[i].spectator)
- continue;
-
- if (P_MobjWasRemoved(players[i].mo))
- continue;
-
- counter++;
-
- if (multiplayer && ((counter % cv_netdemosyncquality.value) != 0)) // Only write 1 in this many ghost datas per tic to cut down on multiplayer replay size.
- continue;
-
- if (((ghostext[i].flags && (ghostext[i].flags & EZT_HIT)) || ghostext[i].hits)
- && !ghostext[i].hitlist) // hitlist might be freed during resynch, beware PU_LEVEL!
- {
- ghostext[i].hits = 0;
- continue;
- }
-
- CHECKSPACE(1);
-
- WRITEUINT8(demobuf.p, i);
- G_WriteGhostTic(players[i].mo, i);
-
- // attention here for the ticcmd size!
- // latest demos with mouse aiming byte in ticcmd
- if (demobuf.p >= demoend - (13 + 9 + 9))
- {
- toobig = true;
- break;
- }
- }
-
- CHECKSPACE(1);
- WRITEUINT8(demobuf.p, 0xFF);
-
- if (toobig)
- {
- G_CheckDemoStatus(); // no more space
- return;
- }
-
-#undef CHECKSPACE
-}
-
-void G_WriteGhostTic(mobj_t *ghost, INT32 playernum)
-{
- char ziptic = 0;
- UINT8 *ziptic_p;
- UINT32 i;
- UINT8 sprite;
- UINT8 frame;
-
- if (!demobuf.p)
- return;
-
- UINT8 *save_demo_p = demobuf.p;
-#define CHECKSPACE(num) if (demobuf.p+(num) > demoend) { demobuf.p = save_demo_p; G_CheckDemoStatus(); return; }
-
- if (!(demoflags & DF_GHOST))
- return; // No ghost data to write.
-
- if (ghost->player && ghost->player->pflags & PF_NIGHTSMODE && ghost->tracer)
- {
- // We're talking about the NiGHTS thing, not the normal platforming thing!
- ziptic |= GZT_NIGHTS;
- ghost = ghost->tracer;
- }
-
- ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
-
-#define MAXMOM (0x7FFF<<8)
-
- // GZT_XYZ is only useful if you've moved 256 FRACUNITS or more in a single tic.
- if (abs(ghost->x-oldghost[playernum].x) > MAXMOM
- || abs(ghost->y-oldghost[playernum].y) > MAXMOM
- || abs(ghost->z-oldghost[playernum].z) > MAXMOM
- || ((UINT8)(leveltime & 255) > 0 && (UINT8)(leveltime & 255) <= (UINT8)cv_netdemosyncquality.value)) // Hack to enable slightly nicer resyncing
- {
- oldghost[playernum].x = ghost->x;
- oldghost[playernum].y = ghost->y;
- oldghost[playernum].z = ghost->z;
- ziptic |= GZT_XYZ;
-
- CHECKSPACE(sizeof(fixed_t)*3);
- WRITEFIXED(demobuf.p, oldghost[playernum].x);
- WRITEFIXED(demobuf.p, oldghost[playernum].y);
- WRITEFIXED(demobuf.p, oldghost[playernum].z);
- }
- else
- {
- // For moving normally:
- // Store one full byte of movement, plus one byte of fractional movement.
- INT16 momx = (INT16)((ghost->x-oldghost[playernum].x + (1<<4))>>8);
- INT16 momy = (INT16)((ghost->y-oldghost[playernum].y + (1<<4))>>8);
-
- if (momx != oldghost[playernum].momx
- || momy != oldghost[playernum].momy)
- {
- oldghost[playernum].momx = momx;
- oldghost[playernum].momy = momy;
- ziptic |= GZT_MOMXY;
-
- CHECKSPACE(4);
-
- WRITEINT16(demobuf.p, momx);
- WRITEINT16(demobuf.p, momy);
- }
-
- momx = (INT16)((ghost->z-oldghost[playernum].z + (1<<4))>>8);
-
- if (momx != oldghost[playernum].momz)
- {
- oldghost[playernum].momz = momx;
- ziptic |= GZT_MOMZ;
-
- CHECKSPACE(2);
-
- WRITEINT16(demobuf.p, momx);
- }
-
- // This SHOULD set oldghost.x/y/z to match ghost->x/y/z
- // but it keeps the fractional loss of one byte,
- // so it will hopefully be made up for in future tics.
- oldghost[playernum].x += oldghost[playernum].momx<<8;
- oldghost[playernum].y += oldghost[playernum].momy<<8;
- oldghost[playernum].z += oldghost[playernum].momz<<8;
- }
-
-#undef MAXMOM
-
- // Only store the 8 most relevant bits of angle
- // because exact values aren't too easy to discern to begin with when only 8 angles have different sprites
- // and it does not affect this mode of movement at all anyway.
- if (ghost->angle>>24 != oldghost[playernum].angle)
- {
- oldghost[playernum].angle = ghost->angle>>24;
- ziptic |= GZT_ANGLE;
-
- CHECKSPACE(1);
-
- WRITEUINT8(demobuf.p, oldghost[playernum].angle);
- }
-
- // Store the sprite frame.
- frame = ghost->frame & 0xFF;
- if (frame != oldghost[playernum].frame)
- {
- oldghost[playernum].frame = frame;
- ziptic |= GZT_SPRITE;
-
- CHECKSPACE(1);
-
- WRITEUINT8(demobuf.p, oldghost[playernum].frame);
- }
-
- // Check for sprite set changes
- sprite = ghost->sprite;
- if (sprite != oldghost[playernum].sprite)
- {
- oldghost[playernum].sprite = sprite;
- ghostext[playernum].flags |= EZT_SPRITE;
- }
-
- if (ghost->player)
- {
- if (
- ghostext[playernum].kartitem != ghost->player->kartstuff[k_itemtype] ||
- ghostext[playernum].kartamount != ghost->player->kartstuff[k_itemamount] ||
- ghostext[playernum].kartbumpers != ghost->player->kartstuff[k_bumper]
- )
- {
- ghostext[playernum].flags |= EZT_KART;
- ghostext[playernum].kartitem = ghost->player->kartstuff[k_itemtype];
- ghostext[playernum].kartamount = ghost->player->kartstuff[k_itemamount];
- ghostext[playernum].kartbumpers = ghost->player->kartstuff[k_bumper];
-
- }
- }
-
- if (ghostext[playernum].color == ghostext[playernum].lastcolor)
- ghostext[playernum].flags &= ~EZT_COLOR;
-
- if (ghostext[playernum].scale == ghostext[playernum].lastscale)
- ghostext[playernum].flags &= ~EZT_SCALE;
-
- if (ghostext[playernum].flags)
- {
- ziptic |= GZT_EXTRA;
- WRITEUINT8(demobuf.p, ghostext[playernum].flags);
-
- if (ghostext[playernum].flags & EZT_COLOR)
- {
- CHECKSPACE(1);
- WRITEUINT8(demobuf.p, ghostext[playernum].color);
- ghostext[playernum].lastcolor = ghostext[playernum].color;
- }
-
- if (ghostext[playernum].flags & EZT_SCALE)
- {
- CHECKSPACE(sizeof(fixed_t));
- WRITEFIXED(demobuf.p, ghostext[playernum].scale);
- ghostext[playernum].lastscale = ghostext[playernum].scale;
- }
-
- if (ghostext[playernum].flags & EZT_HIT)
- {
- CHECKSPACE(2);
- WRITEUINT16(demobuf.p, ghostext[playernum].hits);
-
- for (i = 0; i < ghostext[playernum].hits; i++)
- {
- mobj_t *mo = ghostext[playernum].hitlist[i];
-
- CHECKSPACE(4+4+2+sizeof(fixed_t)*3+sizeof(angle_t));
-
- WRITEUINT32(demobuf.p, UINT32_MAX); // reserved for some method of determining exactly which mobj this is. (mobjnum doesn't work here.)
- WRITEUINT32(demobuf.p, mo->type);
- WRITEUINT16(demobuf.p, (UINT16)mo->health);
- WRITEFIXED(demobuf.p, mo->x);
- WRITEFIXED(demobuf.p, mo->y);
- WRITEFIXED(demobuf.p, mo->z);
- WRITEANGLE(demobuf.p, mo->angle);
- P_SetTarget(ghostext[playernum].hitlist+i, NULL);
- }
-
- ghostext[playernum].hits = 0;
- }
-
- if (ghostext[playernum].flags & EZT_SPRITE)
- {
- CHECKSPACE(1);
- WRITEUINT8(demobuf.p, sprite);
- }
-
- if (ghostext[playernum].flags & EZT_KART)
- {
- CHECKSPACE(12);
- WRITEINT32(demobuf.p, ghostext[playernum].kartitem);
- WRITEINT32(demobuf.p, ghostext[playernum].kartamount);
- WRITEINT32(demobuf.p, ghostext[playernum].kartbumpers);
- }
-
- ghostext[playernum].flags = 0;
- }
-
- *ziptic_p = ziptic;
-#undef CHECKSPACE
-}
-
-void G_ConsAllGhostTics(void)
-{
- UINT8 p;
-
- if (!demobuf.p || !demo.deferstart)
- return;
-
- p = READUINT8(demobuf.p);
-
- while (p != 0xFF)
- {
- G_ConsGhostTic(p);
- p = READUINT8(demobuf.p);
- }
-
- if (*demobuf.p == DEMOMARKER)
- {
- // end of demo data stream
- G_CheckDemoStatus();
- return;
- }
-}
-
-// Uses ghost data to do consistency checks on your position.
-// This fixes desynchronising demos when fighting eggman.
-void G_ConsGhostTic(INT32 playernum)
-{
- UINT8 ziptic;
- fixed_t px,py,pz,gx,gy,gz;
- mobj_t *testmo;
- fixed_t syncleeway;
- boolean nightsfail = false;
-
- if (!(demoflags & DF_GHOST))
- return; // No ghost data to use.
-
- testmo = players[playernum].mo;
-
- // Grab ghost data.
- ziptic = READUINT8(demobuf.p);
-
- if (ziptic & GZT_XYZ)
- {
- oldghost[playernum].x = READFIXED(demobuf.p);
- oldghost[playernum].y = READFIXED(demobuf.p);
- oldghost[playernum].z = READFIXED(demobuf.p);
- syncleeway = 0;
- }
- else
- {
- if (ziptic & GZT_MOMXY)
- {
- oldghost[playernum].momx = READINT16(demobuf.p)<<8;
- oldghost[playernum].momy = READINT16(demobuf.p)<<8;
- }
-
- if (ziptic & GZT_MOMZ)
- oldghost[playernum].momz = READINT16(demobuf.p)<<8;
-
- oldghost[playernum].x += oldghost[playernum].momx;
- oldghost[playernum].y += oldghost[playernum].momy;
- oldghost[playernum].z += oldghost[playernum].momz;
- syncleeway = FRACUNIT;
- }
-
- if (ziptic & GZT_ANGLE)
- demobuf.p++;
-
- if (ziptic & GZT_SPRITE)
- demobuf.p++;
-
- if (ziptic & GZT_NIGHTS)
- {
- if (!testmo || !testmo->player || !(testmo->player->pflags & PF_NIGHTSMODE) || !testmo->tracer)
- nightsfail = true;
- else
- testmo = testmo->tracer;
- }
-
- if (ziptic & GZT_EXTRA)
- { // But wait, there's more!
- ziptic = READUINT8(demobuf.p);
- if (ziptic & EZT_COLOR)
- demobuf.p++;
-
- if (ziptic & EZT_SCALE)
- demobuf.p += sizeof(fixed_t);
-
- if (ziptic & EZT_HIT)
- { // Resync mob damage.
- UINT16 i, count = READUINT16(demobuf.p);
- thinker_t *th;
- mobj_t *mobj;
-
- UINT32 type;
- UINT16 health;
- fixed_t x;
- fixed_t y;
- fixed_t z;
-
- for (i = 0; i < count; i++)
- {
- demobuf.p += 4; // reserved.
- type = READUINT32(demobuf.p);
- health = READUINT16(demobuf.p);
- x = READFIXED(demobuf.p);
- y = READFIXED(demobuf.p);
- z = READFIXED(demobuf.p);
- demobuf.p += sizeof(angle_t); // angle, unnecessary for cons.
-
- mobj = NULL;
- for (th = thinkercap.next; th != &thinkercap; th = th->next)
- {
- if (th->function.acp1 != (actionf_p1)P_MobjThinker)
- continue;
- mobj = (mobj_t *)th;
- if (mobj->type == (mobjtype_t)type && mobj->x == x && mobj->y == y && mobj->z == z)
- break;
- mobj = NULL; // wasn't this one, keep searching.
- }
-
- if (mobj && mobj->health != health) // Wasn't damaged?! This is desync! Fix it!
- {
- if (demosynced)
- {
- CONS_Alert(CONS_WARNING, M_GetText("Demo playback has desynced (health)!\n"));
- CONS_Printf("expected health %d got %d\n", health, mobj->health);
- }
-
- demosynced = false;
- P_DamageMobj(mobj, players[0].mo, players[0].mo, 1);
- }
- }
- }
-
- if (ziptic & EZT_SPRITE)
- demobuf.p++;
-
- if (ziptic & EZT_KART)
- {
- ghostext[playernum].kartitem = READINT32(demobuf.p);
- ghostext[playernum].kartamount = READINT32(demobuf.p);
- ghostext[playernum].kartbumpers = READINT32(demobuf.p);
- }
- }
-
- if (testmo)
- {
- // Re-synchronise
- px = testmo->x;
- py = testmo->y;
- pz = testmo->z;
- gx = oldghost[playernum].x;
- gy = oldghost[playernum].y;
- gz = oldghost[playernum].z;
-
- if (nightsfail || abs(px-gx) > syncleeway || abs(py-gy) > syncleeway || abs(pz-gz) > syncleeway)
- {
- ghostext[playernum].desyncframes++;
-
- if (ghostext[playernum].desyncframes >= 2)
- {
- if (demosynced)
- CONS_Alert(CONS_WARNING, "Demo playback has desynced (player %s)!\n", player_names[playernum]);
- demosynced = false;
-
- P_UnsetThingPosition(testmo);
- testmo->x = oldghost[playernum].x;
- testmo->y = oldghost[playernum].y;
- P_SetThingPosition(testmo);
- testmo->z = oldghost[playernum].z;
-
- if (abs(testmo->z - testmo->floorz) < 4*FRACUNIT)
- testmo->z = testmo->floorz; // Sync players to the ground when they're likely supposed to be there...
-
- ghostext[playernum].desyncframes = 2;
- }
- }
- else
- ghostext[playernum].desyncframes = 0;
-
- if (
-#ifdef DEMO_COMPAT_100
- demo.version != 0x0001 &&
-#endif
- (
- players[playernum].kartstuff[k_itemtype] != ghostext[playernum].kartitem ||
- players[playernum].kartstuff[k_itemamount] != ghostext[playernum].kartamount ||
- players[playernum].kartstuff[k_bumper] != ghostext[playernum].kartbumpers
- )
- )
- {
- if (demosynced)
- {
- CONS_Alert(CONS_WARNING, "Demo playback has desynced (item/bumpers)!(player %s)!\n", player_names[playernum]);
- CONS_Printf("expected item type %d got %d\n", ghostext[playernum].kartitem, players[playernum].kartstuff[k_itemtype]);
- CONS_Printf("expected item amount %d got %d\n", ghostext[playernum].kartamount, players[playernum].kartstuff[k_itemamount]);
- }
- demosynced = false;
-
- players[playernum].kartstuff[k_itemtype] = ghostext[playernum].kartitem;
- players[playernum].kartstuff[k_itemamount] = ghostext[playernum].kartamount;
- players[playernum].kartstuff[k_bumper] = ghostext[playernum].kartbumpers;
- }
- }
-
- if (*demobuf.p == DEMOMARKER)
- {
- // end of demo data stream
- G_CheckDemoStatus();
- return;
- }
-}
-
-void G_GhostTicker(void)
-{
- demoghost *g,*p;
-
- for (g = ghosts, p = NULL; g; g = g->next)
- {
- // Skip normal demo data.
- UINT8 ziptic = READUINT8(g->p);
-
-#ifdef DEMO_COMPAT_100
- if (g->version != 0x0001)
- {
-#endif
- while (ziptic != DW_END) // Get rid of extradata stuff
- {
- if (ziptic == 0) // Only support player 0 info for now
- {
- ziptic = READUINT8(g->p);
- if (ziptic & DXD_SKIN)
- g->p += 18; // We _could_ read this info, but it shouldn't change anything in record attack...
- if (ziptic & DXD_COLOR)
- g->p += 16; // Same tbh
- if (ziptic & DXD_NAME)
- g->p += 16; // yea
- if (ziptic & DXD_PLAYSTATE && READUINT8(g->p) != DXD_PST_PLAYING)
- I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
- }
- else if (ziptic == DW_RNG)
- g->p += 4; // RNG seed
- else
- I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
-
- ziptic = READUINT8(g->p);
- }
-
- ziptic = READUINT8(g->p); // Back to actual ziptic stuff
-#ifdef DEMO_COMPAT_100
- }
-#endif
-
- if (ziptic & ZT_FWD)
- g->p++;
- if (ziptic & ZT_SIDE)
- g->p++;
- if (ziptic & ZT_ANGLE)
- g->p += 2;
- if (ziptic & ZT_BUTTONS)
- g->p += 2;
- if (ziptic & ZT_AIMING)
- g->p += 2;
- if (ziptic & ZT_DRIFT)
- g->p += 2;
- if (ziptic & ZT_LATENCY)
- g->p += 1;
-
- // Grab ghost data.
- ziptic = READUINT8(g->p);
-
-#ifdef DEMO_COMPAT_100
- if (g->version != 0x0001)
- {
-#endif
- if (ziptic == 0xFF)
- goto skippedghosttic; // Didn't write ghost info this frame
- else if (ziptic != 0)
- I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
- ziptic = READUINT8(g->p);
-#ifdef DEMO_COMPAT_100
- }
-#endif
- if (ziptic & GZT_XYZ)
- {
- g->oldmo.x = READFIXED(g->p);
- g->oldmo.y = READFIXED(g->p);
- g->oldmo.z = READFIXED(g->p);
- }
- else
- {
- if (ziptic & GZT_MOMXY)
- {
- g->oldmo.momx = READINT16(g->p)<<8;
- g->oldmo.momy = READINT16(g->p)<<8;
- }
- if (ziptic & GZT_MOMZ)
- g->oldmo.momz = READINT16(g->p)<<8;
- g->oldmo.x += g->oldmo.momx;
- g->oldmo.y += g->oldmo.momy;
- g->oldmo.z += g->oldmo.momz;
- }
- if (ziptic & GZT_ANGLE)
- g->oldmo.angle = READUINT8(g->p)<<24;
- if (ziptic & GZT_SPRITE)
- g->oldmo.frame = READUINT8(g->p);
-
- // Update ghost
- P_UnsetThingPosition(g->mo);
- g->mo->x = g->oldmo.x;
- g->mo->y = g->oldmo.y;
- g->mo->z = g->oldmo.z;
- P_SetThingPosition(g->mo);
- g->mo->angle = g->oldmo.angle;
- g->mo->frame = g->oldmo.frame | tr_trans30<p);
- if (ziptic & EZT_COLOR)
- {
- g->color = READUINT8(g->p);
- switch(g->color)
- {
- default:
- case GHC_NORMAL: // Go back to skin color
- g->mo->color = g->oldmo.color;
- break;
- // Handled below
- case GHC_SUPER:
- case GHC_INVINCIBLE:
- break;
- case GHC_FIREFLOWER: // Fireflower
- g->mo->color = SKINCOLOR_WHITE;
- break;
- }
- }
- if (ziptic & EZT_FLIP)
- g->mo->eflags ^= MFE_VERTICALFLIP;
- if (ziptic & EZT_SCALE)
- {
- g->mo->destscale = READFIXED(g->p);
- if (g->mo->destscale != g->mo->scale)
- P_SetScale(g->mo, g->mo->destscale);
- }
- if (ziptic & EZT_THOKMASK)
- { // Let's only spawn ONE of these per frame, thanks.
- mobj_t *mobj;
- INT32 type = -1;
- if (g->mo->skin)
- {
- switch (ziptic & EZT_THOKMASK)
- {
- case EZT_THOK:
- type = (UINT32)mobjinfo[MT_PLAYER].painchance;
- break;
- case EZT_SPIN:
- type = (UINT32)mobjinfo[MT_PLAYER].damage;
- break;
- case EZT_REV:
- type = (UINT32)mobjinfo[MT_PLAYER].raisestate;
- break;
- }
- }
- if (type == MT_GHOST)
- {
- mobj = P_SpawnGhostMobj(g->mo); // does a large portion of the work for us
- mobj->frame = (mobj->frame & ~FF_FRAMEMASK)|tr_trans60<mo->x, g->mo->y, g->mo->z - FixedDiv(FixedMul(g->mo->info->height, g->mo->scale) - g->mo->height,3*FRACUNIT), MT_THOK);
- mobj->sprite = states[mobjinfo[type].spawnstate].sprite;
- mobj->frame = (states[mobjinfo[type].spawnstate].frame & FF_FRAMEMASK) | tr_trans60<tics = -1; // nope.
- mobj->color = g->mo->color;
- if (g->mo->eflags & MFE_VERTICALFLIP)
- {
- mobj->flags2 |= MF2_OBJECTFLIP;
- mobj->eflags |= MFE_VERTICALFLIP;
- }
- P_SetScale(mobj, g->mo->scale);
- mobj->destscale = g->mo->scale;
- }
- mobj->floorz = mobj->z;
- mobj->ceilingz = mobj->z+mobj->height;
- P_UnsetThingPosition(mobj);
- mobj->flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY; // make an ATTEMPT to curb crazy SOCs fucking stuff up...
- P_SetThingPosition(mobj);
- mobj->fuse = 8;
- P_SetTarget(&mobj->target, g->mo);
- }
- if (ziptic & EZT_HIT)
- { // Spawn hit poofs for killing things!
- UINT16 i, count = READUINT16(g->p), health;
- //UINT32 type;
- fixed_t x,y,z;
- angle_t angle;
- mobj_t *poof;
- for (i = 0; i < count; i++)
- {
- g->p += 4; // reserved
- g->p += 4; // backwards compat., type used to be here
- health = READUINT16(g->p);
- x = READFIXED(g->p);
- y = READFIXED(g->p);
- z = READFIXED(g->p);
- angle = READANGLE(g->p);
- if (health != 0 || i >= 4) // only spawn for the first 4 hits per frame, to prevent ghosts from splode-spamming too bad.
- continue;
- poof = P_SpawnMobj(x, y, z, MT_GHOST);
- poof->angle = angle;
- poof->flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY; // make an ATTEMPT to curb crazy SOCs fucking stuff up...
- poof->health = 0;
- P_SetMobjStateNF(poof, S_XPLD1);
- }
- }
- if (ziptic & EZT_SPRITE)
- g->mo->sprite = READUINT8(g->p);
- if (ziptic & EZT_KART)
- g->p += 12; // kartitem, kartamount, kartbumpers
- }
-
-#ifdef DEMO_COMPAT_100
- if (g->version != 0x0001)
- {
-#endif
- if (READUINT8(g->p) != 0xFF) // Make sure there isn't other ghost data here.
- I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this
-#ifdef DEMO_COMPAT_100
- }
-#endif
-
-skippedghosttic:
- // Tick ghost colors (Super and Mario Invincibility flashing)
- switch(g->color)
- {
- case GHC_SUPER: // Super Sonic (P_DoSuperStuff)
- g->mo->color = SKINCOLOR_SUPER1;
- g->mo->color += abs( ( (signed)( (unsigned)leveltime >> 1 ) % 9) - 4);
- break;
- case GHC_INVINCIBLE: // Mario invincibility (P_CheckInvincibilityTimer)
- g->mo->color = (UINT8)(leveltime % MAXSKINCOLORS);
- break;
- default:
- break;
- }
-
- // Demo ends after ghost data.
- if (*g->p == DEMOMARKER)
- {
- g->mo->momx = g->mo->momy = g->mo->momz = 0;
- if (p)
- p->next = g->next;
- else
- ghosts = g->next;
- Z_Free(g);
- continue;
- }
- p = g;
- }
-}
-
-// Demo rewinding functions
-typedef struct rewindinfo_s {
- tic_t leveltime;
-
- struct {
- boolean ingame;
- player_t player;
- mobj_t mobj;
- } playerinfo[MAXPLAYERS];
-
- struct rewindinfo_s *prev;
-} rewindinfo_t;
-
-static tic_t currentrewindnum;
-static rewindinfo_t *rewindhead = NULL; // Reverse chronological order
-
-void G_InitDemoRewind(void)
-{
- CL_ClearRewinds();
-
- while (rewindhead)
- {
- rewindinfo_t *p = rewindhead->prev;
- Z_Free(rewindhead);
- rewindhead = p;
- }
-
- currentrewindnum = 0;
-}
-
-void G_StoreRewindInfo(void)
-{
- static UINT8 timetolog = 8;
- rewindinfo_t *info;
- size_t i;
-
- if (timetolog-- > 0)
- return;
- timetolog = 8;
-
- info = Z_Calloc(sizeof(rewindinfo_t), PU_STATIC, NULL);
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- if (!playeringame[i] || players[i].spectator)
- {
- info->playerinfo[i].ingame = false;
- continue;
- }
-
- info->playerinfo[i].ingame = true;
- memcpy(&info->playerinfo[i].player, &players[i], sizeof(player_t));
- if (players[i].mo)
- memcpy(&info->playerinfo[i].mobj, players[i].mo, sizeof(mobj_t));
- }
-
- info->leveltime = leveltime;
- info->prev = rewindhead;
- rewindhead = info;
-}
-
-void G_PreviewRewind(tic_t previewtime)
-{
- SINT8 i;
- size_t j;
- fixed_t tweenvalue = 0;
- rewindinfo_t *info = rewindhead, *next_info = rewindhead;
-
- if (!info)
- return;
-
- while (info->leveltime > previewtime && info->prev)
- {
- next_info = info;
- info = info->prev;
- }
- if (info != next_info)
- tweenvalue = FixedDiv(previewtime - info->leveltime, next_info->leveltime - info->leveltime);
-
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- if (!playeringame[i] || players[i].spectator)
- {
- if (info->playerinfo[i].player.mo)
- {
- //@TODO spawn temp object to act as a player display
- }
-
- continue;
- }
-
- if (!info->playerinfo[i].ingame || !info->playerinfo[i].player.mo)
- {
- if (players[i].mo)
- players[i].mo->flags2 |= MF2_DONTDRAW;
-
- continue;
- }
-
- if (!players[i].mo)
- continue; //@TODO spawn temp object to act as a player display
-
- players[i].mo->flags2 &= ~MF2_DONTDRAW;
-
- P_UnsetThingPosition(players[i].mo);
-#define TWEEN(pr) info->playerinfo[i].mobj.pr + FixedMul((INT32) (next_info->playerinfo[i].mobj.pr - info->playerinfo[i].mobj.pr), tweenvalue)
- players[i].mo->x = TWEEN(x);
- players[i].mo->y = TWEEN(y);
- players[i].mo->z = TWEEN(z);
- players[i].mo->angle = TWEEN(angle);
-#undef TWEEN
- P_SetThingPosition(players[i].mo);
-
- players[i].frameangle = info->playerinfo[i].player.frameangle + FixedMul((INT32) (next_info->playerinfo[i].player.frameangle - info->playerinfo[i].player.frameangle), tweenvalue);
-
- players[i].mo->sprite = info->playerinfo[i].mobj.sprite;
- players[i].mo->frame = info->playerinfo[i].mobj.frame;
-
- players[i].realtime = info->playerinfo[i].player.realtime;
- for (j = 0; j < NUMKARTSTUFF; j++)
- players[i].kartstuff[j] = info->playerinfo[i].player.kartstuff[j];
- }
-
- for (i = splitscreen; i >= 0; i--)
- P_ResetCamera(&players[displayplayers[i]], &camera[i]);
-}
-
-void G_ConfirmRewind(tic_t rewindtime)
-{
- SINT8 i;
- tic_t j;
- boolean oldmenuactive = menuactive, oldsounddisabled = sound_disabled;
-
- INT32 olddp1 = displayplayers[0], olddp2 = displayplayers[1], olddp3 = displayplayers[2], olddp4 = displayplayers[3];
- UINT8 oldss = splitscreen;
-
- menuactive = false; // Prevent loops
-
- CV_StealthSetValue(&cv_renderview, 0);
-
- if (rewindtime <= starttime)
- {
- demo.rewinding = false;
- G_DoPlayDemo(NULL); // Restart the current demo
- }
- else
- {
- rewind_t *rewind;
- sound_disabled = true; // Prevent sound spam
- demo.rewinding = true;
-
- rewind = CL_RewindToTime(rewindtime);
-
- if (rewind)
- {
- demobuf.p = demobuf.buffer + rewind->demopos;
- memcpy(oldcmd, rewind->oldcmd, sizeof (oldcmd));
- memcpy(oldghost, rewind->oldghost, sizeof (oldghost));
- paused = false;
- }
- else
- {
- demo.rewinding = true;
- G_DoPlayDemo(NULL); // Restart the current demo
- }
- }
-
- for (j = 0; j < rewindtime && leveltime < rewindtime; j++)
- {
- G_Ticker((j % NEWTICRATERATIO) == 0);
- }
-
- demo.rewinding = false;
- menuactive = oldmenuactive; // Bring the menu back up
- sound_disabled = oldsounddisabled; // Re-enable SFX
-
- wipegamestate = gamestate; // No fading back in!
-
- COM_BufInsertText("renderview on\n");
-
- splitscreen = oldss;
- displayplayers[0] = olddp1;
- displayplayers[1] = olddp2;
- displayplayers[2] = olddp3;
- displayplayers[3] = olddp4;
- R_ExecuteSetViewSize();
- G_ResetViews();
-
- for (i = splitscreen; i >= 0; i--)
- P_ResetCamera(&players[displayplayers[i]], &camera[i]);
-}
-
-void G_ReadMetalTic(mobj_t *metal)
-{
- UINT8 ziptic;
- UINT16 speed;
- UINT8 statetype;
-
- if (!metal_p)
- return;
- ziptic = READUINT8(metal_p);
-
- // Read changes from the tic
- if (ziptic & GZT_XYZ)
- {
- oldmetal.x = READFIXED(metal_p);
- oldmetal.y = READFIXED(metal_p);
- oldmetal.z = READFIXED(metal_p);
- P_MoveOrigin(metal, oldmetal.x, oldmetal.y, oldmetal.z);
- oldmetal.x = metal->x;
- oldmetal.y = metal->y;
- oldmetal.z = metal->z;
- }
- else
- {
- if (ziptic & GZT_MOMXY)
- {
- oldmetal.momx = READINT16(metal_p)<<8;
- oldmetal.momy = READINT16(metal_p)<<8;
- }
- if (ziptic & GZT_MOMZ)
- oldmetal.momz = READINT16(metal_p)<<8;
- oldmetal.x += oldmetal.momx;
- oldmetal.y += oldmetal.momy;
- oldmetal.z += oldmetal.momz;
- }
- if (ziptic & GZT_ANGLE)
- oldmetal.angle = READUINT8(metal_p)<<24;
- if (ziptic & GZT_SPRITE)
- metal_p++; // Currently unused. (Metal Sonic figures out what he's doing his own damn self.)
-
- // Set movement, position, and angle
- // oldmetal contains where you're supposed to be.
- metal->momx = oldmetal.momx;
- metal->momy = oldmetal.momy;
- metal->momz = oldmetal.momz;
- P_UnsetThingPosition(metal);
- metal->x = oldmetal.x;
- metal->y = oldmetal.y;
- metal->z = oldmetal.z;
- P_SetThingPosition(metal);
- metal->angle = oldmetal.angle;
-
- if (ziptic & GZT_EXTRA)
- { // But wait, there's more!
- ziptic = READUINT8(metal_p);
- if (ziptic & EZT_FLIP)
- metal->eflags ^= MFE_VERTICALFLIP;
- if (ziptic & EZT_SCALE)
- {
- metal->destscale = READFIXED(metal_p);
- if (metal->destscale != metal->scale)
- P_SetScale(metal, metal->destscale);
- }
- }
-
- // Calculates player's speed based on distance-of-a-line formula
- speed = FixedDiv(P_AproxDistance(oldmetal.momx, oldmetal.momy), metal->scale)>>FRACBITS;
-
- // Use speed to decide an appropriate state
- if (speed > 20) // default skin runspeed
- statetype = 2;
- else if (speed > 1) // stopspeed
- statetype = 1;
- else
- statetype = 0;
-
- // Set state
- if (statetype != metal->threshold)
- {
- switch (statetype)
- {
- case 2: // run
- P_SetMobjState(metal,metal->info->meleestate);
- break;
- case 1: // walk
- P_SetMobjState(metal,metal->info->seestate);
- break;
- default: // stand
- P_SetMobjState(metal,metal->info->spawnstate);
- break;
- }
- metal->threshold = statetype;
- }
-
- // TODO: Modify state durations based on movement speed, similar to players?
-
- if (*metal_p == DEMOMARKER)
- {
- // end of demo data stream
- G_StopMetalDemo();
- return;
- }
-}
-
-void G_WriteMetalTic(mobj_t *metal)
-{
- UINT8 ziptic = 0;
- UINT8 *ziptic_p;
-
- if (!demobuf.p) // demobuf.p will be NULL until the race start linedef executor is triggered!
- return;
-
- ziptic_p = demobuf.p++; // the ziptic, written at the end of this function
-
- #define MAXMOM (0xFFFF<<8)
-
- // GZT_XYZ is only useful if you've moved 256 FRACUNITS or more in a single tic.
- if (abs(metal->x-oldmetal.x) > MAXMOM
- || abs(metal->y-oldmetal.y) > MAXMOM
- || abs(metal->z-oldmetal.z) > MAXMOM)
- {
- oldmetal.x = metal->x;
- oldmetal.y = metal->y;
- oldmetal.z = metal->z;
- WRITEFIXED(demobuf.p,oldmetal.x);
- WRITEFIXED(demobuf.p,oldmetal.y);
- WRITEFIXED(demobuf.p,oldmetal.z);
- ziptic |= GZT_XYZ;
- }
- else
- {
- // For moving normally:
- // Store one full byte of movement, plus one byte of fractional movement.
- INT16 momx = (INT16)((metal->x-oldmetal.x)>>8);
- INT16 momy = (INT16)((metal->y-oldmetal.y)>>8);
- if (momx != oldmetal.momx
- || momy != oldmetal.momy)
- {
- oldmetal.momx = momx;
- oldmetal.momy = momy;
- WRITEINT16(demobuf.p,momx);
- WRITEINT16(demobuf.p,momy);
- ziptic |= GZT_MOMXY;
- }
- momx = (INT16)((metal->z-oldmetal.z)>>8);
- if (momx != oldmetal.momz)
- {
- oldmetal.momz = momx;
- WRITEINT16(demobuf.p,momx);
- ziptic |= GZT_MOMZ;
- }
-
- // This SHOULD set oldmetal.x/y/z to match metal->x/y/z
- // but it keeps the fractional loss of one byte,
- // so it will hopefully be made up for in future tics.
- oldmetal.x += oldmetal.momx<<8;
- oldmetal.y += oldmetal.momy<<8;
- oldmetal.z += oldmetal.momz<<8;
- }
-
- #undef MAXMOM
-
- // Only store the 8 most relevant bits of angle
- // because exact values aren't too easy to discern to begin with when only 8 angles have different sprites
- // and it does not affect movement at all anyway.
- if (metal->angle>>24 != oldmetal.angle)
- {
- oldmetal.angle = metal->angle>>24;
- WRITEUINT8(demobuf.p,oldmetal.angle);
- ziptic |= GZT_ANGLE;
- }
-
- // Metal Sonic does not need our state changes.
- // ... currently.
-
- {
- UINT8 *exttic_p = NULL;
- UINT8 exttic = 0;
- if ((metal->eflags & MFE_VERTICALFLIP) != (oldmetal.eflags & MFE_VERTICALFLIP))
- {
- if (!exttic_p)
- exttic_p = demobuf.p++;
- exttic |= EZT_FLIP;
- oldmetal.eflags ^= MFE_VERTICALFLIP;
- }
- if (metal->scale != oldmetal.scale)
- {
- if (!exttic_p)
- exttic_p = demobuf.p++;
- exttic |= EZT_SCALE;
- WRITEFIXED(demobuf.p,metal->scale);
- oldmetal.scale = metal->scale;
- }
- if (exttic_p)
- {
- *exttic_p = exttic;
- ziptic |= GZT_EXTRA;
- }
- }
-
- *ziptic_p = ziptic;
-
- // attention here for the ticcmd size!
- // latest demos with mouse aiming byte in ticcmd
- if (demobuf.p >= demoend - 32)
- {
- G_StopMetalRecording(); // no more space
- return;
- }
-}
-
-//
-// G_RecordDemo
-//
-void G_RecordDemo(const char *name)
-{
- INT32 maxsize;
-
- demobuf.p = NULL;
- G_ResetDemoRecording();
- demoend = NULL;
-
- if (cv_recordmultiplayerdemos.value)
- {
- CONS_Printf("Recording demo %s.lmp\n", name);
-
- strcpy(demoname, name);
- strcat(demoname, ".lmp");
-
- maxsize = cv_maxdemosize.value*1024*1024;
-
- demobuf.buffer = Z_Malloc(maxsize + 100*1024, PU_STATIC, NULL);
- demoend = demobuf.buffer + maxsize;
-
- if (demobuf.buffer)
- demo.recording = true;
- else
- CONS_Alert(CONS_ERROR, "Failed to allocate demo buffer\n");
- }
-}
-
-void G_RecordMetal(void)
-{
- INT32 maxsize;
- maxsize = cv_maxdemosize.value*1024*1024;
- if (demobuf.buffer)
- Z_Free(demobuf.buffer);
- demobuf.p = NULL;
- metalrecording = false;
- demobuf.buffer = Z_Malloc(maxsize + 100*1024, PU_STATIC, NULL);
- demoend = demobuf.buffer + maxsize;
-
- if (demobuf.buffer)
- metalrecording = true;
- else
- CONS_Alert(CONS_ERROR, "Failed to allocate demo buffer\n");
-}
-
-void G_BeginRecording(void)
-{
- UINT8 i, p;
- char name[17];
- player_t *player = &players[consoleplayer];
-
- char *filename;
- UINT8 totalfiles;
- UINT8 *m;
-
- if (!cv_recordmultiplayerdemos.value)
- {
- G_ResetDemoRecording();
- return;
- }
-
- if (demobuf.buffer == NULL)
- {
- CONS_Alert(CONS_ERROR, "No demo buffer allocated\n");
- G_ResetDemoRecording();
- return;
- }
-
- if (demobuf.p)
- {
- G_ResetDemoRecording();
- return;
- }
-
- memset(name,0,sizeof(name));
-
- demobuf.p = demobuf.buffer;
- demoflags = DF_GHOST|(multiplayer ? DF_MULTIPLAYER : (modeattacking<important)
- {
- nameonly(( filename = va("%s", wadfiles[i]->filename) ));
- WRITESTRINGL(demobuf.p, filename, MAX_WADPATH);
- WRITEMEM(demobuf.p, wadfiles[i]->md5sum, 16);
-
- totalfiles++;
- }
-
- WRITEUINT8(m, totalfiles);
-
- switch ((demoflags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
- {
- case ATTACKING_NONE: // 0
- break;
- case ATTACKING_RECORD: // 1
- demotime_p = demobuf.p;
- WRITEUINT32(demobuf.p,UINT32_MAX); // time
- WRITEUINT32(demobuf.p,UINT32_MAX); // lap
- break;
- default: // 3
- break;
- }
-
- WRITEUINT32(demobuf.p, P_GetInitSeed());
-
- // Reserved for extrainfo location from start of file
- demoinfo_p = demobuf.p;
- WRITEUINT32(demobuf.p, 0);
-
- // Save netvars
- CV_SaveNetVars(&demobuf.p, true);
-
- // Now store some info for each in-game player
- for (p = 0; p < MAXPLAYERS; p++) {
- if (playeringame[p]) {
- player = &players[p];
-
- WRITEUINT8(demobuf.p, p | (player->spectator ? DEMO_SPECTATOR : 0));
-
- // Name
- memset(name, 0, 16);
- memcpy(name, player_names[p], 15);
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
-
- // Skin
- memset(name, 0, 16);
- strncpy(name, skins[player->skin].name, 16);
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
-
- // Color
- memset(name, 0, 16);
- strncpy(name, KartColor_Names[player->skincolor], 16);
- M_Memcpy(demobuf.p,name,16);
- demobuf.p += 16;
-
- // Score, since Kart uses this to determine where you start on the map
- WRITEUINT32(demobuf.p, player->score);
-
- // Kart speed and weight
- WRITEUINT8(demobuf.p, skins[player->skin].kartspeed);
- WRITEUINT8(demobuf.p, skins[player->skin].kartweight);
-
- }
- }
-
- WRITEUINT8(demobuf.p, 0xFF); // Denote the end of the player listing
-
- // player lua vars, always saved even if empty... Unless it's record attack.
- if (demoflags & DF_LUAVARS)
- LUA_Archive(&demobuf, false);
-
- memset(&oldcmd,0,sizeof(oldcmd));
- memset(&oldghost,0,sizeof(oldghost));
- memset(&ghostext,0,sizeof(ghostext));
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- ghostext[i].lastcolor = ghostext[i].color = GHC_NORMAL;
- ghostext[i].lastscale = ghostext[i].scale = FRACUNIT;
-
- if (players[i].mo)
- {
- oldghost[i].x = players[i].mo->x;
- oldghost[i].y = players[i].mo->y;
- oldghost[i].z = players[i].mo->z;
- oldghost[i].angle = players[i].mo->angle;
-
- // preticker started us gravity flipped
- if (players[i].mo->eflags & MFE_VERTICALFLIP)
- ghostext[i].flags |= EZT_FLIP;
- }
- }
-}
-
-void G_BeginMetal(void)
-{
- mobj_t *mo = players[consoleplayer].mo;
-
- if (demobuf.buffer == NULL)
- {
- CONS_Alert(CONS_ERROR, "No metal demo buffer allocated\n");
- metalrecording = false;
- return;
- }
-
- if (demobuf.p)
- {
- Z_Free(demobuf.buffer);
- demobuf.buffer = NULL;
- metalrecording = false;
- return;
- }
-
- demobuf.p = demobuf.buffer;
-
- // Write header.
- M_Memcpy(demobuf.p, DEMOHEADER, 12); demobuf.p += 12;
- WRITEUINT8(demobuf.p,VERSION);
- WRITEUINT8(demobuf.p,SUBVERSION);
- WRITEUINT16(demobuf.p,DEMOVERSION);
-
- // demo checksum
- demobuf.p += 16;
-
- M_Memcpy(demobuf.p, "METL", 4); demobuf.p += 4;
-
- // Set up our memory.
- memset(&oldmetal,0,sizeof(oldmetal));
- oldmetal.x = mo->x;
- oldmetal.y = mo->y;
- oldmetal.z = mo->z;
- oldmetal.angle = mo->angle;
-}
-
-void G_WriteStanding(UINT8 ranking, char *name, INT32 skinnum, UINT8 color, UINT32 val)
-{
- char temp[17];
-
- if (!demobuf.p)
- return;
-
- if (demoinfo_p && *(UINT32 *)demoinfo_p == 0 && demobuf.buffer != NULL)
- {
- WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
- *(UINT32 *)demoinfo_p = demobuf.p - demobuf.buffer;
- }
-
- WRITEUINT8(demobuf.p, DW_STANDING);
- WRITEUINT8(demobuf.p, ranking);
-
- // Name
- memset(temp, 0, 16);
- strncpy(temp, name, 16);
- M_Memcpy(demobuf.p,temp,16);
- demobuf.p += 16;
-
- // Skin
- memset(temp, 0, 16);
- strncpy(temp, skins[skinnum].name, 16);
- M_Memcpy(demobuf.p,temp,16);
- demobuf.p += 16;
-
- // Color
- memset(temp, 0, 16);
- strncpy(temp, KartColor_Names[color], 16);
- M_Memcpy(demobuf.p,temp,16);
- demobuf.p += 16;
-
- // Score/time/whatever
- WRITEUINT32(demobuf.p, val);
-}
-
-void G_SetDemoTime(UINT32 ptime, UINT32 plap)
-{
- if (!demo.recording || !demotime_p)
- return;
- if (demoflags & DF_RECORDATTACK)
- {
- WRITEUINT32(demotime_p, ptime);
- WRITEUINT32(demotime_p, plap);
- demotime_p = NULL;
- }
-}
-
-static void G_LoadDemoExtraFiles(UINT8 **pp)
-{
- UINT8 totalfiles;
- char filename[MAX_WADPATH];
- UINT8 md5sum[16];
- filestatus_t ncs = FS_NOTFOUND;
- boolean toomany = false;
- boolean alreadyloaded;
- UINT8 i, j;
-
- totalfiles = READUINT8((*pp));
- for (i = 0; i < totalfiles; ++i)
- {
- if (toomany)
- SKIPSTRING((*pp));
- else
- {
- strlcpy(filename, (char *)(*pp), sizeof filename);
- SKIPSTRING((*pp));
- }
- READMEM((*pp), md5sum, 16);
-
- if (!toomany)
- {
- alreadyloaded = false;
-
- for (j = 0; j < numwadfiles; ++j)
- {
- if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0)
- {
- alreadyloaded = true;
- break;
- }
- }
-
- if (alreadyloaded)
- continue;
-
- if (numwadfiles >= MAX_WADFILES)
- toomany = true;
- else
- ncs = findfile(filename, md5sum, false);
-
- if (toomany)
- {
- CONS_Alert(CONS_WARNING, M_GetText("Too many files loaded to add anymore for demo playback\n"));
- if (!CON_Ready())
- M_StartMessage(M_GetText("There are too many files loaded to add this demo's addons.\n\nDemo playback may desync.\n\nPress ESC\n"), NULL, MM_NOTHING);
- }
- else if (ncs != FS_FOUND)
- {
- if (ncs == FS_NOTFOUND)
- CONS_Alert(CONS_NOTICE, M_GetText("You do not have a copy of %s\n"), filename);
- else if (ncs == FS_MD5SUMBAD)
- CONS_Alert(CONS_NOTICE, M_GetText("Checksum mismatch on %s\n"), filename);
- else
- CONS_Alert(CONS_NOTICE, M_GetText("Unknown error finding file %s\n"), filename);
-
- if (!CON_Ready())
- M_StartMessage(M_GetText("There were errors trying to add this demo's addons. Check the console for more information.\n\nDemo playback may desync.\n\nPress ESC\n"), NULL, MM_NOTHING);
- }
- else
- {
- P_PartialAddWadFile(filename, false);
- }
- }
- }
-
- if (P_PartialAddGetStage() >= 0)
- P_MultiSetupWadFiles(true); // in case any partial adds were done
-}
-
-static void G_SkipDemoExtraFiles(UINT8 **pp)
-{
- UINT8 totalfiles;
- UINT8 i;
-
- totalfiles = READUINT8((*pp));
- for (i = 0; i < totalfiles; ++i)
- {
- SKIPSTRING((*pp));// file name
- (*pp) += 16;// md5
- }
-}
-
-// G_CheckDemoExtraFiles: checks if our loaded WAD list matches the demo's.
-// Enabling quick prevents filesystem checks to see if needed files are available to load.
-static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick)
-{
- UINT8 totalfiles, filesloaded, nmusfilecount;
- char filename[MAX_WADPATH];
- UINT8 md5sum[16];
- boolean toomany = false;
- boolean alreadyloaded;
- UINT8 i, j;
- UINT8 error = 0;
-
- totalfiles = READUINT8((*pp));
- filesloaded = 0;
- for (i = 0; i < totalfiles; ++i)
- {
- if (toomany)
- SKIPSTRING((*pp));
- else
- {
- strlcpy(filename, (char *)(*pp), sizeof filename);
- SKIPSTRING((*pp));
- }
- READMEM((*pp), md5sum, 16);
-
- if (!toomany)
- {
- alreadyloaded = false;
- nmusfilecount = 0;
-
- for (j = 0; j < numwadfiles; ++j)
- {
- if (wadfiles[j]->important && j > mainwads)
- nmusfilecount++;
- else
- continue;
-
- if (memcmp(md5sum, wadfiles[j]->md5sum, 16) == 0)
- {
- alreadyloaded = true;
-
- if (i != nmusfilecount-1 && error < DFILE_ERROR_OUTOFORDER)
- error |= DFILE_ERROR_OUTOFORDER;
-
- break;
- }
- }
-
- if (alreadyloaded)
- {
- filesloaded++;
- continue;
- }
-
- if (numwadfiles >= MAX_WADFILES)
- error = DFILE_ERROR_CANNOTLOAD;
- else if (!quick && findfile(filename, md5sum, false) != FS_FOUND)
- error = DFILE_ERROR_CANNOTLOAD;
- else if (error < DFILE_ERROR_INCOMPLETEOUTOFORDER)
- error |= DFILE_ERROR_NOTLOADED;
- } else
- error = DFILE_ERROR_CANNOTLOAD;
- }
-
- // Get final file count
- nmusfilecount = 0;
-
- for (j = 0; j < numwadfiles; ++j)
- if (wadfiles[j]->important && j > mainwads)
- nmusfilecount++;
-
- if (!error && filesloaded < nmusfilecount)
- error = DFILE_ERROR_EXTRAFILES;
-
- return error;
-}
-
-// Returns bitfield:
-// 1 == new demo has lower time
-// 2 == new demo has higher score
-// 4 == new demo has higher rings
-UINT8 G_CmpDemoTime(char *oldname, char *newname)
-{
- UINT8 *buffer,*p;
- UINT8 flags;
- UINT32 oldtime, newtime, oldlap, newlap;
- UINT16 oldversion;
- size_t bufsize ATTRUNUSED;
- UINT8 c;
- UINT16 s ATTRUNUSED;
- UINT8 aflags = 0;
-
- // load the new file
- FIL_DefaultExtension(newname, ".lmp");
- bufsize = FIL_ReadFile(newname, &buffer);
- I_Assert(bufsize != 0);
- p = buffer;
-
- // read demo header
- I_Assert(!memcmp(p, DEMOHEADER, 12));
- p += 12; // DEMOHEADER
- c = READUINT8(p); // VERSION
- I_Assert(c == VERSION);
- c = READUINT8(p); // SUBVERSION
- I_Assert(c == SUBVERSION);
- s = READUINT16(p);
- I_Assert(s == DEMOVERSION);
- p += 64; // full demo title
- p += 16; // demo checksum
- I_Assert(!memcmp(p, "PLAY", 4));
- p += 4; // PLAY
- p += 2; // gamemap
- p += 16; // map md5
- flags = READUINT8(p); // demoflags
- p++; // gametype
- G_SkipDemoExtraFiles(&p);
-
- aflags = flags & (DF_RECORDATTACK|DF_NIGHTSATTACK);
- I_Assert(aflags);
- if (flags & DF_RECORDATTACK)
- {
- newtime = READUINT32(p);
- newlap = READUINT32(p);
- }
- else // appease compiler
- return 0;
-
- Z_Free(buffer);
-
- // load old file
- FIL_DefaultExtension(oldname, ".lmp");
- if (!FIL_ReadFile(oldname, &buffer))
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), oldname);
- return UINT8_MAX;
- }
- p = buffer;
-
- // read demo header
- if (memcmp(p, DEMOHEADER, 12))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
- Z_Free(buffer);
- return UINT8_MAX;
- } p += 12; // DEMOHEADER
- p++; // VERSION
- p++; // SUBVERSION
- oldversion = READUINT16(p);
- switch(oldversion) // demoversion
- {
- case DEMOVERSION: // latest always supported
- p += 64; // full demo title
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- // Old replays gotta go :]
- CONS_Alert(CONS_NOTICE, M_GetText("File '%s' outdated version. It will be overwritten. Nyeheheh.\n"), oldname);
- Z_Free(buffer);
- return UINT8_MAX;
-#endif
- // too old, cannot support.
- default:
- CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
- Z_Free(buffer);
- return UINT8_MAX;
- }
- p += 16; // demo checksum
- if (memcmp(p, "PLAY", 4))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname);
- Z_Free(buffer);
- return UINT8_MAX;
- } p += 4; // "PLAY"
- p += 2; // gamemap
- p += 16; // mapmd5
- flags = READUINT8(p);
- p++; // gametype
- G_SkipDemoExtraFiles(&p);
- if (!(flags & aflags))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("File '%s' not from same game mode. It will be overwritten.\n"), oldname);
- Z_Free(buffer);
- return UINT8_MAX;
- }
- if (flags & DF_RECORDATTACK)
- {
- oldtime = READUINT32(p);
- oldlap = READUINT32(p);
- }
- else // appease compiler
- return UINT8_MAX;
-
- Z_Free(buffer);
-
- c = 0;
- if (newtime < oldtime
- || (newtime == oldtime && (newlap < oldlap)))
- c |= 1; // Better time
- if (newlap < oldlap
- || (newlap == oldlap && newtime < oldtime))
- c |= 1<<1; // Better lap time
- return c;
-}
-
-void G_LoadDemoInfo(menudemo_t *pdemo)
-{
- UINT8 *infobuffer, *info_p, *extrainfo_p;
- UINT8 version, subversion, pdemoflags;
- UINT16 pdemoversion, count;
-
- if (!FIL_ReadFile(pdemo->filepath, &infobuffer))
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath);
- pdemo->type = MD_INVALID;
- sprintf(pdemo->title, "INVALID REPLAY");
-
- return;
- }
-
- info_p = infobuffer;
-
- if (memcmp(info_p, DEMOHEADER, 12))
- {
- CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath);
- pdemo->type = MD_INVALID;
- sprintf(pdemo->title, "INVALID REPLAY");
- Z_Free(infobuffer);
- return;
- }
-
- pdemo->type = MD_LOADED;
-
- info_p += 12; // DEMOHEADER
-
- version = READUINT8(info_p);
- subversion = READUINT8(info_p);
- pdemoversion = READUINT16(info_p);
-
- memset(pdemo->version, 0, sizeof(pdemo->version));
- snprintf(pdemo->version, sizeof(pdemo->version), "v%d.%d", version, subversion);
-
- switch(pdemoversion)
- {
- case DEMOVERSION: // latest always supported
- // demo title
- M_Memcpy(pdemo->title, info_p, 64);
- info_p += 64;
-
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- pdemo->type = MD_OUTDATED;
- sprintf(pdemo->title, "Legacy Replay");
- break;
-#endif
- // too old, cannot support.
- default:
- CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath);
- pdemo->type = MD_INVALID;
- sprintf(pdemo->title, "INVALID REPLAY");
- Z_Free(infobuffer);
- return;
- }
-
- if (version != VERSION || subversion != SUBVERSION)
- pdemo->type = MD_OUTDATED;
-
- info_p += 16; // demo checksum
- if (memcmp(info_p, "PLAY", 4))
- {
- CONS_Alert(CONS_ERROR, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemo->filepath);
- pdemo->type = MD_INVALID;
- sprintf(pdemo->title, "INVALID REPLAY");
- Z_Free(infobuffer);
- return;
- }
- info_p += 4; // "PLAY"
- pdemo->map = READINT16(info_p);
- info_p += 16; // mapmd5
-
- pdemoflags = READUINT8(info_p);
-
- // temp?
- if (!(pdemoflags & DF_MULTIPLAYER))
- {
- CONS_Alert(CONS_ERROR, M_GetText("%s is not a multiplayer replay and can't be listed on this menu fully yet.\n"), pdemo->filepath);
- Z_Free(infobuffer);
- return;
- }
-#ifdef DEMO_COMPAT_100
- else if (pdemoversion == 0x0001)
- {
- CONS_Alert(CONS_ERROR, M_GetText("%s is a legacy multiplayer replay and cannot be played.\n"), pdemo->filepath);
- pdemo->type = MD_INVALID;
- sprintf(pdemo->title, "INVALID REPLAY");
- Z_Free(infobuffer);
- return;
- }
-#endif
-
- pdemo->gametype = READUINT8(info_p);
-
- pdemo->addonstatus = G_CheckDemoExtraFiles(&info_p, true);
- info_p += 4; // RNG seed
-
- extrainfo_p = infobuffer + READUINT32(info_p);
-
- // Pared down version of CV_LoadNetVars to find the kart speed
- pdemo->kartspeed = 1; // Default to normal speed
- count = READUINT16(info_p);
- while (count--)
- {
- UINT16 netid;
- char *svalue;
-
- netid = READUINT16(info_p);
- svalue = (char *)info_p;
- SKIPSTRING(info_p);
- info_p++; // stealth
-
- if (netid == cv_kartspeed.netid)
- {
- UINT8 j;
- for (j = 0; kartspeed_cons_t[j].strvalue; j++)
- if (!stricmp(kartspeed_cons_t[j].strvalue, svalue))
- pdemo->kartspeed = kartspeed_cons_t[j].value;
- }
- else if (netid == cv_basenumlaps.netid && pdemo->gametype == GT_RACE)
- pdemo->numlaps = atoi(svalue);
- }
-
- if (pdemoflags & DF_ENCORE)
- pdemo->kartspeed |= DF_ENCORE;
-
- // Read standings!
- count = 0;
-
- while (READUINT8(extrainfo_p) == DW_STANDING) // Assume standings are always first in the extrainfo
- {
- INT32 i;
- char temp[16];
-
- pdemo->standings[count].ranking = READUINT8(extrainfo_p);
-
- // Name
- M_Memcpy(pdemo->standings[count].name, extrainfo_p, 16);
- extrainfo_p += 16;
-
- // Skin
- M_Memcpy(temp,extrainfo_p,16);
- extrainfo_p += 16;
- pdemo->standings[count].skin = UINT8_MAX;
- for (i = 0; i < numskins; i++)
- if (stricmp(skins[i].name, temp) == 0)
- {
- pdemo->standings[count].skin = i;
- break;
- }
-
- // Color
- M_Memcpy(temp,extrainfo_p,16);
- extrainfo_p += 16;
- for (i = 0; i < MAXSKINCOLORS; i++)
- if (!stricmp(KartColor_Names[i],temp)) // SRB2kart
- {
- pdemo->standings[count].color = i;
- break;
- }
-
- // Score/time/whatever
- pdemo->standings[count].timeorscore = READUINT32(extrainfo_p);
-
- count++;
-
- if (count >= MAXPLAYERS)
- break; //@TODO still cycle through the rest of these if extra demo data is ever used
- }
-
- // I think that's everything we need?
- Z_Free(infobuffer);
-}
-
-#if defined (_WIN32)
-// return the file creation time
-// useful for demos that were renamed
-static long G_GetCreationTime(char *filepath)
-{
- struct stat fileinfo;
-
- if (stat(filepath, &fileinfo) == 0)
- return fileinfo.st_ctime;
-
- return 0;
-}
-#endif
-
-static char *G_GetDemoDate(menudemo_t *pdemo)
-{
- char *datetime;
- datetime = malloc(sizeof(pdemo->date)); // mallocma balls
-
- // no mallocma balls... :c
- if (!datetime)
- {
- return NULL;
- }
-
- time_t file_time = 0;
-
- // get le filepath
- char *filename;
- filename = strdup(pdemo->filepath);
-
-#if defined (_WIN32)
- if (!filename)
- {
- // if we cant get a filename try just getting the file create time
- file_time = G_GetCreationTime(pdemo->filepath);
- goto skipfilenametime;
- }
-#else
- if (!filename)
- {
- free(datetime);
- return NULL;
- }
-#endif
-
- // get the actual filename Zzz...
- nameonly(filename);
-
- // convert it to long Zzz....
- file_time = strtol(filename, NULL, 10);
- free(filename); // dont need this anymore a
-
-#if defined (_WIN32)
-skipfilenametime:
-#endif
-
- // then throw it into localtime to get an actual human readable format lmao
- struct tm *tm_buf = NULL;
- tm_buf = localtime(&file_time);
-
- // cant believe we ended up in 1970
- if (tm_buf == NULL || tm_buf->tm_year <= 110)
- {
-#if defined (_WIN32)
- // uh ohh, we got an invalid time
- // try one more time getting the creation time
- file_time = G_GetCreationTime(pdemo->filepath);
- tm_buf = localtime(&file_time);
-
- if (tm_buf == NULL || tm_buf->tm_year <= 110)
- {
- free(datetime);
- return NULL;
- }
-
- goto gotcreationtime;
-#else
- free(datetime);
- return NULL;
-#endif
- }
-
-#if defined (_WIN32)
-gotcreationtime:
-#endif
-
- const char *format;
-
- // US ppl are special (:
- if (cv_demodateformat.value == 2)
- format = "%m.%d.%Y";
- else if (cv_demodateformat.value == 1)
- format = "%d.%m.%Y";
- else
- format = strstr(setlocale(LC_TIME, NULL), "en_US") ? "%m.%d.%Y" : "%d.%m.%Y";
-
- strftime(datetime, sizeof(pdemo->date), format, tm_buf);
-
- return datetime;
-}
-
-void G_LoadDemoTitle(menudemo_t *pdemo)
-{
- UINT8 infobuffer[96], *info_p;
- UINT16 pdemoversion;
- size_t count;
-
- FILE *handle = fopen(pdemo->filepath, "rb");
-
- if (!handle)
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath);
- sprintf(pdemo->title, "INVALID REPLAY");
- return;
- }
-
- count = fread(infobuffer, 1, 96, handle);
- fclose(handle);
- info_p = infobuffer;
-
- // First check isn't too accurate technically, but well, valid replays should be larger than that anyway
- if (count < 96 || memcmp(info_p, DEMOHEADER, 12))
- {
- CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath);
- sprintf(pdemo->title, "INVALID REPLAY");
- return;
- }
-
- info_p += 12; // DEMOHEADER
-
- READUINT8(info_p);
- READUINT8(info_p);
- pdemoversion = READUINT16(info_p);
-
- memset(pdemo->date, 0, sizeof(pdemo->date));
-
- switch(pdemoversion)
- {
- case DEMOVERSION: // latest always supported
- // demo title
- M_Memcpy(pdemo->title, info_p, 64);
-
- // demo date
- char *demodate;
- demodate = G_GetDemoDate(pdemo);
- if (demodate)
- strncpy(pdemo->date, demodate, sizeof(pdemo->date));
- free(demodate);
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- sprintf(pdemo->title, "Legacy Replay");
- break;
-#endif
- // too old, cannot support.
- default:
- CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath);
- sprintf(pdemo->title, "INVALID REPLAY");
- }
-}
-
-//
-// G_PlayDemo
-//
-void G_DeferedPlayDemo(const char *name)
-{
- COM_BufAddText("playdemo \"");
- COM_BufAddText(name);
- COM_BufAddText("\" -addfiles\n");
-}
-
-//
-// Start a demo from a .LMP file or from a wad resource
-//
-#define SKIPERRORS
-void G_DoPlayDemo(char *defdemoname)
-{
- UINT8 i, p;
- lumpnum_t l;
- char skin[17],color[17],*n,*pdemoname;
- UINT8 version,subversion;
- UINT32 randseed;
- char msg[1024];
-#if defined(SKIPERRORS) && !defined(DEVELOP)
- boolean skiperrors = false;
-#endif
- boolean spectator;
- UINT8 slots[MAXPLAYERS], kartspeed[MAXPLAYERS], kartweight[MAXPLAYERS], numslots = 0;
-
- G_InitDemoRewind();
-
- skin[16] = '\0';
- color[16] = '\0';
-
- // No demo name means we're restarting the current demo
- if (defdemoname == NULL)
- {
- demobuf.p = demobuf.buffer;
- pdemoname = ZZ_Alloc(1); // Easier than adding checks for this everywhere it's freed
- }
- else
- {
- n = defdemoname+strlen(defdemoname);
- while (*n != '/' && *n != '\\' && n != defdemoname)
- n--;
- if (n != defdemoname)
- n++;
- pdemoname = ZZ_Alloc(strlen(n)+1);
- strcpy(pdemoname,n);
-
- M_SetPlaybackMenuPointer();
-
- // Internal if no extension, external if one exists
- if (FIL_CheckExtension(defdemoname))
- {
- //FIL_DefaultExtension(defdemoname, ".lmp");
- if (!FIL_ReadFile(defdemoname, &demobuf.buffer))
- {
- snprintf(msg, 1024, M_GetText("Failed to read file '%s'.\n"), defdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- gameaction = ga_nothing;
- M_StartMessage(msg, NULL, MM_NOTHING);
- return;
- }
- demobuf.p = demobuf.buffer;
- }
- // load demo resource from WAD
- else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR)
- {
- snprintf(msg, 1024, M_GetText("Failed to read lump '%s'.\n"), defdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- gameaction = ga_nothing;
- M_StartMessage(msg, NULL, MM_NOTHING);
- return;
- }
- else // it's an internal demo
- {
- demobuf.buffer = demobuf.p = W_CacheLumpNum(l, PU_STATIC);
-#if defined(SKIPERRORS) && !defined(DEVELOP)
- skiperrors = true; // SRB2Kart: Don't print warnings for staff ghosts, since they'll inevitably happen when we make bugfixes/changes...
-#endif
- }
- }
-
- // read demo header
- gameaction = ga_nothing;
- demo.playback = true;
- if (memcmp(demobuf.p, DEMOHEADER, 12))
- {
- snprintf(msg, 1024, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- demobuf.p += 12; // DEMOHEADER
-
- version = READUINT8(demobuf.p);
- subversion = READUINT8(demobuf.p);
- demo.version = READUINT16(demobuf.p);
- switch(demo.version)
- {
- case DEMOVERSION: // latest always supported
- // demo title
- M_Memcpy(demo.titlename, demobuf.p, 64);
- demobuf.p += 64;
-
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- break;
-#endif
- // too old, cannot support.
- default:
- snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- demobuf.p += 16; // demo checksum
- if (memcmp(demobuf.p, "PLAY", 4))
- {
- snprintf(msg, 1024, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- demobuf.p += 4; // "PLAY"
- gamemap = READINT16(demobuf.p);
- demobuf.p += 16; // mapmd5
-
- demoflags = READUINT8(demobuf.p);
-#ifdef DEMO_COMPAT_100
- if (demo.version == 0x0001)
- {
- if (demoflags & DF_MULTIPLAYER)
- {
- snprintf(msg, 1024, M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- }
- else
- {
-#endif
- gametype = READUINT8(demobuf.p);
-
- if (demo.title) // Titledemos should always play and ought to always be compatible with whatever wadlist is running.
- G_SkipDemoExtraFiles(&demobuf.p);
- else if (demo.loadfiles)
- G_LoadDemoExtraFiles(&demobuf.p);
- else if (demo.ignorefiles)
- G_SkipDemoExtraFiles(&demobuf.p);
- else
- {
- UINT8 error = G_CheckDemoExtraFiles(&demobuf.p, false);
-
- if (error)
- {
- switch (error)
- {
- case DFILE_ERROR_NOTLOADED:
- snprintf(msg, 1024,
- M_GetText("Required files for this demo are not loaded.\n\nUse\n\"playdemo %s -addfiles\"\nto load them and play the demo.\n"),
- pdemoname);
- break;
-
- case DFILE_ERROR_OUTOFORDER:
- snprintf(msg, 1024,
- M_GetText("Required files for this demo are loaded out of order.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
- pdemoname);
- break;
-
- case DFILE_ERROR_INCOMPLETEOUTOFORDER:
- snprintf(msg, 1024,
- M_GetText("Required files for this demo are not loaded, and some are out of order.\n\nUse\n\"playdemo %s -addfiles\"\nto load needed files and play the demo.\n"),
- pdemoname);
- break;
-
- case DFILE_ERROR_CANNOTLOAD:
- snprintf(msg, 1024,
- M_GetText("Required files for this demo cannot be loaded.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
- pdemoname);
- break;
-
- case DFILE_ERROR_EXTRAFILES:
- snprintf(msg, 1024,
- M_GetText("You have additional files loaded beyond the demo's file list.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"),
- pdemoname);
- break;
- }
-
- CONS_Alert(CONS_ERROR, "%s", msg);
- if (!CON_Ready()) // In the console they'll just see the notice there! No point pulling them out.
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- }
-#ifdef DEMO_COMPAT_100
- }
-#endif
-
- modeattacking = (demoflags & DF_ATTACKMASK)>>DF_ATTACKSHIFT;
- multiplayer = !!(demoflags & DF_MULTIPLAYER);
- CON_ToggleOff();
-
- hu_demotime = UINT32_MAX;
- hu_demolap = UINT32_MAX;
-
- switch (modeattacking)
- {
- case ATTACKING_NONE: // 0
- break;
- case ATTACKING_RECORD: // 1
- hu_demotime = READUINT32(demobuf.p);
- hu_demolap = READUINT32(demobuf.p);
- break;
- default: // 3
- modeattacking = ATTACKING_NONE;
- break;
- }
-
- // Random seed
- randseed = READUINT32(demobuf.p);
-#ifdef DEMO_COMPAT_100
- if (demo.version != 0x0001)
-#endif
- demobuf.p += 4; // Extrainfo location
-
-#ifdef DEMO_COMPAT_100
- if (demo.version == 0x0001)
- {
- // Player name
- M_Memcpy(player_names[0],demobuf.p,16);
- demobuf.p += 16;
-
- // Skin
- M_Memcpy(skin,demobuf.p,16);
- demobuf.p += 16;
-
- // Color
- M_Memcpy(color,demobuf.p,16);
- demobuf.p += 16;
-
- demobuf.p += 5; // Backwards compat - some stats
- // SRB2kart
- kartspeed[0] = READUINT8(demobuf.p);
- kartweight[0] = READUINT8(demobuf.p);
- //
- demobuf.p += 9; // Backwards compat - more stats
-
- // Skin not loaded?
- if (!SetPlayerSkin(0, skin))
- {
- snprintf(msg, 1024, M_GetText("%s features a character that is not currently loaded.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
-
- // ...*map* not loaded?
- if (!gamemap || (gamemap > NUMMAPS) || !mapheaderinfo[gamemap-1] || !(mapheaderinfo[gamemap-1]->menuflags & LF2_EXISTSHACK))
- {
- snprintf(msg, 1024, M_GetText("%s features a course that is not currently loaded.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
-
- // Set color
- for (i = 0; i < MAXSKINCOLORS; i++)
- if (!stricmp(KartColor_Names[i],color)) // SRB2kart
- {
- players[0].skincolor = i;
- break;
- }
-
- // net var data
- CV_LoadNetVars(&demobuf.p);
-
- // Sigh ... it's an empty demo.
- if (*demobuf.p == DEMOMARKER)
- {
- snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
-
- Z_Free(pdemoname);
-
- memset(&oldcmd,0,sizeof(oldcmd));
- memset(&oldghost,0,sizeof(oldghost));
- memset(&ghostext,0,sizeof(ghostext));
-
- CONS_Alert(CONS_WARNING, M_GetText("Demo version does not match game version. Desyncs may occur.\n"));
-
- // console warning messages
-#if defined(SKIPERRORS) && !defined(DEVELOP)
- demosynced = (!skiperrors);
-#else
- demosynced = true;
-#endif
-
- // didn't start recording right away.
- demo.deferstart = false;
-
- consoleplayer = 0;
- memset(displayplayers, 0, sizeof(displayplayers));
- memset(playeringame, 0, sizeof(playeringame));
- playeringame[0] = true;
-
- goto post_compat;
- }
-#endif
-
- // net var data
- CV_LoadNetVars(&demobuf.p);
-
- // Sigh ... it's an empty demo.
- if (*demobuf.p == DEMOMARKER)
- {
- snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
-
- Z_Free(pdemoname);
-
- memset(&oldcmd,0,sizeof(oldcmd));
- memset(&oldghost,0,sizeof(oldghost));
- memset(&ghostext,0,sizeof(ghostext));
-
-#if defined(SKIPERRORS) && !defined(DEVELOP)
- if ((VERSION != version || SUBVERSION != subversion) && !skiperrors)
-#else
- if (VERSION != version || SUBVERSION != subversion)
-#endif
- CONS_Alert(CONS_WARNING, M_GetText("Demo version does not match game version. Desyncs may occur.\n"));
-
- // console warning messages
-#if defined(SKIPERRORS) && !defined(DEVELOP)
- demosynced = (!skiperrors);
-#else
- demosynced = true;
-#endif
-
- // didn't start recording right away.
- demo.deferstart = false;
-
- //LUA_HookInt(gamemap, HOOK(MapChange));
-
- consoleplayer = 0;
- memset(playeringame,0,sizeof(playeringame));
- memset(displayplayers,0,sizeof(displayplayers));
- memset(camera,0,sizeof(camera)); // reset freecam
-
- // Load players that were in-game when the map started
- p = READUINT8(demobuf.p);
-
- while (p != 0xFF)
- {
- spectator = false;
- if (p & DEMO_SPECTATOR)
- {
- spectator = true;
- p &= ~DEMO_SPECTATOR;
-
- if (modeattacking)
- {
- snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
- }
- slots[numslots] = p; numslots++;
-
- if (modeattacking && numslots > 1)
- {
- snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname);
- CONS_Alert(CONS_ERROR, "%s", msg);
- M_StartMessage(msg, NULL, MM_NOTHING);
- G_ResetDemoPlayback(pdemoname);
- return;
- }
-
- if (!playeringame[displayplayers[0]] || players[displayplayers[0]].spectator)
- displayplayers[0] = consoleplayer = serverplayer = p;
-
- playeringame[p] = true;
- players[p].spectator = spectator;
-
- // Name
- M_Memcpy(player_names[p],demobuf.p,16);
- demobuf.p += 16;
-
- // Skin
- M_Memcpy(skin,demobuf.p,16);
- demobuf.p += 16;
- SetPlayerSkin(p, skin);
-
- // Color
- M_Memcpy(color,demobuf.p,16);
- demobuf.p += 16;
- for (i = 0; i < MAXSKINCOLORS; i++)
- if (!stricmp(KartColor_Names[i],color)) // SRB2kart
- {
- players[p].skincolor = i;
- break;
- }
-
- // Score, since Kart uses this to determine where you start on the map
- players[p].score = READUINT32(demobuf.p);
-
- // Kart stats, temporarily
- kartspeed[p] = READUINT8(demobuf.p);
- kartweight[p] = READUINT8(demobuf.p);
-
- if (stricmp(skins[players[p].skin].name, skin) != 0)
- FindClosestSkinForStats(p, kartspeed[p], kartweight[p]);
-
- // Look for the next player
- p = READUINT8(demobuf.p);
- }
-
- // end of player read (the 0xFF marker)
- // so this is where we are to read our lua variables (if possible!)
- if (demoflags & DF_LUAVARS) // again, used for compability, lua shit will be saved to replays regardless of if it's even been loaded
- {
- if (!gL) // No Lua state! ...I guess we'll just start one...
- LUA_ClearState();
-
- // No modeattacking check, DF_LUAVARS won't be present here.
- LUA_UnArchive(&demobuf, false);
- }
-
- splitscreen = 0;
-
- if (demo.title)
- {
- splitscreen = M_RandomKey(6)-1;
- splitscreen = min(min(3, numslots-1), splitscreen); // Bias toward 1p and 4p views
-
- for (p = 0; p <= splitscreen; p++)
- G_ResetView(p+1, slots[M_RandomKey(numslots)], false);
- }
-
- R_ExecuteSetViewSize();
-
-#ifdef DEMO_COMPAT_100
-post_compat:
-#endif
-
- P_SetRandSeed(randseed);
- G_InitNew(demoflags & DF_ENCORE, G_BuildMapName(gamemap), true, true); // Doesn't matter whether you reset or not here, given changes to resetplayer.
-
- for (i = 0; i < MAXPLAYERS; i++)
- {
- if (players[i].mo)
- {
- players[i].mo->color = players[i].skincolor;
- oldghost[i].x = players[i].mo->x;
- oldghost[i].y = players[i].mo->y;
- oldghost[i].z = players[i].mo->z;
- }
-
- // Set saved attribute values
- // No cheat checking here, because even if they ARE wrong...
- // it would only break the replay if we clipped them.
- players[i].kartspeed = kartspeed[i];
- players[i].kartweight = kartweight[i];
- }
-
- if (cv_director.value)
- CV_SetValue(&cv_director, 0);
-
- demo.deferstart = true;
-}
-#undef SKIPERRORS
-
-void G_AddGhost(char *defdemoname)
-{
- INT32 i;
- lumpnum_t l;
- char name[17],skin[17],color[17],*n,*pdemoname,md5[16];
- demoghost *gh;
- UINT8 flags;
- UINT8 *buffer,*p;
- mapthing_t *mthing;
- UINT16 count, ghostversion;
- skin_t *ghskin = &skins[0];
- UINT8 kartspeed = UINT8_MAX, kartweight = UINT8_MAX;
-
- name[16] = '\0';
- skin[16] = '\0';
- color[16] = '\0';
-
- n = defdemoname+strlen(defdemoname);
- while (*n != '/' && *n != '\\' && n != defdemoname)
- n--;
- if (n != defdemoname)
- n++;
- pdemoname = ZZ_Alloc(strlen(n)+1);
- strcpy(pdemoname,n);
-
- // Internal if no extension, external if one exists
- if (FIL_CheckExtension(defdemoname))
- {
- //FIL_DefaultExtension(defdemoname, ".lmp");
- if (!FIL_ReadFileTag(defdemoname, &buffer, PU_LEVEL))
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), defdemoname);
- Z_Free(pdemoname);
- return;
- }
- p = buffer;
- }
- // load demo resource from WAD
- else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR)
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to read lump '%s'.\n"), defdemoname);
- Z_Free(pdemoname);
- return;
- }
- else // it's an internal demo
- buffer = p = W_CacheLumpNum(l, PU_LEVEL);
-
- // read demo header
- if (memcmp(p, DEMOHEADER, 12))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Not a SRB2Kart replay.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
- p += 12; // DEMOHEADER
- p++; // VERSION
- p++; // SUBVERSION
-
- ghostversion = READUINT16(p);
- switch(ghostversion)
- {
- case DEMOVERSION: // latest always supported
- p += 64; // title
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- break;
-#endif
- // too old, cannot support.
- default:
- CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo version incompatible.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
- M_Memcpy(md5, p, 16); p += 16; // demo checksum
- for (gh = ghosts; gh; gh = gh->next)
- if (!memcmp(md5, gh->checksum, 16)) // another ghost in the game already has this checksum?
- { // Don't add another one, then!
- CONS_Debug(DBG_SETUP, "Rejecting duplicate ghost %s (MD5 was matched)\n", pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
- if (memcmp(p, "PLAY", 4))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo format unacceptable.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
- p += 4; // "PLAY"
- p += 2; // gamemap
- p += 16; // mapmd5 (possibly check for consistency?)
-
- flags = READUINT8(p);
-
- if (!(flags & DF_GHOST))
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: No ghost data in this demo.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion != 0x0001)
-#endif
- p++; // gametype
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion != 0x0001)
-#endif
- G_SkipDemoExtraFiles(&p); // Don't wanna modify the file list for ghosts.
- switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
- {
- case ATTACKING_NONE: // 0
- break;
- case ATTACKING_RECORD: // 1
- p += 8; // demo time, lap
- break;
- default: // 3
- break;
- }
-
- p += 4; // random seed
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion == 0x0001)
- {
- // Player name (TODO: Display this somehow if it doesn't match cv_playername!)
- M_Memcpy(name, p,16);
- p += 16;
-
- // Skin
- M_Memcpy(skin, p,16);
- p += 16;
-
- // Color
- M_Memcpy(color, p,16);
- p += 16;
-
- // Ghosts do not have a player structure to put this in.
- p++; // charability
- p++; // charability2
- p++; // actionspd
- p++; // mindash
- p++; // maxdash
- // SRB2kart
- p++; // kartspeed
- p++; // kartweight
- //
- p++; // normalspeed
- p++; // runspeed
- p++; // thrustfactor
- p++; // accelstart
- p++; // acceleration
- p += 4; // jumpfactor
- }
- else
-#endif
- p += 4; // Extra data location reference
-
- // net var data
- count = READUINT16(p);
- while (count--)
- {
- p += 2;
- SKIPSTRING(p);
- p++;
- }
-
- if (*p == DEMOMARKER)
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Replay is empty.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion != 0x0001)
- {
-#endif
- if (READUINT8(p) != 0)
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-
- // Player name (TODO: Display this somehow if it doesn't match cv_playername!)
- M_Memcpy(name, p, 16);
- p += 16;
-
- // Skin
- M_Memcpy(skin, p, 16);
- p += 16;
-
- // Color
- M_Memcpy(color, p, 16);
- p += 16;
-
- p += 4; // score
-
- kartspeed = READUINT8(p);
- kartweight = READUINT8(p);
-
- if (READUINT8(p) != 0xFF)
- {
- CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname);
- Z_Free(pdemoname);
- Z_Free(buffer);
- return;
- }
-#ifdef DEMO_COMPAT_100
- }
-#endif
-
- for (i = 0; i < numskins; i++)
- if (!stricmp(skins[i].name,skin))
- {
- ghskin = &skins[i];
- break;
- }
-
- if (i == numskins)
- {
- if (kartspeed != UINT8_MAX && kartweight != UINT8_MAX)
- ghskin = &skins[GetSkinNumClosestToStats(kartspeed, kartweight)];
-
- CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Invalid character. Falling back to %s.\n"), pdemoname, ghskin->name);
- }
-
- gh = Z_Calloc(sizeof(demoghost), PU_LEVEL, NULL);
- gh->next = ghosts;
- gh->buffer = buffer;
- M_Memcpy(gh->checksum, md5, 16);
- gh->p = p;
-
- ghosts = gh;
-
- gh->version = ghostversion;
- mthing = playerstarts[0];
- I_Assert(mthing);
- { // A bit more complex than P_SpawnPlayer because ghosts aren't solid and won't just push themselves out of the ceiling.
- fixed_t z,f,c;
- gh->mo = P_SpawnMobj(mthing->x << FRACBITS, mthing->y << FRACBITS, 0, MT_GHOST);
- gh->mo->angle = FixedAngle(mthing->angle*FRACUNIT);
- f = gh->mo->floorz;
- c = gh->mo->ceilingz - mobjinfo[MT_PLAYER].height;
- if (!!(mthing->options & MTF_AMBUSH) ^ !!(mthing->options & MTF_OBJECTFLIP))
- {
- z = c;
- if (mthing->options >> ZSHIFT)
- z -= ((mthing->options >> ZSHIFT) << FRACBITS);
- if (z < f)
- z = f;
- }
- else
- {
- z = f;
- if (mthing->options >> ZSHIFT)
- z += ((mthing->options >> ZSHIFT) << FRACBITS);
- if (z > c)
- z = c;
- }
- gh->mo->z = z;
- }
- gh->mo->state = states+S_KART_STND1; // SRB2kart - was S_PLAY_STND
- gh->mo->sprite = gh->mo->state->sprite;
- gh->mo->frame = (gh->mo->state->frame & FF_FRAMEMASK) | tr_trans20<mo->tics = -1;
-
- gh->oldmo.x = gh->mo->x;
- gh->oldmo.y = gh->mo->y;
- gh->oldmo.z = gh->mo->z;
-
- // Set skin
- gh->mo->skin = gh->oldmo.skin = ghskin;
-
- // Set color
- gh->mo->color = ((skin_t*)gh->mo->skin)->prefcolor;
- for (i = 0; i < MAXSKINCOLORS; i++)
- if (!stricmp(KartColor_Names[i],color)) // SRB2kart
- {
- gh->mo->color = (UINT8)i;
- break;
- }
- gh->oldmo.color = gh->mo->color;
-
- CONS_Printf(M_GetText("Added ghost %s from %s\n"), name, pdemoname);
- Z_Free(pdemoname);
-}
-
-// A simplified version of G_AddGhost...
-void G_UpdateStaffGhostName(lumpnum_t l)
-{
- UINT8 *buffer,*p;
- UINT16 ghostversion;
- UINT8 flags;
-
- buffer = p = W_CacheLumpNum(l, PU_CACHE);
-
- // read demo header
- if (memcmp(p, DEMOHEADER, 12))
- {
- goto fail;
- }
-
- p += 12; // DEMOHEADER
- p++; // VERSION
- p++; // SUBVERSION
-
- ghostversion = READUINT16(p);
- switch(ghostversion)
- {
- case DEMOVERSION: // latest always supported
- p += 64; // full demo title
- break;
-
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- break;
-#endif
-
- // too old, cannot support.
- default:
- goto fail;
- }
-
- p += 16; // demo checksum
-
- if (memcmp(p, "PLAY", 4))
- {
- goto fail;
- }
-
- p += 4; // "PLAY"
- p += 2; // gamemap
- p += 16; // mapmd5 (possibly check for consistency?)
-
- flags = READUINT8(p);
- if (!(flags & DF_GHOST))
- {
- goto fail; // we don't NEED to do it here, but whatever
- }
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion != 0x0001)
-#endif
- p++; // Gametype
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion != 0x0001)
-#endif
- G_SkipDemoExtraFiles(&p);
-
- switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT)
- {
- case ATTACKING_NONE: // 0
- break;
- case ATTACKING_RECORD: // 1
- p += 8; // demo time, lap
- break;
- default: // 3
- break;
- }
-
- p += 4; // random seed
-
-
-#ifdef DEMO_COMPAT_100
- if (ghostversion == 0x0001)
- {
- // Player name
- M_Memcpy(dummystaffname, p,16);
- dummystaffname[16] = '\0';
- goto fail; // Not really a failure but whatever
- }
-#endif
-
- p += 4; // Extrainfo location marker
-
- // Ehhhh don't need ghostversion here (?) so I'll reuse the var here
- ghostversion = READUINT16(p);
- while (ghostversion--)
- {
- p += 2;
- SKIPSTRING(p);
- p++; // stealth
- }
-
- // Assert first player is in and then read name
- if (READUINT8(p) != 0)
- goto fail;
- M_Memcpy(dummystaffname, p,16);
- dummystaffname[16] = '\0';
-
- // Ok, no longer any reason to care, bye
-fail:
- Z_Free(buffer);
- return;
-}
-
-//
-// G_TimeDemo
-// NOTE: name is a full filename for external demos
-//
-static INT32 restorecv_vidwait;
-
-void G_TimeDemo(const char *name)
-{
- nodrawers = M_CheckParm("-nodraw");
- noblit = M_CheckParm("-noblit");
- restorecv_vidwait = cv_vidwait.value;
- if (cv_vidwait.value)
- CV_Set(&cv_vidwait, "0");
- demo.timing = true;
- singletics = true;
- framecount = 0;
- demostarttime = I_GetTime();
- G_DeferedPlayDemo(name);
-}
-
-void G_DoPlayMetal(void)
-{
- lumpnum_t l;
- mobj_t *mo = NULL;
- thinker_t *th;
-
- // it's an internal demo
- if ((l = W_CheckNumForName(va("%sMS",G_BuildMapName(gamemap)))) == LUMPERROR)
- {
- CONS_Alert(CONS_WARNING, M_GetText("No bot recording for this map.\n"));
- return;
- }
- else
- metalbuffer = metal_p = W_CacheLumpNum(l, PU_STATIC);
-
- // find metal sonic
- for (th = thinkercap.next; th != &thinkercap; th = th->next)
- {
- if (th->function.acp1 != (actionf_p1)P_MobjThinker)
- continue;
-
- mo = (mobj_t *)th;
- if (mo->type == MT_METALSONIC_RACE)
- break;
- }
- if (!mo)
- {
- CONS_Alert(CONS_ERROR, M_GetText("Failed to find bot entity.\n"));
- Z_Free(metalbuffer);
- return;
- }
-
- // read demo header
- metal_p += 12; // DEMOHEADER
- metal_p++; // VERSION
- metal_p++; // SUBVERSION
- metalversion = READUINT16(metal_p);
- switch(metalversion)
- {
- case DEMOVERSION: // latest always supported
- break;
-#ifdef DEMO_COMPAT_100
- case 0x0001:
- I_Error("You need to implement demo compat here, doofus! %s:%d", __FILE__, __LINE__);
-#endif
- // too old, cannot support.
- default:
- CONS_Alert(CONS_WARNING, M_GetText("Failed to load bot recording for this map, format version incompatible.\n"));
- Z_Free(metalbuffer);
- return;
- }
- metal_p += 16; // demo checksum
- if (memcmp(metal_p, "METL", 4))
- {
- CONS_Alert(CONS_WARNING, M_GetText("Failed to load bot recording for this map, wasn't recorded in Metal format.\n"));
- Z_Free(metalbuffer);
- return;
- } metal_p += 4; // "METL"
-
- // read initial tic
- memset(&oldmetal,0,sizeof(oldmetal));
- oldmetal.x = mo->x;
- oldmetal.y = mo->y;
- oldmetal.z = mo->z;
- oldmetal.angle = mo->angle;
- metalplayback = mo;
-}
-
-void G_DoneLevelLoad(void)
-{
- CONS_Printf(M_GetText("Loaded level in %f sec\n"), (double)(I_GetTime() - demostarttime) / TICRATE);
- framecount = 0;
- demostarttime = I_GetTime();
-}
-
-/*
-===================
-=
-= G_CheckDemoStatus
-=
-= Called after a death or level completion to allow demos to be cleaned up
-= Returns true if a new demo loop action will take place
-===================
-*/
-
-// Stops metal sonic's demo. Separate from other functions because metal + replays can coexist
-void G_StopMetalDemo(void)
-{
- // Metal Sonic finishing doesn't end the game, dammit.
- Z_Free(metalbuffer);
- metalbuffer = NULL;
- metalplayback = NULL;
- metal_p = NULL;
-}
-
-// Stops metal sonic recording.
-ATTRNORETURN void FUNCNORETURN G_StopMetalRecording(void)
-{
- boolean saved = false;
- if (demobuf.p && demobuf.buffer != NULL)
- {
- UINT8 *p = demobuf.buffer+16; // checksum position
-#ifdef NOMD5
- UINT8 i;
- WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
- for (i = 0; i < 16; i++, p++)
- *p = P_RandomByte(); // This MD5 was chosen by fair dice roll and most likely < 50% correct.
-#else
- WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
- md5_buffer((char *)p+16, demobuf.p - (p+16), (void *)p); // make a checksum of everything after the checksum in the file.
-#endif
- saved = FIL_WriteFile(va("%sMS.LMP", G_BuildMapName(gamemap)), demobuf.buffer, demobuf.p - demobuf.buffer); // finally output the file.
- }
- Z_Free(demobuf.buffer);
- demobuf.buffer = NULL;
- metalrecording = false;
- if (saved)
- I_Error("Saved to %sMS.LMP", G_BuildMapName(gamemap));
- I_Error("Failed to save demo!");
-}
-
-// reset engine variable set for the demos
-// called from stopdemo command, map command, and g_checkdemoStatus.
-void G_StopDemo(void)
-{
- Z_Free(demobuf.buffer);
- demobuf.buffer = NULL;
- demo.playback = false;
- if (demo.title)
- modeattacking = ATTACKING_NONE;
- demo.title = false;
- demo.timing = false;
- singletics = false;
-
- UINT8 i;
- for (i = 0; i < MAXSPLITSCREENPLAYERS; ++i)
- {
- camera[i].freecam = false;
- camera[i].localangle = 0;
- camera[i].localaiming = 0;
- }
-
- CV_SetValue(&cv_playbackspeed, 1);
- demo.rewinding = false;
- CL_ClearRewinds();
-
- if (gamestate == GS_LEVEL && rendermode != render_none)
- {
- V_SetPaletteLump("PLAYPAL"); // Reset the palette
- R_ReInitColormaps(0, LUMPERROR);
- }
- if (gamestate == GS_INTERMISSION)
- Y_EndIntermission(); // cleanup
- if (gamestate == GS_VOTING)
- Y_EndVote();
-
- M_ClearMenus(true);
-
- G_SetGamestate(GS_NULL);
- wipegamestate = GS_NULL;
- SV_StopServer();
- SV_ResetServer();
-}
-
-// Stops timing a demo.
-static void G_StopTimingDemo(void)
-{
- INT32 demotime;
- double f1, f2;
- demotime = I_GetTime() - demostarttime;
- if (!demotime)
- return;
- G_StopDemo();
- demo.timing = false;
- f1 = (double)demotime;
- f2 = (double)framecount*TICRATE;
-
- CONS_Printf(M_GetText("timed %u gametics in %d realtics - %u frames\n%f seconds, %f avg fps\n"),
- leveltime, demotime, (UINT32)framecount, f1/TICRATE, f2/f1);
-
- if (restorecv_vidwait != cv_vidwait.value)
- CV_SetValue(&cv_vidwait, restorecv_vidwait);
-
- D_StartTitle();
-}
-
-
-boolean G_CheckDemoStatus(void)
-{
- while (ghosts)
- {
- demoghost *next = ghosts->next;
- Z_Free(ghosts);
- ghosts = next;
- }
- ghosts = NULL;
-
- // DO NOT end metal sonic demos here
-
- if (demo.timing)
- {
- G_StopTimingDemo();
- return true;
- }
-
- if (demo.playback)
- {
- if (demo.quitafterplaying)
- I_Quit();
-
- if (multiplayer && !demo.title)
- {
- G_ExitLevel();
- }
- else if (modeattacking && !demo.title) // nooo dont crash our titledemos
- {
- G_StopDemo();
- M_EndModeAttackRun();
- }
- else
- {
- G_StopDemo();
- D_StartTitle();
- }
-
- return true;
- }
-
- if (!demo.recording)
- return false;
-
- if (modeattacking || demo.savemode != DSM_NOTSAVING)
- {
- G_SaveDemo();
- return true;
- }
-
- G_ResetDemoRecording();
-
- return false;
-}
-
-void G_ResetDemoRecording(void)
-{
- if (demobuf.buffer)
- Z_Free(demobuf.buffer);
- demobuf.buffer = NULL;
- demo.recording = false;
-}
-
-static void G_ResetDemoPlayback(char *pdemoname)
-{
- if (pdemoname)
- Z_Free(pdemoname);
- if (demobuf.buffer)
- Z_Free(demobuf.buffer);
- demobuf.buffer = NULL;
- demo.playback = false;
- if (demo.title)
- modeattacking = ATTACKING_NONE;
- demo.title = false;
-}
-
-void G_SaveDemo(void)
-{
- if (!demobuf.p)
- {
- CONS_Alert(CONS_ERROR, "Failed to save Demo. No Demo pointer exists!\n");
- // reset the demo buffer
- G_ResetDemoRecording();
- return;
- }
-
- if (demobuf.buffer == NULL)
- {
- CONS_Alert(CONS_ERROR, "Failed to save Demo. No Demo buffer allocated!\n");
- // reset the demo buffer
- G_ResetDemoRecording();
- return;
- }
-
- UINT8 *p = demobuf.buffer+16; // after version
- UINT32 length;
-#ifdef NOMD5
- UINT8 i;
-#endif
-
- // Ensure extrainfo pointer is always available, even if no info is present.
- if (demoinfo_p && *(UINT32 *)demoinfo_p == 0)
- {
- WRITEUINT8(demobuf.p, DEMOMARKER); // add the demo end marker
- *(UINT32 *)demoinfo_p = demobuf.p - demobuf.buffer;
- }
- WRITEUINT8(demobuf.p, DW_END); // Mark end of demo extra data.
-
- M_Memcpy(p, demo.titlename, 64); // Write demo title here
- p += 64;
-
- if (multiplayer)
- {
- // Change the demo's name to be a slug of the title
- char demo_slug[128];
- char *writepoint;
- size_t i, strindex = 0;
- boolean dash = true;
-
- for (i = 0; i < 127 && demo.titlename[i]; i++)
- {
- if ((demo.titlename[i] >= 'a' && demo.titlename[i] <= 'z') ||
- (demo.titlename[i] >= '0' && demo.titlename[i] <= '9'))
- {
- demo_slug[strindex] = demo.titlename[i];
- strindex++;
- dash = false;
- }
- else if (demo.titlename[i] >= 'A' && demo.titlename[i] <= 'Z')
- {
- demo_slug[strindex] = demo.titlename[i] + 'a' - 'A';
- strindex++;
- dash = false;
- }
- else if (!dash)
- {
- demo_slug[strindex] = '-';
- strindex++;
- dash = true;
- }
- }
-
- demo_slug[strindex] = 0;
- if (dash) demo_slug[strindex-1] = 0;
-
- writepoint = strstr(demoname, "-") + 1;
- demo_slug[128 - (writepoint - demoname) - 4] = 0;
- sprintf(writepoint, "%s.lmp", demo_slug);
- }
-
- length = *(UINT32 *)demoinfo_p;
- WRITEUINT32(demoinfo_p, length);
-#ifdef NOMD5
- for (i = 0; i < 16; i++, p++)
- *p = M_RandomByte(); // This MD5 was chosen by fair dice roll and most likely < 50% correct.
-#else
- // Make a checksum of everything after the checksum in the file up to the end of the standard data. Extrainfo is freely modifiable.
- md5_buffer((char *)p+16, (demobuf.buffer + length) - (p+16), p);
-#endif
-
-
- if (FIL_WriteFile(va(pandf, srb2home, demoname), demobuf.buffer, demobuf.p - demobuf.buffer)) // finally output the file.
- demo.savemode = DSM_SAVED;
-
- G_ResetDemoRecording();
-
- if (modeattacking != ATTACKING_RECORD)
- {
- if (demo.savemode == DSM_SAVED)
- CONS_Printf(M_GetText("Demo %s recorded\n"), demoname);
- else
- CONS_Alert(CONS_WARNING, M_GetText("Demo %s not saved\n"), demoname);
- }
-}
-
-boolean G_DemoTitleResponder(event_t *ev)
-{
- INT32 ch;
-
- if (ev->type != ev_keydown)
- return false;
-
- ch = (INT32)ev->data1;
-
- // Only ESC and non-keyboard keys abort connection
- if (ch == KEY_ESCAPE)
- {
- demo.savemode = (cv_recordmultiplayerdemos.value == 2) ? DSM_WILLAUTOSAVE : DSM_NOTSAVING;
- return true;
- }
-
- if (ch == KEY_ENTER || ch >= KEY_MOUSE1)
- {
- demo.savemode = DSM_WILLSAVE;
- return true;
- }
-
- M_TextInputHandle(&demo.titlenameinput, ch);
-
- return true;
-}
-
//
// G_SetGamestate
//
@@ -8231,6 +4227,11 @@ boolean G_DemoTitleResponder(event_t *ev)
void G_SetGamestate(gamestate_t newstate)
{
gamestate = newstate;
+
+ //HACK: reset musiccredits whenever we change gamestate
+ // since we allow them to run everywhere now
+ S_ResetMusicCredit();
+
#ifdef HAVE_DISCORDRPC
DRPC_UpdatePresence();
#endif
diff --git a/src/g_game.h b/src/g_game.h
index 5714097b2..9d8b74144 100644
--- a/src/g_game.h
+++ b/src/g_game.h
@@ -14,9 +14,14 @@
#ifndef __G_GAME__
#define __G_GAME__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "doomdef.h"
#include "doomstat.h"
#include "d_event.h"
+#include "g_demo.h"
#include "p_saveg.h"
#include "m_textinput.h"
@@ -34,75 +39,6 @@ extern INT32 player_name_changes[MAXPLAYERS];
extern player_t players[MAXPLAYERS];
extern boolean playeringame[MAXPLAYERS];
-extern savebuffer_t demobuf;
-
-// ======================================
-// DEMO playback/recording related stuff.
-// ======================================
-
-// demoplaying back and demo recording
-extern consvar_t cv_recordmultiplayerdemos, cv_netdemosyncquality, cv_maxdemosize, cv_demochangemap;
-extern consvar_t cv_demodateformat;
-
-// Publicly-accessible demo vars
-struct demovars_s {
- char titlename[65];
- textinput_t titlenameinput;
- boolean recording, playback, timing;
- UINT16 version; // Current file format of the demo being played
- boolean title; // Title Screen demo can be cancelled by any key
- boolean rewinding; // Rewind in progress
-
- boolean loadfiles, ignorefiles; // Demo file loading options
- boolean fromtitle; // SRB2Kart: Don't stop the music
- boolean inreplayhut; // Go back to replayhut after demos
- boolean quitafterplaying; // quit after playing a demo from cmdline
- boolean deferstart; // don't start playing demo right away
-
- tic_t savebutton; // Used to determine when the local player can choose to save the replay while the race is still going
- enum {
- DSM_NOTSAVING,
- DSM_WILLAUTOSAVE,
- DSM_TITLEENTRY,
- DSM_WILLSAVE,
- DSM_SAVED
- } savemode;
-};
-
-extern struct demovars_s demo;
-
-typedef enum {
- MD_NOTLOADED,
- MD_LOADED,
- MD_SUBDIR,
- MD_OUTDATED,
- MD_INVALID
-} menudemotype_e;
-
-typedef struct menudemo_s {
- char filepath[256];
- menudemotype_e type;
-
- char title[65]; // Null-terminated for string prints
- char date[11]; // date when replay was recorded
- char version[12]; // combined version and subversion
- UINT16 map;
- UINT8 addonstatus; // What do we need to do addon-wise to play this demo?
- UINT8 gametype;
- UINT8 kartspeed; // Add OR DF_ENCORE for encore mode, idk
- UINT8 numlaps;
-
- struct {
- UINT8 ranking;
- char name[17];
- UINT8 skin, color;
- UINT32 timeorscore;
- } standings[MAXPLAYERS];
-} menudemo_t;
-
-
-extern mobj_t *metalplayback;
-
// gametic at level start
extern tic_t levelstarttic;
@@ -286,10 +222,6 @@ void G_SpawnPlayer(INT32 playernum, boolean starpost);
void G_DeferedInitNew(boolean pencoremode, const char *mapname, INT32 pickedchar,
UINT8 ssplayers, boolean FLS);
-void G_LoadDemoInfo(menudemo_t *pdemo);
-void G_LoadDemoTitle(menudemo_t *pdemo); // For use in replay search feature
-void G_DeferedPlayDemo(const char *demo);
-
// Can be called by the startup code or M_Responder, calls P_SetupLevel.
void G_LoadGame(UINT32 slot, INT16 mapoverride);
@@ -297,97 +229,6 @@ void G_SaveGameData(boolean force);
void G_SaveGame(UINT32 slot);
-// Only called by startup code.
-void G_RecordDemo(const char *name);
-void G_RecordMetal(void);
-void G_BeginRecording(void);
-void G_BeginMetal(void);
-
-// Only called by shutdown code.
-void G_WriteStanding(UINT8 ranking, char *name, INT32 skinnum, UINT8 color, UINT32 val);
-void G_SetDemoTime(UINT32 ptime, UINT32 plap);
-UINT8 G_CmpDemoTime(char *oldname, char *newname);
-
-typedef enum
-{
- GHC_NORMAL = 0,
- GHC_SUPER,
- GHC_FIREFLOWER,
- GHC_INVINCIBLE
-} ghostcolor_t;
-
-extern UINT8 demo_extradata[MAXPLAYERS];
-extern UINT8 demo_writerng;
-#define DXD_RESPAWN 0x01 // "respawn" command in console
-#define DXD_SKIN 0x02 // skin changed
-#define DXD_NAME 0x04 // name changed
-#define DXD_COLOR 0x08 // color changed
-#define DXD_PLAYSTATE 0x10 // state changed between playing, spectating, or not in-game
-
-#define DXD_PST_PLAYING 0x01
-#define DXD_PST_SPECTATING 0x02
-#define DXD_PST_LEFT 0x03
-
-// Record/playback tics
-void G_ReadDemoExtraData(void);
-void G_WriteDemoExtraData(void);
-void G_ReadDemoTiccmd(ticcmd_t *cmd, INT32 playernum);
-void G_WriteDemoTiccmd(ticcmd_t *cmd, INT32 playernum);
-void G_GhostAddThok(INT32 playernum);
-void G_GhostAddSpin(INT32 playernum);
-void G_GhostAddRev(INT32 playernum);
-void G_GhostAddColor(INT32 playernum, ghostcolor_t color);
-void G_GhostAddFlip(INT32 playernum);
-void G_GhostAddScale(INT32 playernum, fixed_t scale);
-void G_GhostAddHit(INT32 playernum, mobj_t *victim);
-void G_WriteAllGhostTics(void);
-void G_WriteGhostTic(mobj_t *ghost, INT32 playernum);
-void G_ConsAllGhostTics(void);
-void G_ConsGhostTic(INT32 playernum);
-void G_GhostTicker(void);
-
-void G_InitDemoRewind(void);
-void G_StoreRewindInfo(void);
-void G_PreviewRewind(tic_t previewtime);
-void G_ConfirmRewind(tic_t rewindtime);
-
-void G_ReadMetalTic(mobj_t *metal);
-void G_WriteMetalTic(mobj_t *metal);
-void G_SaveMetal(UINT8 **buffer);
-void G_LoadMetal(UINT8 **buffer);
-
-// Your naming conventions are stupid and useless.
-// There is no conflict here.
-typedef struct demoghost {
- UINT8 checksum[16];
- UINT8 *buffer, *p, color;
- UINT16 version;
- mobj_t oldmo, *mo;
- struct demoghost *next;
-} demoghost;
-extern demoghost *ghosts;
-
-// G_CheckDemoExtraFiles: checks if our loaded WAD list matches the demo's.
-#define DFILE_ERROR_NOTLOADED 0x01 // Files are not loaded, but can be without a restart.
-#define DFILE_ERROR_OUTOFORDER 0x02 // Files are loaded, but out of order.
-#define DFILE_ERROR_INCOMPLETEOUTOFORDER 0x03 // Some files are loaded out of order, but others are not.
-#define DFILE_ERROR_CANNOTLOAD 0x04 // Files are missing and cannot be loaded.
-#define DFILE_ERROR_EXTRAFILES 0x05 // Extra files outside of the replay's file list are loaded.
-
-void G_ResetDemoRecording(void);
-void G_DoPlayDemo(char *defdemoname);
-void G_TimeDemo(const char *name);
-void G_AddGhost(char *defdemoname);
-void G_UpdateStaffGhostName(lumpnum_t l);
-void G_DoPlayMetal(void);
-void G_DoneLevelLoad(void);
-void G_StopMetalDemo(void);
-ATTRNORETURN void FUNCNORETURN G_StopMetalRecording(void);
-void G_StopDemo(void);
-boolean G_CheckDemoStatus(void);
-void G_SaveDemo(void);
-boolean G_DemoTitleResponder(event_t *ev);
-
#define G_GametypeHasTeams() (G_IsGameType(GT_TEAMMATCH) || G_IsGameType(GT_CTF))
#define G_BattleGametype() (G_IsGameType(GT_MATCH))
#define G_RaceGametype() (G_IsGameType(GT_RACE))
@@ -484,4 +325,8 @@ void G_AddMapToBuffer(INT16 map);
void G_FixCamera(UINT8 view);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/g_input.c b/src/g_input.c
index 43b7f48ca..8d5b38bf2 100644
--- a/src/g_input.c
+++ b/src/g_input.c
@@ -1030,7 +1030,7 @@ INT32 G_KeyStringtoNum(const char *keystr)
if (!keystr[0])
return 0;
- if (!keystr[0] || (!keystr[1] && keystr[0] > ' ' && keystr[0] <= 'z'))
+ if (!keystr[1] && keystr[0] > ' ' && keystr[0] <= 'z')
return keystr[0];
if (!strncmp(keystr, "KEY", 3) && keystr[3] >= '0' && keystr[3] <= '9')
diff --git a/src/hardware/Sourcefile b/src/hardware/Sourcefile
new file mode 100644
index 000000000..e66482c3d
--- /dev/null
+++ b/src/hardware/Sourcefile
@@ -0,0 +1,14 @@
+hw_bsp.c
+hw_draw.c
+hw_main.cpp
+hw_clip.c
+hw_md2.c
+hw_cache.c
+hw_md2load.c
+hw_md3load.c
+hw_model.c
+hw_portal.c
+hw_batching.c
+hw_shaders.c
+u_list.c
+r_opengl/r_opengl.c
diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c
index 3655beb8a..3b5c5426e 100644
--- a/src/hardware/hw_batching.c
+++ b/src/hardware/hw_batching.c
@@ -25,22 +25,23 @@ GLMipmap_t *current_texture = NULL;
boolean currently_batching = false;
-FOutVector* finalVertexArray = NULL;// contains subset of sorted vertices and texture coordinates to be sent to gpu
+FOutVector* finalVertexArray = NULL;// contains subset of sorted vertices and texture coordinates to be sent to gpu
UINT32* finalVertexIndexArray = NULL;// contains indexes for glDrawElements, taking into account fan->triangles conversion
// NOTE have this alloced as 3x finalVertexArray size
int finalVertexArrayAllocSize = 65536;
+
//GLubyte* colorArray = NULL;// contains color data to be sent to gpu, if needed
//int colorArrayAllocSize = 65536;
// not gonna use this for now, just sort by color and change state when it changes
// later maybe when using vertex attributes if it's needed
-PolygonArrayEntry* polygonArray = NULL;// contains the polygon data from DrawPolygon, waiting to be processed
-int polygonArraySize = 0;
-PolygonArrayEntry **polygonArraySorted = NULL;// contains sorted pointers to polygonArray
+PolygonArrayEntry* polygonArray = NULL ;// contains the polygon data from DrawPolygon, waiting to be processed
+PolygonArrayEntry **polygonArraySorted = NULL; // contains sorted pointers to polygonArray
+int polygonArraySize = 0;
int polygonArrayAllocSize = 65536;
-FOutVector* unsortedVertexArray = NULL;// contains unsorted vertices and texture coordinates from DrawPolygon
-int unsortedVertexArraySize = 0;
+FOutVector* unsortedVertexArray = NULL; // contains unsorted vertices and texture coordinates from DrawPolygon
+int unsortedVertexArraySize = 0;
int unsortedVertexArrayAllocSize = 65536;
// Enables batching mode. HWR_ProcessPolygon will collect polygons instead of passing them directly to the rendering backend.
@@ -55,11 +56,11 @@ void HWR_StartBatching(void)
// init arrays if that has not been done yet
if (!finalVertexArray)
{
- finalVertexArray = malloc(finalVertexArrayAllocSize * sizeof(FOutVector));
+ finalVertexArray = malloc(finalVertexArrayAllocSize * sizeof(FOutVector));
finalVertexIndexArray = malloc(finalVertexArrayAllocSize * 3 * sizeof(UINT32));
- polygonArray = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry));
- polygonArraySorted = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry *));
- unsortedVertexArray = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector));
+ polygonArray = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry));
+ polygonArraySorted = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry *));
+ unsortedVertexArray = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector));
}
currently_batching = true;
@@ -89,32 +90,23 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt
{
if (!pSurf)
{
- I_Error("Got a null FSurfaceInfo in batching");// nulls should not come in the stuff that batching currently applies to
+ I_Error("Got a null FSurfaceInfo in batching"); // nulls should not come in the stuff that batching currently applies to
}
if (polygonArraySize == polygonArrayAllocSize)
{
- PolygonArrayEntry* new_array;
- // ran out of space, make new array double the size
+ // ran out of space, double the array size
polygonArrayAllocSize *= 2;
- new_array = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry));
- memcpy(new_array, polygonArray, polygonArraySize * sizeof(PolygonArrayEntry));
- free(polygonArray);
- polygonArray = new_array;
+ polygonArray = realloc(polygonArray, polygonArrayAllocSize * sizeof(PolygonArrayEntry));
// also need to redo the index array, dont need to copy it though
- free(polygonArraySorted);
- polygonArraySorted = malloc(polygonArrayAllocSize * sizeof(PolygonArrayEntry *));
+ polygonArraySorted = realloc(polygonArraySorted, polygonArrayAllocSize * sizeof(PolygonArrayEntry*));
}
while (unsortedVertexArraySize + (int)iNumPts > unsortedVertexArrayAllocSize)
{
- FOutVector* new_array;
// need more space for vertices in unsortedVertexArray
unsortedVertexArrayAllocSize *= 2;
- new_array = malloc(unsortedVertexArrayAllocSize * sizeof(FOutVector));
- memcpy(new_array, unsortedVertexArray, unsortedVertexArraySize * sizeof(FOutVector));
- free(unsortedVertexArray);
- unsortedVertexArray = new_array;
+ unsortedVertexArray = realloc(unsortedVertexArray, unsortedVertexArrayAllocSize * sizeof(FOutVector));
}
// add the polygon data to the arrays
@@ -124,7 +116,7 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt
polygonArray[polygonArraySize].numVerts = iNumPts;
polygonArray[polygonArraySize].polyFlags = PolyFlags;
polygonArray[polygonArraySize].texture = current_texture;
- polygonArray[polygonArraySize].shader = (shader_target != -1) ? HWR_GetShaderFromTarget(shader_target) : shader_target;
+ polygonArray[polygonArraySize].shader = (shader_target != SHADER_NONE) ? HWR_GetShaderFromTarget(shader_target) : shader_target;
polygonArray[polygonArraySize].horizonSpecial = horizonSpecial;
polygonArraySize++;
@@ -140,13 +132,13 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt
static int comparePolygons(const void *p1, const void *p2)
{
- PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1;
- PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2;
int diff;
INT64 diff64;
+ const PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1;
+ const PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2;
- int shader1 = (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) ? -1 : poly1->shader;
- int shader2 = (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) ? -1 : poly2->shader;
+ const int shader1 = (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) ? -1 : poly1->shader;
+ const int shader2 = (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) ? -1 : poly2->shader;
// skywalls and horizon lines must retain their order for horizon lines to work
if (shader1 == -1 && shader2 == -1)
@@ -177,20 +169,18 @@ static int comparePolygons(const void *p1, const void *p2)
diff = poly1->surf.LightInfo.fade_end - poly2->surf.LightInfo.fade_end;
if (diff != 0) return diff;
- diff = poly1->surf.LightInfo.directional - poly2->surf.LightInfo.directional;
-
- return diff;
+ return poly1->surf.LightInfo.directional - poly2->surf.LightInfo.directional;
}
static int comparePolygonsNoShaders(const void *p1, const void *p2)
{
- PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1;
- PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2;
int diff;
INT64 diff64;
+ const PolygonArrayEntry *poly1 = *(PolygonArrayEntry *const *)p1;
+ const PolygonArrayEntry *poly2 = *(PolygonArrayEntry *const *)p2;
- GLMipmap_t *texture1 = (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) ? NULL : poly1->texture;
- GLMipmap_t *texture2 = (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) ? NULL : poly2->texture;
+ const GLMipmap_t *texture1 = (poly1->polyFlags & PF_NoTexture || poly1->horizonSpecial) ? NULL : poly1->texture;
+ const GLMipmap_t *texture2 = (poly2->polyFlags & PF_NoTexture || poly2->horizonSpecial) ? NULL : poly2->texture;
// skywalls and horizon lines must retain their order for horizon lines to work
if (!texture1 && !texture2)
@@ -214,17 +204,16 @@ static int comparePolygonsNoShaders(const void *p1, const void *p2)
// the rendering backend to draw them.
void HWR_RenderBatches(void)
{
- int finalVertexWritePos = 0;// position in finalVertexArray
- int finalIndexWritePos = 0;// position in finalVertexIndexArray
-
- int polygonReadPos = 0;// position in polygonArraySorted
+ int finalVertexWritePos = 0; // position in finalVertexArray
+ int finalIndexWritePos = 0; // position in finalVertexIndexArray
+ int polygonReadPos = 0; // position in polygonArraySorted
int currentShader;
int nextShader = 0;
- GLMipmap_t *currentTexture = NULL;
- GLMipmap_t *nextTexture = NULL;
- FBITFIELD currentPolyFlags = 0;
- FBITFIELD nextPolyFlags = 0;
+ GLMipmap_t *currentTexture = NULL;
+ GLMipmap_t *nextTexture = NULL;
+ FBITFIELD currentPolyFlags = 0;
+ FBITFIELD nextPolyFlags = 0;
FSurfaceInfo currentSurfaceInfo;
FSurfaceInfo nextSurfaceInfo;
@@ -235,8 +224,8 @@ void HWR_RenderBatches(void)
I_Error("HWR_RenderBatches called without starting batching");
}
- nextSurfaceInfo.LightInfo.fade_end = 0;
- nextSurfaceInfo.LightInfo.fade_start = 0;
+ nextSurfaceInfo.LightInfo.fade_end = 0;
+ nextSurfaceInfo.LightInfo.fade_start = 0;
nextSurfaceInfo.LightInfo.light_level = 0;
nextSurfaceInfo.LightInfo.directional = false;
@@ -254,7 +243,7 @@ void HWR_RenderBatches(void)
ps_hw_numpolys.value.i = polygonArraySize;
ps_hw_numcalls.value.i = ps_hw_numverts.value.i = 0;
ps_hw_numshaders.value.i = ps_hw_numtextures.value.i
- = ps_hw_numpolyflags.value.i = ps_hw_numcolors.value.i = 1;
+ = ps_hw_numpolyflags.value.i = ps_hw_numcolors.value.i = 1;
// init polygonArraySorted
for (i = 0; i < polygonArraySize; i++)
@@ -264,10 +253,7 @@ void HWR_RenderBatches(void)
// sort polygons
PS_START_TIMING(ps_hw_batchsorttime);
- if (cv_glshaders.value && gl_shadersavailable)
- qs22j(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygons);
- else
- qs22j(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), comparePolygonsNoShaders);
+ qs22j(polygonArraySorted, polygonArraySize, sizeof(PolygonArrayEntry *), (HWR_UseShader() ? comparePolygons : comparePolygonsNoShaders));
PS_STOP_TIMING(ps_hw_batchsorttime);
// sort order
@@ -279,16 +265,16 @@ void HWR_RenderBatches(void)
PS_START_TIMING(ps_hw_batchdrawtime);
- currentShader = polygonArraySorted[0]->shader;
- currentTexture = polygonArraySorted[0]->texture;
- currentPolyFlags = polygonArraySorted[0]->polyFlags;
+ currentShader = polygonArraySorted[0]->shader;
+ currentTexture = polygonArraySorted[0]->texture;
+ currentPolyFlags = polygonArraySorted[0]->polyFlags;
currentSurfaceInfo = polygonArraySorted[0]->surf;
// For now, will sort and track the colors. Vertex attributes could be used instead of uniforms
// and a color array could replace the color calls.
// set state for first batch
- if (cv_glshaders.value && gl_shadersavailable)
+ if (HWR_UseShader())
{
GL_SetShader(currentShader);
}
@@ -313,42 +299,37 @@ void HWR_RenderBatches(void)
// steps:
// write vertices
// check for changes or end, otherwise go back to writing
- // changes will affect the next vars and the change bools
- // end could set flag for stopping
+ // changes will affect the next vars and the change bools
+ // end could set flag for stopping
// execute draw call
// could check ending flag here
// change states according to next vars and change bools, updating the current vars and reseting the bools
// reset write pos
// repeat loop
- PolygonArrayEntry *entry = polygonArraySorted[polygonReadPos++];
- int numVerts = entry->numVerts;
+ const PolygonArrayEntry *entry = polygonArraySorted[polygonReadPos++];
+ const int numVerts = entry->numVerts;
+
// before writing, check if there is enough room
// using 'while' instead of 'if' here makes sure that there will *always* be enough room.
// probably never will this loop run more than once though
while (finalVertexWritePos + numVerts > finalVertexArrayAllocSize)
{
- FOutVector* new_array;
- unsigned int* new_index_array;
finalVertexArrayAllocSize *= 2;
- new_array = malloc(finalVertexArrayAllocSize * sizeof(FOutVector));
- memcpy(new_array, finalVertexArray, finalVertexWritePos * sizeof(FOutVector));
- free(finalVertexArray);
- finalVertexArray = new_array;
+ finalVertexArray = realloc(finalVertexArray, finalVertexArrayAllocSize * sizeof(FOutVector));
// also increase size of index array, 3x of vertex array since
// going from fans to triangles increases vertex count to 3x
- new_index_array = malloc(finalVertexArrayAllocSize * 3 * sizeof(UINT32));
- memcpy(new_index_array, finalVertexIndexArray, finalIndexWritePos * sizeof(UINT32));
- free(finalVertexIndexArray);
- finalVertexIndexArray = new_index_array;
+ finalVertexIndexArray = realloc(finalVertexIndexArray, finalVertexArrayAllocSize * 3 * sizeof(UINT32));
}
+
// write the vertices of the polygon
- memcpy(&finalVertexArray[finalVertexWritePos], &unsortedVertexArray[entry->vertsIndex],
- numVerts * sizeof(FOutVector));
+ memcpy(&finalVertexArray[finalVertexWritePos], &unsortedVertexArray[entry->vertsIndex], numVerts * sizeof(FOutVector));
+
// write the indexes, pointing to the fan vertexes but in triangles format
firstIndex = finalVertexWritePos;
lastIndex = finalVertexWritePos + numVerts;
finalVertexWritePos += 2;
+
while (finalVertexWritePos < lastIndex)
{
finalVertexIndexArray[finalIndexWritePos++] = firstIndex;
@@ -363,16 +344,16 @@ void HWR_RenderBatches(void)
else
{
// check if a state change is required, set the change bools and next vars
- PolygonArrayEntry *nextEntry = polygonArraySorted[polygonReadPos];
- nextShader = nextEntry->shader;
- nextTexture = nextEntry->texture;
- nextPolyFlags = nextEntry->polyFlags;
+ const PolygonArrayEntry *nextEntry = polygonArraySorted[polygonReadPos];
+ nextShader = nextEntry->shader;
+ nextTexture = nextEntry->texture;
+ nextPolyFlags = nextEntry->polyFlags;
nextSurfaceInfo = nextEntry->surf;
if (nextPolyFlags & PF_NoTexture)
nextTexture = 0;
- if (currentShader != nextShader && cv_glshaders.value && gl_shadersavailable)
+ if (currentShader != nextShader && HWR_UseShader())
{
changeState = true;
changeShader = true;
@@ -390,14 +371,14 @@ void HWR_RenderBatches(void)
changePolyFlags = true;
}
- if (cv_glshaders.value && gl_shadersavailable)
+ if (HWR_UseShader())
{
if (currentSurfaceInfo.PolyColor.rgba != nextSurfaceInfo.PolyColor.rgba ||
currentSurfaceInfo.TintColor.rgba != nextSurfaceInfo.TintColor.rgba ||
currentSurfaceInfo.FadeColor.rgba != nextSurfaceInfo.FadeColor.rgba ||
currentSurfaceInfo.LightInfo.light_level != nextSurfaceInfo.LightInfo.light_level ||
- currentSurfaceInfo.LightInfo.fade_start != nextSurfaceInfo.LightInfo.fade_start ||
- currentSurfaceInfo.LightInfo.fade_end != nextSurfaceInfo.LightInfo.fade_end ||
+ currentSurfaceInfo.LightInfo.fade_start != nextSurfaceInfo.LightInfo.fade_start ||
+ currentSurfaceInfo.LightInfo.fade_end != nextSurfaceInfo.LightInfo.fade_end ||
currentSurfaceInfo.LightInfo.directional != nextSurfaceInfo.LightInfo.directional)
{
changeState = true;
@@ -423,7 +404,7 @@ void HWR_RenderBatches(void)
ps_hw_numverts.value.i += finalIndexWritePos;
// reset write positions
finalVertexWritePos = 0;
- finalIndexWritePos = 0;
+ finalIndexWritePos = 0;
}
else
continue;
@@ -469,9 +450,10 @@ void HWR_RenderBatches(void)
ps_hw_numcolors.value.i++;
}
- // and that should be it?
}
+ // and that should be it?
}
+
// reset the arrays (set sizes to 0)
polygonArraySize = 0;
unsortedVertexArraySize = 0;
diff --git a/src/hardware/hw_batching.h b/src/hardware/hw_batching.h
index 7f418fc77..d1808ce43 100644
--- a/src/hardware/hw_batching.h
+++ b/src/hardware/hw_batching.h
@@ -13,6 +13,10 @@
#ifndef __HWR_BATCHING_H__
#define __HWR_BATCHING_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "hw_defs.h"
#include "hw_data.h"
#include "hw_gl.h"
@@ -36,4 +40,8 @@ void HWR_SetCurrentTexture(GLMipmap_t *texture);
void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPts, FBITFIELD PolyFlags, int shader, boolean horizonSpecial);
void HWR_RenderBatches(void);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c
index 934f13a14..76231750c 100644
--- a/src/hardware/hw_bsp.c
+++ b/src/hardware/hw_bsp.c
@@ -371,12 +371,13 @@ static poly_t *CutOutSubsecPoly(seg_t *lseg, INT32 count, poly_t *poly)
line_t *line = lseg->linedef;
// portal check
- if (!gl_maphasportals && line->special == 40 && lseg->side == 0)
+ if (!gl_maphasportals && line->special == PORTALSPECIAL && lseg->side == 0)
{
// Find the other side!
- INT32 line2 = P_FindSpecialLineFromTag(40, line->tag, -1);
+ INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, -1);
+
if (line == &lines[line2])
- line2 = P_FindSpecialLineFromTag(40, line->tag, line2);
+ line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->tag, line2);
if (line2 >= 0) // found it!
gl_maphasportals = 1;
}
diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c
index 85e50465a..36f6a57a5 100644
--- a/src/hardware/hw_cache.c
+++ b/src/hardware/hw_cache.c
@@ -46,12 +46,16 @@ RGBA_t *HWR_GetTexturePalette(void)
static INT32 format2bpp(GLTextureFormat_t format)
{
- if (format == GL_TEXFMT_RGBA)
- return 4;
- else if (format == GL_TEXFMT_ALPHA_INTENSITY_88 || format == GL_TEXFMT_AP_88)
- return 2;
- else
- return 1;
+ switch (format)
+ {
+ case GL_TEXFMT_RGBA:
+ return 4;
+ case GL_TEXFMT_ALPHA_INTENSITY_88:
+ case GL_TEXFMT_AP_88:
+ return 2;
+ default:
+ return 1;
+ }
}
// This code was originally placed directly in HWR_DrawPatchInCache.
@@ -221,8 +225,6 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap,
if (texture->width <= 0 || texture->height <= 0)
return;
- palette = HWR_GetTexturePalette();
-
x1 = patch->originx;
width = SHORT(realpatch->width);
height = SHORT(realpatch->height);
@@ -234,6 +236,8 @@ static void HWR_DrawTexturePatchInCache(GLMipmap_t *mipmap,
if (patch->originy > texture->height || (patch->originy + height) < 0)
return; // patch not located within texture's y bounds, ignore
+ palette = HWR_GetTexturePalette();
+
// patch is actually inside the texture!
// now check if texture is partly off-screen and adjust accordingly
@@ -323,7 +327,6 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe
boolean skyspecial = false; // poor hack for Legacy large skies..
RGBA_t *palette;
- palette = HWR_GetTexturePalette();
texture = textures[texnum];
@@ -361,6 +364,8 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe
INT32 j;
RGBA_t col;
+ palette = HWR_GetTexturePalette();
+
col = palette[HWR_CHROMAKEY_EQUIVALENTCOLORINDEX];
for (idx = 0, j = 0; j < blockheight; j++)
diff --git a/src/hardware/hw_clip.h b/src/hardware/hw_clip.h
index dfaa87f81..4299fbaea 100644
--- a/src/hardware/hw_clip.h
+++ b/src/hardware/hw_clip.h
@@ -7,6 +7,10 @@
*
*/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
// OpenGL BSP clipping
#include "../doomdef.h"
#include "../tables.h"
@@ -22,3 +26,7 @@ angle_t gld_FrustumAngle(angle_t tiltangle);
void gld_FrustumSetup(void);
boolean gld_SphereInFrustum(float x, float y, float z, float radius);
#endif
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h
index 08cce42c9..1da42770a 100644
--- a/src/hardware/hw_defs.h
+++ b/src/hardware/hw_defs.h
@@ -318,6 +318,8 @@ enum hwdsetspecialstate
HWD_SET_TEXTUREFILTERMODE,
HWD_SET_TEXTUREANISOTROPICMODE,
+ HWD_SET_WIREFRAME,
+
HWD_SET_MSAA,
HWD_SET_SCREEN_TEXTURES,
diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c
index 9fd90fb09..5c13cf9ff 100644
--- a/src/hardware/hw_draw.c
+++ b/src/hardware/hw_draw.c
@@ -96,12 +96,12 @@ void HWR_DrawPatch(patch_t *gpatch, INT32 x, INT32 y, INT32 option)
pdupx = pdupy = 2.0f;
break;
case V_SMALLSCALEPATCH:
- pdupx = 2.0f * FIXED_TO_FLOAT(vid.fsmalldupx);
- pdupy = 2.0f * FIXED_TO_FLOAT(vid.fsmalldupy);
+ pdupx = 2.0f * FIXED_TO_FLOAT(vid.smalldupx*FRACUNIT);
+ pdupy = 2.0f * FIXED_TO_FLOAT(vid.smalldupy*FRACUNIT);
break;
case V_MEDSCALEPATCH:
- pdupx = 2.0f * FIXED_TO_FLOAT(vid.fmeddupx);
- pdupy = 2.0f * FIXED_TO_FLOAT(vid.fmeddupy);
+ pdupx = 2.0f * FIXED_TO_FLOAT(vid.meddupx*FRACUNIT);
+ pdupy = 2.0f * FIXED_TO_FLOAT(vid.meddupx*FRACUNIT);
break;
}
@@ -241,16 +241,16 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p
if (option & V_SNAPTORIGHT)
cx += (fvw - (FLOATBASEVIDWIDTH * dupx));
else if (!(option & V_SNAPTOLEFT))
- cx += (fvw - (FLOATBASEVIDWIDTH * dupx))/2;
+ cx += (fvw - (FLOATBASEVIDWIDTH * dupx))/2.0f;
}
if (fabsf(fvh - FLOATBASEVIDHEIGHT * dupy) > 1.0E-36f)
{
if ((option & (V_SPLITSCREEN|V_SNAPTOTOP)) == (V_SPLITSCREEN|V_SNAPTOTOP))
- cy += (fvh/2 - (FLOATBASEVIDHEIGHT/2 * dupy));
+ cy += (fvh/2.0f - (FLOATBASEVIDHEIGHT/2.0f * dupy));
else if (option & V_SNAPTOBOTTOM)
cy += (fvh - (FLOATBASEVIDHEIGHT * dupy));
else if (!(option & V_SNAPTOTOP))
- cy += (fvh - (FLOATBASEVIDHEIGHT * dupy))/2;
+ cy += (fvh - (FLOATBASEVIDHEIGHT * dupy))/2.0f;
}
}
}
@@ -305,10 +305,13 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p
FSurfaceInfo Surf;
Surf.PolyColor.s.red = Surf.PolyColor.s.green = Surf.PolyColor.s.blue = 0xff;
- if (alphalevel == 13) Surf.PolyColor.s.alpha = softwaretranstogl_lo[hudtrans];
- else if (alphalevel == 14) Surf.PolyColor.s.alpha = softwaretranstogl[hudtrans];
- else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans];
- else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel];
+ switch (alphalevel)
+ {
+ case 13: Surf.PolyColor.s.alpha = softwaretranstogl_lo[hudtrans]; break;
+ case 14: Surf.PolyColor.s.alpha = softwaretranstogl[hudtrans]; break;
+ case 15: Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans]; break;
+ default: Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; break;
+ }
flags |= PF_Modulated;
GL_DrawPolygon(&Surf, v, 4, flags);
@@ -392,16 +395,16 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale,
if (option & V_SNAPTORIGHT)
cx += (fvw - (FLOATBASEVIDWIDTH * dupx));
else if (!(option & V_SNAPTOLEFT))
- cx += (fvw - (FLOATBASEVIDWIDTH * dupx))/2;
+ cx += (fvw - (FLOATBASEVIDWIDTH * dupx))/2.0f;
}
if (fabsf(fvh - FLOATBASEVIDHEIGHT * dupy) > 1.0E-36f)
{
if ((option & (V_SPLITSCREEN|V_SNAPTOTOP)) == (V_SPLITSCREEN|V_SNAPTOTOP))
- cy += (fvh/2 - (FLOATBASEVIDHEIGHT/2 * dupy));
+ cy += (fvh/2.0f - (FLOATBASEVIDHEIGHT/2.0f * dupy));
else if (option & V_SNAPTOBOTTOM)
cy += (fvh - (FLOATBASEVIDHEIGHT * dupy));
else if (!(option & V_SNAPTOTOP))
- cy += (fvh - (FLOATBASEVIDHEIGHT * dupy))/2;
+ cy += (fvh - (FLOATBASEVIDHEIGHT * dupy))/2.0f;
}
}
}
@@ -467,10 +470,13 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale,
FSurfaceInfo Surf;
Surf.PolyColor.s.red = Surf.PolyColor.s.green = Surf.PolyColor.s.blue = 0xff;
- if (alphalevel == 13) Surf.PolyColor.s.alpha = softwaretranstogl_lo[cv_translucenthud.value];
- else if (alphalevel == 14) Surf.PolyColor.s.alpha = softwaretranstogl[cv_translucenthud.value];
- else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[cv_translucenthud.value];
- else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel];
+ switch (alphalevel)
+ {
+ case 13: Surf.PolyColor.s.alpha = softwaretranstogl_lo[cv_translucenthud.value]; break;
+ case 14: Surf.PolyColor.s.alpha = softwaretranstogl[cv_translucenthud.value]; break;
+ case 15: Surf.PolyColor.s.alpha = softwaretranstogl_hi[cv_translucenthud.value]; break;
+ default: Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; break;
+ }
flags |= PF_Modulated;
GL_DrawPolygon(&Surf, v, 4, flags);
@@ -487,7 +493,7 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale,
// --------------------------------------------------------------------------
// Fills a box of pixels using a flat texture as a pattern
// --------------------------------------------------------------------------
-void HWR_DrawFlatFill (INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum)
+void HWR_DrawFlatFill(INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum)
{
FOutVector v[4];
double dflatsize;
@@ -840,7 +846,7 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color)
if (color & V_SNAPTORIGHT)
fx += (fvw - (FLOATBASEVIDWIDTH * dupx));
else if (!(color & V_SNAPTOLEFT))
- fx += (fvw - (FLOATBASEVIDWIDTH * dupx)) / 2;
+ fx += (fvw - (FLOATBASEVIDWIDTH * dupx)) / 2.0f;
}
if (fabsf(fvh - (FLOATBASEVIDHEIGHT * dupy)) > 1.0E-36f)
{
@@ -848,7 +854,7 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color)
if (color & V_SNAPTOBOTTOM)
fy += (fvh - (FLOATBASEVIDHEIGHT * dupy));
else if (!(color & V_SNAPTOTOP))
- fy += (fvh - (FLOATBASEVIDHEIGHT * dupy)) / 2;
+ fy += (fvh - (FLOATBASEVIDHEIGHT * dupy)) / 2.0f;
}
}
@@ -1122,10 +1128,13 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color)
if (alphalevel)
{
- if (alphalevel == 13) Surf.PolyColor.s.alpha = softwaretranstogl_lo[hudtrans];
- else if (alphalevel == 14) Surf.PolyColor.s.alpha = softwaretranstogl[hudtrans];
- else if (alphalevel == 15) Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans];
- else Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel];
+ switch (alphalevel)
+ {
+ case 13: Surf.PolyColor.s.alpha = softwaretranstogl_lo[hudtrans]; break;
+ case 14: Surf.PolyColor.s.alpha = softwaretranstogl[hudtrans]; break;
+ case 15: Surf.PolyColor.s.alpha = softwaretranstogl_hi[hudtrans]; break;
+ default: Surf.PolyColor.s.alpha = softwaretranstogl[10-alphalevel]; break;
+ }
}
GL_DrawPolygon(&Surf, v, 4, PF_NoTexture|PF_Modulated|PF_Translucent|PF_NoDepthTest);
diff --git a/src/hardware/hw_gl.h b/src/hardware/hw_gl.h
index a21fd0a3a..8780fc57b 100644
--- a/src/hardware/hw_gl.h
+++ b/src/hardware/hw_gl.h
@@ -13,6 +13,10 @@
#ifndef __HWR_GL_H__
#define __HWR_GL_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "../screen.h"
#include "hw_data.h"
@@ -76,4 +80,8 @@ UINT32 GL_CreateLightTable(RGBA_t *hw_lighttable);
void GL_ClearLightTables(void);
void GL_SetScreenPalette(RGBA_t *palette);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // __HWR_GL_H__
diff --git a/src/hardware/hw_glob.h b/src/hardware/hw_glob.h
index 0589ba1d2..09956b99d 100644
--- a/src/hardware/hw_glob.h
+++ b/src/hardware/hw_glob.h
@@ -14,6 +14,10 @@
#ifndef _HWR_GLOB_H_
#define _HWR_GLOB_H_
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "hw_defs.h"
#include "../m_misc.h"
#include "../r_defs.h"
@@ -109,4 +113,8 @@ const char *HWR_GetShaderName(INT32 shader);
extern customshaderxlat_t shaderxlat[];
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif //_HW_GLOB_
diff --git a/src/hardware/hw_main.c b/src/hardware/hw_main.cpp
similarity index 91%
rename from src/hardware/hw_main.c
rename to src/hardware/hw_main.cpp
index 94767ff5d..bbb116250 100644
--- a/src/hardware/hw_main.c
+++ b/src/hardware/hw_main.cpp
@@ -11,13 +11,15 @@
/// \file
/// \brief hardware renderer, using the standard HardWareRender driver DLL for SRB2
-#include
+#ifdef HWRENDER
+
+#include
+#define _USE_MATH_DEFINES
+#include
#include "../doomstat.h"
#include "../doomdef.h"
-#ifdef HWRENDER
-
#include "hw_main.h"
#include "hw_glob.h"
#include "hw_gl.h"
@@ -100,28 +102,28 @@ sector_t *gl_backsector;
static boolean gl_maphashorizonlines = false;
// values for the far clipping plane
-static float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f};
+static constexpr float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f};
// values for bsp culling
// slightly higher than the far clipping plane to compensate for impreciseness
-static INT32 bsp_culling_distances[] = {(1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT,
+static constexpr INT32 bsp_culling_distances[] = {(1024+512)*FRACUNIT, (2048+512)*FRACUNIT, (4096+512)*FRACUNIT,
(6144+512)*FRACUNIT, (8192+512)*FRACUNIT, (12288+512)*FRACUNIT, (16384+512)*FRACUNIT};
// Performance stats
-ps_metric_t ps_hw_nodesorttime = {0};
-ps_metric_t ps_hw_nodedrawtime = {0};
-ps_metric_t ps_hw_spritesorttime = {0};
-ps_metric_t ps_hw_spritedrawtime = {0};
+ps_metric_t ps_hw_nodesorttime = {};
+ps_metric_t ps_hw_nodedrawtime = {};
+ps_metric_t ps_hw_spritesorttime = {};
+ps_metric_t ps_hw_spritedrawtime = {};
// Performance stats for batching
-ps_metric_t ps_hw_numpolys = {0};
-ps_metric_t ps_hw_numverts = {0};
-ps_metric_t ps_hw_numcalls = {0};
-ps_metric_t ps_hw_numshaders = {0};
-ps_metric_t ps_hw_numtextures = {0};
-ps_metric_t ps_hw_numpolyflags = {0};
-ps_metric_t ps_hw_numcolors = {0};
-ps_metric_t ps_hw_batchsorttime = {0};
-ps_metric_t ps_hw_batchdrawtime = {0};
+ps_metric_t ps_hw_numpolys = {};
+ps_metric_t ps_hw_numverts = {};
+ps_metric_t ps_hw_numcalls = {};
+ps_metric_t ps_hw_numshaders = {};
+ps_metric_t ps_hw_numtextures = {};
+ps_metric_t ps_hw_numpolyflags = {};
+ps_metric_t ps_hw_numcolors = {};
+ps_metric_t ps_hw_batchsorttime = {};
+ps_metric_t ps_hw_batchdrawtime = {};
static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum, boolean noencore, FSurfaceInfo* Surf, INT32 cutflag, ffloor_t *pfloor, FBITFIELD polyflags);
static void HWR_RenderWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap);
@@ -226,6 +228,8 @@ consvar_t cv_glsolvetjoin = {"gr_solvetjoin", "On", 0, CV_OnOff, NULL, 0, NULL,
consvar_t cv_glbatching = {"gr_batching", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_glwireframe = {"gr_wireframe", "Off", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
consvar_t cv_glrenderdistance = {"gr_renderdistance", "Max", CV_SAVE, glrenderdistance_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
consvar_t cv_glhorizonlines = {"gr_horizonlines", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
@@ -338,6 +342,11 @@ static void HWR_SetShaderState(void)
GL_SetSpecialState(HWD_SET_SHADERS, HWR_UseShader() ? 1 : 0);
}
+static boolean HWR_IsWireframeMode(void)
+{
+ return (cv_glwireframe.value /*&& cv_debug*/);
+}
+
static boolean HWR_OverrideObjectLightLevel(mobj_t *thing, INT32 *lightlevel)
{
if (R_ThingIsFullBright(thing))
@@ -365,15 +374,15 @@ void HWR_ObjectLightLevelPost(gl_vissprite_t *spr, const sector_t *sector, INT32
fixed_t extralight = R_GetSpriteDirectionalLighting(R_PointToAngle(spr->mobj->x, spr->mobj->y));
// Less change in contrast in dark sectors
- extralight = FixedMul(extralight, min(max(0, *lightlevel), 255) * FRACUNIT / 255);
+ extralight = FixedMul(extralight, CLAMP(*lightlevel, 0, 255) * FRACUNIT / 255);
// simple OGL approximation
- fixed_t tr = R_PointToDist(spr->mobj->x, spr->mobj->y);
+ fixed_t tr = R_QuickCamDist(spr->mobj->x, spr->mobj->y) << FRACBITS;
fixed_t xscale = FixedDiv((vid.width / 2) << FRACBITS, tr);
// Less change in contrast at further distances, to counteract DOOM diminished light
fixed_t n = FixedDiv(FixedMul(xscale, LIGHTRESOLUTIONFIX), ((MAXLIGHTSCALE-1) << LIGHTSCALESHIFT));
- extralight = FixedMul(extralight, min(n, FRACUNIT));
+ extralight = FixedMul(extralight, std::min(n, FRACUNIT));
// Contrast is stronger for normal sprites, stronger than wall lighting is at the same distance
*lightlevel += FixedFloor((extralight * 2) + (FRACUNIT / 2)) / FRACUNIT;
@@ -407,9 +416,9 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col
float tint_alpha, fade_alpha;
float red, green, blue;
- red = (float)poly_color.s.red;
+ red = (float)poly_color.s.red;
green = (float)poly_color.s.green;
- blue = (float)poly_color.s.blue;
+ blue = (float)poly_color.s.blue;
// 48 is just an arbritrary value that looked relatively okay.
tint_alpha = (float)(sqrt(tint_color.s.alpha) * 48) / 255.0f;
@@ -421,20 +430,20 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col
fade_alpha = (float)(sqrt(255-light_level) * 12) / 255.0f;
// Clamp the alpha values
- tint_alpha = min(max(tint_alpha, 0.0f), 1.0f);
- fade_alpha = min(max(fade_alpha, 0.0f), 1.0f);
+ tint_alpha = CLAMP(tint_alpha, 0.0f, 1.0f);
+ fade_alpha = CLAMP(fade_alpha, 0.0f, 1.0f);
- red = (tint_color.s.red * tint_alpha) + (red * (1.0f - tint_alpha));
+ red = (tint_color.s.red * tint_alpha) + (red * (1.0f - tint_alpha));
green = (tint_color.s.green * tint_alpha) + (green * (1.0f - tint_alpha));
- blue = (tint_color.s.blue * tint_alpha) + (blue * (1.0f - tint_alpha));
+ blue = (tint_color.s.blue * tint_alpha) + (blue * (1.0f - tint_alpha));
- red = (fade_color.s.red * fade_alpha) + (red * (1.0f - fade_alpha));
+ red = (fade_color.s.red * fade_alpha) + (red * (1.0f - fade_alpha));
green = (fade_color.s.green * fade_alpha) + (green * (1.0f - fade_alpha));
- blue = (fade_color.s.blue * fade_alpha) + (blue * (1.0f - fade_alpha));
+ blue = (fade_color.s.blue * fade_alpha) + (blue * (1.0f - fade_alpha));
- poly_color.s.red = (UINT8)red;
+ poly_color.s.red = (UINT8)red;
poly_color.s.green = (UINT8)green;
- poly_color.s.blue = (UINT8)blue;
+ poly_color.s.blue = (UINT8)blue;
}
// Clamp the light level, since it can sometimes go out of the 0-255 range from animations
@@ -541,7 +550,7 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool
size_t len;
float tempxsow, tempytow;
- float scrollx = 0.0f, scrolly = 0.0f;
+ float scrollx = 0.0f, scrolly = 0.0f, anglef = 0.0f;
angle_t angle = 0;
static FOutVector *planeVerts = NULL;
@@ -661,14 +670,11 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool
if (angle) // Only needs to be done if there's an altered angle
{
- angle = InvAngle(angle)>>ANGLETOFINESHIFT;
-
- // This needs to be done so everything aligns after rotation
- // It would be done so that rotation is done, THEN the translation, but I couldn't get it to rotate AND scroll like software does
- tempxsow = FloatToFixed(flatxref);
- tempytow = FloatToFixed(flatyref);
- flatxref = (FixedToFloat(FixedMul(tempxsow, FINECOSINE(angle)) - FixedMul(tempytow, FINESINE(angle))));
- flatyref = (FixedToFloat(FixedMul(tempxsow, FINESINE(angle)) + FixedMul(tempytow, FINECOSINE(angle))));
+ tempxsow = flatxref;
+ tempytow = flatyref;
+ anglef = ANG2RAD(InvAngle(angle));
+ flatxref = (tempxsow * cos(anglef)) - (tempytow * sin(anglef));
+ flatyref = (tempxsow * sin(anglef)) + (tempytow * cos(anglef));
}
#define SETUP3DVERT(vert, vx, vy) {\
@@ -679,10 +685,10 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool
/* Need to rotate before translate */\
if (angle) /* Only needs to be done if there's an altered angle */\
{\
- tempxsow = FloatToFixed(vert->s);\
- tempytow = FloatToFixed(vert->t);\
- vert->s = (FixedToFloat(FixedMul(tempxsow, FINECOSINE(angle)) - FixedMul(tempytow, FINESINE(angle))));\
- vert->t = (FixedToFloat(FixedMul(tempxsow, FINESINE(angle)) + FixedMul(tempytow, FINECOSINE(angle))));\
+ tempxsow = vert->s;\
+ tempytow = vert->t;\
+ vert->s = (tempxsow * cos(anglef)) - (tempytow * sin(anglef));\
+ vert->t = (tempxsow * sin(anglef)) + (tempytow * cos(anglef));\
}\
\
vert->x = (vx);\
@@ -733,10 +739,10 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool
UINT8 numplanes, j;
vertex_t v; // For determining the closest distance from the line to the camera, to split render planes for minimum distortion;
- const float renderdist = 27000.0f; // How far out to properly render the plane
- const float farrenderdist = 32768.0f; // From here, raise plane to horizon level to fill in the line with some texture distortion
+ static constexpr float renderdist = 27000.0f; // How far out to properly render the plane
+ static constexpr float farrenderdist = 32768.0f; // From here, raise plane to horizon level to fill in the line with some texture distortion
- seg_t *line = &segs[subsector->firstline];
+ const seg_t *line = &segs[subsector->firstline];
for (i = 0; i < subsector->numlines; i++, line++)
{
@@ -773,6 +779,7 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool
// Based on the seg length and the distance from the line, split horizon into multiple poly sets to reduce distortion
dist = sqrtf((xd*xd) + (yd*yd)) / dist / 16.0f;
+
if (dist > 100.0f)
numplanes = 100;
else
@@ -1020,7 +1027,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
// Lactozilla: If both heights of a side lay on the same position, then this wall is a triangle.
// To avoid division by zero, which would result in a NaN, we check if the vertical difference
// between the two vertices is not zero.
- if (fpclassify(diff) == FP_ZERO)
+ if (std::fpclassify(diff) == FP_ZERO)
pegmul = 0.0;
else
pegmul = (pegb - pegt) / diff;
@@ -1032,7 +1039,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
endpegt = wallVerts[2].t;
endpegb = wallVerts[1].t;
- if (fpclassify(diff) == FP_ZERO)
+ if (std::fpclassify(diff) == FP_ZERO)
endpegmul = 0.0;
else
endpegmul = (endpegb - endpegt) / diff;
@@ -1077,12 +1084,12 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
else
solid = false;
- height = FixedToFloat(P_GetLightZAt(&list[i], v1x, v1y));
+ height = FixedToFloat(P_GetLightZAt(&list[i], v1x, v1y));
endheight = FixedToFloat(P_GetLightZAt(&list[i], v2x, v2y));
if (solid)
{
- bheight = FixedToFloat(P_GetFFloorBottomZAt(list[i].caster, v1x, v1y));
+ bheight = FixedToFloat(P_GetFFloorBottomZAt(list[i].caster, v1x, v1y));
endbheight = FixedToFloat(P_GetFFloorBottomZAt(list[i].caster, v2x, v2y));
}
@@ -1090,6 +1097,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
{
if (solid && top > bheight)
top = bheight;
+
if (solid && endtop > endbheight)
endtop = endbheight;
}
@@ -1105,15 +1113,12 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
endbheight = endrealbot;
}
- if (endbheight >= endtop)
- continue;
-
- if (bheight >= top)
+ if ((endbheight >= endtop) || (bheight >= top))
continue;
// Found a break
// The heights are clamped to ensure the polygon doesn't cross itself.
- bot = CLAMP(bheight, realbot, top);
+ bot = CLAMP(bheight, realbot, top);
endbot = CLAMP(endbheight, endrealbot, endtop);
Surf->PolyColor.s.alpha = alpha;
@@ -1142,6 +1147,7 @@ static void HWR_SplitWall(sector_t *sector, FOutVector *wallVerts, INT32 texnum,
bot = realbot;
endbot = endrealbot;
+
if ((endtop <= endrealbot) && (top <= realbot))
return;
@@ -1188,14 +1194,14 @@ static void HWR_SkyWallList_Add(FOutVector *wallVerts)
if (!skyWallVertexArray)
{
// array has not been allocated yet. allocate it now
- skyWallVertexArray = Z_Malloc(sizeof(FOutVector) * 4 * skyWallVertexArrayAllocSize, PU_STATIC, NULL);
+ skyWallVertexArray = static_cast(Z_Malloc(sizeof(FOutVector) * 4 * skyWallVertexArrayAllocSize, PU_STATIC, NULL));
}
if (skyWallVertexArraySize == skyWallVertexArrayAllocSize)
{
// allocated array got full, allocate more space
skyWallVertexArrayAllocSize *= 2;
- skyWallVertexArray = Z_Realloc(skyWallVertexArray, sizeof(FOutVector) * 4 * skyWallVertexArrayAllocSize, PU_STATIC, NULL);
+ skyWallVertexArray = static_cast(Z_Realloc(skyWallVertexArray, sizeof(FOutVector) * 4 * skyWallVertexArrayAllocSize, PU_STATIC, NULL));
}
memcpy(skyWallVertexArray + skyWallVertexArraySize * 4, wallVerts, sizeof(FOutVector) * 4);
@@ -1382,7 +1388,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
// x offset the texture
fixed_t texturehpeg = gl_sidedef->textureoffset + gl_curline->offset;
- float cliplow = (float)texturehpeg;
+ float cliplow = (float)texturehpeg;
float cliphigh = (float)(texturehpeg + (gl_curline->flength*FRACUNIT));
FUINT lightnum = gl_frontsector->lightlevel;
@@ -1413,6 +1419,13 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
// Sky Ceilings
wallVerts[3].y = wallVerts[2].y = FixedToFloat(INT32_MAX);
+ auto draw_sky_walls = [&](int vert1, int vert2, fixed_t world, fixed_t worldslope)
+ {
+ wallVerts[vert1].y = FixedToFloat(world);
+ wallVerts[vert2].y = FixedToFloat(worldslope);
+ HWR_DrawSkyWall(wallVerts, &Surf);
+ };
+
if (gl_frontsector->ceilingpic == skyflatnum)
{
if (gl_backsector->ceilingpic == skyflatnum)
@@ -1423,25 +1436,19 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
&& (worldhigh != worldtop || worldhighslope != worldtopslope))
// Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race
{
- wallVerts[0].y = FixedToFloat(worldhigh);
- wallVerts[1].y = FixedToFloat(worldhighslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(0, 1, worldhigh, worldhighslope);
}
}
else
{
// Only the frontsector is sky, just draw a skywall from the front ceiling
- wallVerts[0].y = FixedToFloat(worldtop);
- wallVerts[1].y = FixedToFloat(worldtopslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(0, 1, worldtop, worldtopslope);
}
}
else if (gl_backsector->ceilingpic == skyflatnum)
{
// Only the backsector is sky, just draw a skywall from the front ceiling
- wallVerts[0].y = FixedToFloat(worldtop);
- wallVerts[1].y = FixedToFloat(worldtopslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(0, 1, worldtop, worldtopslope);
}
// Sky Floors
@@ -1459,25 +1466,19 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
// Removing the second line above will render more rarely visible skywalls. Example: Cave garden ceiling in Dark race
&& !(gl_sidedef->bottomtexture))
{
- wallVerts[3].y = FixedToFloat(worldlow);
- wallVerts[2].y = FixedToFloat(worldlowslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(3, 2, worldlow, worldlowslope);
}
}
else
{
// Only the backsector has sky, just draw a skywall from the back floor
- wallVerts[3].y = FixedToFloat(worldbottom);
- wallVerts[2].y = FixedToFloat(worldbottomslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(3, 2, worldbottom, worldbottomslope);
}
}
else if ((gl_backsector->floorpic == skyflatnum) && !(gl_sidedef->bottomtexture))
{
// Only the backsector has sky, just draw a skywall from the back floor if there's no bottomtexture
- wallVerts[3].y = FixedToFloat(worldlow);
- wallVerts[2].y = FixedToFloat(worldlowslope);
- HWR_DrawSkyWall(wallVerts, &Surf);
+ draw_sky_walls(3, 2, worldlow, worldlowslope);
}
}
@@ -1670,10 +1671,10 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
}
else
{
- popentop = min(worldtop, worldhigh);
- popenbottom = max(worldbottom, worldlow);
- popentopslope = min(worldtopslope, worldhighslope);
- popenbottomslope = max(worldbottomslope, worldlowslope);
+ popentop = std::min(worldtop, worldhigh);
+ popenbottom = std::max(worldbottom, worldlow);
+ popentopslope = std::min(worldtopslope, worldhighslope);
+ popenbottomslope = std::max(worldbottomslope, worldlowslope);
}
// Find the wall's coordinates
@@ -1683,12 +1684,12 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
{
if (!!(gl_linedef->flags & ML_DONTPEGBOTTOM) ^ !!(gl_linedef->flags & ML_EFFECT3)) // Peg it to the floor
{
- polybottom = max(front->floorheight, back->floorheight) + gl_sidedef->rowoffset;
- polytop = polybottom + midtexheight;
+ polybottom = std::max(front->floorheight, back->floorheight) + gl_sidedef->rowoffset;
+ polytop = polybottom + midtexheight;
}
else // Peg it to the ceiling
{
- polytop = min(front->ceilingheight, back->ceilingheight) + gl_sidedef->rowoffset;
+ polytop = std::min(front->ceilingheight, back->ceilingheight) + gl_sidedef->rowoffset;
polybottom = polytop - midtexheight;
}
@@ -1705,9 +1706,9 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
}
else // Skew it according to the ceiling's slope
{
- polytop = popentop + gl_sidedef->rowoffset;
- polybottom = polytop - midtexheight;
- polytopslope = popentopslope + gl_sidedef->rowoffset;
+ polytop = popentop + gl_sidedef->rowoffset;
+ polybottom = polytop - midtexheight;
+ polytopslope = popentopslope + gl_sidedef->rowoffset;
polybottomslope = polytopslope - midtexheight;
}
@@ -1716,24 +1717,24 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
// you must use the linedef's backsector to be correct
if (gl_curline->polyseg)
{
- lowcut = polybottom;
- highcut = polytop;
- lowcutslope = polybottomslope;
+ lowcut = polybottom;
+ highcut = polytop;
+ lowcutslope = polybottomslope;
highcutslope = polytopslope;
}
else
{
// The cut-off values of a linedef can always be constant, since every line has an absoulute front and or back sector
- lowcut = popenbottom;
- highcut = popentop;
- lowcutslope = popenbottomslope;
+ lowcut = popenbottom;
+ highcut = popentop;
+ lowcutslope = popenbottomslope;
highcutslope = popentopslope;
}
- h = min(highcut, polytop);
- l = max(polybottom, lowcut);
- hS = min(highcutslope, polytopslope);
- lS = max(polybottomslope, lowcutslope);
+ h = std::min(highcut, polytop);
+ l = std::max(polybottom, lowcut);
+ hS = std::min(highcutslope, polytopslope);
+ lS = std::max(polybottomslope, lowcutslope);
// PEGGING
fixed_t texturevpegslope;
@@ -1889,10 +1890,10 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
INT32 texnum;
line_t * newline = NULL; // Multi-Property FOF
- lowcut = max(worldbottom, worldlow);
- highcut = min(worldtop, worldhigh);
- lowcutslope = max(worldbottomslope, worldlowslope);
- highcutslope = min(worldtopslope, worldhighslope);
+ lowcut = std::max(worldbottom, worldlow);
+ highcut = std::min(worldtop, worldhigh);
+ lowcutslope = std::max(worldbottomslope, worldlowslope);
+ highcutslope = std::min(worldtopslope, worldhighslope);
if (gl_backsector->ffloors)
{
@@ -1913,7 +1914,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
if (rover->master->flags & ML_TFERLINE)
{
- size_t linenum = min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount);
+ size_t linenum = std::min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount);
newline = rover->master->frontsector->lines[0] + linenum;
texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture);
}
@@ -2027,7 +2028,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
if ((roverflags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend)
{
- blendmode = rover->blend ? HWR_GetBlendModeFlag(rover->blend) : PF_Translucent;
+ blendmode = rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent);
Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255);
}
@@ -2063,7 +2064,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
if (rover->master->flags & ML_TFERLINE)
{
- size_t linenum = min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount);
+ size_t linenum = std::min((size_t)(gl_curline->linedef-gl_backsector->lines[0]), rover->master->frontsector->linecount);
newline = rover->master->frontsector->lines[0] + linenum;
texnum = R_GetTextureNum(sides[newline->sidenum[0]].midtexture);
}
@@ -2144,7 +2145,7 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom
if ((roverflags & FF_TRANSLUCENT && rover->alpha < 256) || rover->blend)
{
- blendmode = rover->blend ? HWR_GetBlendModeFlag(rover->blend) : PF_Translucent;
+ blendmode = rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent);
Surf.PolyColor.s.alpha = CLAMP(rover->alpha, 0, 255);
}
@@ -2178,6 +2179,7 @@ static inline boolean HWR_UsePortals(void)
boolean checkforemptylines = true;
// Don't modify anything here, just check
// Kalaron: Modified for sloped linedefs
+
static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector)
{
fixed_t frontf1,frontf2, frontc1, frontc2; // front floor/ceiling ends
@@ -2311,17 +2313,107 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector)
// HWR_AddLine
// Clips the given segment and adds any visible pieces to the line list.
+namespace
+{
+ enum class AddLineType
+ {
+ kPortal,
+ kNormal,
+ };
+
+template
+static inline void DoAddLine(seg_t* line, angle_t angle1, angle_t angle2)
+{
+ // SoM: Backsector needs to be run through R_FakeFlat
+ static sector_t tempsec;
+
+ auto do_addline = [&](bool dontdraw) {
+ if (!line->backsector)
+ {
+ gld_clipper_SafeAddClipRange(angle2, angle1);
+ }
+ else
+ {
+ gl_backsector = R_FakeFlat(gl_backsector, &tempsec, NULL, NULL, true);
+
+ if (CheckClip(gl_frontsector, gl_backsector))
+ {
+ gld_clipper_SafeAddClipRange(angle2, angle1);
+ checkforemptylines = false;
+ }
+
+ // Reject empty lines used for triggers and special events.
+ // Identical floor and ceiling on both sides,
+ // identical light levels on both sides,
+ // and no middle texture.
+ if (checkforemptylines && R_IsEmptyLine(line, gl_frontsector, gl_backsector))
+ return;
+ }
+
+ if constexpr (Type == AddLineType::kPortal)
+ {
+ if (gl_portal_state != GLPORTAL_SEARCH && !dontdraw)// no need to do this during the portal check
+ HWR_ProcessSeg(); // Doesn't need arguments because they're defined globally :D
+ }
+ else if constexpr (Type == AddLineType::kNormal)
+ {
+ HWR_ProcessSeg(); // Doesn't need arguments because they're defined globally :D
+ }
+ };
+
+ if constexpr (Type == AddLineType::kPortal)
+ {
+ boolean dont_draw = false;
+
+ // do extra checks on the seg when rendering portals:
+ // don't render segs that are behind the portal destination line
+ if (portalclipline &&
+ !HWR_PortalCheckPointSide(line->v1->x, line->v1->y) &&
+ !HWR_PortalCheckPointSide(line->v2->x, line->v2->y))
+ {
+ return;
+ }
+
+ if (gl_portal_state == GLPORTAL_STENCIL || gl_portal_state == GLPORTAL_DEPTH)
+ goto doaddline;
+
+ if (line->linedef->special == PORTALSPECIAL)
+ {
+ if (line->side == 0)
+ {
+ // Find the other side!
+ INT32 line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, -1);
+
+ if (line->linedef == &lines[line2])
+ line2 = P_FindSpecialLineFromTag(PORTALSPECIAL, line->linedef->tag, line2);
+
+ if (line2 >= 0) // found it!
+ {
+ if (gl_portal_state == GLPORTAL_SEARCH)
+ HWR_Portal_Add2Lines(line->linedef-lines, line2, line);
+ else if (gl_portal_state == GLPORTAL_INSIDE)
+ dont_draw = true;
+ }
+ }
+ else
+ return;// dont do anything with the other side i guess?
+ }
+
+ doaddline:
+ do_addline(dont_draw); // no need to do this during the portal check
+ }
+ else if constexpr (Type == AddLineType::kNormal)
+ {
+ do_addline(false);
+ }
+}
+
static void HWR_AddLine(seg_t *line)
{
angle_t angle1, angle2;
- // SoM: Backsector needs to be run through R_FakeFlat
- static sector_t tempsec;
-
fixed_t v1x, v1y, v2x, v2y; // the seg's vertexes as fixed_t
- boolean dont_draw = false;
-
if (line->polyseg && !(line->polyseg->flags & POF_RENDERSIDES))
return;
@@ -2365,73 +2457,12 @@ static void HWR_AddLine(seg_t *line)
gl_backsector = line->backsector;
- if (LIKELY(!HWR_UsePortals()))
- {
-doaddline:
- if (!line->backsector)
- {
- gld_clipper_SafeAddClipRange(angle2, angle1);
- }
- else
- {
- gl_backsector = R_FakeFlat(gl_backsector, &tempsec, NULL, NULL, true);
-
- if (CheckClip(gl_frontsector, gl_backsector))
- {
- gld_clipper_SafeAddClipRange(angle2, angle1);
- checkforemptylines = false;
- }
-
- // Reject empty lines used for triggers and special events.
- // Identical floor and ceiling on both sides,
- // identical light levels on both sides,
- // and no middle texture.
- if (checkforemptylines && R_IsEmptyLine(line, gl_frontsector, gl_backsector))
- return;
- }
-
- if (LIKELY(gl_portal_state != GLPORTAL_SEARCH && !dont_draw))// no need to do this during the portal check
- HWR_ProcessSeg(); // Doesn't need arguments because they're defined globally :D
-
- return;
- }
-
- // do extra checks on the seg when rendering portals:
- // don't render segs that are behind the portal destination line
- if (portalclipline &&
- !HWR_PortalCheckPointSide(line->v1->x, line->v1->y) &&
- !HWR_PortalCheckPointSide(line->v2->x, line->v2->y))
- {
- return;
- }
-
- if (gl_portal_state == GLPORTAL_STENCIL || gl_portal_state == GLPORTAL_DEPTH)
- goto doaddline;
-
- if (line->linedef->special == 40)
- {
- if (line->side == 0)
- {
- // Find the other side!
- INT32 line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, -1);
-
- if (line->linedef == &lines[line2])
- line2 = P_FindSpecialLineFromTag(40, line->linedef->tag, line2);
-
- if (line2 >= 0) // found it!
- {
- if (gl_portal_state == GLPORTAL_SEARCH)
- HWR_Portal_Add2Lines(line->linedef-lines, line2, line);
- else if (gl_portal_state == GLPORTAL_INSIDE)
- dont_draw = true;
- }
- }
- else
- return;// dont do anything with the other side i guess?
- }
-
- goto doaddline;
+ if (UNLIKELY(HWR_UsePortals()))
+ DoAddLine(line, angle1, angle2);
+ else
+ DoAddLine(line, angle1, angle2);
}
+};
// HWR_CheckBBox
// Checks BSP node/subtree bounding box.
@@ -2495,18 +2526,18 @@ static boolean HWR_CheckBBox(const fixed_t *bspcoord)
if (viewx < bspcoord[BOXLEFT]) // 1,4,6
{
if (viewy > bspcoord[BOXTOP]) // 1
- mindist = R_PointToDist(bspcoord[BOXLEFT], bspcoord[BOXTOP]);
+ mindist = R_QuickCamDist(bspcoord[BOXLEFT], bspcoord[BOXTOP]) << FRACBITS;
else if (viewy < bspcoord[BOXBOTTOM]) // 6
- mindist = R_PointToDist(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]);
+ mindist = R_QuickCamDist(bspcoord[BOXLEFT], bspcoord[BOXBOTTOM]) << FRACBITS;
else // 4
mindist = bspcoord[BOXLEFT] - viewx;
}
else if (viewx > bspcoord[BOXRIGHT]) // 3,5,8
{
if (viewy > bspcoord[BOXTOP]) // 3
- mindist = R_PointToDist(bspcoord[BOXRIGHT], bspcoord[BOXTOP]);
+ mindist = R_QuickCamDist(bspcoord[BOXRIGHT], bspcoord[BOXTOP]) << FRACBITS;
else if (viewy < bspcoord[BOXBOTTOM]) // 8
- mindist = R_PointToDist(bspcoord[BOXRIGHT], bspcoord[BOXBOTTOM]);
+ mindist = R_QuickCamDist(bspcoord[BOXRIGHT], bspcoord[BOXBOTTOM]) << FRACBITS;
else // 5
mindist = viewx - bspcoord[BOXRIGHT];
}
@@ -2913,7 +2944,7 @@ static void HWR_Subsector(size_t num)
if (sub->validcount == validcount)
continue;
- sector_t *controlSec = §ors[rover->secnum];
+ const sector_t *controlSec = §ors[rover->secnum];
if (!controlSec->moved)
continue;
@@ -3034,7 +3065,7 @@ static void HWR_Subsector(size_t num)
false,
*rover->bottomheight,
*gl_frontsector->lightlist[light].lightlevel,
- CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : PF_Translucent),
+ CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent)),
false, gl_frontsector->lightlist[light].extra_colormap);
}
else
@@ -3080,7 +3111,7 @@ static void HWR_Subsector(size_t num)
true,
*rover->topheight,
*gl_frontsector->lightlist[light].lightlevel,
- CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : PF_Translucent),
+ CLAMP(rover->alpha, 0 ,255), rover->master->frontsector, HWR_RippleBlend(gl_frontsector, rover, false) | (rover->blend ? HWR_GetBlendModeFlag(rover->blend) : static_cast(PF_Translucent)),
false, gl_frontsector->lightlist[light].extra_colormap);
}
else
@@ -3149,7 +3180,10 @@ doaddline:
while (count--)
{
if (LIKELY(!line->polyseg)) // ignore segs that belong to polyobjects
+ {
HWR_AddLine(line);
+ }
+
line++;
}
}
@@ -3172,10 +3206,19 @@ doaddline:
// Just call with BSP root.
//
+namespace
+{
+ enum class BspType
+ {
+ kPortal,
+ kNormal,
+ };
+
+template
static void HWR_RenderBSPNode(INT32 bspnum)
{
- register const node_t *bsp;
- register INT32 side;
+ const node_t *bsp;
+ INT32 side;
ps_numbspcalls.value.i++;
while (!(bspnum & NF_SUBSECTOR)) // Keep going until found a subsector
@@ -3185,61 +3228,47 @@ static void HWR_RenderBSPNode(INT32 bspnum)
// Decide which side the view point is on.
side = R_PointOnSideFast(viewx, viewy, bsp);
- // Recursively divide front space (toward the viewer).
- HWR_RenderBSPNode(bsp->children[side]);
+ if constexpr (Type == BspType::kPortal)
+ {
+ // Recursively divide front space (toward the viewer).
+ if (HWR_PortalCheckBBox(bsp->bbox[side]))
+ HWR_RenderBSPNode(bsp->children[side]);
- // Possibly divide back space (away from the viewer).
- if (!(HWR_CheckBBox(bsp->bbox[side^1])))
- return;
+ // Possibly divide back space (away from the viewer).
+ if (!(HWR_CheckBBox(bsp->bbox[side^1]) && HWR_PortalCheckBBox(bsp->bbox[side^1])))
+ return;
+ }
+ else if constexpr (Type == BspType::kNormal)
+ {
+ // Recursively divide front space (toward the viewer).
+ HWR_RenderBSPNode(bsp->children[side]);
+
+ // Possibly divide back space (away from the viewer).
+ if (!(HWR_CheckBBox(bsp->bbox[side^1])))
+ return;
+ }
bspnum = bsp->children[side^1];
}
+ if constexpr (Type == BspType::kPortal)
+ {
+ // PORTAL CULLING
+ if (portalcullsector)
+ {
+ // skip all subsectors encountered before the portal
+ // destination's front sector
+ if (portalcullsector != subsectors[bspnum & ~NF_SUBSECTOR].sector)
+ return;
+ else
+ portalcullsector = NULL;
+ }
+ }
+
// e6y: support for extended nodes
HWR_Subsector(bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR);
}
-
-//
-// Same thing but with extra portal checks
-//
-static void HWR_RenderPortalBSPNode(INT32 bspnum)
-{
- register const node_t *bsp;
- register INT32 side;
- ps_numbspcalls.value.i++;
-
- while (!(bspnum & NF_SUBSECTOR)) // Keep going until found a subsector
- {
- bsp = &nodes[bspnum];
-
- // Decide which side the view point is on.
- side = R_PointOnSideFast(viewx, viewy, bsp);
-
- // Recursively divide front space (toward the viewer).
- if (HWR_PortalCheckBBox(bsp->bbox[side]))
- HWR_RenderPortalBSPNode(bsp->children[side]);
-
- // Possibly divide back space (away from the viewer).
- if (!(HWR_CheckBBox(bsp->bbox[side^1]) && HWR_PortalCheckBBox(bsp->bbox[side^1])))
- return;
-
- bspnum = bsp->children[side^1];
- }
-
- // PORTAL CULLING
- if (portalcullsector)
- {
- // skip all subsectors encountered before the portal
- // destination's front sector
- if (portalcullsector != subsectors[bspnum & ~NF_SUBSECTOR].sector)
- return;
- else
- portalcullsector = NULL;
- }
-
- // e6y: support for extended nodes
- HWR_Subsector(bspnum == -1 ? 0 : bspnum & ~NF_SUBSECTOR);
-}
+};
// ==========================================================================
// gl_things.c
@@ -3497,15 +3526,11 @@ static void HWR_RotateSpritePolyToAim(gl_vissprite_t *spr, FOutVector *wallVerts
}
// uncapped/interpolation
- interpmobjstate_t interp = {0};
+ interpmobjstate_t interp = {};
float basey, lowy;
- INT32 dist = -1;
-
- if (cv_maxinterpdist.value)
- dist = R_QuickCamDist(spr->mobj->x, spr->mobj->y);
// do interpolation
- if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value))
+ if (R_UsingFrameInterpolation() && !paused && R_CheckInterpDist(spr->mobj))
{
if (precip)
{
@@ -3564,8 +3589,8 @@ static inline void HWR_ApplyDispoffset(gl_vissprite_t *spr, FOutVector *wallVert
{
HWR_RotateSpritePolyToAim(spr, wallVerts, false, papersprite);
- float sprdist = sqrtf((spr->x1 - gl_viewx)*(spr->x1 - gl_viewx) + (spr->z1 - gl_viewy)*(spr->z1 - gl_viewy) + (spr->gzt - gl_viewz)*(spr->gzt - gl_viewz));
- float distfact = ((2.0f*spr->dispoffset) + 20.0f) / sprdist;
+ const float sprdist = sqrtf((spr->x1 - gl_viewx)*(spr->x1 - gl_viewx) + (spr->z1 - gl_viewy)*(spr->z1 - gl_viewy) + (spr->gzt - gl_viewz)*(spr->gzt - gl_viewz));
+ const float distfact = ((2.0f*spr->dispoffset) + 20.0f) / sprdist;
for (size_t i = 0; i < 4; i++)
{
@@ -3612,10 +3637,10 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite)
hwrpatch = ((GLPatch_t *)gpatch->hardware);
// Draw shadow BEFORE sprite
- if (cv_shadow.value // Shadows enabled
+ if (UNLIKELY(cv_shadow.value // Shadows enabled
&& (spr->mobj->flags & (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) != (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY) // Ceiling scenery have no shadow.
&& !(spr->mobj->flags2 & MF2_DEBRIS) // Debris have no corona or shadow.
- && (spr->mobj->z >= spr->mobj->floorz)) // Without this, your shadow shows on the floor, even after you die and fall through the ground.
+ && (spr->mobj->z >= spr->mobj->floorz))) // Without this, your shadow shows on the floor, even after you die and fall through the ground.
{
////////////////////
// SHADOW SPRITE! //
@@ -3726,12 +3751,14 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite)
for (i = 1; i < sector->numlights; i++)
{
- fixed_t h = P_GetLightZAt(§or->lightlist[i], spr->mobj->x, spr->mobj->y);
+ const fixed_t h = P_GetLightZAt(§or->lightlist[i], spr->mobj->x, spr->mobj->y);
+
if (!(h <= temp))
continue;
if (!lightset)
- lightlevel = min(*list[i-1].lightlevel, 255);
+ lightlevel = static_cast(CLAMP(*list[i-1].lightlevel, 0, 255));
+
colormap = list[i-1].extra_colormap;
break;
}
@@ -3749,7 +3776,7 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite)
{
if (!lightset)
{
- lightlevel = min(*list[i].lightlevel, 255);
+ lightlevel = static_cast(CLAMP(*list[i].lightlevel, 0, 255));
HWR_ObjectLightLevelPost(spr, sector, &lightlevel, false);
}
@@ -3758,9 +3785,9 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite)
if (i + 1 < sector->numlights)
{
- temp = P_GetLightZAt(&list[i+1], v1x, v1y);
- bheight = FixedToFloat(temp);
- temp = P_GetLightZAt(&list[i+1], v2x, v2y);
+ temp = P_GetLightZAt(&list[i+1], v1x, v1y);
+ bheight = FixedToFloat(temp);
+ temp = P_GetLightZAt(&list[i+1], v2x, v2y);
endbheight = FixedToFloat(temp);
}
else
@@ -3769,15 +3796,12 @@ static void HWR_SplitSprite(gl_vissprite_t *spr, const boolean papersprite)
endbheight = endrealbot;
}
- if (endbheight >= endtop)
- continue;
-
- if (bheight >= top)
+ if ((endbheight >= endtop) || (bheight >= top))
continue;
// Found a break
// The heights are clamped to ensure the polygon doesn't cross itself.
- bot = CLAMP(bheight, realbot, top);
+ bot = CLAMP(bheight, realbot, top);
endbot = CLAMP(endbheight, endrealbot, endtop);
wallVerts[3].t = towtop + ((realtop - top) * towmult);
@@ -3866,7 +3890,7 @@ static void HWR_DrawSprite(gl_vissprite_t *spr)
return;
const boolean papersprite = (spr->mobj->frame & FF_PAPERSPRITE);
- sector_t *sector = spr->mobj->subsector->sector;
+ const sector_t *sector = spr->mobj->subsector->sector;
if (sector->numlights)
{
@@ -3931,10 +3955,10 @@ static void HWR_DrawSprite(gl_vissprite_t *spr)
}
// Draw shadow BEFORE sprite
- if (cv_shadow.value // Shadows enabled
+ if (UNLIKELY(cv_shadow.value // Shadows enabled
&& (spr->mobj->flags & (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY)) != (MF_SCENERY|MF_SPAWNCEILING|MF_NOGRAVITY) // Ceiling scenery have no shadow.
&& !(spr->mobj->flags2 & MF2_DEBRIS) // Debris have no corona or shadow.
- && (spr->mobj->z >= spr->mobj->floorz)) // Without this, your shadow shows on the floor, even after you die and fall through the ground.
+ && (spr->mobj->z >= spr->mobj->floorz))) // Without this, your shadow shows on the floor, even after you die and fall through the ground.
{
////////////////////
// SHADOW SPRITE! //
@@ -3951,13 +3975,13 @@ static void HWR_DrawSprite(gl_vissprite_t *spr)
// colormap test
INT32 lightlevel = 255;
- boolean lightset = HWR_OverrideObjectLightLevel(spr->mobj, &lightlevel);
+ const boolean lightset = HWR_OverrideObjectLightLevel(spr->mobj, &lightlevel);
extracolormap_t *colormap = sector->extra_colormap;
const boolean fullbright = R_ThingIsFullBright(spr->mobj);
if (!lightset)
{
- lightlevel = min(sector->lightlevel, 255);
+ lightlevel = static_cast(CLAMP(sector->lightlevel, 0, 255));
HWR_ObjectLightLevelPost(spr, sector, &lightlevel, false);
}
@@ -4063,7 +4087,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr)
light = R_GetPlaneLight(sector, spr->mobj->z + spr->mobj->height, false); // Always use the light at the top instead of whatever I was doing before
if (!(spr->mobj->frame & FF_FULLBRIGHT))
- lightlevel = min(*sector->lightlist[light].lightlevel, 255);
+ lightlevel = static_cast(CLAMP(*sector->lightlist[light].lightlevel, 0, 255));
if (sector->lightlist[light].extra_colormap)
colormap = sector->lightlist[light].extra_colormap;
@@ -4071,7 +4095,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr)
else
{
if (!(spr->mobj->frame & FF_FULLBRIGHT))
- lightlevel = min(sector->lightlevel, 255);
+ lightlevel = static_cast(CLAMP(sector->lightlevel, 0, 255));
if (sector->extra_colormap)
colormap = sector->extra_colormap;
@@ -4122,8 +4146,8 @@ static int CompareVisSprites(const void *p1, const void *p2)
// "boolean to int"
// check for precip first, because then sprX->mobj is actually a precipmobj_t and does not have flags2 or tracer
- int transparency1 = (!spr1->precip && (spr1->mobj->flags2 & MF2_SHADOW)) || (spr1->mobj->frame & FF_TRANSMASK);
- int transparency2 = (!spr2->precip && (spr2->mobj->flags2 & MF2_SHADOW)) || (spr2->mobj->frame & FF_TRANSMASK);
+ const int transparency1 = (!spr1->precip && (spr1->mobj->flags2 & MF2_SHADOW)) || (spr1->mobj->frame & FF_TRANSMASK);
+ const int transparency2 = (!spr2->precip && (spr2->mobj->flags2 & MF2_SHADOW)) || (spr2->mobj->frame & FF_TRANSMASK);
idiff = transparency1 - transparency2;
if (idiff != 0) return idiff;
@@ -4219,7 +4243,7 @@ static void *HWR_CreateDrawNode(gl_drawnode_type_t type)
if (!drawnodes)
{
alloceddrawnodes = DRAWNODES_INIT_SIZE;
- drawnodes = Z_Malloc(alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes);
+ drawnodes = static_cast(Z_Malloc(alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes));
}
else if (numdrawnodes >= alloceddrawnodes)
{
@@ -4227,7 +4251,6 @@ static void *HWR_CreateDrawNode(gl_drawnode_type_t type)
Z_Realloc(drawnodes, alloceddrawnodes * sizeof(gl_drawnode_t), PU_LEVEL, &drawnodes);
}
-
drawnode = &drawnodes[numdrawnodes++];
drawnode->type = type;
@@ -4246,7 +4269,7 @@ static void *HWR_CreateDrawNode(gl_drawnode_type_t type)
static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, INT32 texnum, boolean noencore, FBITFIELD blend, boolean fogwall, INT32 lightlevel, extracolormap_t *wallcolormap)
{
- wallinfo_t *wallinfo = HWR_CreateDrawNode(DRAWNODE_WALL);
+ wallinfo_t *wallinfo = static_cast(HWR_CreateDrawNode(DRAWNODE_WALL));
M_Memcpy(wallinfo->wallVerts, wallVerts, sizeof (wallinfo->wallVerts));
M_Memcpy(&wallinfo->Surf, pSurf, sizeof (FSurfaceInfo));
@@ -4260,7 +4283,7 @@ static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, I
static void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, boolean fogplane, extracolormap_t *planecolormap)
{
- planeinfo_t *planeinfo = HWR_CreateDrawNode(DRAWNODE_PLANE);
+ planeinfo_t *planeinfo = static_cast(HWR_CreateDrawNode(DRAWNODE_PLANE));
planeinfo->isceiling = isceiling;
planeinfo->fixedheight = fixedheight;
@@ -4278,7 +4301,7 @@ static void HWR_AddTransparentFloor(lumpnum_t lumpnum, extrasubsector_t *xsub, b
// When that happens it'll just be done through HWR_AddTransparentFloor and HWR_RenderPlane
static void HWR_AddTransparentPolyobjectFloor(lumpnum_t lumpnum, polyobj_t *polysector, boolean isceiling, fixed_t fixedheight, INT32 lightlevel, INT32 alpha, sector_t *FOFSector, FBITFIELD blend, extracolormap_t *planecolormap)
{
- polyplaneinfo_t *polyplaneinfo = HWR_CreateDrawNode(DRAWNODE_POLYOBJECT_PLANE);
+ polyplaneinfo_t *polyplaneinfo = static_cast(HWR_CreateDrawNode(DRAWNODE_POLYOBJECT_PLANE));
polyplaneinfo->isceiling = isceiling;
polyplaneinfo->fixedheight = fixedheight;
@@ -4317,7 +4340,7 @@ static void HWR_RenderDrawNodes(void)
PS_START_TIMING(ps_hw_nodesorttime);
- sortindex = Z_Malloc(sizeof(INT32) * numdrawnodes, PU_STATIC, NULL);
+ sortindex = static_cast(Z_Malloc(sizeof(INT32) * numdrawnodes, PU_STATIC, NULL));
// Reversed order
for (i = 0; i < numdrawnodes; i++)
@@ -4337,7 +4360,8 @@ static void HWR_RenderDrawNodes(void)
for (i = run_start+1; i < numdrawnodes; i++)
{
- if (drawnodes[sortindex[i]].type != DRAWNODE_PLANE) break;
+ if (drawnodes[sortindex[i]].type != DRAWNODE_PLANE)
+ break;
}
run_end = i-1;
@@ -4458,7 +4482,10 @@ static void HWR_DrawModels(void)
continue;
}
- if (spr->mobj && spr->mobj->skin && spr->mobj->sprite == SPR_PLAY)
+ if (!spr->mobj)
+ continue;
+
+ if (spr->mobj->skin && spr->mobj->sprite == SPR_PLAY)
{
md2_t *md2;
@@ -4513,7 +4540,7 @@ static void HWR_AddSprites(sector_t *sec)
{
// Use the smaller setting
if (limit_dist)
- limit_dist = min(current_bsp_culling_distance/mapobjectscale, limit_dist);
+ limit_dist = std::min(current_bsp_culling_distance/mapobjectscale, limit_dist);
else
limit_dist = current_bsp_culling_distance/mapobjectscale;
}
@@ -4553,13 +4580,13 @@ static void HWR_AddPrecipitationSprites(void)
drawdist = ((fixed_t)(cv_drawdist_precip.value) * (cv_mobjscaleprecip.value ? mapobjectscale : FRACUNIT));
// No to infinite precipitation draw distance.
- if (drawdist == 0)
+ if (cv_drawdist_precip.value == 0)
{
return;
}
if (current_bsp_culling_distance)
- drawdist = min((fixed_t)current_bsp_culling_distance, drawdist);
+ drawdist = std::min((fixed_t)current_bsp_culling_distance, drawdist);
R_GetRenderBlockMapDimensions(drawdist, &xl, &xh, &yl, &yh);
@@ -4611,7 +4638,6 @@ static void HWR_ProjectSprite(mobj_t *thing)
angle_t camang = 0;
#endif
INT32 heightsec, phs;
- INT32 dist = -1;
fixed_t spr_width, spr_height;
fixed_t spr_offset, spr_topoffset;
@@ -4626,12 +4652,9 @@ static void HWR_ProjectSprite(mobj_t *thing)
return;
// uncapped/interpolation
- interpmobjstate_t interp = {0};
+ interpmobjstate_t interp = {};
- if (cv_maxinterpdist.value)
- dist = R_QuickCamDist(thing->x, thing->y);
-
- if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value))
+ if (R_UsingFrameInterpolation() && !paused && R_CheckInterpDist(thing))
{
R_InterpolateMobjState(thing, rendertimefrac, &interp);
}
@@ -4670,8 +4693,8 @@ static void HWR_ProjectSprite(mobj_t *thing)
return;
const boolean mirrored = thing->mirrored;
- const boolean vflip = (thing->eflags & MFE_VERTICALFLIP);
- const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored);
+ const boolean vflip = (thing->eflags & MFE_VERTICALFLIP);
+ const boolean hflip = (!(thing->frame & FF_HORIZONTALFLIP) != !mirrored);
this_scale = FixedToFloat(interp.scale);
spritexscale = FixedToFloat(interp.spritexscale);
@@ -4688,7 +4711,7 @@ static void HWR_ProjectSprite(mobj_t *thing)
#ifdef ROTSPRITE
// determine here if sprite should rotate for optimization
const boolean sliprollrotate = (cv_sliptideroll.value && (thing->player && thing->player->sliproll));
- const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || sliprollrotate);
+ const boolean shouldrotate = (interp.sloperoll || interp.slopepitch || interp.roll || interp.pitch || thing->rollangle || sliprollrotate);
#endif
//Fab : 02-08-98: 'skin' override spritedef currently used for skin
@@ -4920,21 +4943,21 @@ static void HWR_ProjectSprite(mobj_t *thing)
if ((vis->mobj->flags & MF_BOSS) && (vis->mobj->flags2 & MF2_FRET) && (leveltime & 1)) // Bosses "flash"
{
if (vis->mobj->type == MT_CYBRAKDEMON)
- vis->colormap = R_GetTranslationColormap(TC_ALLWHITE, 0, GTC_CACHE);
+ vis->colormap = static_cast(R_GetTranslationColormap(TC_ALLWHITE, SKINCOLOR_NONE, GTC_CACHE));
else if (vis->mobj->type == MT_METALSONIC_BATTLE)
- vis->colormap = R_GetTranslationColormap(TC_METALSONIC, 0, GTC_CACHE);
+ vis->colormap = static_cast(R_GetTranslationColormap(TC_METALSONIC, SKINCOLOR_NONE, GTC_CACHE));
else
- vis->colormap = R_GetTranslationColormap(TC_BOSS, 0, GTC_CACHE);
+ vis->colormap = static_cast(R_GetTranslationColormap(TC_BOSS, SKINCOLOR_NONE, GTC_CACHE));
}
else if (thing->color)
{
// New colormap stuff for skins Tails 06-07-2002
if (thing->colorized)
- vis->colormap = R_GetTranslationColormap(TC_RAINBOW, thing->color, GTC_CACHE);
+ vis->colormap = static_cast(R_GetTranslationColormap(TC_RAINBOW, static_cast(thing->color), GTC_CACHE));
else if (thing->skin && thing->sprite == SPR_PLAY) // This thing is a player!
- vis->colormap = R_GetLocalTranslationColormap(thing->skin, thing->localskin, thing->color, GTC_CACHE, thing->skinlocal);
+ vis->colormap = static_cast(R_GetLocalTranslationColormap(static_cast(thing->skin), static_cast(thing->localskin), static_cast(thing->color), GTC_CACHE, thing->skinlocal));
else
- vis->colormap = R_GetTranslationColormap(TC_DEFAULT, thing->color, GTC_CACHE);
+ vis->colormap = static_cast(R_GetTranslationColormap(TC_DEFAULT, static_cast(thing->color), GTC_CACHE));
}
else
{
@@ -4972,7 +4995,6 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing)
size_t lumpoff;
unsigned rot = 0;
UINT8 flip;
- INT32 dist = -1;
if (!thing)
return;
@@ -4984,13 +5006,10 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing)
}
// uncapped/interpolation
- interpmobjstate_t interp = {0};
-
- if (cv_maxinterpdist.value)
- dist = R_QuickCamDist(thing->x, thing->y);
+ interpmobjstate_t interp = {};
// do interpolation
- if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || dist < cv_maxinterpdist.value))
+ if (R_UsingFrameInterpolation() && !paused && R_CheckInterpDist((mobj_t*)thing))
{
R_InterpolatePrecipMobjState(thing, rendertimefrac, &interp);
}
@@ -5109,8 +5128,8 @@ static gl_sky_t gl_sky;
static void HWR_SkyDomeVertex(gl_sky_t *sky, gl_skyvertex_t *vbo, int r, int c, signed char yflip, float delta, boolean foglayer)
{
- static const float scale = 10000.0f;
- static const float maxSideAngle = DEG2RADGL(60.0f);
+ static constexpr float scale = 10000.0f;
+ static constexpr float maxSideAngle = DEG2RADGL(60.0f);
float topAngle = DEG2RADGL(c / (float)sky->columns * 360.0f);
float sideAngle = (maxSideAngle * (float)(sky->rows - r) / (float)sky->rows);
@@ -5121,7 +5140,7 @@ static void HWR_SkyDomeVertex(gl_sky_t *sky, gl_skyvertex_t *vbo, int r, int c,
float z = (realRadius * (float)sin(topAngle));
float timesRepeat = (4 * (256.0f / sky->width));
- if (fpclassify(timesRepeat) == FP_ZERO)
+ if (std::fpclassify(timesRepeat) == FP_ZERO)
timesRepeat = 1.0f;
if (!foglayer)
@@ -5195,11 +5214,11 @@ void HWR_BuildSkyDome(void)
sky->vertex_count = 2 * sky->rows * (sky->columns * 2 + 2) + sky->columns * 2;
if (!sky->loops)
- sky->loops = malloc((sky->rows * 2 + 2) * sizeof(sky->loops[0]));
+ sky->loops = static_cast(malloc((sky->rows * 2 + 2) * sizeof(sky->loops[0])));
// create vertex array
if (!sky->data)
- sky->data = malloc(sky->vertex_count * sizeof(sky->data[0]));
+ sky->data = static_cast(malloc(sky->vertex_count * sizeof(sky->data[0])));
sky->texture = texturetranslation[skytexture];
sky->width = texture->width;
@@ -5250,7 +5269,7 @@ void HWR_BuildSkyDome(void)
static boolean drewsky = false;
// precompute to save a bit of division
-static const float FINEDEGREE = (360.0f/(float)FINEANGLES);
+static constexpr float FINEDEGREE = (360.0f/(float)FINEANGLES);
static void HWR_DrawSkyBackground(void)
{
@@ -5259,6 +5278,9 @@ static void HWR_DrawSkyBackground(void)
if (drewsky)
return;
+ if (HWR_IsWireframeMode())
+ return;
+
GL_SetBlend(PF_Translucent|PF_NoDepthTest|PF_Modulated);
memcpy(&dometransform, &atransform, sizeof(FTransform));
@@ -5404,48 +5426,56 @@ void HWR_SetStencilState(int state, int level)
GL_SetSpecialState(HWD_SET_PORTAL_MODE, state);
}
-typedef void (*bspfunc)(INT32 bspnum);
-
// Renders the current viewpoint, though takes portal arguments for recursive portals.
-void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals)
+namespace
+{
+ enum class RenderViewpointType
+ {
+ kPortal,
+ kNormal,
+ };
+
+template
+void HWR_RenderViewpoint(gl_portal_t *rootportal, player_t *player, int stencil_level, boolean allow_portals)
{
gl_portallist_t portallist;
+ const float fpov = FixedToFloat(R_GetPlayerFov(player));
const boolean skybox = (skyboxmo[0] && cv_skybox.value);
- const boolean useportals = HWR_UsePortals() && allow_portals;
- bspfunc bspFunc = (useportals && portalclipline) ? HWR_RenderPortalBSPNode : HWR_RenderBSPNode;
portallist.base = portallist.cap = NULL;
+ HWR_SetPortalState(GLPORTAL_OFF); // there may be portals and they need to be drawn as regural walls
- if (useportals && stencil_level < cv_maxportals.value) // if recursion limit is not reached
+ if constexpr (Type == RenderViewpointType::kPortal)
{
- gl_portal_t *portal;
-
- // search for portals in current frame
- currentportallist = &portallist;
- HWR_SetPortalState(GLPORTAL_SEARCH);
-
- HWR_ClearClipper();
-
- if (rootportal)
- HWR_PortalClipping(rootportal);
-
- validcount++;
-
- // no actual rendering happens
- bspFunc((INT32)numnodes-1);
-
- // for each found portal:
- // note: if necessary, could sort the portals here?
- for (portal = portallist.base; portal; portal = portal->next)
+ if (allow_portals && stencil_level < cv_maxportals.value) // if recursion limit is not reached
{
- HWR_RenderPortal(portal, rootportal, fpov, player, stencil_level);
- }
+ gl_portal_t *portal;
- HWR_SetPortalState(GLPORTAL_INSIDE); // when portal walls are encountered in following bsp traversal, nothing should be drawn
+ // search for portals in current frame
+ currentportallist = &portallist;
+ HWR_SetPortalState(GLPORTAL_SEARCH);
+
+ HWR_ClearClipper();
+
+ if (rootportal)
+ HWR_PortalClipping(rootportal);
+
+ validcount++;
+
+ // no actual rendering happens
+ HWR_RenderBSPNode((INT32)numnodes-1);
+
+ // for each found portal:
+ // note: if necessary, could sort the portals here?
+ for (portal = portallist.base; portal; portal = portal->next)
+ {
+ HWR_RenderPortal(portal, rootportal, fpov, player, stencil_level);
+ }
+
+ HWR_SetPortalState(GLPORTAL_INSIDE); // when portal walls are encountered in following bsp traversal, nothing should be drawn
+ }
}
- else
- HWR_SetPortalState(GLPORTAL_OFF); // there may be portals and they need to be drawn as regural walls
// draw normal things in current frame in current incremented stencil buffer area
HWR_SetStencilState(HWR_STENCIL_NORMAL, stencil_level);
@@ -5455,16 +5485,19 @@ void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *pl
HWR_ClearSprites();
HWR_ClearClipper();
- if (useportals && rootportal)
+ if constexpr (Type == RenderViewpointType::kPortal)
{
- HWR_PortalFrame(rootportal);// for portalclipsector, it could have gone null from search
- HWR_PortalClipping(rootportal);
+ if (allow_portals && rootportal)
+ {
+ HWR_PortalFrame(rootportal);// for portalclipsector, it could have gone null from search
+ HWR_PortalClipping(rootportal);
+ }
}
- // Set transform.
- GL_SetTransform(&atransform);
+ if (HWR_IsWireframeMode())
+ GL_SetSpecialState(HWD_SET_WIREFRAME, 1);
- ps_numbspcalls.value.i = 0;
+ ps_numbspcalls.value.i = 0;
ps_numpolyobjects.value.i = 0;
PS_START_TIMING(ps_bsptime);
@@ -5473,21 +5506,32 @@ void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *pl
if (LIKELY(cv_glbatching.value))
HWR_StartBatching();
- if (useportals && !rootportal && portallist.base && !skybox) // if portals have been drawn in the main view, then render skywalls differently
- gl_collect_skywalls = true;
+ if constexpr (Type == RenderViewpointType::kPortal)
+ {
+ if (allow_portals && !rootportal && portallist.base && !skybox) // if portals have been drawn in the main view, then render skywalls differently
+ gl_collect_skywalls = true;
- // HAYA: Save the old portal state, and turn portals off while normally rendering the BSP tree.
- // This fixes specific effects not working, such as horizon lines.
- SINT8 oldgl_portal_state = gl_portal_state;
+ // HAYA: Save the old portal state, and turn portals off while normally rendering the BSP tree.
+ // This fixes specific effects not working, such as horizon lines.
+ SINT8 oldgl_portal_state = gl_portal_state;
- if (gl_portal_state != GLPORTAL_OFF) // if we already haven't hit the recursion limit or we already ended our portal shenanigans
- HWR_SetPortalState(GLPORTAL_INSIDE); // TURN IT OFF
+ if (gl_portal_state != GLPORTAL_OFF) // if we already haven't hit the recursion limit or we already ended our portal shenanigans
+ HWR_SetPortalState(GLPORTAL_INSIDE); // TURN IT OFF
- // Recursively "render" the BSP tree.
- bspFunc((INT32)numnodes-1);
+ // Recursively "render" the BSP tree.
+ if (allow_portals && portalclipline)
+ HWR_RenderBSPNode((INT32)numnodes-1);
+ else
+ HWR_RenderBSPNode((INT32)numnodes-1);
- // woo we back
- HWR_SetPortalState(oldgl_portal_state);
+ // woo we back
+ HWR_SetPortalState(oldgl_portal_state);
+ }
+ else if constexpr (Type == RenderViewpointType::kNormal)
+ {
+ // Recursively "render" the BSP tree.
+ HWR_RenderBSPNode((INT32)numnodes-1);
+ }
if (allow_portals) // looks weird, but this is only true when its not skybox rendering skipping precip in skyboxes like software does
HWR_AddPrecipitationSprites();
@@ -5497,17 +5541,20 @@ void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *pl
if (LIKELY(cv_glbatching.value))
HWR_RenderBatches();
- if (skyWallVertexArraySize) // if there are skywalls to draw using the alternate method
+ if constexpr (Type == RenderViewpointType::kPortal)
{
- HWR_SetStencilState(HWR_STENCIL_SKY, -1);
- HWR_DrawSkyWallList();
- HWR_SkyWallList_Clear();
- HWR_SetStencilState(HWR_STENCIL_NORMAL, 1);
- drewsky = false;
- HWR_DrawSkyBackground();
- HWR_SetStencilState(HWR_STENCIL_NORMAL, 0);
- GL_ClearBuffer(false, false, true, 0);// clear skywall markings from the stencil buffer
- HWR_SetTransform(fpov);// restore transform
+ if (skyWallVertexArraySize) // if there are skywalls to draw using the alternate method
+ {
+ HWR_SetStencilState(HWR_STENCIL_SKY, -1);
+ HWR_DrawSkyWallList();
+ HWR_SkyWallList_Clear();
+ HWR_SetStencilState(HWR_STENCIL_NORMAL, 1);
+ drewsky = false;
+ HWR_DrawSkyBackground();
+ HWR_SetStencilState(HWR_STENCIL_NORMAL, 0);
+ GL_ClearBuffer(false, false, true, 0);// clear skywall markings from the stencil buffer
+ HWR_SetTransform(fpov);// restore transform
+ }
}
gl_collect_skywalls = false;
@@ -5522,22 +5569,29 @@ void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *pl
HWR_DrawModels();
PS_STOP_TIMING(ps_hw_spritedrawtime);
- ps_numdrawnodes.value.i = 0;
+ ps_numdrawnodes.value.i = 0;
ps_hw_nodesorttime.value.p = 0;
ps_hw_nodedrawtime.value.p = 0;
HWR_RenderDrawNodes();
- HWR_FreePortalList(portallist);
-}
+ if (HWR_IsWireframeMode())
+ GL_SetSpecialState(HWD_SET_WIREFRAME, 0);
+ HWR_FreePortalList(portallist); // always call this just in case
+}
+};
+
+extern "C" {
+ void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, player_t *player, int stencil_level, boolean allow_portals) {
+ HWR_RenderViewpoint(rootportal, player, stencil_level, allow_portals);
+ }
+}
// ==========================================================================
// Render the current frame.
// ==========================================================================
static void HWR_RenderFrame(player_t *player, boolean skybox)
{
- const float fpov = FixedToFloat(R_GetPlayerFov(player));
-
// set window position
gl_viewwindowx = gl_baseviewwindowx;
gl_viewwindowy = gl_baseviewwindowy;
@@ -5552,28 +5606,12 @@ static void HWR_RenderFrame(player_t *player, boolean skybox)
gl_viewwindowx += gl_viewwidth;
}
- if (splitscreen == 2 && player == &players[displayplayers[2]])
- {
- // V_DrawPatchFill, but for the fourth screen only
- patch_t *gpatch = W_CachePatchName("SRB2BACK", PU_PATCH);
- INT32 dupz = (vid.dupx < vid.dupy ? vid.dupx : vid.dupy);
- INT32 x, y, pw = (gpatch->width * dupz), ph = (gpatch->height * dupz);
-
- for (x = vid.width >> 1; x < vid.width; x += pw)
- {
- for (y = vid.height >> 1; y < vid.height; y += ph)
- HWR_DrawStretchyFixedPatch(gpatch, (x)<(NULL, player, 0, !skybox);
+ else
+ HWR_RenderViewpoint(NULL, player, 0, !skybox);
// Unset transform and shader
GL_SetTransform(NULL);
@@ -5627,10 +5668,6 @@ static void HWR_RollTransform(FTransform *tr, angle_t roll)
void HWR_RenderPlayerView(void)
{
- player_t * player = &players[displayplayers[viewssnum]];
-
- const boolean skybox = (skyboxmo[0] && cv_skybox.value); // True if there's a skybox object and skyboxes are on
-
// Clear the color buffer, stops HOMs. Also seems to fix the skybox issue on Intel GPUs.
if (viewssnum == 0) // Only do it if it's the first screen being rendered
{
@@ -5661,6 +5698,9 @@ void HWR_RenderPlayerView(void)
if (viewssnum > 3)
return;
+ player_t * player = &players[displayplayers[viewssnum]];
+ const boolean skybox = (skyboxmo[0] && cv_skybox.value); // True if there's a skybox object and skyboxes are on
+
// Render the skybox if there is one.
PS_START_TIMING(ps_skyboxtime);
drewsky = false;
@@ -5730,6 +5770,7 @@ void HWR_LoadLevel(boolean reloadinggamestate)
static void HWR_TogglePaletteRendering(void)
{
V_ResetPaletteCVars(); // dont carry over changed palettes
+ ST_ResetPaletteStuff();
// which state should we go to?
if (HWR_ShouldUsePaletteRendering())
@@ -5750,7 +5791,7 @@ static void HWR_TogglePaletteRendering(void)
// If the r_opengl "texture palette" stays the same during this switch, these textures
// will not be cleared out. However they are still out of date since the
// composite texture blending method has changed. Therefore they need to be cleared.
- GL_ClearMipMapCache();
+ HWR_LoadMapTextures(numtextures);
}
}
else
@@ -5764,7 +5805,7 @@ static void HWR_TogglePaletteRendering(void)
// If the r_opengl "texture palette" stays the same during this switch, these textures
// will not be cleared out. However they are still out of date since the
// composite texture blending method has changed. Therefore they need to be cleared.
- GL_ClearMipMapCache();
+ HWR_LoadMapTextures(numtextures);
}
}
}
@@ -5801,6 +5842,8 @@ void HWR_AddCommands(void)
CV_RegisterVar(&cv_glbatching);
+ CV_RegisterVar(&cv_glwireframe);
+
CV_RegisterVar(&cv_glrenderdistance);
CV_RegisterVar(&cv_glhorizonlines);
@@ -5873,7 +5916,6 @@ static void COM_HWR_glinfo(void)
CONS_Printf("Unrecognized argument: %s\n", argv);
return;
}
-
}
CONS_Printf("\x88OpenGL %s\x80\n", gl_version);
@@ -5993,19 +6035,19 @@ static void HWR_DoPostProcessor(player_t *player)
if (cv_glscreentextures.value != 2) // screen textures are needed for the rest of the effects
return;
+ //UINT8 viewnum = R_GetViewNumber(); // see below
+ //camera_t *thiscam = &camera[viewnum];
+ const camera_t *thiscam = &camera[0];
+
+ // Not supported in splitscreen - someone want to add support?
+ const boolean screenwave = (!splitscreen && (thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT));
+
// Capture the screen for intermission and screen waving
- if (gamestate != GS_INTERMISSION)
+ if ((lastdraw || screenwave) && gamestate != GS_INTERMISSION)
GL_MakeScreenTexture(HWD_SCREENTEXTURE_GENERIC1);
- if (splitscreen) // Not supported in splitscreen - someone want to add support?
- return;
-
- //UINT8 viewnum = R_GetViewNumber(); // see above
- //camera_t *thiscam = &camera[viewnum];
- camera_t *thiscam = &camera[0];
-
// Drunken vision! WooOOooo~
- if (thiscam->postimg & POSTIMG_WATER || thiscam->postimg & POSTIMG_HEAT)
+ if (screenwave)
{
// 10 by 10 grid. 2 coordinates (xy)
float v[SCREENVERTS][SCREENVERTS][2];
@@ -6039,6 +6081,7 @@ static void HWR_DoPostProcessor(player_t *player)
v[x][y][1] = (y/((float)(SCREENVERTS-1.0f)/9.0f))-4.5f;
}
}
+
GL_PostImgRedraw(v);
// Capture the screen again for screen waving on the intermission
diff --git a/src/hardware/hw_main.h b/src/hardware/hw_main.h
index b8d6ef939..2ffbfd506 100644
--- a/src/hardware/hw_main.h
+++ b/src/hardware/hw_main.h
@@ -20,6 +20,10 @@
#ifndef __HWR_MAIN_H__
#define __HWR_MAIN_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "hw_gl.h"
#include "hw_glob.h"
#include "hw_data.h"
@@ -105,7 +109,8 @@ void HWR_SetViewSize(void);
void HWR_AddCommands(void);
void HWR_RenderPlayerView(void);
-void HWR_RenderViewpoint(gl_portal_t *rootportal, const float fpov, player_t *player, int stencil_level, boolean allow_portals);
+void HWR_RenderViewpoint(gl_portal_t *rootportal, player_t *player, int stencil_level, boolean allow_portals);
+void HWR_RenderPortalViewpoint(gl_portal_t *rootportal, player_t *player, int stencil_level, boolean allow_portals);
void HWR_ClearSkyDome(void);
void HWR_BuildSkyDome(void);
@@ -202,6 +207,8 @@ extern consvar_t cv_glsolvetjoin;
extern consvar_t cv_glbatching;
+extern consvar_t cv_glwireframe;
+
extern consvar_t cv_glrenderdistance;
extern consvar_t cv_glhorizonlines;
@@ -223,7 +230,11 @@ FUNCINLINE static ATTRINLINE boolean HWR_ShouldUsePaletteRendering(void)
FUNCINLINE static ATTRINLINE boolean HWR_PalRenderFlashpal(void)
{
- return (HWR_ShouldUsePaletteRendering() && cv_glflashpal.value);
+ return (cv_glflashpal.value && HWR_ShouldUsePaletteRendering());
}
+#ifdef __cplusplus
+}// extern "C"
+#endif
+
#endif
diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c
index 2696cf89d..e1b31bda0 100644
--- a/src/hardware/hw_md2.c
+++ b/src/hardware/hw_md2.c
@@ -1187,7 +1187,7 @@ void HWR_DrawMD2(gl_vissprite_t *spr)
spriteinfo_t *sprinfo;
interpmobjstate_t interp;
- if (R_UsingFrameInterpolation() && !paused && (!cv_maxinterpdist.value || R_QuickCamDist(spr->mobj->x, spr->mobj->y) < cv_maxinterpdist.value))
+ if (R_UsingFrameInterpolation() && !paused && R_CheckInterpDist(spr->mobj))
{
R_InterpolateMobjState(spr->mobj, rendertimefrac, &interp);
}
diff --git a/src/hardware/hw_md2.h b/src/hardware/hw_md2.h
index 2e3e005b7..014638f56 100644
--- a/src/hardware/hw_md2.h
+++ b/src/hardware/hw_md2.h
@@ -15,6 +15,10 @@
#ifndef _HW_MD2_H_
#define _HW_MD2_H_
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "hw_glob.h"
#include "hw_model.h"
@@ -46,4 +50,8 @@ void HWR_DrawMD2(gl_vissprite_t *spr);
void HWR_AddPlayerMD2(INT32 skin, boolean local);
void HWR_AddSpriteMD2(size_t spritenum);
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif // _HW_MD2_H_
diff --git a/src/hardware/hw_portal.c b/src/hardware/hw_portal.c
index 9bb5af40f..909214171 100644
--- a/src/hardware/hw_portal.c
+++ b/src/hardware/hw_portal.c
@@ -45,8 +45,8 @@ static gl_portal_t* HWR_Portal_Add (seg_t *seg)
// Linked list.
if (!currentportallist->base)
{
- currentportallist->base = portal;
- currentportallist->cap = portal;
+ currentportallist->base = portal;
+ currentportallist->cap = portal;
}
else
{
@@ -66,6 +66,7 @@ void HWR_FreePortalList(gl_portallist_t freelist)
// free memory from portal list allocated by calls to Add2Lines
gl_portal_t *gl_portal_temp = freelist.base;
+
while (gl_portal_temp)
{
gl_portal_t *nextportal = gl_portal_temp->next;
@@ -125,8 +126,7 @@ void HWR_PortalFrame(gl_portal_t* portal)
if (portal->clipline != -1)
{
portalclipline = &lines[portal->clipline];
- portalcullsector = portalclipline->frontsector;
- viewsector = portalclipline->frontsector;
+ portalcullsector = viewsector = portalclipline->frontsector;
}
else
{
@@ -146,7 +146,7 @@ static void HWR_RenderPortalSeg(gl_portal_t* portal, SINT8 state)
gl_curline = portal->seg;
gl_frontsector = portal->seg->frontsector;
- gl_backsector = portal->seg->backsector;
+ gl_backsector = portal->seg->backsector;
HWR_ProcessSeg();
gl_drawing_stencil = false;
@@ -169,7 +169,7 @@ void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float
// go to portal frame lmao
HWR_PortalFrame(portal);
// call HWR_RenderViewpoint
- HWR_RenderViewpoint(portal, fpov, player, stencil_level + 1, true);
+ HWR_RenderPortalViewpoint(portal, player, stencil_level + 1, true);
// return to current frame
if (rootportal)
HWR_PortalFrame(rootportal);
@@ -202,7 +202,9 @@ boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y)
// so first check if the point is precisely on the line, and then if not, check the side.
vertex_t closest_point;
+
P_ClosestPointOnLine(x, y, portalclipline, &closest_point);
+
if (closest_point.x != x || closest_point.y != y)
{
if (P_PointOnLineSide(x, y, portalclipline) != 1)
diff --git a/src/hardware/hw_portal.h b/src/hardware/hw_portal.h
index f42d2f61c..494110d79 100644
--- a/src/hardware/hw_portal.h
+++ b/src/hardware/hw_portal.h
@@ -14,6 +14,10 @@
#ifndef __HW_PORTAL__
#define __HW_PORTAL__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#ifdef HWRENDER
#include "../doomstat.h"
@@ -77,5 +81,9 @@ void HWR_FreePortalList(gl_portallist_t portallist);
boolean HWR_PortalCheckPointSide(fixed_t x, fixed_t y);
boolean HWR_PortalCheckBBox(const fixed_t *bspcoord);
+#endif
+
+#ifdef __cplusplus
+}// extern "C"
#endif
#endif
diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c
index 3dd7c0589..a8e9d6350 100644
--- a/src/hardware/r_opengl/r_opengl.c
+++ b/src/hardware/r_opengl/r_opengl.c
@@ -349,6 +349,8 @@ typedef void (APIENTRY * PFNglDisable) (GLenum cap);
static PFNglDisable pglDisable;
typedef void (APIENTRY * PFNglGetFloatv) (GLenum pname, GLfloat *params);
static PFNglGetFloatv pglGetFloatv;
+typedef void (APIENTRY * PFNglPolygonMode) (GLenum, GLenum);
+static PFNglPolygonMode pglPolygonMode;
/* Depth Buffer */
typedef void (APIENTRY * PFNglClearDepth) (GLclampd depth);
@@ -548,6 +550,7 @@ boolean SetupGLfunc(void)
GETOPENGLFUNC(pglGetFloatv, glGetFloatv)
GETOPENGLFUNC(pglGetIntegerv, glGetIntegerv)
GETOPENGLFUNC(pglGetString, glGetString)
+ GETOPENGLFUNC(pglPolygonMode, glPolygonMode)
GETOPENGLFUNC(pglClearDepth, glClearDepth)
GETOPENGLFUNC(pglDepthFunc, glDepthFunc)
@@ -733,69 +736,78 @@ static boolean GLFramebuffer_CheckExt(void)
return false;
// check if all needed gl extensions are available
- return (GL_isExtAvailable("GL_ARB_framebuffer_no_attachments", gl_extensions) && GL_isExtAvailable("GL_ARB_framebuffer_object", gl_extensions) && GL_isExtAvailable("GL_ARB_framebuffer_sRGB", gl_extensions));
+ return (GL_isExtAvailable("GL_ARB_framebuffer_no_attachments", gl_extensions)
+ && GL_isExtAvailable("GL_ARB_framebuffer_object", gl_extensions)
+ && GL_isExtAvailable("GL_ARB_framebuffer_sRGB", gl_extensions));
}
#endif
void SetupGLFunc4(void)
{
+#define GetGLfunc(func) \
+ p##func = GetGLFunc(#func); \
+ if (!p##func) \
+ { \
+ GL_MSG_Warning("failed to get OpenGL function: %s", #func); \
+ } \
+
/* 1.2 funcs */
- pglTexImage3D = GetGLFunc("glTexImage3D");
+ GetGLfunc(glTexImage3D);
/* 1.3 funcs */
- pglActiveTexture = GetGLFunc("glActiveTexture");
- pglMultiTexCoord2f = GetGLFunc("glMultiTexCoord2f");
- pglClientActiveTexture = GetGLFunc("glClientActiveTexture");
- pglMultiTexCoord2fv = GetGLFunc("glMultiTexCoord2fv");
+ GetGLfunc(glActiveTexture);
+ GetGLfunc(glMultiTexCoord2f);
+ GetGLfunc(glClientActiveTexture);
+ GetGLfunc(glMultiTexCoord2fv);
/* 1.5 funcs */
- pglGenBuffers = GetGLFunc("glGenBuffers");
- pglBindBuffer = GetGLFunc("glBindBuffer");
- pglBufferData = GetGLFunc("glBufferData");
- pglDeleteBuffers = GetGLFunc("glDeleteBuffers");
- pglColorPointer = GetGLFunc("glColorPointer");
+ GetGLfunc(glGenBuffers);
+ GetGLfunc(glBindBuffer);
+ GetGLfunc(glBufferData);
+ GetGLfunc(glDeleteBuffers);
+ GetGLfunc(glColorPointer);
/* 2.0 funcs */
- pglBlendEquation = GetGLFunc("glBlendEquation");
+ GetGLfunc(glBlendEquation);
- pglStencilFuncSeparate = GetGLFunc("glStencilFuncSeparate");
- pglStencilOpSeparate = GetGLFunc("glStencilOpSeparate");
+ GetGLfunc(glStencilFuncSeparate);
+ GetGLfunc(glStencilOpSeparate);
- pglCreateShader = GetGLFunc("glCreateShader");
- pglShaderSource = GetGLFunc("glShaderSource");
- pglCompileShader = GetGLFunc("glCompileShader");
- pglGetShaderiv = GetGLFunc("glGetShaderiv");
- pglGetShaderInfoLog = GetGLFunc("glGetShaderInfoLog");
- pglDeleteShader = GetGLFunc("glDeleteShader");
- pglCreateProgram = GetGLFunc("glCreateProgram");
- pglDeleteProgram = GetGLFunc("glDeleteProgram");
- pglAttachShader = GetGLFunc("glAttachShader");
- pglLinkProgram = GetGLFunc("glLinkProgram");
- pglGetProgramiv = GetGLFunc("glGetProgramiv");
- pglGetProgramInfoLog = GetGLFunc("glGetProgramInfoLog");
- pglUseProgram = GetGLFunc("glUseProgram");
- pglUniform1i = GetGLFunc("glUniform1i");
- pglUniform1f = GetGLFunc("glUniform1f");
- pglUniform2f = GetGLFunc("glUniform2f");
- pglUniform3f = GetGLFunc("glUniform3f");
- pglUniform4f = GetGLFunc("glUniform4f");
- pglUniform1fv = GetGLFunc("glUniform1fv");
- pglUniform2fv = GetGLFunc("glUniform2fv");
- pglUniform3fv = GetGLFunc("glUniform3fv");
- pglGetUniformLocation = GetGLFunc("glGetUniformLocation");
+ GetGLfunc(glCreateShader);
+ GetGLfunc(glShaderSource);
+ GetGLfunc(glCompileShader);
+ GetGLfunc(glGetShaderiv);
+ GetGLfunc(glGetShaderInfoLog);
+ GetGLfunc(glDeleteShader);
+ GetGLfunc(glCreateProgram);
+ GetGLfunc(glDeleteProgram);
+ GetGLfunc(glAttachShader);
+ GetGLfunc(glLinkProgram);
+ GetGLfunc(glGetProgramiv);
+ GetGLfunc(glGetProgramInfoLog);
+ GetGLfunc(glUseProgram);
+ GetGLfunc(glUniform1i);
+ GetGLfunc(glUniform1f);
+ GetGLfunc(glUniform2f);
+ GetGLfunc(glUniform3f);
+ GetGLfunc(glUniform4f);
+ GetGLfunc(glUniform1fv);
+ GetGLfunc(glUniform2fv);
+ GetGLfunc(glUniform3fv);
+ GetGLfunc(glGetUniformLocation);
#ifdef USE_FBO_OGL
if (GLFramebuffer_CheckExt())
{
- pglGenFramebuffers = GetGLFunc("glGenFramebuffers");
- pglBindFramebuffer = GetGLFunc("glBindFramebuffer");
- pglDeleteFramebuffers = GetGLFunc("glDeleteFramebuffers");
- pglFramebufferTexture2D = GetGLFunc("glFramebufferTexture2D");
- pglCheckFramebufferStatus = GetGLFunc("glCheckFramebufferStatus");
- pglGenRenderbuffers = GetGLFunc("glGenRenderbuffers");
- pglBindRenderbuffer = GetGLFunc("glBindRenderbuffer");
- pglDeleteRenderbuffers = GetGLFunc("glDeleteRenderbuffers");
- pglRenderbufferStorage = GetGLFunc("glRenderbufferStorage");
- pglFramebufferRenderbuffer = GetGLFunc("glFramebufferRenderbuffer");
+ GetGLfunc(glGenFramebuffers);
+ GetGLfunc(glBindFramebuffer);
+ GetGLfunc(glDeleteFramebuffers);
+ GetGLfunc(glFramebufferTexture2D);
+ GetGLfunc(glCheckFramebufferStatus);
+ GetGLfunc(glGenRenderbuffers);
+ GetGLfunc(glBindRenderbuffer);
+ GetGLfunc(glDeleteRenderbuffers);
+ GetGLfunc(glRenderbufferStorage);
+ GetGLfunc(glFramebufferRenderbuffer);
// check if ALL functions are availible
if (pglGenFramebuffers && pglBindFramebuffer &&
@@ -806,6 +818,7 @@ void SetupGLFunc4(void)
supportFBO = true;
}
#endif
+#undef GetGLfunc
}
boolean GL_InitShaders(void)
@@ -955,6 +968,7 @@ static void GL_SetNoTexture(void)
{
if (NOTEXTURE_NUM == 0)
pglGenTextures(1, &NOTEXTURE_NUM);
+
pglBindTexture(GL_TEXTURE_2D, NOTEXTURE_NUM);
tex_downloaded = NOTEXTURE_NUM;
}
@@ -1104,10 +1118,12 @@ void GL_DeleteTexture(GLMipmap_t *pTexInfo)
head->next->prev = head->prev;
else // no next -> tail is being deleted -> update TexCacheTail
TexCacheTail = head->prev;
+
if (head->prev)
head->prev->next = head->next;
else // no prev -> head is being deleted -> update TexCacheHead
TexCacheHead = head->next;
+
free(head);
break;
}
@@ -1128,7 +1144,7 @@ static void GL_Framebuffer_GenerateAttachments(void)
pglBindFramebuffer(GL_FRAMEBUFFER, FramebufferObject);
// Generate the framebuffer texture
- if (FramebufferTexture == 0)
+ if (!FramebufferTexture)
{
pglGenTextures(1, &FramebufferTexture);
pglBindTexture(GL_TEXTURE_2D, FramebufferTexture);
@@ -1142,7 +1158,7 @@ static void GL_Framebuffer_GenerateAttachments(void)
}
// Generate the renderbuffer
- if (RenderbufferObject == 0)
+ if (!RenderbufferObject)
{
pglGenRenderbuffers(1, &RenderbufferObject);
@@ -1164,10 +1180,10 @@ static void GL_Framebuffer_GenerateAttachments(void)
static void GL_Framebuffer_DeleteAttachments(void)
{
- if (!supportFBO || fboinit == false)
+ if (!supportFBO || !fboinit)
return;
- if (FramebufferObject == 0 && RenderbufferObject == 0 && FramebufferTexture == 0)
+ if (!FramebufferObject && !RenderbufferObject && !FramebufferTexture)
return;
// Unbind the framebuffer
@@ -1191,7 +1207,7 @@ static void GL_Framebuffer_Generate(void)
return;
// Generate the framebuffer
- if (FramebufferObject == 0)
+ if (!FramebufferObject)
pglGenFramebuffers(1, &FramebufferObject);
if (pglCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
@@ -1200,7 +1216,7 @@ static void GL_Framebuffer_Generate(void)
static void GL_Framebuffer_Delete(void)
{
- if (!supportFBO || fboinit == false)
+ if (!supportFBO || !fboinit)
return;
if (FramebufferObject)
@@ -1212,10 +1228,10 @@ static void GL_Framebuffer_Delete(void)
void GL_Framebuffer_Unbind(void)
{
- if (!supportFBO || fboinit == false)
+ if (!supportFBO || !fboinit)
return;
- if (FramebufferObject == 0 && RenderbufferObject == 0)
+ if (!FramebufferObject && !RenderbufferObject)
return;
pglBindFramebuffer(GL_FRAMEBUFFER, 0);
@@ -1229,7 +1245,7 @@ void GL_Framebuffer_Enable(void)
if (FramebufferObject == 0)
GL_Framebuffer_Generate();
- else if (FramebufferTexture == 0 || RenderbufferObject == 0)
+ else if (!FramebufferTexture || !RenderbufferObject)
GL_Framebuffer_GenerateAttachments();
pglBindFramebuffer(GL_FRAMEBUFFER, FramebufferObject);
@@ -1238,10 +1254,10 @@ void GL_Framebuffer_Enable(void)
void GL_Framebuffer_Disable(void)
{
- if (!supportFBO || fboinit == false)
+ if (!supportFBO || !fboinit)
return;
- if (FramebufferObject == 0 && RenderbufferObject == 0)
+ if (!FramebufferObject && !RenderbufferObject)
return;
pglBindFramebuffer(GL_FRAMEBUFFER, 0);
@@ -1291,20 +1307,29 @@ INT32 GL_isExtAvailable(const char *extension, const GLubyte *start)
{
GLubyte *where, *terminator;
- if (!extension || !start) return 0;
+ if (!extension || !start)
+ return 0;
+
where = (GLubyte *) strchr(extension, ' ');
+
if (where || *extension == '\0')
return 0;
for (;;)
{
where = (GLubyte *) strstr((const char *) start, extension);
+
if (!where)
break;
+
terminator = where + strlen(extension);
+
if (where == start || *(where - 1) == ' ')
+ {
if (*terminator == ' ' || *terminator == '\0')
return 1;
+ }
+
start = terminator;
}
return 0;
@@ -1336,23 +1361,33 @@ void GL_ReadScreenTexture(int tex, UINT16 *dst_data)
{
INT32 i;
int dst_stride = screen_width * 3; // stride between rows of image data
- GLubyte*top = (GLvoid*)dst_data, *bottom = top + dst_stride * (screen_height - 1);
+ GLubyte *top, *bottom;
GLubyte *row;
+
row = malloc(dst_stride);
- if (!row) return;
+
+ if (!row)
+ return;
+
+ top = (GLvoid*)dst_data;
+ bottom = top + dst_stride * (screen_height - 1);
+
// at the time this function is called, generic2 can be found drawn on the framebuffer
// if some other screen texture is needed, draw it to the framebuffer
// and draw generic2 back after reading the framebuffer.
// this hack is for some reason **much** faster than the simple solution of using glGetTexImage.
if (tex != HWD_SCREENTEXTURE_GENERIC2)
GL_DrawScreenTexture(tex, NULL, 0);
+
pglPixelStorei(GL_PACK_ALIGNMENT, 1);
pglReadPixels(0, 0, screen_width, screen_height, GL_RGB, GL_UNSIGNED_BYTE, dst_data);
+
if (tex != HWD_SCREENTEXTURE_GENERIC2)
GL_DrawScreenTexture(HWD_SCREENTEXTURE_GENERIC2, NULL, 0);
+
// Flip image upside down.
// In other words, convert OpenGL's "bottom->top" row order into "top->bottom".
- for(i = 0; i < screen_height/2; i++)
+ for (i = 0; i < screen_height/2; i++)
{
memcpy(row, top, dst_stride);
memcpy(top, bottom, dst_stride);
@@ -1360,6 +1395,7 @@ void GL_ReadScreenTexture(int tex, UINT16 *dst_data)
top += dst_stride;
bottom -= dst_stride;
}
+
free(row);
}
@@ -1412,10 +1448,8 @@ void GL_ClearBuffer(FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask
if (ColorMask)
{
if (ClearColor)
- pglClearColor(ClearColor->red,
- ClearColor->green,
- ClearColor->blue,
- ClearColor->alpha);
+ pglClearColor(ClearColor->red, ClearColor->green, ClearColor->blue, ClearColor->alpha);
+
ClearMask |= GL_COLOR_BUFFER_BIT;
}
if (DepthMask)
@@ -1430,6 +1464,7 @@ void GL_ClearBuffer(FBOOLEAN ColorMask, FBOOLEAN DepthMask, FBOOLEAN StencilMask
if (StencilMask)
ClearMask |= GL_STENCIL_BUFFER_BIT;// looks like sometimes stencil buffer needs clearing? had a problem with random black screens
+
pglClear(ClearMask);
pglEnableClientState(GL_VERTEX_ARRAY); // We always use this one
pglEnableClientState(GL_TEXTURE_COORD_ARRAY); // And mostly this one, too
@@ -2054,7 +2089,7 @@ static boolean GL_Shader_CompileProgram(gl_shader_t *shader, GLint i)
pglGetShaderiv(gl_fragShader, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
- pglGetShaderInfoLog(gl_fragShader, 512, NULL, info_log);
+ pglGetShaderInfoLog(gl_fragShader, 512, NULL, info_log);
GL_MSG_Error("Error compiling fragment shader: %s\n", info_log);
pglDeleteShader(gl_vertShader);
@@ -2092,25 +2127,25 @@ static boolean GL_Shader_CompileProgram(gl_shader_t *shader, GLint i)
#define GETUNI(uniform) pglGetUniformLocation(shader->program, uniform);
// lighting
- shader->uniforms[gluniform_poly_color] = GETUNI("poly_color");
- shader->uniforms[gluniform_tint_color] = GETUNI("tint_color");
- shader->uniforms[gluniform_fade_color] = GETUNI("fade_color");
- shader->uniforms[gluniform_lighting] = GETUNI("lighting");
- shader->uniforms[gluniform_fade_start] = GETUNI("fade_start");
- shader->uniforms[gluniform_fade_end] = GETUNI("fade_end");
- shader->uniforms[gluniform_light_dir] = GETUNI("light_dir");
- shader->uniforms[gluniform_light_contrast] = GETUNI("light_contrast");
- shader->uniforms[gluniform_light_backlight] = GETUNI("light_backlight");
+ shader->uniforms[gluniform_poly_color] = GETUNI("poly_color");
+ shader->uniforms[gluniform_tint_color] = GETUNI("tint_color");
+ shader->uniforms[gluniform_fade_color] = GETUNI("fade_color");
+ shader->uniforms[gluniform_lighting] = GETUNI("lighting");
+ shader->uniforms[gluniform_fade_start] = GETUNI("fade_start");
+ shader->uniforms[gluniform_fade_end] = GETUNI("fade_end");
+ shader->uniforms[gluniform_light_dir] = GETUNI("light_dir");
+ shader->uniforms[gluniform_light_contrast] = GETUNI("light_contrast");
+ shader->uniforms[gluniform_light_backlight] = GETUNI("light_backlight");
// palette rendering
- shader->uniforms[gluniform_palette_tex] = GETUNI("palette_tex");
- shader->uniforms[gluniform_palette_lookup_tex] = GETUNI("palette_lookup_tex");
- shader->uniforms[gluniform_lighttable_tex] = GETUNI("lighttable_tex");
+ shader->uniforms[gluniform_palette_tex] = GETUNI("palette_tex");
+ shader->uniforms[gluniform_palette_lookup_tex] = GETUNI("palette_lookup_tex");
+ shader->uniforms[gluniform_lighttable_tex] = GETUNI("lighttable_tex");
- shader->uniforms[gluniform_scr_resolution] = GETUNI("scr_resolution");
+ shader->uniforms[gluniform_scr_resolution] = GETUNI("scr_resolution");
// misc.
- shader->uniforms[gluniform_leveltime] = GETUNI("leveltime");
+ shader->uniforms[gluniform_leveltime] = GETUNI("leveltime");
#undef GETUNI
// set permanent uniform values
@@ -2318,49 +2353,54 @@ void GL_SetSpecialState(hwdspecialstate_t IdState, INT32 Value)
gl_allowshaders = Value;
break;
case HWD_SET_TEXTUREFILTERMODE:
-
- switch (Value)
{
- case HWD_SET_TEXTUREFILTER_TRILINEAR:
- min_filter = GL_LINEAR_MIPMAP_LINEAR;
- mag_filter = GL_LINEAR;
- MipMap = GL_TRUE;
- break;
- case HWD_SET_TEXTUREFILTER_BILINEAR:
- min_filter = mag_filter = GL_LINEAR;
+ switch (Value)
+ {
+ case HWD_SET_TEXTUREFILTER_TRILINEAR:
+ min_filter = GL_LINEAR_MIPMAP_LINEAR;
+ mag_filter = GL_LINEAR;
+ MipMap = GL_TRUE;
+ break;
+ case HWD_SET_TEXTUREFILTER_BILINEAR:
+ min_filter = mag_filter = GL_LINEAR;
+ MipMap = GL_FALSE;
+ break;
+ case HWD_SET_TEXTUREFILTER_POINTSAMPLED:
+ min_filter = mag_filter = GL_NEAREST;
+ MipMap = GL_FALSE;
+ break;
+ case HWD_SET_TEXTUREFILTER_MIXED1:
+ min_filter = GL_NEAREST;
+ mag_filter = GL_LINEAR;
+ MipMap = GL_FALSE;
+ break;
+ case HWD_SET_TEXTUREFILTER_MIXED2:
+ min_filter = GL_LINEAR;
+ mag_filter = GL_NEAREST;
+ MipMap = GL_FALSE;
+ break;
+ case HWD_SET_TEXTUREFILTER_MIXED3:
+ min_filter = GL_LINEAR_MIPMAP_LINEAR;
+ mag_filter = GL_NEAREST;
+ MipMap = GL_TRUE;
+ break;
+ default:
+ min_filter = GL_NEAREST;
+ mag_filter = GL_LINEAR;
+ }
+
+ if (!supportMipMap)
+ {
MipMap = GL_FALSE;
- break;
- case HWD_SET_TEXTUREFILTER_POINTSAMPLED:
- min_filter = mag_filter = GL_NEAREST;
- MipMap = GL_FALSE;
- break;
- case HWD_SET_TEXTUREFILTER_MIXED1:
- min_filter = GL_NEAREST;
- mag_filter = GL_LINEAR;
- MipMap = GL_FALSE;
- break;
- case HWD_SET_TEXTUREFILTER_MIXED2:
min_filter = GL_LINEAR;
- mag_filter = GL_NEAREST;
- MipMap = GL_FALSE;
- break;
- case HWD_SET_TEXTUREFILTER_MIXED3:
- min_filter = GL_LINEAR_MIPMAP_LINEAR;
- mag_filter = GL_NEAREST;
- MipMap = GL_TRUE;
- break;
- default:
- min_filter = GL_NEAREST;
- mag_filter = GL_LINEAR;
- }
+ }
- if (!supportMipMap)
- {
- MipMap = GL_FALSE;
- min_filter = GL_LINEAR;
+ GL_Flush(); //??? if we want to change filter mode by texture, remove this
}
+ break;
- GL_Flush(); //??? if we want to change filter mode by texture, remove this
+ case HWD_SET_WIREFRAME:
+ pglPolygonMode(GL_FRONT_AND_BACK, Value ? GL_LINE : GL_FILL);
break;
case HWD_SET_TEXTURE_FORMAT:
@@ -2698,7 +2738,7 @@ void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics
pglColor4ubv((GLubyte*)&Surface->PolyColor.s);
- GL_SetBlend((poly.alpha < 1 ? Surface->PolyFlags : (PF_Masked|PF_Occlude))|PF_Modulated);
+ GL_SetBlend(((poly.alpha < 1) ? Surface->PolyFlags : (PF_Masked|PF_Occlude))|PF_Modulated);
tint.red = byte2float[Surface->TintColor.s.red];
tint.green = byte2float[Surface->TintColor.s.green];
@@ -2742,9 +2782,9 @@ void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics
if (hflipped)
scalez = -scalez;
- pglRotatef(pos->anglez, 0.0f, 0.0f, -1.0f);
- pglRotatef(pos->anglex, 1.0f, 0.0f, 0.0f);
- pglRotatef(pos->angley, 0.0f, -1.0f, 0.0f);
+ pglRotatef(pos->anglez, 0.0f, 0.0f, -1.0f);
+ pglRotatef(pos->anglex, 1.0f, 0.0f, 0.0f);
+ pglRotatef(pos->angley, 0.0f, -1.0f, 0.0f);
if (pos->roll)
{
@@ -2915,8 +2955,10 @@ void GL_SetTransform(FTransform *stransform)
if (shearing)
{
float dy = stransform->viewaiming * 2;
+
if (stransform->fliptype == TRANSFORM_FLIP || stransform->fliptype == TRANSFORM_MIRRORFLIP)
dy *= -1.0f;
+
pglTranslatef(0.0f, -dy/BASEVIDHEIGHT, 0.0f);
}
@@ -2968,9 +3010,9 @@ void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2])
const float blackBack[16] =
{
-16.0f, -16.0f, 6.0f,
- -16.0f, 16.0f, 6.0f,
- 16.0f, 16.0f, 6.0f,
- 16.0f, -16.0f, 6.0f
+ -16.0f, 16.0f, 6.0f,
+ 16.0f, 16.0f, 6.0f,
+ 16.0f, -16.0f, 6.0f
};
if (gl_enable_screen_textures != 2)
@@ -2992,9 +3034,9 @@ void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2])
pglDrawArrays(GL_TRIANGLE_FAN, 0, 4);
pglEnableClientState(GL_TEXTURE_COORD_ARRAY);
- for(x = 0; x < SCREENVERTS-1;x ++)
+ for (x = 0; x < (SCREENVERTS-1); x ++)
{
- for(y = 0; y < SCREENVERTS-1; y++)
+ for (y = 0; y < (SCREENVERTS-1); y++)
{
float stCoords[8];
float vertCoords[12];
@@ -3046,23 +3088,22 @@ void GL_PostImgRedraw(float points[SCREENVERTS][SCREENVERTS][2])
void GL_FlushScreenTextures(void)
{
pglDeleteTextures(NUMSCREENTEXTURES, screenTextures);
- memset(screenTextures, 0 , sizeof(screenTextures));
+ memset(screenTextures, 0, sizeof(screenTextures));
}
void GL_DrawScreenTexture(int tex, FSurfaceInfo *surf, FBITFIELD polyflags)
{
+ float fix[8];
float xfix, yfix;
const float screenVerts[12] =
{
-1.0f, -1.0f, 1.0f,
- -1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f,
- 1.0f, -1.0f, 1.0f
+ -1.0f, 1.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f,
+ 1.0f, -1.0f, 1.0f
};
- float fix[8];
-
if (gl_enable_screen_textures != 2)
return;
@@ -3107,9 +3148,9 @@ void GL_DoScreenWipe(int wipeStart, int wipeEnd)
const float screenVerts[12] =
{
-1.0f, -1.0f, 1.0f,
- -1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f,
- 1.0f, -1.0f, 1.0f
+ -1.0f, 1.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f,
+ 1.0f, -1.0f, 1.0f
};
float fix[8];
@@ -3193,9 +3234,9 @@ void GL_RenderVhsEffect(fixed_t upbary, fixed_t downbary, UINT8 updistort, UINT8
float screenVerts[12] =
{
-1.0f, -1.0f, 1.0f,
- -1.0f, 1.0f, 1.0f,
- 1.0f, 1.0f, 1.0f,
- 1.0f, -1.0f, 1.0f
+ -1.0f, 1.0f, 1.0f,
+ 1.0f, 1.0f, 1.0f,
+ 1.0f, -1.0f, 1.0f
};
if (gl_enable_screen_textures != 2)
@@ -3294,6 +3335,7 @@ void GL_MakeScreenTexture(int tex)
// Create screen texture
if (firstTime)
pglGenTextures(1, &screenTextures[tex]);
+
pglBindTexture(GL_TEXTURE_2D, screenTextures[tex]);
if (firstTime)
@@ -3328,6 +3370,7 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh
origaspect = (float)screen_width / screen_height;
newaspect = (float)width / height;
+
if (origaspect < newaspect)
{
xoff = origaspect / newaspect;
@@ -3463,8 +3506,10 @@ void GL_SetScreenPalette(RGBA_t *palette)
if (memcmp(screenPalette, palette, sizeof(screenPalette)))
{
memcpy(screenPalette, palette, sizeof(screenPalette));
+
if (!screenPaletteTex)
pglGenTextures(1, &screenPaletteTex);
+
pglActiveTexture(GL_TEXTURE2);
pglBindTexture(GL_TEXTURE_1D, screenPaletteTex);
pglTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
diff --git a/src/hardware/r_opengl/r_opengl.h b/src/hardware/r_opengl/r_opengl.h
index b70febad4..e0d7e13ac 100644
--- a/src/hardware/r_opengl/r_opengl.h
+++ b/src/hardware/r_opengl/r_opengl.h
@@ -20,6 +20,10 @@
#ifndef _R_OPENGL_H_
#define _R_OPENGL_H_
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#ifdef HAVE_SDL
#define _MATH_DEFINES_DEFINED
@@ -143,4 +147,8 @@ typedef enum
GLF_NOTEXENV = 0x02,
} oglflags_t;
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/http-mserv.c b/src/http-mserv.c
index 30a6f977d..2831e34e6 100644
--- a/src/http-mserv.c
+++ b/src/http-mserv.c
@@ -220,9 +220,9 @@ HMS_connect (const char *format, ...)
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
- curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
+ curl_easy_setopt(curl, CURLOPT_IPRESOLVE, (long)CURL_IPRESOLVE_V4);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, cv_masterserver_timeout.value);
+ curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)cv_masterserver_timeout.value);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HMS_on_read);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, buffer);
@@ -339,8 +339,8 @@ HMS_unlist (void)
if (! hms)
return 0;
- curl_easy_setopt(hms->curl, CURLOPT_POST, 1);
- curl_easy_setopt(hms->curl, CURLOPT_POSTFIELDSIZE, 0);
+ curl_easy_setopt(hms->curl, CURLOPT_POST, (long)1);
+ curl_easy_setopt(hms->curl, CURLOPT_POSTFIELDSIZE, (long)0);
okay = HMS_do(hms);
HMS_end(hms);
diff --git a/src/hu_stuff.c b/src/hu_stuff.c
index 2821c4021..cd4c60dd8 100644
--- a/src/hu_stuff.c
+++ b/src/hu_stuff.c
@@ -49,6 +49,7 @@
#include "s_sound.h" // song credits
#include "k_kart.h"
+#include "k_hud.h"
#include "m_textinput.h"
@@ -259,8 +260,6 @@ INT32 HU_FallBackFrSpecialLetter(INT32 key)
}
}
-
-
static char cechotext[1024];
static tic_t cechotimer = 0;
static tic_t cechoduration = 5*TICRATE;
@@ -2133,7 +2132,7 @@ void HU_TickSongCredits(void)
}
}
-void HU_DrawSongCredits(void)
+static void HU_DrawSongCreditsVanilla(void)
{
char *str;
INT32 len;
@@ -2141,9 +2140,6 @@ void HU_DrawSongCredits(void)
INT32 y = (splitscreen ? (BASEVIDHEIGHT/2)-4 : 32);
INT32 bgt;
- if (!cursongcredit.def) // No def
- return;
-
str = va("\x1F"" %s", cursongcredit.def->source);
len = V_ThinStringWidth(str, V_ALLOWLOWERCASE|V_6WIDTHSPACE);
destx = (len + 7) * FRACUNIT;
@@ -2173,6 +2169,70 @@ void HU_DrawSongCredits(void)
V_DrawRightAlignedThinString(cursongcredit.x / FRACUNIT, y, V_ALLOWLOWERCASE|V_6WIDTHSPACE|V_SNAPTOLEFT|(cursongcredit.trans<source;
+ INT32 strwidth = V_SmallStringWidth(str, V_ALLOWLOWERCASE) + 4;
+
+ // dup dup dup dup
+ INT32 dup = min(vid.dupx, vid.dupy);
+
+ // Center it
+ INT32 x = (BASEVIDWIDTH/2 - strwidth/2)*dup + ((vid.width - (BASEVIDWIDTH * vid.dupx)) / 2);
+ INT32 y = 0;
+
+ INT32 flags = V_SNAPTOTOP|V_NOSCALESTART;
+ INT32 t = cursongcredit.anim;
+ INT32 bgt;
+
+ fixed_t interpoffset = FixedMul(BOXCREDITHEIGHT*dup*FRACUNIT/(TICRATE/2), R_GetHudUncap());
+
+ if (t > BOXCREDITSLIDEIN)
+ {
+ // Sliding in
+ t = TICRATE/2 - (t - BOXCREDITSLIDEIN);
+ y = -BOXCREDITHEIGHT*dup + (FixedMul(BOXCREDITHEIGHT*FRACUNIT, FixedDiv(t*FRACUNIT, TICRATE*FRACUNIT/2))*dup + interpoffset)/FRACUNIT;
+ }
+ else if (t < TICRATE/2)
+ {
+ // Sliding out
+ y = -BOXCREDITHEIGHT*dup + (FixedMul(BOXCREDITHEIGHT*FRACUNIT, FixedDiv(t*FRACUNIT, TICRATE*FRACUNIT/2))*dup - interpoffset)/FRACUNIT;
+ }
+
+ bgt = (NUMTRANSMAPS/2) + (cursongcredit.trans/2);
+
+ if (bgt < NUMTRANSMAPS)
+ {
+ V_DrawFill(x, y, strwidth*dup, BOXCREDITHEIGHT*dup, 28|flags|(bgt< 1.0/ticratescaled)
{
diff --git a/src/i_video.h b/src/i_video.h
index 70321d138..68042a654 100644
--- a/src/i_video.h
+++ b/src/i_video.h
@@ -14,6 +14,10 @@
#ifndef __I_VIDEO__
#define __I_VIDEO__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#include "doomtype.h"
#ifdef __GNUG__
@@ -149,4 +153,8 @@ boolean UseScreenFBO(void);
extern boolean downsample;
#endif
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
#endif
diff --git a/src/k_hud.c b/src/k_hud.c
new file mode 100644
index 000000000..502089033
--- /dev/null
+++ b/src/k_hud.c
@@ -0,0 +1,4797 @@
+// SONIC ROBO BLAST 2 KART
+//-----------------------------------------------------------------------------
+// Copyright (C) 2018-2020 by Kart Krew
+//
+// This program is free software distributed under the
+// terms of the GNU General Public License, version 2.
+// See the 'LICENSE' file for more details.
+//-----------------------------------------------------------------------------
+/// \file k_hud.c
+/// \brief HUD drawing functions exclusive to Kart
+
+#include "doomdef.h"
+#include "doomstat.h"
+#include "doomtype.h"
+#include "command.h"
+#include "d_netcmd.h"
+#include "d_player.h"
+#include "hu_stuff.h"
+#include "g_game.h"
+#include "i_joy.h"
+#include "m_fixed.h"
+#include "m_menu.h" // ffdhidshfuisduifigergho9igj89dgodhfih AAAAAAAAAA
+#include "p_local.h"
+#include "p_setup.h"
+#include "r_defs.h"
+#include "r_draw.h"
+#include "r_state.h"
+#include "r_fps.h"
+#include "s_sound.h"
+#include "screen.h"
+#include "st_stuff.h"
+#include "tables.h"
+#include "v_video.h"
+#include "z_zone.h"
+#include "m_cond.h"
+#include "k_director.h"
+#include "k_kart.h"
+#include "lua_hud.h" // For Lua hud checks
+#include "d_main.h" // found_extra_kart
+#include "i_video.h"
+
+#include "k_hud.h"
+
+#ifdef ROTSPRITE
+#include "r_patchrotation.h"
+#endif
+
+#ifdef HWRENDER
+#include "hardware/hw_main.h"
+#endif
+
+#define XTRA3PSCALE 50135 //0.765
+#define XTRA3VSCALE 35344 //0.55
+
+// Hud offset cvars
+#define IMPL_HUD_OFFSET_X(name)\
+consvar_t cv_##name##_xoffset = {"hud_" #name "_xoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+#define IMPL_HUD_OFFSET_Y(name)\
+consvar_t cv_##name##_yoffset = {"hud_" #name "_yoffset", "0", CV_SAVE, NULL, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+#define IMPL_HUD_OFFSET(name)\
+IMPL_HUD_OFFSET_X(name)\
+IMPL_HUD_OFFSET_Y(name)
+
+IMPL_HUD_OFFSET(item); // Item box
+IMPL_HUD_OFFSET(time); // Time
+IMPL_HUD_OFFSET(laps); // Number of laps
+IMPL_HUD_OFFSET(dnft); // Countdown (did not finish timer)
+IMPL_HUD_OFFSET(speed); // Speedometer
+IMPL_HUD_OFFSET(posi); // Position in race
+IMPL_HUD_OFFSET(wheel); // RA Wheel
+IMPL_HUD_OFFSET(face); // Mini rankings
+IMPL_HUD_OFFSET(stcd); // Starting countdown
+IMPL_HUD_OFFSET_Y(chek); // Check gfx
+IMPL_HUD_OFFSET(mini); // Minimap
+IMPL_HUD_OFFSET(want); // Wanted
+IMPL_HUD_OFFSET(stat); // Stats
+
+#undef IMPL_HUD_OFFSET
+#undef IMPL_HUD_OFFSET_X
+#undef IMPL_HUD_OFFSET_Y
+
+// extra hud things
+consvar_t cv_showstats = {"showstats", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_highresportrait = {"highresportrait", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // make char potraits use their high-res version instead
+
+CV_PossibleValue_t inputdisplay_cons_t[NUMINPUTDISPLAYSTUFF];
+consvar_t cv_showinput = {"showinput", "Off", CV_SAVE, inputdisplay_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t minihead_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Others"}, {0, NULL}};
+consvar_t cv_minihead = {"smallminimapplayers", "Off", CV_SAVE, minihead_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_showminimapnames = {"showminimapnames", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+CV_PossibleValue_t minimapdot_cons_t[NUMMINIMAPDOTSTUFF];
+consvar_t cv_showminimapangle = {"showminimapangle", "Off", CV_SAVE, minimapdot_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_posanim = {"postitionanimation", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_smallposnum = {"smallpositionnumber", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_showlapemblem = {"showlapemblem", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t huditemamount_cons_t[] = {{0, "Vanilla"}, {1, "Multiple"}, {2, "Always"},{0, NULL}};
+consvar_t cv_huditemamount = {"showitemamountnumber", "Vanilla", CV_SAVE, huditemamount_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_fancyroulette = {"animatedroulette", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_darkitembox = {"darkitembox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // itembox gets a dark border with specific items
+consvar_t cv_multiitemicon = {"multiitemicon", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_showlaptimes = {"showlaptimes", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+consvar_t cv_biglaps = {"biglaphud", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // here for ppl who dont want to make 2 more patches for their custom hud
+
+// Speedometer
+CV_PossibleValue_t speedo_cons_t[NUMSPEEDOSTUFF];
+consvar_t cv_newspeedometer = {"newspeedometer", "Default", CV_SAVE, speedo_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_battlespeedo = {"battlespeedo", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // toggle for showing the speedometer in battlemode
+
+// Colourized HUD
+consvar_t cv_colorizedhud = {"colorizedhud", "Off", CV_SAVE|CV_CALL, CV_OnOff, SaturnHud_menu_Onchange, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_colorizeditembox = {"colorizeditembox", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+static CV_PossibleValue_t HudColor_cons_t[MAXSKINCOLORS+1];
+consvar_t cv_colorizedhudcolor = {"colorizedhudcolor", "Skin Color", CV_SAVE, HudColor_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+// Driftgauge
+static CV_PossibleValue_t driftgaugeoffset_cons_t[] = {
+ {-FRACUNIT*128, "MIN"}, {FRACUNIT*128, "MAX"}, {0, NULL}};
+CV_PossibleValue_t driftgaugestyle_cons_t[NUMDGAUGESTUFF];
+
+consvar_t cv_driftgauge = {"kartdriftgauge", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_driftgaugeofs = {"kartdriftgaugeoffset", "-20", CV_FLOAT|CV_SAVE, driftgaugeoffset_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_driftgaugetrans = {"kartdriftgaugetransparency", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_driftgaugestyle = {"kartdriftgaugestyle", "1", CV_SAVE, driftgaugestyle_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+// Nametags
+static CV_PossibleValue_t nametagtrans_cons_t[] = {
+ {0, "Never"}, {1, "Far only"}, {2, "Dynamic"}, {3, "Always"}, {4, "HUD Trans."}, {0, NULL}};
+static CV_PossibleValue_t nametagdistance_cons_t[] = {
+ {0, "MIN"}, {640, "MAX"}, {0, NULL}};
+static CV_PossibleValue_t nametagmaxplayer_cons_t[] = {
+ {1, "MIN"}, {MAXPLAYERS, "MAX"}, {0, NULL}};
+static CV_PossibleValue_t nametagsize_cons_t[] = {
+ {0, "Off"}, {1, "Small"}, {2, "Minimal"}, {0, NULL}};
+static CV_PossibleValue_t nametagrestat_cons_t[] = {
+ {0, "Off"}, {1, "Restat"}, {2, "Always"}, {0, NULL}};
+
+consvar_t cv_nametag = {"kartnametag", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagtrans = {"kartnametagtransparency", "Dynamic", CV_SAVE, nametagtrans_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagfacerank = {"kartnametagfacerank", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagrestat = {"kartnametagrestat", "Restat", CV_SAVE, nametagrestat_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagdist = {"kartnametagdist", "320", CV_SAVE, nametagdistance_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagmaxplayers = {"kartnametagmaxplayers", "3", CV_SAVE, nametagmaxplayer_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagmaxlenght = {"kartnametagmaxlenght", "12", CV_SAVE, CV_Unsigned, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_showownnametag = {"kartnametagshowown", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_smallnametags = {"kartnametagsmall", "Off", CV_SAVE, nametagsize_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_nametagscore = {"kartnametagscore", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
+consvar_t cv_shownametagspectator = {"kartshownametagspectator", "No", CV_SAVE, CV_YesNo, NULL, 0, NULL, NULL, 0, 0, NULL};
+
+// Registers kart client commands and variables.
+// Nothing needed for a dedicated server should be registered here.
+void K_RegisterKartHudStuff(void)
+{
+ HudColor_cons_t[0].value = 0;
+ HudColor_cons_t[0].strvalue = "Skin Color";
+
+ for (INT32 i = 1; i < MAXSKINCOLORS; i++)
+ {
+ HudColor_cons_t[i].value = i;
+ HudColor_cons_t[i].strvalue = KartColor_Names[i]; // SRB2kart
+ }
+ HudColor_cons_t[MAXSKINCOLORS].value = 0;
+ HudColor_cons_t[MAXSKINCOLORS].strvalue = NULL;
+
+#define REG_HUD_OFFSET_X(name)\
+ CV_RegisterVar(&cv_##name##_xoffset);
+
+#define REG_HUD_OFFSET_Y(name)\
+ CV_RegisterVar(&cv_##name##_yoffset);
+
+#define REG_HUD_OFFSET(name)\
+ REG_HUD_OFFSET_X(name)\
+ REG_HUD_OFFSET_Y(name)
+
+ REG_HUD_OFFSET(item); // Item box
+ REG_HUD_OFFSET(time); // Time
+ REG_HUD_OFFSET(laps); // Number of laps
+ REG_HUD_OFFSET(dnft); // Countdown (did not finish timer)
+ REG_HUD_OFFSET(speed); // Speedometer
+ REG_HUD_OFFSET(posi); // Position in race
+ REG_HUD_OFFSET(wheel); // Position in race
+ REG_HUD_OFFSET(face); // Mini rankings
+ REG_HUD_OFFSET(stcd); // Starting countdown
+ REG_HUD_OFFSET_Y(chek); // Check gfx
+ REG_HUD_OFFSET(mini); // Minimap
+ REG_HUD_OFFSET(want); // Wanted
+ REG_HUD_OFFSET(stat); // Stats
+
+#undef REG_HUD_OFFSET
+#undef REG_HUD_OFFSET_X
+#undef REG_HUD_OFFSET_Y
+
+ CV_RegisterVar(&cv_kartminimap);
+ CV_RegisterVar(&cv_kartcheck);
+
+ CV_RegisterVar(&cv_kartspeedometer);
+
+ CV_RegisterVar(&cv_showstats);
+ CV_RegisterVar(&cv_showinput);
+
+ CV_RegisterVar(&cv_posanim);
+ CV_RegisterVar(&cv_smallposnum);
+
+ CV_RegisterVar(&cv_fancyroulette);
+
+ CV_RegisterVar(&cv_showlaptimes);
+ CV_RegisterVar(&cv_newspeedometer);
+
+ CV_RegisterVar(&cv_battlespeedo);
+
+ CV_RegisterVar(&cv_minihead);
+ CV_RegisterVar(&cv_showminimapnames);
+ CV_RegisterVar(&cv_showminimapangle);
+
+ CV_RegisterVar(&cv_showlapemblem);
+
+ CV_RegisterVar(&cv_stagetitle);
+
+ // Colourized HUD
+ CV_RegisterVar(&cv_colorizedhud);
+ CV_RegisterVar(&cv_colorizedhudcolor);
+ CV_RegisterVar(&cv_colorizeditembox);
+
+ CV_RegisterVar(&cv_biglaps);
+
+ CV_RegisterVar(&cv_darkitembox);
+
+ CV_RegisterVar(&cv_multiitemicon);
+ CV_RegisterVar(&cv_huditemamount);
+
+ CV_RegisterVar(&cv_highresportrait);
+
+ CV_RegisterVar(&cv_nametag);
+ CV_RegisterVar(&cv_nametagtrans);
+ CV_RegisterVar(&cv_nametagfacerank);
+ CV_RegisterVar(&cv_nametagmaxplayers);
+ CV_RegisterVar(&cv_nametagmaxlenght);
+ CV_RegisterVar(&cv_nametagdist);
+ CV_RegisterVar(&cv_showownnametag);
+ CV_RegisterVar(&cv_smallnametags);
+ CV_RegisterVar(&cv_nametagrestat);
+ CV_RegisterVar(&cv_nametagscore);
+ CV_RegisterVar(&cv_shownametagspectator);
+
+ CV_RegisterVar(&cv_driftgauge);
+ CV_RegisterVar(&cv_driftgaugeofs);
+ CV_RegisterVar(&cv_driftgaugetrans);
+ CV_RegisterVar(&cv_driftgaugestyle);
+
+ CV_RegisterVar(&cv_lessflicker);
+}
+
+//{ Patch Definitions
+
+// --Saturn patches--
+// dont leave those unitialized incase we missed a check somewhere
+
+// -Speedometers-
+
+// Smol speedo
+static patch_t *skp_smallsticker = NULL;
+static patch_t *skp_smallsticker3 = NULL;
+
+static patch_t *skp_speedpatches[5] = {NULL};
+
+// Achii speedo
+static patch_t *skp_smallstickerachi = NULL;
+static patch_t *skp_speedpatchesachi[5] = {NULL};
+static patch_t *skp_smallstickerachiclr = NULL;
+static patch_t *skp_speedpatchesachiclr[5] = {NULL};
+
+// Kartz speedo
+static patch_t *kp_kartzspeedo[25] = {NULL};
+static patch_t *kp_kartzspeedo_smol[25] = {NULL};
+
+// dial speedometer
+static patch_t *skp_rankfinish = NULL;
+static patch_t *skp_dialbase[2] = {NULL};
+static patch_t *skp_speedpatchesdial[5] = {NULL};
+static patch_t *skp_dialnum[10] = {NULL};
+//static patch_t *skp_dialclr = NULL;
+static patch_t *skp_dialbaseclr[2] = {NULL};
+static patch_t *skp_speedpatchesdialclr[5] = {NULL};
+static patch_t *skp_dialnumclr[10] = {NULL};
+
+// -Colourized hud-
+
+static patch_t *kp_timestickerclr = NULL;
+static patch_t *kp_timestickerwideclr = NULL;
+static patch_t *kp_lapstickerclr = NULL;
+static patch_t *kp_lapstickerbigclr = NULL;
+static patch_t *kp_lapstickerbig2clr = NULL;
+static patch_t *kp_lapstickerwideclr = NULL;
+//static patch_t *kp_lapstickernarrowclr = NULL;
+static patch_t *kp_bumperstickerclr = NULL;
+static patch_t *kp_bumperstickerwideclr = NULL;
+static patch_t *kp_karmastickerclr = NULL;
+static patch_t *kp_timeoutstickerclr = NULL;
+static patch_t *skp_smallstickerclr = NULL;
+static patch_t *skp_smallstickerclr3 = NULL;
+static patch_t *kp_itemmulstickerclr[2] = {NULL};
+static patch_t *kp_itembgclr[4] = {NULL};
+
+// -Misc.-
+
+static patch_t *kp_lapstickerbig = NULL;
+static patch_t *kp_lapstickerbig2 = NULL;
+
+static patch_t *nametagpic = NULL;
+static patch_t *nametagline = NULL;
+static patch_t *nametagspeed = NULL;
+static patch_t *nametagweight = NULL;
+
+static patch_t *driftgauge = NULL;
+static patch_t *driftgaugecolor = NULL;
+static patch_t *driftgaugesmall = NULL;
+static patch_t *driftgaugesmallcolor = NULL;
+
+static patch_t *kp_minimapdot = NULL;
+
+static patch_t *joybacking = NULL;
+static patch_t *joyknob = NULL;
+static patch_t *joyshadow = NULL;
+
+static patch_t *kp_multjawz = NULL;
+static patch_t *kp_multsneaker[2] = {NULL};
+static patch_t *kp_multbanana[3] = {NULL};
+
+static void K_LoadSaturnHUDGraphics(void)
+{
+ INT32 i;
+ char buffer[9];
+
+ if (found_extra_kart)
+ {
+ if (xtra_speedo) // smol speedometer
+ {
+ skp_smallsticker = (patch_t *)W_CachePatchName("SP_SMSTC", PU_HUDGFX);
+ skp_speedpatches[0] = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd
+ skp_speedpatches[1] = (patch_t *)W_CachePatchName("SP_MKMH", PU_HUDGFX);
+ skp_speedpatches[2] = (patch_t *)W_CachePatchName("SP_MMPH", PU_HUDGFX);
+ skp_speedpatches[3] = (patch_t *)W_CachePatchName("SP_MFRAC", PU_HUDGFX);
+ skp_speedpatches[4] = (patch_t *)W_CachePatchName("SP_MPERC", PU_HUDGFX);
+ }
+
+ if (achi_speedo)
+ {
+ skp_smallstickerachi = (patch_t *)W_CachePatchName("SP_AMSTC", PU_HUDGFX);
+ skp_speedpatchesachi[0] = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd
+ skp_speedpatchesachi[1] = (patch_t *)W_CachePatchName("SP_AKMH", PU_HUDGFX);
+ skp_speedpatchesachi[2] = (patch_t *)W_CachePatchName("SP_AMPH", PU_HUDGFX);
+ skp_speedpatchesachi[3] = (patch_t *)W_CachePatchName("SP_AFRAC", PU_HUDGFX);
+ skp_speedpatchesachi[4] = (patch_t *)W_CachePatchName("SP_APERC", PU_HUDGFX);
+ }
+
+ if (dial_speedo)
+ {
+ skp_rankfinish = (patch_t *)W_CachePatchName("RANKFIN", PU_HUDGFX);
+ skp_dialbase[0] = (patch_t *)W_CachePatchName("K_DSPBS1", PU_HUDGFX);
+ skp_dialbase[1] = (patch_t *)W_CachePatchName("K_DSPBS2", PU_HUDGFX);
+
+ skp_speedpatchesdial[0] = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd
+ skp_speedpatchesdial[1] = (patch_t *)W_CachePatchName("SP_DKMH", PU_HUDGFX);
+ skp_speedpatchesdial[2] = (patch_t *)W_CachePatchName("SP_DMPH", PU_HUDGFX);
+ skp_speedpatchesdial[3] = (patch_t *)W_CachePatchName("SP_DFRAC", PU_HUDGFX);
+ skp_speedpatchesdial[4] = (patch_t *)W_CachePatchName("SP_DPERC", PU_HUDGFX);
+
+ sprintf(buffer, "K_DSPNMx");
+ for (i = 0; i < 10; i++)
+ {
+ buffer[7] = '0'+(i%10);
+ skp_dialnum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+ }
+
+ // KartZ speedo
+ if (kartz_speedo)
+ {
+ const char* patchNames[] = {
+ "K_KZSP1", "K_KZSP2", "K_KZSP3", "K_KZSP4", "K_KZSP5",
+ "K_KZSP6", "K_KZSP7", "K_KZSP8", "K_KZSP9", "K_KZSP10",
+ "K_KZSP11", "K_KZSP12", "K_KZSP13", "K_KZSP14", "K_KZSP15",
+ "K_KZSP16", "K_KZSP17", "K_KZSP18", "K_KZSP19", "K_KZSP20",
+ "K_KZSP21", "K_KZSP22", "K_KZSP23", "K_KZSP24", "K_KZSP25"
+ };
+
+ for (size_t m = 0; m < sizeof(patchNames) / sizeof(patchNames[0]); ++m)
+ {
+ kp_kartzspeedo[m] = (patch_t *)W_CachePatchName(patchNames[m], PU_HUDGFX);
+ }
+ }
+
+ if (kartz_speedo_smol)
+ {
+ const char* patchNames[] = {
+ "K_KZSS1", "K_KZSS2", "K_KZSS3", "K_KZSS4", "K_KZSS5",
+ "K_KZSS6", "K_KZSS7", "K_KZSS8", "K_KZSS9", "K_KZSS10",
+ "K_KZSS11", "K_KZSS12", "K_KZSS13", "K_KZSS14", "K_KZSS15",
+ "K_KZSS16", "K_KZSS17", "K_KZSS18", "K_KZSS19", "K_KZSS20",
+ "K_KZSS21", "K_KZSS22", "K_KZSS23", "K_KZSS24", "K_KZSS25"
+ };
+
+ for (size_t m = 0; m < sizeof(patchNames) / sizeof(patchNames[0]); ++m)
+ {
+ kp_kartzspeedo_smol[m] = (patch_t *)W_CachePatchName(patchNames[m], PU_HUDGFX);
+ }
+ }
+
+ if (big_lap)
+ {
+ kp_lapstickerbig = (patch_t *)W_CachePatchName("K_STLAPB", PU_HUDGFX);
+ kp_lapstickerbig2 = (patch_t *)W_CachePatchName("K_STLA2B", PU_HUDGFX);
+ }
+
+ // Nametags
+ if (nametaggfx)
+ {
+ nametagpic = (patch_t *)W_CachePatchName("NTLINE", PU_HUDGFX);
+ nametagline = (patch_t *)W_CachePatchName("NTLINEV", PU_HUDGFX);
+ nametagspeed = (patch_t *)W_CachePatchName("NTSP", PU_HUDGFX);
+ nametagweight = (patch_t *)W_CachePatchName("NTWH", PU_HUDGFX);
+ }
+
+ if (driftgaugegfx)
+ {
+ driftgauge = (patch_t *)W_CachePatchName("K_DGAU", PU_HUDGFX);
+ driftgaugesmall = (patch_t *)W_CachePatchName("K_DGSU", PU_HUDGFX);
+
+ if (driftgaugegfx_clr)
+ {
+ driftgaugecolor = (patch_t *)W_CachePatchName("K_DCAU", PU_HUDGFX);
+ driftgaugesmallcolor = (patch_t *)W_CachePatchName("K_DCSU", PU_HUDGFX);
+ }
+ }
+
+ if (joystickicon)
+ {
+ joybacking = (patch_t *)W_CachePatchName("JOYBCK", PU_HUDGFX);
+ joyknob = (patch_t *)W_CachePatchName("JOYKNB", PU_HUDGFX);
+ joyshadow = (patch_t *)W_CachePatchName("JOYSHD", PU_HUDGFX);
+ }
+
+ if (minidoticon)
+ {
+ kp_minimapdot = (patch_t *)W_CachePatchName("MMAPDOT", PU_HUDGFX);
+ }
+
+ if (multiitem_icon)
+ {
+ kp_multsneaker[0] = (patch_t *)W_CachePatchName("K_ITSHO2", PU_HUDGFX);
+ kp_multsneaker[1] = (patch_t *)W_CachePatchName("K_ITSHO3", PU_HUDGFX);
+ kp_multbanana[0] = (patch_t *)W_CachePatchName("K_ITBAN2", PU_HUDGFX);
+ kp_multbanana[1] = (patch_t *)W_CachePatchName("K_ITBAN3", PU_HUDGFX);
+ kp_multbanana[2] = (patch_t *)W_CachePatchName("K_ITBAN4", PU_HUDGFX);
+ kp_multjawz = (patch_t *)W_CachePatchName("K_ITJAW2", PU_HUDGFX);
+ }
+ }
+
+ if (found_extra2_kart)
+ {
+ if (xtra_speedo_clr)
+ {
+ skp_smallstickerclr = (patch_t *)W_CachePatchName("SC_SMSTC", PU_HUDGFX);
+ }
+
+ if (xtra_speedo_clr3)
+ {
+ skp_smallstickerclr3 = (patch_t *)W_CachePatchName("SC_SM3TC", PU_HUDGFX);
+ }
+
+ if (achi_speedo_clr)
+ {
+ skp_smallstickerachiclr = (patch_t *)W_CachePatchName("SC_AMSTC", PU_HUDGFX);
+ skp_speedpatchesachiclr[0] = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd
+ skp_speedpatchesachiclr[1] = (patch_t *)W_CachePatchName("SC_AKMH", PU_HUDGFX);
+ skp_speedpatchesachiclr[2] = (patch_t *)W_CachePatchName("SC_AMPH", PU_HUDGFX);
+ skp_speedpatchesachiclr[3] = (patch_t *)W_CachePatchName("SC_AFRAC", PU_HUDGFX);
+ skp_speedpatchesachiclr[4] = (patch_t *)W_CachePatchName("SC_APERC", PU_HUDGFX);
+ }
+
+ if (dial_speedo_clr)
+ {
+ skp_dialbaseclr[0] = (patch_t *)W_CachePatchName("K_DSPBC1", PU_HUDGFX);
+ skp_dialbaseclr[1] = (patch_t *)W_CachePatchName("K_DSPBC2", PU_HUDGFX);
+
+ skp_speedpatchesdialclr[0] = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX); // lolxd
+ skp_speedpatchesdialclr[1] = (patch_t *)W_CachePatchName("SC_DKMH", PU_HUDGFX);
+ skp_speedpatchesdialclr[2] = (patch_t *)W_CachePatchName("SC_DMPH", PU_HUDGFX);
+ skp_speedpatchesdialclr[3] = (patch_t *)W_CachePatchName("SC_DFRAC", PU_HUDGFX);
+ skp_speedpatchesdialclr[4] = (patch_t *)W_CachePatchName("SC_DPERC", PU_HUDGFX);
+
+ sprintf(buffer, "K_DSPNCx");
+ for (i = 0; i < 10; i++)
+ {
+ buffer[7] = '0'+(i%10);
+ skp_dialnumclr[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+ }
+
+ if (big_lap_color)
+ {
+ kp_lapstickerbigclr = (patch_t *)W_CachePatchName("K_SCLAPB", PU_HUDGFX);
+ kp_lapstickerbig2clr = (patch_t *)W_CachePatchName("K_SCLA2B", PU_HUDGFX);
+ }
+
+ // Colourized hud
+ if (clr_hud)
+ {
+ kp_timestickerclr = (patch_t *)W_CachePatchName("K_SCTIME", PU_HUDGFX);
+ kp_timestickerwideclr = (patch_t *)W_CachePatchName("K_SCTIMW", PU_HUDGFX);
+ kp_lapstickerclr = (patch_t *)W_CachePatchName("K_SCLAPS", PU_HUDGFX);
+ kp_lapstickerwideclr = (patch_t *)W_CachePatchName("K_SCLAPW", PU_HUDGFX);
+ kp_bumperstickerclr = (patch_t *)W_CachePatchName("K_SCBALN", PU_HUDGFX);
+ kp_bumperstickerwideclr = (patch_t *)W_CachePatchName("K_SCBALW", PU_HUDGFX);
+ kp_karmastickerclr = (patch_t *)W_CachePatchName("K_SCKARM", PU_HUDGFX);
+ kp_timeoutstickerclr = (patch_t *)W_CachePatchName("K_SCTOUT", PU_HUDGFX);
+ kp_itembgclr[0] = (patch_t *)W_CachePatchName("K_ITBC" , PU_HUDGFX);
+ kp_itembgclr[1] = (patch_t *)W_CachePatchName("K_ITBCD" , PU_HUDGFX);
+ kp_itembgclr[2] = (patch_t *)W_CachePatchName("K_ISBC" , PU_HUDGFX);
+ kp_itembgclr[3] = (patch_t *)W_CachePatchName("K_ISBCD" , PU_HUDGFX);
+ kp_itemmulstickerclr[1] = (patch_t *)W_CachePatchName("K_ISMULC", PU_HUDGFX);
+ kp_itemmulstickerclr[0] = (patch_t *)W_CachePatchName("K_ITMULC", PU_HUDGFX);
+ }
+ }
+
+ if (found_extra3_kart)
+ {
+ if (xtra_speedo3) // 80x11 patch scaled to size
+ {
+ skp_smallsticker3 = (patch_t *)W_CachePatchName("SP_SM3TC", PU_HUDGFX);
+ }
+ }
+}
+
+// -- Kart patches --
+
+#define NUMPOSNUMS 10
+#define NUMPOSFRAMES 7 // White, three blues, three reds
+#define NUMWINFRAMES 6 // Red, yellow, green, cyan, blue, purple
+
+static patch_t *kp_nodraw;
+static patch_t *kp_timesticker;
+static patch_t *kp_timestickerwide;
+static patch_t *kp_lapsticker;
+static patch_t *kp_lapstickerwide;
+//static patch_t *kp_lapstickernarrow;
+static patch_t *kp_splitlapflag;
+static patch_t *kp_bumpersticker;
+static patch_t *kp_bumperstickerwide;
+static patch_t *kp_karmasticker;
+static patch_t *kp_splitkarmabomb;
+static patch_t *kp_timeoutsticker;
+
+static patch_t *kp_startcountdown[16];
+static patch_t *kp_racefinish[6];
+
+static patch_t *kp_positionnum[NUMPOSNUMS][NUMPOSFRAMES];
+static patch_t *kp_winnernum[NUMPOSFRAMES];
+
+static patch_t *kp_facenum[MAXPLAYERS+1];
+static patch_t *kp_facehighlight[8];
+
+static patch_t *kp_rankbumper;
+static patch_t *kp_tinybumper[2];
+static patch_t *kp_ranknobumpers;
+
+static patch_t *kp_battlewin;
+static patch_t *kp_battlecool;
+static patch_t *kp_battlelose;
+static patch_t *kp_battlewait;
+static patch_t *kp_battleinfo;
+static patch_t *kp_wanted;
+static patch_t *kp_wantedsplit;
+static patch_t *kp_wantedreticle;
+
+static patch_t *kp_itembg[4];
+static patch_t *kp_itemtimer[2];
+static patch_t *kp_itemmulsticker[2];
+static patch_t *kp_itemx;
+
+static patch_t *kp_sneaker[2];
+static patch_t *kp_rocketsneaker[2];
+static patch_t *kp_invincibility[13];
+static patch_t *kp_banana[2];
+static patch_t *kp_eggman[2];
+static patch_t *kp_orbinaut[5];
+static patch_t *kp_jawz[2];
+static patch_t *kp_mine[2];
+static patch_t *kp_ballhog[2];
+static patch_t *kp_selfpropelledbomb[2];
+static patch_t *kp_grow[2];
+static patch_t *kp_shrink[2];
+static patch_t *kp_thundershield[2];
+static patch_t *kp_hyudoro[2];
+static patch_t *kp_pogospring[2];
+static patch_t *kp_kitchensink[2];
+static patch_t *kp_sadface[2];
+
+static patch_t *kp_check[6];
+
+static patch_t *kp_eggnum[4];
+
+static patch_t *kp_fpview[3];
+static patch_t *kp_inputwheel[5];
+
+static patch_t *kp_challenger[25];
+
+static patch_t *kp_lapanim_lap[7];
+static patch_t *kp_lapanim_final[11];
+static patch_t *kp_lapanim_number[10][3];
+static patch_t *kp_lapanim_emblem[2];
+static patch_t *kp_lapanim_hand[3];
+
+static patch_t *kp_yougotem;
+
+void K_LoadKartHUDGraphics(void)
+{
+ INT32 i, j;
+ char buffer[9];
+
+ // Null Stuff
+ kp_nodraw = (patch_t *)W_CachePatchName("K_TRNULL", PU_HUDGFX);
+
+ // Stickers
+ kp_timesticker = (patch_t *)W_CachePatchName("K_STTIME", PU_HUDGFX);
+ kp_timestickerwide = (patch_t *)W_CachePatchName("K_STTIMW", PU_HUDGFX);
+ kp_lapsticker = (patch_t *)W_CachePatchName("K_STLAPS", PU_HUDGFX);
+ kp_lapstickerwide = (patch_t *)W_CachePatchName("K_STLAPW", PU_HUDGFX);
+ //kp_lapstickernarrow = (patch_t *)W_CachePatchName("K_STLAPN", PU_HUDGFX);
+ kp_splitlapflag = (patch_t *)W_CachePatchName("K_SPTLAP", PU_HUDGFX);
+ kp_bumpersticker = (patch_t *)W_CachePatchName("K_STBALN", PU_HUDGFX);
+ kp_bumperstickerwide = (patch_t *)W_CachePatchName("K_STBALW", PU_HUDGFX);
+ kp_karmasticker = (patch_t *)W_CachePatchName("K_STKARM", PU_HUDGFX);
+ kp_splitkarmabomb = (patch_t *)W_CachePatchName("K_SPTKRM", PU_HUDGFX);
+ kp_timeoutsticker = (patch_t *)W_CachePatchName("K_STTOUT", PU_HUDGFX);
+
+ // Starting countdown
+ kp_startcountdown[0] = (patch_t *)W_CachePatchName("K_CNT3A", PU_HUDGFX);
+ kp_startcountdown[1] = (patch_t *)W_CachePatchName("K_CNT2A", PU_HUDGFX);
+ kp_startcountdown[2] = (patch_t *)W_CachePatchName("K_CNT1A", PU_HUDGFX);
+ kp_startcountdown[3] = (patch_t *)W_CachePatchName("K_CNTGOA", PU_HUDGFX);
+ kp_startcountdown[4] = (patch_t *)W_CachePatchName("K_CNT3B", PU_HUDGFX);
+ kp_startcountdown[5] = (patch_t *)W_CachePatchName("K_CNT2B", PU_HUDGFX);
+ kp_startcountdown[6] = (patch_t *)W_CachePatchName("K_CNT1B", PU_HUDGFX);
+ kp_startcountdown[7] = (patch_t *)W_CachePatchName("K_CNTGOB", PU_HUDGFX);
+
+ // Splitscreen
+ kp_startcountdown[8] = (patch_t *)W_CachePatchName("K_SMC3A", PU_HUDGFX);
+ kp_startcountdown[9] = (patch_t *)W_CachePatchName("K_SMC2A", PU_HUDGFX);
+ kp_startcountdown[10] = (patch_t *)W_CachePatchName("K_SMC1A", PU_HUDGFX);
+ kp_startcountdown[11] = (patch_t *)W_CachePatchName("K_SMCGOA", PU_HUDGFX);
+ kp_startcountdown[12] = (patch_t *)W_CachePatchName("K_SMC3B", PU_HUDGFX);
+ kp_startcountdown[13] = (patch_t *)W_CachePatchName("K_SMC2B", PU_HUDGFX);
+ kp_startcountdown[14] = (patch_t *)W_CachePatchName("K_SMC1B", PU_HUDGFX);
+ kp_startcountdown[15] = (patch_t *)W_CachePatchName("K_SMCGOB", PU_HUDGFX);
+
+ // Finish
+ kp_racefinish[0] = (patch_t *)W_CachePatchName("K_FINA", PU_HUDGFX);
+ kp_racefinish[1] = (patch_t *)W_CachePatchName("K_FINB", PU_HUDGFX);
+
+ // Splitscreen
+ kp_racefinish[2] = (patch_t *)W_CachePatchName("K_SMFINA", PU_HUDGFX);
+ kp_racefinish[3] = (patch_t *)W_CachePatchName("K_SMFINB", PU_HUDGFX);
+
+ // 2P splitscreen
+ kp_racefinish[4] = (patch_t *)W_CachePatchName("K_2PFINA", PU_HUDGFX);
+ kp_racefinish[5] = (patch_t *)W_CachePatchName("K_2PFINB", PU_HUDGFX);
+
+ // Position numbers
+ sprintf(buffer, "K_POSNxx");
+ for (i = 0; i < NUMPOSNUMS; i++)
+ {
+ buffer[6] = '0'+i;
+ for (j = 0; j < NUMPOSFRAMES; j++)
+ {
+ buffer[7] = '0'+j;
+ kp_positionnum[i][j] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+ }
+
+ sprintf(buffer, "K_POSNWx");
+ for (i = 0; i < NUMWINFRAMES; i++)
+ {
+ buffer[7] = '0'+i;
+ kp_winnernum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "OPPRNKxx");
+ for (i = 0; i <= MAXPLAYERS; i++)
+ {
+ buffer[6] = '0'+(i/10);
+ buffer[7] = '0'+(i%10);
+ kp_facenum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_CHILIx");
+ for (i = 0; i < 8; i++)
+ {
+ buffer[7] = '0'+(i+1);
+ kp_facehighlight[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // Extra ranking icons
+ kp_rankbumper = (patch_t *)W_CachePatchName("K_BLNICO", PU_HUDGFX);
+ kp_tinybumper[0] = (patch_t *)W_CachePatchName("K_BLNA", PU_HUDGFX);
+ kp_tinybumper[1] = (patch_t *)W_CachePatchName("K_BLNB", PU_HUDGFX);
+ kp_ranknobumpers = (patch_t *)W_CachePatchName("K_NOBLNS", PU_HUDGFX);
+
+ // Battle graphics
+ kp_battlewin = (patch_t *)W_CachePatchName("K_BWIN", PU_HUDGFX);
+ kp_battlecool = (patch_t *)W_CachePatchName("K_BCOOL", PU_HUDGFX);
+ kp_battlelose = (patch_t *)W_CachePatchName("K_BLOSE", PU_HUDGFX);
+ kp_battlewait = (patch_t *)W_CachePatchName("K_BWAIT", PU_HUDGFX);
+ kp_battleinfo = (patch_t *)W_CachePatchName("K_BINFO", PU_HUDGFX);
+ kp_wanted = (patch_t *)W_CachePatchName("K_WANTED", PU_HUDGFX);
+ kp_wantedsplit = (patch_t *)W_CachePatchName("4PWANTED", PU_HUDGFX);
+ kp_wantedreticle = (patch_t *)W_CachePatchName("MMAPWANT", PU_HUDGFX);
+
+ // Kart Item Windows
+ kp_itembg[0] = (patch_t *)W_CachePatchName("K_ITBG", PU_HUDGFX);
+ kp_itembg[1] = (patch_t *)W_CachePatchName("K_ITBGD", PU_HUDGFX);
+ kp_itemtimer[0] = (patch_t *)W_CachePatchName("K_ITIMER", PU_HUDGFX);
+ kp_itemmulsticker[0] = (patch_t *)W_CachePatchName("K_ITMUL", PU_HUDGFX);
+ kp_itemx = (patch_t *)W_CachePatchName("K_ITX", PU_HUDGFX);
+ // Splitscreen
+ kp_itembg[2] = (patch_t *)W_CachePatchName("K_ISBG", PU_HUDGFX);
+ kp_itembg[3] = (patch_t *)W_CachePatchName("K_ISBGD", PU_HUDGFX);
+ kp_itemtimer[1] = (patch_t *)W_CachePatchName("K_ISIMER", PU_HUDGFX);
+ kp_itemmulsticker[1] = (patch_t *)W_CachePatchName("K_ISMUL", PU_HUDGFX);
+
+ // Kart Items
+ kp_sneaker[0] = (patch_t *)W_CachePatchName("K_ITSHOE", PU_HUDGFX);
+ kp_rocketsneaker[0] = (patch_t *)W_CachePatchName("K_ITRSHE", PU_HUDGFX);
+ kp_banana[0] = (patch_t *)W_CachePatchName("K_ITBANA", PU_HUDGFX);
+ kp_eggman[0] = (patch_t *)W_CachePatchName("K_ITEGGM", PU_HUDGFX);
+ kp_jawz[0] = (patch_t *)W_CachePatchName("K_ITJAWZ", PU_HUDGFX);
+ kp_mine[0] = (patch_t *)W_CachePatchName("K_ITMINE", PU_HUDGFX);
+ kp_ballhog[0] = (patch_t *)W_CachePatchName("K_ITBHOG", PU_HUDGFX);
+ kp_selfpropelledbomb[0] = (patch_t *)W_CachePatchName("K_ITSPB", PU_HUDGFX);
+ kp_grow[0] = (patch_t *)W_CachePatchName("K_ITGROW", PU_HUDGFX);
+ kp_shrink[0] = (patch_t *)W_CachePatchName("K_ITSHRK", PU_HUDGFX);
+ kp_thundershield[0] = (patch_t *)W_CachePatchName("K_ITTHNS", PU_HUDGFX);
+ kp_hyudoro[0] = (patch_t *)W_CachePatchName("K_ITHYUD", PU_HUDGFX);
+ kp_pogospring[0] = (patch_t *)W_CachePatchName("K_ITPOGO", PU_HUDGFX);
+ kp_kitchensink[0] = (patch_t *)W_CachePatchName("K_ITSINK", PU_HUDGFX);
+ kp_sadface[0] = (patch_t *)W_CachePatchName("K_ITSAD", PU_HUDGFX);
+ // Splitscreen
+ kp_sneaker[1] = (patch_t *)W_CachePatchName("K_ISSHOE", PU_HUDGFX);
+ kp_rocketsneaker[1] = (patch_t *)W_CachePatchName("K_ISRSHE", PU_HUDGFX);
+ kp_banana[1] = (patch_t *)W_CachePatchName("K_ISBANA", PU_HUDGFX);
+ kp_eggman[1] = (patch_t *)W_CachePatchName("K_ISEGGM", PU_HUDGFX);
+ kp_orbinaut[4] = (patch_t *)W_CachePatchName("K_ISORBN", PU_HUDGFX);
+ kp_jawz[1] = (patch_t *)W_CachePatchName("K_ISJAWZ", PU_HUDGFX);
+ kp_mine[1] = (patch_t *)W_CachePatchName("K_ISMINE", PU_HUDGFX);
+ kp_ballhog[1] = (patch_t *)W_CachePatchName("K_ISBHOG", PU_HUDGFX);
+ kp_selfpropelledbomb[1] = (patch_t *)W_CachePatchName("K_ISSPB", PU_HUDGFX);
+ kp_grow[1] = (patch_t *)W_CachePatchName("K_ISGROW", PU_HUDGFX);
+ kp_shrink[1] = (patch_t *)W_CachePatchName("K_ISSHRK", PU_HUDGFX);
+ kp_thundershield[1] = (patch_t *)W_CachePatchName("K_ISTHNS", PU_HUDGFX);
+ kp_hyudoro[1] = (patch_t *)W_CachePatchName("K_ISHYUD", PU_HUDGFX);
+ kp_pogospring[1] = (patch_t *)W_CachePatchName("K_ISPOGO", PU_HUDGFX);
+ kp_kitchensink[1] = (patch_t *)W_CachePatchName("K_ISSINK", PU_HUDGFX);
+ kp_sadface[1] = (patch_t *)W_CachePatchName("K_ISSAD", PU_HUDGFX);
+
+ sprintf(buffer, "K_ITINVx");
+ for (i = 0; i < 7; i++)
+ {
+ buffer[7] = '1'+i;
+ kp_invincibility[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_ITORBx");
+ for (i = 0; i < 4; i++)
+ {
+ buffer[7] = '1'+i;
+ kp_orbinaut[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_ISINVx");
+ for (i = 0; i < 6; i++)
+ {
+ buffer[7] = '1'+i;
+ kp_invincibility[i+7] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // CHECK indicators
+ sprintf(buffer, "K_CHECKx");
+ for (i = 0; i < 6; i++)
+ {
+ buffer[7] = '1'+i;
+ kp_check[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // Eggman warning numbers
+ sprintf(buffer, "K_EGGNx");
+ for (i = 0; i < 4; i++)
+ {
+ buffer[6] = '0'+i;
+ kp_eggnum[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // First person mode
+ kp_fpview[0] = (patch_t *)W_CachePatchName("VIEWA0", PU_HUDGFX);
+ kp_fpview[1] = (patch_t *)W_CachePatchName("VIEWB0D0", PU_HUDGFX);
+ kp_fpview[2] = (patch_t *)W_CachePatchName("VIEWC0E0", PU_HUDGFX);
+
+ // Input UI Wheel
+ sprintf(buffer, "K_WHEELx");
+ for (i = 0; i < 5; i++)
+ {
+ buffer[7] = '0'+i;
+ kp_inputwheel[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // HERE COMES A NEW CHALLENGER
+ sprintf(buffer, "K_CHALxx");
+ for (i = 0; i < 25; i++)
+ {
+ buffer[6] = '0'+((i+1)/10);
+ buffer[7] = '0'+((i+1)%10);
+ kp_challenger[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ // Lap start animation
+ sprintf(buffer, "K_LAP0x");
+ for (i = 0; i < 7; i++)
+ {
+ buffer[6] = '0'+(i+1);
+ kp_lapanim_lap[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_LAPFxx");
+ for (i = 0; i < 11; i++)
+ {
+ buffer[6] = '0'+((i+1)/10);
+ buffer[7] = '0'+((i+1)%10);
+ kp_lapanim_final[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_LAPNxx");
+ for (i = 0; i < 10; i++)
+ {
+ buffer[6] = '0'+i;
+ for (j = 0; j < 3; j++)
+ {
+ buffer[7] = '0'+(j+1);
+ kp_lapanim_number[i][j] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+ }
+
+ sprintf(buffer, "K_LAPE0x");
+ for (i = 0; i < 2; i++)
+ {
+ buffer[7] = '0'+(i+1);
+ kp_lapanim_emblem[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ sprintf(buffer, "K_LAPH0x");
+ for (i = 0; i < 3; i++)
+ {
+ buffer[7] = '0'+(i+1);
+ kp_lapanim_hand[i] = (patch_t *)W_CachePatchName(buffer, PU_HUDGFX);
+ }
+
+ kp_yougotem = (patch_t *)W_CachePatchName("YOUGOTEM", PU_HUDGFX);
+
+ if (found_extra_kart || found_extra2_kart || found_extra3_kart)
+ K_LoadSaturnHUDGraphics();
+}
+
+// For the item toggle menu
+const char *K_GetItemPatch(UINT8 item, boolean tiny)
+{
+ switch (item)
+ {
+ case KITEM_SNEAKER:
+ case KRITEM_TRIPLESNEAKER:
+ return (tiny ? "K_ISSHOE" : "K_ITSHOE");
+ case KITEM_ROCKETSNEAKER:
+ return (tiny ? "K_ISRSHE" : "K_ITRSHE");
+ case KITEM_INVINCIBILITY:
+ return (tiny ? "K_ISINV1" : "K_ITINV1");
+ case KITEM_BANANA:
+ case KRITEM_TRIPLEBANANA:
+ case KRITEM_TENFOLDBANANA:
+ return (tiny ? "K_ISBANA" : "K_ITBANA");
+ case KITEM_EGGMAN:
+ return (tiny ? "K_ISEGGM" : "K_ITEGGM");
+ case KITEM_ORBINAUT:
+ return (tiny ? "K_ISORBN" : "K_ITORB1");
+ case KITEM_JAWZ:
+ case KRITEM_DUALJAWZ:
+ return (tiny ? "K_ISJAWZ" : "K_ITJAWZ");
+ case KITEM_MINE:
+ return (tiny ? "K_ISMINE" : "K_ITMINE");
+ case KITEM_BALLHOG:
+ return (tiny ? "K_ISBHOG" : "K_ITBHOG");
+ case KITEM_SPB:
+ return (tiny ? "K_ISSPB" : "K_ITSPB");
+ case KITEM_GROW:
+ return (tiny ? "K_ISGROW" : "K_ITGROW");
+ case KITEM_SHRINK:
+ return (tiny ? "K_ISSHRK" : "K_ITSHRK");
+ case KITEM_THUNDERSHIELD:
+ return (tiny ? "K_ISTHNS" : "K_ITTHNS");
+ case KITEM_HYUDORO:
+ return (tiny ? "K_ISHYUD" : "K_ITHYUD");
+ case KITEM_POGOSPRING:
+ return (tiny ? "K_ISPOGO" : "K_ITPOGO");
+ case KITEM_KITCHENSINK:
+ return (tiny ? "K_ISSINK" : "K_ITSINK");
+ case KRITEM_TRIPLEORBINAUT:
+ return (tiny ? "K_ISORBN" : "K_ITORB3");
+ case KRITEM_QUADORBINAUT:
+ return (tiny ? "K_ISORBN" : "K_ITORB4");
+ default:
+ return (tiny ? "K_ISSAD" : "K_ITSAD");
+ }
+}
+
+//}
+
+INT32 ITEM_X, ITEM_Y; // Item Window
+INT32 TIME_X, TIME_Y; // Time Sticker
+INT32 LAPS_X, LAPS_Y; // Lap Sticker
+INT32 SPDM_X, SPDM_Y; // Speedometer
+INT32 POSI_X, POSI_Y; // Position Number
+INT32 FACE_X, FACE_Y; // Top-four Faces
+INT32 STCD_X, STCD_Y; // Starting countdown
+INT32 CHEK_Y; // CHECK graphic
+INT32 MINI_X, MINI_Y; // Minimap
+INT32 WANT_X, WANT_Y; // Battle WANTED poster
+
+// This is for the P2 and P4 side of splitscreen. Then we'll flip P1's and P2's to the bottom with V_SPLITSCREEN.
+INT32 ITEM2_X, ITEM2_Y;
+INT32 LAPS2_X, LAPS2_Y;
+INT32 POSI2_X, POSI2_Y;
+
+static void K_initKartHUD(void)
+{
+ /*
+ BASEVIDWIDTH = 320
+ BASEVIDHEIGHT = 200
+
+ Item window graphic is 41 x 33
+
+ Time Sticker graphic is 116 x 11
+ Time Font is a solid block of (8 x [12) x 14], equal to 96 x 14
+ Therefore, timestamp is 116 x 14 altogether
+
+ Lap Sticker is 80 x 11
+ Lap flag is 22 x 20
+ Lap Font is a solid block of (3 x [12) x 14], equal to 36 x 14
+ Therefore, lapstamp is 80 x 20 altogether
+
+ Position numbers are 43 x 53
+
+ Faces are 32 x 32
+ Faces draw downscaled at 16 x 16
+ Therefore, the allocated space for them is 16 x 67 altogether
+
+ ----
+
+ ORIGINAL CZ64 SPLITSCREEN:
+
+ Item window:
+ if (!splitscreen) { ICONX = 139; ICONY = 20; }
+ else { ICONX = BASEVIDWIDTH-315; ICONY = 60; }
+
+ Time: 236, STRINGY( 12)
+ Lap: BASEVIDWIDTH-304, STRINGY(BASEVIDHEIGHT-189)
+
+ */
+
+ // Single Screen (defaults)
+ // Item Window
+ ITEM_X = 5 + cv_item_xoffset.value; // 5
+ ITEM_Y = 5 + cv_item_yoffset.value; // 5
+ // Level Timer
+ TIME_X = BASEVIDWIDTH - 148 + cv_time_xoffset.value; // 172
+ TIME_Y = 9 + cv_time_yoffset.value; // 9
+ // Level Laps
+ LAPS_X = 9 + cv_laps_xoffset.value; // 9
+ LAPS_Y = BASEVIDHEIGHT - 29 + cv_laps_yoffset.value; // 171
+ // Speedometer
+ SPDM_X = 9 + cv_speed_xoffset.value; // 9
+ SPDM_Y = BASEVIDHEIGHT - 45 + cv_speed_yoffset.value; // 155
+ // Position Number
+ POSI_X = BASEVIDWIDTH - 9 + cv_posi_xoffset.value; // 268
+ POSI_Y = BASEVIDHEIGHT - 9 + cv_posi_yoffset.value; // 138
+ // Top-Four Faces
+ FACE_X = 9 + cv_face_xoffset.value; // 9
+ FACE_Y = 92 + cv_face_yoffset.value; // 92
+ // Starting countdown
+ STCD_X = BASEVIDWIDTH/2 + cv_stcd_xoffset.value; // 9
+ STCD_Y = BASEVIDHEIGHT/2 + cv_stcd_yoffset.value; // 92
+ // CHECK graphic
+ CHEK_Y = BASEVIDHEIGHT + cv_chek_yoffset.value; // 200
+ // Minimap
+ MINI_X = BASEVIDWIDTH - 50 + cv_mini_xoffset.value; // 270
+ MINI_Y = (BASEVIDHEIGHT/2)-16 + cv_mini_yoffset.value; // 84
+ // Battle WANTED poster
+ WANT_X = BASEVIDWIDTH - 55 + cv_want_xoffset.value; // 270
+ WANT_Y = BASEVIDHEIGHT- 71 + cv_want_yoffset.value; // 176
+
+ if (splitscreen) // Splitscreen
+ {
+ ITEM_X = 5;
+ ITEM_Y = 3;
+
+ LAPS_Y = (BASEVIDHEIGHT/2)-24;
+
+ POSI_Y = (BASEVIDHEIGHT/2)- 2;
+
+ STCD_Y = BASEVIDHEIGHT/4;
+
+ MINI_Y = (BASEVIDHEIGHT/2);
+
+ if (splitscreen > 1) // 3P/4P Small Splitscreen
+ {
+ // 1P (top left)
+ ITEM_X = -9;
+ ITEM_Y = -8;
+
+ LAPS_X = 3;
+ LAPS_Y = (BASEVIDHEIGHT/2)-13;
+
+ POSI_X = 24;
+ POSI_Y = (BASEVIDHEIGHT/2)- 16;
+
+ // 2P (top right)
+ ITEM2_X = BASEVIDWIDTH-39;
+ ITEM2_Y = -8;
+
+ LAPS2_X = BASEVIDWIDTH-3;
+ LAPS2_Y = (BASEVIDHEIGHT/2)-13;
+
+ POSI2_X = BASEVIDWIDTH -4;
+ POSI2_Y = (BASEVIDHEIGHT/2)- 16;
+
+ // Reminder that 3P and 4P are just 1P and 2P splitscreen'd to the bottom.
+
+ STCD_X = BASEVIDWIDTH/4;
+
+ MINI_X = (3*BASEVIDWIDTH/4);
+ MINI_Y = (3*BASEVIDHEIGHT/4);
+
+ if (splitscreen > 2) // 4P-only
+ {
+ MINI_X = (BASEVIDWIDTH/2);
+ MINI_Y = (BASEVIDHEIGHT/2);
+ }
+ }
+ }
+
+ if (timeinmap > 113 || forceshowhud)
+ hudtrans = cv_translucenthud.value;
+ else if (timeinmap > 105)
+ hudtrans = ((((INT32)timeinmap) - 105)*cv_translucenthud.value)/(113-105);
+ else
+ hudtrans = 0;
+
+ // K_GetScreenCoords needs the right view* variables
+ R_SetViewContext(stplyrnum);
+ R_InterpolateView(rendertimefrac_unpaused, !cv_uncappedhud.value);
+}
+
+UINT8 K_GetHudColor(void)
+{
+ if (cv_colorizedhud.value && cv_colorizedhudcolor.value)
+ return cv_colorizedhudcolor.value;
+
+ return ((stplyr && gamestate == GS_LEVEL) ? stplyr->skincolor : cv_playercolor.value);
+}
+
+boolean K_UseColorHud(void)
+{
+ return (cv_colorizedhud.value && clr_hud);
+}
+
+enum
+{
+ SPEEDO_VANILLA,
+ SPEEDO_EXTRA,
+ SPEEDO_ACHII,
+ SPEEDO_DIAL,
+ SPEEDO_PMETER,
+ SPEEDO_PMETERSMOL,
+ SPEEDO_EXTRA3,
+};
+
+static SINT8 K_GetSpeedometerStyle(void)
+{
+ if (cv_newspeedometer.value == 2 && xtra_speedo)
+ return SPEEDO_EXTRA;
+ else if (cv_newspeedometer.value == 3 && achi_speedo)
+ return SPEEDO_ACHII;
+ else if (cv_newspeedometer.value == 4 && dial_speedo)
+ return SPEEDO_DIAL;
+ else if (cv_newspeedometer.value == 5 && kartz_speedo)
+ return SPEEDO_PMETER;
+ else if (cv_newspeedometer.value == 6 && kartz_speedo_smol)
+ return SPEEDO_PMETERSMOL;
+ else if (cv_newspeedometer.value == 7 && xtra_speedo3)
+ return SPEEDO_EXTRA3;
+ else
+ return SPEEDO_VANILLA;
+}
+
+static boolean K_UseColorSpeedo(int speedostyle)
+{
+ if (!K_UseColorHud())
+ return false;
+
+ switch (speedostyle)
+ {
+ case SPEEDO_EXTRA:
+ return xtra_speedo_clr;
+ case SPEEDO_ACHII:
+ return achi_speedo_clr;
+ case SPEEDO_DIAL:
+ return dial_speedo_clr;
+ case SPEEDO_EXTRA3:
+ return xtra_speedo_clr3;
+ default:
+ return false;
+ }
+}
+
+static boolean K_IsHighResolution(void)
+{
+ return (vid.width >= 640 && vid.height >= 400);
+}
+
+boolean K_UseHighResPortraits(void)
+{
+ return (cv_highresportrait.value && K_IsHighResolution());
+}
+
+// returns the players faceprefix
+// accounts for localskins
+patch_t *K_GetFacePrefix(player_t *player, INT32 skinnum)
+{
+ if (!player->skinlocal)
+ return (K_UseHighResPortraits() ? facewantprefix[skinnum] : facerankprefix[skinnum]);
+ else
+ return (K_UseHighResPortraits() ? localfacewantprefix[skinnum] : localfacerankprefix[skinnum]);
+}
+
+INT32 K_calcSplitFlags(INT32 snapflags)
+{
+ INT32 splitflags = 0;
+
+ if (splitscreen == 0)
+ return snapflags;
+
+ if (stplyrnum != 0)
+ {
+ if (splitscreen == 1 && stplyrnum == 1)
+ {
+ splitflags |= V_SPLITSCREEN;
+ }
+ else if (splitscreen > 1)
+ {
+ if (stplyrnum == 2 || (splitscreen == 3 && stplyrnum == 3))
+ splitflags |= V_SPLITSCREEN;
+ if (stplyrnum == 1 || (splitscreen == 3 && stplyrnum == 3))
+ splitflags |= V_HORZSCREEN;
+ }
+ }
+
+ if (splitflags & V_SPLITSCREEN)
+ snapflags &= ~V_SNAPTOTOP;
+ else
+ snapflags &= ~V_SNAPTOBOTTOM;
+
+ if (splitscreen > 1)
+ {
+ if (splitflags & V_HORZSCREEN)
+ snapflags &= ~V_SNAPTOLEFT;
+ else
+ snapflags &= ~V_SNAPTORIGHT;
+ }
+
+ return (splitflags|snapflags);
+}
+
+void K_getItemBoxDrawinfo(drawinfo_t *out)
+{
+ INT32 fx, fy, fflags;
+
+ // pain and suffering defined below
+ if (splitscreen < 2) // don't change shit for THIS splitscreen.
+ {
+ fx = ITEM_X;
+ fy = ITEM_Y;
+ fflags = K_calcSplitFlags(V_SNAPTOTOP|V_SNAPTOLEFT);
+ }
+ else // now we're having a fun game.
+ {
+ if (!(stplyrnum & 1)) // If we are P1 or P3...
+ {
+ fx = ITEM_X;
+ fy = ITEM_Y;
+ fflags = V_SNAPTOLEFT|(stplyrnum & 2 ? V_SPLITSCREEN : V_SNAPTOTOP); // flip P3 to the bottom.
+ }
+ else // else, that means we're P2 or P4.
+ {
+ fx = ITEM2_X;
+ fy = ITEM2_Y;
+ fflags = V_SNAPTORIGHT|(stplyrnum & 2 ? V_SPLITSCREEN : V_SNAPTOTOP); // flip P4 to the bottom
+ }
+ }
+
+ out->x = fx;
+ out->y = fy;
+ out->flags = fflags;
+}
+
+void K_getLapsDrawinfo(drawinfo_t *out)
+{
+ INT32 fx, fy, fflags;
+
+ // pain and suffering defined below
+ if (splitscreen < 2) // don't change shit for THIS splitscreen.
+ {
+ fx = LAPS_X;
+ fy = LAPS_Y;
+ fflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT);
+ }
+ else
+ {
+ if (!(stplyrnum & 1)) // If we are P1 or P3...
+ {
+ fx = LAPS_X;
+ fy = LAPS_Y;
+ fflags = V_SNAPTOLEFT|(stplyrnum & 2 ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P3 to the bottom.
+ }
+ else // else, that means we're P2 or P4.
+ {
+ fx = LAPS2_X;
+ fy = LAPS2_Y;
+ fflags = V_SNAPTORIGHT|(stplyrnum & 2 ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P4 to the bottom
+ }
+ }
+
+ out->x = fx;
+ out->y = fy;
+ out->flags = fflags;
+}
+
+void K_getMinimapDrawinfo(drawinfo_t *out)
+{
+ INT32 fx = MINI_X, fy = MINI_Y, fflags = (splitscreen == 3 ? 0 : V_SNAPTORIGHT); // flags should only be 0 when it's centered (4p split)
+
+ out->x = fx;
+ out->y = fy;
+ out->flags = fflags;
+}
+
+INT32 K_getMinimapTrans(void)
+{
+ INT32 minimaptrans = cv_kartminimap.value;
+
+ if (!minimaptrans)
+ return -1;
+
+ if (forceshowhud)
+ return (10-minimaptrans)<kartstuff[k_bumper] ? -5 : -8) : 0);
+
+ // Customizations c:
+ if (!splitscreen)
+ {
+ x += 18 + cv_stat_xoffset.value + spdxoffset;
+ y += cv_stat_yoffset.value + spdoffset;
+ }
+ else if (splitscreen == 1) // I tried my best, but this is still mess :/ < :Blobcatpats: c:
+ {
+ x -= 10;
+ y -= 40;
+ y += spdoffset;
+
+ // If we are in 2-player splitscreen, for player 1 we move hud to up and remove snapping
+ // to bottom
+ if (splitnum == 0)
+ {
+ y /= 2;
+ flags = V_SNAPTOLEFT;
+ }
+ else
+ {
+ // Can move it down a bit
+ y += 45;
+ }
+ }
+ else
+ {
+ if (splitnum == 0 || splitnum == 2) // If we are P1 or P3...
+ {
+ // ye i just align it to position number lol
+ x = POSI_X + 19;
+ y = POSI_Y - 6;
+ flags = V_SNAPTOLEFT|((splitnum == 2) ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P3 to the bottom.
+ }
+ else // else, that means we're P2 or P4.
+ {
+ x = POSI2_X - 75;
+ y = POSI2_Y - 6;
+ flags = V_SNAPTORIGHT|((splitnum == 3) ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P4 to the bottom
+ }
+ }
+
+ flags |= V_HUDTRANS;
+
+ skin_t *fakeskin;
+ fakeskin = K_GetPlayerSkin(stplyr);
+
+ if (!splitscreen)
+ {
+ // Skin name
+ if (K_IsHighResolution()) // V_DrawSmallString becomes a mess at low resolutions lel
+ {
+ V_DrawSmallString(x+20, y+12, flags|V_ALLOWLOWERCASE|V_SkinColorToHighlightcolor(stplyr->skincolor), fakeskin->realname);
+ }
+ else
+ {
+ V_DrawThinString(x+20, y+7, flags|V_ALLOWLOWERCASE|V_SkinColorToHighlightcolor(stplyr->skincolor), fakeskin->realname);
+ }
+
+ // Icon and stats
+ if (K_UseHighResPortraits())
+ V_DrawSmallMappedPatch(x, y, flags, R_GetSkinFaceWant(stplyr), R_GetLocalTranslationColormap(fakeskin, fakeskin, stplyr->skincolor, GTC_CACHE, stplyr->skinlocal));
+ else
+ V_DrawMappedPatch(x, y, flags, R_GetSkinFaceRank(stplyr), R_GetLocalTranslationColormap(fakeskin, fakeskin, stplyr->skincolor, GTC_CACHE, stplyr->skinlocal));
+
+ V_DrawMappedPatch(x-3, y-2, flags, kp_facenum[min(9, max(1, stplyr->kartspeed))], R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_BLUEBERRY, GTC_CACHE));
+ V_DrawMappedPatch(x+10, y+10, flags, kp_facenum[min(9, max(1, stplyr->kartweight))], R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_BURGUNDY, GTC_CACHE));
+ }
+ else
+ {
+ // In splitscreen, just draw a string with stats
+ V_DrawString(x, y+10, flags, va("\x84%dS \x87%dW", stplyr->kartspeed, stplyr->kartweight));
+ }
+}
+
+static void K_drawKartItem(void)
+{
+ // ITEM_X = BASEVIDWIDTH-50; // 270
+ // ITEM_Y = 24; // 24
+
+ // Why write V_DrawScaledPatch calls over and over when they're all the same?
+ // Set to 'no item' just in case.
+ const UINT8 offset = ((splitscreen > 1) ? 1 : 0);
+ patch_t *localpatch = kp_nodraw;
+ patch_t *localbg;
+ boolean dark = false;
+
+ patch_t *localinv = ((offset) ? kp_invincibility[((leveltime % (6*3)) / 3) + 7] : kp_invincibility[(leveltime % (7*3)) / 3]);
+ INT32 fx = 0, fy = 0, fflags = 0; // final coords for hud and flags...
+ INT32 numberdisplaymin = cv_huditemamount.value == 2 ? 1 : 2; // No longer a constant so other things can modify this value
+ INT32 itembar = 0;
+ INT32 maxl = 0; // itembar's normal highest value
+ const INT32 barlength = (splitscreen > 1 ? 12 : 26);
+ UINT8 localcolor = SKINCOLOR_NONE;
+ SINT8 colormode = TC_RAINBOW;
+ UINT8 *colmap = NULL;
+ UINT8 *colormap = NULL;
+
+ if (stplyr->kartstuff[k_itemroulette])
+ {
+ localcolor = K_GetHudColor();
+
+ switch((stplyr->kartstuff[k_itemroulette] % (14*3)) / 3)
+ {
+ // Each case is handled in threes, to give three frames of in-game time to see the item on the roulette
+ case 0: // Sneaker
+ localpatch = kp_sneaker[offset];
+ //localcolor = SKINCOLOR_RASPBERRY;
+ break;
+ case 1: // Banana
+ localpatch = kp_banana[offset];
+ //localcolor = SKINCOLOR_YELLOW;
+ break;
+ case 2: // Orbinaut
+ localpatch = kp_orbinaut[3+offset];
+ //localcolor = SKINCOLOR_STEEL;
+ break;
+ case 3: // Mine
+ localpatch = kp_mine[offset];
+ //localcolor = SKINCOLOR_JET;
+ break;
+ case 4: // Grow
+ localpatch = kp_grow[offset];
+ //localcolor = SKINCOLOR_TEAL;
+ break;
+ case 5: // Hyudoro
+ localpatch = kp_hyudoro[offset];
+ //localcolor = SKINCOLOR_STEEL;
+ break;
+ case 6: // Rocket Sneaker
+ localpatch = kp_rocketsneaker[offset];
+ //localcolor = SKINCOLOR_TANGERINE;
+ break;
+ case 7: // Jawz
+ localpatch = kp_jawz[offset];
+ //localcolor = SKINCOLOR_JAWZ;
+ break;
+ case 8: // Self-Propelled Bomb
+ localpatch = kp_selfpropelledbomb[offset];
+ //localcolor = SKINCOLOR_JET;
+ break;
+ case 9: // Shrink
+ localpatch = kp_shrink[offset];
+ //localcolor = SKINCOLOR_ORANGE;
+ break;
+ case 10: // Invincibility
+ localpatch = localinv;
+ //localcolor = SKINCOLOR_GREY;
+ break;
+ case 11: // Eggman Monitor
+ localpatch = kp_eggman[offset];
+ //localcolor = SKINCOLOR_ROSE;
+ break;
+ case 12: // Ballhog
+ localpatch = kp_ballhog[offset];
+ //localcolor = SKINCOLOR_LILAC;
+ break;
+ case 13: // Thunder Shield
+ localpatch = kp_thundershield[offset];
+ //localcolor = SKINCOLOR_CYAN;
+ break;
+ /*case 14: // Pogo Spring
+ localpatch = kp_pogospring[offset];
+ localcolor = SKINCOLOR_TANGERINE;
+ break;
+ case 15: // Kitchen Sink
+ localpatch = kp_kitchensink[offset];
+ localcolor = SKINCOLOR_STEEL;
+ break;*/
+ default:
+ break;
+ }
+ }
+ else
+ {
+ // I'm doing this a little weird and drawing mostly in reverse order
+ // The only actual reason is to make sneakers line up this way in the code below
+ // This shouldn't have any actual baring over how it functions
+ // Hyudoro is first, because we're drawing it on top of the player's current item
+ if (stplyr->kartstuff[k_stolentimer] > 0)
+ {
+ if (leveltime & 2)
+ localpatch = kp_hyudoro[offset];
+ else
+ localpatch = kp_nodraw;
+ }
+ else if ((stplyr->kartstuff[k_stealingtimer] > 0) && (leveltime & 2))
+ {
+ localpatch = kp_hyudoro[offset];
+ }
+ else if (stplyr->kartstuff[k_eggmanexplode] > 1)
+ {
+ if (leveltime & 1)
+ localpatch = kp_eggman[offset];
+ else
+ localpatch = kp_nodraw;
+ }
+ else if (stplyr->kartstuff[k_rocketsneakertimer] > 1)
+ {
+ itembar = stplyr->kartstuff[k_rocketsneakertimer];
+ maxl = (itemtime*3) - barlength;
+
+ if (leveltime & 1)
+ localpatch = kp_rocketsneaker[offset];
+ else
+ localpatch = kp_nodraw;
+ }
+ else if (stplyr->kartstuff[k_growshrinktimer] > 0)
+ {
+ if (stplyr->kartstuff[k_growcancel] > 0)
+ {
+ itembar = stplyr->kartstuff[k_growcancel];
+ maxl = 26;
+ }
+
+ if (leveltime & 1)
+ localpatch = kp_grow[offset];
+ else
+ localpatch = kp_nodraw;
+ }
+ else if (stplyr->kartstuff[k_sadtimer] > 0)
+ {
+ if (leveltime & 2)
+ localpatch = kp_sadface[offset];
+ else
+ localpatch = kp_nodraw;
+ }
+ else
+ {
+ if (stplyr->kartstuff[k_itemamount] <= 0)
+ return;
+
+ const boolean usemultiicon = (multiitem_icon && cv_multiitemicon.value && !offset);
+
+ switch (stplyr->kartstuff[k_itemtype])
+ {
+ case KITEM_SNEAKER:
+ if (usemultiicon)
+ {
+ if (!cv_huditemamount.value)
+ numberdisplaymin = 4;
+ switch(stplyr->kartstuff[k_itemamount])
+ {
+ case 1:
+ localpatch = kp_sneaker[offset];
+ break;
+ case 2:
+ localpatch = kp_multsneaker[0];
+ break;
+ default:
+ localpatch = kp_multsneaker[1];
+ break;
+ }
+ }
+ else
+ {
+ localpatch = kp_sneaker[offset];
+ }
+ break;
+ case KITEM_ROCKETSNEAKER:
+ localpatch = kp_rocketsneaker[offset];
+ break;
+ case KITEM_INVINCIBILITY:
+ localpatch = localinv;
+ dark = true;
+ break;
+ case KITEM_BANANA:
+ if (usemultiicon)
+ {
+ if (!cv_huditemamount.value)
+ numberdisplaymin = 4;
+ switch(stplyr->kartstuff[k_itemamount])
+ {
+ case 1:
+ localpatch = kp_banana[offset];
+ break;
+ case 2:
+ localpatch = kp_multbanana[0];
+ break;
+ case 3:
+ localpatch = kp_multbanana[1];
+ break;
+ default:
+ localpatch = kp_multbanana[2];
+ break;
+ }
+ }
+ else
+ {
+ localpatch = kp_banana[offset];
+ }
+ break;
+ case KITEM_EGGMAN:
+ localpatch = kp_eggman[offset];
+ break;
+ case KITEM_ORBINAUT:
+ if (!cv_huditemamount.value)
+ numberdisplaymin = offset ? 2 : 5;
+ localpatch = kp_orbinaut[(offset ? 4 : min(stplyr->kartstuff[k_itemamount]-1, 3))];
+ break;
+ case KITEM_JAWZ:
+ if (usemultiicon)
+ {
+ if (!cv_huditemamount.value)
+ numberdisplaymin = 3;
+ localpatch = ((stplyr->kartstuff[k_itemamount] == 1) ? kp_jawz[offset] : kp_multjawz);
+ }
+ else
+ {
+ localpatch = kp_jawz[offset];
+ }
+ break;
+ case KITEM_MINE:
+ localpatch = kp_mine[offset];
+ break;
+ case KITEM_BALLHOG:
+ localpatch = kp_ballhog[offset];
+ break;
+ case KITEM_SPB:
+ localpatch = kp_selfpropelledbomb[offset];
+ dark = true;
+ break;
+ case KITEM_GROW:
+ localpatch = kp_grow[offset];
+ break;
+ case KITEM_SHRINK:
+ localpatch = kp_shrink[offset];
+ break;
+ case KITEM_THUNDERSHIELD:
+ localpatch = kp_thundershield[offset];
+ dark = true;
+ break;
+ case KITEM_HYUDORO:
+ localpatch = kp_hyudoro[offset];
+ break;
+ case KITEM_POGOSPRING:
+ localpatch = kp_pogospring[offset];
+ break;
+ case KITEM_KITCHENSINK:
+ localpatch = kp_kitchensink[offset];
+ break;
+ case KITEM_SAD:
+ localpatch = kp_sadface[offset];
+ break;
+ default:
+ return;
+ }
+
+ if (stplyr->kartstuff[k_itemheld] && !(leveltime & 1))
+ localpatch = kp_nodraw;
+ }
+
+ if (stplyr->kartstuff[k_itemblink] && (leveltime & 1))
+ {
+ colormode = TC_BLINK;
+
+ switch (stplyr->kartstuff[k_itemblinkmode])
+ {
+ case 2:
+ localcolor = (UINT8)(1 + (leveltime % (MAXSKINCOLORS-1)));
+ break;
+ case 1:
+ localcolor = SKINCOLOR_RED;
+ break;
+ default:
+ localcolor = SKINCOLOR_WHITE;
+ break;
+ }
+ }
+ }
+
+ localbg = K_getItemBoxPatch((boolean)offset, dark);
+ drawinfo_t info;
+ K_getItemBoxDrawinfo(&info);
+ fx = info.x;
+ fy = info.y;
+ fflags = info.flags;
+
+ boolean flipamount = splitscreen > 1 && stplyrnum & 1; // Used for 3P/4P splitscreen to flip item amount stuff
+
+ if (K_UseColorHud())
+ colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+
+ V_DrawMappedPatch(fx, fy, V_HUDTRANS|fflags, localbg, cv_colorizeditembox.value ? colormap : NULL);
+
+ fixed_t rfy = fy<kartstuff[k_itemroulette] && !stplyr->deadtimer)
+ {
+ fixed_t frac = R_GetHudUncap();
+ UINT8 fancystep = (offset ? 6 : 10);
+ fixed_t fancyoffset = (stplyr->kartstuff[k_itemroulette] % 3)-1;
+
+ if (fancyoffset != 0)
+ {
+ fancyflags &= ~V_HUDTRANS;
+ fancyflags |=V_HUDTRANSHALF;
+ }
+
+ rfy += (fancystep * fancyoffset * FRACUNIT) + FixedMul(fancystep*FRACUNIT, frac) - fancystep/2*FRACUNIT;
+ }
+
+ if (localcolor != SKINCOLOR_NONE)
+ colmap = R_GetTranslationColormap(colormode, localcolor, GTC_CACHE);
+
+ // Then, the numbers:
+ if (stplyr->kartstuff[k_itemamount] >= numberdisplaymin && !stplyr->kartstuff[k_itemroulette])
+ {
+ localbg = K_getItemMulPatch((boolean)offset);
+
+ V_DrawMappedPatch(fx + (flipamount ? 48 : 0), fy, V_HUDTRANS|fflags|(flipamount ? V_FLIP : 0), localbg, colormap); // flip this graphic for p2 and p4 in split and shift it.
+ V_DrawFixedPatch(fx<kartstuff[k_itemamount]));
+ }
+ else
+ {
+ V_DrawScaledPatch(fx+28, fy+41, V_HUDTRANS|fflags, kp_itemx);
+ V_DrawKartString(fx+38, fy+36, V_HUDTRANS|fflags, va("%d", stplyr->kartstuff[k_itemamount]));
+ }
+ }
+ else
+ V_DrawFixedPatch(fx< 2)
+ {
+ V_DrawFill(fx+x+length, fy+y+1, 1, height, 12|fflags); // the right one
+ if (height == 2)
+ V_DrawFill(fx+x+2, fy+y+2, length-2, 1, 8|fflags); // the dulled underside
+ V_DrawFill(fx+x+2, fy+y+1, length-2, 1, 120|fflags); // the shine
+ }
+ }
+
+ // Quick Eggman numbers
+ if (stplyr->kartstuff[k_eggmanexplode] > 1 /*&& stplyr->kartstuff[k_eggmanexplode] <= 3*TICRATE*/)
+ V_DrawScaledPatch(fx+17, fy+13-offset, V_HUDTRANS|fflags, kp_eggnum[min(3, G_TicsToSeconds(stplyr->kartstuff[k_eggmanexplode]))]);
+}
+
+void K_drawKartTimestamp(tic_t drawtime, INT32 TX, INT32 TY, INT16 emblemmap, UINT8 mode)
+{
+ // TIME_X = BASEVIDWIDTH-124; // 196
+ // TIME_Y = 6; // 6
+
+ INT32 splitflags = 0;
+
+ if (!mode)
+ {
+ splitflags = V_HUDTRANS|K_calcSplitFlags(V_SNAPTOTOP|V_SNAPTORIGHT);
+ if (cv_timelimit.value && timelimitintics > 0)
+ {
+ if (drawtime >= timelimitintics)
+ drawtime = 0;
+ else
+ drawtime = timelimitintics - drawtime;
+ }
+ }
+
+ if (K_UseColorHud()) // Colourized hud
+ {
+ UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ V_DrawMappedPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwideclr : kp_timestickerwideclr), colormap);
+ }
+ else
+ V_DrawScaledPatch(TX, TY, splitflags, ((mode == 2) ? kp_lapstickerwide : kp_timestickerwide));
+
+ TX += 33;
+
+ if (drawtime == UINT32_MAX)
+ ;
+ else if (mode && !drawtime)
+ {
+ V_DrawKartString(TX, TY+3, splitflags, va("--'--\"--"));
+ }
+ else
+ {
+ tic_t worktime = drawtime/(60*TICRATE);
+
+ if (cv_timelimit.value && cv_overtime.value && G_BattleGametype() && !players[consoleplayer].exiting && (leveltime > (timelimitintics + starttime + TICRATE/2))) // i hate this so much
+ {
+ V_DrawKartString(TX, TY+3, splitflags, va("OVERTIME"));
+ }
+ else if (worktime < 100)
+ {
+ // minutes time 00 __ __
+ V_DrawKartString(TX, TY+3, splitflags, va("%d", worktime/10));
+ V_DrawKartString(TX+12, TY+3, splitflags, va("%d", worktime%10));
+
+ // apostrophe location _'__ __
+ V_DrawKartString(TX+24, TY+3, splitflags, va("'"));
+
+ worktime = (drawtime/TICRATE % 60);
+
+ // seconds time _ 00 __
+ V_DrawKartString(TX+36, TY+3, splitflags, va("%d", worktime/10));
+ V_DrawKartString(TX+48, TY+3, splitflags, va("%d", worktime%10));
+
+ // quotation mark location _ __"__
+ V_DrawKartString(TX+60, TY+3, splitflags, va("\""));
+
+ worktime = G_TicsToCentiseconds(drawtime);
+
+ // tics _ __ 00
+ V_DrawKartString(TX+72, TY+3, splitflags, va("%d", worktime/10));
+ V_DrawKartString(TX+84, TY+3, splitflags, va("%d", worktime%10));
+ }
+ else if ((drawtime/TICRATE) & 1)
+ V_DrawKartString(TX, TY+3, splitflags, va("99'59\"99"));
+ }
+
+ if (emblemmap && (modeattacking || (mode == 1)) && !demo.playback) // emblem time!
+ {
+ INT32 workx = TX + 96, worky = TY+18;
+ SINT8 curemb = 0;
+ patch_t *emblempic[3] = {NULL, NULL, NULL};
+ UINT8 *emblemcol[3] = {NULL, NULL, NULL};
+
+ emblem_t *emblem = M_GetLevelEmblems(emblemmap);
+ while (emblem)
+ {
+ char targettext[9];
+
+ switch (emblem->type)
+ {
+ case ET_TIME:
+ {
+ static boolean canplaysound = true;
+ tic_t timetoreach = emblem->var;
+
+ if (emblem->collected)
+ {
+ emblempic[curemb] = W_CachePatchName(M_GetEmblemPatch(emblem), PU_PATCH);
+ emblemcol[curemb] = R_GetTranslationColormap(TC_DEFAULT, M_GetEmblemColor(emblem), GTC_CACHE);
+ if (++curemb == 3)
+ break;
+ goto bademblem;
+ }
+
+ snprintf(targettext, 9, "%i'%02i\"%02i",
+ G_TicsToMinutes(timetoreach, false),
+ G_TicsToSeconds(timetoreach),
+ G_TicsToCentiseconds(timetoreach));
+
+ if (!mode)
+ {
+ if (stplyr->realtime > timetoreach)
+ {
+ splitflags = (splitflags &~ V_HUDTRANS)|V_HUDTRANSHALF;
+ if (canplaysound)
+ {
+ S_StartSound(NULL, sfx_s3k72); //sfx_s26d); -- you STOLE fizzy lifting drinks
+ canplaysound = false;
+ }
+ }
+ else if (!canplaysound)
+ canplaysound = true;
+ }
+
+ targettext[8] = 0;
+ }
+ break;
+ default:
+ goto bademblem;
+ }
+
+ V_DrawRightAlignedString(workx, worky, splitflags, targettext);
+ workx -= 67;
+ V_DrawSmallScaledPatch(workx + 4, worky, splitflags, W_CachePatchName("NEEDIT", PU_PATCH));
+
+ break;
+
+ bademblem:
+ emblem = M_GetLevelEmblems(-1);
+ }
+
+ if (!mode)
+ splitflags = (splitflags &~ V_HUDTRANSHALF)|V_HUDTRANS;
+
+ while (curemb--)
+ {
+ workx -= 12;
+ V_DrawSmallMappedPatch(workx + 4, worky, splitflags, emblempic[curemb], emblemcol[curemb]);
+ }
+ }
+}
+
+static void K_DrawKartPositionNum(INT32 num)
+{
+ // POSI_X = BASEVIDWIDTH - 51; // 269
+ // POSI_Y = BASEVIDHEIGHT- 64; // 136
+
+ const boolean wheeloffs = (cv_showinput.value && cv_posi_xoffset.value == 0 && cv_posi_yoffset.value == 0 && cv_wheel_xoffset.value == 0 && cv_wheel_yoffset.value == 0);
+ const boolean win = (stplyr->exiting && num == 1);
+ INT32 W = kp_positionnum[0][0]->width;
+ fixed_t scale = FRACUNIT;
+ patch_t *localpatch = kp_positionnum[0][0];
+ INT32 fx = 0, fy = 0, fflags = 0;
+ const INT32 xoffs = wheeloffs ? -48 : 0;
+ boolean flipdraw = false; // flip the order we draw it in for MORE splitscreen bs. fun.
+ boolean flipvdraw = false; // used only for 2p splitscreen so overtaking doesn't make 1P's position fly off the screen.
+ boolean overtake = false;
+
+ if ((cv_posanim.value && stplyr->kartstuff[k_positiondelay]) || stplyr->exiting)
+ {
+ scale *= 2;
+ overtake = true; // this is used for splitscreen stuff in conjunction with flipdraw.
+ }
+
+ if (splitscreen || cv_smallposnum.value || wheeloffs)
+ {
+ scale /= 2;
+ }
+
+ W = FixedMul(W<>FRACBITS;
+
+ // pain and suffering defined below
+ if (!splitscreen)
+ {
+ fx = POSI_X + xoffs;
+ fy = BASEVIDHEIGHT - 8 + cv_posi_yoffset.value;
+ fflags = V_SNAPTOBOTTOM|V_SNAPTORIGHT;
+ }
+ else if (splitscreen == 1) // for this splitscreen, we'll use case by case because it's a bit different.
+ {
+ fx = POSI_X;
+ if (stplyrnum == 0) // for player 1: display this at the top right, above the minimap.
+ {
+ fy = 30 + cv_posi_yoffset.value;
+ fflags = V_SNAPTOTOP|V_SNAPTORIGHT;
+ if (overtake)
+ flipvdraw = true; // make sure overtaking doesn't explode us
+ }
+ else // if we're not p1, that means we're p2. display this at the bottom right, below the minimap.
+ {
+ fy = BASEVIDHEIGHT - 8 + cv_posi_yoffset.value;
+ fflags = V_SNAPTOBOTTOM|V_SNAPTORIGHT;
+ }
+ }
+ else
+ {
+ if (!(stplyrnum & 1)) // If we are P1 or P3...
+ {
+ fx = POSI_X;
+ fy = POSI_Y;
+ fflags = V_SNAPTOLEFT|((stplyrnum == 2) ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P3 to the bottom.
+ flipdraw = true;
+ if (num && num >= 10)
+ fx += W; // this seems dumb, but we need to do this in order for positions above 10 going off screen.
+ }
+ else // else, that means we're P2 or P4.
+ {
+ fx = POSI2_X;
+ fy = POSI2_Y;
+ fflags = V_SNAPTORIGHT|((stplyrnum == 3) ? V_SPLITSCREEN|V_SNAPTOBOTTOM : 0); // flip P4 to the bottom
+ }
+ }
+
+ // Special case for 0
+ if (!num)
+ {
+ V_DrawFixedPatch(fx<= 0); // This function does not draw negative numbers
+
+ // Draw the number
+ while (num)
+ {
+ if (win) // 1st place winner? You get rainbows!!
+ {
+ localpatch = kp_winnernum[(leveltime % (NUMWINFRAMES*3)) / 3];
+ }
+ else if (stplyr->laps+1 >= cv_numlaps.value || stplyr->exiting) // Check for the final lap, or won
+ {
+ // Alternate frame every three frames
+ switch (leveltime % 9)
+ {
+ case 1: case 2: case 3:
+ if (K_IsPlayerLosing(stplyr))
+ localpatch = kp_positionnum[num % 10][4];
+ else
+ localpatch = kp_positionnum[num % 10][1];
+ break;
+ case 4: case 5: case 6:
+ if (K_IsPlayerLosing(stplyr))
+ localpatch = kp_positionnum[num % 10][5];
+ else
+ localpatch = kp_positionnum[num % 10][2];
+ break;
+ case 7: case 8: case 9:
+ if (K_IsPlayerLosing(stplyr))
+ localpatch = kp_positionnum[num % 10][6];
+ else
+ localpatch = kp_positionnum[num % 10][3];
+ break;
+ default:
+ localpatch = kp_positionnum[num % 10][0];
+ break;
+ }
+ }
+ else
+ {
+ localpatch = kp_positionnum[num % 10][0];
+ }
+
+ V_DrawFixedPatch((fx<width*scale/2) : 0), (fy<height*scale/2) : 0), scale, V_HUDTRANSHALF|fflags, localpatch, NULL);
+ // ^ if we overtake as p1 or p3 in splitscren, we shift it so that it doesn't go off screen.
+ // ^ if we overtake as p1 in 2p splits, shift vertically so that this doesn't happen either.
+
+ fx -= W;
+ num /= 10;
+ }
+}
+
+static boolean K_drawKartPositionFaces(void)
+{
+ // FACE_X = 15; // 15
+ // FACE_Y = 72; // 72
+
+ INT32 Y = FACE_Y+9; // +9 to offset where it's being drawn if there are more than one
+ INT32 i, j, ranklines, strank = -1;
+ boolean completed[MAXPLAYERS];
+ INT32 rankplayer[MAXPLAYERS];
+ INT32 bumperx, numplayersingame = 0;
+ UINT8 *colormap;
+
+ ranklines = 0;
+ memset(completed, 0, sizeof (completed));
+ memset(rankplayer, 0, sizeof (rankplayer));
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ rankplayer[i] = -1;
+
+ if (!playeringame[i] || players[i].spectator || !players[i].mo)
+ continue;
+
+ numplayersingame++;
+ }
+
+ if (numplayersingame <= 1)
+ return true;
+
+ if (!LUA_HudEnabled(hud_minirankings))
+ return false; // Don't proceed but still return true for free play above if HUD is disabled.
+
+ for (j = 0; j < numplayersingame; j++)
+ {
+ UINT8 lowestposition = MAXPLAYERS+1;
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ if (completed[i] || !playeringame[i] || players[i].spectator || !players[i].mo)
+ continue;
+
+ if (players[i].kartstuff[k_position] >= lowestposition)
+ continue;
+
+ rankplayer[ranklines] = i;
+ lowestposition = players[i].kartstuff[k_position];
+ }
+
+ i = rankplayer[ranklines];
+
+ completed[i] = true;
+
+ if (players+i == stplyr)
+ strank = ranklines;
+
+ ranklines++;
+ }
+
+ if (ranklines < 5)
+ Y -= (9*ranklines);
+ else
+ Y -= (9*5);
+
+ if (G_BattleGametype() || strank <= 2) // too close to the top, or playing battle, or a spectator? would have had (strank == -1) called out, but already caught by (strank <= 2)
+ {
+ i = 0;
+ if (ranklines > 5) // could be both...
+ ranklines = 5;
+ }
+ else if (strank+3 > ranklines) // too close to the bottom?
+ {
+ i = ranklines - 5;
+ if (i < 0)
+ i = 0;
+ }
+ else
+ {
+ i = strank-2;
+ ranklines = strank+3;
+ }
+
+ for (; i < ranklines; i++)
+ {
+ player_t *player;
+ player = &players[rankplayer[i]];
+
+ if (!playeringame[rankplayer[i]])
+ continue;
+ if (player->spectator)
+ continue;
+ if (!player->mo)
+ continue;
+
+ const UINT8 mocolor = player->mo->color;
+
+ bumperx = FACE_X+19;
+
+ if (mocolor)
+ {
+ colormap = R_GetTranslationColormap(player->skin, mocolor, GTC_CACHE);
+ if (player->mo->colorized)
+ colormap = R_GetTranslationColormap(TC_RAINBOW, mocolor, GTC_CACHE);
+
+ if (K_UseHighResPortraits())
+ V_DrawSmallMappedPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, R_GetSkinFaceWant(player), colormap);
+ else
+ V_DrawMappedPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, R_GetSkinFaceRank(player), colormap);
+
+ if (LUA_HudEnabled(hud_battlebumpers))
+ {
+ if (G_BattleGametype() && player->kartstuff[k_bumper] > 0)
+ {
+ V_DrawMappedPatch(bumperx-2, Y, V_HUDTRANS|V_SNAPTOLEFT, kp_tinybumper[0], colormap);
+ for (j = 1; j < player->kartstuff[k_bumper]; j++)
+ {
+ bumperx += 5;
+ V_DrawMappedPatch(bumperx, Y, V_HUDTRANS|V_SNAPTOLEFT, kp_tinybumper[1], colormap);
+ }
+ }
+ } // A new level of stupidity: checking if lua is enabled to close a bracket. :Fascinating:
+ }
+
+ if (i == strank)
+ V_DrawScaledPatch(FACE_X, Y, V_HUDTRANS|V_SNAPTOLEFT, kp_facehighlight[(leveltime / 4) % 8]);
+
+ if (G_BattleGametype() && player->kartstuff[k_bumper] <= 0)
+ V_DrawScaledPatch(FACE_X-4, Y-3, V_HUDTRANS|V_SNAPTOLEFT, kp_ranknobumpers);
+ else
+ {
+ INT32 pos = player->kartstuff[k_position];
+ if (pos < 0 || pos > MAXPLAYERS)
+ pos = 0;
+ // Draws the little number over the face
+ V_DrawScaledPatch(FACE_X-5, Y+10, V_HUDTRANS|V_SNAPTOLEFT, kp_facenum[pos]);
+ }
+
+ Y += 18;
+ }
+
+ return false;
+}
+
+//
+// HU_DrawTabRankings -- moved here to take advantage of kart stuff!
+//
+void HU_DrawTabRankings(INT32 x, INT32 y, playersort_t *tab, INT32 scorelines, INT32 hilicol)
+{
+ INT32 i, rightoffset = 240;
+ const UINT8 *colormap;
+ const INT32 dupadjust = cv_betainterscreen.value ? 314 : (vid.width/vid.dupx), duptweak = cv_betainterscreen.value ? -3 : (dupadjust - BASEVIDWIDTH)/2;
+
+ boolean (*_isHighlightedPlayer)(const player_t *) = (demo.playback ? P_IsDisplayPlayer : P_IsLocalPlayer);
+
+ //this function is designed for 9 or less score lines only
+ //I_Assert(scorelines <= 9); -- not today bitch, kart fixed it up
+
+ V_DrawFill(1-duptweak, 26, dupadjust-2, 1, 0); // Draw a horizontal line because it looks nice!
+ if (scorelines > 8)
+ {
+ V_DrawFill(160, 26, 1, 147, 0); // Draw a vertical line to separate the two sides.
+ V_DrawFill(1-duptweak, 173, dupadjust-2, 1, 0); // And a horizontal line near the bottom.
+ rightoffset = (BASEVIDWIDTH/2) - 4 - x;
+ }
+
+ for (i = 0; i < scorelines; i++)
+ {
+ char strtime[MAXPLAYERNAME+1];
+ const UINT8 pnum = tab[i].num;
+ player_t *player = &players[pnum];
+
+ if (player->spectator || !player->mo)
+ continue; //ignore them.
+
+ const boolean whiteplayer = _isHighlightedPlayer(player);
+ const INT32 philicol = (whiteplayer ? V_SkinColorToHighlightcolor(player->skincolor) : 0);
+
+ if ((netgame && pnum != serverplayer) || (cv_mindelay.value && P_IsLocalPlayer(player)))
+ {
+ HU_drawPlayerPing(x + ((i < 8) ? -17 : rightoffset + 11), y-4, pnum, 0);
+ }
+
+ STRBUFCPY(strtime, tab[i].name);
+
+ if (scorelines > 8)
+ V_DrawThinString(x + 20, y, philicol|V_ALLOWLOWERCASE|V_6WIDTHSPACE, strtime);
+ else
+ V_DrawString(x + 20, y, philicol|V_ALLOWLOWERCASE, strtime);
+
+ if (player->mo->color)
+ {
+ if (player->mo->colorized)
+ colormap = R_GetTranslationColormap(TC_RAINBOW, player->mo->color, GTC_CACHE);
+ else
+ colormap = R_GetTranslationColormap(player->skin, player->mo->color, GTC_CACHE);
+
+ if (K_UseHighResPortraits())
+ V_DrawSmallMappedPatch(x, y-4, 0, R_GetSkinFaceWant(player), colormap);
+ else
+ V_DrawMappedPatch(x, y-4, 0, R_GetSkinFaceRank(player), colormap);
+
+ /*if (G_BattleGametype() && player->kartstuff[k_bumper] > 0) -- not enough space for this
+ {
+ INT32 bumperx = x+19;
+ V_DrawMappedPatch(bumperx-2, y-4, 0, kp_tinybumper[0], colormap);
+ for (j = 1; j < player->kartstuff[k_bumper]; j++)
+ {
+ bumperx += 5;
+ V_DrawMappedPatch(bumperx, y-4, 0, kp_tinybumper[1], colormap);
+ }
+ }*/
+ }
+
+ if (whiteplayer)
+ V_DrawScaledPatch(x, y-4, 0, kp_facehighlight[(leveltime / 4) % 8]);
+
+ if (G_BattleGametype() && player->kartstuff[k_bumper] <= 0)
+ V_DrawScaledPatch(x-4, y-7, 0, kp_ranknobumpers);
+ else
+ {
+ INT32 pos = player->kartstuff[k_position];
+ if (pos < 0 || pos > MAXPLAYERS)
+ pos = 0;
+ // Draws the little number over the face
+ V_DrawScaledPatch(x-5, y+6, 0, kp_facenum[pos]);
+ }
+
+ if (G_RaceGametype())
+ {
+#define timestring(time) va("%i'%02i\"%02i", G_TicsToMinutes(time, true), G_TicsToSeconds(time), G_TicsToCentiseconds(time))
+ if (scorelines > 8)
+ {
+ if (player->exiting)
+ V_DrawRightAlignedThinString(x+rightoffset, y-1, hilicol|V_6WIDTHSPACE, timestring(player->realtime));
+ else if (player->pflags & PF_TIMEOVER)
+ V_DrawRightAlignedThinString(x+rightoffset, y-1, V_6WIDTHSPACE, "NO CONTEST.");
+ else if (circuitmap)
+ V_DrawRightAlignedThinString(x+rightoffset, y-1, V_6WIDTHSPACE, va("Lap %d", tab[i].count));
+ }
+ else
+ {
+ if (player->exiting)
+ V_DrawRightAlignedString(x+rightoffset, y, hilicol, timestring(player->realtime));
+ else if (player->pflags & PF_TIMEOVER)
+ V_DrawRightAlignedThinString(x+rightoffset, y-1, 0, "NO CONTEST.");
+ else if (circuitmap)
+ V_DrawRightAlignedString(x+rightoffset, y, 0, va("Lap %d", tab[i].count));
+ }
+#undef timestring
+ }
+ else
+ V_DrawRightAlignedString(x+rightoffset, y, 0, va("%u", tab[i].count));
+
+ y += 18;
+ if (i == 7)
+ {
+ y = 33;
+ x = (BASEVIDWIDTH/2) + 4;
+ }
+ }
+}
+
+static boolean K_BigLap(void)
+{
+ return (cv_biglaps.value && (cv_numlaps.value > 9) && (K_UseColorHud() ? big_lap_color : big_lap) && (!stplyr->exiting));
+}
+
+static void K_drawKartLaps(void)
+{
+ const INT32 splitflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT);
+ INT32 fx = 0, fy = 0, fflags = 0; // stuff for 3p / 4p splitscreen.
+ const boolean flipstring = splitscreen > 1 && stplyrnum & 1; // used for 3p or 4p
+ INT32 stringw = 0; // used with the above
+ const char *laps;
+
+ drawinfo_t info;
+ K_getLapsDrawinfo(&info);
+ fx = info.x;
+ fy = info.y;
+ fflags = info.flags;
+
+ laps = (stplyr->exiting ? "FIN" : va("%d/%d", stplyr->laps+1, cv_numlaps.value));
+
+ // draw stuff as god intended.
+ if (splitscreen > 1)
+ {
+ if (flipstring)
+ {
+ stringw = V_StringWidth(laps, 0);
+
+ V_DrawScaledPatch(fx-stringw-13, fy, V_HUDTRANS|fflags, kp_splitlapflag);
+ V_DrawRightAlignedString(fx, fy+1, V_HUDTRANS|fflags, laps);
+ }
+ else // draw stuff NORMALLY.
+ {
+ V_DrawScaledPatch(fx, fy, V_HUDTRANS|fflags, kp_splitlapflag);
+ V_DrawString(fx+13, fy+1, V_HUDTRANS|fflags, laps);
+ }
+ }
+ else
+ {
+ if (K_UseColorHud()) // Colourized hud
+ {
+ UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ patch_t *biglapclr = (K_BigLap() ? ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2clr : kp_lapstickerbigclr) : kp_lapstickerclr);
+ V_DrawMappedPatch(fx, fy, V_HUDTRANS|splitflags, biglapclr, colormap);
+ }
+ else
+ {
+ patch_t *biglap = (K_BigLap() ? ((stplyr->laps + 1 > 9) ? kp_lapstickerbig2 : kp_lapstickerbig) : kp_lapsticker);
+ V_DrawScaledPatch(fx, fy, V_HUDTRANS|splitflags, biglap);
+ }
+
+ V_DrawKartString(fx+33, fy+3, V_HUDTRANS|splitflags, laps);
+ }
+}
+
+#ifdef ROTSPRITE
+
+#define DIALSPDDIV 97090 // 1.48148; converts 200 to 135
+#define MPHDIV 68283 // 1.04192; converts 141 to 135
+
+static void K_DrawDialNum(INT32 x, INT32 y, boolean colorized, INT32 flags, INT32 num, INT32 digits, const UINT8 *colormap)
+{
+ INT32 w;
+
+ if (colorized)
+ w = skp_dialnumclr[0]->width;
+ else
+ w = skp_dialnum[0]->width;
+
+ if (flags & V_NOSCALESTART)
+ w *= vid.dupx;
+
+ if (num < 0)
+ num = -num;
+
+ // draw the number
+ do
+ {
+ x -= (w);
+
+ if (colorized)
+ V_DrawFixedPatch(x << FRACBITS, y << FRACBITS, FRACUNIT, flags, skp_dialnumclr[num % 10], colormap);
+ else
+ V_DrawFixedPatch(x << FRACBITS, y << FRACBITS, FRACUNIT, flags, skp_dialnum[num % 10], colormap);
+
+ num /= 10;
+ } while (--digits);
+}
+
+static void K_DrawDialLaps(INT32 x, INT32 y, INT32 num, INT32 total, INT32 flags)
+{
+ INT32 fx;
+ fx = x + ((num < 10) ? 0 : 6);
+ V_DrawRankNum(fx, y, flags, num, (num < 10) ? 1 : 2, NULL);
+ V_DrawScaledPatch(fx + 2, y, flags, frameslash);
+ V_DrawRankNum(fx + 13 + ((total < 10) ? 0 : 6), y, flags, total, (total < 10) ? 1 : 2, NULL);
+}
+
+static void K_DrawDialSpeedometer(fixed_t speed,
+ fixed_t divisor,
+ INT32 splitflags,
+ boolean battlemode,
+ boolean infoactive,
+ boolean colorized)
+{
+ const UINT8* colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+
+ INT32 rot = 0;
+ const UINT8 infoidx = (infoactive) ? 1 : 0;
+ patch_t* dialpatch;
+
+ const angle_t speedangle =
+ FixedAngle(((min(135 * FRACUNIT, FixedDiv(speed, divisor)) - (45 * FRACUNIT))));
+
+ rot = R_GetRollAngle(speedangle);
+
+ if (rot)
+ {
+ dialpatch = W_CachePatchNameRotated("K_DSDIAL", rot, PU_PATCH);
+ }
+ else
+ {
+ dialpatch = W_CachePatchName("K_DSDIAL", PU_PATCH);
+ }
+
+ if (colorized) // Colourized hud
+ {
+ V_DrawMappedPatch(
+ SPDM_X, SPDM_Y - 9, (V_HUDTRANS | splitflags), skp_dialbaseclr[infoidx], colormap);
+ V_DrawMappedPatch(SPDM_X,
+ SPDM_Y + 30,
+ V_HUDTRANS | splitflags,
+ skp_speedpatchesdialclr[cv_kartspeedometer.value],
+ colormap);
+ }
+ else
+ {
+ V_DrawScaledPatch(SPDM_X, SPDM_Y - 9, (V_HUDTRANS | splitflags), skp_dialbase[infoidx]);
+ V_DrawScaledPatch(SPDM_X,
+ SPDM_Y + 30,
+ V_HUDTRANS | splitflags,
+ skp_speedpatchesdial[cv_kartspeedometer.value]);
+ }
+
+ K_DrawDialNum(SPDM_X + 10,
+ SPDM_Y + 25,
+ colorized,
+ V_HUDTRANS | splitflags,
+ speed / FRACUNIT,
+ 3,
+ colormap);
+
+ // gotta center the dial manually
+ V_DrawMappedPatch(SPDM_X - 19, SPDM_Y + 15, (V_HUDTRANS | splitflags), (dialpatch), colormap);
+
+ if (!infoactive)
+ {
+ // no need to draw info if we're not supposed to
+ return;
+ }
+
+ // draw the info
+ if (battlemode)
+ {
+ if (stplyr->kartstuff[k_bumper] <= 0)
+ {
+ V_DrawMappedPatch(
+ SPDM_X + 28, SPDM_Y + 27, V_HUDTRANS | splitflags, kp_splitkarmabomb, colormap);
+ K_DrawDialLaps(SPDM_X + 46,
+ SPDM_Y + 29,
+ stplyr->kartstuff[k_comebackpoints],
+ 2,
+ V_HUDTRANS | splitflags);
+ }
+ else // the above doesn't need to account for weird stuff since the max amount of karma
+ // necessary is always 2 ^^^^
+ {
+ V_DrawMappedPatch(
+ SPDM_X + 28, SPDM_Y + 27, V_HUDTRANS | splitflags, kp_rankbumper, colormap);
+ K_DrawDialLaps(SPDM_X + 46,
+ SPDM_Y + 29,
+ stplyr->kartstuff[k_bumper],
+ cv_kartbumpers.value,
+ V_HUDTRANS | splitflags);
+ }
+ }
+ else
+ {
+ V_DrawScaledPatch(SPDM_X + 28, SPDM_Y + 27, V_HUDTRANS | splitflags, kp_splitlapflag);
+
+ if (stplyr->exiting)
+ V_DrawScaledPatch(SPDM_X + 39, SPDM_Y + 29, V_HUDTRANS | splitflags, skp_rankfinish);
+ else
+ K_DrawDialLaps(SPDM_X + 46,
+ SPDM_Y + 29,
+ stplyr->laps + 1,
+ cv_numlaps.value,
+ V_HUDTRANS | splitflags);
+ }
+}
+
+#endif
+
+static void K_drawKartSpeedometer(void)
+{
+ // why?
+ if (cv_kartspeedometer.value == 0)
+ return;
+
+ // index 0 is the raw value, index 1 is the converted value
+ fixed_t convSpeed[2] = {0,0};
+#ifdef ROTSPRITE
+ fixed_t dial_divisor = DIALSPDDIV;
+#endif
+
+ INT32 splitflags = K_calcSplitFlags(V_SNAPTOBOTTOM|V_SNAPTOLEFT);
+
+ // man.
+ const UINT8 speedostyle = K_GetSpeedometerStyle();
+
+ switch (cv_kartspeedometer.value)
+ {
+ case 1:
+ convSpeed[0] = FixedDiv(FixedMul(stplyr->speed, 142371), mapobjectscale); // 2.172409058
+ convSpeed[1] = convSpeed[0] / FRACUNIT;
+ break;
+ case 2:
+ convSpeed[0] = FixedDiv(FixedMul(stplyr->speed, 88465), mapobjectscale); // 1.349868774
+ convSpeed[1] = convSpeed[0] / FRACUNIT;
+#ifdef ROTSPRITE
+ dial_divisor = MPHDIV;
+#endif
+ break;
+ case 3:
+ convSpeed[0] = FixedDiv(stplyr->speed, mapobjectscale);
+ convSpeed[1] = convSpeed[0] / FRACUNIT;
+#ifdef ROTSPRITE
+ dial_divisor = MPHDIV;
+#endif
+ break;
+ case 4:
+ if (stplyr->mo)
+ {
+ convSpeed[0] = (FixedDiv(stplyr->speed, FixedMul(K_GetKartSpeed(stplyr, false), ORIG_FRICTION))*100);
+ convSpeed[1] = convSpeed[0] >> FRACBITS;
+ }
+ break;
+ default:
+ break;
+ }
+
+ if (speedostyle == SPEEDO_VANILLA)
+ {
+ const char *metric = "";
+
+ switch (cv_kartspeedometer.value)
+ {
+ case 1:
+ metric = va("%3d km/h", convSpeed[1]);
+ break;
+ case 2:
+ metric = va("%3d mph", convSpeed[1]);
+ break;
+ case 3:
+ metric = va("%3d fu/t", convSpeed[1]);
+ break;
+ case 4:
+ // if extra.kart is found, use its included % symbol
+ if (!xtra_speedo)
+ metric = va("%4d P", convSpeed[1]);
+ else
+ metric = va("%4d %%", convSpeed[1]);
+ break;
+ default:
+ break;
+ }
+
+ V_DrawKartString(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, metric);
+ }
+ else if (speedostyle == SPEEDO_EXTRA) // why bother if we dont?
+ {
+ if (K_UseColorSpeedo(SPEEDO_EXTRA)) //Colourized hud
+ {
+ UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerclr, colormap);
+ }
+ else
+ V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallsticker);
+
+ V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL);
+ V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatches[cv_kartspeedometer.value]);
+ }
+ else if (speedostyle == SPEEDO_ACHII) // why bother if we dont?
+ {
+ if (K_UseColorSpeedo(SPEEDO_ACHII)) //Colourized hud
+ {
+ UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ V_DrawMappedPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerachiclr, colormap);
+ V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL);
+ V_DrawMappedPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatchesachiclr[cv_kartspeedometer.value], colormap);
+ }
+ else
+ {
+ V_DrawScaledPatch(SPDM_X + 1, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_smallstickerachi);
+ V_DrawRankNum(SPDM_X + 26, SPDM_Y + 4, V_HUDTRANS|splitflags, convSpeed[1], 3, NULL);
+ V_DrawScaledPatch(SPDM_X + 31, SPDM_Y + 4, V_HUDTRANS|splitflags, skp_speedpatchesachi[cv_kartspeedometer.value]);
+ }
+ }
+#ifdef ROTSPRITE
+ else if (speedostyle == SPEEDO_DIAL) // why bother if we dont?
+ {
+ K_DrawDialSpeedometer(convSpeed[0],
+ dial_divisor,
+ splitflags,
+ (boolean)(G_BattleGametype()),
+ (LUA_HudEnabled(hud_gametypeinfo)),
+ (K_UseColorSpeedo(SPEEDO_DIAL)));
+ }
+#endif
+ else if (speedostyle == SPEEDO_EXTRA3) // why bother if we dont?
+ {
+ if (K_UseColorSpeedo(SPEEDO_EXTRA3)) //Colourized hud
+ {
+ UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ V_DrawStretchyFixedPatch((SPDM_X-1)<speed, mapobjectscale)/FRACUNIT;
+
+ for (INT32 i = 0; i < 22; ++i)
+ {
+ if (fuspeed < speedIntervals[i])
+ {
+ spdpatch = i;
+ break;
+ }
+ }
+
+ if (((fuspeed < 57 && fuspeed > 54) || (fuspeed < 60 && fuspeed > 56) || (fuspeed > 59)) && (leveltime & 4))
+ spdpatch = 24;
+ else if (((fuspeed < 57 && fuspeed > 54) || (fuspeed < 60 && fuspeed > 56) || (fuspeed > 59)) && !(leveltime & 4))
+ spdpatch = 23;
+
+ V_DrawScaledPatch(SPDM_X, SPDM_Y, V_HUDTRANS|splitflags, (speedostyle == SPEEDO_PMETER) ? kp_kartzspeedo[spdpatch] : kp_kartzspeedo_smol[spdpatch]);
+ }
+}
+
+#ifdef ROTSPRITE
+#undef DIALSPDDIV
+#undef MPHDIV
+#endif
+
+static void K_drawKartBumpersOrKarma(void)
+{
+ const UINT8 *colormap = R_GetTranslationColormap(TC_DEFAULT, K_GetHudColor(), GTC_CACHE);
+ INT32 fx, fy, fflags;
+ const boolean flipstring = splitscreen > 1 && stplyrnum & 1; // same as laps, used for splitscreen
+ INT32 stringw = 0; // used with the above
+ const char *bumpval = "";
+
+ drawinfo_t info;
+ K_getLapsDrawinfo(&info);
+ fx = info.x;
+ fy = info.y;
+ fflags = info.flags;
+
+ if (cv_battlespeedo.value && !splitscreen)
+ {
+ const UINT8 speedostyle = K_GetSpeedometerStyle();
+
+ if ((speedostyle == SPEEDO_EXTRA) || (speedostyle == SPEEDO_ACHII) || (speedostyle == SPEEDO_EXTRA3))
+ fy += 5;
+ else
+ fy += 7;
+ }
+
+ if (splitscreen > 1)
+ {
+ if (stplyr->kartstuff[k_bumper] <= 0)
+ {
+ bumpval = va("%d/2", stplyr->kartstuff[k_comebackpoints]);
+
+ if (flipstring)
+ fx -= 37;
+ V_DrawMappedPatch(fx, fy-1, V_HUDTRANS|fflags, kp_splitkarmabomb, colormap);
+ V_DrawString(fx+13, fy+1, V_HUDTRANS|fflags, bumpval);
+ }
+ else // the above doesn't need to account for weird stuff since the max amount of karma necessary is always 2 ^^^^
+ {
+ bumpval = va("%d/%d", stplyr->kartstuff[k_bumper], cv_kartbumpers.value);
+
+ if (flipstring) // for p2 and p4, assume we can have more than 10 bumpers. It's retarded but who knows.
+ {
+ stringw = V_StringWidth(bumpval, 0);
+
+ V_DrawMappedPatch(fx-stringw-13, fy-1, V_HUDTRANS|fflags, kp_rankbumper, colormap);
+ V_DrawRightAlignedString(fx, fy+1, V_HUDTRANS|fflags, bumpval);
+ }
+ else // draw bumpers normally.
+ {
+ V_DrawMappedPatch(fx, fy-1, V_HUDTRANS|fflags, kp_rankbumper, colormap);
+ V_DrawString(fx+13, fy+1, V_HUDTRANS|fflags, bumpval);
+ }
+ }
+ }
+ else
+ {
+ patch_t *patch;
+
+ if (stplyr->kartstuff[k_bumper] <= 0)
+ {
+ patch = (K_UseColorHud() ? kp_karmastickerclr : kp_karmasticker);
+ bumpval = va("%d/2", stplyr->kartstuff[k_comebackpoints]);
+ }
+ else
+ {
+ if (stplyr->kartstuff[k_bumper] > 9 && cv_kartbumpers.value > 9)
+ patch = (K_UseColorHud() ? kp_bumperstickerwideclr : kp_bumperstickerwide);
+ else
+ patch = (K_UseColorHud() ? kp_bumperstickerclr : kp_bumpersticker);
+
+ bumpval = va("%d/%d", stplyr->kartstuff[k_bumper], cv_kartbumpers.value);
+ }
+
+ V_DrawMappedPatch(fx, fy, V_HUDTRANS|fflags, patch, colormap);
+ V_DrawKartString(fx+47, fy+3, V_HUDTRANS|fflags, bumpval);
+ }
+}
+
+#define lerp(from, to) cv_uncappedhud.value ? from + FixedMul(rendertimefrac, to - from) : to
+
+// converts mobj coordinates into screen coordinates
+// NOTE: use with V_NOSCALESTART!
+// Code updated in Lua by GenericHeroGuy for libSG
+// Badly ported to C by NepDisk and acutally made to work and fixed by Indev!(Thanks so much!)
+// Badly uncapped in C by GenericHeroGuy
+// original code by Lat'
+static boolean K_GetScreenCoords(vector2_t *vec, player_t *player, mobj_t *target, fixed_t hofs, boolean dontclip)
+{
+ fixed_t y, x;
+ fixed_t targx, targy, targz;
+
+ fixed_t dist;
+ fixed_t distfact;
+ fixed_t offset;
+
+ fixed_t yres, xres;
+ fixed_t fov;
+
+ // this should never happen but its also kart so ¯\_(ツ)_/¯
+ if (!player || P_MobjWasRemoved(target))
+ return false;
+
+ targx = lerp(target->old_x, target->x);
+ targy = lerp(target->old_y, target->y);
+ targz = lerp(target->old_z, target->z);
+
+ // X coordinate
+ // get difference between camangle and angle towards target
+ x = (INT32)viewangle - (INT32)R_PointToAngle(targx, targy);
+
+ distfact = FINECOSINE((x>>ANGLETOFINESHIFT) & FINEMASK);
+ if (!distfact) distfact = 1;
+
+ if (encoremode)
+ x = -x;
+ if (x < (fixed_t)ANGLE_270 || x > (fixed_t)ANGLE_90)
+ return false;
+
+ xres = vid.width<<(FRACBITS-1);
+ yres = vid.height<<(FRACBITS-1);
+ fov = FixedDiv(xres, FINETANGENT(((FixedAngle(cv_fov.value/2)+ANGLE_90)>>ANGLETOFINESHIFT) & 4095));
+
+ // flipping
+ const boolean targflip = target->eflags & MFE_VERTICALFLIP;
+ const boolean srcflip = player->pflags & PF_FLIPCAM && player->mo->eflags & MFE_VERTICALFLIP;
+
+ // Y coordinate
+ // getting the angle difference here is a bit more involved...
+ // start by getting the height difference between the camera and target
+ y = viewz - targz - (targflip ? ((target->height * 2) / 3) : 0); // for some reason needs to be divided by "1.5" idk
+
+ if (hofs)
+ y = y - (targflip ? -hofs : hofs);
+
+ // then get the distance between camera and target
+ dist = R_PointToDist(targx, targy);
+
+#ifdef HWRENDER
+ // NOW we can get the angle differnce
+ if (rendermode == render_opengl && !cv_glshearing.value)
+ {
+ angle_t yang = R_PointToAngle2(0, 0, dist, y); // not perspective
+ x = FixedMul(x, FINECOSINE((yang>>ANGLETOFINESHIFT) & FINEMASK)); // perspective
+ y = -aimingangle - FixedDiv(yang, distfact);
+
+ if (y < (fixed_t)ANGLE_270 || y > (fixed_t)ANGLE_90) // clip points behind the camera
+ return false;
+ if (splitscreen == 1) // multiply by 1.25 for 2P splitscreen
+ y = y + (y/4) ;
+ if (srcflip) // flipcam
+ y = -y;
+
+ y = FixedMul(FINETANGENT((((angle_t)(-y)+ANGLE_90)>>ANGLETOFINESHIFT) & 4095), fov) + yres; // project the angle to get our final Y coordinate
+ }
+ else
+#endif
+ {
+ const fixed_t fovratio = FixedDiv(90*FRACUNIT, 180*FRACUNIT - FixedMul(cv_fov.value, 4*FRACUNIT/3)-FRACUNIT*-30);
+
+ y = FixedDiv(y, FixedMul(dist, distfact));
+ if (srcflip)
+ y = -y; // flipcam
+ if (y != INT32_MIN) // I_Error(): FixedDiv: divide by zero
+ y = FixedMul(FixedDiv(y, fovratio), xres) + yres;
+ //else print("NOPE!")
+
+ offset = FixedMul(FINETANGENT(((aimingangle+ANGLE_90)>>ANGLETOFINESHIFT) & 4095), xres);
+
+ // this isn't fovtan... what am i even doing anymore
+ if (splitscreen == 1)
+ offset = 17*offset/120;
+
+ // thanks fickle
+ offset = FixedDiv(offset, fovratio);
+ if (srcflip)
+ offset = -offset; // flipcam
+ y = y + offset;
+ }
+
+ // project the angle to get our final X coordinate
+ x = FixedMul(FINETANGENT(((x+ANGLE_90)>>ANGLETOFINESHIFT) & 4095), fov);
+ if (splitscreen == 1) // divide by 320/200 (1.6) on 2P splitscreen
+ x = (x/2) + (x/8);
+ x = x + xres;
+
+ // now clip in screen-space
+ if (!dontclip && (x < 0 || x > xres*2 || y < 0 || y > yres*2))
+ return false;
+
+ // adjust coords for splitscreen
+ if (splitscreen == 1) // 2P
+ {
+ y = y>>1;
+ if (stplyrnum > 0)
+ y = y + yres;
+ }
+ if (splitscreen >= 2) // 3P or 4P
+ {
+ x = x>>1;
+ y = y>>1;
+ if (stplyrnum & 1)
+ x = x + xres;
+ if (stplyrnum >= 2)
+ y = y + yres;
+ }
+
+ vec->y = y;
+ vec->x = x;
+ return true;
+}
+
+//Slighty fixed by Alug and further rewritten by NepDisk
+//Decided to port and highly modify sunflower version for the main nametag drawing with additions by NepDisk. My previous one was broken anyway due to the changed screencoords and noscalestart
+static void K_drawNameTags(void)
+{
+ UINT8 i, j;
+ INT32 trans;
+ vector2_t pos = {0};
+ fixed_t namex, namey;
+ int tagsdisplayed = 0;
+ fixed_t distance = 0;
+ fixed_t maxdistance = 0;
+ boolean flipped = false;
+ fixed_t z;
+
+ char *tag;
+ patch_t *icon = NULL;
+
+ INT32 dup;
+ UINT8 *cm = NULL;
+ UINT8 tagcolor = 0;
+ INT32 vflags = 0;
+ boolean usenametagrestat = false;
+ fixed_t tagwidthsmall;
+ fixed_t tagwidth;
+
+ if (P_MobjWasRemoved(stplyr->mo) || (stplyr->spectator && !cv_shownametagspectator.value) || stplyr->exiting)
+ return;
+
+ maxdistance = ((10*cv_nametagdist.value) * mapobjectscale);
+
+ for (i = 0; i < MAXPLAYERS; i++)
+ {
+ distance = 0;
+ flipped = false;
+
+ if (i > PLAYERSMASK)
+ continue;
+ if (players[i].spectator || !playeringame[i] || P_MobjWasRemoved(players[i].mo))
+ continue;
+ if (i == displayplayers[stplyrnum] && !cv_showownnametag.value && !(leveltime < 130))
+ continue;
+ if (i != displayplayers[stplyrnum] && leveltime < starttime)
+ continue;
+ if (players[i].kartstuff[k_hyudorotimer]) // player is invisible
+ continue;
+ if (maxdistance)
+ distance = R_PointToDist(players[i].mo->x, players[i].mo->y);
+ if (distance > maxdistance)
+ continue;
+ if (!P_CheckSightFast(stplyr->mo, players[i].mo))
+ continue;
+
+ z = players[i].mo->height;
+
+ //Saltyhop hehe
+ z += lerp(players[i].mo->old_spriteyoffset, players[i].mo->spriteyoffset);
+
+ if (!K_GetScreenCoords(&pos, stplyr, players[i].mo, z, false))
+ continue;
+
+ tagsdisplayed++;
+
+ if (tagsdisplayed > cv_nametagmaxplayers.value)
+ break;
+
+ trans = 0;
+
+ switch (cv_nametagtrans.value)
+ {
+ case 1:
+ if (distance > (maxdistance*3/4))
+ trans = V_60TRANS;
+ break;
+ case 2:
+ if (distance > (maxdistance*3/1))
+ trans = V_90TRANS;
+ else if (distance > (maxdistance*3/2))
+ trans = V_80TRANS;
+ else if (distance > (maxdistance*3/3))
+ trans = V_60TRANS;
+ else if (distance > (maxdistance*3/4))
+ trans = V_40TRANS;
+ else if (distance > (maxdistance*3/5))
+ trans = V_20TRANS;
+ break;
+ case 3:
+ trans = V_40TRANS;
+ break;
+ case 4:
+ trans = V_LocalTransFlag();
+ break;
+ case 0:
+ default:
+ break;
+ }
+
+ namex = pos.x>>FRACBITS;
+ namey = pos.y>>FRACBITS;
+
+ tag = va("%s%s ", HU_SkinColorToConsoleColor(players[i].mo->color), player_names[i]);
+ icon = R_GetSkinFaceMini(players[i].mo->player);
+
+ dup = vid.dupx;
+ cm = R_GetTranslationColormap(players[i].skin, players[i].mo->color, GTC_CACHE);
+ tagcolor = colortranslations[players[i].mo->color][7];
+ vflags = trans | V_NOSCALESTART;
+ usenametagrestat = ((cv_nametagrestat.value == 1 && (players[i].kartspeed != skins[players[i].skin].kartspeed || players[i].kartweight != skins[players[i].skin].kartweight)) || cv_nametagrestat.value == 2);
+ tagwidthsmall = cv_smallnametags.value ? V_SmallStringWidth(player_names[i], V_ALLOWLOWERCASE) : V_ThinStringWidth(player_names[i], V_ALLOWLOWERCASE);
+ tagwidth = dup*tagwidthsmall;
+
+ // If flipcam is on, other player is flipped relative to us when we have different
+ // verticalflip flag value. Otherwise, they are simply flipped when verticalflip flag says so
+ if ((stplyr->pflags & PF_FLIPCAM) && (stplyr->mo->eflags & MFE_VERTICALFLIP))
+ flipped = (players[i].mo->eflags & MFE_VERTICALFLIP) != (stplyr->mo->eflags & MFE_VERTICALFLIP);
+ else
+ flipped = players[i].mo->eflags & MFE_VERTICALFLIP;
+
+ if (cv_smallnametags.value || !nametaggfx)
+ {
+ if (flipped)
+ namey += dup*5;
+ else // small offset
+ namey -= dup*3;
+
+ if (nametaggfx && cv_smallnametags.value == 1)
+ {
+ if (cv_nametagfacerank.value)
+ tagwidthsmall += icon->width - dup;
+
+ // Have to draw the nametag using patches here since drawfill can't draw at this scale...
+ if (!flipped)
+ V_DrawFixedPatch(namex<