Mesonification

This commit is contained in:
Tamás Bálint Misius 2019-12-17 15:03:41 +01:00
parent a3c2a0d677
commit 360297c338
No known key found for this signature in database
GPG Key ID: 5B472A12F6ECA9F2
179 changed files with 7602 additions and 1511 deletions

1
.github/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
build_init.bat

61
.github/build.sh vendored Executable file
View File

@ -0,0 +1,61 @@
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
if [ -z "${PLATFORM_SHORT-}" ]; then
>&2 echo "PLATFORM_SHORT not set"
exit 1
fi
if [ -z "${STATIC_DYNAMIC-}" ]; then
>&2 echo "STATIC_DYNAMIC not set"
exit 1
fi
if [ -z "${RELTYPECFG-}" ]; then
>&2 echo "RELTYPECFG not set"
exit 1
fi
if [ -z "${build_sh_init-}" ]; then
if [ $PLATFORM_SHORT == "win" ]; then
for i in C:/Program\ Files\ \(x86\)/Microsoft\ Visual\ Studio/**/**/VC/Auxiliary/Build/vcvarsall.bat; do
vcvarsall_path=$i
done
cat << BUILD_INIT_BAT > .github/build_init.bat
@echo off
call "${vcvarsall_path}" x64
bash -c 'build_sh_init=1 ./.github/build.sh'
BUILD_INIT_BAT
./.github/build_init.bat
else
build_sh_init=1 ./.github/build.sh
fi
exit 0
fi
other_flags=
bin_postfix=
static_flag=
if [ $STATIC_DYNAMIC == "static" ]; then
static_flag=-Dstatic=prebuilt
if [ $PLATFORM_SHORT == "win" ]; then
other_flags+=$'\t-Db_vscrt=mt'
fi
fi
if [ $PLATFORM_SHORT == "lin" ]; then
# We use gcc on lin; sadly, gcc + lto + libstdc++ + pthread = undefined reference to
# pthread_create, thanks to weak symbols in libstdc++.so (or something). See
# https://gcc.gnu.org/legacy-ml/gcc-help/2017-03/msg00081.html
other_flags+=$'\t-Db_asneeded=false\t-Dcpp_link_args=-Wl,--no-as-needed'
fi
if [ $PLATFORM_SHORT == "win" ]; then
bin_postfix=$bin_postfix.exe
fi
meson -Dbuildtype=release -Dbuild_render=true -Dbuild_font=true -Db_pie=false -Db_staticpic=false -Db_lto=true $static_flag -Dinstall_check=true $other_flags `echo $RELTYPECFG | base64 -d` build
cd build
ninja
7z a ../powder.zip powder$bin_postfix render$bin_postfix font$bin_postfix
cd ..
7z a powder.zip README.md LICENSE

2
.github/get-release-info.sh vendored Executable file
View File

@ -0,0 +1,2 @@
value=`cat release_url/release_url.txt`
echo ::set-output name=upload_url::$value

20
.github/get-type.py vendored Normal file
View File

@ -0,0 +1,20 @@
import base64
import re
import sys
ref = sys.argv[1]
match_stable = re.match(r'refs/tags/v([0-9]+)\.([0-9]+)\.([0-9]+)', ref)
match_snapshot = re.match(r'refs/tags/snapshot-([0-9]+)', ref)
if match_stable:
print('::set-output name=TYPE::stable')
print('::set-output name=NAME::v%s.%s.%s' % (match_stable.group(1), match_stable.group(2), match_stable.group(3)))
print('::set-output name=RELTYPECFG::%s' % base64.b64encode(('-Dignore_updates=false\t-Dversion_major=%s\t-Dversion_minor=%s\t-Dversion_build=%s' % (match_stable.group(1), match_stable.group(2), match_stable.group(3))).encode('utf-8')).decode('utf-8'))
elif match_snapshot:
print('::set-output name=TYPE::snapshot')
print('::set-output name=NAME::snapshot-%s' % match_snapshot.group(1))
print('::set-output name=RELTYPECFG::%s' % base64.b64encode(('-Dignore_updates=false\t-Dsnapshot=true\t-Dsnapshot_id=%s' % match_snapshot.group(1)).encode('utf-8')).decode('utf-8'))
else:
print('::set-output name=TYPE::dev')
print('::set-output name=NAME::dev')
print('::set-output name=RELTYPECFG::%s' % base64.b64encode(('-Dignore_updates=true').encode('utf-8')).decode('utf-8'))

7
.github/invoke-vcvarsall.bat vendored Normal file
View File

@ -0,0 +1,7 @@
@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x86
echo ::set-env name=PATH::%PATH%
echo ::set-env name=CC::cl
echo ::set-env name=CXX::cl
exit

83
.github/workflows/build.yaml vendored Normal file
View File

@ -0,0 +1,83 @@
name: build
on:
push:
branches:
- '*'
tags:
- 'v*.*'
- 'snapshot-*'
pull_request:
branches:
- '*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- id: get_type
run: python ./.github/get-type.py ${{ github.ref }}
- id: create_release
if: steps.get_type.outputs.TYPE != 'dev'
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ steps.get_type.outputs.NAME }}
draft: true
prerelease: false
- run: echo "${{ steps.create_release.outputs.upload_url }}" > release_url.txt
- uses: actions/upload-artifact@v1
with:
name: release_url
path: release_url.txt
build:
runs-on: ${{ matrix.os }}
needs: [release]
strategy:
matrix:
platform_short: [lin, mac, win]
static_dynamic: [static, dynamic]
include:
- platform_short: lin
os: ubuntu-latest
- platform_short: mac
os: macos-latest
- platform_short: win
os: windows-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- id: get_type
run: python ./.github/get-type.py ${{ github.ref }}
- uses: actions/download-artifact@v1
with:
name: release_url
- id: get_release_info
if: steps.get_type.outputs.TYPE != 'dev'
run: bash -c "./.github/get-release-info.sh" ## gg github, this is terrible
- if: matrix.platform_short == 'mac'
run: brew install pkg-config
- if: matrix.platform_short == 'mac' && matrix.static_dynamic != 'static'
run: brew install luajit curl fftw zlib sdl2
- if: matrix.platform_short == 'lin' && matrix.static_dynamic != 'static'
run: sudo apt update && sudo apt install libluajit-5.1-dev libcurl4-openssl-dev libfftw3-dev zlib1g-dev libsdl2-dev
- run: python -m pip install meson ninja
- run: bash -c 'PLATFORM_SHORT=${{ matrix.platform_short }} STATIC_DYNAMIC=${{ matrix.static_dynamic }} RELTYPECFG=${{ steps.get_type.outputs.RELTYPECFG }} ./.github/build.sh'
- uses: actions/upload-release-asset@v1
if: steps.get_type.outputs.TYPE != 'dev' && matrix.static_dynamic == 'static'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.get_release_info.outputs.upload_url }}
asset_path: powder.zip
asset_name: powder-${{ matrix.platform_short }}-${{ steps.get_type.outputs.NAME }}64.zip
asset_content_type: application/zip
- uses: actions/upload-artifact@v2
if: steps.get_type.outputs.TYPE == 'dev' && matrix.static_dynamic == 'static'
with:
path: powder.zip
name: powder-${{ steps.get_type.outputs.NAME }}-${{ matrix.static_dynamic }}-${{ matrix.platform_short }}64.zip

2
.gitignore vendored
View File

@ -71,7 +71,5 @@ site_scons/site_tools/mfprogram/*.pyc
site_scons/site_tools/gch/*.pyc
.vscode/
.vs/
# Intentional merge conflict (meson stuff)
subprojects/
screenshot_*

View File

@ -1,612 +0,0 @@
import os
import subprocess
import sys
import platform
import atexit
import time
import SCons.Util
# because of an implementation detail commandlines are limited to 10000 characters on windows using mingw. the following fix was copied from
# http://scons.org/wiki/LongCmdLinesOnWin32 and circumvents this issue.
class ourSpawn:
def ourspawn(self, sh, escape, cmd, args, env):
newargs = ' '.join(args[1:])
cmdline = cmd + " " + newargs
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
data, err = proc.communicate()
rv = proc.wait()
if rv:
print("=====")
print(err)
print("=====")
return rv
def SetupSpawn(env):
buf = ourSpawn()
buf.ourenv = env
env['SPAWN'] = buf.ourspawn
def FatalError(message):
print(message)
raise SystemExit(1)
#wrapper around SCons' AddOption
def AddSconsOption(name, default, hasArgs, help):
AddOption("--{0}".format(name), dest=name, action=("store" if hasArgs else "store_true"), default=default, help=help)
AddSconsOption('win', False, False, "Target Windows.")
AddSconsOption('lin', False, False, "Target Linux.")
AddSconsOption('mac', False, False, "Target Mac OS X.")
AddSconsOption('msvc', False, False, "Use the Microsoft Visual Studio compiler.")
AddSconsOption("tool", False, True, "Tool prefix appended before gcc/g++.")
AddSconsOption('beta', False, False, "Beta build.")
AddSconsOption('no-install-prompt', False, False, "Disable the \"do you want to install Powder Toy?\" prompt.")
AddSconsOption('ignore-updates', False, False, "Disable checking for updates.")
AddSconsOption('save-version', False, True, "Save version.")
AddSconsOption('minor-version', False, True, "Minor version.")
AddSconsOption('build-number', False, True, "Build number.")
AddSconsOption('snapshot', False, False, "Snapshot build.")
AddSconsOption('snapshot-id', False, True, "Snapshot build ID.")
AddSconsOption('64bit', False, False, "Compile a 64 bit binary.")
AddSconsOption('32bit', False, False, "Compile a 32 bit binary.")
AddSconsOption("universal", False, False, "compile universal binaries on Mac OS X.")
AddSconsOption('no-sse', False, False, "Disable SSE optimizations.")
AddSconsOption('sse', True, False, "Enable SSE optimizations (default).")
AddSconsOption('sse2', True, False, "Enable SSE2 optimizations (default).")
AddSconsOption('sse3', False, False, "Enable SSE3 optimizations.")
AddSconsOption('native', False, False, "Enable optimizations specific to your cpu.")
AddSconsOption('release', False, False, "Enable loop / compiling optimizations.")
AddSconsOption('debugging', False, False, "Compile with debug symbols.")
AddSconsOption('symbols', False, False, "Preserve (don't strip) symbols")
AddSconsOption('static', False, False, "Compile statically.")
AddSconsOption('opengl', False, False, "Build with OpenGL interface support.")
AddSconsOption('opengl-renderer', False, False, "Build with OpenGL renderer support (turns on --opengl).") #Note: this has nothing to do with --renderer, only tells the game to render particles with opengl
AddSconsOption('renderer', False, False, "Build the save renderer.")
AddSconsOption('font', False, False, "Build the font editor.")
AddSconsOption('wall', False, False, "Error on all warnings.")
AddSconsOption('no-warnings', False, False, "Disable all compiler warnings.")
AddSconsOption('nolua', False, False, "Disable Lua.")
AddSconsOption('luajit', False, False, "Enable LuaJIT.")
AddSconsOption('lua52', False, False, "Compile using lua 5.2.")
AddSconsOption('nofft', False, False, "Disable FFT.")
AddSconsOption('nohttp', False, False, "Disable http requests and libcurl.")
AddSconsOption("output", False, True, "Executable output name.")
#detect platform automatically, but it can be overrided
tool = GetOption('tool')
isX86 = platform.machine() in ["amd64", "AMD64", "i386", "i686", "x86", "x86_64"]
platform = compilePlatform = platform.system()
if GetOption('win'):
platform = "Windows"
elif GetOption('lin'):
platform = "Linux"
elif GetOption('mac'):
platform = "Darwin"
elif compilePlatform not in ["Linux", "Windows", "Darwin", "FreeBSD"]:
FatalError("Unknown platform: {0}".format(platform))
msvc = GetOption('msvc')
if msvc and platform != "Windows":
FatalError("Error: --msvc only works on windows")
#Create SCons Environment
if GetOption('msvc'):
env = Environment(tools=['default'], ENV=os.environ, TARGET_ARCH='x86')
elif platform == "Windows" and not GetOption('msvc'):
env = Environment(tools=['mingw'], ENV=os.environ)
else:
env = Environment(tools=['default'], ENV=os.environ)
#attempt to automatically find cross compiler
if not tool and compilePlatform == "Linux" and platform == "Windows" and compilePlatform != platform:
if not GetOption('64bit'):
crossList = ["mingw32", "i686-w64-mingw32", "i386-mingw32msvc", "i486-mingw32msvc", "i586-mingw32msvc", "i686-mingw32msvc"]
else:
crossList = ["x86_64-w64-mingw32", "amd64-mingw32msvc"]
for i in crossList:
#found a cross compiler, set tool here, which will update everything in env later
if WhereIs("{0}-g++".format(i)):
tool = i+"-"
break
if not tool:
print("Could not automatically find cross compiler, use --tool to specify manually")
#set tool prefix
#more things may need to be set (http://clam-project.org/clam/trunk/CLAM/scons/sconstools/crossmingw.py), but this works for us
if tool:
env['CC'] = tool+env['CC']
env['CXX'] = tool+env['CXX']
if platform == "Windows":
env['RC'] = tool+env['RC']
env['STRIP'] = tool+'strip'
if os.path.isdir("/usr/{0}/bin".format(tool[:-1])):
env['ENV']['PATH'] = "/usr/{0}/bin:{1}".format(tool[:-1], os.environ['PATH'])
#copy environment variables because scons doesn't do this by default
for var in ["CC","CXX","LD","LIBPATH","STRIP"]:
if var in os.environ:
env[var] = os.environ[var]
print("copying environment variable {0}={1!r}".format(var,os.environ[var]))
# variables containing several space separated things
for var in ["CFLAGS","CCFLAGS","CXXFLAGS","LINKFLAGS","CPPDEFINES","CPPPATH"]:
if var in os.environ:
if var in env:
env[var] += SCons.Util.CLVar(os.environ[var])
else:
env[var] = SCons.Util.CLVar(os.environ[var])
print("copying environment variable {0}={1!r}".format(var,os.environ[var]))
#Used for intro text / executable name, actual bit flags are only set if the --64bit/--32bit command line args are given
def add32bitflags(env):
env["BIT"] = 32
def add64bitflags(env):
if platform == "Windows":
env.Append(CPPDEFINES=['__CRT__NO_INLINE'])
env.Append(LINKFLAGS=['-Wl,--stack=16777216'])
env.Append(CPPDEFINES=['_64BIT'])
env["BIT"] = 64
#add 32/64 bit defines before configuration
if GetOption('64bit'):
env.Append(LINKFLAGS=['-m64'])
env.Append(CCFLAGS=['-m64'])
add64bitflags(env)
elif GetOption('32bit'):
env.Append(LINKFLAGS=['-m32'])
env.Append(CCFLAGS=['-m32'])
add32bitflags(env)
if GetOption('universal'):
if platform != "Darwin":
FatalError("Error: --universal only works on Mac OS X")
else:
env.Append(CCFLAGS=['-arch', 'i386', '-arch', 'x86_64'])
env.Append(LINKFLAGS=['-arch', 'i386', '-arch', 'x86_64'])
env.Append(CPPPATH=['src/', 'data/'])
if GetOption("msvc"):
if GetOption("static"):
env.Append(LIBPATH=['StaticLibs/'])
else:
env.Append(LIBPATH=['Libraries/'])
env.Append(CPPPATH=['includes/', 'resources/'])
#Check 32/64 bit
def CheckBit(context):
context.Message('Checking if 64 bit... ')
program = """#include <stdlib.h>
#include <stdio.h>
int main() {
printf("%d", (int)sizeof(size_t));
return 0;
}
"""
ret = context.TryCompile(program, '.c')
if ret == 0:
return False
ret = context.TryRun(program, '.c')
if ret[1] == '':
return False
context.Result(int(ret[1]) == 8)
if int(ret[1]) == 8:
print("Adding 64 bit compile flags")
add64bitflags(context.env)
elif int(ret[1]) == 4:
print("Adding 32 bit compile flags")
add32bitflags(context.env)
return ret[1]
#Custom function to check for Mac OS X frameworks
def CheckFramework(context, framework):
import SCons.Conftest
#Extreme hack, TODO: maybe think of a better one (like replicating CheckLib here) or at least just fix the message
oldLinkFlags = env["LINKFLAGS"]
context.env.Append(LINKFLAGS=["-framework", framework])
context.Display("Checking for Darwin Framework {0}...".format(framework))
ret = SCons.Conftest.CheckLib(context, ["m"], autoadd = 0)
context.did_show_result = 1
if not ret:
context.env.Append(LINKFLAGS=["-framework", framework])
if framework != "Cocoa":
env.Append(CPPPATH=['/Library/Frameworks/{0}.framework/Headers/'.format(framework)])
else:
context.env.Replace(LINKFLAGS=oldLinkFlags)
return not ret
#function that finds libraries and appends them to LIBS
def findLibs(env, conf):
#Windows specific libs
if platform == "Windows":
if msvc:
libChecks = ['shell32', 'wsock32', 'user32', 'Advapi32', 'ws2_32', 'Wldap32', 'crypt32']
if GetOption('static'):
libChecks += ['imm32', 'version', 'Ole32', 'OleAut32', 'SetupApi']
for i in libChecks:
if not conf.CheckLib(i):
FatalError("Error: some windows libraries not found or not installed, make sure your compiler is set up correctly")
else:
if not conf.CheckLib('mingw32') or not conf.CheckLib('ws2_32'):
FatalError("Error: some windows libraries not found or not installed, make sure your compiler is set up correctly")
if not GetOption('renderer') and not conf.CheckLib('SDL2main'):
FatalError("libSDL2main not found or not installed")
#Look for SDL
runSdlConfig = platform == "Linux" or compilePlatform == "Linux" or platform == "FreeBSD"
if platform == "Darwin" and conf.CheckFramework("SDL2"):
runSdlConfig = False
elif not conf.CheckLib("SDL2"):
FatalError("SDL2 development library not found or not installed")
if runSdlConfig:
try:
env.ParseConfig('sdl2-config --cflags')
if GetOption('static'):
env.ParseConfig('sdl2-config --static-libs')
else:
env.ParseConfig('sdl2-config --libs')
except:
pass
#look for SDL.h
if conf.CheckCHeader('SDL2/SDL.h'):
env.Append(CPPDEFINES=["SDL_INC"])
elif not conf.CheckCHeader('SDL.h'):
FatalError("SDL.h not found")
if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'):
#Look for Lua
if platform == "FreeBSD":
luaver = "lua-5.1"
else:
luaver = "lua5.1"
if GetOption('luajit'):
if not conf.CheckLib(['luajit-5.1', 'luajit5.1', 'luajit2.0', 'luajit', 'libluajit']):
FatalError("luajit development library not found or not installed")
env.Append(CPPDEFINES=["LUAJIT"])
luaver = "luajit"
elif GetOption('lua52'):
if not conf.CheckLib(['lua5.2', 'lua-5.2', 'lua52', 'lua']):
FatalError("lua5.2 development library not found or not installed")
env.Append(CPPDEFINES=["LUA_COMPAT_ALL"])
if platform == "FreeBSD":
luaver = "lua-5.2"
else:
luaver = "lua5.2"
else:
if not conf.CheckLib(['lua5.1', 'lua-5.1', 'lua51', 'lua']):
if platform != "Darwin" or not conf.CheckFramework("Lua"):
FatalError("lua5.1 development library not found or not installed")
foundpkg = False
if platform == "Linux" or platform == "FreeBSD":
try:
env.ParseConfig("pkg-config --cflags {0}".format(luaver))
env.ParseConfig("pkg-config --libs {0}".format(luaver))
env.Append(CPPDEFINES=["LUA_R_INCL"])
foundpkg = True
except:
pass
if not foundpkg:
#Look for lua.h
foundheader = False
if GetOption('luajit'):
foundheader = conf.CheckCHeader('luajit-2.0/lua.h')
elif GetOption('lua52'):
foundheader = conf.CheckCHeader('lua5.2/lua.h') or conf.CheckCHeader('lua52/lua.h')
else:
foundheader = conf.CheckCHeader('lua5.1/lua.h') or conf.CheckCHeader('lua51/lua.h')
if not foundheader:
if conf.CheckCHeader('lua.h'):
env.Append(CPPDEFINES=["LUA_R_INCL"])
else:
FatalError("lua.h not found")
#needed for static lua compiles (in some cases)
if platform == "Linux":
conf.CheckLib('dl')
#Look for fftw
if not GetOption('nofft') and not GetOption('renderer') and not conf.CheckLib(['fftw3f', 'fftw3f-3', 'libfftw3f-3', 'libfftw3f']):
FatalError("fftw3f development library not found or not installed")
#Look for bz2
if not conf.CheckLib(['bz2', 'libbz2']):
FatalError("bz2 development library not found or not installed")
#Check bz2 header too for some reason
if not conf.CheckCHeader('bzlib.h'):
FatalError("bzip2 headers not found")
#Look for libz
if not conf.CheckLib(['z', 'zlib']):
FatalError("libz not found or not installed")
#Look for libcurl
useCurl = not GetOption('nohttp') and not GetOption('renderer')
if useCurl and not conf.CheckLib(['curl', 'libcurl']):
FatalError("libcurl not found or not installed")
if useCurl and (platform == "Linux" or compilePlatform == "Linux" or platform == "FreeBSD"):
if GetOption('static'):
env.ParseConfig("curl-config --static-libs")
else:
env.ParseConfig("curl-config --libs")
# Needed for ssl. Scons seems incapable of parsing this out of curl-config
if platform == "Darwin":
if not conf.CheckFramework('Security'):
FatalError("Could not find Security.Framework")
#Look for pthreads
if not conf.CheckLib(['pthread', 'pthreadVC2']):
FatalError("pthreads development library not found or not installed")
if msvc:
if not conf.CheckHeader('dirent.h') or not conf.CheckHeader('fftw3.h') or not conf.CheckHeader('pthread.h') or not conf.CheckHeader('zlib.h'):
FatalError("Required headers not found")
else:
#Look for libm
if not conf.CheckLib('m'):
FatalError("libm not found or not installed")
#Look for OpenGL libraries
if GetOption('opengl'):
if platform == "Linux" or platform == "FreeBSD":
if not conf.CheckLib('GL'):
FatalError("libGL not found or not installed")
try:
env.ParseConfig('pkg-config --libs glew gl glu')
except:
FatalError(sys.exc_info()[0])
elif platform == "Windows":
if not conf.CheckLib('opengl32'):
FatalError("opengl32 not found or not installed")
if not conf.CheckLib('glew32'):
FatalError("glew32 not found or not installed")
elif platform == "Darwin":
if not conf.CheckFramework("OpenGL"):
FatalError("OpenGL framework not found or not installed")
if platform == "Linux" or platform == "FreeBSD":
if not conf.CheckLib('X11'):
FatalError("X11 development library not found or not installed")
if not conf.CheckLib('rt'):
FatalError("librt not found or not installed")
elif platform == "Windows":
#These need to go last
if not conf.CheckLib('gdi32') or not conf.CheckLib('winmm') or (not msvc and not conf.CheckLib('dxguid')):
FatalError("Error: some windows libraries not found or not installed, make sure your compiler is set up correctly")
elif platform == "Darwin":
if not conf.CheckFramework("Cocoa"):
FatalError("Cocoa framework not found or not installed")
if GetOption('clean'):
pass
elif not GetOption('help'):
conf = Configure(env)
conf.AddTest('CheckFramework', CheckFramework)
conf.AddTest('CheckBit', CheckBit)
if not conf.CheckCC() or not conf.CheckCXX():
FatalError("compiler not correctly configured")
if platform == compilePlatform and isX86 and not GetOption('32bit') and not GetOption('64bit') and not GetOption('msvc'):
conf.CheckBit()
findLibs(env, conf)
env = conf.Finish()
if not msvc:
env.Append(CXXFLAGS=['-std=c++11', '-U__STRICT_ANSI__'])
env.Append(CXXFLAGS=['-Wno-invalid-offsetof'])
if platform == "Linux":
env.Append(CXXFLAGS=['-Wno-unused-result'])
#Add platform specific flags and defines
if platform == "Windows":
env.Append(CPPDEFINES=["WIN", "_WIN32_WINNT=0x0501", "_USING_V110_SDK71_"])
if msvc:
env.Append(CCFLAGS=['/Gm', '/Zi', '/EHsc', '/FS', '/GS']) #enable minimal rebuild, ?, enable exceptions, allow -j to work in debug builds, enable security check
if GetOption('renderer'):
env.Append(LINKFLAGS=['/SUBSYSTEM:CONSOLE'])
else:
env.Append(LINKFLAGS=['/SUBSYSTEM:WINDOWS,"5.01"'])
env.Append(LINKFLAGS=['/OPT:REF', '/OPT:ICF'])
env.Append(CPPDEFINES=['_SCL_SECURE_NO_WARNINGS']) #Disable warnings about 'std::print'
if GetOption('static'):
env.Append(LINKFLAGS=['/NODEFAULTLIB:msvcrt.lib', '/LTCG'])
elif not GetOption('debugging'):
env.Append(LINKFLAGS=['/NODEFAULTLIB:msvcrtd.lib'])
else:
env.Append(LINKFLAGS=['-mwindows'])
elif platform == "Linux" or platform == "FreeBSD":
env.Append(CPPDEFINES=['LIN'])
elif platform == "Darwin":
env.Append(CPPDEFINES=['MACOSX'])
#env.Append(LINKFLAGS=['-headerpad_max_install_names']) #needed in some cross compiles
if GetOption('luajit'):
env.Append(LINKFLAGS=['-pagezero_size', '10000', '-image_base', '100000000'])
#Add architecture flags and defines
if isX86:
env.Append(CPPDEFINES='X86')
if not GetOption('no-sse'):
if GetOption('sse'):
if msvc:
if not GetOption('sse2'):
env.Append(CCFLAGS=['/arch:SSE'])
else:
env.Append(CCFLAGS=['-msse'])
env.Append(CPPDEFINES=['X86_SSE'])
if GetOption('sse2'):
if msvc:
env.Append(CCFLAGS=['/arch:SSE2'])
else:
env.Append(CCFLAGS=['-msse2'])
env.Append(CPPDEFINES=['X86_SSE2'])
if GetOption('sse3'):
if msvc:
FatalError("--sse3 doesn't work with --msvc")
else:
env.Append(CCFLAGS=['-msse3'])
env.Append(CPPDEFINES=['X86_SSE3'])
if GetOption('native') and not msvc:
env.Append(CCFLAGS=['-march=native'])
#Add optimization flags and defines
if GetOption('debugging'):
if msvc:
env.Append(CCFLAGS=['/Od'])
if GetOption('static'):
env.Append(CCFLAGS=['/MTd'])
else:
env.Append(CCFLAGS=['/MDd'])
else:
env.Append(CCFLAGS=['-Wall', '-g'])
env.Append(CPPDEFINES=['DEBUG'])
elif GetOption('release'):
if msvc:
# Certain options (like /GL and /GS) cause TPT to be flagged as a virus. Don't include them
env.Append(CCFLAGS=['/O2', '/Oy-', '/fp:fast'])
if GetOption('static'):
env.Append(CCFLAGS=['/MT'])
else:
env.Append(CCFLAGS=['/MD'])
else:
env.Append(CCFLAGS=['-O3', '-ftree-vectorize', '-funsafe-math-optimizations', '-ffast-math', '-fomit-frame-pointer'])
if platform != "Darwin":
env.Append(CCFLAGS=['-funsafe-loop-optimizations'])
if GetOption('static'):
if platform == "Windows":
env.Append(CPPDEFINES=['CURL_STATICLIB'])
if compilePlatform == "Windows" and not msvc:
env.Append(CPPDEFINES=['_PTW32_STATIC_LIB'])
else:
env.Append(CPPDEFINES=['PTW32_STATIC_LIB'])
if msvc:
env.Append(CPPDEFINES=['ZLIB_WINAPI'])
else:
env.Append(LINKFLAGS=['-Wl,-Bstatic'])
#Add other flags and defines
if not GetOption('nofft') and not GetOption('renderer'):
env.Append(CPPDEFINES=['GRAVFFT'])
if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'):
env.Append(CPPDEFINES=['LUACONSOLE'])
if GetOption('nohttp') or GetOption('renderer'):
env.Append(CPPDEFINES=['NOHTTP'])
if GetOption('opengl') or GetOption('opengl-renderer'):
env.Append(CPPDEFINES=['OGLI', 'PIX32OGL'])
if GetOption('opengl-renderer'):
env.Append(CPPDEFINES=['OGLR'])
if GetOption('renderer'):
env.Append(CPPDEFINES=['RENDERER'])
if GetOption('font'):
env.Append(CPPDEFINES=['FONTEDITOR'])
if GetOption("wall"):
if msvc:
env.Append(CCFLAGS=['/WX'])
else:
env.Append(CCFLAGS=['-Werror'])
elif GetOption("no-warnings"):
if msvc:
env.Append(CCFLAGS=['/W0'])
else:
env.Append(CCFLAGS=['-w'])
#Add version defines
if GetOption('save-version'):
env.Append(CPPDEFINES=["SAVE_VERSION={0}".format(GetOption('save-version'))])
if GetOption('minor-version'):
env.Append(CPPDEFINES=["MINOR_VERSION={0}".format(GetOption('minor-version'))])
if GetOption('build-number'):
env.Append(CPPDEFINES=["BUILD_NUM={0}".format(GetOption('build-number'))])
if GetOption('snapshot-id'):
env.Append(CPPDEFINES=["SNAPSHOT", "SNAPSHOT_ID={0}".format(GetOption('snapshot-id'))])
elif GetOption('snapshot'):
env.Append(CPPDEFINES=["SNAPSHOT", "SNAPSHOT_ID={0}".format(str(int(time.time())))])
if GetOption('beta'):
env.Append(CPPDEFINES=['BETA'])
if GetOption('no-install-prompt'):
env.Append(CPPDEFINES=['NO_INSTALL_CHECK'])
if GetOption('ignore-updates'):
env.Append(CPPDEFINES=['IGNORE_UPDATES'])
#Generate list of sources to compile
sources = Glob("src/*.cpp") + Glob("src/*/*.cpp") + Glob("src/*/*/*.cpp") + Glob("data/*.cpp")
if not GetOption('nolua') and not GetOption('renderer') and not GetOption('font'):
sources += Glob("src/lua/socket/*.c") + Glob("src/lua/LuaCompat.c")
if platform == "Windows":
sources += env.RES('resources/powder-res.rc')
if not msvc:
sources = filter(lambda source: not 'src\\simulation\\Gravity.cpp' in str(source), sources)
sources = filter(lambda source: not 'src/simulation/Gravity.cpp' in str(source), sources)
envCopy = env.Clone()
envCopy.Append(CCFLAGS='-mstackrealign')
sources += envCopy.Object('src/simulation/Gravity.cpp')
#elif platform == "Darwin":
# sources += ["src/SDLMain.m"]
#Program output name
if GetOption('output'):
programName = GetOption('output')
else:
programName = "powder"
if GetOption('renderer'):
programName = "render"
if GetOption('font'):
programName = "font"
if "BIT" in env and env["BIT"] == 64:
programName += "64"
if isX86 and GetOption('no-sse'):
programName += "-legacy"
if platform == "Windows":
programName = programName.capitalize()
programName += ".exe"
elif platform == "Darwin":
programName += "-x"
#strip binary after compilation
def strip():
global programName
global env
try:
os.system("{0} {1}/{2}".format(env['STRIP'] if 'STRIP' in env else "strip", GetOption('builddir'), programName))
except:
print("Couldn't strip binary")
if not GetOption('debugging') and not GetOption('symbols') and not GetOption('clean') and not GetOption('help') and not msvc:
atexit.register(strip)
#Long command line fix for mingw on windows
if compilePlatform == "Windows" and not msvc:
SetupSpawn(env)
#Once we get here, finally compile
env.Decider('MD5-timestamp')
SetOption('implicit_cache', 1)
t = env.Program(target=programName, source=sources)
Default(t)

View File

@ -1,18 +0,0 @@
AddOption('--builddir',dest="builddir",default="build",help="Directory to build to.")
SConscript('SConscript', variant_dir=GetOption('builddir'), duplicate=0)
if GetOption('clean'):
import os, shutil
try:
shutil.rmtree(".sconf_temp/")
except:
print("couldn't remove .sconf_temp/")
try:
shutil.rmtree("generated/")
except:
print("couldn't remove generated/")
try:
os.remove(".sconsign.dblite")
except:
print("couldn't remove .sconsign.dblite")

View File

@ -1,4 +1,6 @@
#pragma once
#include "Config.h"
const char *const introTextData =
"\blThe Powder Toy - Version " MTOS(SAVE_VERSION) "." MTOS(MINOR_VERSION) " - https://powdertoy.co.uk, irc.freenode.net #powder\n"
"\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\xEE\x81\xA9\n"

File diff suppressed because one or more lines are too long

View File

@ -1,3 +1,5 @@
#include "images.h"
/**
* Powder Toy - Images
*

10
data/meson.build Normal file
View File

@ -0,0 +1,10 @@
data_files = files(
'font.cpp',
'hmap.cpp',
'icon.cpp',
'images.cpp',
)
powder_files += data_files
render_files += data_files
font_files += data_files

317
meson.build Normal file
View File

@ -0,0 +1,317 @@
project('the-powder-toy', [ 'c', 'cpp' ], version: 'the.cake.is.a.lie', default_options: [
'cpp_std=c++11',
'b_vscrt=md',
'backend_startup_project=powder',
])
cpp_compiler = meson.get_compiler('cpp')
project_c_args = []
project_cpp_args = []
project_link_args = []
conf_data = configuration_data()
conf_data.set('CURL_STATICLIB', false)
conf_data.set('ZLIB_WINAPI', false)
copt_x86 = host_machine.cpu_family() in [ 'x86_64', 'x86' ]
copt_64bit = host_machine.cpu_family() in [ 'x86_64', 'aarch64' ]
copt_msvc = cpp_compiler.get_id() in [ 'msvc' ]
if host_machine.system() in [ 'linux', 'freebsd' ]
copt_platform = 'linux'
elif host_machine.system() in [ 'windows' ]
copt_platform = 'windows'
elif host_machine.system() in [ 'darwin' ]
copt_platform = 'macosx'
else
error('unsupported platform: ' + host_machine.system())
endif
if copt_platform == 'linux' and not copt_64bit
error('lin32 is not supported')
endif
if copt_platform == 'windows' and not copt_64bit
error('win32 is not supported')
endif
if copt_platform == 'macosx' and not copt_64bit
error('mac32 is not even a thing')
endif
if get_option('ogli') or get_option('oglr')
error('OpenGL features are currently unavailable')
endif
uopt_static = get_option('static')
use_tpt_libs = false
if uopt_static == 'system'
if copt_platform == 'windows'
error('no way to find static system libraries on windows')
endif
elif uopt_static == 'prebuilt'
if copt_platform == 'windows'
use_tpt_libs = true
tpt_libs = subproject('tpt-libs-prebuilt-win64-static')
elif copt_platform == 'linux'
use_tpt_libs = true
tpt_libs = subproject('tpt-libs-prebuilt-lin64-static')
elif copt_platform == 'macosx'
use_tpt_libs = true
tpt_libs = subproject('tpt-libs-prebuilt-mac64-static')
endif
else
if copt_platform == 'windows'
use_tpt_libs = true
tpt_libs = subproject('tpt-libs-prebuilt-win64-dynamic')
endif
endif
uopt_native = get_option('native')
uopt_x86_sse = get_option('x86_sse')
if uopt_x86_sse == 'auto'
uopt_x86_sse_level = 20
elif uopt_x86_sse == 'sse3'
uopt_x86_sse_level = 30
elif uopt_x86_sse == 'sse2'
uopt_x86_sse_level = 20
elif uopt_x86_sse == 'sse'
uopt_x86_sse_level = 10
elif uopt_x86_sse == 'none'
uopt_x86_sse_level = 0
endif
if not copt_x86 or uopt_native
uopt_x86_sse_level = 0
endif
uopt_lua = get_option('lua')
if uopt_lua == 'luajit'
lua_opt_dep = [ use_tpt_libs ? tpt_libs.get_variable('luajit_dep') : dependency('luajit', static: uopt_static == 'system') ]
elif uopt_lua == 'lua5.2'
lua_opt_dep = [ use_tpt_libs ? tpt_libs.get_variable('lua52_dep') : dependency('lua5.2', static: uopt_static == 'system') ]
elif uopt_lua == 'lua5.1'
lua_opt_dep = [ use_tpt_libs ? tpt_libs.get_variable('lua51_dep') : dependency('lua5.1', static: uopt_static == 'system') ]
else
lua_opt_dep = []
endif
uopt_http = get_option('http')
if uopt_http
curl_opt_dep = [ use_tpt_libs ? tpt_libs.get_variable('libcurl_dep') : dependency('libcurl', static: uopt_static == 'system') ]
else
curl_opt_dep = []
endif
uopt_fftw = get_option('gravfft')
if uopt_fftw
fftw_opt_dep = [ use_tpt_libs ? tpt_libs.get_variable('fftw_dep') : dependency('fftw3f', static: uopt_static == 'system') ]
else
fftw_opt_dep = []
endif
threads_dep = dependency('threads')
zlib_dep = use_tpt_libs ? tpt_libs.get_variable('zlib_dep') : dependency('zlib', static: uopt_static == 'system')
sdl2_dep = use_tpt_libs ? tpt_libs.get_variable('sdl2_dep') : dependency('sdl2', static: uopt_static == 'system')
bzip2_dep = subproject('tpt-bzip2').get_variable('bzip2_dep')
if copt_msvc
if uopt_x86_sse_level >= 30
message('SSE3 configured to be enabled but unavailable in msvc')
uopt_x86_sse_level = 20
endif
if uopt_native
message('local machine optimization configured to be enabled but unavailable in msvc')
uopt_native = false
endif
if copt_64bit
message('SSE explicitly configured but unavailable in msvc targeting 64-bit machines')
else
args_msvc_sse = []
if uopt_x86_sse_level >= 20
args_msvc_sse += '/arch:SSE2'
elif uopt_x86_sse_level >= 10
args_msvc_sse += '/arch:SSE'
endif
project_c_args += args_msvc_sse
project_cpp_args += args_msvc_sse
endif
args_msvc = [ '/GS', '-D_SCL_SECURE_NO_WARNINGS' ]
project_c_args += args_msvc
project_cpp_args += args_msvc
project_link_args += [
'/OPT:REF',
'/OPT:ICF',
]
if not get_option('debug')
args_msvc_opt = [ '/Oy-', '/fp:fast' ]
project_c_args += args_msvc_opt
project_cpp_args += args_msvc_opt
endif
else
if copt_platform == 'macosx'
if uopt_x86_sse_level >= 0
message('SSE level explicitly configured but unavailable on macosx')
uopt_x86_sse_level = 0
endif
if uopt_native
message('local machine optimization configured to be enabled but unavailable on macosx')
uopt_native = false
endif
else
args_ccomp_sse = []
if uopt_x86_sse_level >= 30
args_ccomp_sse += '-msse3'
endif
if uopt_x86_sse_level >= 20
args_ccomp_sse += '-msse2'
endif
if uopt_x86_sse_level >= 10
args_ccomp_sse += '-msse'
endif
if uopt_native
args_ccomp_sse += '-march=native'
endif
project_c_args += args_ccomp_sse
project_cpp_args += args_ccomp_sse
endif
project_c_args += [ '-U__STRICT_ANSI__', '-Wno-unused-result' ]
project_cpp_args += [ '-U__STRICT_ANSI__', '-Wno-unused-result', '-Wno-invalid-offsetof' ]
if not get_option('debug')
args_ccomp = [ '-ftree-vectorize', '-funsafe-math-optimizations', '-ffast-math', '-fomit-frame-pointer' ]
project_c_args += args_ccomp
project_cpp_args += args_ccomp
endif
endif
if copt_platform == 'windows'
other_dep = tpt_libs.get_variable('other_dep')
sdl2main_dep = tpt_libs.get_variable('sdl2main_dep')
project_c_args += [ '-D_WIN32_WINNT=0x0501' ]
project_cpp_args += [ '-D_WIN32_WINNT=0x0501' ]
windows_mod = import('windows')
if uopt_static != 'none'
conf_data.set('CURL_STATICLIB', true)
conf_data.set('ZLIB_WINAPI', true)
else
foreach input_and_output : tpt_libs.get_variable('config_dlls')
configure_file(input: input_and_output[0], output: input_and_output[1], copy: true)
endforeach
endif
endif
if copt_platform == 'macosx' and uopt_lua == 'luajit'
project_link_args += [ '-pagezero_size', '10000', '-image_base', '100000000' ]
endif
project_inc = include_directories([ 'src', 'data', 'resources' ])
conf_data.set('LIN', copt_platform == 'linux')
conf_data.set('WIN', copt_platform == 'windows')
conf_data.set('MACOSX', copt_platform == 'macosx')
conf_data.set('X86', copt_x86)
conf_data.set('X86_SSE3', uopt_x86_sse_level >= 30)
conf_data.set('X86_SSE2', uopt_x86_sse_level >= 20)
conf_data.set('X86_SSE', uopt_x86_sse_level >= 10)
conf_data.set('NATIVE', uopt_native)
conf_data.set('_64BIT', copt_64bit)
conf_data.set('OGLI', get_option('ogli'))
conf_data.set('OGLR', get_option('oglr'))
conf_data.set('PIX32OGL', get_option('ogli'))
conf_data.set('BETA', get_option('beta'))
conf_data.set('NO_INSTALL_CHECK', not get_option('install_check'))
conf_data.set('IGNORE_UPDATES', get_option('ignore_updates'))
conf_data.set('SAVE_VERSION', get_option('version_major'))
conf_data.set('MINOR_VERSION', get_option('version_minor'))
conf_data.set('BUILD_NUM', get_option('version_build'))
conf_data.set('MOD_ID', get_option('mod_id'))
conf_data.set('DEBUG', get_option('debug'))
conf_data.set('SNAPSHOT', get_option('snapshot'))
conf_data.set('SNAPSHOT_ID', get_option('snapshot_id'))
conf_data.set('FUTURE_SAVE_VERSION', get_option('future_major'))
conf_data.set('FUTURE_MINOR_VERSION', get_option('future_minor'))
resources_files = []
subdir('src')
subdir('data')
subdir('resources')
if get_option('build_powder')
powder_args = []
if uopt_lua != 'none'
powder_args += '-DLUACONSOLE'
endif
if not uopt_http
powder_args += '-DNOHTTP'
endif
if uopt_fftw
powder_args += '-DGRAVFFT'
endif
powder_deps = [
threads_dep,
zlib_dep,
sdl2_dep,
bzip2_dep,
lua_opt_dep,
curl_opt_dep,
fftw_opt_dep,
]
if copt_platform == 'windows'
powder_deps += other_dep
powder_deps += sdl2main_dep
endif
executable(
'powder',
sources: powder_files,
include_directories: project_inc,
c_args: project_c_args + powder_args,
cpp_args: project_cpp_args + powder_args,
cpp_pch: 'pch/pch_cpp.h',
gui_app: true,
link_args: project_link_args,
dependencies: powder_deps,
)
endif
if get_option('build_render')
render_args = [ '-DRENDERER', '-DNOHTTP' ]
render_deps = [
threads_dep,
zlib_dep,
bzip2_dep,
]
executable(
'render',
sources: render_files,
include_directories: project_inc,
c_args: project_c_args + render_args,
cpp_args: project_cpp_args + render_args,
cpp_pch: 'pch/pch_cpp.h',
link_args: project_link_args,
dependencies: render_deps,
)
endif
if get_option('build_font')
font_args = [ '-DFONTEDITOR', '-DNOHTTP' ]
font_deps = [
threads_dep,
zlib_dep,
sdl2_dep,
bzip2_dep,
]
if copt_platform == 'windows'
font_deps += other_dep
font_deps += sdl2main_dep
endif
executable(
'font',
sources: font_files,
include_directories: project_inc,
c_args: project_c_args + font_args,
cpp_args: project_cpp_args + font_args,
cpp_pch: 'pch/pch_cpp.h',
gui_app: true,
link_args: project_link_args,
dependencies: font_deps,
)
endif

149
meson_options.txt Normal file
View File

@ -0,0 +1,149 @@
option(
'static',
type: 'combo',
choices: [ 'none', 'system', 'prebuilt' ],
value: 'none',
description: 'Build statically using libraries present on the system (\'system\') or using prebuilt libraries official builds use (\'prebuilt\')'
)
option(
'beta',
type: 'boolean',
value: false,
description: 'Beta build'
)
option(
'ignore_updates',
type: 'boolean',
value: true,
description: 'Don\'t show notifications about available updates'
)
option(
'install_check',
type: 'boolean',
value: false,
description: 'Do install check on startup'
)
option(
'http',
type: 'boolean',
value: true,
description: 'Enable HTTP via libcurl'
)
option(
'gravfft',
type: 'boolean',
value: true,
description: 'Enable FFT gravity via libfftw3'
)
option(
'snapshot',
type: 'boolean',
value: false,
description: 'Snapshot build'
)
option(
'version_major',
type: 'integer',
min: 0,
value: 95,
description: 'Major version'
)
option(
'version_minor',
type: 'integer',
min: 0,
value: 0,
description: 'Minor version'
)
option(
'version_build',
type: 'integer',
min: 0,
value: 345,
description: 'Build number'
)
option(
'snapshot_id',
type: 'integer',
min: 0,
value: 199,
description: 'Snapshot ID, only relevant if \'snapshot\' is true'
)
option(
'future_major',
type: 'integer',
min: 0,
value: 95,
description: 'Future major version, used for debugging and in snapshots, only relevant if at least one of \'debug\' and \'snapshot\' is true'
)
option(
'future_minor',
type: 'integer',
min: 0,
value: 0,
description: 'Future minor version, similar to \'future_major\''
)
option(
'mod_id',
type: 'integer',
min: 0,
value: 0,
description: 'Mod ID, used on the https://starcatcher.us/TPT build server, the build server will compile for all platforms for you and send updates in-game, see jacob1 to get a mod ID'
)
option(
'lua',
type: 'combo',
choices: [ 'none', 'lua5.1', 'lua5.2', 'luajit' ],
value: 'luajit',
description: 'Lua library to use'
)
option(
'ssl',
type: 'combo',
choices: [ 'openssl' ],
value: 'openssl',
description: 'SSL library to use'
)
option(
'x86_sse',
type: 'combo',
choices: [ 'none', 'sse', 'sse2', 'sse3', 'auto' ],
value: 'auto',
description: 'Enable SSE (available only on x86)'
)
option(
'native',
type: 'boolean',
value: false,
description: 'Build with optimizations specific to the local machine, may not run on other machines, overrides \'x86_sse\''
)
option(
'ogli',
type: 'boolean',
value: false,
description: 'Enable OpenGL interface rendering (currently defunct)'
)
option(
'oglr',
type: 'boolean',
value: false,
description: 'Enable OpenGL particle rendering (currently defunct)'
)
option(
'build_powder',
type: 'boolean',
value: true,
description: 'Build the game'
)
option(
'build_render',
type: 'boolean',
value: false,
description: 'Build the thumbnail renderer'
)
option(
'build_font',
type: 'boolean',
value: false,
description: 'Build the font editor'
)

95
pch/pch_cpp.h Normal file
View File

@ -0,0 +1,95 @@
#include "Config.h"
#include "common/Format.h"
#include "common/Singleton.h"
#include "common/String.h"
#include "common/tpt-compat.h"
#include "common/tpt-inline.h"
#include "common/tpt-minmax.h"
#include "common/tpt-rand.h"
#include "common/tpt-rand.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <condition_variable>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <ostream>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <thread>
#include <typeinfo>
#include <type_traits>
#include <utility>
#include <vector>
#include <errno.h>
#include <fcntl.h>
#include <fftw3.h>
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef WIN
# include <sys/param.h>
# include <sys/poll.h>
# include <sys/socket.h>
# include <sys/stat.h>
# include <sys/time.h>
# include <sys/types.h>
# include <sys/un.h>
#endif
#ifdef WIN
# include <shlobj.h>
# include <shlwapi.h>
# include <windows.h>
# include <winsock.h>
#endif
#include <bzlib.h>
#include <curl/curl.h>
#include <bson/BSON.h>
#include <json/json-forwards.h>
#include <json/json.h>
#include <zlib.h>
#if !defined(FONTEDITOR) && !defined(RENDERER)
# include "lua/LuaCompat.h"
#endif
#include "SDLCompat.h"

11
resources/meson.build Normal file
View File

@ -0,0 +1,11 @@
resources_files += files(
'icon.ico',
'document.ico',
)
if copt_platform == 'windows'
powder_files += windows_mod.compile_resources(
'powder-res.rc',
depend_files: resources_files,
)
endif

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include "gui/interface/Window.h"

View File

@ -1,47 +1,50 @@
#ifndef CONFIG_H
#define CONFIG_H
#mesondefine CURL_STATICLIB
#mesondefine ZLIB_WINAPI
#mesondefine BETA
#mesondefine DEBUG
#mesondefine IGNORE_UPDATES
#mesondefine LIN
#mesondefine NATIVE
#mesondefine NO_INSTALL_CHECK
#mesondefine OGLI
#mesondefine OGLR
#mesondefine PIX32OGL
#mesondefine SNAPSHOT
#mesondefine WIN
#mesondefine MACOSX
#mesondefine X86
#mesondefine X86_SSE
#mesondefine X86_SSE2
#mesondefine X86_SSE3
#mesondefine _64BIT
#ifdef WIN
#define PATH_SEP "\\"
#define PATH_SEP_CHAR '\\'
# define PATH_SEP "\\"
# define PATH_SEP_CHAR '\\'
#else
#define PATH_SEP "/"
#define PATH_SEP_CHAR '/'
# define PATH_SEP "/"
# define PATH_SEP_CHAR '/'
#endif
//VersionInfoStart
#ifndef SAVE_VERSION
#define SAVE_VERSION 95
#endif
#mesondefine SAVE_VERSION
#mesondefine MINOR_VERSION
#mesondefine BUILD_NUM
#mesondefine SNAPSHOT_ID
#mesondefine MOD_ID
#mesondefine FUTURE_SAVE_VERSION
#mesondefine FUTURE_MINOR_VERSION
#ifndef MINOR_VERSION
#define MINOR_VERSION 0
#endif
#ifndef BUILD_NUM
#define BUILD_NUM 345
#endif
#ifndef SNAPSHOT_ID
#define SNAPSHOT_ID 0
#endif
// Mod ID, used on the https://starcatcher.us/TPT build server
// The build server will compile for all platforms for you, and send updates in game
// See jacob1 to get a mod ID
#ifndef MOD_ID
#define MOD_ID 0
#endif
#if defined(SNAPSHOT) || defined(BETA) || defined(DEBUG) || MOD_ID > 0
#define FUTURE_SAVE_VERSION 96
#define FUTURE_MINOR_VERSION 0
#if !(defined(SNAPSHOT) || defined(BETA) || defined(DEBUG) || MOD_ID > 0)
#undef FUTURE_SAVE_VERSION
#undef FUTURE_MINOR_VERSION
#endif
//VersionInfoEnd
//#define IGNORE_UPDATES //uncomment this for mods, to not get any update notifications
#if !(defined(MACOSX) && defined(DEBUG))
#define HIGH_QUALITY_RESAMPLE //High quality image resampling, slower but much higher quality than my terribad linear interpolation
#endif
@ -118,8 +121,6 @@
#define WINDOWW (XRES+BARSIZE)
#define WINDOWH (YRES+MENUSIZE)
#define MAX_DISTANCE sqrt(pow((float)XRES, 2)+pow((float)YRES, 2))
#define GRAV_DIFF
#define MAXSIGNS 16

View File

@ -7,6 +7,7 @@ private:
virtual void Exit();
virtual void Show();
virtual void Hide();
virtual ~Controller() = default;
};
#endif /* CONTROLLER_H_ */

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include "common/String.h"
#include <vector>

