├── src ├── py │ ├── __init__.py │ ├── Manifest.in │ ├── Makefile │ ├── Readme.md │ ├── uniton │ │ ├── protocol.py │ │ ├── util │ │ │ ├── __init__.py │ │ │ └── appdirs.py │ │ ├── csutil.py │ │ ├── __main__.py │ │ ├── __init__.py │ │ ├── timing.py │ │ ├── namespace.py │ │ ├── unityengine.py │ │ ├── csobject.py │ │ ├── render.py │ │ ├── examples.py │ │ ├── scene.py │ │ └── unityproc.py │ ├── setup.py │ └── .gitignore ├── __init__.py ├── cs │ ├── src │ │ ├── core │ │ │ ├── Operations.cs │ │ │ ├── Util.cs │ │ │ ├── UnityBehaviour.cs │ │ │ └── Render.cs │ │ ├── plus │ │ │ └── flavor.cs │ │ ├── pro │ │ │ └── flavor.cs │ │ ├── free │ │ │ └── flavor.cs │ │ ├── bootstrap │ │ │ ├── FlyCamera.cs │ │ │ └── Bootstrap.cs │ │ └── editor │ │ │ └── Buildinfo.cs │ ├── misc │ │ └── unity-example-package │ │ │ ├── Runtime │ │ │ └── Unity.PySharp.Runtime.asmdef │ │ │ ├── package.json │ │ │ └── manifest.json │ ├── Readme.md │ ├── .gitignore │ └── Makefile ├── .gitignore ├── buildpy.py ├── protocol.py └── buildcs.py ├── examples ├── .gitignore ├── img.png ├── img_1.png ├── img_2.png ├── img_3.png ├── res │ ├── img.png │ ├── img_1.png │ ├── img_2.png │ ├── img_3.png │ ├── img_4.png │ └── img_5.png ├── benchmark_kart.py ├── benchmark_screen.py ├── benchmark_shapes.py ├── kart_instantiate.ipynb ├── Readme.md └── kart.py ├── res ├── c.png ├── signin.png ├── screenshot.png ├── screenshot1.png ├── yt_thumbnail.png ├── yt_thumbnail_old.png └── sp.svg ├── .gitignore ├── README.md └── LICENSE /src/py/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | *.mp4 2 | -------------------------------------------------------------------------------- /src/py/Manifest.in: -------------------------------------------------------------------------------- 1 | include uniton/core.dll -------------------------------------------------------------------------------- /res/c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/c.png -------------------------------------------------------------------------------- /res/signin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/signin.png -------------------------------------------------------------------------------- /examples/img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/img.png -------------------------------------------------------------------------------- /examples/img_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/img_1.png -------------------------------------------------------------------------------- /examples/img_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/img_2.png -------------------------------------------------------------------------------- /examples/img_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/img_3.png -------------------------------------------------------------------------------- /res/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/screenshot.png -------------------------------------------------------------------------------- /examples/res/img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img.png -------------------------------------------------------------------------------- /res/screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/screenshot1.png -------------------------------------------------------------------------------- /res/yt_thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/yt_thumbnail.png -------------------------------------------------------------------------------- /examples/res/img_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img_1.png -------------------------------------------------------------------------------- /examples/res/img_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img_2.png -------------------------------------------------------------------------------- /examples/res/img_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img_3.png -------------------------------------------------------------------------------- /examples/res/img_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img_4.png -------------------------------------------------------------------------------- /examples/res/img_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/examples/res/img_5.png -------------------------------------------------------------------------------- /res/yt_thumbnail_old.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rmst/uniton/HEAD/res/yt_thumbnail_old.png -------------------------------------------------------------------------------- /src/cs/src/core/Operations.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace Uniton{ 3 | public static class Ops{ 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/cs/misc/unity-example-package/Runtime/Unity.PySharp.Runtime.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Unity.Uniton" 3 | } 4 | -------------------------------------------------------------------------------- /src/cs/src/plus/flavor.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | namespace Uniton{ 5 | class Flavor{ 6 | public static string name = "Plus"; 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /src/cs/src/pro/flavor.cs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | namespace Uniton{ 5 | class Flavor{ 6 | public static string name = "Pro"; 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | # OS files 2 | .DS_Store 3 | 4 | # IDE files 5 | .idea/ 6 | 7 | # Python 8 | __pycache__/ 9 | *.pyc 10 | 11 | # Build artifacts 12 | *.dll 13 | *_Protocol.cs 14 | 15 | # Presentation files 16 | *.key 17 | -------------------------------------------------------------------------------- /src/py/Makefile: -------------------------------------------------------------------------------- 1 | # The following variables should be set 2 | # export TWINE_USERNAME='...' 3 | # export TWINE_PASSPORT='...' 4 | 5 | all: 6 | 7 | public: 8 | pip install twine 9 | python setup.py sdist bdist_wheel 10 | twine upload dist/* 11 | rm -rf dist build -------------------------------------------------------------------------------- /src/py/Readme.md: -------------------------------------------------------------------------------- 1 | # Uniton Python Frontent 2 | 3 | To build and upload the Python package to PyPi run 4 | ```bash 5 | export TWINE_USERNAME='SimonRamstedt' 6 | export TWINE_PASSPORT='...' 7 | pip install twine 8 | python setup.py sdist bdist_wheel 9 | twine upload dist/* 10 | rm -rf dist build 11 | ``` -------------------------------------------------------------------------------- /src/py/uniton/protocol.py: -------------------------------------------------------------------------------- 1 | # This is a generated file. Do not modify manually. 2 | 3 | UNITON_VERSION = "0.3.6" 4 | MAGIC_NUMBER = 1283621 5 | 6 | class rpc: 7 | 8 | GETMEMBER = 0 9 | INVOKE = 1 10 | GETOBJ = 2 11 | INIT = 3 12 | NOOP = 4 13 | FLOAT32 = 5 14 | STRING = 6 15 | INT32 = 7 16 | TUPLE = 8 17 | BOOL = 9 18 | OPEN_CMD_STREAM = 10 19 | BYTES = 11 20 | SETMEMBER = 12 21 | 22 | -------------------------------------------------------------------------------- /src/py/uniton/util/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | 4 | def user_data_dir(appname): 5 | if sys.platform == "win32": 6 | data_dir = os.environ["CSIDL_APPDATA"] 7 | elif sys.platform == 'darwin': 8 | home = os.environ["HOME"] 9 | data_dir = f'{home}/Library/Application Support/' 10 | else: 11 | home = os.environ["HOME"] 12 | data_dir = os.environ.get('XDG_DATA_HOME', f"{home}/.local/share") 13 | 14 | return os.path.join(data_dir, appname) 15 | -------------------------------------------------------------------------------- /src/cs/misc/unity-example-package/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "net.uniton.unity", 3 | "version": "0.0.1", 4 | "displayName": "Uniton", 5 | "description": "Python-C# Interface", 6 | "unity": "2020.1", 7 | "unityRelease": "0b5", 8 | "dependencies": { 9 | 10 | }, 11 | "keywords": [ 12 | "python" 13 | ], 14 | "author": { 15 | "name": "Simon Ramstedt", 16 | "email": "simonramstedt@gmail.com", 17 | "url": "https://simonramstedt.com" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/py/uniton/csutil.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def removeprefix(s, prefix): 4 | # this is built into str from Python 3.9 5 | return s[len(prefix):] if s.startswith(prefix) else s 6 | 7 | 8 | class BrokenPromiseException(Exception): 9 | pass 10 | 11 | 12 | class RemoteException(Exception): 13 | pass 14 | 15 | 16 | def topy(x): 17 | if isinstance(x, (list, tuple)): 18 | x = [e.py for e in x] # request all 19 | return [e.wait() for e in x] # wait all 20 | 21 | raise AttributeError(f"Objects like {x} are not supported") -------------------------------------------------------------------------------- /src/cs/src/core/Util.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEngine.Rendering; 3 | using System; 4 | using Unity.Collections; 5 | 6 | 7 | 8 | 9 | 10 | namespace Uniton { 11 | 12 | 13 | public static class Util { 14 | public static object nullreference = null; 15 | } 16 | 17 | 18 | public static class Log { 19 | public enum Level{ 20 | VERBOSE = 0, 21 | DEBUG = 1, 22 | INFO = 2, 23 | ERROR = 3, 24 | } 25 | public static Level level = Level.INFO; 26 | public static void Print(string s, Level level = Level.DEBUG){ 27 | if(level >= Log.level) 28 | UnityEngine.Debug.Log(s); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /src/py/uniton/__main__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from uniton.util import user_data_dir 4 | import shutil 5 | 6 | 7 | def cmd_delete_data(): 8 | d = user_data_dir('Uniton') 9 | shutil.rmtree(d, ignore_errors=True) 10 | print("Deleted all Uniton user data") 11 | 12 | def cmd_open_data_dir(): 13 | os.system(f"open '{user_data_dir('Uniton')}'") 14 | 15 | def cmd_token(): 16 | p = os.path.join(user_data_dir('Uniton'), 'token') 17 | if os.path.exists(p): 18 | print(open(p).read()) 19 | else: 20 | print("You need to log in via the Unity Editor to get a token") 21 | 22 | cmd = sys.argv[1] if len(sys.argv) > 1 else '' 23 | 24 | cmds = {k[4:]: f for k, f in locals().items() if k.startswith("cmd_")} 25 | 26 | if cmd not in cmds: 27 | print("You must provide on of the following commands:") 28 | print(*cmds.keys()) 29 | else: 30 | cmds[cmd](*sys.argv[2:]) 31 | -------------------------------------------------------------------------------- /src/cs/Readme.md: -------------------------------------------------------------------------------- 1 | # Uniton C# Backend 2 | 3 | C# code for the Uniton backend. Everything is compiled into `uniton.dll`. To use Uniton in a new Unity3D project just drop the `uniton.dll` somewhere into the project's `Assets` directory. 4 | 5 | 6 | ### Build 7 | To compile all the `.cs` files into `out/uniton.dll` the [Mono C# compiler](https://www.mono-project.com/download/stable/) `csc` is needed. To compile run 8 | 9 | ```bash 10 | make # check Makefile 11 | cp out/uniton.dll ~/dev/uniton/ 12 | ``` 13 | 14 | 15 | 16 | ### Development 17 | To put `/src` directly into a Unity project the files can be symlinked via 18 | ```bash 19 | ln -sf $(pwd)/src/* destination 20 | ``` 21 | E.g. 22 | ``` 23 | ln -sf $(pwd)/src/* $UNITY_PROJECT_PATH/Assets/Scripts/ 24 | ``` 25 | 26 | 27 | ### Demo 28 | This is a quick demo of Uniton. Uniton is a framework for controlling C# programs and the Unity game engine from Python. 29 | 30 | To show you how easy it to use Uniton, I'm going to open up this example project that comes with Unity. 31 | -------------------------------------------------------------------------------- /src/py/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from os.path import dirname, join 3 | 4 | import sys 5 | if sys.version_info < (3, 7): 6 | sys.exit('Sorry, Python < 3.7 is not supported') 7 | 8 | 9 | def direct_import(path, name=None): 10 | import importlib.util 11 | from os.path import basename, splitext 12 | if not name: 13 | name = splitext(basename(path))[0] 14 | spec = importlib.util.spec_from_file_location(name, path) 15 | module = importlib.util.module_from_spec(spec) 16 | spec.loader.exec_module(module) 17 | return module 18 | 19 | protocol = direct_import(join(dirname(__file__), "uniton", "protocol.py")) 20 | 21 | setup( 22 | name='uniton', 23 | version=protocol.UNITON_VERSION, 24 | description='Control Unity from Python', 25 | url='https://github.com/rmst/uniton', 26 | author='Simon Ramstedt', 27 | author_email='simonramstedt@gmail.com', 28 | license='', 29 | packages=find_packages(), 30 | scripts=[], 31 | install_requires=[ 32 | # there shouldn't be any hard dependecies (we promise that in the readme) 33 | ], 34 | zip_safe=False, 35 | include_package_data=True 36 | ) -------------------------------------------------------------------------------- /src/cs/.gitignore: -------------------------------------------------------------------------------- 1 | # This .gitignore file should be placed at the root of your Unity project directory 2 | # 3 | # Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore 4 | # 5 | 6 | out 7 | 8 | 9 | /[Ll]ibrary/ 10 | /[Tt]emp/ 11 | /[Oo]bj/ 12 | /[Bb]uild/ 13 | /[Bb]uilds/ 14 | /[Ll]ogs/ 15 | /[Mm]emoryCaptures/ 16 | 17 | # Asset meta data should only be ignored when the corresponding asset is also ignored 18 | !/[Aa]ssets/**/*.meta 19 | 20 | # Uncomment this line if you wish to ignore the asset store tools plugin 21 | # /[Aa]ssets/AssetStoreTools* 22 | 23 | # Autogenerated Jetbrains Rider plugin 24 | [Aa]ssets/Plugins/Editor/JetBrains* 25 | 26 | # Visual Studio cache directory 27 | .vs/ 28 | 29 | # Gradle cache directory 30 | .gradle/ 31 | 32 | # Autogenerated VS/MD/Consulo solution and project files 33 | ExportedObj/ 34 | .consulo/ 35 | *.csproj 36 | *.unityproj 37 | *.sln 38 | *.suo 39 | *.tmp 40 | *.user 41 | *.userprefs 42 | *.pidb 43 | *.booproj 44 | *.svd 45 | *.pdb 46 | *.mdb 47 | *.opendb 48 | *.VC.db 49 | 50 | # Unity3D generated meta files 51 | *.pidb.meta 52 | *.pdb.meta 53 | *.mdb.meta 54 | 55 | # Unity3D generated file on crash reports 56 | sysinfo.txt 57 | 58 | # Builds 59 | *.apk 60 | *.unitypackage 61 | 62 | # Crashlytics generated file 63 | crashlytics-build.properties 64 | 65 | -------------------------------------------------------------------------------- /src/cs/Makefile: -------------------------------------------------------------------------------- 1 | DIR:=$(strip $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))) 2 | UNITYENGINE_DLL?=$(error UNITYENGINE_DLL is not set) 3 | UNITYEDITOR_DLL?=$(error UNITYEDITOR_DLL is not set) 4 | FLAVOR:=plus 5 | 6 | dll: 7 | csc -target:library \ 8 | -r:${UNITYENGINE_DLL} \ 9 | -r:${UNITYEDITOR_DLL} \ 10 | -r:./lib/AsyncGPUReadbackPlugin.dll \ 11 | -out:./out/${NAME} \ 12 | ./src/*.cs \ 13 | ./src/${FLAVOR}/*.cs 14 | dlls: 15 | make dll FLAVOR=free NAME=uniton.dll 16 | make dll FLAVOR=plus NAME=uniton-plus.dll 17 | make dll FLAVOR=pro NAME=uniton-pro.dll 18 | 19 | src-link: 20 | rm -rf ${TGT}/Uniton; mkdir ${TGT}/Uniton 21 | ln -sf ${DIR}/src/*.cs ${TGT}/Uniton/ 22 | mkdir ${TGT}/Uniton/${FLAVOR} 23 | ln -sf ${DIR}/src/${FLAVOR}/*.cs ${TGT}/Uniton/${FLAVOR}/ 24 | 25 | src-test: 26 | @echo "Set UNITY_PROJECT_PATH environment variable to test" 27 | @test -n "$$UNITY_PROJECT_PATH" && make src-link TGT=$$UNITY_PROJECT_PATH/Assets/ FLAVOR=pro || true 28 | 29 | 30 | dll-link: 31 | rm -rf ${TGT}/Uniton; mkdir ${TGT}/Uniton 32 | ln -sf ${DIR}/out/${NAME} ${TGT}/Uniton/ 33 | 34 | dll-test: 35 | @echo "Set UNITY_PROJECT_PATH environment variable to test" 36 | make dll FLAVOR=free NAME=uniton.dll 37 | @test -n "$$UNITY_PROJECT_PATH" && make dll-link TGT=$$UNITY_PROJECT_PATH/Assets/ NAME=uniton.dll || true -------------------------------------------------------------------------------- /src/buildpy.py: -------------------------------------------------------------------------------- 1 | # The following variables should be set 2 | # export TWINE_USERNAME='...' 3 | # export TWINE_PASSWORD='...' 4 | from contextlib import contextmanager 5 | 6 | from os.path import dirname, join 7 | import os 8 | import protocol 9 | import buildcs 10 | 11 | CS = join(dirname(__file__), 'cs') 12 | PY = join(dirname(__file__), 'py') 13 | 14 | 15 | def s(*args): 16 | import os 17 | assert os.system(*args) == 0 18 | 19 | 20 | def r(f): 21 | f() 22 | 23 | 24 | @contextmanager 25 | def cwd(path): 26 | import os 27 | orig = os.getcwd() 28 | os.chdir(path) 29 | yield 30 | os.chdir(orig) 31 | 32 | 33 | def dev(): 34 | open(f"{PY}/uniton/core.dll", 'wb').write(buildcs.core_dll()) 35 | open(f"{PY}/uniton/protocol.py", "w").write(protocol.template_py()) 36 | 37 | 38 | def pypi(): 39 | open(f"{PY}/uniton/core.dll", 'wb').write(buildcs.core_dll()) 40 | open(f"{PY}/uniton/protocol.py", "w").write(protocol.template_py()) 41 | 42 | with cwd(PY): 43 | s('pip install twine') 44 | s('rm -rf build dist') 45 | s('python setup.py sdist bdist_wheel') 46 | twine_username = os.getenv("TWINE_USERNAME") 47 | twine_password = os.getenv("TWINE_PASSWORD") 48 | s(f'TWINE_USERNAME={twine_username} TWINE_PASSWORD={twine_password} twine upload dist/*') 49 | s('rm -rf dist build') 50 | 51 | 52 | if __name__ == '__main__': 53 | pypi() 54 | 55 | -------------------------------------------------------------------------------- /src/protocol.py: -------------------------------------------------------------------------------- 1 | from os.path import dirname, join 2 | 3 | CS = join(dirname(__file__), 'cs') 4 | PY = join(dirname(__file__), 'py') 5 | 6 | 7 | UNITON_VERSION = "0.3.6" 8 | # UNITON_DLL_VERSION = "0.3.0" 9 | MAGIC_NUMBER = 1283621 10 | 11 | skip_dll_bytes = 239 12 | 13 | 14 | def replace_all(variables: dict, template: str): 15 | for k, v in variables.items(): 16 | template = template.replace(f"<<<{k}>>>", v) 17 | 18 | return template 19 | 20 | 21 | # TODO: remove rpc class and expose constants directly 22 | def template_py(): 23 | return f"""\ 24 | # This is a generated file. Do not modify manually. 25 | 26 | UNITON_VERSION = "{UNITON_VERSION}" 27 | MAGIC_NUMBER = {MAGIC_NUMBER} 28 | 29 | class rpc: 30 | 31 | GETMEMBER = 0 32 | INVOKE = 1 33 | GETOBJ = 2 34 | INIT = 3 35 | NOOP = 4 36 | FLOAT32 = 5 37 | STRING = 6 38 | INT32 = 7 39 | TUPLE = 8 40 | BOOL = 9 41 | OPEN_CMD_STREAM = 10 42 | BYTES = 11 43 | SETMEMBER = 12 44 | 45 | """ 46 | 47 | 48 | # TODO: add more of the protocol below 49 | # in format string f"..." we can write {{ to produce one curly brace 50 | 51 | def template_cs(namespace="Uniton"): 52 | return f"""\ 53 | // This is a generated file. Do not modify manually. 54 | namespace {namespace}{{ 55 | 56 | public static class Protocol{{ 57 | public static string UNITON_VERSION = "{UNITON_VERSION}"; 58 | public static int MAGIC_NUMBER = {MAGIC_NUMBER}; 59 | }} 60 | 61 | }} 62 | """ 63 | -------------------------------------------------------------------------------- /src/cs/src/free/flavor.cs: -------------------------------------------------------------------------------- 1 | using UnityEditor; 2 | using UnityEditor.Build; 3 | using UnityEditor.Build.Reporting; 4 | using UnityEngine; 5 | using UnityEditor.Build.Reporting; 6 | 7 | using UnityEditor.SceneManagement; // will fail during compile of standalone 8 | using System; 9 | 10 | namespace Uniton{ 11 | 12 | [InitializeOnLoad] // will run as soon as the script is compiled 13 | public class FlavorGuard{ 14 | static FlavorGuard(){ 15 | BuildPlayerWindow.RegisterBuildPlayerHandler(BuildPlayerHandler); 16 | } 17 | 18 | public static void BuildPlayerHandler(BuildPlayerOptions obj) 19 | { 20 | throw new BuildPlayerWindow.BuildMethodException("Uniton Plus or Uniton Pro is needed to build standalone. You can get them at https://github.com/sponsors/uniton-dev. Otherwise, you can build your project without Uniton by removing the uniton.dll from the assets."); 21 | } 22 | } 23 | 24 | 25 | class FreeBuildProcessor : IPreprocessBuildWithReport{ 26 | public int callbackOrder { get { return 0; } } 27 | public void OnPreprocessBuild(BuildReport report){ 28 | // Debug.Log("MyCustomBuildProcessor.OnPreprocessBuild for target " + report.summary.platform + " at path " + report.summary.outputPath);j 29 | // throw new Exception("Uniton Plus or Uniton Pro is needed to build standalone"); 30 | } 31 | } 32 | 33 | 34 | class Flavor{ 35 | public static string name = "Free"; 36 | UnityEditor.SceneManagement.EditorSceneManager stest; // will fail during compile of standalone 37 | 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /examples/benchmark_kart.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import imageio 3 | from timeit import timeit 4 | from uniton import UnityEngine 5 | from uniton.render import QueuedRenderer 6 | 7 | import os 8 | ue = UnityEngine(os.getenv("UNITY_BUILD_PATH")) 9 | # ue = uniton.UnityEngine() 10 | 11 | ue.pause() 12 | # ue.Uniton.Log.level = 3 # suppress log messages 13 | 14 | 15 | ue.scene.BackgroundMusic.SetActive(False) # not necessary but nice 16 | 17 | cam = ue.scene.Main_Camera.Camera 18 | 19 | # we need to make sure that nothing is rendering to the screen because that can slow us down by 10x 20 | cam.enabled = False # this is the only camera in the scene 21 | ue.scene.GameManager.SetActive(False) # disables all GUI in the Kart game 22 | 23 | 24 | def test(n): 25 | # w, h = 1024, 768 26 | w, h = 512, 256 27 | # w, h = 256, 64 28 | renderer = QueuedRenderer(cam, w, h) 29 | 30 | videowriter = imageio.get_writer('test.mp4', fps=25) 31 | kart = ue.scene.KartClassic_Player.Rigidbody # we want to make things move 32 | 33 | for _ in range(n): 34 | frame = renderer.render() 35 | kart.velocity = ue.Vector3(0, 0.5, 0) 36 | kart.angularVelocity = ue.Vector3(0, 1., 0) 37 | ue.step() 38 | videowriter.append_data(frame) 39 | 40 | videowriter.close() 41 | 42 | 43 | print("start timing...") 44 | from timeit import timeit 45 | n = 1000 46 | t = timeit(lambda: test(n), number=1) 47 | 48 | print(f"Rendered {n} frames and simulated {0.04 * n} seconds of game time in {t} seconds.") 49 | print(f"On average, that is {n/t} frames and simulated {0.04 * n / t} seconds of game time per second.") 50 | 51 | from IPython import embed; embed() 52 | -------------------------------------------------------------------------------- /examples/benchmark_screen.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import imageio 3 | from timeit import timeit 4 | from uniton import UnityEngine 5 | from uniton.render import QueuedRenderer 6 | 7 | import os 8 | ue = UnityEngine(os.getenv("UNITY_BUILD_PATH")) 9 | # ue = uniton.UnityEngine() 10 | 11 | ue.pause() 12 | # ue.Uniton.Log.level = 3 # suppress log messages 13 | 14 | 15 | ue.scene.BackgroundMusic.SetActive(False) # not necessary but nice 16 | 17 | cam = ue.scene.Main_Camera.Camera 18 | 19 | # we need to make sure that nothing is rendering to the screen because that can slow us down by 10x 20 | cam.enabled = False # this is the only camera in the scene 21 | ue.scene.GameManager.SetActive(False) # disables all GUI in the Kart game 22 | 23 | 24 | def test(n): 25 | # w, h = 1024, 768 26 | w, h = 512, 256 27 | # w, h = 256, 64 28 | renderer = QueuedRenderer(cam, w, h) 29 | 30 | videowriter = imageio.get_writer('test.mp4', fps=25) 31 | kart = ue.scene.KartClassic_Player.Rigidbody # we want to make things move 32 | 33 | for _ in range(n): 34 | frame = renderer.render() 35 | kart.velocity = ue.Vector3(0, 0.5, 0) 36 | kart.angularVelocity = ue.Vector3(0, 1., 0) 37 | ue.step() 38 | videowriter.append_data(frame) 39 | 40 | videowriter.close() 41 | 42 | 43 | print("start timing...") 44 | from timeit import timeit 45 | n = 1000 46 | t = timeit(lambda: test(n), number=1) 47 | 48 | print(f"Rendered {n} frames and simulated {0.04 * n} seconds of game time in {t} seconds.") 49 | print(f"On average, that is {n/t} frames and simulated {0.04 * n / t} seconds of game time per second.") 50 | 51 | from IPython import embed; embed() 52 | -------------------------------------------------------------------------------- /examples/benchmark_shapes.py: -------------------------------------------------------------------------------- 1 | import uniton 2 | # import numpy as np 3 | # import imageio 4 | # from timeit import timeit 5 | from uniton.render import QueuedRenderer 6 | 7 | import os 8 | ue = uniton.UnityEngine(os.getenv("UNITY_BUILD_PATH")) 9 | # u = uniton.Unity() 10 | ue.pause() 11 | 12 | # u.Uniton.Log.level = 3 # suppress log messages 13 | 14 | cam = ue.GameObject.Find("Main Camera").GetComponent("Camera") 15 | 16 | cam.set_enabled(False) 17 | print("Cameras disabled") 18 | 19 | w, h = 256, 128 20 | 21 | 22 | print(f"{ue.SystemInfo.supportsAsyncGPUReadback = }") 23 | print(f"{ue.QualitySettings.maxQueuedFrames = }") 24 | print(f"{ue.QualitySettings.vSyncCount = }") 25 | print(f"{ue.Application.targetFrameRate = }") 26 | 27 | 28 | def test_queue(n): 29 | import imageio 30 | import numpy as np 31 | cam.usePhysicalProperties = True # necessary to use cam.focalLength 32 | 33 | videowriter = imageio.get_writer('test.mp4', fps=ue.Time.captureFramerate.py()) 34 | 35 | qr = QueuedRenderer(cam, w, h, 4, 3) 36 | for i in range(n): 37 | cam.focalLength = i # to see that something is happening 38 | ue.step() # trigger FixedUpdate and Update 39 | frame = qr.render() 40 | img = np.frombuffer(frame, dtype=np.uint8).reshape(h, w, 4) 41 | videowriter.append_data(img[::-1, :, :3]) 42 | 43 | videowriter.close() 44 | 45 | 46 | print("start timing...") 47 | from timeit import timeit 48 | n = 3000 49 | t = timeit(lambda: test_queue(n), number=1) 50 | 51 | frames_per_step = ue.Time.captureFramerate.py() * ue.Time.fixedDeltaTime.py() 52 | print("frames per step", frames_per_step) 53 | frames = n 54 | print(f"rendered {frames} frames at {frames/t} fps") # around 2000 fps on Macbook 55 | 56 | 57 | # from IPython import embed; embed() 58 | -------------------------------------------------------------------------------- /src/cs/misc/unity-example-package/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "com.unity.collab-proxy": "1.3.9", 4 | "com.unity.ide.rider": "2.0.7", 5 | "com.unity.ide.visualstudio": "2.0.5", 6 | "com.unity.ide.vscode": "1.2.3", 7 | "com.unity.test-framework": "1.1.19", 8 | "com.unity.textmeshpro": "3.0.1", 9 | "com.unity.timeline": "1.2.10", 10 | "com.unity.ugui": "1.0.0", 11 | "com.unity.modules.ai": "1.0.0", 12 | "com.unity.modules.androidjni": "1.0.0", 13 | "com.unity.modules.animation": "1.0.0", 14 | "com.unity.modules.assetbundle": "1.0.0", 15 | "com.unity.modules.audio": "1.0.0", 16 | "com.unity.modules.cloth": "1.0.0", 17 | "com.unity.modules.director": "1.0.0", 18 | "com.unity.modules.imageconversion": "1.0.0", 19 | "com.unity.modules.imgui": "1.0.0", 20 | "com.unity.modules.jsonserialize": "1.0.0", 21 | "com.unity.modules.particlesystem": "1.0.0", 22 | "com.unity.modules.physics": "1.0.0", 23 | "com.unity.modules.physics2d": "1.0.0", 24 | "com.unity.modules.screencapture": "1.0.0", 25 | "com.unity.modules.terrain": "1.0.0", 26 | "com.unity.modules.terrainphysics": "1.0.0", 27 | "com.unity.modules.tilemap": "1.0.0", 28 | "com.unity.modules.ui": "1.0.0", 29 | "com.unity.modules.uielements": "1.0.0", 30 | "com.unity.modules.umbra": "1.0.0", 31 | "com.unity.modules.unityanalytics": "1.0.0", 32 | "com.unity.modules.unitywebrequest": "1.0.0", 33 | "com.unity.modules.unitywebrequestassetbundle": "1.0.0", 34 | "com.unity.modules.unitywebrequestaudio": "1.0.0", 35 | "com.unity.modules.unitywebrequesttexture": "1.0.0", 36 | "com.unity.modules.unitywebrequestwww": "1.0.0", 37 | "com.unity.modules.vehicles": "1.0.0", 38 | "com.unity.modules.video": "1.0.0", 39 | "com.unity.modules.vr": "1.0.0", 40 | "com.unity.modules.wind": "1.0.0", 41 | "com.unity.modules.xr": "1.0.0" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/cs/src/core/UnityBehaviour.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEngine.SceneManagement; 5 | 6 | // using UnpyGrpc; 7 | using System.Threading.Tasks; 8 | // using Grpc.Core; 9 | using System.Runtime.CompilerServices; 10 | using System.Reflection; 11 | using System.Linq; 12 | using System; 13 | 14 | using System; 15 | using System.Net; 16 | using System.Net.Sockets; 17 | using System.Text; 18 | using System.Threading.Tasks; 19 | 20 | using Microsoft.CSharp; 21 | using System.CodeDom.Compiler; 22 | 23 | 24 | namespace Uniton{ 25 | 26 | // this is the entry point for the bootstrap process 27 | public static class Loader { 28 | public static void OnLoad(){ 29 | GameObject go = new GameObject("Uniton"); 30 | go.AddComponent(); 31 | } 32 | } 33 | 34 | // public class UnityBehaviour : MonoBehaviour { 35 | 36 | // // [RuntimeInitializeOnLoadMethod] 37 | // public static void OnLoad(){ 38 | // // Log.Print("Uniton " + Flavor.name + " " + Protocol.UNITON_VERSION + " is running", Log.Level.INFO); 39 | 40 | // AudioListener.volume = 0; // disable sound 41 | 42 | // GameObject go = new GameObject("Uniton"); 43 | // go.AddComponent(); 44 | // } 45 | 46 | // Connection service; 47 | // // Use this for initialization 48 | 49 | // void Awake() { 50 | // this.service = new Connection(); 51 | // // https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html 52 | // DontDestroyOnLoad(this.gameObject); 53 | // } 54 | 55 | // void OnDestroy() { 56 | // this.service.Dispose(); 57 | // } 58 | 59 | // // Update is called once per frame 60 | // void Update () { 61 | // this.service.Update(); 62 | // } 63 | 64 | // void FixedUpdate(){ 65 | // this.service.FixedUpdate(); 66 | // } 67 | 68 | // void OnGUI(){ 69 | // this.service.OnGUI(); 70 | // } 71 | 72 | // } 73 | 74 | } -------------------------------------------------------------------------------- /res/sp.svg: -------------------------------------------------------------------------------- 1 | Sponsor: UnitonSponsorUniton -------------------------------------------------------------------------------- /examples/kart_instantiate.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "photographic-locator", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": "import os\nfrom uniton import UnityEngine\nue = UnityEngine(os.getenv(\"UNITY_BUILD_PATH\"))\n# ue = UnityEngine()" 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 2, 14 | "id": "military-privilege", 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "ue.scene.GameManager.SetActive(False) # disable timer and GUI\n", 19 | "ue.scene.KartClassic_Player.ArcadeKart.SetCanMove(True);" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 3, 25 | "id": "literary-diamond", 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "kart = ue.scene.KartClassic_Player" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 4, 35 | "id": "competent-institute", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "def slow(c, dt=0.05):\n", 40 | " from time import sleep\n", 41 | " for x in c:\n", 42 | " yield x\n", 43 | " sleep(dt)" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 5, 49 | "id": "challenging-florence", 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "copies = [ue.GameObject.Instantiate(kart, kart.position + ue.Vector3(i, 0, j), kart.rotation) for i in range(-4, 5) for j in slow(range(4, 4*20, 4))]" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 6, 59 | "id": "detected-geneva", 60 | "metadata": { 61 | "pycharm": { 62 | "name": "#%%\n" 63 | } 64 | }, 65 | "outputs": [], 66 | "source": [ 67 | "[ue.GameObject.Destroy(c) for c in slow(copies)];" 68 | ] 69 | } 70 | ], 71 | "metadata": { 72 | "kernelspec": { 73 | "display_name": "Python 3", 74 | "language": "python", 75 | "name": "python3" 76 | }, 77 | "language_info": { 78 | "codemirror_mode": { 79 | "name": "ipython", 80 | "version": 3 81 | }, 82 | "file_extension": ".py", 83 | "mimetype": "text/x-python", 84 | "name": "python", 85 | "nbconvert_exporter": "python", 86 | "pygments_lexer": "ipython3", 87 | "version": "3.9.1" 88 | } 89 | }, 90 | "nbformat": 4, 91 | "nbformat_minor": 5 92 | } -------------------------------------------------------------------------------- /examples/Readme.md: -------------------------------------------------------------------------------- 1 | # Example Environments 2 | 3 | Uniton comes with pre-built example environments that automatically download when they are first used. All examples (except 'Empty' and 'Kart') come with a fly cam, which lets you move in 3D and explore the environment with the mouse and WASD-keys. 4 | 5 | 6 | ## Empty Scene 7 | An empty scene - 50 MB 8 | ```python 9 | import uniton 10 | ue = uniton.examples.Empty() 11 | ``` 12 | To modify and compile the scene yourself create an empty project and drop in the `uniton.dll`. 13 | 14 | 15 | ## Kart ([Demo Video](https://www.youtube.com/watch?v=7BHYa1Ycb-A)) 16 | The kart game from the Uniton demo video – 100 MB 17 | ```python 18 | import uniton 19 | ue = uniton.examples.Kart() 20 | ``` 21 | To modify and compile the scene yourself follow the instructions in the video. 22 | 23 | 24 | ## Temple ([Demo Video](https://www.youtube.com/watch?v=Y9R2vkMJCDM)) 25 | ![img_3.png](res/img_3.png) 26 | A large and detailed Temple scene – 300 MB 27 | ```python 28 | import uniton 29 | ue = uniton.examples.Temple() 30 | ``` 31 | To modify and compile the scene yourself you can download it for free from the Asset Store [here](https://assetstore.unity.com/packages/3d/environments/sun-temple-115417). 32 | 33 | 34 | 35 | ## Flooded Grounds ([Demo Video](https://youtu.be/zp7g1VFo_74?t=190)) 36 | ![img.png](res/img.png) 37 | A large outdoor scene – 500 MB 38 | ```python 39 | import uniton 40 | ue = uniton.examples.FloodedGrounds() 41 | ``` 42 | To modify and compile the scene yourself you can download it for free from the Asset Store [here](https://assetstore.unity.com/packages/3d/environments/flooded-grounds-48529). 43 | 44 | 45 | ## Forest ([Video](https://www.youtube.com/watch?v=PELoyIT437Y)) 46 | ![img_4.png](res/img_4.png) 47 | A small but high-fidelity forest scene – 300 MB 48 | ```python 49 | import uniton 50 | ue = uniton.examples.Forest() 51 | ``` 52 | To modify and compile the scene yourself you can download it from the description in the video. 53 | 54 | 55 | ## Windridge City ([Demo Video](https://www.youtube.com/watch?v=qo9vr7GetTA)) 56 | ![img_5.png](res/img_5.png) 57 | A scene containing a mini city surrounded trees and mountains – 500 MB 58 | ```python 59 | import uniton 60 | ue = uniton.examples.WindridgeCity() 61 | ``` 62 | To modify and compile the scene yourself you can download it for free from the Asset Store [here](https://assetstore.unity.com/packages/3d/environments/roadways/windridge-city-132222). -------------------------------------------------------------------------------- /src/py/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OS files 2 | .DS_Store 3 | **/.DS_Store 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | pip-wheel-metadata/ 28 | share/python-wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .nox/ 48 | .coverage 49 | .coverage.* 50 | .cache 51 | nosetests.xml 52 | coverage.xml 53 | *.cover 54 | *.py,cover 55 | .hypothesis/ 56 | .pytest_cache/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | 117 | # Spyder project settings 118 | .spyderproject 119 | .spyproject 120 | 121 | # Rope project settings 122 | .ropeproject 123 | 124 | # mkdocs documentation 125 | /site 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ 134 | -------------------------------------------------------------------------------- /src/py/uniton/__init__.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import subprocess 3 | 4 | # from .unityproc import UnityProc 5 | from os.path import dirname 6 | 7 | from . import protocol 8 | __version__ = protocol.UNITON_VERSION 9 | 10 | from .unityengine import UnityEngine 11 | from . import examples 12 | 13 | 14 | # 15 | # class Uniton(Namespace): 16 | # def __init__(self): 17 | # c = Connection() 18 | # super().__init__(c) 19 | # self.unity = Unity(self) 20 | # 21 | # def close(self): 22 | # self._con.close() 23 | 24 | 25 | # class Unity(CsProc): 26 | # # def __init__(self, path=None, port=11000): 27 | # # pass 28 | # 29 | # _default_timescales = (1., 0.02, 0.) # the real values will be set on stepping=True 30 | # 31 | # @property 32 | # def stepping(self): 33 | # return self._backend.stepping.py() 34 | # 35 | # @stepping.setter 36 | # def stepping(self, v): 37 | # t = self.UnityEngine.Time 38 | # if v: 39 | # self._default_timescales = ( 40 | # t.timeScale, 41 | # t.fixedDeltaTime, 42 | # t.captureDeltaTime, 43 | # ) 44 | # t.timeScale = 100 # Warning: 100 is the max value. if higher Unity will silently reject the change! 45 | # t.fixedDeltaTime = 0.02 46 | # t.captureDeltaTime = 0.02 # aligns Update and FixedUpdate 47 | # else: 48 | # (t.timeScale, t.fixedDeltaTime, t.captureDeltaTime) = self._default_timescales 49 | # self._backend.setStepping(v) 50 | # 51 | # def step(self): 52 | # if "_step" not in vars(self): 53 | # self._step = self._backend.step 54 | # self._step() 55 | # # self._con.u.step() 56 | 57 | 58 | # class Unity(Connection): 59 | # def __init__(self): 60 | # # TODO: create tmp dir, override $HOME and watch unity log paths (https://docs.unity3d.com/Manual/LogFiles.html) 61 | # pass 62 | 63 | 64 | 65 | 66 | def _monkey_patch_completer(): 67 | # Avoid querying every object on autocomplete in the REPL. 68 | 69 | from .csobject import CsObject 70 | from .namespace import Namespace 71 | 72 | def patched_getattr(object, name, default=None): 73 | if isinstance(object, (CsObject, Namespace)): 74 | return None 75 | # raise AttributeError() 76 | # return getattr(object, name) 77 | else: 78 | return getattr(object, name, default) 79 | 80 | try: 81 | import rlcompleter 82 | rlcompleter.getattr = patched_getattr 83 | except: 84 | pass 85 | 86 | try: 87 | from jedi.inference.compiled import access 88 | access.getattr = patched_getattr 89 | except: 90 | pass 91 | 92 | _monkey_patch_completer() 93 | 94 | -------------------------------------------------------------------------------- /src/py/uniton/timing.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | IMPORTANT NOTE ON TIMING IN THE UNITY ENGINE - FIXEDUPDATE VS UPDATE 4 | 5 | This is assuming you already know when `Update` and `FixedUpdate` are called. If you don't, check this https://answers.unity.com/questions/640828/can-anyone-link-to-explain-unitys-game-loop.html. 6 | 7 | Here, we're talking about timing when we're in "capture mode", i.e. when `Time.captureDeltaTime = 1 / Time.captureFramerate != 0`. In that case real time doesn't matter. Instead, `FixedUpdate` and `Update` will run at a constant fraction of each other. The tricky part is to understand what that rate is. Normally, you'd think the following holds 8 | 9 | ```FixedUpdates = Time.fixedDeltaTime / Time.captureDeltaTime * Updates``` 10 | 11 | However, if `Time.timeScale != 1`, then `Time.fixedDeltaTime` is enforced in scaled time (i.e. `Time.time`) and `Time.captureDeltaTime` is enforced in unscaled time (i.e. `Time.time / Time.timeScale`). Therefore, we need 12 | 13 | ```Time.captureDeltaTime = actualCaptureDeltaTime / Time.timeScale``` 14 | 15 | or alternatively 16 | 17 | ```Time.captureFrameRate = actualCaptureFramerate * Time.timeScale``` 18 | 19 | It seems silly but maybe the Unity devs had their reasons. 20 | 21 | Note that generally `Time.timeScale` should be set to `100` to allow the engine to run faster than real-time. Careful, though, if you set it to higher than `100` Unity will silently reject the change! 22 | """ 23 | 24 | 25 | 26 | class Time: 27 | """ 28 | This class only has an effect in 'paused mode' 29 | """ 30 | def __init__(self, ue): 31 | self._ue = ue 32 | self._delta = 0.04 33 | self._physics_substeps = 2 34 | 35 | @property 36 | def delta(self): 37 | return self._delta 38 | 39 | @delta.setter 40 | def delta(self, v): 41 | self._delta = v 42 | if self._ue.paused(): 43 | self._update_engine_timing() 44 | 45 | def _update_engine_timing(self): 46 | self._ue.Time.captureDeltaTime = self._delta / self._ue.Time.timeScale.py() 47 | self._ue.Time.fixedDeltaTime = self._desired_fixed_delta() 48 | 49 | def _desired_fixed_delta(self): 50 | return self._delta / self._physics_substeps 51 | 52 | @property 53 | def physics_substeps(self): 54 | return self._physics_substeps 55 | 56 | @physics_substeps.setter 57 | def physics_substeps(self, v: int): 58 | self._physics_substeps = v 59 | if self._desired_fixed_delta() < 0.0001: 60 | raise ValueError("Unity won't allow physics timesteps smaller than 0.0001") 61 | 62 | if self._ue.paused(): 63 | self._update_engine_timing() 64 | 65 | 66 | 67 | # def _approximate_integer_multiple(x, y): 68 | # modulo = x % y 69 | # return modulo < 1e-3 70 | -------------------------------------------------------------------------------- /src/py/uniton/namespace.py: -------------------------------------------------------------------------------- 1 | from functools import lru_cache 2 | from .csutil import topy 3 | 4 | 5 | # noinspection PyProtectedMember 6 | class Namespace: 7 | ue = None 8 | 9 | def __init__(self, ue, ns=""): 10 | self.ue = ue 11 | self._ns = ns 12 | 13 | def __getattr__(self, k): 14 | 15 | # this shit below is necessary because somehow @property and @cached_property is interfering with __getattr__ 16 | if k == '_namespaces': 17 | self._namespaces = self._get_namespaces() 18 | return self._namespaces 19 | if k == '_typenames': 20 | self._typenames = self._get_typenames() 21 | return self._typenames 22 | # ----- 23 | 24 | if ( 25 | k in ("_ipython_canary_method_should_not_exist_", "_repr_mimebundle_") # this is needed for the ipython console 26 | or k.startswith('_') # probably Python internal 27 | ): 28 | raise AttributeError(f'{self} does not have a property called {k}') 29 | 30 | # print("gettr", self._ns, k) 31 | 32 | full_name = self._ns + '.' + k if self._ns else k 33 | 34 | if k in self._namespaces: 35 | v = Namespace(self.ue, full_name) 36 | elif k in self._typenames: 37 | # TODO: make class CsType and cache methods? 38 | v = self.ue._backend.GetTypeByFullName(full_name) 39 | elif self._ns == "" and k in self.UnityEngine._namespaces + self.UnityEngine._typenames: 40 | v = getattr(self.UnityEngine, k) 41 | else: 42 | if self._ns == "": 43 | raise AttributeError(f"'{k}' is not a type or namespace in root nor UnityEngine") 44 | else: 45 | raise AttributeError(f"'{k}' is not a type or namespace in {self._ns}") 46 | 47 | if v is not None: # occurs after exceptions 48 | vars(self)[k] = v # next time __getattr__ won't be called again 49 | return v 50 | 51 | def _get_namespaces(self): 52 | x = self.ue._backend.GetNamespaces(self._ns) # C# 53 | x = [e.py for e in x] 54 | x = (e.wait() for e in x) 55 | x = (e.split('.')[-1] for e in x) 56 | x = (e for e in x if e.isidentifier()) 57 | return list(set(x)) 58 | 59 | def _get_typenames(self): 60 | x = self.ue._backend.GetTypenamesInNamespace(self._ns) 61 | x = topy(list(x)) 62 | x = (e.split('.')[-1] for e in x) 63 | x = (e for e in x if e.isidentifier()) 64 | return list(set(x)) 65 | 66 | def __dir__(self): 67 | r = super().__dir__() 68 | r += self._namespaces 69 | r += self._typenames 70 | if not self._ns: # root ns 71 | r += self.UnityEngine._namespaces 72 | r += self.UnityEngine._typenames 73 | # r += self.System._typenames 74 | r = list(set(r)) 75 | return r 76 | 77 | def __repr__(self): 78 | return f" '{self._ns}'" 79 | -------------------------------------------------------------------------------- /src/cs/src/bootstrap/FlyCamera.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class FlyCamera : MonoBehaviour { 5 | 6 | [SerializeField] 7 | float mainSpeed = 10.0f; //regular speed 8 | [SerializeField] 9 | float shiftAdd = 40.0f; //multiplied by how long shift is held. Basically running 10 | [SerializeField] 11 | float maxShift = 1000.0f; //Maximum speed when holding shift 12 | [SerializeField] 13 | float camSens = 5.0f; //How sensitive it with mouse 14 | private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play) 15 | private float totalRun= 1.0f; 16 | 17 | private bool isLocked = true; 18 | 19 | void Update () { 20 | // Unlock curser if escape is pressed, lock it on mouse click 21 | isLocked = isLocked ? (!Input.GetKeyDown(KeyCode.Escape)) : Input.GetMouseButtonDown(0); 22 | 23 | if (isLocked) { 24 | Cursor.lockState = CursorLockMode.Locked; 25 | // Cursor.visible = false; 26 | } else { 27 | Cursor.lockState = CursorLockMode.None; 28 | // Cursor.visible = true; 29 | return; 30 | } 31 | 32 | lastMouse = new Vector3(Input.GetAxisRaw ("Mouse X") , Input.GetAxisRaw ("Mouse Y"), 0); 33 | // lastMouse = Input.mousePosition - lastMouse ; 34 | lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0 ); 35 | lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x , transform.eulerAngles.y + lastMouse.y, 0); 36 | transform.eulerAngles = lastMouse; 37 | // lastMouse = Input.mousePosition; 38 | 39 | //Mouse camera angle done. 40 | 41 | //Keyboard commands 42 | float f = 0.0f; 43 | Vector3 p = GetBaseInput(); 44 | if (Input.GetKey (KeyCode.LeftShift)){ 45 | totalRun += Time.unscaledDeltaTime; 46 | p = p * totalRun * shiftAdd; 47 | p.x = Mathf.Clamp(p.x, -maxShift, maxShift); 48 | p.y = Mathf.Clamp(p.y, -maxShift, maxShift); 49 | p.z = Mathf.Clamp(p.z, -maxShift, maxShift); 50 | } 51 | else{ 52 | totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f); 53 | p = p * mainSpeed; 54 | } 55 | 56 | p = p * Time.unscaledDeltaTime; 57 | Vector3 newPosition = transform.position; 58 | if (Input.GetKey(KeyCode.Space)){ //If player wants to move on X and Z axis only 59 | transform.Translate(p); 60 | newPosition.x = transform.position.x; 61 | newPosition.z = transform.position.z; 62 | transform.position = newPosition; 63 | } 64 | else{ 65 | transform.Translate(p); 66 | } 67 | 68 | 69 | 70 | } 71 | 72 | private Vector3 GetBaseInput() { //returns the basic values, if it's 0 than it's not active. 73 | Vector3 p_Velocity = new Vector3(); 74 | if (Input.GetKey (KeyCode.W)){ 75 | p_Velocity += new Vector3(0, 0 , 1); 76 | } 77 | if (Input.GetKey (KeyCode.S)){ 78 | p_Velocity += new Vector3(0, 0, -1); 79 | } 80 | if (Input.GetKey (KeyCode.A)){ 81 | p_Velocity += new Vector3(-1, 0, 0); 82 | } 83 | if (Input.GetKey (KeyCode.D)){ 84 | p_Velocity += new Vector3(1, 0, 0); 85 | } 86 | return p_Velocity; 87 | } 88 | 89 | } -------------------------------------------------------------------------------- /src/py/uniton/unityengine.py: -------------------------------------------------------------------------------- 1 | 2 | from functools import lru_cache 3 | from .unityproc import UnityProc 4 | 5 | """ 6 | IMPORTANT NOTE ON TIMING IN THE UNITY ENGINE - FIXEDUPDATE VS UPDATE 7 | 8 | This is assuming you already know when `Update` and `FixedUpdate` are called. If you don't, check this https://answers.unity.com/questions/640828/can-anyone-link-to-explain-unitys-game-loop.html. 9 | 10 | Here, we're talking about timing when we're in "capture mode", i.e. when `Time.captureDeltaTime = 1 / Time.captureFramerate != 0`. In that case real time doesn't matter. Instead, `FixedUpdate` and `Update` will run at a constant fraction of each other. The tricky part is to understand what that rate is. Normally, you'd think the following holds 11 | 12 | ```FixedUpdates = Time.fixedDeltaTime / Time.captureDeltaTime * Updates``` 13 | 14 | However, if `Time.timeScale != 1`, then `Time.fixedDeltaTime` is enforced in scaled time (i.e. `Time.time`) and `Time.captureDeltaTime` is enforced in unscaled time (i.e. `Time.time / Time.timeScale`). Therefore, we need 15 | 16 | ```Time.captureDeltaTime = actualCaptureDeltaTime / Time.timeScale``` 17 | 18 | or alternatively 19 | 20 | ```Time.captureFrameRate = actualCaptureFramerate * Time.timeScale``` 21 | 22 | It seems silly but maybe the Unity devs had their reasons. 23 | 24 | Note that generally `Time.timeScale` should be set to `100` to allow the engine to run faster than real-time. Careful, though, if you set it to higher than `100` Unity will silently reject the change! 25 | """ 26 | 27 | 28 | # noinspection PyProtectedMember 29 | class UnityEngine(UnityProc): 30 | _default_settings = (1., 0.02, 0., 1) # the real values will be set on stepping=True 31 | 32 | # def __init__(self, ue): 33 | # super().__init__(ue, "UnityEngine") 34 | 35 | def pause(self): 36 | self._default_settings = ( 37 | self.Time.timeScale, 38 | self.Time.fixedDeltaTime, 39 | self.Time.captureDeltaTime, 40 | self.QualitySettings.vSyncCount, 41 | ) 42 | self.Time.timeScale = 100 # Warning: 100 is the max value. if higher Unity will silently reject the change! 43 | self.QualitySettings.vSyncCount = 0 # otherwise Update can be artificially slowed down to match the display refresh rate 44 | self.time._update_engine_timing() 45 | 46 | self._backend.setStepping(True) 47 | 48 | def paused(self): 49 | return self._backend.stepping.py() 50 | 51 | def resume(self): 52 | ( 53 | self.Time.timeScale, 54 | self.Time.fixedDeltaTime, 55 | self.Time.captureDeltaTime, 56 | self.QualitySettings.vSyncCount, 57 | ) = self._default_settings 58 | 59 | self._backend.setStepping(False) 60 | 61 | def step(self): 62 | if "_step" not in vars(self): 63 | self._step = self._backend.step 64 | self._step() 65 | 66 | @property 67 | @lru_cache(maxsize=None) 68 | def time(self): 69 | from .timing import Time 70 | return Time(self) 71 | 72 | @property # don't cache as the active scene could change! 73 | def scene(self): 74 | from .scene import Scene 75 | active_scene = self.SceneManagement.SceneManager.GetActiveScene() 76 | return Scene(active_scene) 77 | 78 | def reset(self): 79 | self.Application.LoadLevel(0) 80 | -------------------------------------------------------------------------------- /examples/kart.py: -------------------------------------------------------------------------------- 1 | # this is meant to be run interactively in ipython 2 | 3 | # This is short intro to Uniton. Uniton let's you control Unity from Python. You can use it with any Unity project. We're going use this Kart project that comes with Unity. 4 | from uniton import UnityEngine 5 | 6 | ue = UnityEngine() 7 | 8 | # Among other things the `ue` object acts as the C# root namespace 9 | # ue. autocomplete works in the REPL for all namespaces, types and objects 10 | 11 | # To print a message we can do 12 | ue.UnityEngine.Debug.Log("Hello World!") 13 | 14 | # The namespaces are organized in a strict hierarchy. The only exception is the "UnityEngine" namespace which is directly available from `ue`. 15 | 16 | # Therefore we can also do 17 | ue.Debug.Log("Hello World!") 18 | # --- 19 | 20 | # timer is running out 21 | # let's try if we can do sth about that 22 | ue.GameObject.Find("GameManager") 23 | _.GetComponent("TimeManager") 24 | _.TimeRemaining # returns remaining time 25 | __.TimeRemaining = 10000 26 | # alright, we're safe 27 | # --- 28 | 29 | # ue.GameObject.Find("GameManager").GetComponent("TimeManager").TimeRemaining = 10000 30 | # ue.GameObject.Find("Main Camera").GetComponent("Camera").enabled = False 31 | 32 | 33 | # okay, let's try to make something move 34 | ue.GameObject.Find("KartClassic_Player") 35 | _.GetComponent("ArcadeKart") 36 | 37 | # let's give this a name 38 | kart = _ 39 | kart.Rigidbody.velocity # ok but what type is that? 40 | kart.Rigidbody.velocity.GetType() # UnityEngine.Vector3 41 | 42 | kart.Rigidbody.velocity = ue.Vector3(30, 0, 0) # goes backwards 43 | kart.Rigidbody.velocity = ue.Vector3(-30, 0, 0) 44 | 45 | # Cool this is cute, but let's shift gears 46 | 47 | 48 | # == Rotate == 49 | kart = ue.scene.KartClassic_Player.Rigidbody # we want to make things move 50 | for i in range(250): 51 | kart.velocity = ue.Vector3(0, 0.5, 0) 52 | kart.angularVelocity = ue.Vector3(0, 1., 0) 53 | ue.step() 54 | 55 | 56 | # == Rotate and Render == 57 | from uniton import UnityEngine 58 | import os 59 | ue = UnityEngine(os.getenv("UNITY_BUILD_PATH")) 60 | ue.pause() 61 | 62 | # QueuedRenderer helps with getting frames from Unity without blocking execution 63 | from uniton.render import QueuedRenderer 64 | renderer = QueuedRenderer(camera=ue.scene.Main_Camera.Camera, width=512, height=256) 65 | 66 | # create videowriter to encode mp4 67 | import imageio # install with: pip install imageio imageio-ffmpeg 68 | videowriter = imageio.get_writer('test.mp4', fps=25) 69 | 70 | # similar loop as before just now with the renderer and videowriter 71 | kart = ue.scene.KartClassic_Player.Rigidbody 72 | 73 | for i in range(250): 74 | kart.velocity = ue.Vector3(0, 0.5, 0) 75 | kart.angularVelocity = ue.Vector3(0, 1., 0) 76 | ue.step() 77 | frame = renderer.render() 78 | videowriter.append_data(frame) 79 | 80 | videowriter.close() 81 | 82 | # We can speed this up by making sure that nothing renders to the screen. 83 | ue.scene.Main_Camera.Camera.enabled = False # this is the only camera in the scene 84 | ue.scene.GameManager.SetActive(False) # disables all GUI in the Kart game 85 | 86 | # run the above loop againg (will be 10x faster) 87 | 88 | 89 | # == Fly Trajectory == 90 | # for some reason, when rendered off-screen, the camera will separate from the kart 91 | import numpy as np 92 | kart = ue.scene.KartClassic_Player.transform 93 | p0 = kart.position 94 | r0 = kart.rotation 95 | for i in range(250): 96 | progress = i / 250 97 | kart.position = p0 + ue.Vector3(0, progress**4 * 30, progress * 100) # 30m up and 100m forwards 98 | kart.rotation = r0 99 | ue.step() -------------------------------------------------------------------------------- /src/buildcs.py: -------------------------------------------------------------------------------- 1 | from os.path import dirname, join 2 | 3 | CS = join(dirname(__file__), 'cs') 4 | PY = join(dirname(__file__), 'py') 5 | 6 | import os 7 | UNITYENGINE_DLL = os.getenv("UNITYENGINE_DLL") 8 | UNITYEDITOR_DLL = os.getenv("UNITYEDITOR_DLL") 9 | 10 | # TODO: check if we still need AsyncGPUReadbackPlugin.dll for linux 11 | 12 | import protocol 13 | 14 | 15 | def s(*args): 16 | import os 17 | assert os.system(*args) == 0 18 | 19 | 20 | # https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/output 21 | def core_dll(): 22 | open(f"{CS}/src/core/_Protocol.cs", "w").write(protocol.template_cs("Uniton")) 23 | 24 | s(f"csc -target:library \ 25 | -r:{UNITYENGINE_DLL} \ 26 | -r:{UNITYEDITOR_DLL} \ 27 | -r:{CS}/lib/AsyncGPUReadbackPlugin.dll \ 28 | -out:{CS}/out/core.dll \ 29 | {CS}/src/core/*.cs") 30 | 31 | dll = open(f"{CS}/out/core.dll", 'rb').read() 32 | dll = dll[-239:] + dll 33 | return dll 34 | 35 | 36 | def uniton_dll(): 37 | # embedding dlls into each other :D 38 | 39 | open(f"{CS}/src/bootstrap/_Protocol.cs", "w").write(protocol.template_cs("Uniton.Bootstrap")) 40 | 41 | s(f"csc -target:library \ 42 | -r:{UNITYENGINE_DLL} \ 43 | -r:{UNITYEDITOR_DLL} \ 44 | -r:System.Net.Http.dll \ 45 | -r:{CS}/lib/AsyncGPUReadbackPlugin.dll \ 46 | -out:{CS}/out/bootstrap.dll \ 47 | {CS}/src/bootstrap/*.cs") 48 | 49 | open(f"{CS}/src/editor/_Protocol.cs", "w").write(protocol.template_cs("Uniton.Editor")) 50 | 51 | s(f"csc -target:library \ 52 | -r:{UNITYENGINE_DLL} \ 53 | -r:{UNITYEDITOR_DLL} \ 54 | -r:System.Net.Http.dll \ 55 | -res:{CS}/out/bootstrap.dll \ 56 | -r:{CS}/lib/AsyncGPUReadbackPlugin.dll \ 57 | -out:{CS}/out/uniton.dll \ 58 | {CS}/src/editor/*.cs \ 59 | ") 60 | 61 | 62 | def link_uniton_dll(target): 63 | s(f"rm -rf {target}/Uniton && mkdir {target}/Uniton") 64 | s(f"ln -sf {CS}/out/uniton.dll {target}/Uniton/") 65 | 66 | 67 | def test_uniton_dll(): 68 | uniton_dll() 69 | unity_projects = os.getenv("UNITY_PROJECTS", "").split(":") 70 | for project in unity_projects: 71 | if project: 72 | link_uniton_dll(f'{project}/Assets') 73 | 74 | 75 | def link_cs(target): 76 | s(f"rm -rf {target}/Uniton && mkdir {target}/Uniton") 77 | s( 78 | f"mkdir {target}/Uniton/Editor && ln -sf {CS}/src/editor/*.cs {target}/Uniton/Editor") # contains editor specific stuff 79 | s(f"mkdir {target}/Uniton/Bootstrap && ln -sf {CS}/src/bootstrap/*.cs {target}/Uniton/Bootstrap") # standalone 80 | s(f"mkdir {target}/Uniton/Core && ln -sf {CS}/src/core/*.cs {target}/Uniton/Core") # core 81 | 82 | 83 | def test_cs(): 84 | unity_projects = os.getenv("UNITY_PROJECTS", "").split(":") 85 | for project in unity_projects[:2]: # limit to first 2 for testing 86 | if project: 87 | link_cs(f'{project}/Assets') 88 | 89 | 90 | def zip_bin(name): 91 | import shutil 92 | print(f"zipping {name}") 93 | build_dir = os.getenv("UNITY_BUILD_DIR", "") 94 | if build_dir: 95 | shutil.make_archive(f'cs/out/{name}_mac', 'zip', f'{build_dir}/{name}/Out/{name.capitalize()}.app') 96 | shutil.make_archive(f'cs/out/{name}_linux', 'zip', f'{build_dir}/{name}/Out/{name.capitalize()}-Linux') 97 | shutil.make_archive(f'cs/out/{name}_windows', 'zip', f'{build_dir}/{name}/Out/{name.capitalize()}-Windows') 98 | 99 | 100 | def example_builds(): 101 | # test_dll('pro') 102 | # input("Press enter when all examples have finished building!") 103 | # TODO: automatic unity build 104 | 105 | # zip_bin('empty') 106 | # zip_bin('kart') 107 | # zip_bin('temple') 108 | # zip_bin('floodedgrounds') 109 | # zip_bin('windridgecity') 110 | zip_bin('forest') 111 | 112 | 113 | if __name__ == '__main__': 114 | # test_uniton_dll() 115 | # test_cs() 116 | 117 | example_builds() 118 | -------------------------------------------------------------------------------- /src/py/uniton/csobject.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | from uniton.protocol import rpc 4 | from uniton.csutil import removeprefix, BrokenPromiseException, RemoteException 5 | 6 | 7 | class Promise: 8 | value = None 9 | 10 | def __init__(self): 11 | self.evt = threading.Event() 12 | 13 | def resolve(self, x): 14 | self.value = x 15 | self.evt.set() 16 | 17 | def __call__(self): 18 | return self.wait() 19 | 20 | def wait(self): 21 | self.evt.wait() 22 | # while self.value is None: 23 | # next(self.con.rit) 24 | 25 | if isinstance(self.value, BrokenPromiseException): 26 | raise self.value 27 | 28 | return self.value 29 | 30 | 31 | GETATTR_BLACKLIST = ( 32 | "_ipython_canary_method_should_not_exist_", # ipython console uses this 33 | "_repr_mimebundle_", # ipython console uses this 34 | ) 35 | 36 | 37 | # noinspection PyProtectedMember 38 | class CsObject: 39 | ue = None 40 | id = None 41 | 42 | def __init__(self, ue, id): 43 | self.ue = ue 44 | self.id = id 45 | 46 | def __getattr__(self, k: str): 47 | if k.startswith('_') or k in GETATTR_BLACKLIST: 48 | raise AttributeError() 49 | 50 | # from traceback import print_stack 51 | # print_stack(limit=2) 52 | # print('getattr', k) 53 | # print("----") 54 | 55 | id = self.ue.cmd(rpc.GETMEMBER, self.ue.serialize_objs(k, self)) 56 | return CsObject(self.ue, id) 57 | 58 | def __setattr__(self, k, v): 59 | if k in ("ue", "id") or k.startswith('_') or k in GETATTR_BLACKLIST: 60 | return super().__setattr__(k, v) 61 | 62 | self.ue.cmd(rpc.SETMEMBER, self.ue.serialize_objs(self, k, v)) 63 | 64 | def __getitem__(self, k): 65 | return self.get_Item(k) 66 | 67 | def __setitem__(self, k, v): 68 | return self.set_Item(k, v) 69 | 70 | def __iter__(self): 71 | for i in range(len(self)): 72 | yield self[i] 73 | 74 | def __len__(self): 75 | return self.Count.py() 76 | 77 | def __bool__(self): 78 | return self.py() 79 | 80 | def __call__(self, *args): 81 | # TODO: better error message for wrong argument types 82 | # return self._con.cmd(rpc.INVOKE, (self, args)) 83 | id = self.ue.cmd(rpc.INVOKE, self.ue.serialize_objs(self, *args)) 84 | return CsObject(self.ue, id) 85 | 86 | @property 87 | def py(self): 88 | out = None 89 | out = Promise() if out is None else out 90 | return self.ue.cmd(rpc.GETOBJ, self.ue.serialize_objs(self), out=out) 91 | 92 | def __str__(self): 93 | try: 94 | return "C# " + self.ue._backend.ToStr(self).py() 95 | except BrokenPromiseException as e: 96 | # return "C# (Broken Promise)" 97 | return "" 98 | except: 99 | return "" 100 | 101 | def __repr__(self): 102 | return self.__str__() 103 | 104 | def __dir__(self): 105 | try: 106 | t = self.GetType() 107 | 108 | if t.IsSubclassOf(self.ue._cs_type).py(): 109 | # self is a type 110 | x = [m.Name.py for m in self.GetMethods()] 111 | else: 112 | x = [m.Name.py for m in t.GetMethods()] 113 | x += [m.Name.py for itf in t.GetInterfaces() for m in itf.GetMethods()] 114 | 115 | x = (m.wait() for m in x) 116 | x = (removeprefix(e, "get_") for e in x) 117 | x = (removeprefix(e, "set_") for e in x) 118 | x = set(x) 119 | x = (e for e in x if e.isidentifier()) 120 | except RemoteException: 121 | x = [] 122 | 123 | r = super().__dir__() 124 | r += list(x) 125 | return r 126 | 127 | def __del__(self): 128 | # del self._con.objs[self.id] 129 | # TODO: Notify the unity registry 130 | 131 | # print("Del ", self.id) 132 | 133 | # self._con.udel(self.id) 134 | self.ue.delete_object(self.id) 135 | 136 | # TODO: add more operators 137 | # TODO: make operators work on C# value types (might be hard) 138 | # https://stackoverflow.com/questions/11113259/how-to-call-custom-operator-with-reflection 139 | def __mul__(self, other): 140 | return self.op_Multiply(self, other) 141 | 142 | def __add__(self, other): 143 | return self.op_Addition(self, other) 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /src/py/uniton/render.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class QueuedRenderer: 5 | """ 6 | Uses two queues: 7 | Unity GPU (render) --render_queue--> Unity CPU --ipc_queue--> Python 8 | 9 | This is not ideal. The ipc queue should be replaced with a push mechanism once that is possible. 10 | 11 | Reduces to non-queued rendering for render_steps = ipc_steps = 1 12 | """ 13 | def __init__(self, camera, width, height, render_steps=4, ipc_steps=3, fill=True): 14 | self.width = width 15 | self.height = height 16 | self.camera = camera 17 | self.render_steps = render_steps 18 | self.ipc_steps = ipc_steps 19 | self.ue = camera.ue 20 | self._renderer = self.ue.Uniton.RenderQueue(render_steps) 21 | texture_fmt = self.ue.RenderTextureFormat.ARGB32 22 | get_texture = self.ue.RenderTexture.GetTemporary 23 | self.textures = [get_texture(width, height, 0, texture_fmt) for _ in range(render_steps)] 24 | self.ipc_queue = deque(maxlen=ipc_steps) 25 | self.step = 0 26 | 27 | if fill: 28 | for i in range(render_steps+ipc_steps): 29 | self.render() 30 | 31 | def delay(self): 32 | return self.render_steps + self.ipc_steps - 2 33 | 34 | def render_raw(self): 35 | original_tex = self.camera.targetTexture 36 | self.camera.targetTexture = self.textures[self.step % self.render_steps] 37 | remote_frame = self._renderer.Render(self.camera) 38 | self.camera.targetTexture = original_tex 39 | 40 | self.step += 1 41 | 42 | self.ipc_queue.append(remote_frame.py) 43 | 44 | if len(self.ipc_queue) < self.ipc_queue.maxlen: 45 | return None 46 | 47 | frame_bytes = self.ipc_queue.popleft().wait() 48 | if len(frame_bytes) == 0: 49 | return None 50 | 51 | return frame_bytes 52 | 53 | def render(self): 54 | try: 55 | import numpy as np 56 | except ImportError: 57 | raise ImportError("To use the `render` function you need numpy. Install it via `pip install numpy`. Alternatively, you can use the `render_raw` function to get the bytes from the ARGB RenderTexture.") 58 | 59 | frame_bytes = self.render_raw() 60 | 61 | 62 | frame = np.frombuffer(frame_bytes, dtype=np.uint8).reshape(self.height, self.width, 4) 63 | frame = frame[::-1, :, :3] # flip and remove alpha 64 | return frame 65 | 66 | def close(self): 67 | [self.ue.RenderTexture.ReleaseTemporary(t) for t in self.textures] 68 | 69 | 70 | class QueuedRendererBuggy: 71 | """ 72 | Uses two queues: 73 | Unity GPU (render) --render_queue--> Unity CPU --ipc_queue--> Python 74 | 75 | This is not ideal. The ipc queue should be replaced with a push mechanism once that is possible. 76 | 77 | Reduces to non-queued rendering for render_steps = ipc_steps = 1 78 | """ 79 | def __init__(self, camera, width, height, render_steps=4, ipc_steps=3, fill=True): 80 | self.camera = camera 81 | self.render_steps = render_steps 82 | self.ipc_steps = ipc_steps 83 | self.ue = camera.ue 84 | self._render = self.ue.Uniton.RenderTools.RenderAsync 85 | self._readback_wait = self.ue.Uniton.RenderTools.WaitReadbackRequest 86 | texture_fmt = self.ue.RenderTextureFormat.ARGB32 87 | get_texture = self.ue.RenderTexture.GetTemporary 88 | self.textures = [get_texture(width, height, 0, texture_fmt) for _ in range(render_steps)] 89 | self.render_queue = deque(maxlen=render_steps) 90 | self.ipc_queue = deque(maxlen=ipc_steps) 91 | self.num_req = 0 92 | 93 | if fill: 94 | for i in range(render_steps+ipc_steps): 95 | self.render() 96 | 97 | @property 98 | def delay(self): 99 | return self.render_steps + self.ipc_steps - 2 100 | 101 | def render(self): 102 | self.camera.targetTexture = self.textures[self.num_req % self.render_steps] 103 | readback_request = self._render(self.camera) 104 | self.render_queue.append(readback_request) 105 | self.num_req += 1 106 | 107 | if self.num_req >= self.render_steps and self.render_queue: 108 | self.ipc_queue.append(self._readback_wait(self.render_queue.popleft()).py) 109 | 110 | if self.num_req >= self.render_steps + self.ipc_steps and self.ipc_queue: 111 | return self.ipc_queue.popleft().wait() 112 | else: 113 | return None 114 | 115 | def close(self): 116 | [self.ue.RenderTexture.ReleaseTemporary(t) for t in self.textures] -------------------------------------------------------------------------------- /src/py/uniton/examples.py: -------------------------------------------------------------------------------- 1 | from urllib.request import urlopen 2 | from io import BytesIO 3 | from zipfile import ZipFile 4 | from os.path import join, exists 5 | import sys 6 | from subprocess import call 7 | 8 | # from uniton.util.appdirs import user_cache_dir 9 | from uniton.protocol import UNITON_VERSION 10 | from uniton import UnityEngine 11 | from uniton.util import user_data_dir 12 | 13 | CACHE_DIR = user_data_dir("Uniton") 14 | # TODO: delete older version binaries to save space 15 | 16 | 17 | def download_and_unzip(url, dest): 18 | http_response = urlopen(url) 19 | zipfile = ZipFile(BytesIO(http_response.read())) 20 | zipfile.extractall(path=dest) 21 | 22 | 23 | class ExampleEnv(UnityEngine): 24 | def __init__(self, host=None, port=None): 25 | super().__init__(get_bin(self), host, port) 26 | 27 | 28 | def get_bin(cls): 29 | x = getattr(cls, sys.platform) 30 | if not exists(x.path): 31 | print(f"Downloading {x.url} to {x.path} ...") 32 | download_and_unzip(x.url, x.path) 33 | 34 | # make exectutable 35 | if sys.platform in ('darwin', 'linux'): 36 | call(["chmod", "+x", x.bin]) 37 | # TODO: do we need to do anything on windows? 38 | 39 | return x.bin 40 | 41 | 42 | BIN_VERSION = '0.3.0' 43 | 44 | 45 | class Empty(ExampleEnv): 46 | class darwin: 47 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/empty_mac.zip" 48 | path = join(CACHE_DIR, "empty.app") 49 | bin = join(CACHE_DIR, "empty.app", "Contents", "MacOS", "Empty") 50 | class linux: 51 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/empty_linux.zip" 52 | path = join(CACHE_DIR, "empty") 53 | bin = join(CACHE_DIR, "empty", "Empty.x86_64") 54 | class win32: 55 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/empty_windows.zip" 56 | path = join(CACHE_DIR, "empty") 57 | bin = join(CACHE_DIR, "empty", "Empty.exe") 58 | 59 | 60 | class Kart(ExampleEnv): 61 | class darwin: 62 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/kart_mac.zip" 63 | path = join(CACHE_DIR, "kart.app") 64 | bin = join(CACHE_DIR, "kart.app", "Contents", "MacOS", "Kart") 65 | class linux: 66 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/kart_linux.zip" 67 | path = join(CACHE_DIR, "kart") 68 | bin = join(CACHE_DIR, "kart", "kart.x86_64") 69 | class win32: 70 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/kart_windows.zip" 71 | path = join(CACHE_DIR, "kart") 72 | bin = join(CACHE_DIR, "kart", "Kart.exe") 73 | 74 | 75 | class Temple(ExampleEnv): 76 | class darwin: 77 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/temple_mac.zip" 78 | path = join(CACHE_DIR, "temple.app") 79 | bin = join(CACHE_DIR, "temple.app", "Contents", "MacOS", "Temple") 80 | class linux: 81 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/temple_linux.zip" 82 | path = join(CACHE_DIR, "temple") 83 | bin = join(CACHE_DIR, "temple", "temple.x86_64") 84 | class win32: 85 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/temple_windows.zip" 86 | path = join(CACHE_DIR, "temple") 87 | bin = join(CACHE_DIR, "temple", "Temple.exe") 88 | 89 | 90 | 91 | class FloodedGrounds(ExampleEnv): 92 | class darwin: 93 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/floodedgrounds_mac.zip" 94 | path = join(CACHE_DIR, "floodedgrounds.app") 95 | bin = join(CACHE_DIR, "floodedgrounds.app", "Contents", "MacOS", "Floodedgrounds") 96 | class linux: 97 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/floodedgrounds_linux.zip" 98 | path = join(CACHE_DIR, "floodedgrounds") 99 | bin = join(CACHE_DIR, "floodedgrounds", "floodedgrounds.x86_64") 100 | class win32: 101 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/floodedgrounds_windows.zip" 102 | path = join(CACHE_DIR, "floodedgrounds") 103 | bin = join(CACHE_DIR, "floodedgrounds", "Floodedgrounds.exe") 104 | 105 | 106 | 107 | class WindridgeCity(ExampleEnv): 108 | class darwin: 109 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/windridgecity_mac.zip" 110 | path = join(CACHE_DIR, "windridgecity.app") 111 | bin = join(CACHE_DIR, "windridgecity.app", "Contents", "MacOS", "Windridgecity") 112 | class linux: 113 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/windridgecity_linux.zip" 114 | path = join(CACHE_DIR, "windridgecity") 115 | bin = join(CACHE_DIR, "windridgecity", "windridgecity.x86_64") 116 | class win32: 117 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/windridgecity_windows.zip" 118 | path = join(CACHE_DIR, "windridgecity") 119 | bin = join(CACHE_DIR, "windridgecity", "Windridgecity.exe") 120 | 121 | 122 | class Forest(ExampleEnv): 123 | class darwin: 124 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/forest_mac.zip" 125 | path = join(CACHE_DIR, "forest.app") 126 | bin = join(CACHE_DIR, "forest.app", "Contents", "MacOS", "Forest") 127 | class linux: 128 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/forest_linux.zip" 129 | path = join(CACHE_DIR, "forest") 130 | bin = join(CACHE_DIR, "forest", "forest.x86_64") 131 | class win32: 132 | url = f"https://github.com/uniton-dev/uniton/releases/download/v{BIN_VERSION}/forest_windows.zip" 133 | path = join(CACHE_DIR, "forest") 134 | bin = join(CACHE_DIR, "forest", "Forest.exe") -------------------------------------------------------------------------------- /src/py/uniton/scene.py: -------------------------------------------------------------------------------- 1 | """ 2 | Under construction 3 | 4 | To implement this properly we need know about the C# type of each CsObject, see ../../Readme.md 5 | 6 | Generally the code in here might be convenient but is slow in principle and poorly written 7 | """ 8 | 9 | from .csutil import topy 10 | 11 | 12 | GETATTR_BLACKLIST = ( 13 | "_ipython_canary_method_should_not_exist_", # ipython console uses this 14 | "_repr_mimebundle_", # ipython console uses this 15 | ) 16 | 17 | 18 | class Scene: 19 | """ 20 | """ 21 | def __init__(self, scene): 22 | self._scene = scene 23 | self._wrapped_cs_object = scene 24 | 25 | def __getattr__(self, item): 26 | if item.startswith('_') or item in GETATTR_BLACKLIST: 27 | raise AttributeError() 28 | 29 | gos = self._scene.GetRootGameObjects() 30 | names = _go_names(gos) 31 | try: 32 | idx = names.index(item) 33 | except ValueError: 34 | raise AttributeError(f"GameObject with name '{item}' not a child of {self}") 35 | 36 | return GameObject(gos[idx]) 37 | 38 | def __dir__(self): 39 | gos = self._scene.GetRootGameObjects() 40 | names = _go_names(gos) 41 | names = [n for n in names if n.isidentifier()] 42 | return names + super().__dir__() 43 | 44 | def __repr__(self): 45 | return f"Scene '{self._scene.name.py()}'" 46 | 47 | 48 | def _go_names(gos): 49 | names = topy([go.name for go in gos]) 50 | names = [n.replace(' ', '_') for n in names] 51 | return names 52 | 53 | 54 | class GameObject: 55 | _CS_GAMEOBJECT_MEMBERS = [ 56 | 'SetActive', 57 | 'isStatic', 58 | # 'transform', # manually handled 59 | # 'ToString', 60 | 'GetInstanceID', 61 | 'activeSelf', 62 | 'GetComponent', 63 | 'scene', 64 | 'tag', 65 | 'GetType', 66 | 'activeInHierarchy', 67 | 'active', 68 | 'Equals', 69 | 'CreatePrimitive', 70 | 'GetHashCode', 71 | 'GetComponentsInChildren', 72 | 'GetComponentInParent', 73 | 'AddComponent', 74 | 'FindGameObjectsWithTag', 75 | 'GetComponents', 76 | 'FindGameObjectWithTag', 77 | 'hideFlags', 78 | 'CompareTag', 79 | 'name', 80 | 'SetActiveRecursively', 81 | 'Find', 82 | 'GetComponentsInParent', 83 | 'SendMessageUpwards', 84 | 'layer', 85 | 'GetComponentInChildren', 86 | 'SendMessage', 87 | 'sceneCullingMask', 88 | 'FindWithTag', 89 | # 'gameObject', # what is this? 90 | 'TryGetComponent', 91 | 'BroadcastMessage', 92 | ] 93 | 94 | _CS_TRANSFORM_MEMBERS = [ 95 | # 'Equals', 96 | 'forward', 97 | 'RotateAroundLocal', 98 | 'GetChild', 99 | # 'FindChild', depreciated, use Find 100 | 'right', 101 | 'GetComponentsInChildren', 102 | 'tag', 103 | 'GetInstanceID', 104 | 'GetEnumerator', 105 | # 'gameObject', 106 | 'TransformVector', 107 | 'GetComponents', 108 | 'hideFlags', 109 | # 'GetType', 110 | 'GetComponentInParent', 111 | 'up', 112 | 'SetAsFirstSibling', 113 | 'localToWorldMatrix', 114 | # 'transform', 115 | 'SendMessageUpwards', 116 | 'DetachChildren', 117 | 'position', 118 | 'hierarchyCapacity', 119 | 'parent', 120 | 'GetComponent', 121 | 'InverseTransformDirection', 122 | 'hasChanged', 123 | 'localScale', 124 | 'RotateAround', 125 | 'SendMessage', 126 | 'LookAt', 127 | 'SetParent', 128 | 'Rotate', 129 | # 'ToString', 130 | 'eulerAngles', 131 | 'GetSiblingIndex', 132 | 'Translate', 133 | 'TransformDirection', 134 | 'rotation', 135 | 'CompareTag', 136 | # 'GetHashCode', 137 | 'GetChildCount', 138 | 'InverseTransformPoint', 139 | 'GetComponentsInParent', 140 | 'BroadcastMessage', 141 | 'localEulerAngles', 142 | 'lossyScale', 143 | 'root', 144 | 'hierarchyCount', 145 | 'worldToLocalMatrix', 146 | 'InverseTransformVector', 147 | 'Find', 148 | 'IsChildOf', 149 | 'TransformPoint', 150 | 'TryGetComponent', 151 | 'SetSiblingIndex', 152 | # 'name', 153 | 'localPosition', 154 | 'SetAsLastSibling', 155 | 'GetComponentInChildren', 156 | 'childCount', 157 | 'localRotation', 158 | 'SetPositionAndRotation', 159 | ] 160 | 161 | def __init__(self, go): 162 | self._go = go 163 | self._wrapped_cs_object = go 164 | 165 | # Transform and GameObject should be the same class: https://forum.unity.com/threads/strange-question-why-are-there-separate-transform-and-gameobject-classes.468451/ 166 | # we combine them here 167 | self.transform = self._go.transform 168 | 169 | def __getattr__(self, item): 170 | """ 171 | this is convenient but really slow 172 | """ 173 | if item.startswith('_') or item in GETATTR_BLACKLIST: 174 | raise AttributeError() 175 | 176 | if item in GameObject._CS_GAMEOBJECT_MEMBERS: 177 | return getattr(self._go, item) 178 | 179 | if item in GameObject._CS_TRANSFORM_MEMBERS: 180 | return getattr(self._go.transform, item) 181 | 182 | if item[0].islower(): 183 | item = item[0].upper() + item[1:] 184 | return self.GetComponent(getattr(self._go.ue.UnityEngine, item)) 185 | else: 186 | go = self.transform.Find(item) 187 | return GameObject(go) 188 | 189 | raise AttributeError(f"'{item}' is neither a component, child nor attribute of {self}") 190 | 191 | def _children(self): 192 | trans = self._go.transform 193 | n = trans.GetChildCount().py() 194 | children = [trans.GetChild(i) for i in range(n)] 195 | return [child.gameObject for child in children] 196 | 197 | def _components(self): 198 | # TODO: this is a bad hack put this on the C# side 199 | cos = self._go.GetComponents(self._go.ue.Component) 200 | isnulls = topy([self._go.ue.System.Object.Equals(co, self._go.ue._null) for co in cos]) 201 | cos = [co for co, isnull in zip(cos, isnulls) if not isnull] 202 | return cos 203 | 204 | def __dir__(self): 205 | co_names = topy([co.GetType().Name for co in self._components()]) 206 | co_names = [n[0].lower() + n[1:] for n in co_names] 207 | 208 | go_names = _go_names(self._children()) # filter lowercase ones? 209 | 210 | names = [n for n in (co_names + go_names) if n.isidentifier()] 211 | names += GameObject._CS_GAMEOBJECT_MEMBERS 212 | names += GameObject._CS_TRANSFORM_MEMBERS 213 | names += super().__dir__() 214 | return names 215 | 216 | def __repr__(self): 217 | return f"GameObject '{self._go.name.py()}'" -------------------------------------------------------------------------------- /src/cs/src/core/Render.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEngine.Rendering; 3 | using System; 4 | using Unity.Collections; 5 | 6 | 7 | namespace Uniton { 8 | 9 | 10 | public class RenderQueue{ 11 | AsyncGPUReadbackRequest?[] requests; // for some reason Async... is not nullable so we need the '?' 12 | byte[][] completed_frames; 13 | int step = 0; 14 | int size; 15 | public RenderQueue(int size){ 16 | this.size = size; 17 | this.requests = new AsyncGPUReadbackRequest?[size]; 18 | this.completed_frames = new byte[size][]; 19 | } 20 | 21 | public byte[] Render(Camera cam){ 22 | cam.Render(); 23 | this.requests[this.step % this.size] = AsyncGPUReadback.Request(cam.targetTexture); 24 | var oldest = (this.step+1) % this.size; // the index for the oldest request 25 | 26 | for(int i=0; i < this.size; i++){ 27 | if(requests[i].HasValue){ 28 | var req = requests[i].Value; // .Value comes from Nullable<> 29 | if(i == oldest) 30 | req.WaitForCompletion(); 31 | else 32 | req.Update(); 33 | if (req.hasError){ 34 | throw new Exception("GPU readback error"); 35 | } else if (req.done) { 36 | var res = req.GetData().ToArray(); 37 | this.completed_frames[i] = res; 38 | this.requests[i] = null; 39 | } 40 | } 41 | } 42 | 43 | var frame = this.completed_frames[oldest]; 44 | 45 | this.step += 1; 46 | return frame is null ? new byte[]{} : frame; // because null not serializable atm 47 | } 48 | } 49 | 50 | public class RenderQueue2{ 51 | // not faster than normal RenderQueue 52 | AsyncGPUReadbackRequest?[] requests; // for some reason Async... is not nullable so we need the '?' 53 | byte[][] completed_frames; 54 | int step = 0; 55 | int size; 56 | public RenderQueue2(int size, int framesize){ 57 | this.size = size; 58 | this.requests = new AsyncGPUReadbackRequest?[size]; 59 | this.completed_frames = new byte[size][]; 60 | for(var i=0; i < this.completed_frames.Length; i++) 61 | this.completed_frames[i] = new byte[framesize]; 62 | } 63 | 64 | public byte[] Render(Camera cam){ 65 | cam.Render(); 66 | this.requests[this.step % this.size] = AsyncGPUReadback.Request(cam.targetTexture); 67 | var oldest = (this.step+1) % this.size; // the index for the oldest request 68 | 69 | for(int i=0; i < this.size; i++){ 70 | if(requests[i].HasValue){ 71 | var req = requests[i].Value; // .Value comes from Nullable<> 72 | if(i == oldest) 73 | req.WaitForCompletion(); 74 | else 75 | req.Update(); 76 | if (req.hasError){ 77 | throw new Exception("GPU readback error"); 78 | } else if (req.done) { 79 | // req.GetData().CopyTo(this.completed_frames[i]); 80 | var na = req.GetData(); 81 | 82 | // convert RGBA to RGB 83 | for(var j=0; j < na.Length/4; j++){ 84 | NativeArray.Copy(na, j*4, this.completed_frames[i], j*3, 3); 85 | } 86 | 87 | na.Dispose(); 88 | this.requests[i] = null; 89 | } 90 | } 91 | } 92 | 93 | var frame = this.completed_frames[oldest]; 94 | 95 | this.step += 1; 96 | return frame; 97 | } 98 | } 99 | 100 | public class RenderTools { 101 | // Camera basics 102 | // https://docs.unity3d.com/ScriptReference/Camera.Render.html 103 | 104 | // Camera properties TODO: read! 105 | // https://docs.unity3d.com/Manual/class-Camera.html 106 | 107 | 108 | // potentially switch to async gpu readbacks 109 | // https://docs.unity3d.com/ScriptReference/Rendering.AsyncGPUReadback.Request.html 110 | 111 | public static void RenderToTexture(Camera cam, ref Texture2D tex, Rect rect){ 112 | // https://forum.unity.com/threads/rendering-gl-to-a-texture2d-immediately-in-unity4.158918/ 113 | var rtex = RenderTexture.GetTemporary(tex.width, tex.height, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Default); 114 | 115 | var r = cam.rect; 116 | var rtex_active = RenderTexture.active; 117 | var rtex_target = cam.targetTexture; 118 | 119 | cam.rect = rect; // make camera full screen https://docs.unity3d.com/ScriptReference/Camera-rect.html 120 | RenderTexture.active = rtex; 121 | cam.targetTexture = rtex; 122 | 123 | cam.Render(); 124 | tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); // Read pixels from screen into the saved texture data. 125 | tex.Apply(); // Actually apply all previous SetPixel and SetPixels changes. 126 | 127 | cam.targetTexture = rtex_target; 128 | RenderTexture.active = rtex_active; 129 | cam.rect = r; 130 | 131 | RenderTexture.ReleaseTemporary(rtex); 132 | } 133 | 134 | 135 | // Async Readback requires Vulkan renderer on Linux (OpenGL doesn't work) 136 | public static AsyncGPUReadbackRequest RenderAsync(Camera cam){ 137 | cam.Render(); 138 | return AsyncGPUReadback.Request(cam.targetTexture); 139 | } 140 | 141 | 142 | public static byte[] WaitReadbackRequest(AsyncGPUReadbackRequest req){ 143 | req.WaitForCompletion(); 144 | // Warning: This will fail if this method is called too late. The result is only available for one frame 145 | if (req.hasError){ 146 | // Log.Print("GPU readback error", Log.Level.ERROR); 147 | throw new Exception("GPU readback error"); 148 | } else if (req.done) { 149 | var res = req.GetData().ToArray(); 150 | return res; 151 | } 152 | throw new Exception("Strange GPU readback error"); 153 | } 154 | 155 | public static byte[] PollReadbackRequest(AsyncGPUReadbackRequest req){ 156 | req.Update(); 157 | if (req.hasError){ 158 | Log.Print("GPU readback error", Log.Level.ERROR); 159 | } else if (req.done) { 160 | var res = req.GetData().ToArray(); 161 | return res; 162 | } 163 | // Log.Print("Empty"); 164 | return new byte[]{}; 165 | } 166 | } 167 | 168 | 169 | 170 | 171 | // public class RenderQueue{ 172 | // AsyncGPUReadbackRequest[] q; 173 | // RenderTexture[] t; 174 | // int i = 0; 175 | // Camera c; 176 | 177 | // public RenderQueue(Camera camera, RenderTexture[] textures){ 178 | // c = camera; 179 | // t = textures; 180 | // q = new AsyncGPUReadbackRequest[t.Length]; 181 | // } 182 | 183 | // public Update(){ 184 | // cam.targetTexture = t[i]; 185 | // q[i] = cam.Render(); 186 | 187 | // if(q[(i+q.Length-1)] != null){ 188 | 189 | // } 190 | // } 191 | // } 192 | } -------------------------------------------------------------------------------- /src/cs/src/bootstrap/Bootstrap.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using UnityEngine; 3 | using System.Net; 4 | using System.Net.Sockets; 5 | using System; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Linq; 9 | using System.IO; 10 | using System.Collections; 11 | using System.Collections.Generic; 12 | 13 | 14 | namespace Uniton.Bootstrap{ 15 | public class Loader{ 16 | [RuntimeInitializeOnLoadMethod] 17 | public static void OnLoad(){ 18 | Debug.Log("Uniton is running!"); 19 | 20 | AudioListener.volume = 0; // disable sound 21 | 22 | var pausedString = System.Environment.GetEnvironmentVariable("UNITON_PAUSED"); 23 | var paused = String.IsNullOrEmpty(pausedString) ? false : Convert.ToBoolean(pausedString); 24 | 25 | if(paused){ 26 | Time.timeScale = 0; 27 | } 28 | 29 | // We add ourselves as a game object such that Start() gets called on the main thread 30 | GameObject go = new GameObject("UnitonBootstrap"); 31 | go.AddComponent(); 32 | } 33 | } 34 | 35 | public static class SocketBox{ 36 | public static Socket socket; 37 | public static bool isStale = false; // can be used to signal that the socket has been used up and can be closed 38 | } 39 | 40 | 41 | public class BootstrapBehaviour : MonoBehaviour{ 42 | 43 | IEnumerator loadDllLoop; 44 | 45 | void Awake() { 46 | // Prevent being destroyed when the scene is unloaded https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html 47 | DontDestroyOnLoad(this.gameObject); 48 | 49 | // Coroutine to load Uniton's core.dll 50 | this.loadDllLoop = LoadDllLoop(); 51 | } 52 | 53 | void Update(){ 54 | loadDllLoop.MoveNext(); 55 | } 56 | 57 | void OnDestroy() { 58 | ((IDisposable)this.loadDllLoop).Dispose(); // necessary for any finally blocks to be executed 59 | } 60 | 61 | IEnumerator LoadDllLoop(){ 62 | var hostStringOrNull = System.Environment.GetEnvironmentVariable("UNITON_HOST"); 63 | var hostString = String.IsNullOrEmpty(hostStringOrNull) ? "127.0.0.1" : hostStringOrNull; 64 | 65 | var portStringOrNull = System.Environment.GetEnvironmentVariable("UNITON_PORT"); 66 | var portString = String.IsNullOrEmpty(portStringOrNull) ? "11000" : portStringOrNull; 67 | var port = Int32.Parse(portString); 68 | 69 | 70 | var host = IPAddress.Parse(hostString); 71 | IPEndPoint localEndPoint = new IPEndPoint(host, port); 72 | 73 | while(true){ 74 | 75 | Socket listener_socket = new Socket(host.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 76 | 77 | // Bind sometimes fails even though the socket was properly closed, therefore we set reuseaddress 78 | // https://hea-www.harvard.edu/~fine/Tech/addrinuse.html 79 | listener_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); 80 | 81 | for(var i=0;; i++){ 82 | try{ 83 | listener_socket.Bind(localEndPoint); 84 | break; 85 | } catch (SocketException) { 86 | // if time is less than 10s, wait and retry 87 | if(i<100) 88 | Thread.Sleep(100); 89 | else 90 | throw; 91 | } 92 | } 93 | 94 | listener_socket.Listen(10); // argument is the max number of pending connections 95 | 96 | Debug.Log("Listening for a new connection..."); 97 | // Socket socket = await Task.Run(() => listener_socket.Accept()); 98 | var listen = Task.Run(() => {return listener_socket.Accept();}); // TODO: use blocking socket instead? 99 | while(!listen.IsCompleted) yield return null; 100 | Socket socket = listen.Result; 101 | SocketBox.socket = socket; 102 | SocketBox.isStale = false; 103 | 104 | try{ 105 | socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); 106 | 107 | socket.ReceiveTimeout = 1000; 108 | socket.SendTimeout = 1000; 109 | 110 | 111 | try{ 112 | LoadDll(socket); 113 | } catch (Exception e){ 114 | Debug.Log(e); 115 | } 116 | 117 | while(!SocketBox.isStale) 118 | yield return null; 119 | 120 | } finally { 121 | // Debug.Log("Restart Bootstrap"); 122 | socket.Close(); 123 | // Thread.Sleep(2200); 124 | } 125 | } 126 | 127 | // TODO: the following is no longer true: After loading the core.dll we're done. Dlls can't be unloaded. Therefore, to load a new core.dll the application needs to be restarted. 128 | GameObject.Destroy(this.gameObject); 129 | } 130 | 131 | static Type UnitonLoader(){ 132 | return System.AppDomain.CurrentDomain.GetAssemblies() 133 | .SelectMany(asm => asm.GetTypes()) 134 | .FirstOrDefault(t => t.FullName == "Uniton.Loader"); 135 | } 136 | 137 | private static void LoadDll(Socket socket){ 138 | // magic exchange 139 | var magic_number = BitConverter.ToInt32(Receive(socket, 4), 0); 140 | if(magic_number != Protocol.MAGIC_NUMBER) 141 | throw new Exception("Handshake failed"); 142 | 143 | socket.Send(BitConverter.GetBytes(Protocol.MAGIC_NUMBER)); 144 | // socket.Send(BitConverter.GetBytes(1)); // signals that bootstrapping is necessary 145 | 146 | // receive dll data 147 | var msg_len = BitConverter.ToInt32(Receive(socket, 4), 0); 148 | var data = Receive(socket, msg_len); 149 | 150 | // remove "obfuscation" 151 | data = data.Skip(239).ToArray(); 152 | 153 | // load 154 | if(UnitonLoader() == null){ 155 | var assembly = Assembly.Load(data); 156 | // Debug.Log("LOADED!"); 157 | // assembly.GetTypes().ToList().ForEach(t => Debug.Log(t.FullName)); 158 | // var Loader = assembly.GetTypes().First(t => t.FullName == "Uniton.Loader"); 159 | Debug.Log("Connected"); 160 | } else { 161 | // Debug.Log("Skipping bootstrap since Uniton has already been loaded. If you experience unexpected behaviour, try restarting the process."); 162 | Debug.Log("Reconnected"); 163 | } 164 | 165 | var Loader = UnitonLoader(); 166 | 167 | Loader.GetMethod("OnLoad").Invoke(Loader, new object[] {}); 168 | 169 | // Debug.Log("Send confirm"); 170 | // socket.Send(BitConverter.GetBytes(0)); // confirmation 171 | } 172 | 173 | private static byte[] Receive(Socket s, int n){ 174 | int i = 0; 175 | int k; 176 | var a = new byte[n]; 177 | do { 178 | k = s.Receive(a, i, a.Length-i, SocketFlags.None); 179 | i += k; 180 | } while (i < n && k > 0); 181 | 182 | if(k == 0) // 0 bytes received indicates socket failure 183 | throw new Exception("Something went wrong..."); 184 | 185 | return a; 186 | } 187 | } 188 | 189 | } 190 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Uniton – Instrumentalize Unity with Python 2 | 3 | Uniton lets you control the Unity game engine from Python. It aims to instrumentalize Unity and make it more useful in non-game applications. 4 | 5 | 6 | [comment]: <> (Uniton is a framework to control the Unity game engine from Python. Here is a three-minute intro video:) 7 | 8 | [comment]: <> ([![](./res/yt_thumbnail.png)](https://www.youtube.com/watch?v=FIpt2yv623k)) 9 | 10 |

11 | 12 | 13 |

14 | 15 | 16 | ### Quick Start 17 | ```bash 18 | pip install uniton 19 | ``` 20 | ```python 21 | import uniton 22 | # launch an example forest scene 23 | ue = uniton.examples.Forest() 24 | ``` 25 | For more pre-built examples check [uniton/examples](https://github.com/uniton-dev/uniton/tree/main/examples)! 26 | 27 | ![Examples](res/c.png) 28 | 29 | 30 | 31 | 32 | ### Installation 33 | Uniton requires Python 3.7+. We recommend the Anaconda/Miniconda distribution but it will work with others just as well. Install the Uniton Python package via `pip install uniton`. 34 | 35 | To use Uniton with your own Unity project, simply drop the – [__uniton.dll__](https://github.com/uniton-dev/uniton/releases/latest/download/uniton.dll) – into your project's `Asset` folder. 36 | 37 | ### Usage 38 | Uniton also comes with pre-built example environments that automatically download when they are first used. Below are two examples but there are more. Check out [uniton/examples](https://github.com/uniton-dev/uniton/tree/main/examples)! 39 | 40 | ```python 41 | # The kart game from the demo video 42 | ue = uniton.examples.KartGame() 43 | 44 | # A higher fidelity scene 45 | ue = uniton.examples.Temple() 46 | ``` 47 | 48 | 49 | #### Uniton in your own Unity project 50 | Any Unity project can become a Uniton project simply by dropping the `uniton.dll` somewhere into the project's asset folder. 51 | Connect to your a running Unity app 52 | To launch and connect to a Uniton app do 53 | ```python 54 | import uniton 55 | ue = uniton.UnityEngine(path='path/to/binary') 56 | ``` 57 | 58 | ```python 59 | ue = uniton.UnityEngine() 60 | 61 | # Alternatively, to connect to a remote Uniton app do, e.g. 62 | ue = uniton.UnityEngine(host='192.168.1.101', port=10001) 63 | 64 | # The remote Uniton app can been launched via, e.g. 'UNITONHOST="0.0.0.0" UNITONPORT=10001 path/to/binary' 65 | # Warning: UNITONHOST="0.0.0.0" should only ever be used in a private and secure network! 66 | # It theoretically allows everyone on the network to control the host. 67 | ``` 68 | 69 | 70 | #### Control time via 71 | ```python 72 | ue.pause() # this can block the whole window when used in the Unity editor 73 | ue.step() # advances game time by ue.time.delta and renders one frame 74 | # more steps, etc.. 75 | ue.resume() # resume real time operation 76 | ``` 77 | 78 | #### Access game objects via 79 | ```python 80 | ue.scene.. 81 | 82 | # Access components within game objects using lower camelcase 83 | ue.scene.. # e.g. rigidbody, boxCollider, camera, light 84 | 85 | # Transform attributes are directly available on the game object, e.g. 86 | ue.scene..position == ue.scene..transform.position 87 | ``` 88 | 89 | #### Access any C# class via 90 | ```python 91 | ue.. 92 | 93 | # The 'UnityEngine' namespace can be omitted, i.e. 94 | ue. == ue.UnityEngine. 95 | 96 | # Instantiate any C# class by calling it, as is usual in Python, e.g. 97 | v = ue.Vector3(0, 1, 0) 98 | ``` 99 | 100 | #### Receiving values from C#/Unity 101 | ```python 102 | v.x # returns a placeholder object for the 'x' property of a C# Vector3 object 103 | v.x.py # immediately returns a promise object and triggers the value of 'v.x' to be sent to Python asynchronously 104 | v.x.py() # blocks until the value has been received and returns the value 105 | 106 | # Currently, only a few types can be received directly, e.g. int, float, str, byte arrays. 107 | ``` 108 | 109 | #### Rendering and receiving frames 110 | ```python 111 | from uniton import QueuedRenderer 112 | 113 | renderer = QueuedRenderer(ue.scene.Main_Camera.Camera, width=512, height=256, render_steps=4, ipc_steps=3) 114 | frame = renderer.render() # will return a Numpy array of shape (256, 512, 3) and dtype 'uint8' 115 | ``` 116 | 117 | Internally, the frame is produced as follows. 118 | ``` 119 | Unity GPU (render) --render_queue--> Unity CPU --ipc_queue--> Python 120 | ``` 121 | 122 | Therefore, `frame` actually shows the state of the game a number of `renderer.render()`-calls earlier. To be precise, that number is 123 | 124 | ```python 125 | renderer.delay() == render_steps + ipc_steps - 2 126 | ``` 127 | 128 | Consequently, the following will block and be slow but show the current state of the game. 129 | ```python 130 | renderer = QueuedRenderer(ue.scene.Main_Camera.Camera, width=512, height=256, render_steps=1, ipc_steps=1) 131 | frame = render.render() 132 | ``` 133 | 134 | ### How does Uniton work? 135 | Uniton creates placeholder objects for C# objects and functions. When a placeholder C# function is called from Python it will immediately return a new placeholder for the return value. This new placeholder object can be immediately worked with. Should the C# function throw an exception such that the actual return value never materializes, then Uniton will throw a delayed exception in Python. Attribute and method lookups on placeholder objects work the same way, as these lookups are also just functions calls internally. 136 | 137 | 138 | ### Limitations 139 | - Generic C# classes and functions can't be used (please open an issue if this is important to you) 140 | - Python functions can't be registered as C# callbacks (please open an issue if this is important to you) 141 | - There is currently no documentation beyond this readme 142 | 143 | 144 | ### Troubleshooting 145 | In case that you aren't using Anaconda you might have to replace the `python` command with `python3` and the `pip` command with `python3 -m pip`. To maximize compatibilty you can install Uniton via 146 | ```bash 147 | python3 -m pip install uniton --upgrade --user 148 | ``` 149 | 150 | ### Uninstall 151 | To remove Uniton including all example binaries that have been loaded run 152 | ```bash 153 | python -m uniton delete_data 154 | pip uninstall uniton 155 | ``` 156 | 157 | 158 | ### Features 159 | [comment]: <> (Edit the table below via https://www.tablesgenerator.com/markdown_tables) 160 | 161 | | | Uniton | 162 | |--------------------------------------------------------------------------------------|:------:| 163 | | Interact live with all C# objects, functions, classes | 🔥 | 164 | | Autocomplete for all C# objects 1 | 🔥 | 165 | | Fast, asynchronous execution | 🔥 | 166 | | Precise control over game time | 🔥 | 167 | | Faster-than-real-time rendering and simulation | 🔥 | 168 | | No dependencies beyond Python and Unity | 🔥 | 169 | | Cool [example environments](https://github.com/uniton-dev/uniton/tree/main/examples) | 🔥 | 170 | | Import custom C# code at runtime | 🧪 | 171 | | Import models at runtime 2 | 🧪 | 172 | 173 | 🔥 = available, 🧪 = work in progress 174 | 175 | 1 Autocomplete is available only during live-coding (e.g. python repl, ipython, jupyter notebooks).
176 | 2 Supports `.obj` and `.urdf` models. 177 | 178 | [comment]: <> (I'm also considering making an editor-focussed version of Uniton to facilitate world creation and asset management.) 179 | 180 | 181 | 182 | ### License 183 | AGPL-3.0 - See LICENSE file for details. 184 | 185 | -------------------------------------------------------------------------------- /src/py/uniton/unityproc.py: -------------------------------------------------------------------------------- 1 | import atexit 2 | import socket 3 | import struct 4 | from queue import Queue 5 | from threading import Thread 6 | from typing import Sequence 7 | from functools import lru_cache 8 | import os 9 | import subprocess 10 | from time import time, sleep 11 | from .csobject import CsObject 12 | from .protocol import rpc, MAGIC_NUMBER, UNITON_VERSION 13 | from .csutil import BrokenPromiseException 14 | 15 | 16 | TLIST = ( 17 | (int, rpc.INT32, struct.Struct("i")), 18 | (float, rpc.FLOAT32, struct.Struct("f")), 19 | (bool, rpc.BOOL, struct.Struct("?")), 20 | ) 21 | TMAP = {x[0]: x[1:] for x in TLIST} 22 | RMAP = {x[1]: x[2] for x in TLIST} 23 | TCODE = struct.Struct("i") 24 | SHOBJ = struct.Struct("i") # should technically be I (unsigned int) 25 | 26 | 27 | def recvall(sock, n): 28 | data = b'' 29 | while len(data) < n: 30 | try: 31 | packet = sock.recv(n - len(data)) 32 | except OSError: 33 | packet = None 34 | 35 | if not packet: 36 | return None 37 | data += packet 38 | return data 39 | 40 | 41 | 42 | def get_free_port(): 43 | """Not 100% guaranteed to be free but good enough""" 44 | s = socket.socket() 45 | s.bind(('', 0)) 46 | port = s.getsockname()[1] 47 | s.close() 48 | return port 49 | 50 | 51 | class UnityProc: 52 | """ 53 | Representing a running Unity program 54 | Doubles as root namespace of that program, i.e. cs.System will return the 'System' namespace 55 | """ 56 | 57 | _return_thread = None 58 | _cmd_queue = None 59 | _proc = None 60 | _sock = None 61 | 62 | def __init__(self, path=None, host=None, port=None, paused=False): 63 | atexit.register(self.close) 64 | 65 | if path is not None: 66 | host = '127.0.0.1' 67 | port = get_free_port() if port is None else port 68 | env = os.environ.copy() 69 | 70 | env["UNITON_PORT"] = str(port) 71 | env["UNITON_PAUSED"] = str(paused) 72 | # TODO: allow to set cmd line args 73 | # TODO: figure out how to set -screen-height -screen-width robustly 74 | self._proc = subprocess.Popen([path], env=env) 75 | # self._proc = subprocess.Popen([path, '-batchmode']) # while this still renders on Mac OS it's much slower 76 | 77 | else: 78 | host = '127.0.0.1' if host is None else host 79 | port = 11000 if port is None else port 80 | 81 | self._id_c = 2 # the first two elements are manually set 82 | 83 | # connect 84 | timeout = time() + 10 85 | 86 | while True: 87 | try: 88 | self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 89 | self._sock.connect((host, port)) 90 | break 91 | except ConnectionRefusedError: 92 | if not self._proc: 93 | raise 94 | elif self._proc.poll() is not None: 95 | raise RuntimeError(f"Process {path} died before Uniton could connect!") 96 | elif time() > timeout: 97 | raise ConnectionRefusedError(f"Is {path} missing Uniton?") 98 | else: 99 | sleep(0.1) # wait, then repeat 100 | 101 | # self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0)) 102 | 103 | # bootstrap 104 | 105 | # magic exchange 106 | self._sock.sendall(struct.pack("i", MAGIC_NUMBER)) 107 | magic_number, = struct.unpack('i', recvall(self._sock, 4)) 108 | if magic_number != MAGIC_NUMBER: 109 | raise ConnectionError("Could not connect.") 110 | # bootstrap, = struct.unpack('i', recvall(self._sock, 4)) 111 | 112 | # if bootstrap: 113 | from importlib import resources 114 | dll = resources.read_binary("uniton", "core.dll") 115 | 116 | self._sock.sendall(struct.pack("i", len(dll))) 117 | self._sock.sendall(dll) 118 | # zero, = struct.unpack('i', recvall(self._sock, 4)) # wait for a 0 as confirmation (so we don't move on to quickly) 119 | # assert zero == 0 120 | 121 | 122 | # sleep(1) # give the server some time to close and reopen the port 123 | # self._sock.shutdown(socket.SHUT_WR) 124 | # self._sock.recv(0) 125 | 126 | # self._sock.close() 127 | # print("closed, waiting..") 128 | 129 | # sleep(4) # We need to wait, otherwise we'll get "Adress already in use" on the server. I've tried to close the socket quicker but nothing worked. 130 | # 131 | # 132 | # # reconnect now to core.dll 133 | # self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 134 | # self._sock.connect((host, port)) 135 | 136 | # self._sock.sendall(struct.pack("i", MAGIC_NUMBER)) 137 | # magic_number, = struct.unpack('i', recvall(self._sock, 4)) 138 | # if magic_number != MAGIC_NUMBER: 139 | # raise ConnectionError("Could not connect.") 140 | # bootstrap, = struct.unpack('i', recvall(self._sock, 4)) 141 | # assert not bootstrap, "We should have already bootstrapped!" 142 | 143 | # 144 | # else: 145 | # print("Warning: This Uniton process has been connected to before. This could lead to strange behaviour.") 146 | 147 | 148 | 149 | # version compatibility check 150 | remote_version_tuple = struct.unpack('iii', recvall(self._sock, 4 * 3)) 151 | self._remote_version = ".".join(str(x) for x in remote_version_tuple) 152 | local_version_macro = ".".join(UNITON_VERSION.split(".")[:2]) 153 | remote_version_macro = ".".join(self._remote_version.split(".")[:2]) 154 | if remote_version_macro != local_version_macro: 155 | # try: 156 | # import urllib.request, json 157 | # with urllib.request.urlopen("https://pypi.org/pypi/uniton/json") as url: 158 | # data = json.loads(url.read().decode()) 159 | # all_versions = data["info"]["releases"].keys() 160 | # best_compatible_local_version = sorted(v for v in all_versions if v.startswith(".".join(remote_version_tuple[:2])))[-1] 161 | # finally: 162 | raise ConnectionError(f'Remote Uniton version {self._remote_version} is not compatible with local version {UNITON_VERSION}. Change remote version to {local_version_macro}.* or local version to {remote_version_macro}.* via\n\npip install "uniton=={remote_version_macro}.*" --force-reinstall\n') 163 | 164 | 165 | # sponsorship check 166 | sponsor_error_len, = struct.unpack('i', recvall(self._sock, 4)) 167 | if sponsor_error_len: 168 | msg = recvall(self._sock, sponsor_error_len).decode("utf-8", "strict") 169 | raise PermissionError(msg) 170 | 171 | 172 | # init object management 173 | self._garbage_objects = [] 174 | 175 | # bootstrap 176 | self._cs_type = CsObject(self, id=0) # C# System.Type 177 | self._backend = CsObject(self, id=1) 178 | 179 | from .namespace import Namespace 180 | self._ns = Namespace(self) 181 | 182 | if paused: 183 | self.pause() # TODO: this is implemented in unityengine.py, should merge those two classes? 184 | 185 | # from .unity_old import UnityEngine 186 | # self._ns.ue = self._ns.UnityEngine = UnityEngine(self) 187 | 188 | # self.Uniton.Log.level = 2 # only print INFO and ERROR 189 | 190 | @property 191 | @lru_cache(maxsize=None) 192 | def _null(self): 193 | # TODO: probably better provide this from the c sharp side 194 | return CsObject(self, id=self.cmd(rpc.NOOP, b'')) 195 | 196 | def waitall(self): 197 | # TODO: this is obviously hacky 198 | str(self._backend) 199 | 200 | @property 201 | def _pid(self): 202 | return self.System.Diagnostics.Process.GetCurrentProcess().Id 203 | 204 | def __getattr__(self, item): 205 | return getattr(self._ns, item) 206 | # return self._ns.__getattr__(item) # Warning: this line breaks the namespace caching! 207 | 208 | def __dir__(self): 209 | return list(super().__dir__()) + dir(self._ns) 210 | 211 | def __del__(self): 212 | self.close() 213 | 214 | def close(self): 215 | atexit.unregister(self.close) 216 | if self._sock is not None: 217 | self._sock.close() 218 | 219 | if self._proc is not None: 220 | self._proc.kill() 221 | 222 | def delete_object(self, x): 223 | self._garbage_objects.append(x) 224 | # print("del", x.id) 225 | 226 | # if len(self.garbage_objects) > 10000000: # Don't delete because we recycle 227 | # # print("garbage collect") 228 | # ids = tuple(obj.id for obj in self.garbage_objects) # also copy is necessary to avoid recursion 229 | # self.garbage_objects.clear() 230 | # self._del_objects(ids) # this will create new garbage 231 | 232 | def make_id(self): 233 | # print(tuple(x.id for x in self.garbage_objects)) 234 | if self._garbage_objects: 235 | x = self._garbage_objects.pop() 236 | # print("recycle", x.id) 237 | else: 238 | x = self._id_c 239 | self._id_c += 1 # TODO: check for overflow 240 | # print('mk', x.id) 241 | return x 242 | 243 | def run_cmds(self): 244 | # TODO: make separate class for this 245 | try: 246 | while True: 247 | # get length 248 | d = recvall(self._sock, 4) 249 | if d is None: break 250 | n, = struct.unpack('i', d) 251 | 252 | # get data 253 | d = recvall(self._sock, n) 254 | if d is None: break # TODO: shouldn't this be an error? 255 | exc, = struct.unpack_from('i', d, 0) 256 | if exc: 257 | # raise RemoteException(self.deserialize(d[4:])) 258 | print("C# " + self.deserialize(d[4:])) 259 | print("------------------\n") 260 | break 261 | else: 262 | # self.response_queue.put(self.deserialize(d[4:])) 263 | p = self.promise_queue.get_nowait() 264 | assert p is not None, 'Received unexpected data from C#' 265 | p.resolve(self.deserialize(d[4:])) 266 | finally: 267 | while not self.promise_queue.empty(): 268 | p = self.promise_queue.get_nowait() 269 | p.resolve(BrokenPromiseException("The command stream was closed before this promise could be resolved.")) 270 | 271 | # print("Shutting down return thread") 272 | 273 | def cmd(self, method, data, out=None): 274 | if self._return_thread is None or not self._return_thread.is_alive(): 275 | # if self.rit is None: 276 | # self.cmd_queue = Queue(1000) 277 | self.promise_queue = Queue() 278 | self.response_queue = Queue(1) 279 | self._return_thread = Thread(target=self.run_cmds, daemon=True) # TODO: remove daemon and shut down properly 280 | self._return_thread.start() 281 | 282 | # self.rit = self.cmd_it() 283 | CsObject(self, self.cmd(rpc.OPEN_CMD_STREAM, b'')) # cmd stream open 284 | 285 | rid = self.make_id() if out is None else 0 # if out is not None then remote object is sent and then discarded 286 | 287 | # self.cmd_queue.put(rpc.Cmd(method=method, rid=rid, args=self.deflate(args))) # block if full 288 | data = struct.pack('ii', method, rid) + data 289 | # self.cmd_queue.put(rpc.Cmd(method=method, rid=rid, data=data)) # block if full 290 | 291 | data = struct.pack('i', len(data)) + data # send length information 292 | 293 | if out is None: 294 | out = rid 295 | else: 296 | # print("blocking!") 297 | # return self.response_queue.get() # block 298 | # self.garbage_objects.append(rid) # prevent memory leak! 299 | 300 | self.promise_queue.put(out) 301 | 302 | self._sock.sendall(data) 303 | 304 | return out 305 | 306 | import sys 307 | assert sys.byteorder == "little", "We only support little endian systems" 308 | 309 | def deserialize(self, x): 310 | # vi = x.WhichOneof("Value") 311 | # if vi == "list": 312 | # return [self.deserialize(e) for e in x.list.items] 313 | 314 | t, = TCODE.unpack_from(x) 315 | offset = TCODE.size 316 | if t in RMAP: 317 | r, = RMAP[t].unpack_from(x, offset) 318 | return r 319 | elif t == rpc.BYTES: 320 | return x[offset:] 321 | elif t == rpc.STRING: 322 | return x[offset:].decode("utf-8", "strict") 323 | else: 324 | raise AttributeError(f"Can't decode type {t}") 325 | 326 | # if vi == "obj": 327 | # if x.obj.id not in self.objs:" 328 | # cls = None if x.obj.tid == 0 else CsObject() 329 | # r = CsObject(id=x.obj.id, _con=self) 330 | # self.objs[x.obj.id] = weakref.ref(r) 331 | # return r 332 | # else: 333 | # return self.objs[x.obj.id]() 334 | 335 | # return getattr(x, vi) 336 | 337 | def serialize_objs(self, *args): # TODO: rename to serialize_obj_ids 338 | # important: we need to create all RObjects and only afterwards query the ids 339 | # if we immediatly get the ids and then forget about each RObject, they will be garbage collected and ids might be reused 340 | obj = tuple(self.tocs(e) for e in 341 | args) # this can't be a generator because of the above reason 342 | ids = (e.id for e in obj) 343 | data = b"".join(SHOBJ.pack(id) for id in ids) 344 | return data 345 | 346 | def tocs(self, x): 347 | """Send Python object to C#""" 348 | # Serialization / Deserialization from bytes 349 | # https://docs.python.org/3.6/library/struct.html 350 | 351 | num_type = TMAP.get(type(x), None) 352 | if num_type is not None: 353 | rpc_fn, st = num_type 354 | # return rpc.Value(int32=x) 355 | id = self.cmd(rpc_fn, st.pack(x)) 356 | elif isinstance(x, str): 357 | # return rpc.Value(str=x) 358 | id = self.cmd(rpc.STRING, x.encode()) # utf8 359 | # elif isinstance(x, bytes): 360 | # return rpc.Value(bytes=x) 361 | # elif isinstance(x, bool): 362 | # return rpc.Value(bool=x) 363 | # elif x is None: 364 | # return rpc.Value(null=rpc.Null()) 365 | elif isinstance(x, CsObject): 366 | return x 367 | 368 | elif hasattr(x, '_wrapped_cs_object'): 369 | return x._wrapped_cs_object 370 | 371 | elif isinstance(x, bytes): 372 | id = self.cmd(rpc.BYTES, x) 373 | 374 | elif isinstance(x, Sequence): 375 | print("sequence") 376 | # return rpc.Value(list=rpc.List(items=(self.deflate(e) for e in x))) 377 | id = self.cmd(rpc.TUPLE, self.serialize_objs(*x)) 378 | else: 379 | raise AttributeError(f"Can't serialize {type(x)}") 380 | 381 | return CsObject(self, id) 382 | -------------------------------------------------------------------------------- /src/cs/src/editor/Buildinfo.cs: -------------------------------------------------------------------------------- 1 | // #if UNITY_EDITOR 2 | using UnityEditor; 3 | using UnityEditor.Build; 4 | using UnityEditor.Build.Reporting; 5 | using UnityEditor.Compilation; 6 | using UnityEditor.Callbacks; 7 | 8 | using UnityEngine; 9 | 10 | using System.IO; 11 | using System.Linq; 12 | using System; 13 | using System.Net.Http; 14 | using System.Net.Http.Headers; 15 | using System.Text; 16 | using System.Collections.Generic; 17 | using System.Security.Cryptography; 18 | 19 | 20 | 21 | namespace Uniton.Editor{ 22 | 23 | [InitializeOnLoad] 24 | public class Startup { 25 | static Startup(){ 26 | var dllpath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath; 27 | 28 | var dllDir = Path.GetDirectoryName(dllpath); 29 | if((new DirectoryInfo(dllDir)).Name != "Editor"){ 30 | // Editor directories have a special purpose in Unity 31 | // .cs and .dll in there will only be executed in the Editor 32 | // this is important for us since we have some editor-only code 33 | 34 | var unitonDir = Path.Combine(dllDir, "Uniton"); 35 | Directory.CreateDirectory(unitonDir); // fine if exists 36 | 37 | var editorDir = Path.Combine(unitonDir, "Editor"); 38 | Directory.CreateDirectory(editorDir); // fine if exists 39 | 40 | File.Move(dllpath, Path.Combine(editorDir, "editor.dll")); 41 | File.Delete(dllpath + ".meta"); 42 | 43 | var fileStream = File.Create(Path.Combine(unitonDir, "bootstrap.dll")); 44 | var dllstream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("bootstrap.dll"); 45 | dllstream.Seek(0, SeekOrigin.Begin); 46 | dllstream.CopyTo(fileStream); 47 | fileStream.Close(); 48 | 49 | AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); 50 | } 51 | } 52 | } 53 | 54 | [System.Serializable] 55 | public class ProductInfo { 56 | public string title; 57 | } 58 | 59 | [System.Serializable] 60 | public class RootObject { 61 | public ProductInfo product_info; 62 | } 63 | 64 | public static class Util { 65 | public static string EnvVar(string name, string alt=null){ 66 | var v = System.Environment.GetEnvironmentVariable(name); 67 | if(String.IsNullOrEmpty(v)){ 68 | if(alt != null) 69 | return alt; 70 | else 71 | throw new Exception($"Environment variable '{name}' does not exist."); 72 | } else { 73 | return v; 74 | } 75 | } 76 | 77 | public static Dictionary parseQuery(string q){ 78 | return q 79 | .Split("&".ToCharArray()) 80 | .Select(x=> x.Split("=".ToCharArray())) 81 | .ToDictionary(x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x[1])); 82 | } 83 | 84 | // public static string ubi = Path.Combine("Assets", "Resources", "ubi.cs"); // uniton build info file 85 | 86 | public static string UserDataDir(){ 87 | if(Application.platform == RuntimePlatform.WindowsEditor){ 88 | return Util.EnvVar("CSIDL_APPDATA"); 89 | } else if(Application.platform == RuntimePlatform.OSXEditor){ 90 | var home = Util.EnvVar("HOME"); 91 | return $"{home}/Library/Application Support/"; 92 | } else if(Application.platform == RuntimePlatform.LinuxEditor) { 93 | var home = Util.EnvVar("HOME"); 94 | return Util.EnvVar("XDG_DATA_HOME", $"{home}/.local/share"); 95 | } else { 96 | throw new Exception("Unsupported platform"); 97 | } 98 | } 99 | 100 | 101 | 102 | // TODO: Unused 103 | public static void SymmetricEncrypt(){ 104 | byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; 105 | 106 | try 107 | { 108 | //Create a file stream 109 | FileStream myStream = new FileStream("TestData.txt", FileMode.OpenOrCreate); 110 | 111 | //Create a new instance of the default Aes implementation class 112 | // and configure encryption key. 113 | Aes aes = Aes.Create(); 114 | aes.Key = key; 115 | 116 | //Stores IV at the beginning of the file. 117 | //This information will be used for decryption. 118 | byte[] iv = aes.IV; 119 | myStream.Write(iv, 0, iv.Length); 120 | 121 | //Create a CryptoStream, pass it the FileStream, and encrypt 122 | //it with the Aes class. 123 | CryptoStream cryptStream = new CryptoStream( 124 | myStream, 125 | aes.CreateEncryptor(), 126 | CryptoStreamMode.Write); 127 | 128 | //Create a StreamWriter for easy writing to the 129 | //file stream. 130 | StreamWriter sWriter = new StreamWriter(cryptStream); 131 | 132 | //Write to the stream. 133 | sWriter.WriteLine("Hello World!"); 134 | 135 | //Inform the user that the message was written 136 | //to the stream. 137 | Console.WriteLine("The file was encrypted."); 138 | } 139 | catch 140 | { 141 | //Inform the user that an exception was raised. 142 | Console.WriteLine("The encryption failed."); 143 | throw; 144 | } 145 | } 146 | 147 | } 148 | 149 | 150 | [Serializable] 151 | public class SponsorQuery { 152 | public string query; 153 | } 154 | 155 | // necessary for json parse :D 156 | [Serializable] 157 | public class SponsorResult { 158 | [Serializable] 159 | public class Data{ 160 | [Serializable] 161 | public class User { 162 | [Serializable] 163 | public class Sponsorship { 164 | [Serializable] 165 | public class Tier { 166 | public int monthlyPriceInCents; 167 | } 168 | public Tier tier; 169 | } 170 | public Sponsorship sponsorshipForViewerAsSponsor; 171 | } 172 | public User user; 173 | 174 | [Serializable] 175 | public class Viewer { 176 | public string name; 177 | public string login; 178 | } 179 | public Viewer viewer; 180 | } 181 | public Data data; 182 | } 183 | 184 | public static class Util2 { 185 | public static SponsorResult.Data Sponsor(string token){ 186 | var c = new HttpClient(); 187 | c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 188 | c.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Uniton", "0.3.0")); // TODO: use version variable 189 | var query = @" 190 | { 191 | user(login: ""uniton-dev""){ 192 | sponsorshipForViewerAsSponsor{ 193 | tier { 194 | monthlyPriceInCents 195 | } 196 | } 197 | } 198 | viewer { 199 | name 200 | login 201 | } 202 | }"; 203 | 204 | // var jq = $"{{\"query\": \"{query}\"}}"; 205 | // Debug.Log(jq); 206 | var res = c.PostAsync("https://api.github.com/graphql", new StringContent(JsonUtility.ToJson(new SponsorQuery {query=query}), Encoding.UTF8, "application/json")) 207 | .Result.Content.ReadAsStringAsync().Result; 208 | 209 | // Debug.Log(res); 210 | 211 | var sr = JsonUtility.FromJson(res); 212 | // Debug.Log($"{sr.data.user.sponsorshipForViewerAsSponsor.tier.monthlyPriceInCents}"); 213 | return sr.data; 214 | } 215 | } 216 | 217 | public class GUI{ 218 | private static readonly HttpClient client = new HttpClient(); 219 | 220 | // https://docs.unity3d.com/ScriptReference/MenuItem.html 221 | [MenuItem("Uniton/Sign In with Github")] 222 | static void SignInWizard(){ 223 | try { 224 | string json = "{\"client_id\": \"8b9263c9919eea0291f4\", \"scope\": \"read:user\"}"; 225 | // client.DefaultRequestHeaders.Accept.Add( 226 | // new MediaTypeWithQualityHeaderValue("application/json")); 227 | var content = new StringContent(json, Encoding.UTF8, "application/json"); 228 | var response = client.PostAsync("https://github.com/login/device/code", content).Result; 229 | var c = response.Content.ReadAsStringAsync().Result; 230 | var j = Util.parseQuery(c); 231 | var uri = j["verification_uri"]; 232 | var code = j["user_code"]; 233 | var dcode = j["device_code"]; 234 | // Debug.Log(j["device_code"]); 235 | if(EditorUtility.DisplayDialog("Sign in with Github", $"Please copy the copy the code: \n {code} \n and go to {uri}", "Open Link", "Cancel")) 236 | Application.OpenURL(uri); 237 | else 238 | return; 239 | 240 | if(!EditorUtility.DisplayDialog("Sign in with Github", $"Please copy the copy the code: \n {code} \n and go to {uri}", "Continue", "Cancel")) 241 | return; 242 | 243 | var response2 = client.PostAsync( 244 | "https://github.com/login/oauth/access_token", 245 | new StringContent($"{{\"client_id\": \"8b9263c9919eea0291f4\", \"device_code\": \"{dcode}\", \"grant_type\": \"urn:ietf:params:oauth:grant-type:device_code\"}}", Encoding.UTF8, "application/json") 246 | ).Result; 247 | var res = Util.parseQuery(response2.Content.ReadAsStringAsync().Result); 248 | // Debug.Log(res["access_token"]); 249 | 250 | var dd = Path.Combine(Util.UserDataDir(), "Uniton"); 251 | Directory.CreateDirectory(dd); // fine if exists 252 | 253 | var token = res["access_token"]; 254 | File.WriteAllText(Path.Combine(dd, "token"), token); 255 | 256 | var d = Util2.Sponsor(token); 257 | if(d.user.sponsorshipForViewerAsSponsor == null){ 258 | var go = EditorUtility.DisplayDialog("Not a sponsor", $"Hey {d.viewer.name}, you don't seem to be a Uniton sponsor. You can go to https://github.com/sponsors/uniton-dev to become one.", "Let's Go!", "Cancel"); 259 | if(go) 260 | Application.OpenURL("https://github.com/sponsors/uniton-dev"); 261 | } else { 262 | EditorUtility.DisplayDialog("Sign-in successful!", $"Hey {d.viewer.name},\nLet's build something great with Uniton!", "Cool!", "Ok"); 263 | } 264 | 265 | } catch (Exception){ 266 | if(EditorUtility.DisplayDialog("Sign-in failed", $"You can report this at https://github.com/uniton-dev/uniton/issues", "Report!", "Cancel")) 267 | Application.OpenURL("https://github.com/uniton-dev/uniton/issues"); 268 | } 269 | } 270 | 271 | [MenuItem("Uniton/Delete Data")] 272 | static void DeleteDataWizard(){ 273 | var dd = Path.Combine(Util.UserDataDir(), "Uniton"); 274 | Directory.Delete(dd, true); 275 | } 276 | } 277 | 278 | 279 | class OnPreprocessBuildClass : IPreprocessBuildWithReport{ 280 | 281 | public int callbackOrder { get { return 0; } } 282 | 283 | public void OnPreprocessBuild(BuildReport report){ 284 | 285 | int contrib = 0; 286 | string ghLogin = null; 287 | string tokenHash = null; 288 | 289 | var udd = Util.UserDataDir(); 290 | var tokenPath = Path.Combine(udd, "Uniton", "token"); 291 | if(File.Exists(tokenPath)){ 292 | try{ 293 | var token = File.ReadAllText(tokenPath); 294 | 295 | // TODO: lift to protocol 296 | tokenHash = SHA256.Create() 297 | .ComputeHash(Encoding.UTF8.GetBytes(token)) 298 | .Select(b => b.ToString("x2")) // convert bytes to strings 299 | .Aggregate(string.Concat); // concatenate everything 300 | 301 | var d = Util2.Sponsor(token); 302 | ghLogin = d.viewer.login; 303 | contrib = d.user.sponsorshipForViewerAsSponsor.tier.monthlyPriceInCents; 304 | 305 | if(ghLogin == "rmst"){ 306 | contrib = 100000000; 307 | } 308 | 309 | } catch (Exception e) { 310 | Debug.Log($"Could not verify Uniton sponsorship. Check: \n\n {e}"); 311 | } 312 | } 313 | 314 | // TODO: lift to protocol 315 | if(contrib == 0) 316 | Debug.Log("Building with Uniton Free"); 317 | else if(contrib <= 500) 318 | Debug.Log("Building with Uniton Pro"); 319 | else if(contrib <= 5000) 320 | Debug.Log("Building with Uniton Build"); 321 | else 322 | Debug.Log("Building with Uniton Build Pro"); 323 | 324 | var date = DateTime.Now.ToString("yyyy-MM-dd"); 325 | 326 | // Directory.CreateDirectory("Assets/Resources"); 327 | var dllpath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath; 328 | var unitonDir = Path.GetDirectoryName(Path.GetDirectoryName(dllpath)); 329 | 330 | File.WriteAllText(unitonDir + ".bi.cs", $"namespace Uniton.Bootstrap{{public static class BuildInfo{{public const string date=\"{date}\"; public const string deviceId=\"{SystemInfo.deviceUniqueIdentifier}\"; public const string userId=\"{UnityEditor.CloudProjectSettings.userId}\"; public const string ghLogin=\"{ghLogin}\"; public const int contrib={contrib}; public const string tokenHash=\"{tokenHash}\"; }}}}"); 331 | 332 | // var dllpath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath; // TODO: what happens if building from source? 333 | 334 | // var fileStream = File.Create(dllpath + ".bootstrap.dll"); 335 | // var dllstream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("bootstrap.dll"); 336 | // dllstream.Seek(0, SeekOrigin.Begin); 337 | // dllstream.CopyTo(fileStream); 338 | // fileStream.Close(); 339 | 340 | // File.Move(dllpath, dllpath + ".backup"); 341 | // File.Move(dllpath + ".backup.meta"); 342 | 343 | AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); 344 | } 345 | 346 | [PostProcessBuildAttribute(0)] 347 | public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { 348 | // Debug.Log( pathToBuiltProject ); 349 | 350 | 351 | var dllpath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath; 352 | var unitonDir = Path.GetDirectoryName(Path.GetDirectoryName(dllpath)); 353 | 354 | File.Delete(unitonDir + ".bi.cs"); 355 | File.Delete(unitonDir + ".bi.cs.meta"); 356 | 357 | // File.Delete(dllpath + ".bootstrap.dll"); 358 | // File.Delete(dllpath + ".bootstrap.dll.meta"); 359 | 360 | // File.Move(dllpath + ".backup", dllpath); 361 | // File.Move(dllpath + ".backup.meta", dllpath + ".meta"); 362 | 363 | AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); 364 | } 365 | 366 | } 367 | 368 | 369 | [InitializeOnLoad] 370 | class NoErrorsValidator 371 | { 372 | 373 | static NoErrorsValidator() 374 | { 375 | // if (Application.isBatchMode) 376 | CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; 377 | } 378 | 379 | private static void OnCompilationFinished(string s, CompilerMessage[] compilerMessages) 380 | { 381 | if (compilerMessages.Count(m => m.type == CompilerMessageType.Error) > 0){ 382 | // EditorApplication.Exit(-1); 383 | 384 | var dllpath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath; 385 | var unitonDir = Path.GetDirectoryName(Path.GetDirectoryName(dllpath)); 386 | 387 | File.Delete(unitonDir + ".bi.cs"); 388 | File.Delete(unitonDir + ".bi.cs.meta"); 389 | 390 | // File.Move(dllpath + ".backup", dllpath); 391 | // File.Move(dllpath + ".backup.meta", dllpath + ".meta"); 392 | 393 | // File.Delete(dllpath + ".bootstrap.dll"); 394 | // File.Delete(dllpath + ".bootstrap.dll.meta"); 395 | AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); 396 | } 397 | 398 | } 399 | } 400 | } 401 | // #endif -------------------------------------------------------------------------------- /src/py/uniton/util/appdirs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright (c) 2010 ActiveState Software Inc. 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a 5 | copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included 13 | in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 18 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 19 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 20 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 21 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | """ 23 | 24 | # -*- coding: utf-8 -*- 25 | # Copyright (c) 2005-2010 ActiveState Software Inc. 26 | # Copyright (c) 2013 Eddy Petrișor 27 | 28 | """Utilities for determining application-specific dirs. 29 | See for details and usage. 30 | """ 31 | # Dev Notes: 32 | # - MSDN on where to store app data files: 33 | # http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120 34 | # - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html 35 | # - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html 36 | 37 | __version__ = "1.4.4" 38 | __version_info__ = tuple(int(segment) for segment in __version__.split(".")) 39 | 40 | 41 | import sys 42 | import os 43 | 44 | PY3 = sys.version_info[0] == 3 45 | 46 | if PY3: 47 | unicode = str 48 | 49 | if sys.platform.startswith('java'): 50 | import platform 51 | os_name = platform.java_ver()[3][0] 52 | if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc. 53 | system = 'win32' 54 | elif os_name.startswith('Mac'): # "Mac OS X", etc. 55 | system = 'darwin' 56 | else: # "Linux", "SunOS", "FreeBSD", etc. 57 | # Setting this to "linux2" is not ideal, but only Windows or Mac 58 | # are actually checked for and the rest of the module expects 59 | # *sys.platform* style strings. 60 | system = 'linux2' 61 | else: 62 | system = sys.platform 63 | 64 | 65 | 66 | def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): 67 | r"""Return full path to the user-specific data dir for this application. 68 | "appname" is the name of application. 69 | If None, just the system directory is returned. 70 | "appauthor" (only used on Windows) is the name of the 71 | appauthor or distributing body for this application. Typically 72 | it is the owning company name. This falls back to appname. You may 73 | pass False to disable it. 74 | "version" is an optional version path element to append to the 75 | path. You might want to use this if you want multiple versions 76 | of your app to be able to run independently. If used, this 77 | would typically be ".". 78 | Only applied when appname is present. 79 | "roaming" (boolean, default False) can be set True to use the Windows 80 | roaming appdata directory. That means that for users on a Windows 81 | network setup for roaming profiles, this user data will be 82 | sync'd on login. See 83 | 84 | for a discussion of issues. 85 | Typical user data directories are: 86 | Mac OS X: ~/Library/Application Support/ 87 | Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined 88 | Win XP (not roaming): C:\Documents and Settings\\Application Data\\ 89 | Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ 90 | Win 7 (not roaming): C:\Users\\AppData\Local\\ 91 | Win 7 (roaming): C:\Users\\AppData\Roaming\\ 92 | For Unix, we follow the XDG spec and support $XDG_DATA_HOME. 93 | That means, by default "~/.local/share/". 94 | """ 95 | if system == "win32": 96 | if appauthor is None: 97 | appauthor = appname 98 | const = "CSIDL_APPDATA" if roaming else "CSIDL_LOCAL_APPDATA" 99 | path = os.path.normpath(_get_win_folder(const)) 100 | if appname: 101 | if appauthor is not False: 102 | path = os.path.join(path, appauthor, appname) 103 | else: 104 | path = os.path.join(path, appname) 105 | elif system == 'darwin': 106 | path = os.path.expanduser('~/Library/Application Support/') 107 | if appname: 108 | path = os.path.join(path, appname) 109 | else: 110 | path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) 111 | if appname: 112 | path = os.path.join(path, appname) 113 | if appname and version: 114 | path = os.path.join(path, version) 115 | return path 116 | 117 | 118 | def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): 119 | r"""Return full path to the user-shared data dir for this application. 120 | "appname" is the name of application. 121 | If None, just the system directory is returned. 122 | "appauthor" (only used on Windows) is the name of the 123 | appauthor or distributing body for this application. Typically 124 | it is the owning company name. This falls back to appname. You may 125 | pass False to disable it. 126 | "version" is an optional version path element to append to the 127 | path. You might want to use this if you want multiple versions 128 | of your app to be able to run independently. If used, this 129 | would typically be ".". 130 | Only applied when appname is present. 131 | "multipath" is an optional parameter only applicable to *nix 132 | which indicates that the entire list of data dirs should be 133 | returned. By default, the first item from XDG_DATA_DIRS is 134 | returned, or '/usr/local/share/', 135 | if XDG_DATA_DIRS is not set 136 | Typical site data directories are: 137 | Mac OS X: /Library/Application Support/ 138 | Unix: /usr/local/share/ or /usr/share/ 139 | Win XP: C:\Documents and Settings\All Users\Application Data\\ 140 | Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) 141 | Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. 142 | For Unix, this is using the $XDG_DATA_DIRS[0] default. 143 | WARNING: Do not use this on Windows. See the Vista-Fail note above for why. 144 | """ 145 | if system == "win32": 146 | if appauthor is None: 147 | appauthor = appname 148 | path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) 149 | if appname: 150 | if appauthor is not False: 151 | path = os.path.join(path, appauthor, appname) 152 | else: 153 | path = os.path.join(path, appname) 154 | elif system == 'darwin': 155 | path = os.path.expanduser('/Library/Application Support') 156 | if appname: 157 | path = os.path.join(path, appname) 158 | else: 159 | # XDG default for $XDG_DATA_DIRS 160 | # only first, if multipath is False 161 | path = os.getenv('XDG_DATA_DIRS', 162 | os.pathsep.join(['/usr/local/share', '/usr/share'])) 163 | pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] 164 | if appname: 165 | if version: 166 | appname = os.path.join(appname, version) 167 | pathlist = [os.sep.join([x, appname]) for x in pathlist] 168 | 169 | if multipath: 170 | path = os.pathsep.join(pathlist) 171 | else: 172 | path = pathlist[0] 173 | return path 174 | 175 | if appname and version: 176 | path = os.path.join(path, version) 177 | return path 178 | 179 | 180 | def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): 181 | r"""Return full path to the user-specific config dir for this application. 182 | "appname" is the name of application. 183 | If None, just the system directory is returned. 184 | "appauthor" (only used on Windows) is the name of the 185 | appauthor or distributing body for this application. Typically 186 | it is the owning company name. This falls back to appname. You may 187 | pass False to disable it. 188 | "version" is an optional version path element to append to the 189 | path. You might want to use this if you want multiple versions 190 | of your app to be able to run independently. If used, this 191 | would typically be ".". 192 | Only applied when appname is present. 193 | "roaming" (boolean, default False) can be set True to use the Windows 194 | roaming appdata directory. That means that for users on a Windows 195 | network setup for roaming profiles, this user data will be 196 | sync'd on login. See 197 | 198 | for a discussion of issues. 199 | Typical user config directories are: 200 | Mac OS X: ~/Library/Preferences/ 201 | Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined 202 | Win *: same as user_data_dir 203 | For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. 204 | That means, by default "~/.config/". 205 | """ 206 | if system == "win32": 207 | path = user_data_dir(appname, appauthor, None, roaming) 208 | elif system == 'darwin': 209 | path = os.path.expanduser('~/Library/Preferences/') 210 | if appname: 211 | path = os.path.join(path, appname) 212 | else: 213 | path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) 214 | if appname: 215 | path = os.path.join(path, appname) 216 | if appname and version: 217 | path = os.path.join(path, version) 218 | return path 219 | 220 | 221 | def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): 222 | r"""Return full path to the user-shared data dir for this application. 223 | "appname" is the name of application. 224 | If None, just the system directory is returned. 225 | "appauthor" (only used on Windows) is the name of the 226 | appauthor or distributing body for this application. Typically 227 | it is the owning company name. This falls back to appname. You may 228 | pass False to disable it. 229 | "version" is an optional version path element to append to the 230 | path. You might want to use this if you want multiple versions 231 | of your app to be able to run independently. If used, this 232 | would typically be ".". 233 | Only applied when appname is present. 234 | "multipath" is an optional parameter only applicable to *nix 235 | which indicates that the entire list of config dirs should be 236 | returned. By default, the first item from XDG_CONFIG_DIRS is 237 | returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set 238 | Typical site config directories are: 239 | Mac OS X: same as site_data_dir 240 | Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in 241 | $XDG_CONFIG_DIRS 242 | Win *: same as site_data_dir 243 | Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) 244 | For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False 245 | WARNING: Do not use this on Windows. See the Vista-Fail note above for why. 246 | """ 247 | if system == 'win32': 248 | path = site_data_dir(appname, appauthor) 249 | if appname and version: 250 | path = os.path.join(path, version) 251 | elif system == 'darwin': 252 | path = os.path.expanduser('/Library/Preferences') 253 | if appname: 254 | path = os.path.join(path, appname) 255 | else: 256 | # XDG default for $XDG_CONFIG_DIRS 257 | # only first, if multipath is False 258 | path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') 259 | pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] 260 | if appname: 261 | if version: 262 | appname = os.path.join(appname, version) 263 | pathlist = [os.sep.join([x, appname]) for x in pathlist] 264 | 265 | if multipath: 266 | path = os.pathsep.join(pathlist) 267 | else: 268 | path = pathlist[0] 269 | return path 270 | 271 | 272 | def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): 273 | r"""Return full path to the user-specific cache dir for this application. 274 | "appname" is the name of application. 275 | If None, just the system directory is returned. 276 | "appauthor" (only used on Windows) is the name of the 277 | appauthor or distributing body for this application. Typically 278 | it is the owning company name. This falls back to appname. You may 279 | pass False to disable it. 280 | "version" is an optional version path element to append to the 281 | path. You might want to use this if you want multiple versions 282 | of your app to be able to run independently. If used, this 283 | would typically be ".". 284 | Only applied when appname is present. 285 | "opinion" (boolean) can be False to disable the appending of 286 | "Cache" to the base app data dir for Windows. See 287 | discussion below. 288 | Typical user cache directories are: 289 | Mac OS X: ~/Library/Caches/ 290 | Unix: ~/.cache/ (XDG default) 291 | Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache 292 | Vista: C:\Users\\AppData\Local\\\Cache 293 | On Windows the only suggestion in the MSDN docs is that local settings go in 294 | the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming 295 | app data dir (the default returned by `user_data_dir` above). Apps typically 296 | put cache data somewhere *under* the given dir here. Some examples: 297 | ...\Mozilla\Firefox\Profiles\\Cache 298 | ...\Acme\SuperApp\Cache\1.0 299 | OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. 300 | This can be disabled with the `opinion=False` option. 301 | """ 302 | if system == "win32": 303 | if appauthor is None: 304 | appauthor = appname 305 | path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) 306 | if appname: 307 | if appauthor is not False: 308 | path = os.path.join(path, appauthor, appname) 309 | else: 310 | path = os.path.join(path, appname) 311 | if opinion: 312 | path = os.path.join(path, "Cache") 313 | elif system == 'darwin': 314 | path = os.path.expanduser('~/Library/Caches') 315 | if appname: 316 | path = os.path.join(path, appname) 317 | else: 318 | path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) 319 | if appname: 320 | path = os.path.join(path, appname) 321 | if appname and version: 322 | path = os.path.join(path, version) 323 | return path 324 | 325 | 326 | def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): 327 | r"""Return full path to the user-specific state dir for this application. 328 | "appname" is the name of application. 329 | If None, just the system directory is returned. 330 | "appauthor" (only used on Windows) is the name of the 331 | appauthor or distributing body for this application. Typically 332 | it is the owning company name. This falls back to appname. You may 333 | pass False to disable it. 334 | "version" is an optional version path element to append to the 335 | path. You might want to use this if you want multiple versions 336 | of your app to be able to run independently. If used, this 337 | would typically be ".". 338 | Only applied when appname is present. 339 | "roaming" (boolean, default False) can be set True to use the Windows 340 | roaming appdata directory. That means that for users on a Windows 341 | network setup for roaming profiles, this user data will be 342 | sync'd on login. See 343 | 344 | for a discussion of issues. 345 | Typical user state directories are: 346 | Mac OS X: same as user_data_dir 347 | Unix: ~/.local/state/ # or in $XDG_STATE_HOME, if defined 348 | Win *: same as user_data_dir 349 | For Unix, we follow this Debian proposal 350 | to extend the XDG spec and support $XDG_STATE_HOME. 351 | That means, by default "~/.local/state/". 352 | """ 353 | if system in ["win32", "darwin"]: 354 | path = user_data_dir(appname, appauthor, None, roaming) 355 | else: 356 | path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state")) 357 | if appname: 358 | path = os.path.join(path, appname) 359 | if appname and version: 360 | path = os.path.join(path, version) 361 | return path 362 | 363 | 364 | def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): 365 | r"""Return full path to the user-specific log dir for this application. 366 | "appname" is the name of application. 367 | If None, just the system directory is returned. 368 | "appauthor" (only used on Windows) is the name of the 369 | appauthor or distributing body for this application. Typically 370 | it is the owning company name. This falls back to appname. You may 371 | pass False to disable it. 372 | "version" is an optional version path element to append to the 373 | path. You might want to use this if you want multiple versions 374 | of your app to be able to run independently. If used, this 375 | would typically be ".". 376 | Only applied when appname is present. 377 | "opinion" (boolean) can be False to disable the appending of 378 | "Logs" to the base app data dir for Windows, and "log" to the 379 | base cache dir for Unix. See discussion below. 380 | Typical user log directories are: 381 | Mac OS X: ~/Library/Logs/ 382 | Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined 383 | Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs 384 | Vista: C:\Users\\AppData\Local\\\Logs 385 | On Windows the only suggestion in the MSDN docs is that local settings 386 | go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in 387 | examples of what some windows apps use for a logs dir.) 388 | OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` 389 | value for Windows and appends "log" to the user cache dir for Unix. 390 | This can be disabled with the `opinion=False` option. 391 | """ 392 | if system == "darwin": 393 | path = os.path.join( 394 | os.path.expanduser('~/Library/Logs'), 395 | appname) 396 | elif system == "win32": 397 | path = user_data_dir(appname, appauthor, version) 398 | version = False 399 | if opinion: 400 | path = os.path.join(path, "Logs") 401 | else: 402 | path = user_cache_dir(appname, appauthor, version) 403 | version = False 404 | if opinion: 405 | path = os.path.join(path, "log") 406 | if appname and version: 407 | path = os.path.join(path, version) 408 | return path 409 | 410 | 411 | class AppDirs(object): 412 | """Convenience wrapper for getting application dirs.""" 413 | def __init__(self, appname=None, appauthor=None, version=None, 414 | roaming=False, multipath=False): 415 | self.appname = appname 416 | self.appauthor = appauthor 417 | self.version = version 418 | self.roaming = roaming 419 | self.multipath = multipath 420 | 421 | @property 422 | def user_data_dir(self): 423 | return user_data_dir(self.appname, self.appauthor, 424 | version=self.version, roaming=self.roaming) 425 | 426 | @property 427 | def site_data_dir(self): 428 | return site_data_dir(self.appname, self.appauthor, 429 | version=self.version, multipath=self.multipath) 430 | 431 | @property 432 | def user_config_dir(self): 433 | return user_config_dir(self.appname, self.appauthor, 434 | version=self.version, roaming=self.roaming) 435 | 436 | @property 437 | def site_config_dir(self): 438 | return site_config_dir(self.appname, self.appauthor, 439 | version=self.version, multipath=self.multipath) 440 | 441 | @property 442 | def user_cache_dir(self): 443 | return user_cache_dir(self.appname, self.appauthor, 444 | version=self.version) 445 | 446 | @property 447 | def user_state_dir(self): 448 | return user_state_dir(self.appname, self.appauthor, 449 | version=self.version) 450 | 451 | @property 452 | def user_log_dir(self): 453 | return user_log_dir(self.appname, self.appauthor, 454 | version=self.version) 455 | 456 | 457 | #---- internal support stuff 458 | 459 | def _get_win_folder_from_registry(csidl_name): 460 | """This is a fallback technique at best. I'm not sure if using the 461 | registry for this guarantees us the correct answer for all CSIDL_* 462 | names. 463 | """ 464 | if PY3: 465 | import winreg as _winreg 466 | else: 467 | import _winreg 468 | 469 | shell_folder_name = { 470 | "CSIDL_APPDATA": "AppData", 471 | "CSIDL_COMMON_APPDATA": "Common AppData", 472 | "CSIDL_LOCAL_APPDATA": "Local AppData", 473 | }[csidl_name] 474 | 475 | key = _winreg.OpenKey( 476 | _winreg.HKEY_CURRENT_USER, 477 | r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" 478 | ) 479 | dir, type = _winreg.QueryValueEx(key, shell_folder_name) 480 | return dir 481 | 482 | 483 | def _get_win_folder_with_ctypes(csidl_name): 484 | import ctypes 485 | 486 | csidl_const = { 487 | "CSIDL_APPDATA": 26, 488 | "CSIDL_COMMON_APPDATA": 35, 489 | "CSIDL_LOCAL_APPDATA": 28, 490 | }[csidl_name] 491 | 492 | buf = ctypes.create_unicode_buffer(1024) 493 | ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) 494 | 495 | # Downgrade to short path name if have highbit chars. See 496 | # . 497 | has_high_char = False 498 | for c in buf: 499 | if ord(c) > 255: 500 | has_high_char = True 501 | break 502 | if has_high_char: 503 | buf2 = ctypes.create_unicode_buffer(1024) 504 | if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): 505 | buf = buf2 506 | 507 | return buf.value 508 | 509 | def _get_win_folder_with_jna(csidl_name): 510 | import array 511 | from com.sun import jna 512 | from com.sun.jna.platform import win32 513 | 514 | buf_size = win32.WinDef.MAX_PATH * 2 515 | buf = array.zeros('c', buf_size) 516 | shell = win32.Shell32.INSTANCE 517 | shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf) 518 | dir = jna.Native.toString(buf.tostring()).rstrip("\0") 519 | 520 | # Downgrade to short path name if have highbit chars. See 521 | # . 522 | has_high_char = False 523 | for c in dir: 524 | if ord(c) > 255: 525 | has_high_char = True 526 | break 527 | if has_high_char: 528 | buf = array.zeros('c', buf_size) 529 | kernel = win32.Kernel32.INSTANCE 530 | if kernel.GetShortPathName(dir, buf, buf_size): 531 | dir = jna.Native.toString(buf.tostring()).rstrip("\0") 532 | 533 | return dir 534 | 535 | def _get_win_folder_from_environ(csidl_name): 536 | env_var_name = { 537 | "CSIDL_APPDATA": "APPDATA", 538 | "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE", 539 | "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA", 540 | }[csidl_name] 541 | 542 | return os.environ[env_var_name] 543 | 544 | if system == "win32": 545 | try: 546 | from ctypes import windll 547 | except ImportError: 548 | try: 549 | import com.sun.jna 550 | except ImportError: 551 | try: 552 | if PY3: 553 | import winreg as _winreg 554 | else: 555 | import _winreg 556 | except ImportError: 557 | _get_win_folder = _get_win_folder_from_environ 558 | else: 559 | _get_win_folder = _get_win_folder_from_registry 560 | else: 561 | _get_win_folder = _get_win_folder_with_jna 562 | else: 563 | _get_win_folder = _get_win_folder_with_ctypes 564 | 565 | 566 | #---- self test code 567 | 568 | if __name__ == "__main__": 569 | appname = "MyApp" 570 | appauthor = "MyCompany" 571 | 572 | props = ("user_data_dir", 573 | "user_config_dir", 574 | "user_cache_dir", 575 | "user_state_dir", 576 | "user_log_dir", 577 | "site_data_dir", 578 | "site_config_dir") 579 | 580 | print("-- app dirs %s --" % __version__) 581 | 582 | print("-- app dirs (with optional 'version')") 583 | dirs = AppDirs(appname, appauthor, version="1.0") 584 | for prop in props: 585 | print("%s: %s" % (prop, getattr(dirs, prop))) 586 | 587 | print("\n-- app dirs (without optional 'version')") 588 | dirs = AppDirs(appname, appauthor) 589 | for prop in props: 590 | print("%s: %s" % (prop, getattr(dirs, prop))) 591 | 592 | print("\n-- app dirs (without optional 'appauthor')") 593 | dirs = AppDirs(appname) 594 | for prop in props: 595 | print("%s: %s" % (prop, getattr(dirs, prop))) 596 | 597 | print("\n-- app dirs (with disabled 'appauthor')") 598 | dirs = AppDirs(appname, appauthor=False) 599 | for prop in props: 600 | print("%s: %s" % (prop, getattr(dirs, prop))) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------