novaphysics 0.2.2__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,18 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: novaphysics
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Nova Physics Engine Python Binding
5
5
  Author: Kadir Aksoy
6
+ License-Expression: MIT
6
7
  Project-URL: homepage, https://github.com/kadir014/nova-physics-python
7
8
  Project-URL: bugtracker, https://github.com/kadir014/nova-physics-python/issues
8
9
  Classifier: Intended Audience :: Developers
9
- Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Topic :: Games/Entertainment
12
12
  Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
13
16
  Requires-Python: >=3.10
14
17
  Description-Content-Type: text/markdown
15
18
  License-File: LICENSE
@@ -17,8 +20,10 @@ Requires-Dist: cffi>=1.17.0
17
20
  Dynamic: license-file
18
21
 
19
22
  # Python binding for [Nova Physics Engine](https://github.com/kadir014/nova-physics)
20
- <img src="https://img.shields.io/badge/license-MIT-blue.svg">
21
- <img src="https://img.shields.io/badge/version-0.2.2-yellow">
23
+ <p>
24
+ <img src="https://img.shields.io/badge/license-MIT-blue.svg">
25
+ <img src="https://img.shields.io/badge/version-0.3.0-yellow">
26
+ </p>
22
27
 
23
28
  Python bindings using CFFI for the Nova Physics Engine.
24
29
 
@@ -34,18 +39,28 @@ This binding tries to be as Pythonic as possible while trying to keep the origin
34
39
 
35
40
 
36
41
  # Installation
37
- Clone the repo and `cd` into it.
42
+ You can simply install from PyPI.
43
+ ```shell
44
+ $ pip install novaphysics
45
+ ```
46
+
47
+ Or if you want to manually install, clone the repo and `cd` into it.
38
48
  ```shell
39
49
  $ git clone https://github.com/kadir014/nova-physics-python.git
40
50
  $ cd nova-physics-python
41
51
  ```
42
52
 
43
- Install the package locally. This will also download the latest commit from C library's repository.
53
+ Install the package locally. This will also download the latest stable release from C library's repository.
44
54
  ```shell
45
55
  $ pip install .
46
56
  ```
47
57
 
48
- Or if you want to build wheels, follow this.
58
+ However, if you want the latest commit of the engine, instead of the last stable release, you should set the build type environment variable to `nightly` before building.
59
+ ```shell
60
+ $ NOVA_BUILD=nightly pip install .
61
+ ```
62
+
63
+ Or if you want to build wheels, invoke `build`.
49
64
  ```shell
50
65
  $ python -m build
51
66
  ```
@@ -1,6 +1,8 @@
1
1
  # Python binding for [Nova Physics Engine](https://github.com/kadir014/nova-physics)
2
- <img src="https://img.shields.io/badge/license-MIT-blue.svg">
3
- <img src="https://img.shields.io/badge/version-0.2.2-yellow">
2
+ <p>
3
+ <img src="https://img.shields.io/badge/license-MIT-blue.svg">
4
+ <img src="https://img.shields.io/badge/version-0.3.0-yellow">
5
+ </p>
4
6
 
5
7
  Python bindings using CFFI for the Nova Physics Engine.
6
8
 
@@ -16,18 +18,28 @@ This binding tries to be as Pythonic as possible while trying to keep the origin
16
18
 
17
19
 
18
20
  # Installation
19
- Clone the repo and `cd` into it.
21
+ You can simply install from PyPI.
22
+ ```shell
23
+ $ pip install novaphysics
24
+ ```
25
+
26
+ Or if you want to manually install, clone the repo and `cd` into it.
20
27
  ```shell
21
28
  $ git clone https://github.com/kadir014/nova-physics-python.git
22
29
  $ cd nova-physics-python
23
30
  ```
24
31
 
25
- Install the package locally. This will also download the latest commit from C library's repository.
32
+ Install the package locally. This will also download the latest stable release from C library's repository.
26
33
  ```shell
27
34
  $ pip install .
28
35
  ```
