Skip to content
Advertisement

Why is a hg.Vec3() vector passed to a Python function modified by it?

I’m working on a 3D project in Python using the HARFANG 3D wheel (I got from Pypi).

I have a function where I pass a series of data, including a vector3:

def evaluate_collision_to_sphere(position, velocity, dt, sphere_pos, sphere_rad):
    # tries to evaluation if the next iteration
    # will drive the position within the sphere radius
    position += velocity * dt
    if hg.Dist(position, sphere_pos) < sphere_rad:
        return True
    else:
        return False

I don’t return position and it is not a global variable. However, when returning from this function, position is modified within the scope of the caller.

How to I prevent this to happen :(

Advertisement

Answer

What happens here is that your Vec3 is passed by reference. This is the expected behavior, you can experiment further:

Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import harfang as hg
Harfang 3.2.3 for CPython 3.2+ on windows-x64 (build e3be7e4c0f9cd201f9bf8286d6dfaefd71b8fff2 Jul 13 2022 11:47:51)
See https://www.harfang3d.com/license for licensing terms
>>> a = hg.Vec3(1,2,3)
>>> a.y
2.0
>>> b = a
>>> b.y
2.0
>>> b.y = -1
>>> b.y
-1.0
>>> a.y
-1.0
>>> c = hg.Vec3(a)
>>> c.y
-1.0
>>> c.y = 100
>>> c.y
100.0
>>> a.y
-1.0
>>>

Design-wise, you might question why Vec3 are passed by reference and not by copy. My answer is that Vec3 is the most wanted type of data in a 3D project/3D engine. You potentially process hundreds if not thousands of vectors per frame, so you’d better have an engine that, by default, does its best to improve performance.

How to I prevent this to happen :(

You need to instruct HARFANG that you want a copy of your vector. For example, the function invocation could look like this:

test = evaluate_collision_to_sphere(hg.Vec3(pos), vel, dt, s_pos, s_rad)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement