def ResetControllers(self):
if self._bone is not None:
if self._bone.parent.fget() is not None:
m = mathutils.Euler((), 'XYZ')
# m.x_rotation = self.f.rx
# m.y_rotation = self.f.ry
# m.z_rotation = self.f.rz
#
self._bone.scale = mathutils.Vector((0,0,0)) # -- resets animations
self._eulerController = m
self._bone.rotation = m
pos = mathutils.Vector((0,0,0))
#pos.x_position = self.f.t.x
# pos.y_position = self.f.t.y
# pos.z_position = self.f.t.z
self._bone.position.controller = pos
for child in self.children:
child.ResetControllers()
python类Euler()的实例源码
def RotateAroundWorld(self, obj, rotation): # XCX used?
print(rotation, type(rotation))
origParent = obj.parent
d = bpy.data.new('UTEMP_PL', None)
d.location = Vector((0,0,0))
obj.parent = d
d.rotation_euler = Euler(rotation, 'XYZ')
act_bk = bpy.ops.active
bpy.ops.active = d
bpy.ops.object.transform_apply(rotation=True)
bpy.ops.active = obj
bpy.ops.object.transform_apply(rotation=True)
bpy.ops.active = act_bk
obj.parent = None
bpy.data.objects.remove(d)
# --delete d
# --if (origParent != undefined) then
# -- obj.parent = origParent
def get_rotated_pt(piv_co, ang_diff_rad, rot_dat, mov_co):
axis_lk = rot_dat.axis_lk
mov_aligned = mov_co - piv_co
rot_val = []
if axis_lk == '': # arbitrary axis / spherical rotations
rot_val = Quaternion(rot_dat.piv_norm, ang_diff_rad)
elif axis_lk == 'X':
rot_val = Euler((ang_diff_rad, 0.0, 0.0), 'XYZ')
elif axis_lk == 'Y':
rot_val = Euler((0.0, ang_diff_rad, 0.0), 'XYZ')
elif axis_lk == 'Z':
rot_val = Euler((0.0, 0.0, ang_diff_rad), 'XYZ')
mov_aligned.rotate(rot_val)
return mov_aligned + piv_co
# Takes a ref_pts (ReferencePoints class) argument and modifies its member
# variable lp_ls (lock pt list). The lp_ls variable is assigned a modified list
# of 3D coordinates (if an axis lock was provided), the contents of the
# ref_pts' rp_ls var (if no axis lock was provided), or an empty list (if there
# wasn't enough ref_pts or there was a problem creating the modified list).
# todo : move inside ReferencePoints class ?
def text(self, en, scene, name):
"""
en: dxf entity
name: ignored; exists to make separate and merged objects methods universally callable from _call_types()
Returns a new single line text object.
"""
if self.import_text:
name = en.text[:8]
d = bpy.data.curves.new(name, "FONT")
d.body = en.plain_text()
d.size = en.height
o = bpy.data.objects.new(name, d)
o.rotation_euler = Euler((0, 0, radians(en.rotation)), 'XYZ')
basepoint = self.proj(en.basepoint) if hasattr(en, "basepoint") else self.proj((0, 0, 0))
o.location = self.proj((en.insert)) + basepoint
if hasattr(en, "thickness"):
et = en.thickness / 2
d.extrude = abs(et)
if et > 0:
o.location.z += et
elif et < 0:
o.location.z -= et
return o
def get_math_data():
from mathutils import Matrix, Vector, Quaternion, Euler
locals = console_namespace()
if not locals:
return {}
variables = {}
for key, var in locals.items():
if key[0] == "_" or not var:
continue
if type(var) in {Matrix, Vector, Quaternion, Euler} or \
type(var) in {tuple, list} and is_display_list(var):
variables[key] = type(var)
return variables
def build(self, buildRequest):
t = time.time()
rotDiff = random.uniform(self.settings["minRandRot"],
self.settings["maxRandRot"])
eul = mathutils.Euler(buildRequest.rot, 'XYZ')
eul.rotate_axis('Z', math.radians(rotDiff))
scaleDiff = random.uniform(self.settings["minRandSz"],
self.settings["maxRandSz"])
newScale = buildRequest.scale * scaleDiff
buildRequest.rot = Vector(eul)
buildRequest.scale = newScale
cm_timings.placement["TemplateRANDOM"] += time.time() - t
cm_timings.placementNum["TemplateRANDOM"] += 1
self.inputs["Template"].build(buildRequest)
camera-calibration-pvr.py 文件源码
项目:camera-calibration-pvr
作者: mrossini-ethz
项目源码
文件源码
阅读 40
收藏 0
点赞 0
评论 0
def reconstruct_rectangle(pa, pb, pc, pd, scale, focal):
# Calculate the coordinates of the rectangle in 3d
coords = get_lambda_d(pa, pb, pc, pd, scale, focal)
# Calculate the transformation of the rectangle
trafo = get_transformation(coords[0], coords[1], coords[2], coords[3])
# Reconstruct the rotation angles of the transformation
angles = get_rot_angles(trafo[0], trafo[1], trafo[2])
xyz_matrix = mathutils.Euler((angles[0], angles[1], angles[2]), "XYZ")
# Reconstruct the camera position and the corners of the rectangle in 3d such that it lies on the xy-plane
tr = trafo[-1]
cam_pos = apply_transformation([mathutils.Vector((0.0, 0.0, 0.0))], tr, xyz_matrix)[0]
corners = apply_transformation(coords, tr, xyz_matrix)
# Printout for debugging
print("Focal length:", focal)
print("Camera rotation:", degrees(angles[0]), degrees(angles[1]), degrees(angles[2]))
print("Camera position:", cam_pos)
length = (coords[0] - coords[1]).length
width = (coords[0] - coords[3]).length
size = max(length, width)
print("Rectangle length:", length)
print("Rectangle width:", width)
print("Rectangle corners:", corners)
return (cam_pos, xyz_matrix, corners, size)
def text(self, en, scene, name):
"""
en: dxf entity
name: ignored; exists to make separate and merged objects methods universally callable from _call_types()
Returns a new single line text object.
"""
if self.import_text:
name = en.text[:8]
d = bpy.data.curves.new(name, "FONT")
d.body = en.plain_text()
d.size = en.height
o = bpy.data.objects.new(name, d)
o.rotation_euler = Euler((0, 0, radians(en.rotation)), 'XYZ')
basepoint = self.proj(en.basepoint) if hasattr(en, "basepoint") else self.proj((0, 0, 0))
o.location = self.proj((en.insert)) + basepoint
if hasattr(en, "thickness"):
et = en.thickness / 2
d.extrude = abs(et)
if et > 0:
o.location.z += et
elif et < 0:
o.location.z -= et
return o
def blender_make_deform_object_from_self(self):
"""
Make blender Lattice object from Lattice object. Only available during
call to Blender.
"""
rot = self.rot
# Make blender lattice object
latt = create_lattice(partitions=self.part, interp=self.interp)
latt.location = Vector(self.center)
latt.scale = Vector(self.scale)
if rot is not None:
vec = Vector(rot['vec'])
mat = Matrix.Rotation(rot['angle'], 3, vec)
latt.rotation_euler = mat.to_euler()
#latt.rotation_euler = Euler (self.rot, 'XYZ')
self.blend_objs.deform_obj = latt
self.blend_objs.deform_type = 'LATTICE'
self.blend_objs.mesh_obj = create_mesh_object('LATTICE', self.nodes)
return ( latt )
def getRotatedPoint(PivC,angleDiffRad,rotDat,movCo):
axisLk = rotDat.axisLk
vecTmp = movCo - PivC
rotVal = []
if axisLk == '': # arbitrary axis / spherical rotations
rotVal = Quaternion(rotDat.pivNorm, angleDiffRad)
elif axisLk == 'X':
rotVal = Euler((angleDiffRad,0.0,0.0), 'XYZ')
elif axisLk == 'Y':
rotVal = Euler((0.0,angleDiffRad,0.0), 'XYZ')
elif axisLk == 'Z':
rotVal = Euler((0.0,0.0,angleDiffRad), 'XYZ')
vecTmp.rotate(rotVal)
return vecTmp + PivC
# Finds out whether rotDat.newAngR or negative rotDat.newAngR will
# result in desired rotation angle.
# angleEq_0_180 for 0 and 180 degree starting rotations
def getRotatedPoint(PivC,angleDiffRad,rotDat,movCo):
axisLk = rotDat.axisLk
vecTmp = movCo - PivC
rotVal = []
if axisLk == '': # arbitrary axis / spherical rotations
rotVal = Quaternion(rotDat.pivNorm, angleDiffRad)
elif axisLk == 'X':
rotVal = Euler((angleDiffRad,0.0,0.0), 'XYZ')
elif axisLk == 'Y':
rotVal = Euler((0.0,angleDiffRad,0.0), 'XYZ')
elif axisLk == 'Z':
rotVal = Euler((0.0,0.0,angleDiffRad), 'XYZ')
vecTmp.rotate(rotVal)
return vecTmp + PivC
# Finds out whether rotDat.newAngR or negative rotDat.newAngR will
# result in desired rotation angle.
# angleEq_0_180 for 0 and 180 degree starting rotations
def get_bone_angle(armature,bone,relative=True):
loc, rot, scale = get_bone_matrix(armature,bone,relative).decompose()
compat_euler = Euler((0.0,0.0,math.pi),"XYZ")
angle = -rot.to_euler().z # negate angle to fit dragonbones angle
return round(math.degrees(angle),2)
def clear_pose(obj):
if obj.type == "ARMATURE":
for bone in obj.pose.bones:
bone.scale = Vector((1,1,1))
bone.location = Vector((0,0,0))
bone.rotation_euler = Euler((0,0,0),"XYZ")
bone.rotation_quaternion = Euler((0,0,0),"XYZ").to_quaternion()
elif obj.type == "MESH":
obj.coa_sprite_frame = 0
obj.coa_alpha = 1.0
obj.coa_modulate_color = (1.0,1.0,1.0)
obj["coa_slot_index"] = max(0,len(obj.coa_slot)-1)
#obj["coa_slot_index"] = obj.coa_slot_reset_index
#obj.coa_slot_index = obj.coa_slot_reset_index
def set_action(context,item=None):
sprite_object = get_sprite_object(context.active_object)
if item == None:
item = sprite_object.coa_anim_collections[sprite_object.coa_anim_collections_index]
children = get_children(context,sprite_object,ob_list=[])
for child in children:
clear_pose(child)
if child.animation_data != None:
child.animation_data.action = None
if child.type == "ARMATURE" and item.name == "Restpose":
for bone in child.pose.bones:
bone.scale = Vector((1,1,1))
bone.location = Vector((0,0,0))
bone.rotation_euler = Euler((0,0,0),"XYZ")
bone.rotation_quaternion = Euler((0,0,0),"XYZ").to_quaternion()
if child.type == "MESH" and item.name == "Restpose":
child.coa_sprite_frame = 0
child.coa_alpha = 1.0
child.coa_modulate_color = (1.0,1.0,1.0)
#child["coa_slot_index"] = len(child.coa_slot)-1#child.coa_slot_reset_index
#print(child["coa_slot_index"])
elif not (child.type == "MESH" and item.name == "Restpose") and context.scene.coa_nla_mode == "ACTION":
action_name = item.name + "_" + child.name
action = None
if action_name in bpy.data.actions:
action = bpy.data.actions[action_name]
if action != None:
action.use_fake_user = True
if child.animation_data == None:
child.animation_data_create()
child.animation_data.action = action
context.scene.frame_set(context.scene.frame_current)
context.scene.update()
def GenerateCracks(pPointNumber, pChildProba, pX, pY, pVector, pAngle,
pShortAngle, pLengthAtt, pProbaAtt, pBaseRadius):
lCrackPointList = []
x = pX
y = pY
z = 0
vec = pVector
for lCurrentPoint in range(pPointNumber):
lNewPointCrack = CrackPoint()
lNewPointCrack.x = x
lNewPointCrack.y = y
lNewPointCrack.z = z
lNewPointCrack.position = lCurrentPoint
lNewPointCrack.hasChildren = DefineProba(pChildProba)
lRadius = DefineCurveRadius(lCurrentPoint, pPointNumber,
lNewPointCrack.hasChildren,
pBaseRadius)
if lNewPointCrack.hasChildren:
lLen = int(pPointNumber / pLengthAtt)
lNewProba = pChildProba / pProbaAtt
lNewPointCrack.children = GenerateCracks(lLen, lNewProba,
x, y, pVector, pAngle,
pShortAngle,
pLengthAtt, pProbaAtt,
lRadius)
lNewPointCrack.radius = lRadius
lCrackPointList.append(lNewPointCrack)
if lCurrentPoint % 5:
angle = random.uniform(-pShortAngle, pShortAngle)
else:
angle = random.uniform(-pAngle, pAngle)
eul = mathutils.Euler((0.0, 0.0, math.radians(angle)), 'XYZ')
vec.rotate(eul)
x = x + vec.x
y = y + vec.y
z = z + vec.z
return lCrackPointList
def FrameMatrix(f):
t = Matrix.Translation(Vector((f.t.x, f.t.y, f.t.z)))
# s = Matrix.Scale
r = Euler((f.rx, f.ry, f.rz), 'XYZ').to_matrix().to_4x4()
res = t*r
return res
def pyaw(ary):
rv3d = bpy.context.window_manager.windows[0].screen.areas[1].spaces[0].region_3d
rv3d.view_rotation.rotate(mathutils.Euler(( float(ary[2]) , 0 , float(ary[1]) ))) #pitch roll
#yaw = ob.rotation_euler.z
#pitch = ob.rotation_euler.y
#roll = ob.rotation_euler.x
def roll(ary):
rv3d = bpy.context.window_manager.windows[0].screen.areas[1].spaces[0].region_3d
rv3d.view_rotation.rotate(mathutils.Euler(( 0 , float(ary[1]) , 0 ))) #pitch roll
def createObjects(tree, parent=None, objectname=None, probability=0.5, size=0.5, randomsize=0.1, randomrot=0.1, maxconnections=2, bunchiness=1.0):
if (parent is None) or (objectname is None) or (objectname == 'None'):
return
# not necessary, we parent the new objects: p=bpy.context.scene.cursor_location
theobject = bpy.data.objects[objectname]
t = gauss(1.0 / probability, 0.1)
bpswithleaves = 0
for bp in tree.branchpoints:
if bp.connections < maxconnections:
dv = tree.branchpoints[bp.parent].v - bp.v if bp.parent else Vector((0, 0, 0))
dvp = Vector((0, 0, 0))
bpswithleaves += 1
nleavesonbp = 0
while t < bpswithleaves:
nleavesonbp += 1
rx = (random() - 0.5) * randomrot * 6.283 # TODO vertical tilt in direction of tropism
ry = (random() - 0.5) * randomrot * 6.283
rot = Euler((rx, ry, random() * 6.283), 'ZXY')
scale = size + (random() - 0.5) * randomsize
# add new object and parent it
obj = bpy.data.objects.new(objectname, theobject.data)
obj.location = bp.v + dvp
obj.rotation_mode = 'ZXY'
obj.rotation_euler = rot[:]
obj.scale = [scale, scale, scale]
obj.parent = parent
bpy.context.scene.objects.link(obj)
t += gauss(1.0 / probability, 0.1) # this is not the best choice of distribution because we might get negative values especially if sigma is large
dvp = nleavesonbp * (dv / (probability ** bunchiness)) # TODO add some randomness to the offset
def _vrot(r, ran, rotx, var2, roty, rotz):
seed(ran + r)
return Euler((radians(rotx) + gauss(0, var2 / 3),
radians(roty) + gauss(0, var2 / 3),
radians(rotz) + gauss(0, var2 / 3)), 'XYZ')
def getTransformFromParent(self):
rot = Euler((radians(self.alpha.value), radians(self.beta.value),
radians(self.gamma.value)), 'XYZ').to_matrix()
rot.resize_4x4()
transl = Matrix.Translation((self.x.value, self.y.value, self.z.value))
# print("here",transl * rot)
return transl * rot
def getTransformFromParent(self):
alphaMatrix = Euler((radians(self.alpha.value), 0, 0),
'XYZ').to_matrix()
alphaMatrix.resize_4x4()
thetaMatrix = Euler((0, 0, radians(self.theta.value)),
'XYZ').to_matrix()
thetaMatrix.resize_4x4()
translation = Matrix.Translation((self.a.value, 0, self.d.value, 1))
return translation * alphaMatrix * thetaMatrix
def calcRelativeTarget(self, pathEntry, lookahead):
context = bpy.context
pathObject = pathEntry.objectName
radius = pathEntry.radius
laneSep = pathEntry.laneSeparation
isDirectional = pathEntry.mode == "directional"
revDirec = pathEntry.revDirec if isDirectional else None
kd, bm, pathMatrixInverse, rotation = self.calcPathData(pathObject,
revDirec)
vel = self.sim.agents[self.userid].globalVelocity * lookahead
if vel.x == 0 and vel.y == 0 and vel.z == 0:
vel = Vector((0, lookahead, 0))
vel.rotate(bpy.context.scene.objects[self.userid].rotation_euler)
vel = vel * rotation
co_find = pathMatrixInverse * \
context.scene.objects[self.userid].location
co, index, dist = kd.find(co_find)
offset = self.followPath(bm, co, index, vel, co_find, radius, laneSep,
isDirectional, pathEntry)
offset = offset * pathMatrixInverse
eul = Euler(
[-x for x in context.scene.objects[self.userid].rotation_euler], 'ZYX')
offset.rotate(eul)
return offset
def build(self, buildRequest):
t = time.time()
placePos = Vector(buildRequest.pos)
diffRow = Vector((self.settings["ArrayRowMargin"], 0, 0))
diffCol = Vector((0, self.settings["ArrayColumnMargin"], 0))
diffRow.rotate(mathutils.Euler(buildRequest.rot))
diffCol.rotate(mathutils.Euler(buildRequest.rot))
diffRow *= buildRequest.scale
diffCol *= buildRequest.scale
number = self.settings["noToPlace"]
rows = self.settings["ArrayRows"]
cm_timings.placement["TemplateFORMATION"] += time.time() - t
cm_timings.placementNum["TemplateFORMATION"] += 1
for fullcols in range(number // rows):
for row in range(rows):
newBuildRequest = buildRequest.copy()
newBuildRequest.pos = placePos + fullcols * diffCol + row * diffRow
self.inputs["Template"].build(newBuildRequest)
for leftOver in range(number % rows):
newBuild = buildRequest.copy()
newBuild.pos = placePos + \
(number // rows) * diffCol + leftOver * diffRow
self.inputs["Template"].build(newBuild)
def _vrot(r, ran, rotx, var2, roty, rotz):
random.seed(ran + r)
return Euler((radians(rotx) + random.gauss(0, var2 / 3), \
radians(roty) + random.gauss(0, var2 / 3), \
radians(rotz) + random.gauss(0, var2 / 3)), 'XYZ')
def __init__(self):
ParameterCell.__init__(self)
self.armature = None
self.bone_name = None
self._prev_armature = LogicNetworkCell.NO_VALUE
self._prev_bone = LogicNetworkCell.NO_VALUE
self._channel = None
self._pos = mathutils.Vector((0,0,0))
self._rot = mathutils.Euler((0,0,0), "XYZ")
self._sca = mathutils.Vector((0,0,0))
self.XYZ_POS = LogicNetworkSubCell(self, self._get_pos)
self.XYZ_ROT = LogicNetworkSubCell(self, self._get_rot)
self.XYZ_SCA = LogicNetworkSubCell(self, self._get_sca)
def __init__(self):
ParameterCell.__init__(self)
self.source_matrix = None
self.input_x = None
self.input_y = None
self.input_z = None
self.OUTX = LogicNetworkSubCell(self, self.get_out_x)
self.OUTY = LogicNetworkSubCell(self, self.get_out_y)
self.OUTZ = LogicNetworkSubCell(self, self.get_out_z)
self.OUTEULER = LogicNetworkSubCell(self, self.get_out_euler)
self._matrix = mathutils.Matrix.Identity(3)
self._eulers = mathutils.Euler((0,0,0), "XYZ")
pass
def __init__(self):
ActionCell.__init__(self)
self.condition = None
self.armature = None
self.bone_name = None
self.set_translation = None
self.set_orientation = None
self.set_scale = None
self.translate = None
self.rotate = None
self.scale = None
self._eulers = mathutils.Euler((0,0,0), "XYZ")
self._vector = mathutils.Vector((0,0,0))
def __init__(self):
ActionCell.__init__(self)
self.condition = None
self.sound = None
self.loop_count = None
self.location = None
self.orientation = None
self.velocity = None
self.pitch = None
self.volume = None
self.attenuation = None
self.distance_ref = None
self.distance_max = None
self._euler = mathutils.Euler((0,0,0), "XYZ")
self._prev_loop_count = None
def __init__(self):
ActionCell.__init__(self)
self.condition = None
self.sound = None
self.location = None
self.orientation = None
self.velocity = None
self.pitch = None
self.volume = None
self.attenuation = None
self.distance_ref = None
self.distance_max = None
self._euler = mathutils.Euler((0,0,0), "XYZ")