View File

@ -1,5 +1,6 @@
#ifndef UTILS_H
#define UTILS_H
#include "Config.h"
#include <cstdio>
#include <cstdlib>
#include <vector>

View File

@ -1,5 +1,6 @@
#ifndef PLATFORM_H
#define PLATFORM_H
#include "Config.h"
#include "common/String.h"

475
src/PowderToyFontEditor.cpp Normal file
View File

@ -0,0 +1,475 @@
#include "Config.h"
#include <ctime>
#include <climits>
#ifdef WIN
#include <direct.h>
#endif
#include "SDLCompat.h"
#ifdef X86_SSE
#include <xmmintrin.h>
#endif
#ifdef X86_SSE3
#include <pmmintrin.h>
#endif
#include <iostream>
#if defined(LIN)
#include "icon.h"
#endif
#include <stdexcept>
#ifndef WIN
#include <unistd.h>
#endif
#ifdef MACOSX
# include "common/macosx.h"
#endif
#include "Format.h"
#include "Misc.h"
#include "graphics/Graphics.h"
#include "client/SaveInfo.h"
#include "client/GameSave.h"
#include "client/SaveFile.h"
#include "client/Client.h"
#include "gui/game/GameController.h"
#include "gui/game/GameView.h"
#include "gui/font/FontEditor.h"
#include "gui/dialogues/ErrorMessage.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "gui/interface/Keys.h"
#include "gui/Style.h"
#include "gui/interface/Engine.h"
#define INCLUDE_SYSWM
#include "SDLCompat.h"
int desktopWidth = 1280, desktopHeight = 1024;
SDL_Window * sdl_window;
SDL_Renderer * sdl_renderer;
SDL_Texture * sdl_texture;
int scale = 1;
bool fullscreen = false;
bool altFullscreen = false;
bool forceIntegerScaling = true;
bool resizable = false;
void ClipboardPush(ByteString text)
{
SDL_SetClipboardText(text.c_str());
}
ByteString ClipboardPull()
{
return ByteString(SDL_GetClipboardText());
}
int GetModifiers()
{
return SDL_GetModState();
}
void CalculateMousePosition(int *x, int *y)
{
int globalMx, globalMy;
SDL_GetGlobalMouseState(&globalMx, &globalMy);
int windowX, windowY;
SDL_GetWindowPosition(sdl_window, &windowX, &windowY);
if (x)
*x = (globalMx - windowX) / scale;
if (y)
*y = (globalMy - windowY) / scale;
}
#ifdef OGLI
void blit()
{
SDL_GL_SwapBuffers();
}
#else
void blit(pixel * vid)
{
SDL_UpdateTexture(sdl_texture, NULL, vid, WINDOWW * sizeof (Uint32));
// need to clear the renderer if there are black edges (fullscreen, or resizable window)
if (fullscreen || resizable)
SDL_RenderClear(sdl_renderer);
SDL_RenderCopy(sdl_renderer, sdl_texture, NULL, NULL);
SDL_RenderPresent(sdl_renderer);
}
#endif
void RecreateWindow();
int SDLOpen()
{
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "Initializing SDL: %s\n", SDL_GetError());
return 1;
}
RecreateWindow();
int displayIndex = SDL_GetWindowDisplayIndex(sdl_window);
if (displayIndex >= 0)
{
SDL_Rect rect;
if (!SDL_GetDisplayUsableBounds(displayIndex, &rect))
{
desktopWidth = rect.w;
desktopHeight = rect.h;
}
}
#ifdef WIN
SDL_SysWMinfo SysInfo;
SDL_VERSION(&SysInfo.version);
if(SDL_GetWindowWMInfo(sdl_window, &SysInfo) <= 0)
{
printf("%s : %p\n", SDL_GetError(), SysInfo.info.win.window);
exit(-1);
}
HWND WindowHandle = SysInfo.info.win.window;
// Use GetModuleHandle to get the Exe HMODULE/HINSTANCE
HMODULE hModExe = GetModuleHandle(NULL);
HICON hIconSmall = (HICON)LoadImage(hModExe, MAKEINTRESOURCE(101), IMAGE_ICON, 16, 16, LR_SHARED);
HICON hIconBig = (HICON)LoadImage(hModExe, MAKEINTRESOURCE(101), IMAGE_ICON, 32, 32, LR_SHARED);
SendMessage(WindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
SendMessage(WindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
#endif
#ifdef LIN
SDL_Surface *icon = SDL_CreateRGBSurfaceFrom((void*)app_icon, 128, 128, 32, 512, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
SDL_SetWindowIcon(sdl_window, icon);
SDL_FreeSurface(icon);
#endif
return 0;
}
void SDLSetScreen(int scale_, bool resizable_, bool fullscreen_, bool altFullscreen_, bool forceIntegerScaling_)
{
// bool changingScale = scale != scale_;
bool changingFullscreen = fullscreen_ != fullscreen || (altFullscreen_ != altFullscreen && fullscreen);
bool changingResizable = resizable != resizable_;
scale = scale_;
fullscreen = fullscreen_;
altFullscreen = altFullscreen_;
resizable = resizable_;
forceIntegerScaling = forceIntegerScaling_;
// Recreate the window when toggling fullscreen, due to occasional issues
// Also recreate it when enabling resizable windows, to fix bugs on windows,
// see https://github.com/jacob1/The-Powder-Toy/issues/24
if (changingFullscreen || (changingResizable && resizable && !fullscreen))
{
RecreateWindow();
return;
}
if (changingResizable)
SDL_RestoreWindow(sdl_window);
SDL_SetWindowSize(sdl_window, WINDOWW * scale, WINDOWH * scale);
SDL_RenderSetIntegerScale(sdl_renderer, forceIntegerScaling && fullscreen ? SDL_TRUE : SDL_FALSE);
unsigned int flags = 0;
if (fullscreen)
flags = altFullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_FULLSCREEN_DESKTOP;
SDL_SetWindowFullscreen(sdl_window, flags);
if (fullscreen)
SDL_RaiseWindow(sdl_window);
SDL_SetWindowResizable(sdl_window, resizable ? SDL_TRUE : SDL_FALSE);
}
void RecreateWindow()
{
unsigned int flags = 0;
if (fullscreen)
flags = altFullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_FULLSCREEN_DESKTOP;
if (resizable && !fullscreen)
flags |= SDL_WINDOW_RESIZABLE;
if (sdl_texture)
SDL_DestroyTexture(sdl_texture);
if (sdl_renderer)
SDL_DestroyRenderer(sdl_renderer);
if (sdl_window)
{
SDL_DestroyWindow(sdl_window);
}
sdl_window = SDL_CreateWindow("The Powder Toy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOWW * scale, WINDOWH * scale,
flags);
sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
SDL_RenderSetLogicalSize(sdl_renderer, WINDOWW, WINDOWH);
if (forceIntegerScaling && fullscreen)
SDL_RenderSetIntegerScale(sdl_renderer, SDL_TRUE);
sdl_texture = SDL_CreateTexture(sdl_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WINDOWW, WINDOWH);
SDL_RaiseWindow(sdl_window);
//Uncomment this to enable resizing
//SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
//SDL_SetWindowResizable(sdl_window, SDL_TRUE);
}
unsigned int GetTicks()
{
return SDL_GetTicks();
}
int elapsedTime = 0, currentTime = 0, lastTime = 0, currentFrame = 0;
unsigned int lastTick = 0;
unsigned int lastFpsUpdate = 0;
float fps = 0;
ui::Engine * engine = NULL;
bool showDoubleScreenDialog = false;
float currentWidth, currentHeight;
int mousex = 0, mousey = 0;
int mouseButton = 0;
bool mouseDown = false;
bool calculatedInitialMouse = false, delay = false;
bool hasMouseMoved = false;
void EventProcess(SDL_Event event)
{
switch (event.type)
{
case SDL_QUIT:
if (engine->GetFastQuit() || engine->CloseWindow())
engine->Exit();
break;
case SDL_KEYDOWN:
if (!event.key.repeat && event.key.keysym.sym == 'q' && (event.key.keysym.mod&KMOD_CTRL))
engine->ConfirmExit();
else
engine->onKeyPress(event.key.keysym.sym, event.key.keysym.scancode, event.key.repeat, event.key.keysym.mod&KMOD_SHIFT, event.key.keysym.mod&KMOD_CTRL, event.key.keysym.mod&KMOD_ALT);
break;
case SDL_KEYUP:
engine->onKeyRelease(event.key.keysym.sym, event.key.keysym.scancode, event.key.repeat, event.key.keysym.mod&KMOD_SHIFT, event.key.keysym.mod&KMOD_CTRL, event.key.keysym.mod&KMOD_ALT);
break;
case SDL_TEXTINPUT:
engine->onTextInput(ByteString(event.text.text).FromUtf8());
break;
case SDL_MOUSEWHEEL:
{
int x = event.wheel.x;
int y = event.wheel.y;
if (event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED)
{
x *= -1;
y *= -1;
}
engine->onMouseWheel(mousex, mousey, y); // TODO: pass x?
break;
}
case SDL_MOUSEMOTION:
mousex = event.motion.x;
mousey = event.motion.y;
engine->onMouseMove(mousex, mousey);
hasMouseMoved = true;
break;
case SDL_DROPFILE:
engine->onFileDrop(event.drop.file);
SDL_free(event.drop.file);
break;
case SDL_MOUSEBUTTONDOWN:
// if mouse hasn't moved yet, sdl will send 0,0. We don't want that
if (hasMouseMoved)
{
mousex = event.motion.x;
mousey = event.motion.y;
}
mouseButton = event.button.button;
engine->onMouseClick(event.motion.x, event.motion.y, mouseButton);
mouseDown = true;
#if !defined(NDEBUG) && !defined(DEBUG)
SDL_CaptureMouse(SDL_TRUE);
#endif
break;
case SDL_MOUSEBUTTONUP:
// if mouse hasn't moved yet, sdl will send 0,0. We don't want that
if (hasMouseMoved)
{
mousex = event.motion.x;
mousey = event.motion.y;
}
mouseButton = event.button.button;
engine->onMouseUnclick(mousex, mousey, mouseButton);
mouseDown = false;
#if !defined(NDEBUG) && !defined(DEBUG)
SDL_CaptureMouse(SDL_FALSE);
#endif
break;
case SDL_WINDOWEVENT:
{
switch (event.window.event)
{
case SDL_WINDOWEVENT_SHOWN:
if (!calculatedInitialMouse)
{
//initial mouse coords, sdl won't tell us this if mouse hasn't moved
CalculateMousePosition(&mousex, &mousey);
engine->onMouseMove(mousex, mousey);
calculatedInitialMouse = true;
}
break;
// This event would be needed in certain glitchy cases of window resizing
// But for all currently tested cases, it isn't needed
/*case SDL_WINDOWEVENT_RESIZED:
{
float width = event.window.data1;
float height = event.window.data2;
currentWidth = width;
currentHeight = height;
// this "* scale" thing doesn't really work properly
// currently there is a bug where input doesn't scale properly after resizing, only when double scale mode is active
inputScaleH = (float)WINDOWW * scale / currentWidth;
inputScaleV = (float)WINDOWH * scale / currentHeight;
std::cout << "Changing input scale to " << inputScaleH << "x" << inputScaleV << std::endl;
break;
}*/
// This would send a mouse up event when focus is lost
// Not even sdl itself will know when the mouse was released if it happens in another window
// So it will ignore the next mouse down (after tpt is re-focused) and not send any events at all
// This is more unintuitive than pretending the mouse is still down when it's not, so this code is commented out
/*case SDL_WINDOWEVENT_FOCUS_LOST:
if (mouseDown)
{
mouseDown = false;
engine->onMouseUnclick(mousex, mousey, mouseButton);
}
break;*/
}
break;
}
}
}
void EngineProcess()
{
double frameTimeAvg = 0.0f, correctedFrameTimeAvg = 0.0f;
SDL_Event event;
while(engine->Running())
{
int frameStart = SDL_GetTicks();
if(engine->Broken()) { engine->UnBreak(); break; }
event.type = 0;
while (SDL_PollEvent(&event))
{
EventProcess(event);
event.type = 0; //Clear last event
}
if(engine->Broken()) { engine->UnBreak(); break; }
engine->Tick();
engine->Draw();
if (scale != engine->Scale || fullscreen != engine->Fullscreen ||
altFullscreen != engine->GetAltFullscreen() ||
forceIntegerScaling != engine->GetForceIntegerScaling() || resizable != engine->GetResizable())
{
SDLSetScreen(engine->Scale, engine->GetResizable(), engine->Fullscreen, engine->GetAltFullscreen(),
engine->GetForceIntegerScaling());
}
#ifdef OGLI
blit();
#else
blit(engine->g->vid);
#endif
int frameTime = SDL_GetTicks() - frameStart;
frameTimeAvg = frameTimeAvg * 0.8 + frameTime * 0.2;
int fpsLimit = ui::Engine::Ref().FpsLimit;
if(fpsLimit > 2)
{
double offset = 1000.0 / fpsLimit - frameTimeAvg;
if(offset > 0)
SDL_Delay(offset + 0.5);
}
int correctedFrameTime = SDL_GetTicks() - frameStart;
correctedFrameTimeAvg = correctedFrameTimeAvg * 0.95 + correctedFrameTime * 0.05;
if (frameStart - lastFpsUpdate > 200)
{
engine->SetFps(1000.0 / correctedFrameTimeAvg);
lastFpsUpdate = frameStart;
}
if (frameStart - lastTick > 100)
{
lastTick = frameStart;
}
if (showDoubleScreenDialog)
{
showDoubleScreenDialog = false;
}
}
#ifdef DEBUG
std::cout << "Breaking out of EngineProcess" << std::endl;
#endif
}
int main(int argc, char * argv[])
{
currentWidth = WINDOWW;
currentHeight = WINDOWH;
scale = 1;
if (argc >= 3)
{
std::istringstream ss(argv[2]);
int buf;
if (ss >> buf)
{
scale = buf;
}
}
resizable = false;
fullscreen = false;
altFullscreen = false;
forceIntegerScaling = true;
// TODO: maybe bind the maximum allowed scale to screen size somehow
if(scale < 1 || scale > 10)
scale = 1;
SDLOpen();
ui::Engine::Ref().g = new Graphics();
ui::Engine::Ref().Scale = scale;
ui::Engine::Ref().SetResizable(resizable);
ui::Engine::Ref().Fullscreen = fullscreen;
ui::Engine::Ref().SetAltFullscreen(altFullscreen);
ui::Engine::Ref().SetForceIntegerScaling(forceIntegerScaling);
engine = &ui::Engine::Ref();
engine->SetMaxSize(desktopWidth, desktopHeight);
engine->Begin(WINDOWW, WINDOWH);
engine->SetFastQuit(true);
GameController * gameController = NULL;
if (argc >= 2)
{
engine->ShowWindow(new FontEditor(argv[1]));
}
else
{
throw std::runtime_error("path to font.cpp not supplied");
}
EngineProcess();
ui::Engine::Ref().CloseWindow();
delete gameController;
delete ui::Engine::Ref().g;
return 0;
}

View File

@ -1,5 +1,4 @@
#if defined(RENDERER)
#include "Config.h"
#include "graphics/Graphics.h"
#include "graphics/Renderer.h"
@ -9,7 +8,6 @@
#include <vector>
#include "common/String.h"
#include "Config.h"
#include "Format.h"
#include "gui/interface/Engine.h"
@ -56,9 +54,16 @@ void writeFile(ByteString filename, std::vector<char> & fileData)
}
}
// * On windows, sdl2 (which gets included somewhere along the way) defines
// main away to some identifier which sdl2main calls. The renderer is not
// linked against sdl2main, so we get an undefined reference to main. This
// can be fixed by removing the macro.
#ifdef main
# undef main
#endif
int main(int argc, char *argv[])
{
ui::Engine * engine;
ByteString outputPrefix, inputFilename;
std::vector<char> inputFile;
ByteString ppmFilename, ptiFilename, ptiSmallFilename, pngFilename, pngSmallFilename;
@ -79,11 +84,6 @@ int main(int argc, char *argv[])
readFile(inputFilename, inputFile);
ui::Engine::Ref().g = new Graphics();
engine = &ui::Engine::Ref();
engine->Begin(WINDOWW, WINDOWH);
GameSave * gameSave = NULL;
try
{
@ -97,7 +97,7 @@ int main(int argc, char *argv[])
}
Simulation * sim = new Simulation();
Renderer * ren = new Renderer(ui::Engine::Ref().g, sim);
Renderer * ren = new Renderer(new Graphics(), sim);
if (gameSave)
{
@ -143,5 +143,3 @@ int main(int argc, char *argv[])
writeFile(pngFilename, pngFile);
writeFile(pngSmallFilename, pngSmallFile);
}
#endif

View File

@ -1,6 +1,6 @@
#ifndef RENDERER
#include "Config.h"
#include "common/tpt-minmax.h"
#include <map>
#include <ctime>
#include <climits>
@ -25,10 +25,14 @@
#include <stdexcept>
#ifndef WIN
#include <unistd.h>
# include <unistd.h>
#endif
#ifdef MACOSX
#include <CoreServices/CoreServices.h>
# ifdef DEBUG
# undef DEBUG
# define DEBUG 1
# endif
# include <CoreServices/CoreServices.h>
#endif
#include <sys/stat.h>
@ -44,7 +48,6 @@
#include "gui/game/GameController.h"
#include "gui/game/GameView.h"
#include "gui/font/FontEditor.h"
#include "gui/dialogues/ErrorMessage.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "gui/interface/Keys.h"
@ -154,7 +157,7 @@ void blit(pixel * vid)
}
#endif
void RecreateWindow();
bool RecreateWindow();
void SDLOpen()
{
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
@ -163,7 +166,11 @@ void SDLOpen()
exit(-1);
}
RecreateWindow();
if (!RecreateWindow())
{
fprintf(stderr, "Creating SDL window: %s\n", SDL_GetError());
exit(-1);
}
int displayIndex = SDL_GetWindowDisplayIndex(sdl_window);
if (displayIndex >= 0)
@ -240,7 +247,7 @@ void SDLSetScreen(int scale_, bool resizable_, bool fullscreen_, bool altFullscr
SDL_SetWindowResizable(sdl_window, resizable ? SDL_TRUE : SDL_FALSE);
}
void RecreateWindow()
bool RecreateWindow()
{
unsigned int flags = 0;
if (fullscreen)
@ -261,6 +268,18 @@ void RecreateWindow()
sdl_window = SDL_CreateWindow("The Powder Toy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOWW * scale, WINDOWH * scale,
flags);
sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
if (!sdl_renderer)
{
fprintf(stderr, "SDL_CreateRenderer failed; available renderers:\n");
int num = SDL_GetNumRenderDrivers();
for (int i = 0; i < num; ++i)
{
SDL_RendererInfo info;
SDL_GetRenderDriverInfo(i, &info);
fprintf(stderr, " - %s\n", info.name);
}
return false;
}
SDL_RenderSetLogicalSize(sdl_renderer, WINDOWW, WINDOWH);
if (forceIntegerScaling && fullscreen)
SDL_RenderSetIntegerScale(sdl_renderer, SDL_TRUE);
@ -272,6 +291,8 @@ void RecreateWindow()
if (!Client::Ref().IsFirstRun())
LoadWindowPosition();
return true;
}
unsigned int GetTicks()
@ -294,6 +315,7 @@ std::map<ByteString, ByteString> readArguments(int argc, char * argv[])
arguments["open"] = "";
arguments["ddir"] = "";
arguments["ptsave"] = "";
arguments["font"] = "";
for (int i=1; i<argc; i++)
{
@ -301,6 +323,10 @@ std::map<ByteString, ByteString> readArguments(int argc, char * argv[])
{
arguments["scale"] = argv[i]+6;
}
if (!strncmp(argv[i], "font:", 5) && argv[i]+5)
{
arguments["font"] = argv[i]+5;
}
else if (!strncmp(argv[i], "proxy:", 6))
{
if(argv[i]+6)
@ -670,7 +696,6 @@ int main(int argc, char * argv[])
fprintf(stderr, "Initializing SDL: %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Quit);
std::map<ByteString, ByteString> arguments = readArguments(argc, argv);
@ -835,7 +860,6 @@ int main(int argc, char * argv[])
try {
#endif
#ifndef FONTEDITOR
gameController = new GameController();
engine->ShowWindow(gameController->GetView());
@ -923,28 +947,8 @@ int main(int argc, char * argv[])
}
}
#else // FONTEDITOR
if(argc <= 1)
throw std::runtime_error("Usage: \n"
" Edit the font:\n"
" " + ByteString(argv[0]) + " ./data/font.cpp\n"
" Copy characters from source to target:\n"
" " + ByteString(argv[0]) + " <target/font.cpp> <source/font.cpp>\n");
if(argc <= 2)
{
engine->ShowWindow(new FontEditor(argv[1]));
EngineProcess();
SaveWindowPosition();
}
else
{
FontEditor(argv[1], argv[2]);
}
#endif
#ifndef FONTEDITOR
EngineProcess();
SaveWindowPosition();
#endif
#if !defined(DEBUG) && !defined(_DEBUG)
}
@ -961,5 +965,3 @@ int main(int argc, char * argv[])
Client::Ref().Shutdown();
return 0;
}
#endif

