예제 #1
0
def main(moreinfo=True):
    # prompt PMX name
    core.MY_PRINT_FUNC("Please enter name of PMX input file:")
    input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")
    pmx = pmxlib.read_pmx(input_filename_pmx, moreinfo=moreinfo)

    # usually want to add/remove endpoints for many bones at once, so put all this in a loop
    num_changed = 0
    while True:
        core.MY_PRINT_FUNC("")
        # valid input is any string that can matched aginst a bone idx
        s = core.MY_GENERAL_INPUT_FUNC(
            lambda x:
            (morph_scale.get_idx_in_pmxsublist(x, pmx.bones) is not None), [
                "Please specify the target bone: bone #, JP name, or EN name (names are not case sensitive).",
                "Empty input will quit the script."
            ])
        # do it again, cuz the lambda only returns true/false
        target_index = morph_scale.get_idx_in_pmxsublist(s, pmx.bones)

        # when given empty text, done!
        if target_index == -1 or target_index is None:
            core.MY_PRINT_FUNC("quitting")
            break
        target_bone = pmx.bones[target_index]

        # print the bone it found
        core.MY_PRINT_FUNC("Found bone #{}: '{}' / '{}'".format(
            target_index, target_bone.name_jp, target_bone.name_en))

        if target_bone.tail_type:
            core.MY_PRINT_FUNC(
                "Was tailmode 'bonelink', changing to mode 'offset'")
            if target_bone.tail == -1:
                core.MY_PRINT_FUNC(
                    "Error: bone is not linked to anything, skipping")
                continue
            # find the location of the bone currently pointing at
            endpos = pmx.bones[target_bone.tail].pos
            # determine the equivalent offset vector
            offset = [endpos[i] - target_bone.pos[i] for i in range(3)]
            # write it into the bone
            target_bone.tail_type = False
            target_bone.tail = offset
            # done unlinking endpoint!
            pass

        else:
            core.MY_PRINT_FUNC(
                "Was tailmode 'offset', changing to mode 'bonelink' and adding new endpoint bone"
            )
            if target_bone.tail == [0, 0, 0]:
                core.MY_PRINT_FUNC(
                    "Error: bone has offset of [0,0,0], skipping")
                continue
            # determine the position of the new endpoint bone
            endpos = [
                target_bone.pos[i] + target_bone.tail[i] for i in range(3)
            ]
            # create the new bone
            newbone = pmxstruct.PmxBone(
                name_jp=target_bone.name_jp + endpoint_suffix_jp,
                name_en=target_bone.name_en + endpoint_suffix_en,
                pos=endpos,
                parent_idx=target_index,
                deform_layer=target_bone.deform_layer,
                deform_after_phys=target_bone.deform_after_phys,
                has_rotate=False,
                has_translate=False,
                has_visible=False,
                has_enabled=True,
                has_ik=False,
                has_localaxis=False,
                has_fixedaxis=False,
                has_externalparent=False,
                inherit_rot=False,
                inherit_trans=False,
                tail_type=True,
                tail=-1)
            # set the target to point at the new bone
            target_bone.tail_type = True
            target_bone.tail = len(pmx.bones)
            # append the new bone
            pmx.bones.append(newbone)
            # done adding endpoint!
            pass

        num_changed += 1
        pass

    if num_changed == 0:
        core.MY_PRINT_FUNC("Nothing was changed")
        return None

    core.MY_PRINT_FUNC("")

    # write out
    output_filename_pmx = input_filename_pmx[0:-4] + "_endpoints.pmx"
    output_filename_pmx = core.get_unused_file_name(output_filename_pmx)
    pmxlib.write_pmx(output_filename_pmx, pmx, moreinfo=moreinfo)
    core.MY_PRINT_FUNC("Done!")
    return None
예제 #2
0
def main():
    # copied codes
    core.MY_PRINT_FUNC("Please enter name of PMX model file:")
    input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")

    moreinfo = False

    input_filename_pmx_abs = os.path.normpath(
        os.path.abspath(input_filename_pmx))
    startpath, input_filename_pmx_rel = os.path.split(input_filename_pmx_abs)

    # object
    retme: pmxstruct.Pmx = pmxlib.read_pmx(input_filename_pmx,
                                           moreinfo=moreinfo)

    # since there is an update to Valve Bip tools (I guess?), there is different bone names: the old and new one
    # only prefixes are changed along with order, thus there is a little bit scripting here to find the last leg
    big_dict: dict
    is_old: bool = False

    if "bip_" in retme.bones[0].name_jp:
        big_dict = {
            **old_body_dict,
            **old_arm_dict,
            **old_leg_dict,
            **old_finger_dict
        }
        is_old = True

    else:
        big_dict = {
            **new_body_dict,
            **new_arm_dict,
            **new_leg_dict,
            **new_finger_dict
        }

    # checking for last leg item so the code could be scalable
    last_leg_item: int
    last_leg_name: str
    last_leg_name_cmp_r: str = ""
    last_leg_name_cmp_l: str = ""

    r_l_index: int = 0
    r_k_index: int = 0
    r_a_index: int = 0
    r_t_index: int = 0
    l_l_index: int = 0
    l_k_index: int = 0
    l_a_index: int = 0
    l_t_index: int = 0

    # lol this is a mess but it works just fine okay
    for key in big_dict:
        for index, i in enumerate(retme.bones):
            # usually, the toes are the last parts of the legs, from there, we can interject the IK bones
            if i.name_jp == "bip_toe_R" or i.name_jp == "ValveBiped.Bip01_R_Toe0":
                r_t_index = index
                # last_leg_name_cmp_r = i.name_jp
            elif i.name_jp == "bip_toe_L" or i.name_jp == "ValveBiped.Bip01_L_Toe0":
                l_t_index = index
                # last_leg_name_cmp_l = i.name_jp
            # without this, the pelvis will start as "green"
            elif i.name_jp == "ValveBiped.Bip01_Pelvis" or i.name_jp == "bip_pelvis":
                retme.bones[index].has_translate = False

            elif i.name_jp == "ValveBiped.Bip01_R_Foot" or i.name_jp == "bip_foot_R":
                r_a_index = index
            elif i.name_jp == "ValveBiped.Bip01_L_Foot" or i.name_jp == "bip_foot_L":
                l_a_index = index
            elif i.name_jp == "ValveBiped.Bip01_R_Calf" or i.name_jp == "bip_knee_R":
                r_k_index = index
            elif i.name_jp == "ValveBiped.Bip01_L_Calf" or i.name_jp == "bip_knee_L":
                l_k_index = index
            elif i.name_jp == "ValveBiped.Bip01_R_Thigh" or i.name_jp == "bip_hip_R":
                r_l_index = index
            elif i.name_jp == "ValveBiped.Bip01_L_Thigh" or i.name_jp == "bip_hip_L":
                l_l_index = index

            # the part that replaces texts
            if i.name_jp == key:
                retme.bones[index].name_jp = big_dict[key]

    last_bone = len(retme.bones) - 1
    # if r_t_index > l_t_index:
    #     last_leg_item = r_t_index
    #     last_leg_name = last_leg_name_cmp_r
    # else:
    #     last_leg_item = l_t_index
    #     last_leg_name = last_leg_name_cmp_l
    # # print(f"This is last leg item {old_last_leg_item}")

    # base bone section
    # base order: 上半身, 下半身, 腰 (b_1), グルーブ, センター, 全ての親
    b1_name = "腰"
    b2_name = "グルーブ"
    b3_name = "センター"
    b4_name = "全ての親"

    # IK bone section
    leg_left_ik_name = "左足IK"
    leg_left_toe_ik_name = "左つま先IK"
    leg_right_ik_name = "右足IK"
    leg_right_toe_ik_name = "右つま先IK"

    knee_limit_1 = [-3.1415927410125732, 0.0, 0.0]
    knee_limit_2 = [-0.008726646192371845, 0.0, 0.0]

    # for some reasons, this value will always be the same
    # pelvis_pos = [-4.999999873689376e-06, 38.566917419433594, -0.533614993095398]

    # adding IK and such
    # leg_left_obj = retme.bones[last_leg_item + l_l]
    # leg_left_knee_obj = retme.bones[last_leg_item + l_k]
    leg_left_ankle_obj = retme.bones[l_a_index]
    leg_left_toe_obj = retme.bones[l_t_index]
    # leg_right_obj = retme.bones[last_leg_item + r_l]
    # leg_right_knee_obj = retme.bones[last_leg_item + r_k]
    leg_right_ankle_obj = retme.bones[r_a_index]
    leg_right_toe_obj = retme.bones[r_t_index]

    leg_left_ankle_pos = leg_left_ankle_obj.pos
    leg_left_toe_pos = leg_left_toe_obj.pos
    leg_right_ankle_pos = leg_right_ankle_obj.pos
    leg_right_toe_pos = leg_right_toe_obj.pos

    # toe /// places of some value wont match with the struct /// taken from hololive's korone model
    # name, name, [-0.823277473449707, 0.2155265510082245, -1.8799238204956055], 112, 0, False,
    # True, True, True, True,
    # False, [0.0, -1.3884940147399902, 1.2653569569920364e-07] /// This is offset, False, False, None,
    # None, False, None, False, None, None, False, None, True,
    # 111, 160, 1.0, [[110, None, None]]

    # leg
    # 右足IK, en_name, [-0.8402935862541199, 1.16348397731781, 0.3492986857891083], 0, 0, False,
    # True, True, True, True,
    # False, [0.0, -2.53071505085245e-07, 1.3884940147399902], False, False, None,
    # None, False, None, False, None, None, False, None, True,
    # 110, 85, 1.9896754026412964, [[109, [-3.1415927410125732, 0.0, 0.0], [-0.008726646192371845, 0.0, 0.0]]
    # /// These ik_links are in radians /// , [108, None, None]]
    # if name == "ValveBiped.Bip01_R_Toe0":
    #     retme.bones.insert(last_leg_item + 1, )

    leg_left_ik_obj = pmxstruct.PmxBone(
        leg_left_ik_name, "", leg_left_ankle_pos, last_bone + 5, 0, False,
        True, True, True, True, True, False, [0.0, 0.0, 0.0], False, False,
        False, False, False, None, None, None, None, None, None, l_a_index, 40,
        114.5916,
        [[l_k_index, knee_limit_1, knee_limit_2], [l_l_index, None, None]])
    retme.bones.insert(last_bone + 1, leg_left_ik_obj)

    leg_left_toe_ik_obj = pmxstruct.PmxBone(
        leg_left_toe_ik_name, "", leg_left_toe_pos, last_bone + 1, 0, False,
        True, True, True, True, True, False, [0, 0, 0], False, False, False,
        False, False, None, None, None, None, None, None, l_t_index, 3,
        229.1831, [[l_a_index, None, None]])
    retme.bones.insert(last_bone + 2, leg_left_toe_ik_obj)

    leg_right_ik_obj = pmxstruct.PmxBone(
        leg_right_ik_name, "", leg_right_ankle_pos, last_bone + 5, 0, False,
        True, True, True, True, True, False, [0.0, 0.0, 0.0], False, False,
        False, False, False, None, None, None, None, None, None, r_a_index, 40,
        114.5916,
        [[r_k_index, knee_limit_1, knee_limit_2], [r_l_index, None, None]])
    retme.bones.insert(last_bone + 3, leg_right_ik_obj)

    leg_right_toe_ik_obj = pmxstruct.PmxBone(
        leg_right_toe_ik_name, "", leg_right_toe_pos, last_bone + 3, 0, False,
        True, True, True, True, True, False, [0, 0, 0], False, False, False,
        False, False, None, None, None, None, None, None, r_t_index, 3,
        229.1831, [[r_a_index, None, None]])
    retme.bones.insert(last_bone + 4, leg_right_toe_ik_obj)

    # # base part
    b4_pos = [0, 0, 0]

    # for some reasons, if we pass value from pelvis_pos to b3_pos, pelvis_pos will change as well?
    b3_pos = [-4.999999873689376e-06, 21, -0.533614993095398]
    b2_pos = b3_pos
    b1_pos = [-4.999999873689376e-06, 32, -0.533614993095398]
    #
    # # 全ての親, name_en, [0.0, 0.0, -0.4735046625137329], -1, 0, False,
    # # True, True, True, True,
    # # False, [0.0, 0.0, 0.0], False, False, None,
    # # None, False, None, False, None, None, False, None, False,
    # # None, None, None, None
    #
    # # base order: 上半身, 下半身, 腰 (b_1), グルーブ, センター, 全ての親
    # # the parents would be fixed later
    b4_obj = pmxstruct.PmxBone(b4_name, "", b4_pos, -1, 0, False, True, True,
                               True, True, False, False, [0, 0, 0], False,
                               False, None, None, False, None, None, None,
                               None, None, None, None, None, None, None)
    retme.bones.insert(last_bone + 5, b4_obj)

    b3_obj = pmxstruct.PmxBone(b3_name, "", b3_pos, last_bone + 5, 0, False,
                               True, True, True, True, False, False, [0, 0, 0],
                               False, False, None, None, False, None, None,
                               None, None, None, None, None, None, None, None)
    retme.bones.insert(last_bone + 6, b3_obj)

    b2_obj = pmxstruct.PmxBone(b2_name, "", b2_pos, last_bone + 6, 0, False,
                               True, True, True, True, False, False, [0, 0, 0],
                               False, False, None, None, False, None, None,
                               None, None, None, None, None, None, None, None)
    retme.bones.insert(last_bone + 7, b2_obj)

    b1_obj = pmxstruct.PmxBone(b1_name, "", b1_pos, last_bone + 7, 0, False,
                               True, False, True, True, False, False,
                               [0, 0, 0], False, False, None, None, False,
                               None, None, None, None, None, None, None, None,
                               None, None)
    retme.bones.insert(last_bone + 8, b1_obj)

    output_filename_pmx = input_filename_pmx[0:-4] + "_sourcetrans.pmx"
    pmxlib.write_pmx(output_filename_pmx, retme, moreinfo=moreinfo)
예제 #3
0
def main(moreinfo=True):
    # prompt PMX name
    core.MY_PRINT_FUNC("Please enter name of PMX input file:")
    input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")
    # input_filename_pmx = "../../python_scripts/grasstest_better.pmx"
    pmx = pmxlib.read_pmx(input_filename_pmx, moreinfo=moreinfo)

    ##################################
    # user flow:
    # first ask whether they want to add armtwist, yes/no
    # second ask whether they want to add legtwist, yes/no
    # then do it
    # then write out to file
    ##################################

    working_queue = []

    s = core.MY_SIMPLECHOICE_FUNC((1, 2), [
        "Do you wish to add magic twistbones to the ARMS?", "1 = Yes, 2 = No"
    ])
    if s == 1:
        # add upperarm set and lowerarm set to the queue
        working_queue.append(armset)
        working_queue.append(wristset)
        pass
    s = core.MY_SIMPLECHOICE_FUNC((1, 2), [
        "Do you wish to add magic twistbones to the LEGS?", "1 = Yes, 2 = No"
    ])
    if s == 1:
        # TODO detect whether d-bones exist or not
        # add legs or d-legs set to the queue
        pass

    if not working_queue:
        core.MY_PRINT_FUNC("Nothing was changed")
        core.MY_PRINT_FUNC("Done")
        return None

    # for each set in the queue,
    for boneset in working_queue:
        # boneset = (start, end, preferred, oldrigs, bezier)
        for side in [jp_l, jp_r]:
            # print(side)
            # print(boneset)
            # 1. first, validate that start/end exist, these are required
            # NOTE: remember to prepend 'side' before all jp names!
            start_jp = side + boneset[0]
            start_idx = core.my_list_search(pmx.bones,
                                            lambda x: x.name_jp == start_jp)
            if start_idx is None:
                core.MY_PRINT_FUNC(
                    "ERROR: standard bone '%s' not found in model, this is required!"
                    % start_jp)
                continue
            end_jp = side + boneset[1]
            end_idx = core.my_list_search(pmx.bones,
                                          lambda x: x.name_jp == end_jp)
            if end_idx is None:
                core.MY_PRINT_FUNC(
                    "ERROR: standard bone '%s' not found in model, this is required!"
                    % end_jp)
                continue

            # 2. determine whether the 'preferredparent' exists and therefore what to acutally use as the parent
            parent_jp = side + boneset[2]
            parent_idx = core.my_list_search(pmx.bones,
                                             lambda x: x.name_jp == parent_jp)
            if parent_idx is None:
                parent_idx = start_idx

            # 3. attempt to collapse known armtwist rig names onto 'parent' so that the base case is further automated
            # for each bonename in boneset[3], if it exists, collapse onto boneidx parent_idx
            for bname in boneset[3]:
                rig_idx = core.my_list_search(
                    pmx.bones, lambda x: x.name_jp == side + bname)
                if rig_idx is None: continue  # if not found, try the next
                # when it is found, what 'factor' do i use?
                # print(side+bname)
                if pmx.bones[rig_idx].inherit_rot and pmx.bones[
                        rig_idx].inherit_parent_idx == parent_idx and pmx.bones[
                            rig_idx].inherit_ratio != 0:
                    # if using partial rot inherit AND inheriting from parent_idx AND ratio != 0, use that
                    # think this is good, if twistbones exist they should be children of preferred
                    f = pmx.bones[rig_idx].inherit_ratio
                elif pmx.bones[rig_idx].parent_idx == parent_idx:
                    # this should be just in case?
                    f = 1
                elif pmx.bones[rig_idx].parent_idx == start_idx:
                    # this should catch magic armtwist bones i previously created
                    f = 1
                else:
                    core.MY_PRINT_FUNC(
                        "Warning, found unusual relationship when collapsing old armtwist rig, assuming ratio=1"
                    )
                    f = 1
                transfer_bone_weights(pmx, parent_idx, rig_idx, f)
                pass
            # also collapse 'start' onto 'preferredparent' if it exists... want to transfer weight from 'arm' to 'armtwist'
            # if start == preferredparent this does nothing, no harm done
            transfer_bone_weights(pmx, parent_idx, start_idx, scalefactor=1)

            # 4. run the weight-cleanup function
            normalize_weights(pmx)

            # 5. append 3 new bones to end of bonelist
            # 	armYZ gets pos = start pos & parent = start parent
            basename_jp = pmx.bones[start_idx].name_jp
            armYZ_new_idx = len(pmx.bones)
            # armYZ = [basename_jp + yz_suffix, local_translate(basename_jp + yz_suffix)]  # name_jp,en
            # armYZ += pmx[5][start_idx][2:]					# copy the whole rest of the bone
            # armYZ[10:12] = [False, False]					# visible=false, enabled=false
            # armYZ[12:14] = [True, [armYZ_new_idx + 1]]		# tail type = tail, tail pointat = armYZend
            # armYZ[14:19] = [False, False, [], False, []]	# disable partial inherit + fixed axis
            # # local axis is copy
            # armYZ[21:25] = [False, [], False, []]			# disable ext parent + ik
            armYZ = pmxstruct.PmxBone(
                name_jp=basename_jp + yz_suffix,
                name_en=local_translate(basename_jp + yz_suffix),
                pos=pmx.bones[start_idx].pos,
                parent_idx=pmx.bones[start_idx].parent_idx,
                deform_layer=pmx.bones[start_idx].deform_layer,
                deform_after_phys=pmx.bones[start_idx].deform_after_phys,
                has_localaxis=True,
                localaxis_x=pmx.bones[start_idx].localaxis_x,
                localaxis_z=pmx.bones[start_idx].localaxis_z,
                tail_type=True,
                tail=armYZ_new_idx + 1,
                has_rotate=True,
                has_translate=True,
                has_visible=False,
                has_enabled=True,
                has_ik=False,
                inherit_rot=False,
                inherit_trans=False,
                has_fixedaxis=False,
                has_externalparent=False,
            )

            # 	armYZend gets pos = end pos & parent = armYZ
            # armYZend = [basename_jp + yz_suffix + "先", local_translate(basename_jp + yz_suffix + "先")]  # name_jp,en
            # armYZend += pmx[5][end_idx][2:]					# copy the whole rest of the bone
            # armYZend[5] = armYZ_new_idx						# parent = armYZ
            # armYZend[10:12] = [False, False]				# visible=false, enabled=false
            # armYZend[12:14] = [True, [-1]]					# tail type = tail, tail pointat = none
            # armYZend[14:19] = [False, False, [], False, []]	# disable partial inherit + fixed axis
            # # local axis is copy
            # armYZend[21:25] = [False, [], False, []]		# disable ext parent + ik
            armYZend = pmxstruct.PmxBone(
                name_jp=basename_jp + yz_suffix + "先",
                name_en=local_translate(basename_jp + yz_suffix + "先"),
                pos=pmx.bones[end_idx].pos,
                parent_idx=armYZ_new_idx,
                deform_layer=pmx.bones[end_idx].deform_layer,
                deform_after_phys=pmx.bones[end_idx].deform_after_phys,
                has_localaxis=True,
                localaxis_x=pmx.bones[end_idx].localaxis_x,
                localaxis_z=pmx.bones[end_idx].localaxis_z,
                tail_type=True,
                tail=-1,
                has_rotate=True,
                has_translate=True,
                has_visible=False,
                has_enabled=True,
                has_ik=False,
                inherit_rot=False,
                inherit_trans=False,
                has_fixedaxis=False,
                has_externalparent=False,
            )

            # # 	elbowIK gets pos = end pos & parent = end parent
            # armYZIK = [basename_jp + yz_suffix + "IK", local_translate(basename_jp + yz_suffix + "IK")]  # name_jp,en
            # armYZIK += pmx[5][end_idx][2:]					# copy the whole rest of the bone
            # armYZIK[10:12] = [False, False]					# visible=false, enabled=false
            # armYZIK[12:14] = [True, [-1]]					# tail type = tail, tail pointat = none
            # armYZIK[14:19] = [False, False, [], False, []]	# disable partial inherit + fixed axis
            # # local axis is copy
            # armYZIK[21:23] = [False, []]					# disable ext parent
            # armYZIK[23] = True								# ik=true
            # # add the ik info: [target, loops, anglelimit, [[link_idx, []], [link_idx, []]] ]
            # armYZIK[24] = [armYZ_new_idx+1, newik_loops, newik_angle, [[armYZ_new_idx, []]]]
            armYZIK = pmxstruct.PmxBone(
                name_jp=basename_jp + yz_suffix + "IK",
                name_en=local_translate(basename_jp + yz_suffix + "IK"),
                pos=pmx.bones[end_idx].pos,
                parent_idx=pmx.bones[end_idx].parent_idx,
                deform_layer=pmx.bones[end_idx].deform_layer,
                deform_after_phys=pmx.bones[end_idx].deform_after_phys,
                has_localaxis=True,
                localaxis_x=pmx.bones[end_idx].localaxis_x,
                localaxis_z=pmx.bones[end_idx].localaxis_z,
                tail_type=True,
                tail=-1,
                has_rotate=True,
                has_translate=True,
                has_visible=False,
                has_externalparent=False,
                has_enabled=True,
                inherit_rot=False,
                inherit_trans=False,
                has_fixedaxis=False,
                has_ik=True,
                ik_target_idx=armYZ_new_idx + 1,
                ik_numloops=newik_loops,
                ik_angle=newik_angle,
                ik_links=[pmxstruct.PmxBoneIkLink(idx=armYZ_new_idx)])

            # now append them to the bonelist
            pmx.bones.append(armYZ)
            pmx.bones.append(armYZend)
            pmx.bones.append(armYZIK)

            # 6. build the bezier curve
            bezier_curve = core.MyBezier(boneset[4][0],
                                         boneset[4][1],
                                         resolution=50)

            # 7. find relevant verts & determine unbounded percentile for each
            (verts, percentiles,
             centers) = calculate_percentiles(pmx, start_idx, end_idx,
                                              parent_idx)

            if moreinfo:
                core.MY_PRINT_FUNC(
                    "Blending between bones '{}'/'{}'=ZEROtwist and '{}'/'{}'=FULLtwist"
                    .format(armYZ.name_jp, armYZ.name_en,
                            pmx.bones[parent_idx].name_jp,
                            pmx.bones[parent_idx].name_en))
                core.MY_PRINT_FUNC(
                    "   Found %d potentially relevant vertices" % len(verts))

            # 8. use X or Y to choose border points, print for debugging, also scale the percentiles
            # first sort ascending by percentile value
            vert_zip = list(zip(verts, percentiles, centers))
            vert_zip.sort(key=lambda x: x[1])
            verts, percentiles, centers = zip(*vert_zip)  # unzip

            # X. highest point mode
            # "liberal" endpoints: extend as far as i can, include all good stuff even if i include some bad stuff with it
            # start at each end and work inward until i find a vert controlled by only parent_idx
            i_min_liberal = 0
            i_max_liberal = len(verts) - 1
            i_min_conserv = -1
            i_max_conserv = len(verts)
            for i_min_liberal in range(
                    0, len(verts)):  # start at head and work down,
                if pmx.verts[verts[
                        i_min_liberal]].weighttype == 0:  # if the vertex is BDEF1 type,
                    break  # then stop looking,
            p_min_liberal = percentiles[
                i_min_liberal]  # and save the percentile it found.
            for i_max_liberal in reversed(range(
                    0, len(verts))):  # start at tail and work up,
                if pmx.verts[verts[
                        i_max_liberal]].weighttype == 0:  # if the vertex is BDEF1 type,
                    break  # then stop looking,
            p_max_liberal = percentiles[
                i_max_liberal]  # and save the percentile it found.
            # Y. lowest highest point mode
            # "conservative" endpoints: define ends such that no bad stuff exists within bounds, even if i miss some good stuff
            # start in the middle and work outward until i find a vert NOT controlled by only parent_idx, then back off 1
            # where is the middle? use "bisect_left"
            middle = core.bisect_left(percentiles, 0.5)
            for i_min_conserv in reversed(
                    range(middle - 1)):  # start in middle, work toward head,
                if pmx.verts[verts[
                        i_min_conserv]].weighttype != 0:  # if the vertex is NOT BDEF1 type,
                    break  # then stop looking,
            i_min_conserv += 1  # and step back 1 to find the last vert that was good BDEF1,
            p_min_conserv = percentiles[
                i_min_conserv]  # and save the percentile it found.
            for i_max_conserv in range(
                    middle + 1,
                    len(verts)):  # start in middle, work toward tail,
                if pmx.verts[verts[
                        i_max_conserv]].weighttype != 0:  # if the vertex is NOT BDEF1 type,
                    break  # then stop looking,
            i_max_conserv -= 1  # and step back 1 to find the last vert that was good BDEF1,
            p_max_conserv = percentiles[
                i_max_conserv]  # and save the percentile it found.

            foobar = False
            if not (i_min_liberal <= i_min_conserv <= i_max_conserv <=
                    i_max_liberal):
                core.MY_PRINT_FUNC(
                    "ERROR: bounding indexes do not follow the expected relationship, results may be bad!"
                )
                foobar = True
            if foobar or moreinfo:
                core.MY_PRINT_FUNC(
                    "   Max liberal bounds:      idx = %d to %d, %% = %f to %f"
                    % (i_min_liberal, i_max_liberal, p_min_liberal,
                       p_max_liberal))
                core.MY_PRINT_FUNC(
                    "   Max conservative bounds: idx = %d to %d, %% = %f to %f"
                    % (i_min_conserv, i_max_conserv, p_min_conserv,
                       p_max_conserv))

            # IDEA: WEIGHTED BLEND! sliding scale!
            avg_factor = core.clamp(ENDPOINT_AVERAGE_FACTOR, 0.0, 1.0)
            if p_min_liberal != p_min_conserv:
                p_min = (p_min_liberal * avg_factor) + (p_min_conserv *
                                                        (1 - avg_factor))
            else:
                p_min = p_min_liberal
            if p_max_liberal != p_max_conserv:
                p_max = (p_max_liberal * avg_factor) + (p_max_conserv *
                                                        (1 - avg_factor))
            else:
                p_max = p_max_liberal
            # clamp just in case
            p_min = core.clamp(p_min, 0.0, 1.0)
            p_max = core.clamp(p_max, 0.0, 1.0)
            if moreinfo:
                i_min = core.bisect_left(percentiles, p_min)
                i_max = core.bisect_left(percentiles, p_max)
                core.MY_PRINT_FUNC(
                    "   Compromise bounds:       idx = %d to %d, %% = %f to %f"
                    % (i_min, i_max, p_min, p_max))

            # now normalize the percentiles to these endpoints
            p_len = p_max - p_min
            percentiles = [(p - p_min) / p_len for p in percentiles]

            # 9. divide weight between preferredparent (or parent) and armYZ
            vert_zip = list(zip(verts, percentiles, centers))
            num_modified, num_bleeders = divvy_weights(
                pmx=pmx,
                vert_zip=vert_zip,
                axis_limits=(pmx.bones[start_idx].pos, pmx.bones[end_idx].pos),
                bone_hasweight=parent_idx,
                bone_getsweight=armYZ_new_idx,
                bezier=bezier_curve)
            if moreinfo:
                core.MY_PRINT_FUNC(
                    "  Modified %d verts to use blending, %d are questionable 'bleeding' points"
                    % (num_modified, num_bleeders))
            pass
        pass

    # 10. run final weight-cleanup
    normalize_weights(pmx)

    # 11. write out
    output_filename_pmx = input_filename_pmx[0:-4] + "_magictwist.pmx"
    output_filename_pmx = core.get_unused_file_name(output_filename_pmx)
    pmxlib.write_pmx(output_filename_pmx, pmx, moreinfo=moreinfo)
    core.MY_PRINT_FUNC("Done!")
    return None
