def test_bge():
import traceback
sys.path.append(build_path)
try:
import mathutils, bge
v=mathutils.Vector()
m=mathutils.Matrix()
scn = bge.logic.getCurrentScene()
o = scn.objects["some"]
a=o.isPlayingAction()
b=o.parent.addDebugProperty("LOL")
o.endObject()
print("Test BGE: OK")
except Exception: traceback.print_exc()
python类Matrix()的实例源码
def __init__(self):
self.SPOT = int()
self.SUN = int()
self.NORMAL = int()
self.HEMI = int()
self.type = None
self.energy = float()
self.shadowClipStart = float()
self.shadowClipEnd = float()
self.shadowFrustumSize = float()
self.shadowBindId = int()
self.shadowMapType = int()
self.shadowBias = float()
self.shadowBleedBias = float()
self.useShadow = bool()
self.shadowColor = mathutils.Color()
self.shadowMatrix = mathutils.Matrix()
self.distance = float()
self.color = [0,0,0]
self.lin_attenuation = float()
self.quad_attenuation = float()
self.spotsize = float()
self.spotblend = float()
self.staticShadow = bool()
def __init__(self):
self.INSIDE = int()
self.INTERSECT = int()
self.OUTSIDE = int()
self.lens = float()
self.lodDistanceFactor = float()
self.fov = float()
self.ortho_scale = float()
self.near = float()
self.far = float()
self.shift_x = float()
self.shift_y = float()
self.perspective = bool()
self.frustum_culling = bool()
self.projection_matrix = mathutils.Matrix()
self.modelview_matrix = mathutils.Matrix()
self.camera_to_world = mathutils.Matrix()
self.world_to_camera = mathutils.Matrix()
self.useViewport = bool()
def mouse_hover_wall(self, context, event):
"""
convert mouse pos to matrix at bottom of surrounded wall, y oriented outside wall
"""
res, pt, y, i, o, tM = self.mouse_to_scene_raycast(context, event)
if res and o.data is not None and 'archipack_wall2' in o.data:
z = Vector((0, 0, 1))
d = o.data.archipack_wall2[0]
y = -y
pt += (0.5 * d.width) * y.normalized()
x = y.cross(z)
return True, Matrix([
[x.x, y.x, z.x, pt.x],
[x.y, y.y, z.y, pt.y],
[x.z, y.z, z.z, o.matrix_world.translation.z],
[0, 0, 0, 1]
]), o, y
return False, Matrix(), None, Vector()
def rotate(self, idx_from, a):
"""
apply rotation to all following segs
"""
self.segs[idx_from].rotate(a)
ca = cos(a)
sa = sin(a)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
# rotation center
p0 = self.segs[idx_from].p0
for i in range(idx_from + 1, len(self.segs)):
seg = self.segs[i]
# rotate seg
seg.rotate(a)
# rotate delta from rotation center to segment start
dp = rM * (seg.p0 - p0)
seg.translate(dp)
def create(self, context):
curve = context.active_object
bpy.ops.archipack.slab(auto_manipulate=self.auto_manipulate)
o = context.scene.objects.active
d = archipack_slab.datablock(o)
spline = curve.data.splines[0]
d.from_spline(curve.matrix_world, 12, spline)
if spline.type == 'POLY':
pt = spline.points[0].co
elif spline.type == 'BEZIER':
pt = spline.bezier_points[0].co
else:
pt = Vector((0, 0, 0))
# pretranslate
o.matrix_world = curve.matrix_world * Matrix([
[1, 0, 0, pt.x],
[0, 1, 0, pt.y],
[0, 0, 1, pt.z],
[0, 0, 0, 1]
])
return o
# -----------------------------------------------------
# Execute
# -----------------------------------------------------
def rotate(self, idx_from, a):
"""
apply rotation to all following segs
"""
self.segs[idx_from].rotate(a)
ca = cos(a)
sa = sin(a)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
# rotation center
p0 = self.segs[idx_from].p0
for i in range(idx_from + 1, len(self.segs)):
seg = self.segs[i]
seg.rotate(a)
dp = rM * (seg.p0 - p0)
seg.translate(dp)
def create(self, context):
curve = context.active_object
for spline in curve.data.splines:
bpy.ops.archipack.wall2(auto_manipulate=self.auto_manipulate)
o = context.scene.objects.active
d = archipack_wall2.datablock(o)
d.from_spline(curve.matrix_world, 12, spline)
if spline.type == 'POLY':
pt = spline.points[0].co
elif spline.type == 'BEZIER':
pt = spline.bezier_points[0].co
else:
pt = Vector((0, 0, 0))
# pretranslate
o.matrix_world = curve.matrix_world * Matrix([
[1, 0, 0, pt.x],
[0, 1, 0, pt.y],
[0, 0, 1, pt.z],
[0, 0, 0, 1]
])
return o
# -----------------------------------------------------
# Execute
# -----------------------------------------------------
def get_proj_matrix(self, part, t, nose_y):
# a matrix to project verts
# into uv space for horizontal parts of this step
# so uv = (rM * vertex).to_2d()
tl = t - nose_y / self.get_length("LEFT")
tr = t - nose_y / self.get_length("RIGHT")
t2, part, dz, shape = self.get_part(tl, "LEFT")
p0 = part.lerp(t2)
t2, part, dz, shape = self.get_part(tr, "RIGHT")
p1 = part.lerp(t2)
v = (p1 - p0).normalized()
return Matrix([
[-v.y, v.x, 0, p0.x],
[v.x, v.y, 0, p0.y],
[0, 0, 1, 0],
[0, 0, 0, 1]
]).inverted()
def rotate(self, a):
"""
Rotate center so we rotate ccw arround p0
"""
ca = cos(a)
sa = sin(a)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
p0 = self.p0
self.c = p0 + rM * (self.c - p0)
dp = p0 - self.c
self.a0 = atan2(dp.y, dp.x)
return self
# make offset for line / arc, arc / arc
def getmat(bone, active, context, ignoreparent):
"""Helper function for visual transform copy,
gets the active transform in bone space
"""
obj_act = context.active_object
data_bone = obj_act.data.bones[bone.name]
#all matrices are in armature space unless commented otherwise
otherloc = active.matrix # final 4x4 mat of target, location.
bonemat_local = data_bone.matrix_local.copy() # self rest matrix
if data_bone.parent:
parentposemat = obj_act.pose.bones[data_bone.parent.name].matrix.copy()
parentbonemat = data_bone.parent.matrix_local.copy()
else:
parentposemat = parentbonemat = Matrix()
if parentbonemat == parentposemat or ignoreparent:
newmat = bonemat_local.inverted() * otherloc
else:
bonemat = parentbonemat.inverted() * bonemat_local
newmat = bonemat.inverted() * parentposemat.inverted() * otherloc
return newmat
def to_matrix(self):
"""
mat = M(to original transform)^-1 * Mt(to origin) * Ms *
Mt(to origin)^-1 * M(to original transform)
"""
m = self.__mat
mi = self.__mat.inverted()
mtoi = mathutils.Matrix.Translation((-self.__iox, -self.__ioy, 0.0))
mto = mathutils.Matrix.Translation((self.__iox, self.__ioy, 0.0))
# every point must be transformed to origin
t = m * mathutils.Vector((self.__ix, self.__iy, 0.0))
tix, tiy = t.x, t.y
t = m * mathutils.Vector((self.__ox, self.__oy, 0.0))
tox, toy = t.x, t.y
t = m * mathutils.Vector((self.__x, self.__y, 0.0))
tx, ty = t.x, t.y
ms = mathutils.Matrix()
ms.identity()
if self.__dir_x == 1:
ms[0][0] = (tx - tox) * self.__dir_x / (tix - tox)
if self.__dir_y == 1:
ms[1][1] = (ty - toy) * self.__dir_y / (tiy - toy)
return mi * mto * ms * mtoi * m
def get_view_projection_matrix(context, settings):
"""
Returns view projection matrix.
Projection matrix is either identity if 3d export is selected or
camera projection if a camera or view is selected.
Currently only orthographic projection is used. (Subject to discussion).
"""
cam = settings['projectionThrough']
if cam is None:
mw = mathutils.Matrix()
mw.identity()
elif cam in projectionMapping.keys():
projection = mathutils.Matrix.OrthoProjection(projectionMapping[cam], 4)
mw = projection
else: # get camera with given name
c = context.scene.objects[cam]
mw = getCameraMatrix(c)
return mw
def z_up_matrix(n):
"""Get a rotation matrix that aligns given vector upwards."""
b = n.xy.length
l = n.length
if b > 0:
return M.Matrix((
(n.x*n.z/(b*l), n.y*n.z/(b*l), -b/l),
(-n.y/b, n.x/b, 0),
(0, 0, 0)
))
else:
# no need for rotation
return M.Matrix((
(1, 0, 0),
(0, (-1 if n.z < 0 else 1), 0),
(0, 0, 0)
))
def finalize_islands(self, is_landscape=False, title_height=0):
for island in self.islands:
if title_height:
island.title = "[{}] {}".format(island.abbreviation, island.label)
points = list(vertex.co for vertex in island.verts) + island.fake_verts
angle = M.geometry.box_fit_2d(points)
rot = M.Matrix.Rotation(angle, 2)
# ensure that the island matches page orientation (portrait/landscape)
dimensions = M.Vector(max(r * v for v in points) - min(r * v for v in points) for r in rot)
if dimensions.x > dimensions.y != is_landscape:
rot = M.Matrix.Rotation(angle + pi / 2, 2)
for point in points:
# note: we need an in-place operation, and Vector.rotate() seems to work for 3d vectors only
point[:] = rot * point
for marker in island.markers:
marker.rot = rot * marker.rot
bottom_left = M.Vector((min(v.x for v in points), min(v.y for v in points) - title_height))
for point in points:
point -= bottom_left
island.bounding_box = M.Vector((max(v.x for v in points), max(v.y for v in points)))
def execute(self, context):
bpy.ops.object.parent_set(type='BONE')
if bpy.context.active_bone.parent:
to_parent_matrix = bpy.context.active_bone.parent.matrix_local
else:
to_parent_matrix = Matrix()
from_parent_matrix, bone_matrix = bpy.context.active_bone.RobotEditor.getTransform()
armature_matrix = bpy.context.active_object.matrix_basis
# find selected physics frame
for ob in bpy.data.objects:
if ob.select and ob.RobotEditor.tag == 'PHYSICS_FRAME':
frame = ob
print(frame.name)
# frame.matrix_basis = armature_matrix*to_parent_matrix*from_parent_matrix*bone_matrix
# frame.matrix_basis = parent_matrix*armature_matrix*bone_matrix
return {'FINISHED'}
def setup():
global init
if init:
return
init = True
view_matrix = workplane.data.get_view_matrix()
zero = Matrix()
zero.zero()
#print(view_matrix)
if view_matrix != zero:
#print("found matrix display")
global matrix
matrix = view_matrix
enable()
#print ("setup done")
def set_transform_orientation(self, context, transform_orientation):
#print("catching space: " + transform_orientation)
#op.create_orientation doesn't work if nothing is selected, so I missuse the view orientation a bit to cicumvent
use_view = transform_orientation == "VIEW" or transform_orientation.endswith("_EMPTY")
bpy.ops.transform.create_orientation(name=work_plane, use=True, use_view=use_view, overwrite=True)
current = context.space_data.current_orientation
if transform_orientation.startswith("GLOBAL"):
current.matrix = Matrix().to_3x3()
if transform_orientation.startswith("LOCAL"):
active_object = context.active_object
current.matrix = active_object.matrix_world.to_3x3()
return current.matrix
def compute_rest( self ): # called after rebuild_tree, recursive roots to leaves
if self.parent:
inverseParentMatrix = self.parent.inverse_total_trans
elif self.fixUpAxis:
inverseParentMatrix = self.flipMat
else:
inverseParentMatrix = mathutils.Matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)))
#self.ogre_rest_matrix = self.skeleton.object_space_transformation * self.matrix # ALLOW ROTATION?
self.ogre_rest_matrix = self.matrix.copy()
# store total inverse transformation
self.inverse_total_trans = self.ogre_rest_matrix.inverted()
# relative to OGRE parent bone origin
self.ogre_rest_matrix = inverseParentMatrix * self.ogre_rest_matrix
self.inverse_ogre_rest_matrix = self.ogre_rest_matrix.inverted()
# recursion
for child in self.children:
child.compute_rest()
def apply(self, bone, json_obj, MhNoLocation):
# the dots in collada exported bone names are replaced with '_', check for data with that changed back
name = bone.name.replace("_", ".") if not self.haveDots else bone.name
if name in json_obj.data:
bone.matrix = Matrix(json_obj.data[name])
if MhNoLocation:
bone.location[0] = 0
bone.location[1] = 0
bone.location[2] = 0
# this operation every bone causes all matrices to be applied in one run
bpy.ops.pose.select_all(action='SELECT')
else:
print(name + ' bone not found coming from MH')
camera-calibration-pvr.py 文件源码
项目:camera-calibration-pvr
作者: mrossini-ethz
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def get_vertical_mode_matrix(is_vertical, camera_rotation):
if is_vertical:
# Get the up direction of the camera
up_vec = mathutils.Vector((0.0, 1.0, 0.0))
up_vec.rotate(camera_rotation)
# Decide around which axis to rotate
vert_mode_rotate_x = abs(up_vec[0]) < abs(up_vec[1])
# Create rotation matrix
if vert_mode_rotate_x:
vert_angle = pi / 2 if up_vec[1] > 0 else -pi / 2
return mathutils.Matrix().Rotation(vert_angle, 3, "X")
else:
vert_angle = pi / 2 if up_vec[0] < 0 else -pi / 2
return mathutils.Matrix().Rotation(vert_angle, 3, "Y")
else:
return mathutils.Matrix().Identity(3)
def change_coordsys(self, fromTM, toTM):
"""
move shape fromTM into toTM coordsys
"""
dp = (toTM.inverted() * fromTM.translation).to_2d()
da = toTM.row[1].to_2d().angle_signed(fromTM.row[1].to_2d())
ca = cos(da)
sa = sin(da)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
for s in self.segs:
tp = (rM * s.p0) - s.p0 + dp
s.rotate(da)
s.translate(tp)
def mouse_hover_wall(self, context, event):
"""
convert mouse pos to matrix at bottom of surrounded wall, y oriented outside wall
"""
res, pt, y, i, o, tM = self.mouse_to_scene_raycast(context, event)
if res and o.data is not None and 'archipack_wall2' in o.data:
z = Vector((0, 0, 1))
d = o.data.archipack_wall2[0]
y = -y
pt += (0.5 * d.width) * y.normalized()
x = y.cross(z)
return True, Matrix([
[x.x, y.x, z.x, pt.x],
[x.y, y.y, z.y, pt.y],
[x.z, y.z, z.z, o.matrix_world.translation.z],
[0, 0, 0, 1]
]), o, y
return False, Matrix(), None, Vector()
def change_coordsys(self, fromTM, toTM):
"""
move shape fromTM into toTM coordsys
"""
dp = (toTM.inverted() * fromTM.translation).to_2d()
da = toTM.row[1].to_2d().angle_signed(fromTM.row[1].to_2d())
ca = cos(da)
sa = sin(da)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
for s in self.segs:
tp = (rM * s.p0) - s.p0 + dp
s.rotate(da)
s.translate(tp)
def relocate_child(self, context, o, g, child):
d = archipack_roof.datablock(child)
if d is not None and d.t_part - 1 < len(g.segs):
# print("relocate_child(%s)" % (child.name))
seg = g.segs[d.t_part]
# adjust T part matrix_world from parent
# T part origin located on parent axis
# with y in parent direction
t = (d.t_dist_x / seg.length)
x, y, z = seg.lerp(t).to_3d()
dy = -seg.v.normalized()
child.matrix_world = o.matrix_world * Matrix([
[dy.x, -dy.y, 0, x],
[dy.y, dy.x, 0, y],
[0, 0, 1, z],
[0, 0, 0, 1]
])
def rotate(self, idx_from, a):
"""
apply rotation to all following segs
"""
self.segs[idx_from].rotate(a)
ca = cos(a)
sa = sin(a)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
# rotation center
p0 = self.segs[idx_from].p0
for i in range(idx_from + 1, len(self.segs)):
seg = self.segs[i]
# rotate seg
seg.rotate(a)
# rotate delta from rotation center to segment start
dp = rM * (seg.p0 - p0)
seg.translate(dp)
def rotate(self, idx_from, a):
"""
apply rotation to all following segs
"""
self.segs[idx_from].rotate(a)
ca = cos(a)
sa = sin(a)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
# rotation center
p0 = self.segs[idx_from].p0
for i in range(idx_from + 1, len(self.segs)):
seg = self.segs[i]
seg.rotate(a)
dp = rM * (seg.p0 - p0)
seg.translate(dp)
def change_coordsys(self, fromTM, toTM):
"""
move shape fromTM into toTM coordsys
"""
dp = (toTM.inverted() * fromTM.translation).to_2d()
da = toTM.row[1].to_2d().angle_signed(fromTM.row[1].to_2d())
ca = cos(da)
sa = sin(da)
rM = Matrix([
[ca, -sa],
[sa, ca]
])
for s in self.segs:
tp = (rM * s.p0) - s.p0 + dp
s.rotate(da)
s.translate(tp)
def create(self, context):
curve = context.active_object
for spline in curve.data.splines:
bpy.ops.archipack.wall2(auto_manipulate=self.auto_manipulate)
o = context.scene.objects.active
d = archipack_wall2.datablock(o)
d.from_spline(curve.matrix_world, 12, spline)
if spline.type == 'POLY':
pt = spline.points[0].co
elif spline.type == 'BEZIER':
pt = spline.bezier_points[0].co
else:
pt = Vector((0, 0, 0))
# pretranslate
o.matrix_world = curve.matrix_world * Matrix([
[1, 0, 0, pt.x],
[0, 1, 0, pt.y],
[0, 0, 1, pt.z],
[0, 0, 0, 1]
])
return o
# -----------------------------------------------------
# Execute
# -----------------------------------------------------
def get_proj_matrix(self, part, t, nose_y):
# a matrix to project verts
# into uv space for horizontal parts of this step
# so uv = (rM * vertex).to_2d()
tl = t - nose_y / self.get_length("LEFT")
tr = t - nose_y / self.get_length("RIGHT")
t2, part, dz, shape = self.get_part(tl, "LEFT")
p0 = part.lerp(t2)
t2, part, dz, shape = self.get_part(tr, "RIGHT")
p1 = part.lerp(t2)
v = (p1 - p0).normalized()
return Matrix([
[-v.y, v.x, 0, p0.x],
[v.x, v.y, 0, p0.y],
[0, 0, 1, 0],
[0, 0, 0, 1]
]).inverted()