All Projects → overfl0 → Pythia

overfl0 / Pythia

Licence: MIT license
An extension for Arma 3 that lets you write extensions in Python 3

Programming Languages

C++
36643 projects - #6 most used programming language
python
139335 projects - #7 most used programming language
CMake
9771 projects
shell
77523 projects
SQF
54 projects
Batchfile
5799 projects

Projects that are alternatives of or similar to Pythia

PboViewer
Cross-platform PBO maker / unpacker
Stars: ✭ 28 (-44%)
Mutual labels:  arma, arma3
tabler
Arma 3 Translation Helper
Stars: ✭ 29 (-42%)
Mutual labels:  arma, arma3
awesome-arma3
Curated list of awesome Arma 3 missions and addons
Stars: ✭ 18 (-64%)
Mutual labels:  arma, arma3
extDB2
Arma3 Extension DB C++ dll / so by @Torndeco. [superseded by extDB3]
Stars: ✭ 17 (-66%)
Mutual labels:  arma, arma3
R3
Arma After Action Replay System, ongoing development in git branches
Stars: ✭ 35 (-30%)
Mutual labels:  arma, arma3
A3ExtendedChat
Adds new functionality to the Arma 3 chat system with emojis, history viewer, message filters and commands!
Stars: ✭ 16 (-68%)
Mutual labels:  arma, arma3
3den-Enhanced
Official 3den Enhanced repository
Stars: ✭ 36 (-28%)
Mutual labels:  arma, arma3
mts marker
NATO joint military symbols for ArmA 3
Stars: ✭ 14 (-72%)
Mutual labels:  arma, arma3
SQFDiscordEmbedBuilder
Send discord webhook embeds from your Arma 3 Server
Stars: ✭ 27 (-46%)
Mutual labels:  arma, arma3
TheseusServices
Private Military Company content mod for Arma 3
Stars: ✭ 16 (-68%)
Mutual labels:  arma, arma3
CLib
CLib is a Function/Script Library for ArmA 3
Stars: ✭ 22 (-56%)
Mutual labels:  arma, arma3
slotlist-backend
Backend of slotlist.info, an ArmA 3 mission planning and slotlist management tool
Stars: ✭ 13 (-74%)
Mutual labels:  arma, arma3
Streamator
A Spectator Specifically build for Content Creation and Streaming
Stars: ✭ 18 (-64%)
Mutual labels:  arma, arma3
Bulletproof-Arma-Launcher
Customisable mod installer and launcher for Arma 3 mods that takes care of *everything* for your community players! Why "bulletproof", you ask? Because "Idiotensicher" was mean :)
Stars: ✭ 21 (-58%)
Mutual labels:  arma, arma3
LambsDanger
AI enhancement mod for Arma 3
Stars: ✭ 88 (+76%)
Mutual labels:  arma3
ARFIMA.jl
Simulate stochastic timeseries that follow ARFIMA, ARMA, ARIMA, AR, etc. processes
Stars: ✭ 44 (-12%)
Mutual labels:  arma
diwako dui
A UI showing unit positions and names of units in your squad
Stars: ✭ 39 (-22%)
Mutual labels:  arma3
arma-dialog-creator
A dialog/GUI creation tool for Arma 3.
Stars: ✭ 73 (+46%)
Mutual labels:  arma
Framework
Altis Life RPG mission framework for Arma 3 originally made by @TAWTonic.
Stars: ✭ 224 (+348%)
Mutual labels:  arma3
arma-intellij-plugin
A plugin for Intellij IDEA that allows for syntactical analysis, code inspections, and other nifty features for the SQF scripting language in Arma 3.
Stars: ✭ 37 (-26%)
Mutual labels:  arma

Pythia logo

Pythia

Build Pythia

An Arma 3 extension that lets you to write python extensions for Arma 3. And it's really simple and straightforward to use!

Pythia's Discord server.

TL;DR:

Create a function:

def my_function(some_string, number, the_truth):
    return ['awesome', 42, True, (1, 3.5)]

Call it from Arma:

["MyAwesomeModule.my_function", ["arg1", 3.14256, False]] call py3_fnc_callExtension

This will return this to your SQF code:

["awesome", 42, True, [1, 3.5]]