예제 #4
0
def main(moreinfo=True):
	# prompt PMX name
	core.MY_PRINT_FUNC("Please enter name of PMX input file:")
	input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")
	pmx = pmxlib.read_pmx(input_filename_pmx, moreinfo=moreinfo)
	
	# detect whether arm ik exists
	r = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_r + jp_newik)
	if r is None:
		r = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_r + jp_newik2)
	l = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_l + jp_newik)
	if l is None:
		l = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_l + jp_newik2)
	
	# decide whether to create or remove arm ik
	if r is None and l is None:
		# add IK branch
		core.MY_PRINT_FUNC(">>>> Adding arm IK <<<")
		# set output name
		if input_filename_pmx.lower().endswith(pmx_noik_suffix.lower()):
			output_filename = input_filename_pmx[0:-(len(pmx_noik_suffix))] + pmx_yesik_suffix
		else:
			output_filename = input_filename_pmx[0:-4] + pmx_yesik_suffix
		for side in [jp_l, jp_r]:
			# first find all 3 arm bones
			# even if i insert into the list, this will still be a valid reference i think
			bones = []
			bones: List[pmxstruct.PmxBone]
			for n in [jp_arm, jp_elbow, jp_wrist]:
				i = core.my_list_search(pmx.bones, lambda x: x.name_jp == side + n, getitem=True)
				if i is None:
					core.MY_PRINT_FUNC("ERROR1: semistandard bone '%s' is missing from the model, unable to create attached arm IK" % (side + n))
					raise RuntimeError()
				bones.append(i)
			# get parent of arm bone (shoulder bone), new bones will be inserted after this
			shoulder_idx = bones[0].parent_idx
			
			# new bones will be inserted AFTER shoulder_idx
			# newarm_idx = shoulder_idx+1
			# newelbow_idx = shoulder_idx+2
			# newwrist_idx = shoulder_idx+3
			# newik_idx = shoulder_idx+4
			
			# make copies of the 3 armchain bones
			
			# arm: parent is shoulder
			newarm = pmxstruct.PmxBone(
				name_jp=bones[0].name_jp + jp_ikchainsuffix, name_en=bones[0].name_en + jp_ikchainsuffix, 
				pos=bones[0].pos, parent_idx=shoulder_idx, deform_layer=bones[0].deform_layer, 
				deform_after_phys=bones[0].deform_after_phys,
				has_rotate=True, has_translate=False, has_visible=False, has_enabled=True, has_ik=False,
				tail_usebonelink=True, tail=0,  # want arm tail to point at the elbow, can't set it until elbow is created
				inherit_rot=False, inherit_trans=False,
				has_localaxis=bones[0].has_localaxis, localaxis_x=bones[0].localaxis_x, localaxis_z=bones[0].localaxis_z,
				has_externalparent=False, has_fixedaxis=False, 
			)
			insert_single_bone(pmx, newarm, shoulder_idx + 1)
			# change existing arm to inherit rot from this
			bones[0].inherit_rot = True
			bones[0].inherit_parent_idx = shoulder_idx + 1
			bones[0].inherit_ratio = 1
			
			# elbow: parent is newarm
			newelbow = pmxstruct.PmxBone(
				name_jp=bones[1].name_jp + jp_ikchainsuffix, name_en=bones[1].name_en + jp_ikchainsuffix, 
				pos=bones[1].pos, parent_idx=shoulder_idx+1, deform_layer=bones[1].deform_layer, 
				deform_after_phys=bones[1].deform_after_phys,
				has_rotate=True, has_translate=False, has_visible=False, has_enabled=True, has_ik=False,
				tail_usebonelink=True, tail=0,  # want elbow tail to point at the wrist, can't set it until wrist is created
				inherit_rot=False, inherit_trans=False,
				has_localaxis=bones[1].has_localaxis, localaxis_x=bones[1].localaxis_x, localaxis_z=bones[1].localaxis_z,
				has_externalparent=False, has_fixedaxis=False, 
			)
			insert_single_bone(pmx, newelbow, shoulder_idx + 2)
			# change existing elbow to inherit rot from this
			bones[1].inherit_rot = True
			bones[1].inherit_parent_idx = shoulder_idx + 2
			bones[1].inherit_ratio = 1
			# now that newelbow exists, change newarm tail to point to this
			newarm.tail = shoulder_idx + 2
			
			# wrist: parent is newelbow
			newwrist = pmxstruct.PmxBone(
				name_jp=bones[2].name_jp + jp_ikchainsuffix, name_en=bones[2].name_en + jp_ikchainsuffix, 
				pos=bones[2].pos, parent_idx=shoulder_idx+2, deform_layer=bones[2].deform_layer, 
				deform_after_phys=bones[2].deform_after_phys,
				has_rotate=True, has_translate=False, has_visible=False, has_enabled=True, has_ik=False,
				tail_usebonelink=True, tail=-1,  # newwrist has no tail
				inherit_rot=False, inherit_trans=False,
				has_localaxis=bones[2].has_localaxis, localaxis_x=bones[2].localaxis_x, localaxis_z=bones[2].localaxis_z,
				has_externalparent=False, has_fixedaxis=False, 
			)
			insert_single_bone(pmx, newwrist, shoulder_idx + 3)
			# now that newwrist exists, change newelbow tail to point to this
			newelbow.tail = shoulder_idx + 3
			
			# copy the wrist to make the IK bone
			en_suffix = "_L" if side == jp_l else "_R"
			# get index of "upperbody" to use as parent of hand IK bone
			ikpar = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_upperbody)
			if ikpar is None:
				core.MY_PRINT_FUNC("ERROR1: semistandard bone '%s' is missing from the model, unable to create attached arm IK" % jp_upperbody)
				raise RuntimeError()
			
			# newik = [side + jp_newik, en_newik + en_suffix] + bones[2][2:5] + [ikpar]  # new names, copy pos, new par
			# newik += bones[2][6:8] + [1, 1, 1, 1]  + [0, [0,1,0]] # copy deform layer, rot/trans/vis/en, tail type
			# newik += [0, 0, [], 0, [], 0, [], 0, []]  # no inherit, no fixed axis, no local axis, no ext parent, yes IK
			# # add the ik info: [is_ik, [target, loops, anglelimit, [[link_idx, []]], [link_idx, []]]] ] ]
			# newik += [1, [shoulder_idx+3, newik_loops, newik_angle, [[shoulder_idx+2,[]],[shoulder_idx+1,[]]] ] ]
			newik = pmxstruct.PmxBone(
				name_jp=side + jp_newik, name_en=en_newik + en_suffix, pos=bones[2].pos,
				parent_idx=ikpar, deform_layer=bones[2].deform_layer, deform_after_phys=bones[2].deform_after_phys,
				has_rotate=True, has_translate=True, has_visible=True, has_enabled=True,
				tail_usebonelink=False, tail=[0,1,0], inherit_rot=False, inherit_trans=False,
				has_fixedaxis=False, has_localaxis=False, has_externalparent=False, has_ik=True,
				ik_target_idx=shoulder_idx+3, ik_numloops=newik_loops, ik_angle=newik_angle,
				ik_links=[pmxstruct.PmxBoneIkLink(idx=shoulder_idx+2), pmxstruct.PmxBoneIkLink(idx=shoulder_idx+1)]
			)
			insert_single_bone(pmx, newik, shoulder_idx + 4)
			
			# then add to dispframe
			# first, does the frame already exist?
			f = core.my_list_search(pmx.frames, lambda x: x.name_jp == jp_newik, getitem=True)
			newframeitem = pmxstruct.PmxFrameItem(is_morph=False, idx=shoulder_idx + 4)
			if f is None:
				# need to create the new dispframe! easy
				newframe = pmxstruct.PmxFrame(name_jp=jp_newik, name_en=en_newik, is_special=False, items=[newframeitem])
				pmx.frames.append(newframe)
			else:
				# frame already exists, also easy
				f.items.append(newframeitem)
	else:
		# remove IK branch
		core.MY_PRINT_FUNC(">>>> Removing arm IK <<<")
		# set output name
		if input_filename_pmx.lower().endswith(pmx_yesik_suffix.lower()):
			output_filename = input_filename_pmx[0:-(len(pmx_yesik_suffix))] + pmx_noik_suffix
		else:
			output_filename = input_filename_pmx[0:-4] + pmx_noik_suffix
		# identify all bones in ik chain of hand ik bones
		bone_dellist = []
		for b in [r, l]:
			bone_dellist.append(b) # this IK bone
			bone_dellist.append(pmx.bones[b].ik_target_idx) # the target of the bone
			for v in pmx.bones[b].ik_links:
				bone_dellist.append(v.idx) # each link along the bone
		bone_dellist.sort()
		# do the actual delete & shift
		delete_multiple_bones(pmx, bone_dellist)
		
		# delete dispframe for hand ik
		# first, does the frame already exist?
		f = core.my_list_search(pmx.frames, lambda x: x.name_jp == jp_newik)
		if f is not None:
			# frame already exists, delete it
			pmx.frames.pop(f)
		
		pass
	
	# write out
	output_filename = core.get_unused_file_name(output_filename)
	pmxlib.write_pmx(output_filename, pmx, moreinfo=moreinfo)
	core.MY_PRINT_FUNC("Done!")
	return None
