├── pyautosplit ├── __init__.py ├── process.py ├── main.py ├── game.py └── callbacks.py ├── v6as4l.png ├── setup.py ├── games ├── vvvvvv-glitchless100perc.json └── vvvvvv.json ├── README.md └── LICENSE /pyautosplit/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /v6as4l.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/christofsteel/pyautosplit/HEAD/v6as4l.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | setuptools.setup( 4 | name="pyautosplit", 5 | version="0.8.0", 6 | author="Christoph Stahl", 7 | author_email="christoph.stahl@tu-dortmund.de", 8 | description="A python autosplit module for linux and the livesplit server module", 9 | url="https://github.com/christofsteel/pyautosplit.git", 10 | packages=setuptools.find_packages(), 11 | install_requires=["eventlet", "python-ptrace", "simpleeval"], 12 | classifiers=[ 13 | "Development Status :: 4 - Beta", 14 | "Programming Language :: Python :: 3", 15 | "Environment :: Console", 16 | "License :: OSI Approved :: Apache Software License", 17 | "Operating System :: POSIX :: Linux", 18 | "Topic :: Games/Entertainment", 19 | "Topic :: Software Development :: Debuggers", 20 | ], 21 | python_requires='>=3.7', 22 | entry_points={ 23 | 'console_scripts': ['pyautosplit=pyautosplit.main:main'] 24 | } 25 | ) 26 | -------------------------------------------------------------------------------- /games/vvvvvv-glitchless100perc.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Glichless 100%", 3 | "gamefile": "vvvvvv.json", 4 | "start" : "gamestart", 5 | "reset" : "menu", 6 | "route": { 7 | "spacestation1": { 8 | "secret_to_nobody": {}, 9 | "trench_warfare": {} 10 | }, 11 | "laboratory": { 12 | "worth_the_challenge": {}, 13 | "lab_maze": {}, 14 | "tantalizing_trinket": {}, 15 | "purest_unobtainium": {} 16 | }, 17 | "spacestation2": { 18 | "victoria_vitellary": {}, 19 | "elephant": {}, 20 | "one_way_room": {}, 21 | "keep_coming_back": {}, 22 | "clarion_call": {}, 23 | "dtthw": {}, 24 | "prize_for_the_reckless": {} 25 | }, 26 | "intermission1": {}, 27 | "warpzone": { 28 | "cave_1": {}, 29 | "cave_2": {}, 30 | "cave_3": {}, 31 | "edge_games": {} 32 | }, 33 | "intermission2": {}, 34 | "tower": { 35 | "tower_1": {}, 36 | "tower_2": {} 37 | }, 38 | "gamecomplete": { 39 | "v": {} 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /pyautosplit/process.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import sys 3 | from signal import SIGTRAP 4 | from typing import Dict, Optional 5 | 6 | import ptrace.debugger 7 | from ptrace.debugger.process_error import ProcessError 8 | 9 | 10 | class GameProcess: 11 | def __init__(self, command, cwd, env: Optional[Dict[str, str]] = None): 12 | self.process = subprocess.Popen(command, 13 | stdout=subprocess.DEVNULL, 14 | cwd=cwd, 15 | env=env) 16 | 17 | self.debugger = ptrace.debugger.PtraceDebugger() 18 | self.dprocess = self.debugger.addProcess(self.process.pid, False) 19 | self.breakpoints = {} 20 | 21 | def insert_breakpoint(self, addr): 22 | self.breakpoints[addr] = self.dprocess.createBreakpoint(addr) 23 | 24 | def check_breakpoint_hit(self): 25 | event = self.debugger._wait_event_pid(self.process.pid, False) 26 | return event is not None and event.signum == SIGTRAP 27 | 28 | def delete_breakpoint(self, addr): 29 | self.breakpoints[addr].desinstall(True) 30 | 31 | def get_instruction_pointer(self): 32 | return self.dprocess.getInstrPointer() 33 | 34 | def get_stack_pointer(self): 35 | return self.dprocess.getStackPointer() 36 | 37 | def get_base_pointer(self): 38 | return self.dprocess.getFramePointer() 39 | 40 | def cont(self): 41 | self.dprocess.cont() 42 | 43 | def read_mem(self, addr, length=4, signed=False, byteorder=sys.byteorder): 44 | try: 45 | return int.from_bytes(self.dprocess.readBytes(addr, length), 46 | byteorder=byteorder, signed=signed) 47 | except ProcessError: 48 | return None 49 | 50 | def read_bool(self, addr): 51 | try: 52 | return self.dprocess.readBytes(addr, 1) == b'\01' 53 | except ProcessError: 54 | return None 55 | -------------------------------------------------------------------------------- /pyautosplit/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os.path 3 | from argparse import ArgumentParser 4 | from collections import OrderedDict 5 | 6 | from .game import Game 7 | from .callbacks import ConsoleOut, LiveSplitServer, LiveSplitOne 8 | 9 | 10 | def main(): 11 | parser = ArgumentParser() 12 | parser.add_argument("--front-ends", "-f", nargs="+", default=["livesplit"], 13 | help="Choose one or multiple of `console', " 14 | "`livesplit', `livesplitone' (default livesplit)") 15 | parser.add_argument("--livesplit-host", default="localhost", 16 | help="Host that runs the livesplit server component " 17 | "(default localhost)") 18 | parser.add_argument("--livesplit-port", type=int, default=16834, 19 | help="Port the livesplit server component listens on " 20 | "(default 16834)") 21 | parser.add_argument("--livesplitone-bind", default="localhost", 22 | help="Bind the livesplitone websocket server to this " 23 | "host (default localhost)") 24 | parser.add_argument("--livesplitone-port", type=int, default=5000, 25 | help="Bind the livesplitone websocket server to this " 26 | "port (default 5000)") 27 | parser.add_argument("runfile") 28 | 29 | args = parser.parse_args() 30 | 31 | with open(args.runfile) as jsonfile: 32 | rundata = json.load(jsonfile, object_pairs_hook=OrderedDict) 33 | 34 | if os.path.isabs(rundata["gamefile"]): 35 | abs_gamefilename = rundata["gamefile"] 36 | else: 37 | relative_base = os.path.dirname(args.runfile) 38 | abs_gamefilename = os.path.join(relative_base, rundata["gamefile"]) 39 | 40 | with open(abs_gamefilename) as jsonfile: 41 | gamedata = json.load(jsonfile, object_pairs_hook=OrderedDict) 42 | 43 | callback_handlers = [] 44 | 45 | if 'console' in args.front_ends: 46 | callback_handlers.append(ConsoleOut()) 47 | if 'livesplitone' in args.front_ends: 48 | callback_handlers.append( 49 | LiveSplitOne(args.livesplitone_bind, args.livesplitone_port)) 50 | if 'livesplit' in args.front_ends: 51 | callback_handlers.append( 52 | LiveSplitServer(args.livesplit_host, args.livesplit_port)) 53 | 54 | game = Game(gamedata, rundata, callback_handlers) 55 | game.hook() 56 | 57 | 58 | if __name__ == "__main__": 59 | main() 60 | -------------------------------------------------------------------------------- /pyautosplit/game.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import shlex 4 | import sys 5 | import traceback 6 | from pathlib import Path 7 | from dataclasses import dataclass, field 8 | from typing import Any, Dict, List, Optional 9 | from copy import deepcopy 10 | 11 | from simpleeval import simple_eval 12 | 13 | from .process import GameProcess 14 | from ptrace.error import PtraceError 15 | 16 | 17 | class State(dict): 18 | def __init__(self, *args, **kwargs): 19 | super().__init__(*args, **kwargs) 20 | self.__dict__ = self 21 | 22 | 23 | @dataclass 24 | class Split(): 25 | name: str 26 | trigger: str 27 | time: int = None 28 | subsplits: List[Any] = field(default_factory=list) 29 | 30 | 31 | class Route: 32 | def entry_to_split(self, splits_dict): 33 | splits = [] 34 | for key, attr in splits_dict.items(): 35 | split = deepcopy(self.events[key]) 36 | split.subsplits = self.entry_to_split(attr) 37 | splits.append(split) 38 | return splits 39 | 40 | def __init__(self, rundata, events): 41 | self.events = events 42 | self.splits = self.entry_to_split(rundata["route"]) 43 | self.resettrigger = self.events[rundata["reset"]] 44 | self.starttigger = self.events[rundata["start"]] 45 | self.name = rundata["name"] 46 | self.gamefile = rundata["gamefile"] 47 | 48 | 49 | class Game: 50 | def __init__(self, gamedata, rundata, callback_handlers): 51 | self.data = gamedata 52 | 53 | if 'overwrites' in rundata: 54 | for k, v in rundata['overwrites'].items(): 55 | self.data[k] = v 56 | 57 | events = {name: Split(**s) for name, s in self.data["events"].items()} 58 | route = Route(rundata, events) 59 | self.callback_handlers = callback_handlers 60 | 61 | for cbh in self.callback_handlers: 62 | cbh.init(deepcopy(route), (self.data.get("time"))) 63 | 64 | if "cwd" in self.data: 65 | cwd = Path(self.data["cwd"]).expanduser() 66 | else: 67 | cwd = None 68 | 69 | env: Optional[Dict[str, str]] = self.data.get("env", None) 70 | if env is not None: 71 | for var in env: 72 | env[var] = os.path.expandvars(env[var]) 73 | 74 | env.update(os.environ) 75 | 76 | command = shlex.split(self.data["command"]) 77 | command[0] = Path(command[0]).expanduser() 78 | self.process = GameProcess(command, cwd, env=env) 79 | 80 | self.breakpoints = {} 81 | 82 | for name, var in self.data["variables"].items(): 83 | if var["type"] != "rsp" and var["type"] != "rbp": 84 | continue 85 | addr = int(var["address"], 16) 86 | self.process.insert_breakpoint(addr) 87 | self.breakpoints[addr] = name 88 | 89 | self.state = State( 90 | {varname: None for varname in self.data["variables"].keys()}) 91 | 92 | def handle_breakpoints(self): 93 | if self.process.check_breakpoint_hit(): 94 | rip = self.process.get_instruction_pointer() - 1 95 | 96 | varname = self.breakpoints[rip] 97 | self.process.delete_breakpoint(rip) 98 | 99 | var = self.data["variables"][varname] 100 | if var["type"] == "rsp": 101 | self.state[varname] = self.process.get_stack_pointer() + \ 102 | int(var["offset"], 16) 103 | elif var["type"] == "rbp": 104 | self.state[varname] = self.process.get_base_pointer() + \ 105 | int(var["offset"], 16) 106 | try: 107 | self.process.cont() 108 | except BaseException: 109 | pass 110 | 111 | def update_data(self): 112 | def eval_address(address_string): 113 | try: 114 | return simple_eval(address_string, names=self.state) 115 | except TypeError: 116 | return None 117 | 118 | for name, var in self.data["variables"].items(): 119 | if var["type"] == "rsp" or var["type"] == "rbp": 120 | continue 121 | var["_address"] = eval_address(var["address"]) 122 | var_obj = Variable(name=name, **var) 123 | try: 124 | if var_obj.type == "bool": 125 | self.state[name] = self.process.read_bool(var_obj._address) 126 | elif var_obj.type == "memory": 127 | self.state[name] = self.process.read_mem( 128 | addr=var_obj._address, 129 | length=int(var_obj.length), 130 | signed=var_obj.signed, 131 | byteorder=var_obj.byteorder) 132 | except TypeError: 133 | pass 134 | 135 | def fill_mappings(self): 136 | mappings = self.process.dprocess.readMappings() 137 | self.state["process_start"] = mappings[0].start 138 | self.state["stack_start"] = self.process.dprocess.findStack().start 139 | self.state["stack_end"] = self.process.dprocess.findStack().end 140 | 141 | def hook(self): 142 | self.process.cont() 143 | 144 | self.fill_mappings() 145 | 146 | try: 147 | while True: 148 | self.handle_breakpoints() 149 | self.update_data() 150 | for cbh in self.callback_handlers: 151 | cbh.tick(self.state) 152 | time.sleep(1 / int(self.data["frequency"])) 153 | except PtraceError as p: 154 | if p.errno != 3: 155 | traceback.print_exc() 156 | 157 | 158 | @dataclass 159 | class Variable: 160 | name: str 161 | address: str 162 | _address: int 163 | type: str = "memory" 164 | length: int = 4 165 | signed: bool = False 166 | byteorder: str = sys.byteorder 167 | comment: str = "" 168 | -------------------------------------------------------------------------------- /games/vvvvvv.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "VVVVVV", 3 | "command": "~/.local/share/Steam/steamapps/common/vvvvvv/x86_64/vvvvvv.x86_64", 4 | "cwd": "~/.local/share/Steam/steamapps/common/vvvvvv/", 5 | "frequency": "30", 6 | "time": "(hours * 60 + minutes) * 60 + seconds + frames/30", 7 | "variables": { 8 | "game_object": { 9 | "type": "rsp", 10 | "address": "0x416da8", 11 | "offset": "0xe20" 12 | }, 13 | "frames": { 14 | "type": "memory", 15 | "address": "game_object + 0xa8" 16 | }, 17 | "seconds": { 18 | "type": "memory", 19 | "length": 4, 20 | "signed": false, 21 | "byteorder": "little", 22 | "address": "game_object + 0xac", 23 | "comment": "Blubb" 24 | }, 25 | "minutes": { 26 | "type": "memory", 27 | "address": "game_object + 0xb0" 28 | }, 29 | "hours": { 30 | "type": "memory", 31 | "address": "game_object + 0xb4" 32 | }, 33 | "trinkets": { 34 | "type": "memory", 35 | "address": "game_object + 0x3d0" 36 | }, 37 | "state": { 38 | "type": "memory", 39 | "address": "game_object + 0x60" 40 | }, 41 | "gamestate": { 42 | "type": "memory", 43 | "address": "game_object + 0x70" 44 | }, 45 | "entity_objects": { 46 | "type": "memory", 47 | "address": "game_object - 0xc00" 48 | }, 49 | "near_elephant": { 50 | "type": "bool", 51 | "address": "game_object - 0xc00 + 0x126" 52 | }, 53 | "sad": { 54 | "type": "bool", 55 | "address": "game_object - 0xc00 + 0x127" 56 | } 57 | }, 58 | "events": { 59 | "elephant_sad" : { 60 | "name": "Elephant Sad", 61 | "trigger": "state.near_elephant and state.sad" 62 | }, 63 | "gamestart": { 64 | "name": "Game Start", 65 | "trigger": "state.gamestate == 0" 66 | }, 67 | "menu": { 68 | "name": "Menu", 69 | "trigger": "state.gamestate == 1" 70 | }, 71 | "spacestation1": { 72 | "name": "Space Station 1", 73 | "trigger": "state.state == 3051" 74 | }, 75 | "laboratory": { 76 | "name": "Laboratory", 77 | "trigger": "state.state == 3040" 78 | }, 79 | "spacestation2": { 80 | "name": "Space Station 2", 81 | "trigger": "state.state == 3020" 82 | }, 83 | "intermission1": { 84 | "name": "Intermission 1", 85 | "trigger": "state.state == 3085" 86 | }, 87 | "warpzone": { 88 | "name": "Warp Zone", 89 | "trigger": "state.state == 3006" 90 | }, 91 | "intermission2": { 92 | "name": "Intermission 2", 93 | "trigger": "state.state == 3080" 94 | }, 95 | "tower": { 96 | "name": "Tower", 97 | "trigger": "state.state == 3060" 98 | }, 99 | "gamecomplete": { 100 | "name": "Game Complete", 101 | "trigger": "state.state == 3503" 102 | }, 103 | "secret_to_nobody": { 104 | "name": "Trinket - It's a Secret to Nobody", 105 | "trigger": "state.trinkets != oldstate.trinkets" 106 | }, 107 | "trench_warfare": { 108 | "name": "Trinket - Trench Warfare", 109 | "trigger": "state.trinkets != oldstate.trinkets" 110 | }, 111 | "worth_the_challenge": { 112 | "name": "Trinket - Young Man, It's Worth the Challenge", 113 | "trigger": "state.trinkets != oldstate.trinkets" 114 | }, 115 | "lab_maze": { 116 | "name": "Trinket - Lab Maze", 117 | "trigger": "state.trinkets != oldstate.trinkets" 118 | }, 119 | "tantalizing_trinket": { 120 | "name": "Trinket - The Tantalizing Trinket", 121 | "trigger": "state.trinkets != oldstate.trinkets" 122 | }, 123 | "purest_unobtainium": { 124 | "name": "Trinket - Purest Unobtainium", 125 | "trigger": "state.trinkets != oldstate.trinkets" 126 | }, 127 | "victoria_vitellary": { 128 | "name": "Trinket - Victoria/Vitellary", 129 | "trigger": "state.trinkets != oldstate.trinkets" 130 | }, 131 | "elephant": { 132 | "name": "Trinket - Elephant", 133 | "trigger": "state.trinkets != oldstate.trinkets" 134 | }, 135 | "one_way_room": { 136 | "name": "Trinket - One Way Room", 137 | "trigger": "state.trinkets != oldstate.trinkets" 138 | }, 139 | "keep_coming_back": { 140 | "name": "Trinket - You Just Keep Coming Back", 141 | "trigger": "state.trinkets != oldstate.trinkets" 142 | }, 143 | "clarion_call": { 144 | "name": "Trinket - Clarion Call", 145 | "trigger": "state.trinkets != oldstate.trinkets" 146 | }, 147 | "dtthw": { 148 | "name": "Trinket - Doing Things the Hard Way", 149 | "trigger": "state.trinkets != oldstate.trinkets" 150 | }, 151 | "prize_for_the_reckless": { 152 | "name": "Trinket - Prize for the Reckless", 153 | "trigger": "state.trinkets != oldstate.trinkets" 154 | }, 155 | "cave_1": { 156 | "name": "Trinket - Cave 1", 157 | "trigger": "state.trinkets != oldstate.trinkets" 158 | }, 159 | "cave_2": { 160 | "name": "Trinket - Cave 2", 161 | "trigger": "state.trinkets != oldstate.trinkets" 162 | }, 163 | "cave_3": { 164 | "name": "Trinket - Cave 3", 165 | "trigger": "state.trinkets != oldstate.trinkets" 166 | }, 167 | "edge_games": { 168 | "name": "Trinket - Edge Games", 169 | "trigger": "state.trinkets != oldstate.trinkets" 170 | }, 171 | "tower_1": { 172 | "name": "Trinket - Tower 1", 173 | "trigger": "state.trinkets != oldstate.trinkets" 174 | }, 175 | "tower_2": { 176 | "name": "Trinket - Tower 2", 177 | "trigger": "state.trinkets != oldstate.trinkets" 178 | }, 179 | "v": { 180 | "name": "Trinket - V", 181 | "trigger": "state.trinkets != oldstate.trinkets" 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PyAutoSplit 2 | =========== 3 | 4 | This is a python based autosplitting tool for speedrunning. Currently only Linux is supported, but adding Windows support should be possible, when I come around to do it. In theory MacOS and other Unix systems work, but this is completely untested. 5 | 6 | ## Why was this done? 7 | 8 | While LiveSplit does work inside wine, the autosplit component does not work on linux machines. In addition to this, it is not possible to create breakpoints and read values in CPU registers with the autosplit component of LiveSplit. PyAutoSplit can do that. This is especially useful in a game like VVVVVV (2.2 and below), where all relevant information are on the stack, and therefore at nonstatic locations in memory. 9 | 10 | Current strategies involve scanning the processes memory for specific values, to guess the location of information like gamestate etc. Unfortunately this is rather error prone. With PyAutoSplit one can set a breakpoint at the (static) instruction where the game object is created, and read the cpu registers to get an exact location of the game object. 11 | 12 | ## Installation 13 | 14 | The program can be installed via pip 15 | 16 | ``` 17 | pip install --user git+https://github.com/christofsteel/pyautosplit.git 18 | ``` 19 | 20 | ## Usage 21 | 22 | PyAutoSplit has three different _front-ends_: _console out_, _LiveSplit_ and _LiveSplit One_. You select one or multiple front-end with the `-f`/`--front-end` flag. If no front-end flag is given, _LiveSplit_ is automatically selected. 23 | 24 | ### LiveSplit 25 | 26 | If you want to connect PyAutoSplit to the server component of LiveSplit, you first have to start LiveSplit, and the LiveSplit server component. After that you can launch PyAutoSplit with 27 | 28 | ``` 29 | pyautosplit -f livesplit -- routefile.json 30 | ``` 31 | 32 | ### LiveSplit One 33 | 34 | Run PyAutoSplit with 35 | 36 | ``` 37 | pyautosplit -f livesplitone -- routefile.json 38 | ``` 39 | 40 | After that, go to https://one.livesplit.org and connect to `ws://localhost:5000`. 41 | 42 | ### Console out 43 | 44 | This is more of a debug output, but you can launch PyAutoSplit with 45 | 46 | ``` 47 | pyautosplit -f console -- routefile.json 48 | ``` 49 | 50 | ## Configuration 51 | 52 | To use PyAutoSplit for a game, you have to have it installed and two files. One specific for the game you are playing and one specific for your route. In this repository, there is an example for the game VVVVVV and a route for glitchless 100%. 53 | 54 | ### Game file 55 | 56 | A game file is a json file with the following fields: 57 | 58 | * `name`, the name of the game 59 | * `command`, the launch command to run the game 60 | * `cwd`, the working directory of the command (optional) 61 | * `env`, additional environment variables for the game (optional) 62 | * `frequency`, how many times a second should the memory be read 63 | * `time`, how does one calculate the ingame time in seconds (optional). If not present, realtime will be used. 64 | * `variables`, variables, that can be used to define other components (see below) 65 | * `events`, events, that can trigger splits, resets etc. (see also below) 66 | 67 | 68 | #### Variables 69 | 70 | A variable in the `variables` field can be either a the state of the stack pointer at a specific instruction (`rsp`), the state of the base pointer at a specific instruction (`rbp`) or an integer value at an address in memory (`memory`). Addresses of variables can use the values of variables, that were defined prior, and the stack and base pointer can define an offset to be added to the value. 71 | 72 | ``` 73 | "game_object": { 74 | "type": "rsp", 75 | "address": "0x416da8", 76 | "offset": "0xe20" 77 | } 78 | ``` 79 | 80 | This defines the variable `game_object` to be the value of the stack pointer at instruction `0x416da8` incremented by `0xe20`. 81 | 82 | ``` 83 | "frames": { 84 | "type": "memory", 85 | "address": "game_object + 0xa8", 86 | "length": 4, 87 | "signed": false, 88 | "byteorder": "little" 89 | } 90 | ``` 91 | 92 | This defines the variable `frames` to be the value in memory at address `game_object + 0xa8`. The variable `game_object` must be defined prior. Optionally it can specify the `length` of the variable, the `signed`ness and the endianess (`byteorder`). The defaults are `4` and `false` for `length` and `signed`. For `byteorder` the native endianess of the system is used (`little` on `x86` machines). 93 | 94 | With the help of the memory access, one can define _multi-level_ variables, meaning variables, whos addresses depend on the value of other variables. 95 | 96 | ``` 97 | "some_pointer": { 98 | "type": "memory", 99 | "address": "0x123456", 100 | "length": 8, 101 | } 102 | 103 | "some_variable": { 104 | "type": "memory", 105 | "address": "some_pointer + 0xc3", 106 | "length": 4 107 | } 108 | ``` 109 | 110 | Since there is no distinction between variables, that are used as pointers, and variables whose value is directly used, one can chain this to arbitrary length. Note: You want to choose a length, that fits your pointer size. For `x86_64`, this is `8`. 111 | 112 | #### Events 113 | 114 | An event in the `events` field is a json object with the fields `name` and `trigger`, bound to an identifier. 115 | 116 | ``` 117 | "gamestart": { 118 | "name": "Game Start", 119 | "trigger": "state.gamestate == 0" 120 | } 121 | ``` 122 | 123 | This defines the event `gamestart` with the name `Game Start` to be triggered, if the variable `gamestate` is equal to `0` at the current state. 124 | 125 | Events can access variables of the current state by prefixing them with `state.`. They also can access variables of the state juste before the current state by prefixing them with `oldstate.`. This is useful to track changes in the state. 126 | 127 | ``` 128 | "secret_to_nobody": { 129 | "name": "Trinket - It's a Secret to Nobody", 130 | "trigger": "state.trinkets != oldstate.trinkets" 131 | } 132 | ``` 133 | 134 | This triggers if the variables `trinkets` changes. 135 | 136 | ### Route file 137 | 138 | A route file defines the route for your speedrun. It is also a json file with the following fields: 139 | 140 | * `name`, the name of your attemtet category 141 | * `gamefile`, the location of the respective json file for the game 142 | * `start`, the event to start the timer 143 | * `reset`, the event to reset the timer 144 | * `route`, this defines the triggers for the actual route (see below) 145 | 146 | The field `route` containes the splits. Each split is itself a json object, that can contain subsplits. 147 | 148 | ``` 149 | 'first_level': {}, 150 | 'second_level': { 151 | 'mid_boss' : {} 152 | } 153 | ``` 154 | In this example the first split is triggered when the event `first_level` happens. The next split would be the first subsplit of `second_level`, namely `mid_boss`, the next split would be `second_level` itself. 155 | 156 | The names of the splits reference events as defined in the game file. 157 | -------------------------------------------------------------------------------- /pyautosplit/callbacks.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import time 3 | import socket 4 | from copy import deepcopy 5 | from threading import Thread 6 | 7 | from simpleeval import simple_eval 8 | 9 | import eventlet 10 | from eventlet import wsgi 11 | from eventlet import websocket 12 | 13 | 14 | class CallbackHandler(): 15 | """ 16 | This is the base class for all callback handlers. The `tick` method of a 17 | callback will be called at specific invervalls and be given the current 18 | state of the observed memory locations. This method then checks, if any 19 | event - like starting a run, reaching a split, etc. - is triggerd and 20 | calls the appropriate method. These methods need to be implemented in a 21 | subclass of `CallbackHandler`. 22 | """ 23 | 24 | def __init__(self): 25 | self.started = False 26 | self.route = None 27 | self.state = None 28 | self.old_state = None 29 | self.timing = None 30 | self.real_time = 0 31 | 32 | def time_in_seconds(self): 33 | if self.timing is None or self.timing == "": 34 | return time.time() - self.real_time 35 | try: 36 | return simple_eval(self.timing, names=self.state) 37 | except TypeError: 38 | return 0 39 | 40 | def findnextsplit(self, startsplit): 41 | if startsplit.time is None: 42 | for split in startsplit.subsplits: 43 | nextsplits = self.findnextsplit(split) 44 | if nextsplits != []: 45 | return [startsplit] + nextsplits 46 | return [startsplit] 47 | return [] 48 | 49 | def nextsplit(self): 50 | for split in self.route.splits: 51 | nextsplit = self.findnextsplit(split) 52 | if nextsplit != []: 53 | return nextsplit 54 | return [] 55 | 56 | def init(self, route, timing): 57 | self.route = route 58 | self.timing = timing 59 | 60 | def update_time(self): 61 | pass 62 | 63 | def split(self, split): 64 | pass 65 | 66 | def checkevent(self, event): 67 | return simple_eval( 68 | event.trigger, 69 | names={ 70 | "state": self.state, 71 | "oldstate": self.old_state}) 72 | 73 | def start(self): 74 | pass 75 | 76 | def resetsplit(self, split): 77 | self.started = False 78 | split.time = None 79 | for subsplit in split.subsplits: 80 | self.resetsplit(subsplit) 81 | 82 | def reset(self): 83 | pass 84 | 85 | def tick(self, values): 86 | self.state = deepcopy(values) 87 | 88 | if self.old_state is None: 89 | self.old_state = deepcopy(self.state) 90 | 91 | if not self.started: 92 | if self.checkevent(self.route.starttigger): 93 | self.started = True 94 | self.real_time = time.time() 95 | self.start() 96 | else: 97 | nextsplits = self.nextsplit() 98 | 99 | if nextsplits == []: 100 | for split in self.route.splits: 101 | self.resetsplit(split) 102 | elif self.checkevent(self.route.resettrigger): 103 | for split in self.route.splits: 104 | self.resetsplit(split) 105 | self.reset() 106 | else: 107 | nextsplit = nextsplits[-1] 108 | self.update_time() 109 | if self.checkevent(nextsplit): 110 | nextsplit.time = self.time_in_seconds() 111 | self.split(nextsplit) 112 | 113 | self.old_state = self.state.copy() 114 | 115 | 116 | class ConsoleOut(CallbackHandler): 117 | def nextsplit_as_string(self): 118 | if self.nextsplit() == []: 119 | return "" 120 | return " - ".join([split.name for split in self.nextsplit()]) 121 | 122 | def update_time(self): 123 | print( 124 | f"\r{datetime.timedelta(seconds=self.time_in_seconds())} - " 125 | f"{self.nextsplit_as_string()}, {self.state}", 126 | end='') 127 | 128 | def split(self, split): 129 | print() 130 | 131 | def reset(self): 132 | print("RESET") 133 | 134 | def start(self): 135 | print("LET'S GO") 136 | 137 | 138 | class LiveSplitServer(CallbackHandler): 139 | def __init__(self, host="localhost", port=16834): 140 | super().__init__() 141 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 142 | self.socket.connect((host, port)) 143 | 144 | def init(self, *args, **kwargs): 145 | super().init(*args, **kwargs) 146 | if self.timing is not None and self.timing != "": 147 | self.socket.send(b"initgametime\r\n") 148 | 149 | def reset(self): 150 | self.socket.send(b"reset\r\n") 151 | 152 | def start(self): 153 | super().start() 154 | self.socket.send(b"starttimer\r\n") 155 | 156 | def update_time(self): 157 | if self.timing is not None and self.timing != "": 158 | self.socket.send( 159 | f"setgametime {self.time_in_seconds()}\r\n".encode()) 160 | 161 | def split(self, split): 162 | self.socket.send(b"split\r\n") 163 | 164 | 165 | class LiveSplitOne(CallbackHandler): 166 | def __init__(self, host="localhost", port=5000): 167 | super().__init__() 168 | 169 | self.listener = eventlet.listen((host, port)) 170 | self.ws_list = set() 171 | 172 | self.thread = Thread(target=self._start_server, daemon=True) 173 | print(f"Connect LiveSplitOne to ws://{host}:{port}") 174 | self.thread.start() 175 | 176 | def dispatch(self, environment, start_response): 177 | @websocket.WebSocketWSGI 178 | def handle(ws): 179 | self.ws_list.add(ws) 180 | try: 181 | while True: 182 | ws.wait() 183 | finally: 184 | self.ws_list.remove(ws) 185 | 186 | return handle(environment, start_response) 187 | 188 | def init(self, *args, **kwargs): 189 | super().init(*args, **kwargs) 190 | 191 | def reset(self): 192 | self._send_command("reset") 193 | 194 | def start(self): 195 | # LiveSplitOne can fail to start to timer if the timer had already been started. (ex. after a pause) 196 | self.reset() 197 | self._send_command("start") 198 | 199 | def split(self, split): 200 | self._send_command("split") 201 | 202 | def pause(self): 203 | self._send_command("togglepause") 204 | 205 | def resume(self): 206 | self._send_command("togglepause") 207 | 208 | def _send_command(self, name): 209 | for ws in self.ws_list: 210 | ws.send(name) 211 | 212 | def _start_server(self): 213 | wsgi.server(self.listener, self.dispatch, log_output=False) 214 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------