Giter Site home page Giter Site logo

godot-python's Introduction

Github action tests

Code style: black

Godot Python, because you want Python on Godot !

🚧🚨 Heavy refactoring in progress 🚨🚧

The project is under heavy refactoring to support Godot4 (which is totally incompatible with the current codebase).

Development is done on the godot4-meson branch until things start getting usable.

image

The goal of this project is to provide Python language support as a scripting module for the Godot game engine.

Quickstart

By order of simplicity:

  • Directly download the project from within Godot with the asset library tab.
  • Download from the asset library website.
  • Finally you can also head to the project release page if you want to only download one specific platform build

image

API

example:

# Explicit is better than implicit
from godot import exposed, export, Vector2, Node2D, ResourceLoader

WEAPON_RES = ResourceLoader.load("res://weapon.tscn")
SPEED = Vector2(10, 10)

@exposed
class Player(Node2D):
    """
    This is the file's main class which will be made available to Godot. This
    class must inherit from `godot.Node` or any of its children (e.g.
    `godot.KinematicBody`).

    Because Godot scripts only accept file paths, you can't have two `exposed` classes in the same file.
    """
    # Exposed class can define some attributes as export(<type>) to achieve
    # similar goal than GDSscript's `export` keyword
    name = export(str)

    # Can export property as well
    @export(int)
    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        self._age = value

    # All methods are exposed to Godot
    def talk(self, msg):
        print(f"I'm saying {msg}")

    def _ready(self):
        # Don't confuse `__init__` with Godot's `_ready`!
        self.weapon = WEAPON_RES.instance()
        self._age = 42
        # Of course you can access property & methods defined in the parent
        name = self.get_name()
        print(f"{name} position x={self.position.x}, y={self.position.y}")

    def _process(self, delta):
        self.position += SPEED * delta

    ...


class Helper:
    """
    Other classes are considered helpers and cannot be called from outside
    Python. However they can be imported from another python module.
    """
    ...

Building

To build the project from source, first checkout the repo or download the latest tarball.

Godot-Python requires Python >= 3.7 and a C compiler.

Godot GDNative header

The Godot GDNative headers are provided as git submodule:

$ git submodule init
$ git submodule update

Alternatively, you can get them from github.

Linux

On a fresh Ubuntu install, you will need to install these:

$ apt install python3 python3-pip python3-venv build-essential

On top of that build the CPython interpreter requires development headers of it extension modules (for instance if you lack sqlite dev headers, your Godot-Python build won't contain the sqlite3 python module)

The simplest way is to uncomment the main deb-src in `/etc/apt/sources.list`:

deb-src http://archive.ubuntu.com/ubuntu/ artful main

and instruct apt to install the needed packages:

$ apt update
$ apt build-dep python3.6

See the Python Developer's Guide for instructions on additional platforms.

MacOS

With MacOS, you will need XCode installed and install the command line tools.

$ xcode-select --install

If you are using CPython as your backend, you will need these. To install with Homebrew:

$ brew install python3 openssl zlib

You will also need virtualenv for your python.

Windows

Install VisualStudio and Python3, then submit a PR to improve this paragraph ;-)

Create the virtual env

Godot-Python build system is heavily based on Python (mainly Scons, Cython and Jinja2). Hence we have to create a Python virtual env to install all those dependencies without clashing with your global Python configuration.

$ cd <godot-python-dir>
godot-python$ python3 -m venv venv

Now you need to activate the virtual env, this is something you should do every time you want to use the virtual env.

For Linux/MacOS:

godot-python$ . ./venv/bin/activate

For Windows:

godot-python$ ./venv/bin/activate.bat

Finally we can install dependencies:

godot-python(venv)$ pip install -r requirements.txt

Running the build

For Linux:

godot-python(venv)$ scons platform=x11-64 release

For Windows:

godot-python(venv)$ scons platform=windows-64 release

For MacOS:

godot-python(venv)$ scons platform=osx-64 CC=clang release

Valid platforms are x11-64, x11-32, windows-64, windows-32 and osx-64. Check Travis or Appveyor links above to see the current status of your platform.

This command will checkout CPython repo, move to a pinned commit and build CPython from source.

It will then generate pythonscript/godot/bindings.pyx (Godot api bindings) from GDNative's api.json and compile it. This part is long and really memory demanding so be patient ;-) When hacking godot-python you can heavily speedup this step by passing sample=true to scons in order to build only a small subset of the bindings.

Eventually the rest of the source will be compiled and a zip build archive will be available in the build directory.

Testing your build

godot-python(venv)$ scons platform=<platform> test

This will run pytests defined in tests/bindings inside the Godot environment. If not present, will download a precompiled Godot binary (defined in SConstruct and platform specific SCSub files) to and set the correct library path for the GDNative wrapper.

Running the example project

godot-python(venv)$ scons platform=<platform> example

This will run the converted pong example in examples/pong inside the Godot environment. If not present, will download a precompiled Godot binary (defined in SConstruct) to and set the correct library path for the GDNative wrapper.

Using a local Godot version

If you have a pre-existing version of godot, you can instruct the build script to use that the static library and binary for building and tests.

godot-python(venv)$ scons platform=x11-64 godot_binary=../godot/bin/godot.x11.opt.64

Additional build options

You check out all the build options in this file.

FAQ

How can I export my project?

Currently, godot-python does not support automatic export, which means that the python environment is not copied to the release when using Godot's export menu. A release can be created manually:

First, export the project in .zip format.

Second, extract the .zip in a directory. For sake of example let's say the directory is called godotpythonproject.