def make_autotwist_segment(pmx: pmxstruct.Pmx, side, arm_s, armtwist_s,
                           elbow_s, moreinfo):
    # note: will be applicable to elbow-wristtwist-wrist as well! just named like armtwist for simplicity

    # 1, locate arm/armtwist/elbow idx and obj
    r = []
    for n in (arm_s, armtwist_s, elbow_s):
        n2 = side[0] + n[0]
        i = core.my_list_search(pmx.bones, lambda x: x.name_jp == n2)
        if i is None:
            core.MY_PRINT_FUNC(
                "ERROR: standard bone '%s' not found in model, this is required!"
                % n2)
            return None
        r.append(i)
    arm_idx, armtwist_idx, elbow_idx = r  # unpack into named variables
    arm = pmx.bones[arm_idx]
    armtwist = pmx.bones[armtwist_idx]
    elbow = pmx.bones[elbow_idx]

    # 2, find all armtwist-sub bones
    armtwist_sub_obj = []
    # # dont forget to refresh elbow_idx
    # elbow_idx = core.my_list_search(pmx.bones, lambda x: x.name_jp == side + elbow_s)
    for d, bone in enumerate(pmx.bones):
        # anything that partial inherit from armtwist (except arm)
        if bone.inherit_rot and bone.inherit_parent_idx == armtwist_idx:
            if d == arm_idx: continue
            armtwist_sub_obj.append(bone)
        # anything that has armtwist as parent (except elbow or elbow helper (full parent armtwist, partial parent elbow))
        if bone.parent_idx == armtwist_idx:
            if d == elbow_idx: continue
            if bone.inherit_rot and bone.inherit_parent_idx == elbow_idx:
                continue
            armtwist_sub_obj.append(bone)

    # 3, calculate "perpendicular" location
    # get axis from arm to elbow, normalize to 1
    axis = [b - a for a, b in zip(arm.pos, elbow.pos)]
    axis = core.normalize_distance(axis)
    # calc vector in XZ plane at 90-deg from axis
    frontback = core.my_cross_product(axis, [0, 1, 0])
    frontback = core.normalize_distance(frontback)
    # calc vector in the same vertical plane as axis, at 90-deg from axis
    perpendicular = core.my_cross_product(axis, frontback)
    perpendicular = core.normalize_distance(perpendicular)
    # if result has negative y, invert
    if perpendicular[1] < 0:
        perpendicular = [p * -1 for p in perpendicular]
    # normalize to perpendicular_offset_dist
    perpendicular = [perpendicular_offset_dist * t for t in perpendicular]
    # add this to elbow pos and save
    perp_pos = [a + b for a, b in zip(elbow.pos, perpendicular)]

    # 4, create the six ik bones
    # cannot reference other bone idxs until they are inserted!!
    start = max(arm_idx, armtwist_idx)
    armD_idx = start + 1
    armDend_idx = start + 2
    armDik_idx = start + 3
    armT_idx = start + 4
    armTend_idx = start + 5
    armTik_idx = start + 6

    # make armD, pos=arm.pos, parent=arm.parent, tail=armDend
    armD = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_base[0],
        name_en=arm_s[1] + n_base[1] + side[1],
        pos=arm.pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=False,
        has_visible=False,
        has_enabled=False,
        has_ik=False,
        tail_usebonelink=True,
        tail=-99,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=arm.has_localaxis,
        localaxis_x=arm.localaxis_x,
        localaxis_z=arm.localaxis_z,
        has_externalparent=False,
    )
    # make armDend, pos=elbow.pos, parent=armD_idx
    armDend = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_base[0] + n_end[0],
        name_en=arm_s[1] + n_base[1] + side[1] + n_end[1],
        pos=elbow.pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=False,
        has_visible=False,
        has_enabled=False,
        has_ik=False,
        tail_usebonelink=True,
        tail=-1,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    # make armD_IK, pos=elbow.pos, parent=elbow.parent, target=armDend, link=armD
    armDik = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_base[0] + n_ik[0],
        name_en=arm_s[1] + n_base[1] + n_ik[1] + side[1],
        pos=elbow.pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=False,
        has_enabled=False,
        has_ik=True,
        tail_usebonelink=True,
        tail=-1,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=-99,
        ik_numloops=ik_numloops,
        ik_angle=ik_angle,
        ik_links=[
            pmxstruct.PmxBoneIkLink(idx=-99,
                                    limit_min=ikD_lim_min,
                                    limit_max=ikD_lim_max)
        ])

    # make armT, pos=elbow.pos, parent=armD_idx, tail=armTend
    armT = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_twist[0],
        name_en=arm_s[1] + n_twist[1] + side[1],
        pos=elbow.pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=False,
        has_visible=False,
        has_enabled=False,
        has_ik=False,
        tail_usebonelink=True,
        tail=-99,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    # make armTend, pos=perp_pos, parent=armT_idx
    armTend = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_twist[0] + n_end[0],
        name_en=arm_s[1] + n_twist[1] + side[1] + n_end[1],
        pos=perp_pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=False,
        has_visible=False,
        has_enabled=False,
        has_ik=False,
        tail_usebonelink=True,
        tail=-1,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    # make armT_IK, pos=perp_pos, parent=elbow.parent, target=armTend, link=armT
    armTik = pmxstruct.PmxBone(
        name_jp=side[0] + arm_s[0] + n_twist[0] + n_ik[0],
        name_en=arm_s[1] + n_twist[1] + n_ik[1] + side[1],
        pos=perp_pos,
        parent_idx=-99,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=False,
        has_enabled=False,
        has_ik=True,
        tail_usebonelink=True,
        tail=-1,
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=-99,
        ik_numloops=ik_numloops,
        ik_angle=ik_angle,
        ik_links=[pmxstruct.PmxBoneIkLink(idx=-99)])

    # insert these 6 bones
    # TODO: create more efficient function for multi-insert? nah, this is fine
    insert_single_bone(pmx, armD, armD_idx)
    insert_single_bone(pmx, armDend, armDend_idx)
    insert_single_bone(pmx, armDik, armDik_idx)
    insert_single_bone(pmx, armT, armT_idx)
    insert_single_bone(pmx, armTend, armTend_idx)
    insert_single_bone(pmx, armTik, armTik_idx)
    # fix all references to other bones (-99s)
    armD.tail = armDend_idx
    armT.tail = armTend_idx
    armD.parent_idx = arm.parent_idx
    armDend.parent_idx = armD_idx
    armDik.parent_idx = elbow.parent_idx
    armT.parent_idx = armD_idx
    armTend.parent_idx = armT_idx
    armTik.parent_idx = elbow.parent_idx
    armDik.ik_target_idx = armDend_idx
    armDik.ik_links[0].idx = armD_idx
    armTik.ik_target_idx = armTend_idx
    armTik.ik_links[0].idx = armT_idx

    # 5, modify the armtwist-sub bones
    # first go back from obj to indices, since the bones moved
    armtwist_sub = [b.idx_within(pmx.bones) for b in armtwist_sub_obj]
    for b_idx in armtwist_sub:
        bone = pmx.bones[b_idx]
        # change parent from arm to armD
        bone.parent_idx = armD_idx
        # change partial inherit from armtwist to armT
        bone.inherit_parent_idx = armT_idx

    # 6, insert additional armtwist-sub bones and transfer weight to them

    # first, check whether armtwistX would receive any weights/RBs
    # note, transferring from armtwist to armtwist changes nothing, this is harmless, just for looking
    armtwistX_used = transfer_to_armtwist_sub(pmx, armtwist_idx, armtwist_idx)
    if armtwistX_used:
        asdf = len(armtwist_sub) + 1
        # make armtwistX, pos=armtwist.pos, parent=armD_idx, inherit armT=1.00
        armtwistX = pmxstruct.PmxBone(
            name_jp=side[0] + armtwist_s[0] + str(asdf),
            name_en=armtwist_s[1] + str(asdf) + side[1],
            pos=armtwist.pos,
            parent_idx=-99,
            deform_layer=0,
            deform_after_phys=False,
            has_rotate=True,
            has_translate=False,
            has_visible=False,
            has_enabled=True,
            has_ik=False,
            tail_usebonelink=True,
            tail=-1,
            inherit_rot=True,
            inherit_trans=False,
            inherit_parent_idx=-99,
            inherit_ratio=1.00,
            has_fixedaxis=False,
            has_localaxis=False,
            has_externalparent=False,
        )
        # insert armtwistX at max(armtwist_sub) + 1
        armtwistX_idx = max(armtwist_sub) + 1
        insert_single_bone(pmx, armtwistX, armtwistX_idx)
        # fix references to other bones
        armtwistX.parent_idx = armD_idx
        armtwistX.inherit_parent_idx = armT_idx

        # transfer all weight and rigidbody references from armtwist to armtwistX
        # this time the return val is not needed
        transfer_to_armtwist_sub(pmx, armtwist_idx, armtwistX_idx)
        armtwist_sub_obj.append(armtwistX)

    # second, do the same thing for armtwist0
    armtwist0_used = transfer_to_armtwist_sub(pmx, arm_idx, arm_idx)
    if armtwist0_used:
        # make armtwist0, pos=arm.pos, parent=armD_idx, inherit armT=0.00
        armtwist0 = pmxstruct.PmxBone(
            name_jp=side[0] + armtwist_s[0] + "0",
            name_en=armtwist_s[1] + "0" + side[1],
            pos=arm.pos,
            parent_idx=-99,
            deform_layer=0,
            deform_after_phys=False,
            has_rotate=True,
            has_translate=False,
            has_visible=False,
            has_enabled=True,
            has_ik=False,
            tail_usebonelink=True,
            tail=-1,
            inherit_rot=True,
            inherit_trans=False,
            inherit_parent_idx=-99,
            inherit_ratio=0.00,
            has_fixedaxis=False,
            has_localaxis=False,
            has_externalparent=False,
        )
        # insert armtwist0 at min(armtwist_sub)
        armtwist0_idx = min(armtwist_sub)
        insert_single_bone(pmx, armtwist0, armtwist0_idx)
        # fix references to other bones
        armtwist0.parent_idx = armD_idx
        armtwist0.inherit_parent_idx = armT_idx

        # transfer all weight and rigidbody references from arm to armtwist0
        # this time the return val is not needed
        transfer_to_armtwist_sub(pmx, arm_idx, armtwist0_idx)
        armtwist_sub_obj.append(armtwist0)

    # 7, detect & fix incorrect structure among primary bones
    # refresh list of armtwist_sub indixes cuz stuff was inserted
    armtwist_sub = [b.idx_within(pmx.bones) for b in armtwist_sub_obj]
    # elbow should be a child of arm or armtwist, NOT any of the armtwist-sub bones
    # this is to prevent deform layers from getting all fucky
    if elbow.parent_idx in armtwist_sub:
        newparent = max(arm_idx, armtwist_idx)
        core.MY_PRINT_FUNC("WARNING: fixing improper parenting for bone '%s'" %
                           elbow.name_jp)
        core.MY_PRINT_FUNC("parent was '%s', changing to '%s'" %
                           (pmx.bones[elbow.parent_idx].name_jp,
                            pmx.bones[newparent].name_jp))
        core.MY_PRINT_FUNC(
            "if this bone has a 'helper bone' please change its parent in the same way"
        )
        elbow.parent_idx = newparent

    # 8, fix shoulder-helper and elbow-helper if they exist
    # shoulder helper: parent=shoulder(C), inherit=arm
    # goto:            parent=shoulder(C), inherit=armD
    # elbow helper: parent=arm(twist), inherit=elbow
    # goto:         parent=armT,       inherit=elbowD

    # need to refresh elbow idx cuz it moved
    elbow_idx = elbow.idx_within(pmx.bones)
    for d, bone in enumerate(pmx.bones):
        # transfer "inherit arm" to "inherit armD"
        # this should be safe for all bones
        if bone.inherit_rot and bone.inherit_parent_idx == arm_idx:
            bone.inherit_parent_idx = armD_idx
        # transfer "parent armtwist" to "parent armT"
        # this needs to exclude elbow, D_IK, T_IK, armtwist, arm
        if bone.parent_idx == armtwist_idx:
            if d not in (elbow_idx, armDik_idx, armTik_idx, armtwist_idx,
                         arm_idx):
                bone.parent_idx = armT_idx
        if bone.parent_idx == arm_idx:
            if d not in (elbow_idx, armDik_idx, armTik_idx, armtwist_idx,
                         arm_idx):
                bone.parent_idx = armD_idx

    # 9, set the deform order of all the bones so that it doesn't break when armIK is added
    # what deform level should they start from?
    base_deform = max(arm.deform_layer, armtwist.deform_layer,
                      elbow.deform_layer)
    armD.deform_layer = base_deform + 2
    armDend.deform_layer = base_deform + 2
    armDik.deform_layer = base_deform + 2
    armT.deform_layer = base_deform + 3
    armTend.deform_layer = base_deform + 3
    armTik.deform_layer = base_deform + 3
    for bone in armtwist_sub_obj:
        bone.deform_layer = base_deform + 4

    # fix deform for anything hanging off of the armtwist bones (rare but sometimes exists)
    deform_changed = 0
    deform_changed += fix_deform_for_children(pmx, armD_idx)
    deform_changed += fix_deform_for_children(pmx, armT_idx)
    for idx in armtwist_sub:
        deform_changed += fix_deform_for_children(pmx, idx)

    if moreinfo and deform_changed:
        core.MY_PRINT_FUNC("modified deform order for %d existing bones" %
                           deform_changed)

    # done with this function???
    return None
예제 #6
0
def main(moreinfo=True):
    # prompt PMX name
    core.MY_PRINT_FUNC("Please enter name of PMX input file:")
    input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")
    pmx = pmxlib.read_pmx(input_filename_pmx, moreinfo=moreinfo)

    # detect whether arm ik exists
    r = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_r + jp_newik)
    if r is None:
        r = core.my_list_search(pmx.bones,
                                lambda x: x.name_jp == jp_r + jp_newik2)
    l = core.my_list_search(pmx.bones, lambda x: x.name_jp == jp_l + jp_newik)
    if l is None:
        l = core.my_list_search(pmx.bones,
                                lambda x: x.name_jp == jp_l + jp_newik2)

    # decide whether to create or remove arm ik
    if r is None and l is None:
        # add IK branch
        core.MY_PRINT_FUNC(">>>> Adding arm IK <<<")
        # set output name
        if input_filename_pmx.lower().endswith(pmx_noik_suffix.lower()):
            output_filename = input_filename_pmx[0:-(
                len(pmx_noik_suffix))] + pmx_yesik_suffix
        else:
            output_filename = input_filename_pmx[0:-4] + pmx_yesik_suffix
        for side in [jp_l, jp_r]:
            # first find all 3 arm bones
            # even if i insert into the list, this will still be a valid reference i think
            bones = []
            bones: List[pmxstruct.PmxBone]
            for n in [jp_arm, jp_elbow, jp_wrist]:
                i = core.my_list_search(pmx.bones,
                                        lambda x: x.name_jp == side + n,
                                        getitem=True)
                if i is None:
                    core.MY_PRINT_FUNC(
                        "ERROR1: semistandard bone '%s' is missing from the model, unable to create attached arm IK"
                        % (side + n))
                    raise RuntimeError()
                bones.append(i)
            # get parent of arm bone
            shoulder_idx = bones[0].parent_idx

            # then do the "remapping" on all existing bone references, to make space for inserting 4 bones
            # don't delete any bones, just remap them
            bone_shiftmap = ([shoulder_idx + 1], [-4])
            apply_bone_remapping(pmx, [], bone_shiftmap)
            # new bones will be inserted AFTER shoulder_idx
            # newarm_idx = shoulder_idx+1
            # newelbow_idx = shoulder_idx+2
            # newwrist_idx = shoulder_idx+3
            # newik_idx = shoulder_idx+4

            # make copies of the 3 armchain bones
            for i, b in enumerate(bones):
                b: pmxstruct.PmxBone

                # newarm = b[0:5] + [shoulder_idx + i] + b[6:8]  # copy names/pos, parent, copy deform layer
                # newarm += [1, 0, 0, 0]  # rotateable, not translateable, not visible, not enabled(?)
                # newarm += [1, [shoulder_idx + 2 + i], 0, 0, [], 0, []]  # tail type, no inherit, no fixed axis,
                # newarm += b[19:21] + [0, [], 0, []]  # copy local axis, no ext parent, no ik
                # newarm[0] += jp_ikchainsuffix  # add suffix to jp name
                # newarm[1] += jp_ikchainsuffix  # add suffix to en name
                newarm = pmxstruct.PmxBone(
                    name_jp=b.name_jp + jp_ikchainsuffix,
                    name_en=b.name_en + jp_ikchainsuffix,
                    pos=b.pos,
                    parent_idx=b.parent_idx,
                    deform_layer=b.deform_layer,
                    deform_after_phys=b.deform_after_phys,
                    has_rotate=True,
                    has_translate=False,
                    has_visible=False,
                    has_enabled=True,
                    tail_type=True,
                    tail=shoulder_idx + 2 + i,
                    inherit_rot=False,
                    inherit_trans=False,
                    has_fixedaxis=False,
                    has_localaxis=b.has_localaxis,
                    localaxis_x=b.localaxis_x,
                    localaxis_z=b.localaxis_z,
                    has_externalparent=False,
                    has_ik=False,
                )
                pmx.bones.insert(shoulder_idx + 1 + i, newarm)
                # then change the existing arm/elbow (not the wrist) to inherit rot from them
                if i != 2:
                    b.inherit_rot = True
                    b.inherit_parent_idx = shoulder_idx + 1 + i
                    b.inherit_ratio = 1

            # copy the wrist to make the IK bone
            en_suffix = "_L" if side == jp_l else "_R"
            # get index of "upperbody" to use as parent of hand IK bone
            ikpar = core.my_list_search(pmx.bones,
                                        lambda x: x.name_jp == jp_upperbody)
            if ikpar is None:
                core.MY_PRINT_FUNC(
                    "ERROR1: semistandard bone '%s' is missing from the model, unable to create attached arm IK"
                    % jp_upperbody)
                raise RuntimeError()

            # newik = [side + jp_newik, en_newik + en_suffix] + bones[2][2:5] + [ikpar]  # new names, copy pos, new par
            # newik += bones[2][6:8] + [1, 1, 1, 1]  + [0, [0,1,0]] # copy deform layer, rot/trans/vis/en, tail type
            # newik += [0, 0, [], 0, [], 0, [], 0, []]  # no inherit, no fixed axis, no local axis, no ext parent, yes IK
            # # add the ik info: [is_ik, [target, loops, anglelimit, [[link_idx, []]], [link_idx, []]]] ] ]
            # newik += [1, [shoulder_idx+3, newik_loops, newik_angle, [[shoulder_idx+2,[]],[shoulder_idx+1,[]]] ] ]
            newik = pmxstruct.PmxBone(
                name_jp=side + jp_newik,
                name_en=en_newik + en_suffix,
                pos=bones[2].pos,
                parent_idx=ikpar,
                deform_layer=bones[2].deform_layer,
                deform_after_phys=bones[2].deform_after_phys,
                has_rotate=True,
                has_translate=True,
                has_visible=True,
                has_enabled=True,
                tail_type=False,
                tail=[0, 1, 0],
                inherit_rot=False,
                inherit_trans=False,
                has_fixedaxis=False,
                has_localaxis=False,
                has_externalparent=False,
                has_ik=True,
                ik_target_idx=shoulder_idx + 3,
                ik_numloops=newik_loops,
                ik_angle=newik_angle,
                ik_links=[
                    pmxstruct.PmxBoneIkLink(idx=shoulder_idx + 2),
                    pmxstruct.PmxBoneIkLink(idx=shoulder_idx + 1)
                ])
            pmx.bones.insert(shoulder_idx + 4, newik)

            # then add to dispframe
            # first, does the frame already exist?
            f = core.my_list_search(pmx.frames,
                                    lambda x: x.name_jp == jp_newik,
                                    getitem=True)
            if f is None:
                # need to create the new dispframe! easy
                newframe = pmxstruct.PmxFrame(name_jp=jp_newik,
                                              name_en=en_newik,
                                              is_special=False,
                                              items=[[0, shoulder_idx + 4]])
                pmx.frames.append(newframe)
            else:
                # frame already exists, also easy
                f.items.append([0, shoulder_idx + 4])
    else:
        # remove IK branch
        core.MY_PRINT_FUNC(">>>> Removing arm IK <<<")
        # set output name
        if input_filename_pmx.lower().endswith(pmx_yesik_suffix.lower()):
            output_filename = input_filename_pmx[0:-(
                len(pmx_yesik_suffix))] + pmx_noik_suffix
        else:
            output_filename = input_filename_pmx[0:-4] + pmx_noik_suffix
        # identify all bones in ik chain of hand ik bones
        bone_dellist = []
        for b in [r, l]:
            bone_dellist.append(b)  # this IK bone
            bone_dellist.append(
                pmx.bones[b].ik_target_idx)  # the target of the bone
            for v in pmx.bones[b].ik_links:
                bone_dellist.append(v.idx)  # each link along the bone
        bone_dellist.sort()
        # build the remap thing
        bone_shiftmap = delme_list_to_rangemap(bone_dellist)
        # do the actual delete & shift
        apply_bone_remapping(pmx, bone_dellist, bone_shiftmap)

        # delete dispframe for hand ik
        # first, does the frame already exist?
        f = core.my_list_search(pmx.frames, lambda x: x.name_jp == jp_newik)
        if f is not None:
            # frame already exists, delete it
            pmx.frames.pop(f)

        pass

    # write out
    output_filename = core.get_unused_file_name(output_filename)
    pmxlib.write_pmx(output_filename, pmx, moreinfo=moreinfo)
    core.MY_PRINT_FUNC("Done!")
    return None
예제 #7
0
def main(moreinfo=True):
    # copied codes
    core.MY_PRINT_FUNC("Please enter name of PMX model file:")
    input_filename_pmx = core.MY_FILEPROMPT_FUNC(".pmx")

    # object
    pmx_file_obj: pmxstruct.Pmx = pmxlib.read_pmx(input_filename_pmx,
                                                  moreinfo=moreinfo)

    # since there is an update to Valve Bip tools (I guess?), there is different bone names: the old and new one
    # only prefixes are changed along with order, thus there is a little bit scripting here to find the last leg
    big_dict: dict = {**body_dict, **leg_dict, **arm_dict, **finger_dict}

    #########################################################################
    # stage 1: create & insert core/base bones (grooves, mother,...)
    #########################################################################

    # base bone section
    # base order: 上半身, 下半身, 腰 (b_1), グルーブ, センター, 全ての親
    base_bone_4_name = "全ての親"  # motherbone
    base_bone_3_name = "センター"  # center
    base_bone_2_name = "グルーブ"  # groove
    base_bone_1_name = "腰"  # waist

    # note: Source models apparently have a much larger scale than MMD models
    base_bone_4_pos = [0, 0, 0]
    base_bone_3_pos = [0, 21, -0.533614993095398]
    base_bone_2_pos = base_bone_3_pos
    base_bone_1_pos = [0, 32, -0.533614993095398]

    # pelvis_pos = [-4.999999873689376e-06, 38.566917419433594, -0.533614993095398]

    # 全ての親, name_en, [0.0, 0.0, -0.4735046625137329], -1, 0, False,
    # True, True, True, True,
    # False, [0.0, 0.0, 0.0], False, False, None,
    # None, False, None, False, None, None, False, None, False,
    # None, None, None, None

    # base order: 上半身, 下半身, 腰 (b_1), グルーブ, センター, 全ての親
    base_bone_4_obj = pmxstruct.PmxBone(
        name_jp=base_bone_4_name,
        name_en="",
        pos=base_bone_4_pos,
        parent_idx=-1,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=False,
        tail_usebonelink=False,
        tail=[0, 3, 0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    insert_single_bone(pmx_file_obj, base_bone_4_obj, 0)

    base_bone_3_obj = pmxstruct.PmxBone(
        name_jp=base_bone_3_name,
        name_en="",
        pos=base_bone_3_pos,
        parent_idx=0,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=False,
        tail_usebonelink=False,
        tail=[0, -3, 0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    insert_single_bone(pmx_file_obj, base_bone_3_obj, 1)

    base_bone_2_obj = pmxstruct.PmxBone(
        name_jp=base_bone_2_name,
        name_en="",
        pos=base_bone_2_pos,
        parent_idx=1,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=False,
        tail_usebonelink=False,
        tail=[0, 0, 1.5],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    insert_single_bone(pmx_file_obj, base_bone_2_obj, 2)

    base_bone_1_obj = pmxstruct.PmxBone(
        name_jp=base_bone_1_name,
        name_en="",
        pos=base_bone_1_pos,
        parent_idx=2,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=False,
        tail_usebonelink=False,
        tail=[0, 0, 0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
    )
    insert_single_bone(pmx_file_obj, base_bone_1_obj, 3)

    #########################################################################
    # phase 2: translate Source names to MMD names
    #########################################################################

    # for each mapping of source-name to mmd-name,
    for mmd_name, source_possible_names in big_dict.items():
        # for each bone,
        for index, bone_object in enumerate(pmx_file_obj.bones):
            # if it has a source-name, replace with mmd-name
            if bone_object.name_jp in source_possible_names:
                pmx_file_obj.bones[index].name_jp = mmd_name

    # next, fix the lowerbody bone
    # find lowerbod
    lowerbod_obj = core.my_list_search(pmx_file_obj.bones,
                                       lambda x: x.name_jp == "下半身",
                                       getitem=True)
    # elif bone_object.name_jp in ["ValveBiped.Bip01_Pelvis", "bip_pelvis"]:
    if lowerbod_obj is not None:
        # should not be translateable
        lowerbod_obj.has_translate = False
        # parent should be waist
        lowerbod_obj.parent_idx = 3
    # next, fix the upperbody bone
    upperbod_obj = core.my_list_search(pmx_file_obj.bones,
                                       lambda x: x.name_jp == "上半身",
                                       getitem=True)
    if upperbod_obj is not None:
        # should not be translateable
        upperbod_obj.has_translate = False
        # parent should be waist
        upperbod_obj.parent_idx = 3

    #########################################################################
    # phase 3: create & insert IK bones for leg/toe
    #########################################################################
    # find the last leg item index
    # when creating IK bones, want to insert the IK bones after both legs
    r_l_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "右足")
    r_k_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "右ひざ")
    r_a_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "右足首")
    r_t_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "右つま先")
    l_l_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "左足")
    l_k_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "左ひざ")
    l_a_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "左足首")
    l_t_index = core.my_list_search(pmx_file_obj.bones,
                                    lambda x: x.name_jp == "左つま先")
    # if somehow they aren't found, default to 0
    if r_l_index is None: r_l_index = 0
    if r_k_index is None: r_k_index = 0
    if r_a_index is None: r_a_index = 0
    if r_t_index is None: r_t_index = 0
    if l_l_index is None: l_l_index = 0
    if l_k_index is None: l_k_index = 0
    if l_a_index is None: l_a_index = 0
    if l_t_index is None: l_t_index = 0

    if r_t_index > l_t_index:
        last_leg_item_index = r_t_index
    else:
        last_leg_item_index = l_t_index

    leg_left_ik_name = "左足IK"
    leg_left_toe_ik_name = "左つま先IK"
    leg_right_ik_name = "右足IK"
    leg_right_toe_ik_name = "右つま先IK"

    # these limits in degrees
    knee_limit_1 = [-180, 0.0, 0.0]
    knee_limit_2 = [-0.5, 0.0, 0.0]
    # other parameters
    ik_loops = 40
    ik_toe_loops = 8
    ik_angle = 114.5916  # degrees, =2 radians
    ik_toe_angle = 229.1831  # degrees, =4 radians

    # adding IK and such
    leg_left_ankle_obj = pmx_file_obj.bones[l_a_index]
    leg_left_toe_obj = pmx_file_obj.bones[l_t_index]
    leg_right_ankle_obj = pmx_file_obj.bones[r_a_index]
    leg_right_toe_obj = pmx_file_obj.bones[r_t_index]

    leg_left_ankle_pos = leg_left_ankle_obj.pos
    leg_left_toe_pos = leg_left_toe_obj.pos
    leg_right_ankle_pos = leg_right_ankle_obj.pos
    leg_right_toe_pos = leg_right_toe_obj.pos

    # toe /// places of some value wont match with the struct /// taken from hololive's korone model
    # name, name, [-0.823277473449707, 0.2155265510082245, -1.8799238204956055], 112, 0, False,
    # True, True, True, True,
    # False, [0.0, -1.3884940147399902, 1.2653569569920364e-07] /// This is offset, False, False, None,
    # None, False, None, False, None, None, False, None, True,
    # 111, 160, 1.0, [[110, None, None]]

    # leg
    # 右足IK, en_name, [-0.8402935862541199, 1.16348397731781, 0.3492986857891083], 0, 0, False,
    # True, True, True, True,
    # False, [0.0, -2.53071505085245e-07, 1.3884940147399902], False, False, None,
    # None, False, None, False, None, None, False, None, True,
    # 110, 85, 1.9896754026412964, [[109, [-3.1415927410125732, 0.0, 0.0], [-0.008726646192371845, 0.0, 0.0]]
    # /// These ik_links are in radians /// , [108, None, None]]

    leg_left_ik_obj = pmxstruct.PmxBone(
        name_jp=leg_left_ik_name,
        name_en="",
        pos=leg_left_ankle_pos,
        parent_idx=0,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=True,
        tail_usebonelink=False,
        tail=[0.0, 0.0, 1.0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=l_a_index,
        ik_numloops=ik_loops,
        ik_angle=ik_angle,
        ik_links=[
            pmxstruct.PmxBoneIkLink(idx=l_k_index,
                                    limit_min=knee_limit_1,
                                    limit_max=knee_limit_2),
            pmxstruct.PmxBoneIkLink(idx=l_l_index)
        ],
    )
    insert_single_bone(pmx_file_obj, leg_left_ik_obj, last_leg_item_index + 1)

    leg_left_toe_ik_obj = pmxstruct.PmxBone(
        name_jp=leg_left_toe_ik_name,
        name_en="",
        pos=leg_left_toe_pos,
        parent_idx=last_leg_item_index + 1,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=True,
        tail_usebonelink=False,
        tail=[0.0, -1.0, 0.0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=l_t_index,
        ik_numloops=ik_toe_loops,
        ik_angle=ik_toe_angle,
        ik_links=[pmxstruct.PmxBoneIkLink(idx=l_a_index)],
    )
    insert_single_bone(pmx_file_obj, leg_left_toe_ik_obj,
                       last_leg_item_index + 2)

    leg_right_ik_obj = pmxstruct.PmxBone(
        name_jp=leg_right_ik_name,
        name_en="",
        pos=leg_right_ankle_pos,
        parent_idx=0,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=True,
        tail_usebonelink=False,
        tail=[0.0, 0.0, 1.0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=r_a_index,
        ik_numloops=ik_loops,
        ik_angle=ik_angle,
        ik_links=[
            pmxstruct.PmxBoneIkLink(idx=r_k_index,
                                    limit_min=knee_limit_1,
                                    limit_max=knee_limit_2),
            pmxstruct.PmxBoneIkLink(idx=r_l_index)
        ],
    )
    insert_single_bone(pmx_file_obj, leg_right_ik_obj, last_leg_item_index + 3)

    leg_right_toe_ik_obj = pmxstruct.PmxBone(
        name_jp=leg_right_toe_ik_name,
        name_en="",
        pos=leg_right_toe_pos,
        parent_idx=last_leg_item_index + 3,
        deform_layer=0,
        deform_after_phys=False,
        has_rotate=True,
        has_translate=True,
        has_visible=True,
        has_enabled=True,
        has_ik=True,
        tail_usebonelink=False,
        tail=[0.0, -1.0, 0.0],
        inherit_rot=False,
        inherit_trans=False,
        has_fixedaxis=False,
        has_localaxis=False,
        has_externalparent=False,
        ik_target_idx=r_t_index,
        ik_numloops=ik_toe_loops,
        ik_angle=ik_toe_angle,
        ik_links=[pmxstruct.PmxBoneIkLink(idx=r_a_index)],
    )
    insert_single_bone(pmx_file_obj, leg_right_toe_ik_obj,
                       last_leg_item_index + 4)

    # output the file
    output_filename_pmx = input_filename_pmx[0:-4] + "_sourcetrans.pmx"
    pmxlib.write_pmx(output_filename_pmx, pmx_file_obj, moreinfo=moreinfo)
    core.MY_PRINT_FUNC("Done!")
    return None