See the examples directory for example mods performing simple functions.

What Pythia does NOT do:

Pythia does NOT replace SQF for modding Arma. You will still have to call your Python code from SQF.

If you're looking for something to extend Arma just like with C++ extensions (access [remote] files, databases, generate images, perform advanced computations) but in Python, then Pythia is the right tool for you!

Features:

  • Full type conversion both ways: pass in an SQF array of ints, get a python array of ints. Return a tuple of a float, a bool and a string, get an SQF array containing the float, bool and the string
  • Embedded python installation (you don't have to install anything; just run the mod)
  • Python code stored inside @YourOwnMod directory
  • Python modules can call and reuse each other, even between separate Arma mods
  • Background Python threads
  • Cython and other compiled python extensions "just work" (C-like speed for performance-critical modules)
  • Extendable python environment through pip
  • Proven to work with libraries such as numpy, scipy, matplotlib, PyQt5, etc...
  • Automatic python code reloader for easier development
  • Allows returning more than 10240 characters from the extension transparently
  • Annoys sloppy SQF developers with correct code indentation since Day One ;)

Example mods:

The following are mods that use Pythia to accomplish their goal.

Frontline

Dynamic Frontline in action

Frontline is like Squad but done in Arma. Like Project Reality: Arma 3 but better. With a Dynamic Frontline feature that moves as you conquer terrain (and a bunch of other features).

The frontline computation is done in Python, with the use of numpy, scipy, matplotlib and custom Cython code.

ObjectPlacementTBH

ObjectPlacementTBH

It's just a tool for object placement, to be honest... ;)

Pythia is used for loading in xml files, file IO, writing images using PIL, loading layers.cfg (using Armaclass). The newest version is using PyQt5 to display Qt widgets over the Arma window.

Status

Current status: It's working, it's stable, you can use it :).

You can contact me to ask for planned changes, on Pythia's Discord server. I don't bite :).

Example usage

See the examples directory for example mods performing simple functions.

Your directory structure:

@MyAwesomeMod/
├── Addons/  # (...)
└── python_code/  # Can be named however you want; you can have more than one
    ├── $PYTHIA$  # Contains the name of your python package, for example: MyAwesomeModule
    ├── __init__.py
    ├── module.py
    ├── cython_module.cp310-win_amd64.pyd  # Compiled Cython code, because we can!
    └── cython_module.cp310-win32.pyd      # Same code but for 32-bit Arma

__init__.py:

def my_function(my, arguments):
    return ["awesome", 42, True, (1, 2)]

module.py:

from .cython_module import stuff  # You can import code from other modules, obviously

def call_stuff():
    return stuff()

Now run Arma 3 with -mod=@Pythia;@MyAwesomeMod and execute the following:


Console:

["MyAwesomeModule.my_function", [3.14256, False]] call py3_fnc_callExtension

Result:

["awesome", 42, True, [1, 2]]

Console:

["MyAwesomeModule.module.call_stuff"] call py3_fnc_callExtension

Result:

["Hello world from a Cython module!"]

Note: MyAwesomeModule is the string that was in the $PYTHIA$ file. You can use any string you want here, obviously.

Performance:

The code is written with performance in mind, meaning that function lookups are cached to limit the number of getattrs, for example. However, keep in mind that the accessibility requirements (SQF <=> Python type conversion) and the general overhead caused by BIs design choice of allowing passing only strings to callExtension must take its toll. I'm open to implementing an alternate set of restricted commands that swap convenience for speed, if required, though...

As such, it is suggested to limit the number of python calls in each frame. It is still faster to call one function with two sets of arguments than two functions, one right after the other.

Concrete numbers:

The test below was executed by calling pythia.ping with different types of arguments, meaning that each list of arguments had to be converted to python and the return value had to be converted back to SQF. Each test was conducted 3 times and the lowest value was written down.

The exact arguments for each test can be found in the Benchmarks.

# Type of arguments 3 arguments 10 arguments
1 Integers 0.0137 ms 0.0197 ms
2 Floats 0.0152 ms 0.0229 ms
3 Booleans 0.0109 ms 0.0130 ms
4 Strings 0.0112 ms 0.0151 ms
5 Arrays with ints 0.0174 ms 0.0327 ms
6 Empty arrays 0.0107 ms 0.0131 ms