29
36
 
30
- Or if you want to build wheels, follow this.
37
+ However, if you want the latest commit of the engine, instead of the last stable release, you should set the build type environment variable to `nightly` before building.
38
+ ```shell
39
+ $ NOVA_BUILD=nightly pip install .
40
+ ```
41
+
42
+ Or if you want to build wheels, invoke `build`.
31
43
  ```shell
32
44
  $ python -m build
33
45
  ```
@@ -0,0 +1,64 @@
1
+ """
2
+
3
+ This file is a part of the Nova Physics Engine
4
+ Python Binding and distributed under the MIT license.
5
+
6
+ Repository: https://github.com/kadir014/nova-physics-python
7
+ Issues: https://github.com/kadir014/nova-physics-python/issues
8
+
9
+ """
10
+
11
+
12
+ __version_major__ = 0
13
+ __version_minor__ = 3
14
+ __version_patch__ = 0
15
+ __version__ = f"{__version_major__}.{__version_minor__}.{__version_patch__}"
16
+
17
+ from nova.common import get_version_buffer
18
+ __nova_version__ = get_version_buffer()
19
+ del get_version_buffer
20
+
21
+
22
+ from nova.body import RigidBody
23
+ from nova.shape import Shape, Circle, Polygon, ShapeFactory
24
+ from nova.constraint import Constraint, DistanceConstraint, HingeConstraint
25
+ from nova.space import Space
26
+ from nova.models import (
27
+ BroadPhaseAlgorithm,
28
+ ShapeType,
29
+ RigidBodyType,
30
+ AABB,
31
+ VisitorAuxiliary,
32
+ ContactEventType,
33
+ ContactEvent,
34
+ Material
35
+ )
36
+ from nova.vector import Vector2
37
+ from nova import math
38
+
39
+
40
+ __all__ = (
41
+ "__version_major__",
42
+ "__version_minor__",
43
+ "__version_patch__",
44
+ "__version__",
45
+ "__nova_version__",
46
+ "RigidBody",
47
+ "Shape",
48
+ "Circle",
49
+ "Polygon",
50
+ "ShapeFactory",
51
+ "Constraint",
52
+ "DistanceConstraint",
53
+ "HingeConstraint",
54
+ "Space",
55
+ "BroadPhaseAlgorithm",
56
+ "ShapeType",
57
+ "RigidBodyType",
58
+ "AABB",
59
+ "VisitorAuxiliary",
60
+ "ContactEventType",
61
+ "ContactEvent",
62
+ "Material",
63
+ "Vector2"
64
+ )
@@ -0,0 +1,188 @@
1
+ """
2
+
3
+ This file is a part of the Nova Physics Engine
4
+ Python Binding and distributed under the MIT license.
5
+
6
+ Repository: https://github.com/kadir014/nova-physics-python
7
+ Issues: https://github.com/kadir014/nova-physics-python/issues
8
+
9
+ """
10
+
11
+ import platform
12
+ import re
13
+ from pathlib import Path
14
+
15
+ from cffi import FFI
16
+
17
+
18
+ RELEASE_BUILD = True
19
+
20
+ BASE_PATH = Path(__file__).resolve().parents[1]
21
+ NOVA_PATH = BASE_PATH / "build" / "nova-physics"
22
+ INCLUDE_PATH = NOVA_PATH / "include"
23
+ HEADER_PATH = INCLUDE_PATH / "novaphysics"
24
+
25
+ MSVC_COMPILER_ARGS = (
26
+ "/arch:AVX2",
27
+ "/D_CRT_SECURE_NO_WARNINGS",
28
+ "/DNV_ENABLE_PROFILER",
29
+ )
30
+ GCC_COMPILER_ARGS = (
31
+ # TODO: Detect if building with python-wasm-sdk, emcc doesn't accept -march
32
+ "-D_POSIX_C_SOURCE=200809L",
33
+ "-DNV_ENABLE_PROFILER",
34
+ )
35
+
36
+ IGNORED_HEADERS = {"internal.h", "internal_alloc.h"}
37
+
38
+
39
+ def read_header(path: Path) -> str:
40
+ source = path.read_text(encoding="utf-8")
41
+ # Preserve string literals while removing comments (including commented code).
42
+ return re.sub(
43
+ r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|/\*.*?\*/|//[^\n]*',
44
+ lambda match: " " if match[0].startswith(("/*", "//")) else match[0],
45
+ source,
46
+ flags=re.S,
47
+ )
48
+
49
+
50
+ def ordered_headers() -> list[Path]:
51
+ """ Visit includes first so typedefs precede the declarations using them. """
52
+
53
+ visited = set()
54
+ ordered = []
55
+
56
+ def visit(path):
57
+ if path in visited:
58
+ return
59
+ visited.add(path)
60
+ for include in re.findall(r'^\s*#include\s+"([^"]+)"', read_header(path), re.M):
61
+ dependency = (INCLUDE_PATH / include).resolve()
62
+ if not dependency.is_file():
63
+ dependency = (path.parent / include).resolve()
64
+ if dependency.is_file() and dependency.is_relative_to(HEADER_PATH.resolve()):
65
+ visit(dependency)
66
+ if path.name not in IGNORED_HEADERS:
67
+ ordered.append(path)
68
+
69
+ for path in sorted(HEADER_PATH.rglob("*.h")):
70
+ visit(path.resolve())
71
+ if not ordered:
72
+ raise FileNotFoundError(f"No Nova headers found in {HEADER_PATH}")
73
+ return ordered
74
+
75
+
76
+ def header_cdef(path: Path) -> str:
77
+ """ Generate cdef for one header. """
78
+
79
+ source = read_header(path)
80
+ if path.name == "types.h":
81
+ # Ignore the alternate precision branch and nv_sin/nv_cos/etc aliases.
82
+ # These math macros are not used by the Python binding. CFFI's float...
83
+ # typedef lets the compiler determine nv_float's actual precision.
84
+ source = re.sub(r"#ifdef NV_USE_DOUBLE_PRECISION\b.*?#else\b", "", source, flags=re.S)
85
+ source = re.sub(r"typedef\s+(float|double)\s+(nv_float)\s*;", r"typedef \1... \2;", source)
86
+
87
+ if path.name == "profiler.h":
88
+ # nvPrecisionTimer and its functions are ignored. Windows & posix types
89
+ # complicate CFFI, and the Python binding only uses nvProfiler.
90
+ source = source.split("typedef struct _nvPrecisionTimer", 1)[0]
91
+
92
+ # Only simple integer macros are exposed. Function-like macros, strings,
93
+ # float expressions, platform flags and include guards are intentionally
94
+ # ignored.
95
+ # BUT DONT FORGET their definitions remain available to the compiled C source!!
96
+ source = re.sub(r"\\\r?\n", "", source)
97
+ constants = re.findall(
98
+ r"^\s*#define\s+([A-Za-z_]\w*)\s+(0[xX][0-9a-fA-F]+|\d+)[uUlL]*\s*$",
99
+ source, re.M,
100
+ )
101
+ source = re.sub(r"^\s*#[^\n]*", "", source, flags=re.M)
102
+ # Initializers do not belong to cdef.
103
+ source = re.sub(r"(\bstatic\s+const\b[^=;]+)\s*=.*?;", r"\1;", source, flags=re.S)
104
+
105
+ # Nova's inline definitions always start with 'static inline'
106
+ # unless I forget this and do a change in the future lol
107
+ declarations = []
108
+ signature = []
109
+ in_inline = False
110
+ depth = 0
111
+ for line in source.splitlines():
112
+
113
+ if not in_inline and re.match(r"\s*static\s+inline\b", line):
114
+ in_inline = True
115
+ signature = []
116
+ line = re.sub(r"\bstatic\s+inline\s+", "", line, count=1)
117
+
118
+ if not in_inline:
119
+ declarations.append(line)
120
+ continue
121
+
122
+ masked = re.sub(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'', '""', line)
123
+ if depth == 0:
124
+ if "{" not in masked:
125
+ signature.append(line)
126
+ if ";" in masked: # inline prototype, without a body
127
+ declarations.extend(signature)
128
+ in_inline = False
129
+ continue
130
+ signature.append(line[:masked.index("{")].rstrip() + ";")
131
+ declarations.extend(signature)
132
+
133
+ depth += masked.count("{") - masked.count("}")
134
+ if depth == 0:
135
+ in_inline = False
136
+
137
+ if in_inline:
138
+ raise ValueError(f"Unfinished static inline function in {path}")
139
+
140
+ return "\n".join(f"#define {name} {value}" for name, value in constants) + "\n" + "\n".join(declarations)
141
+
142
+
143
+ def generate_cdef(headers: list[Path] | None = None) -> str:
144
+ """ Generate cdef header. """
145
+ headers = ordered_headers() if headers is None else headers
146
+ return "\n\n".join(header_cdef(path) for path in headers)
147
+
148
+
149
+ headers = ordered_headers()
150
+ cdef_source = generate_cdef(headers)
151
+ # Includes put the original inline implementations in the generated C module.
152
+ # No need to copy the bodies header guards already prevent duplicate definitions
153
+ ffi_sources = "\n".join(
154
+ f'#include "{path.relative_to(INCLUDE_PATH).as_posix()}"' for path in headers
155
+ )
156
+
157
+
158
+ print(
159
+ " \n"
160
+ " nova/_cffi_gen.py:\n"
161
+ " =========================================\n"
162
+ " Parsing & building the cdef header.\n"
163
+ " =========================================\n"
164
+ " \n"
165
+ )
166
+ ffibuilder = FFI()
167
+ ffibuilder.cdef(cdef_source)
168
+ ffibuilder.set_source(
169
+ "_nova",
170
+ ffi_sources,
171
+ sources=[str(path) for path in sorted((NOVA_PATH / "src").rglob("*.c"))],
172
+ include_dirs=[str(INCLUDE_PATH)],
173
+ extra_compile_args=list(MSVC_COMPILER_ARGS if platform.system() == "Windows" else GCC_COMPILER_ARGS),
174
+ libraries=[] if platform.system() == "Windows" else ["m"],
175
+ )
176
+
177
+ if __name__ == "__main__":
178
+ print(
179
+ " \n"
180
+ " nova/_cffi_gen.py:\n"
181
+ " =========================================\n"
182
+ " Building the CFFI module.\n"
183
+ " =========================================\n"
184
+ " \n"
185
+ )
186
+
187
+ (BASE_PATH / "novaphysics_cdef.h").write_text(cdef_source, encoding="utf-8")
188
+ ffibuilder.compile(verbose=False, debug=not RELEASE_BUILD)
@@ -0,0 +1,182 @@
1
+ """
2
+
3
+ This file is a part of the Nova Physics Engine
4
+ Python Binding and distributed under the MIT license.
5
+
6
+ Repository: https://github.com/kadir014/nova-physics-python
7
+ Issues: https://github.com/kadir014/nova-physics-python/issues
8
+
9
+ """
10
+
11
+ from typing import TYPE_CHECKING
12
+ from collections.abc import Iterator
13
+
14
+ from nova.common import lib, ffi, get_error_buffer
15
+ from nova.typing import Coordinate, enforce
16
+ from nova.error import NovaError
17
+ from nova.models import RigidBodyType, Material, AABB
18
+ from nova.vector import Vector2
19
+
20
+ if TYPE_CHECKING:
21
+ from nova.shape import Shape
22
+
23
+
24
+ class RigidBody:
25
+ def __init__(
26
+ self,
27
+ type: RigidBodyType = RigidBodyType.STATIC,
28
+ position: Coordinate = Vector2(0.0, 0.0),
29
+ angle: float = 0.0,
30
+ linear_velocity: Coordinate = Vector2(0.0, 0.0),
31
+ angular_velocity: float = 0.0,
32
+ material: Material = Material()
33
+ ) -> None:
34
+ type = enforce("type", type, RigidBodyType)
35
+ position = enforce("position", position, Coordinate)
36
+ angle = enforce("angle", angle, float)
37
+ linear_velocity = enforce("linear_velocity", linear_velocity, Coordinate)
38
+ angular_velocity = enforce("angular_velocity", angular_velocity, float)
39
+ material = enforce("material", material, Material)
40
+
41
+ position = Vector2(position)
42
+ linear_velocity = Vector2(linear_velocity)
43
+
44
+ init = lib.nvRigidBodyInitializer_default
45
+ init.type = type.value
46
+ init.position = position.to_tuple()
47
+ init.angle = angle
48
+ init.linear_velocity = linear_velocity.to_tuple()
49
+ init.angular_velocity = angular_velocity
50
+ init.material = material.to_tuple()
51
+ self._rigidbody = lib.nvRigidBody_new(init)
52
+ self._refd = False
53
+
54
+ # To keep GC
55
+ self._shape_ref: list["Shape"] = []
56
+
57
+ if self._rigidbody == ffi.NULL:
58
+ raise NovaError(get_error_buffer())
59
+
60
+ def __del__(self) -> None:
61
+ if not hasattr(self, "_rigidbody"): return
62
+ if self._refd: return
63
+
64
+ lib.nvRigidBody_free(self._rigidbody)
65
+
66
+ # Do not clear shape references
67
+ # because nvRigidBody_free already frees all shapes
68
+ # heap corruption -> for shape in self._shape_ref: shape._refd = False
69
+ self._shape_ref.clear()
70
+
71
+ def _get_shape_by_pointer(self, cshape) -> "Shape | None":
72
+ for shape in self._shape_ref:
73
+ if shape._shape == cshape:
74
+ return shape
75
+ return None
76
+
77
+ def add_shape(self, shape: "Shape") -> None:
78
+ shape._refd = True
79
+ if (lib.nvRigidBody_add_shape(self._rigidbody, shape._shape)):
80
+ raise NovaError(get_error_buffer())
81
+ self._shape_ref.append(shape)
82
+
83
+ def remove_shape(self, shape: "Shape") -> None:
84
+ shape._refd = False
85
+ if (lib.nvRigidBody_remove_shape(self._rigidbody, shape._shape)):
86
+ raise NovaError(get_error_buffer())
87
+ self._shape_ref.remove(shape)
88
+
89
+ def iter_shapes(self) -> Iterator["Shape"]:
90
+ for shape in self._shape_ref:
91
+ yield shape
92
+
93
+ def apply_force(self, force: Coordinate) -> None:
94
+ force = Vector2(force)
95
+ lib.nvRigidBody_apply_force(self._rigidbody, force.to_tuple())
96
+
97
+ def apply_torque(self, torque: float) -> None:
98
+ lib.nvRigidBody_apply_torque(self._rigidbody, torque)
99
+
100
+ @property
101
+ def type(self) -> RigidBodyType:
102
+ type = lib.nvRigidBody_get_type(self._rigidbody)
103
+ if type == 0:
104
+ return RigidBodyType.STATIC
105
+ else:
106
+ return RigidBodyType.DYNAMIC
107
+
108
+ @type.setter
109
+ def type(self, type: RigidBodyType) -> None:
110
+ if lib.nvRigidBody_set_type(self._rigidbody, type.value):
111
+ raise NovaError(get_error_buffer())
112
+
113
+ @property
114
+ def aabb(self) -> AABB:
115
+ aabb = lib.nvRigidBody_get_aabb(self._rigidbody)
116
+ return AABB(aabb.min_x, aabb.min_y, aabb.max_x, aabb.max_y)
117
+
118
+ @property
119
+ def position(self) -> Vector2:
120
+ pos = lib.nvRigidBody_get_position(self._rigidbody)
121
+ return Vector2(pos.x, pos.y)
122
+
123
+ @position.setter
124
+ def position(self, position: Vector2) -> None:
125
+ lib.nvRigidBody_set_position(self._rigidbody, position.to_tuple())
126
+
127
+ @property
128
+ def angle(self) -> float:
129
+ return lib.nvRigidBody_get_angle(self._rigidbody)
130
+
131
+ @angle.setter
132
+ def angle(self, angle: Vector2) -> None:
133
+ lib.nvRigidBody_set_angle(self._rigidbody, angle)
134
+
135
+ @property
136
+ def linear_velocity(self) -> Vector2:
137
+ vel = lib.nvRigidBody_get_linear_velocity(self._rigidbody)
138
+ return Vector2(vel.x, vel.y)
139
+
140
+ @linear_velocity.setter
141
+ def linear_velocity(self, linear_velocity: Vector2) -> None:
142
+ lib.nvRigidBody_set_linear_velocity(self._rigidbody, linear_velocity.to_tuple())
143
+
144
+ @property
145
+ def angular_velocity(self) -> float:
146
+ return lib.nvRigidBody_get_angular_velocity(self._rigidbody)
147
+
148
+ @angular_velocity.setter
149
+ def angular_velocity(self, angular_velocity: float) -> None:
150
+ lib.nvRigidBody_set_angular_velocity(self._rigidbody, angular_velocity)
151
+
152
+ @property
153
+ def linear_damping_scale(self) -> float:
154
+ return lib.nvRigidBody_get_linear_damping_scale(self._rigidbody)
155
+
156
+ @linear_damping_scale.setter
157
+ def linear_damping_scale(self, linear_damping_scale: float) -> None:
158
+ lib.nvRigidBody_set_linear_damping_scale(self._rigidbody, linear_damping_scale)
159
+
160
+ @property
161
+ def angular_damping_scale(self) -> float:
162
+ return lib.nvRigidBody_get_angular_damping_scale(self._rigidbody)
163
+
164
+ @angular_damping_scale.setter
165
+ def angular_damping_scale(self, angular_damping_scale: float) -> None:
166
+ lib.nvRigidBody_set_angular_damping_scale(self._rigidbody, angular_damping_scale)
167
+
168
+ @property
169
+ def inertia(self) -> float:
170
+ return lib.nvRigidBody_get_inertia(self._rigidbody)
171
+
172
+ @inertia.setter
173
+ def inertia(self, inertia: float) -> None:
174
+ lib.nvRigidBody_set_inertia(self._rigidbody, inertia)
175
+
176
+ @property
177
+ def gravity_scale(self) -> float:
178
+ return lib.nvRigidBody_get_gravity_scale(self._rigidbody)
179
+
180
+ @gravity_scale.setter
181
+ def gravity_scale(self, gravity_scale: float) -> None:
182
+ lib.nvRigidBody_set_gravity_scale(self._rigidbody, gravity_scale)
@@ -0,0 +1,25 @@
1
+ """
2
+
3
+ This file is a part of the Nova Physics Engine
4
+ Python Binding and distributed under the MIT license.
5
+
6
+ Repository: https://github.com/kadir014/nova-physics-python
7
+ Issues: https://github.com/kadir014/nova-physics-python/issues
8
+
9
+ """
10
+
11
+ import _nova
12
+
13
+
14
+ lib = _nova.lib
15
+ ffi = _nova.ffi
16
+
17
+
18
+ def get_error_buffer() -> str:
19
+ error_buf = ffi.string(lib.nv_get_error())
20
+ return error_buf.decode("utf-8")
21
+
22
+
23
+ def get_version_buffer() -> str:
24
+ error_buf = ffi.string(lib.nv_get_version())
25
+ return error_buf.decode("utf-8")