Third, copy the correct Python environment into this folder (if it hasn't been automatically included in the export). Inside your project folder, you will need to find /addons/pythonscript/x11-64, replacing "x11-64" with the correct target system you are deploying to. Copy the entire folder for your system, placing it at the same relative position, e.g. godotpythonproject/addons/pythonscript/x11-64 if your unzipped directory was "godotpythonproject". Legally speaking you should also copy LICENSE.txt from the pythonscript folder. (The lazy option at this point is to simply copy the entire addons folder from your project to your unzipped directory.)

Fourth, place a godot release into the directory. The Godot export menu has probably downloaded an appropriate release already, or you can go to Editor -> Manage Export Templates inside Godot to download fresh ones. These are stored in a location which depends on your operating system. For example, on Windows they may be found at %APPDATA%\Godot\templates\ ; in Linux or OSX it is ~/.godot/templates/. Copy the file matching your export. (It may matter whether you selected "Export With Debug" when creating the .zip file; choose the debug or release version accordingly.)

Running the Godot release should now properly execute your release. However, if you were developing on a different Python environment (say, the one held in the osx-64 folder) than you include with the release (for example the windows-64 folder), and you make any alterations to that environment, such as installing Python packages, these will not carry over; take care to produce a suitable Python environment for the target platform.

See also this issue.

How can I use Python packages in my project?

In essence, godot-python installs a python interpreter inside your project which can then be distributed as part of the final game. Python packages you want to use need to be installed for that interpreter and of course included in the final release. This can be accomplished by using pip to install packages; however, pip is not provided, so it must be installed too.

First, locate the correct python interpreter. This will be inside your project at addons\pythonscript\windows-64\python.exe for 64-bit Windows, addons/pythonscript/ox-64/bin/python3 for OSX, etc. Then install pip by running:

addons\pythonscript\windows-64\python.exe -m ensurepip

(substituting the correct python for your system). Any other method of installing pip at this location is fine too, and this only needs to be done once. Afterward, any desired packages can be installed by running

addons\pythonscript\windows-64\python.exe -m pip install numpy

again, substituting the correct python executable, and replacing numpy with whatever packages you desire. The package can now be imported in your Python code as normal.

Note that this will only install packages onto the target platform (here, windows-64), so when exporting the project to a different platform, care must be taken to provide all the necessary libraries.

How can I debug my project with PyCharm?

This can be done using "Attach to Local Process", but first you have to change the Godot binary filename to include python, for example Godot_v3.0.2-stable_win64.exe to python_Godot_v3.0.2-stable_win64.exe. For more detailed guide and explanation see this external blog post.

How can I autoload a python script without attaching it to a Node?

In your project.godot file, add the following section:

[autoload]
autoloadpy="*res://autoload.py"

In addition to the usual:

[gdnative]
singletons=[ "res://pythonscript.gdnlib" ]

You can use any name for the python file and the class name autoloadpy.

Then autoload.py can expose a Node:

from godot import exposed, export
from godot.bindings import *

@exposed
class autoload(Node):

    def hi(self, to):
        return 'Hello %s from Python !' % to

which can then be called from your gdscript code as an attribute of the autoloadpy class (use the name defined in your project.godot):

print(autoloadpy.hi('root'))

How can I efficiently access PoolArrays?

PoolIntArray, PoolFloatArray, PoolVector3Array and the other pool arrays can't be accessed directly because they must be locked in memory first. Use the arr.raw_access() context manager to lock it:

arr = PoolIntArray() # create the array
arr.resize(10000)

with arr.raw_access() as ptr:
    for i in range(10000):
        ptr[i] = i # this is fast

# read access:
with arr.raw_access() as ptr:
    for i in range(10000):
        assert ptr[i] == i # so is this

Keep in mind great performances comes with great responsabilities: there is no boundary check so you may end up with memory corruption if you don't take care ;-)

See the godot-python issue.

godot-python's People

Contributors

albertas avatar buresu avatar colinkinloch avatar cridenour avatar dranorter avatar follower avatar garyo avatar matheus2740 avatar mhilbrunner avatar nat-72o avatar paolobb4 avatar prokopst avatar razcore-rad avatar swenner avatar touilleman avatar williamtambellini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

godot-python's Issues

Some failed tests

On the Discord channel, @touilleMan asked me to post some information about failed tests I encountered while testing the module. So here's some of the information he wanted.

If I recall, this was the configuration I used to build the engine:

scons platform=x11 gdnative_wrapper=yes target=release_debug tools=yes

The command I used to build the module:

scons platform=x11-64 backend=cpython godot_binary=/home/user/code/godot-master/bin/godot.x11.opt.64 gdnative_wrapper_lib=/home/user/code/godot-master/bin/libgdnative_wrapper_code.x11.opt.64.a

Command I used to test it:

scons platform=x11-64 backend=cpython godot_binary=../godot-master/bin/godot.x11.opt.tools.64 gdnative_wrapper_lib=../godot-master/bin/libgdnative_wrapper_code.x11.opt.64.a test

And the output from the test, found here.

make test errors

With latest version of git godot + godot-python I'm getting these errors with make test:

============================================================================================================= test session starts =============================================================================================================
platform linux -- Python 3.6.1, pytest-3.0.5, py-1.4.31, pluggy-0.4.0                                                                                                                                                                          
rootdir: /home/razvan/Documents/projects/dev/github-godot-python/tests/bindings, inifile:                                                                                                                                                      
collected 874 items                                                                                                                                                                                                                            
                                                                                                                                                                                                                                               
test_array.py .....................................................................                                                                                                                                                            
test_basis.py ....................................................                                                                                                                                                                             
test_color.py .................................................                                                                                                                                                                                
test_dictionary.py .x.................................                                                                                                                                                                                         
test_dynamic_bindings.py .......X.                                                                                                                                                                                                             
test_godot_bindings_module.py ...                                                                                                                                                                                                              
test_node_path.py ................                                                                                                                                                                                                             
test_plane.py ...................                                                                                                                                                                                                              
test_pool_arrays.py ...........................................................................................................................................................................................................................
...................................................................................................                                                                                                                                            
test_quat.py .......................................................X                                                                                                                                                                          
test_rect2.py .........................                                                                                                                                                                                                        
test_rect3.py ...................................                                                                                                                                                                                              
test_rid.py ............                                                                                                                                                                                                                       
test_tools.py ..................                                                                                                                                                                                                               
test_transform2d.py .......................                                                                                                                                                                                                    
test_vector2.py ...................................................................                                                                                                                                                            
test_vector3.py ......................F.............................................
================================================================================================================== FAILURES ===================================================================================================================
______________________________________________________________________________________________________ TestVector3.test_methods[snapped] ______________________________________________________________________________________________________
                                                                                                                                                                                                                                               
self = <test_vector3.TestVector3 object at 0x7f4d1b021940>, args = ['snapped', <class 'Vector3'>, (0.5,)]                                                                                                                                      
                                                                                                                                                                                                                                               
    @pytest.mark.parametrize('args', [                                                                                                                                                                                                         
        ['abs', Vector3, ()],                                                                                                                                                                                                                  
        ['angle_to', float, (Vector3(), )],                                                                                                                                                                                                    
        ['ceil', Vector3, ()],                                                                                                                                                                                                                 
        ['cross', Vector3, (Vector3(), )],                                                                                                                                                                                                     
        ['cubic_interpolate', Vector3, (Vector3(), Vector3(), Vector3(), 0.5)],                                                                                                                                                                
        ['distance_squared_to', float, (Vector3(), )],                                                                                                                                                                                         
        ['distance_to', float, (Vector3(), )],                                                                                                                                                                                                 
        ['dot', float, (Vector3(), )],                                                                                                                                                                                                         
        ['floor', Vector3, ()],                                                                                                                                                                                                                
        ['inverse', Vector3, ()],                                                                                                                                                                                                              
        ['length', float, ()],                                                                                                                                                                                                                 
        ['length_squared', float, ()],                                                                                                                                                                                                         
        ['linear_interpolate', Vector3, (Vector3(), 0.5)],                                                                                                                                                                                     
        ['max_axis', int, ()],                                                                                                                                                                                                                 
        ['min_axis', int, ()],                                                                                                                                                                                                                 
        ['normalized', Vector3, ()],                                                                                                                                                                                                           
        ['reflect', Vector3, (Vector3(), )],                                                                                                                                                                                                   
        ['rotated', Vector3, (Vector3(), 0.5)],                                                                                                                                                                                                
        ['slide', Vector3, (Vector3(), )],                                                                                                                                                                                                     
        ['snapped', Vector3, (0.5, )],                                                                                                                                                                                                         
    ], ids=lambda x: x[0])                                                                                                                                                                                                                     
    def test_methods(self, args): 
        v = Vector3()                                                                                                                                                                                                                  [0/9692]
        # Don't test methods' validity but bindings one
        field, ret_type, params = args
        assert hasattr(v, field)
        method = getattr(v, field)
        assert callable(method)
>       ret = method(*params)

test_vector3.py:70:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <Vector3(x=0.0, y=0.0, z=0.0)>, val = 0.5

>   ???
E   TypeError: initializer for ctype 'struct godot_vector3 *' must be a cdata pointer, not float

<init code for 'pythonscriptcffi'>:1229: TypeError
========================================================================================= 1 failed, 870 passed, 1 xfailed, 2 xpassed in 1.09 seconds ==========================================================================================

Documentation

First, thanks for a great library - I always like to model out simulations in Python and always dread having to translate that to another language.

I've tried a couple times with varying levels of success on 64-bit Linux to build the project working following the README.md and I'm not sure all the examples and tests are up to date for the latest GDNative file formats - which makes total sense since it's a moving target.

I'm thinking about taking a stab at updating the examples / README as a PR now that we're closer to 3.0 (and saw your latest PR was merged) but wanted to make sure I don't do work that's already in progress.

If you're already working on these things, no worries! And if there is anything else I can do to help, let me know.

ModuleNotFoundError: No module named '_bz2'

Hey there! I'm trying to incorporate a tensor-flow chat bot but am getting this error when I run the scene:

  File "/media/ecludian/Data/GameDev/Godot/godot-python-0.9.0/lib/python36.zip/bz2.py", line 23, in <module>
ModuleNotFoundError: No module named '_bz2'

Is there anyway to add support for bz2? Cheers!

Error trying to test

Hello, im trying to test the module but i keep getting the following error:

ERROR: get_property_default_value: Cannot retrieve Python class for this script, is you code correct ?
At: modules/pythonscript/py_script.cpp:314.

What am i doing wrong?

thx

Windows godot-python

Make an instruction for Windows users! I did not understand what to do!
How to make this add-on for Godot ???

No such file godot/modules/gdnative/godot.h when building on macos

I'm trying to build godot-python under macos. I've got following error:

╰─ make generate_gdnative_cffidefs
/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py --output /Users/roman/work/godot-python/pythonscript/cffi_bindings/cdef.gen.h /Users/roman/work/godot-python/godot
clang: error: no such file or directory: '/Users/roman/work/godot-python/godot/modules/gdnative/godot.h'
clang: error: no input files
Traceback (most recent call last):
  File "/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py", line 61, in <module>
    fd.write(generate(args.godot_root_path))
  File "/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py", line 47, in generate
    first_line = next(i for i, line in enumerate(splitted_src) if 'godot' in line.lower())
StopIteration
make: *** [generate_gdnative_cffidefs] Error 1

I tried to change gdnative/godot.h to gdnative/gdnative.h but it cause other strange errors like:

╰─ make generate_gdnative_cffidefs
/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py --output /Users/roman/work/godot-python/pythonscript/cffi_bindings/cdef.gen.h /Users/roman/work/godot-python/godot
In file included from /Users/roman/work/godot-python/godot/modules/gdnative/godot/gdnative.h:50:
/usr/include/TargetConditionals.h:269:6: error: #elif after #else
    #elif defined(TARGET_CPU_PPC64) && TARGET_CPU_PPC64
     ^
/usr/include/TargetConditionals.h:279:6: error: #elif after #else
    #elif defined(TARGET_CPU_X86) && TARGET_CPU_X86
     ^
/usr/include/TargetConditionals.h:289:6: error: #elif after #else
    #elif defined(TARGET_CPU_X86_64) && TARGET_CPU_X86_64
     ^
/usr/include/TargetConditionals.h:299:6: error: #elif after #else
    #elif defined(TARGET_CPU_ARM) && TARGET_CPU_ARM
     ^
/usr/include/TargetConditionals.h:309:6: error: #elif after #else
    #elif defined(TARGET_CPU_ARM64) && TARGET_CPU_ARM64
     ^
/usr/include/TargetConditionals.h:319:6: error: #else after #else
    #else
     ^
/usr/include/TargetConditionals.h:369:2: error: #endif without #if
#endif
 ^
/usr/include/TargetConditionals.h:371:2: error: #endif without #if
#endif  /* __TARGETCONDITIONALS__ */
 ^
/Users/roman/work/godot-python/godot/modules/gdnative/godot/gdnative.h:97:31: warning: missing
      terminating ' character [-Winvalid-pp-token]
        GODOT_ERR_CANT_OPEN, ///< Can't open a resource/socket/file
                                     ^
In file included from /Users/roman/work/godot-python/godot/modules/gdnative/godot/gdnative.h:177:
In file included from /Users/roman/work/godot-python/godot/modules/gdnative/godot/string.h:38:
In file included from /usr/include/wchar.h:72:
In file included from /usr/include/Availability.h:190:
/usr/include/AvailabilityInternal.h:22938:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_12
         ^
/usr/include/AvailabilityInternal.h:22867:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_11_4
         ^
/usr/include/AvailabilityInternal.h:22800:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_11_3
         ^
/usr/include/AvailabilityInternal.h:22737:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_11_2
         ^
/usr/include/AvailabilityInternal.h:22678:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_11
         ^
/usr/include/AvailabilityInternal.h:22623:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_10_3
         ^
/usr/include/AvailabilityInternal.h:22572:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_10_2
         ^
/usr/include/AvailabilityInternal.h:22525:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_10
         ^
/usr/include/AvailabilityInternal.h:22482:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9
         ^
/usr/include/AvailabilityInternal.h:22443:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_8
         ^
/usr/include/AvailabilityInternal.h:22408:10: error: unterminated conditional directive
        #if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_7
         ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
1 warning and 20 errors generated.
Traceback (most recent call last):
  File "/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py", line 61, in <module>
    fd.write(generate(args.godot_root_path))
  File "/Users/roman/work/godot-python/tools/generate_gdnative_cffidefs.py", line 41, in generate
    ast = parse_file(gdnative_header, use_cpp=True, cpp_args=['-D__attribute__(x)=', '-I' + gdnative_include, '-I%sfake_libc_include' % BASEDIR])
  File "/Users/roman/work/godot-python/tools/pycparser/__init__.py", line 93, in parse_file
    return parser.parse(text, filename)
  File "/Users/roman/work/godot-python/tools/pycparser/c_parser.py", line 152, in parse
    debug=debuglevel)
  File "/Users/roman/work/godot-python/tools/pycparser/ply/yacc.py", line 331, in parse
    return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
  File "/Users/roman/work/godot-python/tools/pycparser/ply/yacc.py", line 1118, in parseopt_notrack
    p.callable(pslice)
  File "/Users/roman/work/godot-python/tools/pycparser/c_parser.py", line 566, in p_pp_directive
    self._token_coord(p, 1))
  File "/Users/roman/work/godot-python/tools/pycparser/plyparser.py", line 66, in _parse_error
    raise ParseError("%s: %s" % (coord, msg))
pycparser.plyparser.ParseError: /usr/include/TargetConditionals.h:95:5: Directives not supported yet
make: *** [generate_gdnative_cffidefs] Error 1

Can anyone help with this problems?

Error while installing pycrypto

I can install successfully some libraries while not anothers, for example pycrypto.

` creating build/lib.linux-x86_64-3.6/Crypto/Signature
copying lib/Crypto/Signature/init.py -> build/lib.linux-x86_64-3.6/Crypto/Signature
copying lib/Crypto/Signature/PKCS1_v1_5.py -> build/lib.linux-x86_64-3.6/Crypto/Signature
copying lib/Crypto/Signature/PKCS1_PSS.py -> build/lib.linux-x86_64-3.6/Crypto/Signature
error: [Errno 20] Not a directory: '/tank/lana/_apps/godot-python-0.9.0/lib/python36.zip/lib2to3/Grammar.txt'

----------------------------------------

Command "/tank/lana/_apps/godot-python-0.9.0/python-bin -u -c "import setuptools, tokenize;file='/tmp/pip-build-18406z3z/pycrypto/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-l85aj1tv-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-18406z3z/pycrypto/
`

Suggestion: Do a windows build available

Linux is a wonderfull system, but, by the fact, most godot users (me include) have windows in their computers. If is needed some testing in godot-python binding, maybe there will be a compilation for windows available in the main page of Godot. I know that 90% of godot dev´s have linux, but 90% of godot users have windows (Percentages invented with a reliability of 90%)

pythonscriptcffi initialization code failed

On ubuntu 17.04. With your master branch. Was I supposed to use the beta release from the release tab?!

Saw your beta release on twitter :D! Nices!! Well, I compiled with latest godot master branch (ref. afbb5261e660acf08dd62f698d353e95fc7fb6bb), but on running godot I get:

modules/pythonscript/py_script.cpp:27:_bind_methods
modules/pythonscript/py_language.cpp:284:PyLanguage     (93900151122192)
modules/pythonscript/py_language.cpp:20:init    (93900151122192)
Traceback (most recent call last):
  File "<init code for 'pythonscriptcffi'>", line 3341, in <module>
  File "<init code for 'pythonscriptcffi'>", line 3312, in __init__
  File "<init code for 'pythonscriptcffi'>", line 2956, in get_global_constansts
  File "<init code for 'pythonscriptcffi'>", line 2559, in godot_dictionary_to_pyobj
TypeError: expected a cdata struct/union/array object

From: pythonscriptcffi
compiled with cffi version: 1.10.0
_cffi_backend module: '/home/razvan/.local/lib/python3.6/site-packages/_cffi_backend.cpython-36m-x86_64-linux-gnu.so'
sys.path: ['/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/razvan/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

function pythonscriptcffi.pybind_init_sys_path_and_argv() called, but initialization code failed.  Returning 0.
ERROR: init: Method/Function Failed.
   At: modules/pythonscript/py_language.cpp:29.
modules/pythonscript/py_language.cpp:97:~PyLanguage     (93900151122192)

Create Games using Godot-Python and Avoid Usage Of Godot Tools

First of all, congratulations for your efforts to add Python support to Godot - huge Python fan here that was looking for something similar.

I have a need however to be able to quickly write a game and execute it without having to open Godot tools. Import the assets from the script etc. and do godot script.py and have it run.

How could that happen ? Thanks !

Packaged Mac build of pong example crashes on startup

I built godot-python on Mac using cypthon backend, like this:
scons platform=osx-64 backend=cpython godot_binary=/Applications/Godot.app/Contents/MacOS/Godot gdnative_parse_cpp="clang -E"

If I package the python pong example as a DMG (from the editor) and run that, it crashes on startup. It works fine when run from Godot though.

% lldb /Volumes/pypong/pypong.app/Contents/MacOS/pypong         
(lldb) target create "/Volumes/pypong/pypong.app/Contents/MacOS/pypong"
Current executable set to '/Volumes/pypong/pypong.app/Contents/MacOS/pypong' (x86_64).
(lldb) run
Process 79358 launched: '/Volumes/pypong/pypong.app/Contents/MacOS/pypong' (x86_64)
arguments
0: /Volumes/pypong/pypong.app/Contents/MacOS/pypong
Current path: /Volumes/pypong/pypong.app/Contents/Resources
2018-02-28 14:52:11.345460-0500 pypong[79358:3128294] MessageTracer: Falling back to default whitelist
OpenGL ES 3.0 Renderer: Intel Iris OpenGL Engine
Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007fff99a9f340 (most recent call first):
Process 79358 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00007fff60b98e3e libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill:
->  0x7fff60b98e3e <+10>: jae    0x7fff60b98e48            ; <+20>
    0x7fff60b98e40 <+12>: movq   %rax, %rdi
    0x7fff60b98e43 <+15>: jmp    0x7fff60b900b8            ; cerror_nocancel
    0x7fff60b98e48 <+20>: retq   
Target 0: (pypong) stopped.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x00007fff60b98e3e libsystem_kernel.dylib`__pthread_kill + 10
    frame #1: 0x00007fff60cd7150 libsystem_pthread.dylib`pthread_kill + 333
    frame #2: 0x00007fff60af5312 libsystem_c.dylib`abort + 127
    frame #3: 0x0000000113c131b1 libpython3.6m.dylib`Py_FatalError(msg=<unavailable>) at pylifecycle.c:1466 [opt]
    frame #4: 0x0000000113c12f94 libpython3.6m.dylib`_Py_InitializeEx_Private(install_sigs=0, install_importlib=1) at pylifecycle.c:444 [opt]
    frame #5: 0x0000000113a02f7b libpythonscript.dylib`_cffi_py_initialize + 11
    frame #6: 0x0000000113a02870 libpythonscript.dylib`_cffi_carefully_make_gil + 288
    frame #7: 0x0000000113a0268d libpythonscript.dylib`_cffi_start_python + 13
    frame #8: 0x0000000113a025ff libpythonscript.dylib`_cffi_start_and_call_python + 31
    frame #9: 0x0000000113a018f2 libpythonscript.dylib`pybind_init + 50
    frame #10: 0x000000010017daec pypong`PluginScriptLanguage::init() + 12
    frame #11: 0x0000000101457e79 pypong`ScriptServer::init_languages() + 41
    frame #12: 0x0000000100027282 pypong`Main::setup2(unsigned long long) + 4594
    frame #13: 0x0000000100023dca pypong`Main::setup(char const*, int, char**, bool) + 18058
    frame #14: 0x000000010000e422 pypong`main + 626
    frame #15: 0x00007fff60a49115 libdyld.dylib`start + 1
    frame #16: 0x00007fff60a49115 libdyld.dylib`start + 1
(lldb) 

It may be relevant that my Python is python3.6, built in my home dir. That's in my path, not MacOS system python. But as I understand, godot-python is supposed to be self-contained.

A PoolArray inside Array doesn't get sized correctly

I added this test to test_pool_arrays.py:

# Extra tests
class TestPoolVector3ArraySize:
    def test_size(self):
        a = PoolVector3Array()
        a.resize(1000)
        assert len(a) == 1000
    def test_size_in_array(self):
        a = Array()
        a.resize(9)
        a[0] = PoolVector3Array()
        a[0].resize(1000)
        assert len(a[0]) == 1000

It fails the assert, because len(a[0]) == 0, not 1000 as it should be. Is this my user error, or an actual bug?
It works fine if the PoolArray is not a member of a parent Array (see the first test).

RealBinder can only be used with floats

After adding Vector3 and GETSET functions for properties (x, y, z) I discovered that if I do:

a = Vector3()
a.x = 10 # this fails
a.x = 10. # this works

This most likely happens for all functions that expect float as a parameter, but are called with int.

pypy version closes editor on run

When a scene is played with pypy as GDNative Library it closes the editor although the scene runs and works correctly,

It does not happen when CPython is used.

Tested on Linux amd64, with both Godot master and Godot beta.

Need more info to start godot-python

I am interested in this project because I want to use general python modules in Godot.
I visited the page https://github.com/touilleMan/godot-python and saw Quickstart to visit https://github.com/touilleMan/godot-python/releases.
Because all I could see there was the link to the file , I dowloaded windows-64 zip and extracted it.
Then moved those folders into my Godot project to see the folder not recognized by Godot.
I wish I could see some exact steps in the description for Quickstart or Wiki here.
Thanks.

Fix leaking PyScript instance warning on game closing

When closing game, PyScript instance are not removed:

WARNING: cleanup: ObjectDB Instances still exist!
   At: core/object.cpp:1968.
Leaked Instance: PyScript:899
Leaked Instance: PyScript:907
ERROR: clear: Resources Still in use at Exit!
   At: core/resource.cpp:389.
Orphan StringName: Master
Orphan StringName: PyScript
StringName: 2 unclaimed string names at exit.
ERROR: cleanup: There are still MemoryPool allocs in use at exit!
   At: core/dvector.cpp:69.

Can't return string from function

I'm trying to use this wonderful code, but I can't seem to do the simplest things.

I have the following Python code:

from godot import exposed, export
from godot.bindings import TileMap
from random import choice, randint

@exposed
class Thing(TileMap):

    names = ["Mike","Bill", "James", "Robert"]

    thing1 = "Hi, I'm thing1."
    thing2 = "Hi, I'm thing2."
    some_number = 0

    def fly(self):
        print("Go fly a kite!")

    def get_name(self):
        name = choice(self.names)
        return name
    
    def do_number(self):
        self.some_number = randint(1,10)
    
    def get_number(self):
        return randint(1,10)
        
    def get_that_guy(self):
        b = "It's the man! Run!"
        return b

When I use the function which returns a number (in this case, an integer), it works fine. But when I try a string, it doesn't work. So I have this code:

extends Node2D

func _ready():
    var b = get_node("py_code")
    print("The random number chosen is %s." % b.get_number)
    print(b.get_that_guy())

It prints out "The random number is 5.", but it doesn't print "It's the man! Run!" So I am at a loss as to why my strings are not being returned from the function. FWIW, I am using Godot 3.0 alpha (very recent version) with recent Python bindings.

Collision with new OpenSSL package

When running run_godot.sh,
the following error occurs when openssl version is newer than 1.0.0:

/home/centos/Desktop/godot-python-0.9.0/godot.x11.opt.tools.64.llvm: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory

Check float/double size are respected between Godot and Python

Both godot and micropython handle real as float or double according to compilation parameter:

  • Godot macro REAL_T_IS_DOUBLE
  • Micropython macro MICROPY_FLOAT_IMPL (set to MICROPY_FLOAT_IMPL_FLOAT or MICROPY_FLOAT_IMPL_DOUBLE)

MICROPY_FLOAT_IMPL should depend of REAL_T_IS_DOUBLE

Please help a student Makefile:67: recipe for target 'setup' failed

Hello,

Looking for a little setup advice.

ln: failed to create symbolic link '/home/ry/GoDOT/GODOT/godot-python/godot/godot': No such file or directory
Makefile:67: recipe for target 'setup' failed
make: *** [setup] Error 1

How do I connect the folder correctly?

Thanks in advance

make generate_gdnative_cffidefs fails with current master branch of godot

This project is meant for Godot 3.0, is it not? It is possible that I made a mistake, but it seems to me, that it is not up to date with Godots gdnative sourcecode.

$ make generate_gdnative_cffidefs
/home/X/code/godot-python/tools/generate_gdnative_cffidefs.py --output /home/X/code/godot-python/pythonscript/cffi_bindings/cdef.gen.h /home/X/code/godot-python/godot
cpp: error: /home/X/code/godot-python/godot/modules/gdnative/godot/gdnative.h: No such file or directory
cpp: warning: ‘-x c’ after last input file has no effect
cpp: fatal error: no input files
compilation terminated.
Traceback (most recent call last):
  File "/home/X/code/godot-python/tools/generate_gdnative_cffidefs.py", line 61, in <module>
    fd.write(generate(args.godot_root_path))
  File "/home/X/code/godot-python/tools/generate_gdnative_cffidefs.py", line 47, in generate
    first_line = next(i for i, line in enumerate(splitted_src) if 'godot' in line.lower())
StopIteration
make: *** [Makefile:117: generate_gdnative_cffidefs] Error 1
$ ls godot/modules/gdnative/
total 2.9M
4.0K config.py           20K gdnative_api_struct.gen.cpp             4.0K gd_native_library_editor.h               4.0K nativescript/                  8.0K SCsub
4.0K config.pyc         200K gdnative_api_struct.gen.x11.tools.64.o  764K gd_native_library_editor.x11.tools.64.o  4.0K pluginscript/
4.0K doc_classes/        12K gdnative.cpp                            968K gdnative.x11.tools.64.o                   12K register_types.cpp
4.0K gdnative/          8.0K gdnative.h                              4.0K include/                                 4.0K register_types.h
132K gdnative_api.json  8.0K gd_native_library_editor.cpp            4.0K nativearvr/                              708K register_types.x11.tools.64.o

As you see, the 'godot' subfolder inside 'gdnative' does not exist.

It crash and leave this log on the terminal.

optirun ./godot.x11.opt.tools.64.llvm
GLES3: max extensions: 317
hdr supported: 1
GLES3: max ubo light: 409
GLES3: max ubo reflections: 455, ubo size: 144
Could not find platform independent libraries
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to [:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Some questions

So you say that the build only works on Linux at the moment
But say if I make a demo in Linux, can I still export to the other OS's that Godot exports to?

Also, if I include external python modules; how does that effect making the project export-able to all platforms?

Is debugging included in the workflow?

Converting from GDscript to Python or vice versa

Have you thought about adding such functionality ?

The reason I am asking is that there will be large codebases in GDscript and it would make sense to have a transpiler in order to be able to work with them.

Optional arguments appearing as positional arguments

I don't know if I'm doing something wrong but all Godot methods that contain optional arguments are being called as if all arguments were positional.

Eg: Node.add_child( Node node, bool legible_unique_name=false )

The node argument is positional but legible_unique_name is optional.

So, calling this by passing only node argument triggers a TypeError.

Python traceback:

Traceback (most recent call last):
  File "<init code for 'pythonscriptcffi'>", line 131, in pybind_call_meth
  File "/home/williamd1k0/Downloads/godot-python-0.9.0/examples/AngryMark/SimpleTest.py", line 22, in _input
    self.add_child(grr)
  File "<init code for 'pythonscriptcffi'>", line 3409, in bind
TypeError: add_child() takes 2 positional argument but 1 were given

Also, I'm using your release v0.9.0 for Linux.

pythonscript.gdnlib missing from release packages

Hi, this is a great project you've started here and I'm very exited about it but I'd like to mention that the packages found in the releases page only contain the folder pythonscript but are missing the file pythonscript.gdnlib that's required by gdnative wich means you can't even check out godot-python withougt having to go though compiling from src wich could be a turnoff for many people either for lack of time or because it can be intimidating for newer programmers (I know it still is a little intimidating for me).
I get it's best to build it yourself and that's what I ended up doing but still this is an easy thing to remedy, and it's such a great tool that I would hate to see people shy away from it for such a silly thing. Maybe it should also be mentioned in the readme that both pythonscript/ and pythonscript.gdnlib are required to be within the godot project.

I hope I don't come out as too pretentious, just trying to add my two cents.

PS: just copy-pasting pythonscript.gdnlib from the pong example dind't work for me, it would actually crush godot. Maybe because the releases are behind in respect to src?

godot-python fails to build

On Manjaro Linux, godot-python fails to build.
I've cloned the repository and tried to compile it with
scons platform=x11-64 backend=cpython release

scons` platform=x11-64 backend=cpython release
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
git clone https://github.com/python/cpython.git --depth=1 --branch=v3.6.3 --single-branch platforms/x11-64/cpython
Klone nach 'platforms/x11-64/cpython' ...
remote: Counting objects: 4426, done.
remote: Compressing objects: 100% (3898/3898), done.
remote: Total 4426 (delta 503), reused 2039 (delta 434), pack-reused 0
Empfange Objekte: 100% (4426/4426), 22.43 MiB | 3.20 MiB/s, Fertig.
Löse Unterschiede auf: 100% (503/503), Fertig.
Hinweis: Checke '2c5fed86e0cbba5a4e34792b0083128ce659909d' aus.

Sie befinden sich im Zustand eines 'losgelösten HEAD'. Sie können sich
umschauen, experimentelle Änderungen vornehmen und diese committen, und
Sie können alle möglichen Commits, die Sie in diesem Zustand machen,
ohne Auswirkungen auf irgendeinen Branch verwerfen, indem Sie einen
weiteren Checkout durchführen.

Wenn Sie einen neuen Branch erstellen möchten, um Ihre erstellten Commits
zu behalten, können Sie das (jetzt oder später) durch einen weiteren Checkout
mit der Option -b tun. Beispiel:

  git checkout -b <neuer-Branchname>

Checke Dateien aus: 100% (4176/4176), Fertig.
cd platforms/x11-64/cpython && echo Configuring CPython... && 1>/dev/null ./configure --enable-shared --prefix=/media/WDElements/Bastelordner_ext/Godot3/Godot Python/godot-python/platforms/x11-64/cpython_build && echo Building CPython... && 1>/dev/null make -j4 && echo Installing CPython in /media/WDElements/Bastelordner_ext/Godot3/Godot Python/godot-python/platforms/x11-64/cpython_build... && 1>/dev/null make install && LD_LIBRARY_PATH=/media/WDElements/Bastelordner_ext/Godot3/Godot Python/godot-python/platforms/x11-64/cpython_build/lib /media/WDElements/Bastelordner_ext/Godot3/Godot Python/godot-python/platforms/x11-64/cpython_build/bin/pip3 install cffi
Configuring CPython...
configure: WARNING: you should use --build, --host, --target
configure: WARNING: invalid host type: Python/godot-python/platforms/x11-64/cpython_build
Invalid configuration `Python/godot-python/platforms/x11-64/cpython_build': machine `Python/godot-python/platforms/x11' not recognized
configure: error: /bin/sh ./config.sub Python/godot-python/platforms/x11-64/cpython_build failed
scons: *** [platforms/x11-64/cpython_build] Error 1
scons: building terminated because of errors.

Can't run test or example after building from source on Windows

I'm sure this is just a newbie problem, but I built the godot engine from source, then built godot-python from source (both latest github master) per the instructions. I'm on Win10, VS2017, python36. When I try test or example I get this error:

c:\dss\Product\GodotEngine\godot-python>scons.bat platform=windows-64 backend=cpython godot_binary=../godot/bin/godot.windows.opt.tools.64.exe test
scons: Reading SConscript files ...

scons: warning: MSVC_USE_SCRIPT set to False, assuming environment set correctly.
File "C:\dss\Product\GodotEngine\godot-python\SConstruct", line 52, in <module>
scons: done reading SConscript files.
scons: Building targets ...
SymLink(["build\main"], ["build\windows-64-cpython"])
C:\dss\Product\GodotEngine\godot\bin\godot.windows.opt.tools.64.exe --path tests/bindings
OpenGL ES 3.0 Renderer: GeForce GTX 970/PCIe/SSE2
ERROR: Can't open dynamic library: C:/dss/Product/GodotEngine/godot-python/tests/bindings/pythonscript/pythonscript.dll. Error: Error 126: The specified module could not be found.

   At: platform\windows\os_windows.cpp:1697
ERROR: No loader found for resource: res://main.py
   At: core\io\resource_loader.cpp:186
ERROR: ResourceInteractiveLoaderText::poll: res://main.tscn:3 - Parse Error: [ext_resource] referenced nonexistent resource at: res://main.py
   At: scene\resources\scene_format_text.cpp:439
ERROR: ResourceFormatLoader::load: Condition ' err != OK ' is true. returned: RES()
   At: core\io\resource_loader.cpp:149
ERROR: Failed loading resource: res://main.tscn
   At: core\io\resource_loader.cpp:186
ERROR: Failed loading scene: res://main.tscn
   At: main\main.cpp:1659
WARNING: ObjectDB::cleanup: ObjectDB Instances still exist!
     At: core\object.cpp:1989
scons: done building targets.

It's right, there is no such file tests/bindings/pythonscript/pythonscript.dll although it did build it.

[c:/dss/Product/GodotEngine/godot-python] % find . -name pythonscript.dll
./build/windows-64-cpython/pythonscript/pythonscript.dll
./pythonscript/pythonscript.dll

Any hints?
Also is it better to bring this kind of issue to IRC? Happy to do that.

Getting Started??

Its not clear how we are supposed to use this. The readme file only explains how to build from source.

I have godot 3.0 installed and downloaded the latest release of this project.

How do I set up the library in my project?

Errors when execute test/example

Hi!, I would like to try Godot Engine with Python to treat 3D objects, the compilation seems to finish correctly, but when running test/example I encounter the following errors:

$ make test
$ make run_example

Errors:

cd tests/bindings && /home/544GH5/Godot-src/godot-python/godot/bin/godot* 
GLES3: max extensions: 165
GLES3: max ubo light: 409
GLES3: max ubo reflections: 455, ubo size: 144
ERROR: load: No loader found for resource: /home/544GH5/Godot-src/godot-python/godot/bin/godot.x11.tools.64.llvm
   At: core/io/resource_loader.cpp:213.
ERROR: start: Failed loading scene: /home/544GH5/Godot-src/godot-python/godot/bin/godot.x11.tools.64.llvm
   At: main/main.cpp:1462.
WARNING: cleanup: ObjectDB Instances still exist!
   At: core/object.cpp:1910.
ERROR: cleanup: There are still MemoryPool allocs in use at exit!
   At: core/dvector.cpp:69.

/godot/bin$ ls

godot.x11.tools.64  godot.x11.tools.64.llvm  libpython3.6m.so.1.0

Thx!

Provide a python WHL for godot ?

It would be great if godot-python could be installed with pip - this would be the most accessible way for python devs to gt godot.

Similar to Panda3D, this would need the build process to adds the godot libraries + any third party libs into the WHL.

Transform2D implementation

Wanted to implement Transform2D but doesn't seem like Transform2D is exposed in GDScript. Do we need this? Looks like it's used only internally.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.