Note that you will probably usually pass a number of arguments lower than 10 (and if you don't, your function will most probably be slower than the (de)serializing overhead) so you can assume that each Pythia call takes less than 0.02 ms on a recent computer.

This allows for under 150 Pythia calls per frame if you want to stay under the 3ms arbitrary limit (arbitrary because the callExtension calls are not really limited by the engine, they just block execution until finished).

Note: You may get away with calls that take even 100 ms server-side, if they happen rarely enough.

Note: If your code is REALLY big and slow consider using a background Python thread. See below.

Your own mod development

Code reloader

Note: The reloader currently only works for native python code! If your code uses Cython or custom C extensions (dll/pyd files) you will get errors when reloading.

To turn the reloader on, simply call:

["pythia.enable_reloader", [True]] call py3_fnc_callExtension

The reloader will then watch all the imported Pythia modules for changes and if any source file is updated, every loaded module will be reloaded on the next Pythia call. Builtin python modules and modules installed with pip are exempt from reloading.

Important: objects in the global namespace will stay as they are. If such an object points to data inside a module, that data will point to the old (not reloaded) module instance, even after the reload! (the module will not be garbage-collected as long as there is something pointing to it).

This can lead to situations where you have two instances of the same module loaded in-memory. The recommended way is to create pre_reload/post_reload hooks for your module and reinitialize your new module and global variables with the data from the old module, on reload. See below.

Keeping your module data between reloads

To prevent losing data during reload your module needs to have __pre_reload__ and __post_reload__ hooks declared. __post_reload__(state) will be called with the exact same arguments as have been returned by __pre_reload__() before reloading the module.

The reloader works as follows: (simplified pseudo-python code)

def reload_all_modules():
    for module in pythia_modules:
        modules_state[module.__name__] = module.__pre_reload__()

    reload_modules(pythia_modules)

    for module in pythia_modules:
        module.__post_reload__(modules_state[module.__name__])

Creating those functions is purely optional.

Note that using the reloader causes a time penalty for each call and shouldn't be used in production.

Threads

You can spawn Python Threads if you want to have functions running in the background or your functions take more than a few milliseconds to complete and you don't want to lock the game.

See examples/@PythiaThread/ for details.

Installing

Installing Python requirements

If any of your Pythia mods contains a requirements.txt file, simply drag it onto @Pythia\install_requirements64.bat to install all the requirements to both python installations before running the game.

Pythia development

Note: You do NOT need to compile Pythia yourself if all you want is create Python extensions. All you need for that is to subscribe to the mod on Workshop, instead.

Building requirements

  • Any Python 3 installation
  • Visual Studio Community 2019
  • WSL2 with clang and Docker installed and configured
  • MakePBO

Building

First-time build:

Run this on Windows (requires WSL2 and Docker to be installed and configured!)

python -m pip install -r requirements.txt

# Setup WSL for both x86 and x64 architectures
wsl /bin/bash -ic "sudo dpkg --add-architecture i386"
wsl /bin/bash -ic "sudo apt update"
wsl /bin/bash -ic "sudo apt install python3-pip patchelf libcrypt1:i386 clang gcc-multilib"
wsl /bin/bash -ic "python3 -m pip install -r requirements.txt"

python tools\rebuild_all.py

This will fetch and install all the python interpreters required both for building Pythia and then used by Pythia itself at runtime. See build.py which is used by rebuild_all.py for details.

Later, for modifying and building the DLLs/SOs:

  • In Visual Studio: File -> Open -> CMake: CmakeLists.txt, Build -> Build All. Remember to build for all configurations!

Later, for building everything else:

  • python tools\build.py --help
  • See rebuild_all.py for usage

Common errors

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Your Docker environment is misconfigured. You probably need to add yourself to the docker group and restart the shell.

sudo usermod -aG docker $USER

FileExistsError: [Errno 17] File exists: '@Pythia/python-310-embed-linux32'

Docker/WSL2 is probably throwing a fit. Restart WSL by typing this command.

wsl --shutdown

Contributing

All contributions are welcome! Is something in the documentation unclear? Feel free to submit a PR or drop a note on Pythia's Discord server.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].