View File

@ -15,6 +15,7 @@
#ifndef tptmath_h
#define tptmath_h
#include "Config.h"
// This file is used for EMP, to simulate many EMP going off at once at the end of the frame

View File

@ -1,15 +1,7 @@
#ifdef SDL_INC
#include "Config.h"
#include "SDL2/SDL.h"
#else
#include "SDL.h"
#endif
#ifdef INCLUDE_SYSWM
#if defined(WIN)
#ifdef SDL_INC
#include <SDL2/SDL_syswm.h>
#else
#include <SDL_syswm.h>
#endif
#endif // WIN
# if defined(WIN)
# include <SDL2/SDL_syswm.h>
# endif // WIN
#endif // INCLUDE_SYSWM

View File

@ -1,16 +0,0 @@
/* SDLMain.m - main entry point for our Cocoa-ized SDL app
Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
Non-NIB-Code & other changes: Max Horn <max@quendi.de>
Feel free to customize this file to suit your needs
*/
#ifndef _SDLMain_h_
#define _SDLMain_h_
#import <Cocoa/Cocoa.h>
@interface SDLMain : NSObject
@end
#endif /* _SDLMain_h_ */

View File

@ -1,433 +0,0 @@
/* SDLMain.m - main entry point for our Cocoa-ized SDL app
Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
Non-NIB-Code & other changes: Max Horn <max@quendi.de>
Feel free to customize this file to suit your needs
*/
#include "SDLCompat.h"
#include "SDLMain.h"
#include <sys/param.h> /* for MAXPATHLEN */
#include <unistd.h>
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare
it ourselves here. */
@interface NSApplication(SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu;
@end
/* Use this flag to determine whether we use SDLMain.nib or not */
#define SDL_USE_NIB_FILE 0
/* Use this flag to determine whether we use CPS (docking) or not */
#define SDL_USE_CPS 1
#ifdef SDL_USE_CPS
/* Portions of CPS.h */
typedef struct CPSProcessSerNum
{
UInt32 lo;
UInt32 hi;
} CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
#endif /* SDL_USE_CPS */
static int gArgc;
static char **gArgv;
static BOOL gFinderLaunch;
static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void)
{
const NSDictionary *dict;
NSString *appName = 0;
/* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict)
appName = [dict objectForKey: @"CFBundleName"];
if (![appName length])
appName = [[NSProcessInfo processInfo] processName];
return appName;
}
#if SDL_USE_NIB_FILE
/* A helper category for NSString */
@interface NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
@end
#endif
@interface NSApplication (SDLApplication)
@end
@implementation NSApplication (SDLApplication)
/* Invoked from the Quit menu item */
- (void)terminate:(id)sender
{
/* Post a SDL_QUIT event */
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
@end
/* The main class of the application, the application's delegate */
@implementation SDLMain
/* Set the working directory to Application Support */
- (void) setupWorkingDirectory:(BOOL)shouldChdir
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
if ([paths count] < 1)
return;
NSString *appSupportPath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error = nil;
NSString *appPath = [appSupportPath stringByAppendingPathComponent:@"The Powder Toy"];
if (![[NSFileManager defaultManager] fileExistsAtPath:appPath isDirectory:&isDir] && isDir == NO)
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:appPath withIntermediateDirectories:YES attributes:nil error:&error])
{
NSLog(@"Could not set up working dir. Error: %@", error);
return;
}
}
chdir([appPath UTF8String]);
}
#if SDL_USE_NIB_FILE
/* Fix menu to contain the real app name instead of "SDL App" */
- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
{
NSRange aRange;
NSEnumerator *enumerator;
NSMenuItem *menuItem;
aRange = [[aMenu title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
enumerator = [[aMenu itemArray] objectEnumerator];
while ((menuItem = [enumerator nextObject]))
{
aRange = [[menuItem title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
if ([menuItem hasSubmenu])
[self fixMenu:[menuItem submenu] withAppName:appName];
}
}
#else
static void setApplicationMenu(void)
{
/* warning: this code is very odd */
NSMenu *appleMenu;
NSMenuItem *menuItem;
NSString *title;
NSString *appName;
appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */
title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
/* Tell the application object that this is now the application menu */
[NSApp setAppleMenu:appleMenu];
/* Finally give up our references to the objects */
[appleMenu release];
[menuItem release];
}
/* Create a window menu */
static void setupWindowMenu(void)
{
NSMenu *windowMenu;
NSMenuItem *windowMenuItem;
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem];
[menuItem release];
/* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu];
/* Finally give up our references to the objects */
[windowMenu release];
[windowMenuItem release];
}
/* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
SDLMain *sdlMain;
/* Ensure the application object is initialised */
[NSApplication sharedApplication];
#ifdef SDL_USE_CPS
{
CPSProcessSerNum PSN;
/* Tell the dock about us */
if (!CPSGetCurrentProcess(&PSN))
if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
if (!CPSSetFrontProcess(&PSN))
[NSApplication sharedApplication];
}
#endif /* SDL_USE_CPS */
/* Set up the menubar */
[NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu();
setupWindowMenu();
/* Create SDLMain and make it the app delegate */
sdlMain = [[SDLMain alloc] init];
[NSApp setDelegate:sdlMain];
/* Start the main event loop */
[NSApp run];
[sdlMain release];
[pool release];
}
#endif
/*
* Catch document open requests...this lets us notice files when the app
* was launched by double-clicking a document, or when a document was
* dragged/dropped on the app's icon. You need to have a
* CFBundleDocumentsType section in your Info.plist to get this message,
* apparently.
*
* Files are added to gArgv, so to the app, they'll look like command line
* arguments. Previously, apps launched from the finder had nothing but
* an argv[0].
*
* This message may be received multiple times to open several docs on launch.
*
* This message is ignored once the app's mainline has been called.
*/
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
const char *temparg;
size_t arglen;
char *arg;
char *openCommandArg;
char **newargv;
if (!gFinderLaunch) /* MacOS is passing command line args. */
return FALSE;
if (gCalledAppMainline) /* app has started, ignore this document. */
return FALSE;
temparg = [filename UTF8String];
arglen = SDL_strlen(temparg) + 1;
arg = (char *) SDL_malloc(arglen);
if (arg == NULL)
return FALSE;
openCommandArg = (char *) SDL_malloc(5);
if (openCommandArg == NULL)
return FALSE;
newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 3));
if (newargv == NULL)
{
SDL_free(arg);
return FALSE;
}
gArgv = newargv;
SDL_strlcpy(openCommandArg, "open", 5);
SDL_strlcpy(arg, temparg, arglen);
gArgv[gArgc++] = "open";
gArgv[gArgc++] = arg;
gArgv[gArgc] = NULL;
return TRUE;
}
/* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note
{
int status;
SInt32 versionMajor = 0, versionMinor = 0;
Gestalt(gestaltSystemVersionMajor, &versionMajor);
Gestalt(gestaltSystemVersionMinor, &versionMinor);
/* using gFinderLaunch doesn't work in Mavericks and above, so always change it */
if (versionMajor > 10 || versionMinor >= 9)
[self setupWorkingDirectory:TRUE];
else
[self setupWorkingDirectory:gFinderLaunch];
#if SDL_USE_NIB_FILE
/* Set the main menu to contain the real app name instead of "SDL App" */
[self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
#endif
/* Hand off to main application code */
gCalledAppMainline = TRUE;
status = SDL_main (gArgc, gArgv);
/* We're done, thank you for playing */
exit(status);
}
@end
@implementation NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
{
unsigned int bufferSize;
unsigned int selfLen = [self length];
unsigned int aStringLen = [aString length];
unichar *buffer;
NSRange localRange;
NSString *result;
bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
/* Get first part into buffer */
localRange.location = 0;
localRange.length = aRange.location;
[self getCharacters:buffer range:localRange];
/* Get middle part into buffer */
localRange.location = 0;
localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange];
/* Get last part into buffer */
localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
/* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize];
NSDeallocateMemoryPages(buffer, bufferSize);
return result;
}
@end
//doesn't work on OS X 10.5 or below
char * readClipboard()
{
NSPasteboard *clipboard = [NSPasteboard generalPasteboard];
NSArray *classes = [[NSArray alloc] initWithObjects:[NSString class], nil];
NSDictionary *options = [NSDictionary dictionary];
NSArray *clipboardItems = [clipboard readObjectsForClasses:classes options:options];
if(clipboardItems == nil || [clipboardItems count] == 0) return NULL;
NSString *newString = [clipboardItems objectAtIndex:0];
const char * clipboardData = [newString UTF8String];
if(clipboardData == NULL)
clipboardData = "";
char *clipboardDataCopy = calloc([newString length]+1, 1);
SDL_strlcpy(clipboardDataCopy, clipboardData, [newString length]+1);
return clipboardDataCopy;
}
//doesn't work on OS X 10.5 or below
void writeClipboard(const char * clipboardData)
{
NSPasteboard *clipboard = [NSPasteboard generalPasteboard];
NSString *newString = [NSString stringWithUTF8String: clipboardData];
[clipboard clearContents];
[clipboard setString:newString forType:NSStringPboardType];
}
#ifdef main
# undef main
#endif
/* Main entry point to executable - should *not* be SDL_main! */
int main (int argc, char **argv)
{
/* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
gArgv[0] = argv[0];
gArgv[1] = NULL;
gArgc = 1;
gFinderLaunch = YES;
} else {
int i;
gArgc = argc;
gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
for (i = 0; i <= argc; i++)
gArgv[i] = argv[i];
gFinderLaunch = NO;
}
#if SDL_USE_NIB_FILE
NSApplicationMain (argc, argv);
#else
CustomApplicationMain (argc, argv);
#endif
return 0;
}

View File

@ -1,5 +1,6 @@
#ifndef UPDATE_H_
#define UPDATE_H_
#include "Config.h"
//char *exe_name(void);
int update_start(char *data, unsigned int len);

View File

@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "BSON.h"
#include <cstdlib>
#include <cstring>
@ -21,7 +22,6 @@
#include <ctime>
#include <climits>
#include "BSON.h"
const int initialBufferSize = 128;

View File

@ -20,6 +20,7 @@
#ifndef _BSON_H_
#define _BSON_H_
#include "Config.h"
#include <ctime>
#include <cstdlib>

3
src/bson/meson.build Normal file
View File

@ -0,0 +1,3 @@
common_files += files(
'BSON.cpp',
)

View File

@ -11,8 +11,7 @@
#include <dirent.h>
#ifdef MACOSX
#include <mach-o/dyld.h>
#include <ApplicationServices/ApplicationServices.h>
# include "common/macosx.h"
#endif
#ifdef WIN
@ -104,11 +103,13 @@ Client::Client():
void Client::Initialise(ByteString proxyString, bool disableNetwork)
{
#if !defined(FONTEDITOR) && !defined(RENDERER)
if (GetPrefBool("version.update", false))
{
SetPref("version.update", false);
update_finish();
}
#endif
#ifndef NOHTTP
if (!disableNetwork)

View File

@ -1,5 +1,6 @@
#ifndef CLIENT_H
#define CLIENT_H
#include "Config.h"
#include <vector>
#include <list>

View File

@ -15,6 +15,8 @@
#include "simulation/Simulation.h"
#include "simulation/ElementClasses.h"
#include "common/tpt-minmax.h"
GameSave::GameSave(GameSave & save):
majorVersion(save.majorVersion),
waterEEnabled(save.waterEEnabled),

View File

@ -1,9 +1,9 @@
#ifndef The_Powder_Toy_GameSave_h
#define The_Powder_Toy_GameSave_h
#include "Config.h"
#include <vector>
#include "common/String.h"
#include "Config.h"
#include "Misc.h"
#include "bson/BSON.h"

View File

@ -1,5 +1,6 @@
#ifndef MD5_H
#define MD5_H
#include "Config.h"
struct md5_context
{

View File

@ -1,5 +1,6 @@
#ifndef SAVE_H
#define SAVE_H
#include "Config.h"
#include <list>
#include "common/String.h"

View File

@ -1,5 +1,6 @@
#ifndef REQUEST_H
#define REQUEST_H
#include "Config.h"
#include "Config.h"
#include <map>

View File

@ -1,3 +1,4 @@
#include "Config.h"
#ifndef NOHTTP
#ifndef REQUESTMANAGER_H
#define REQUESTMANAGER_H

View File

@ -0,0 +1,10 @@
client_files += files(
'APIRequest.cpp',
'AvatarRequest.cpp',
'GetUserInfoRequest.cpp',
'ImageRequest.cpp',
'Request.cpp',
'RequestManager.cpp',
'SaveUserInfoRequest.cpp',
'ThumbnailRequest.cpp',
)

16
src/client/meson.build Normal file
View File

@ -0,0 +1,16 @@
client_files = files(
'MD5.cpp',
'SaveFile.cpp',
'SaveInfo.cpp',
'ThumbnailRendererTask.cpp',
'Client.cpp',
'GameSave.cpp',
)
subdir('http')
powder_files += client_files
render_files += files(
'GameSave.cpp',
)

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include <stdexcept>
#include <sstream>
@ -8,6 +9,8 @@
#include <locale>
#include <ios>
#include "tpt-minmax.h"
/*
There are two "string" classes: ByteString and String. They have nearly
identical interfaces, except that one stores 8-bit octets (bytes) and

10
src/common/macosx.h Normal file
View File

@ -0,0 +1,10 @@
#pragma once
#ifdef DEBUG
# undef DEBUG
# define DEBUG 1
#else
# define DEBUG 0
#endif
#include <mach-o/dyld.h>
#include <ApplicationServices/ApplicationServices.h>

4
src/common/meson.build Normal file
View File

@ -0,0 +1,4 @@
common_files += files(
'String.cpp',
'tpt-rand.cpp',
)

View File

@ -18,19 +18,25 @@
#ifdef _MSC_VER
// less than VS2013. Untested since I don't use VS2012 anymore
#if _MSC_VER < 1800
#define fmin min
#define fminf min
#define fmax max
#define fmaxf max
#else
# if _MSC_VER < 1800
# define fmin min
# define fminf min
# define fmax max
# define fmaxf max
# else
// >= VS2013
#include <algorithm>
#define NOMINMAX
#endif
# include <algorithm>
# define NOMINMAX
# ifdef min
# undef min
# endif
# ifdef max
# undef max
# endif
# endif
#else
// not using visual studio, std::min and std::max are normal
#include <algorithm>
# include <algorithm>
#endif
#endif

View File

@ -1,5 +1,6 @@
#ifndef TPT_RAND_
#define TPT_RAND_
#include "Config.h"
#include <stdint.h>
#include "Singleton.h"

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include "gui/interface/Point.h"

6
src/debug/meson.build Normal file
View File

@ -0,0 +1,6 @@
powder_files += files(
'DebugLines.cpp',
'DebugParts.cpp',
'ElementPopulation.cpp',
'ParticleDebug.cpp',
)

View File

@ -0,0 +1,48 @@
#include "FontReader.h"
FontReader::FontReader(unsigned char const *_pointer):
pointer(_pointer + 1),
width(*_pointer),
pixels(0),
data(0)
{
}
unsigned char const *FontReader::lookupChar(String::value_type ch)
{
size_t offset = 0;
for(int i = 0; font_ranges[i][1]; i++)
if(font_ranges[i][0] > ch)
break;
else if(font_ranges[i][1] >= ch)
return &font_data[font_ptrs[offset + (ch - font_ranges[i][0])]];
else
offset += font_ranges[i][1] - font_ranges[i][0] + 1;
if(ch == 0xFFFD)
return &font_data[0];
else
return lookupChar(0xFFFD);
}
FontReader::FontReader(String::value_type ch):
FontReader(lookupChar(ch))
{
}
int FontReader::GetWidth() const
{
return width;
}
int FontReader::NextPixel()
{
if(!pixels)
{
data = *(pointer++);
pixels = 4;
}
int old = data;
pixels--;
data >>= 2;
return old & 0x3;
}

View File

@ -11,50 +11,11 @@ class FontReader
int pixels;
int data;
inline FontReader(unsigned char const *_pointer):
pointer(_pointer + 1),
width(*_pointer),
pixels(0),
data(0)
{}
static inline unsigned char const *lookupChar(String::value_type ch)
{
size_t offset = 0;
for(int i = 0; font_ranges[i][1]; i++)
if(font_ranges[i][0] > ch)
break;
else if(font_ranges[i][1] >= ch)
return &font_data[font_ptrs[offset + (ch - font_ranges[i][0])]];
else
offset += font_ranges[i][1] - font_ranges[i][0] + 1;
if(ch == 0xFFFD)
return &font_data[0];
else
return lookupChar(0xFFFD);
}
FontReader(unsigned char const *_pointer);
static unsigned char const *lookupChar(String::value_type ch);
public:
inline FontReader(String::value_type ch):
FontReader(lookupChar(ch))
{
}
inline int GetWidth() const
{
return width;
}
inline int NextPixel()
{
if(!pixels)
{
data = *(pointer++);
pixels = 4;
}
int old = data;
pixels--;
data >>= 2;
return old & 0x3;
}
FontReader(String::value_type ch);
int GetWidth() const;
int NextPixel();
};

View File

@ -1,11 +1,11 @@
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "Config.h"
#include "common/String.h"
#if defined(OGLI)
#include "OpenGLHeaders.h"
#endif
#include "Config.h"
#include "common/tpt-inline.h"
#include "Pixel.h"
#include "Icons.h"

View File

@ -1,29 +1,30 @@
#include "Config.h"
#ifndef OPENGLHEADERS_H_
#define OPENGLHEADERS_H_
#ifdef MACOSX
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_OS_X_VERSION_10_9
#include <OpenGL/glu.h>
#ifndef GL_RGBA32F
#define GL_RGBA32F GL_RGBA32F_ARB
#endif
#elif __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
#include <OpenGL/gl3.h>
#include <OpenGL/glu.h>
#else
# if __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_OS_X_VERSION_10_9
# include <OpenGL/glu.h>
# ifndef GL_RGBA32F
# define GL_RGBA32F GL_RGBA32F_ARB
# endif
# elif __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
# include <OpenGL/gl3.h>
# include <OpenGL/glu.h>
# else
//#include <GL/glew.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#define GL_RGBA32F 0x8814
#endif
# include <OpenGL/gl.h>
# include <OpenGL/glu.h>
# define GL_RGBA32F 0x8814
# endif
#elif defined(WIN)
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
# include <GL/glew.h>
# include <GL/gl.h>
# include <GL/glu.h>
#else
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
# include <GL/glew.h>
# include <GL/gl.h>
# include <GL/glu.h>
#endif
#endif // OPENGLHEADERS_H_

View File

@ -112,10 +112,12 @@ void Renderer::RenderBegin()
std::fill(warpVid, warpVid+(VIDXRES*VIDYRES), 0);
}
#ifndef FONTEDITOR
draw_air();
draw_grav();
DrawWalls();
render_parts();
if(display_mode & DISPLAY_PERS)
{
int i,r,g,b;
@ -138,6 +140,7 @@ void Renderer::RenderBegin()
draw_other();
draw_grav_zones();
DrawSigns();
#endif
if(display_mode & DISPLAY_WARP)
{
@ -523,11 +526,10 @@ void Renderer::RenderZoom()
#endif
}
std::vector<wall_type> Renderer_wtypes = LoadWalls();
#ifndef FONTEDITOR
VideoBuffer * Renderer::WallIcon(int wallID, int width, int height)
{
static std::vector<wall_type> Renderer_wtypes = LoadWalls();
int i, j;
int wt = wallID;
if (wt<0 || wt>=(int)Renderer_wtypes.size())
@ -688,6 +690,7 @@ VideoBuffer * Renderer::WallIcon(int wallID, int width, int height)
}
return newTexture;
}
#endif
void Renderer::DrawBlob(int x, int y, unsigned char cr, unsigned char cg, unsigned char cb)
{
@ -976,6 +979,7 @@ void Renderer::DrawWalls()
#endif
}
#ifndef FONTEDITOR
void Renderer::DrawSigns()
{
int x, y, w, h;
@ -1023,6 +1027,7 @@ void Renderer::DrawSigns()
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, prevFbo);
#endif
}
#endif
void Renderer::render_gravlensing(pixel * source)
{
@ -1191,6 +1196,7 @@ void Renderer::prepare_alpha(int size, float intensity)
#endif
}
#ifndef FONTEDITOR
void Renderer::render_parts()
{
int deca, decr, decg, decb, cola, colr, colg, colb, firea, firer, fireg, fireb, pixel_mode, q, i, t, nx, ny, x, y, caddress;
@ -2330,6 +2336,7 @@ void Renderer::draw_other() // EMP effect
#endif
}
}
#endif
void Renderer::draw_grav()
{

View File

@ -1,5 +1,6 @@
#ifndef RENDERER_H
#define RENDERER_H
#include "Config.h"
#include <vector>
#ifdef OGLR
@ -7,7 +8,6 @@
#endif
#include "Graphics.h"
#include "Config.h"
#include "gui/interface/Point.h"
class RenderPreset;

11
src/graphics/meson.build Normal file
View File

@ -0,0 +1,11 @@
graphics_files = files(
'Graphics.cpp',
#'OpenGLGraphics.cpp', # this is defunct right now
'RasterGraphics.cpp',
'FontReader.cpp',
'Renderer.cpp',
)
powder_files += graphics_files
render_files += graphics_files
font_files += graphics_files

View File

@ -1,5 +1,6 @@
#ifndef STYLE_H_
#define STYLE_H_
#include "Config.h"
#include "gui/interface/Colour.h"

View File

@ -0,0 +1,3 @@
powder_files += files(
'ColourPickerActivity.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef CONSOLECONTROLLER_H_
#define CONSOLECONTROLLER_H_
#include "Config.h"
#include "common/String.h"

View File

@ -1,5 +1,6 @@
#ifndef CONSOLEMODEL_H_
#define CONSOLEMODEL_H_
#include "Config.h"
#include <vector>
#include <deque>

View File

@ -0,0 +1,5 @@
powder_files += files(
'ConsoleController.cpp',
'ConsoleModel.cpp',
'ConsoleView.cpp',
)

View File

@ -0,0 +1,7 @@
gui_files += files(
'ConfirmPrompt.cpp',
'ErrorMessage.cpp',
'InformationMessage.cpp',
'SaveIDMessage.cpp',
'TextPrompt.cpp',
)

View File

@ -0,0 +1,3 @@
powder_files += files(
'ElementSearchActivity.cpp',
)

View File

@ -0,0 +1,3 @@
powder_files += files(
'FileBrowserActivity.cpp',
)

View File

@ -16,7 +16,6 @@
#include "gui/interface/ScrollPanel.h"
#include "graphics/Graphics.h"
#ifdef FONTEDITOR
unsigned char *font_data;
unsigned int *font_ptrs;
unsigned int (*font_ranges)[2];
@ -658,4 +657,3 @@ void FontEditor::Save()
WriteDataFile(dataFile, tmpFontData, tmpFontPtrs, tmpFontRanges);
savedButton->SetToggleState(true);
}
#endif

3
src/gui/font/meson.build Normal file
View File

@ -0,0 +1,3 @@
font_files += files(
'FontEditor.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef BRUSH_H_
#define BRUSH_H_
#include "Config.h"
#include "gui/interface/Point.h"

View File

@ -1,5 +1,6 @@
#ifndef FAVORITE_H
#define FAVORITE_H
#include "Config.h"
#include "common/String.h"
#include <vector>

View File

@ -1,5 +1,6 @@
#ifndef GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include "Config.h"
#include <vector>
#include <utility>

View File

@ -1,5 +1,6 @@
#ifndef GAMEMODEL_H
#define GAMEMODEL_H
#include "Config.h"
#include <vector>
#include <deque>

View File

@ -38,6 +38,8 @@
#include "simulation/ElementDefs.h"
#include "simulation/ElementClasses.h"
#include <cstring>
#ifdef GetUserName
# undef GetUserName // dammit windows
#endif

View File

@ -1,5 +1,6 @@
#ifndef MENU_H_
#define MENU_H_
#include "Config.h"
#include "common/String.h"

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include "common/String.h"

View File

@ -1,5 +1,6 @@
#ifndef TOOL_H_
#define TOOL_H_
#include "Config.h"
#include "common/String.h"
#include "gui/interface/Point.h"

17
src/gui/game/meson.build Normal file
View File

@ -0,0 +1,17 @@
powder_files += files(
'BitmapBrush.cpp',
'Brush.cpp',
'DecorationTool.cpp',
'Favorite.cpp',
'GameController.cpp',
'GameModel.cpp',
'GameView.cpp',
'GOLTool.cpp',
'Menu.cpp',
'PropertyTool.cpp',
'QuickOptions.cpp',
'SampleTool.cpp',
'SignTool.cpp',
'ToolButton.cpp',
'Tool.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef APPEARANCE_H_
#define APPEARANCE_H_
#include "Config.h"
#include "Border.h"
#include "Colour.h"

View File

@ -1,4 +1,5 @@
#pragma once
#include "Config.h"
#include "common/String.h"
#include "Appearance.h"

View File

@ -1,6 +1 @@
#ifdef SDL_INC
#include "SDL2/SDL_mouse.h"
#else
#include "SDL_mouse.h"
#endif

View File

@ -0,0 +1,25 @@
gui_files += files(
'Appearance.cpp',
'Button.cpp',
'Checkbox.cpp',
'Component.cpp',
'ContextMenu.cpp',
'CopyTextButton.cpp',
'DropDown.cpp',
'Engine.cpp',
'Label.cpp',
'Panel.cpp',
'ProgressBar.cpp',
'ScrollPanel.cpp',
'Slider.cpp',
'Spinner.cpp',
'Textbox.cpp',
'TextWrapper.cpp',
'Window.cpp',
)
powder_files += files(
'AvatarButton.cpp',
'RichLabel.cpp',
'SaveButton.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef STAMPSCONTROLLER_H_
#define STAMPSCONTROLLER_H_
#include "Config.h"
#include "common/String.h"

View File

@ -1,5 +1,6 @@
#ifndef STAMPSMODEL_H_
#define STAMPSMODEL_H_
#include "Config.h"
#include <vector>
#include "common/String.h"

View File

@ -0,0 +1,5 @@
powder_files += files(
'LocalBrowserController.cpp',
'LocalBrowserModel.cpp',
'LocalBrowserView.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef LOGINCONTROLLER_H_
#define LOGINCONTROLLER_H_
#include "Config.h"
#include "common/String.h"
#include "client/User.h"

View File

@ -1,5 +1,6 @@
#ifndef LOGINMODEL_H_
#define LOGINMODEL_H_
#include "Config.h"
#include <vector>
#include "common/String.h"

View File

@ -0,0 +1,5 @@
powder_files += files(
'LoginController.cpp',
'LoginModel.cpp',
'LoginView.cpp',
)

25
src/gui/meson.build Normal file
View File

@ -0,0 +1,25 @@
gui_files = files(
'Style.cpp',
)
subdir('colourpicker')
subdir('console')
subdir('dialogues')
subdir('elementsearch')
subdir('filebrowser')
subdir('font')
subdir('game')
subdir('interface')
subdir('localbrowser')
subdir('login')
subdir('options')
subdir('preview')
subdir('profile')
subdir('render')
subdir('save')
subdir('search')
subdir('tags')
subdir('update')
powder_files += gui_files
font_files += gui_files

View File

@ -1,5 +1,6 @@
#ifndef OPTIONSCONTROLLER_H_
#define OPTIONSCONTROLLER_H_
#include "Config.h"
#include <functional>

View File

@ -1,5 +1,6 @@
#ifndef OPTIONSMODEL_H_
#define OPTIONSMODEL_H_
#include "Config.h"
#include <vector>

View File

@ -4,6 +4,7 @@
#include "OptionsModel.h"
#include <cstdio>
#include <cstring>
#ifdef WIN
#include <direct.h>
#define getcwd _getcwd

View File

@ -0,0 +1,5 @@
powder_files += files(
'OptionsController.cpp',
'OptionsModel.cpp',
'OptionsView.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef PREVIEWCONTROLLER_H_
#define PREVIEWCONTROLLER_H_
#include "Config.h"
#include "client/ClientListener.h"

View File

@ -1,5 +1,6 @@
#ifndef PREVIEWMODEL_H
#define PREVIEWMODEL_H
#include "Config.h"
#include <vector>
#include "common/String.h"

View File

@ -0,0 +1,5 @@
powder_files += files(
'PreviewController.cpp',
'PreviewModel.cpp',
'PreviewView.cpp',
)

View File

@ -0,0 +1,3 @@
powder_files += files(
'ProfileActivity.cpp',
)

View File

@ -1,5 +1,6 @@
#ifndef RENDERCONTROLLER_H_
#define RENDERCONTROLLER_H_
#include "Config.h"
#include <functional>

View File

@ -1,5 +1,6 @@
#ifndef RENDERMODEL_H_
#define RENDERMODEL_H_
#include "Config.h"
#include <vector>

View File

@ -0,0 +1,5 @@
powder_files += files(
'RenderController.cpp',
'RenderModel.cpp',
'RenderView.cpp',
)

4
src/gui/save/meson.build Normal file
View File

@ -0,0 +1,4 @@
powder_files += files(
'LocalSaveActivity.cpp',
'ServerSaveActivity.cpp',
)

Some files were not shown because too many files have changed in this diff Show More