6
$\begingroup$

How can I get the absolute position in 3d space of a face using python. I can get the position relative to the object origin using face.calc_center_median() this is not the absolute 3d position.

Here is how I got the relative position:

import bpy
import bmesh

# get current mesh
current_mesh = bpy.context.object.data

# create empty bmesh, add current mesh into empty bmesh
current_bm = bmesh.new()
current_bm.from_mesh(current_mesh)

# TODO: get absolute position
# get location of face (atm it relative to object origin)
for face in current_bm.faces:
    face_location = face.calc_center_median()
    normal = face.normal
    x = face_location[0]
    y = face_location[1]
    z = face_location[2]
    print('index: '+str(face.index), x, y, z)  # DEBUG


# current_bmesh back to mesh
current_bm.to_mesh(current_mesh)
current_bm.free()

In this scene for example the cube is a good distance from the world origin, the absolute 3d shall reflect this.

enter image description here

These are the reported coordinates of each face (they are relative to the origin of the object)

enter image description here

$\endgroup$
0

1 Answer 1

10
$\begingroup$

Multiply it with the object's world matrix.

loc_world_space = obj.matrix_world * loc_obj_space

where loc_obj_space is a 3d mathutils.Vector

There is an addon View3D-> Math Vis(Console) available to visualize vectors and matrices directly in the viewport.

I.e. paste the following lines to the interactive console

obj = bpy.context.active_object
lobj = [vertex.co for vertex in obj.data.vertices]
lworld = [obj.matrix_world * vector for vector in lobj]

Math Vis(Console)

$\endgroup$
2
  • $\begingroup$ This also works for converting the face normals to world coordinates! $\endgroup$
    – lmjohns3
    Commented Mar 7, 2023 at 2:03
  • $\begingroup$ A note: in today's Blender scripting, you need to use the Python @ operator to multiply matrices and vectors: obj.matrix_world @ vector for vector in lobj. $\endgroup$
    – lmjohns3
    Commented Mar 7, 2023 at 2:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .