XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

MyDimension-Lord

【我的世界】我的维度附属模组:维度之主

公开
关注 0 Fork 0 Star 0
UTF-8
"""Build original articulated voxel geometry from the concept sheet.

Run AFTER generate_equipment_assets.py. Item meshes and worn armor share a
single geometric description. No external animation library is required.
"""
from pathlib import Path
import json
import math
from generate_equipment_assets import Canvas, write, ROOT, RES, NS

MATERIALS = {
    'obsidian': ('211e30', '302b42', '403852'),
    'metal': ('b5b8c5', 'd0d2dd', 'f0f1f7'),
    'gold': ('8e7552', 'bda175', 'e5cd9d'),
    'crystal': ('8745d5', 'bb79fb', 'e9c9ff'),
    'leather': ('161521', '252333', '353141'),
    'rune': ('9a59e5', 'c38aff', 'ead1ff'),
}
KINDS = ('dimension_blade', 'dimension_pickaxe', 'lord_helmet', 'lord_chestplate', 'lord_leggings', 'lord_boots')
PARTS = ('body', 'core', 'halo', 'shards')


def box(x, y, z, w, h, d, material='obsidian', rotation=0, axis='z', pivot=None, bone='body', name=''):
    assert min(w, h, d) > 0
    return dict(from_=[x, y, z], to=[x+w, y+h, z+d], material=material,
                rotation=rotation, axis=axis, pivot=pivot or [x+w/2, y+h/2, z+d/2], bone=bone, name=name)


def diamond(x, y, z, size, bone='core', material='crystal'):
    return box(x-size/2, y-size/2, z-size/2, size, size, size, material, 45, 'z', [x,y,z], bone)


def halo(x, y, z, radius, bone='halo'):
    result=[]
    for i in range(8):
        a=i*math.pi/4
        # Every fragment's long axis is radial. Vanilla permits only rotations
        # within +/-45 degrees, so quarter-turns swap the X/Z dimensions.
        xx=x+math.cos(a)*radius; zz=z+math.sin(a)*radius
        w,d=(.6,1.6) if i%4==2 else (1.6,.6)
        angle=-45 if i%4==1 else 45 if i%4==3 else 0
        result.append(box(xx-w/2,y-.22,zz-d/2,w,.44,d,'gold',
                          angle,'y',[xx,y,zz],bone,name=f'halo_radial_{i}'))
    return result


def blade():
    b=[box(7.25,-8,7.3,1.5,10,1.4,'leather'),
       box(6.9,-8.3,6.95,2.2,.7,2.1,'gold'),
       box(6.95,1.0,6.95,2.1,.65,2.1,'gold')]
    for y in (-6.6,-4.9,-3.2,-1.5): b.append(box(7.14,y,7.16,1.72,.26,1.68,'obsidian'))
    # A continuous full tang sits BEHIND the floating jewel. The blade remains
    # physically connected to the grip at every phase of the jewel animation.
    b += [box(7.6,1.55,8.75,.8,6.1,.55,'obsidian',name='full_tang')]
    # The neck, one voxel-high shoulder and blade meet end-to-end. The old
    # silver forks shared the blade's front/back planes and caused flicker.
    profile=[(5.35,2.64,1.0,1.76),(6.35,4.0,1.0,2.2),
             (7.35,5.5,3.0,3.1),(10.35,4.8,4.65,2.7),
             (15,4.0,5.7,2.15),(20.7,3.2,4.2,1.55),
             (24.9,2.35,3.0,1.0),(27.9,1.45,1.2,.45)]
    for y,outer,h,inner in profile:
        name='ricasso' if y==5.35 else 'blade_shoulder' if y==6.35 else ''
        b.append(box(8-inner/2,y,7.45,inner,h,1.1,'obsidian',name=name))
        bevel=(outer-inner)/2
        for s in (-1,1):
            x=8-outer/2+.18 if s<0 else 8+inner/2
            # Broad silver bevels and a genuinely thin outer cutting edge.
            # Each strip owns its width, preventing duplicate exposed sides.
            b.append(box(x,y,7.62,bevel-.18,h,.76,'metal'))
            edge_x=8-outer/2 if s<0 else 8+outer/2-.18
            b.append(box(edge_x,y,7.86,.18,h,.28,'metal'))
            rib_width=min(.24,(inner-.2)/2)
            rib_x=8-inner/2 if s<0 else 8+inner/2-rib_width
            b.append(box(rib_x,y,7.31,rib_width,h,.14,'obsidian'))
        b += [box(7.9,y,7.27,.2,h,.16,'rune'),box(7.9,y,8.57,.2,h,.16,'rune')]
    # A rotated square provides converging diagonal edges and a true pointed
    # silhouette. It has no horizontal upper face, unlike the old last slab.
    b.append(box(7.45,28.55,7.67,1.1,1.1,.66,'metal',45,'z',[8,29.1,8],name='pointed_tip'))
    for y in (9,18,24):
        b += [box(7.78,y,7.09,.44,.44,.25,'rune',45),
              box(7.78,y,8.66,.44,.44,.25,'rune',45)]
    # Sculpted golden cradle: lower branches curl around, rather than terminate
    # as disconnected upright posts. The blade joins its narrow silver neck.
    for s in (-1,1):
        b += [box(8+s*1.9-1.25,1.9,7.18,2.5,.65,1.64,'gold',s*22.5),
              box(8+s*3.35-.55,2.65,7.18,1.1,1.8,1.64,'gold',-s*22.5),
              box(8+s*3.7-.48,4.2,7.35,.96,1.35,1.3,'obsidian',-s*22.5),
              box(8+s*3.75-.36,5.15,7.25,.72,.8,1.5,'metal',-s*22.5),
              box(8+s*4.4-.4,6.45,7.72,.8,.8,.56,'crystal',45,bone='shards')]
    # Thin nested diamond facets replace the opaque rotating cube.
    b += [box(7.1,2.8,7.55,1.8,1.8,.9,'crystal',45,'z',[8,3.7,8],'core'),
          box(7.55,2.8,7.1,.9,1.8,1.8,'crystal',45,'x',[8,3.7,8],'core'),
          box(7.42,3.12,7.36,1.16,1.16,.22,'rune',45,'z',[8,3.7,8],'core'),
          box(7.42,3.12,8.42,1.16,1.16,.22,'rune',45,'z',[8,3.7,8],'core'),
          box(7.53,2.18,7.47,.94,.94,1.06,'gold',45,bone='body'),
          box(7.53,4.32,7.47,.94,.94,1.06,'gold',45,bone='body'),
          box(7.42,-9.6,7.64,1.16,1.16,.72,'gold',45,bone='body'),
          box(7.65,-9.37,7.48,.7,.7,1.04,'crystal',45,bone='body')]
    b += halo(8,3.45,8,3.15)
    return b, [8,3.7,8]


def pickaxe():
    b=[box(7.25,-10,7.25,1.5,27,1.5,'leather')]
    for y in (-9.4,-5.5,1,8,14.5): b.append(box(6.85,y,6.85,2.3,.75,2.3,'gold'))
    for y in range(-8,14,2): b.append(box(7.1,y,7.1,1.8,.32,1.8,'obsidian'))
    b += [box(6.65,3.5,6.7,2.7,3.7,2.6),box(7.5,4.3,6.4,1,2.1,.4,'crystal'),
          diamond(8,-10.6,8,1.7,'body'),box(6.1,16,6.55,3.8,2,2.9)]
    for s in (-1,1):
        # Curved-in-steps spine, pronounced tips; front/back have actual depth.
        for distance,y,w,h in [(2.2,18.2,3.2,2.7),(4.9,17.5,3,2.5),(7.3,16.1,2.6,2.25)]:
            b.append(box(8+s*distance-w/2,y,6.45,w,h,3.1,'obsidian',-s*22.5))
            b.append(box(8+s*distance-w/2,y+2,6.25,w,.6,3.5,'gold',-s*22.5))
        b += [box(8+s*8.7-.75,13.8,6.7,1.5,3.8,2.6,'metal',-s*22.5),
              box(8+s*9.7-.4,12.3,7.05,.8,2.9,1.9,'metal',-s*22.5),
              box(8+s*1.9-.5,17,6.05,1,3,3.9,'gold'),
              diamond(8+s*3.4,23.1,8,.85,'shards')]
    b += [diamond(8,20.6,8,2.5),
          box(7.4,23.9,7.4,1.2,1.2,1.2,'crystal',0,bone='halo',name='pick_halo_core')]
    b += halo(8,24.5,8,2.45)
    return b, [8,20.6,8]


def armor(slot):
    """Minecraft humanoid local coordinates (Y down); face is Y -6..0, Z -4."""
    b=[]
    def add(parent,x,y,z,w,h,d,mat='obsidian',rot=0,bone='body',name=''):
        e=box(x,y,z,w,h,d,mat,rot,bone=bone,name=name);e['parent']=parent;b.append(e)
    if slot=='helmet':
        add('head',-4.55,-7.9,-4.6,9.1,.85,.8,'gold')
        add('head',-4.7,-8.2,3.85,9.4,3.0,.85)
        for s in (-1,1):
            add('head',s*4.45-.45,-8.2,-3.9,.9,3.7,8.2)
            add('head',s*4.55-.45,-5.1,-.8,.9,2.2,4.6)
            add('head',s*4.5-.55,-7.3,-4.1,1.1,1.1,.85,'gold')
            add('head',s*2.8-.4,-9.9,-4.2,.8,2.0,.8,'crystal',s*22.5)
        add('head',-.65,-9.7,-4.7,1.3,1.3,.8,'gold',45)
        add('head',-.38,-9.5,-4.85,.76,.9,.7,'crystal',45)
        add('head',-.6,-12.2,-2.8,1.2,2.4,1.2,'crystal',0,'shards','crown_spark')
        add('head',-.32,-12.8,-2.52,.64,1.1,.64,'rune',0,'shards','crown_tip')
    elif slot=='chestplate':
        # Separate front/back breastplate, collar and articulated sleeve segments.
        add('body',-4.45,.45,-2.75,8.9,8.2,5.5)
        for y,w in [(1,8),(3.4,7.4),(5.8,6.8)]:
            add('body',-w/2,y,-3.0,w,1.9,.65)
            for s in (-1,1): add('body',s*(w/2)-.35,y,-3.15,.7,2,.7,'gold',s*22.5)
        add('body',-4.65,0,-2.55,9.3,.65,5.1,'gold')
        add('body',-3.4,-.9,-2.2,1.3,1.6,4.4)
        add('body',2.1,-.9,-2.2,1.3,1.6,4.4)
        add('body',-3.9,7.9,-2.9,7.8,.7,5.8,'gold')
        add('body',-1.8,2.1,-3.35,3.6,3.6,.8,'gold',45)
        add('body',-1.25,2.6,-3.95,2.5,2.5,1.2,'crystal',45,'core','chest_core')
        add('body',-.4,6,-3.08,.8,1.35,.4,'rune')
        add('body',-1.4,3,2.8,2.8,2.8,.6,'gold',45)
        add('body',-.8,3.6,3.1,1.6,1.6,.8,'crystal',45,'shards','back_core')
        for side,parent in [(-1,'right_arm'),(1,'left_arm')]:
            center=side # arm origin lies at inner side of its 4px width
            add(parent,center-2.9,-2.8,-2.85,5.8,3.35,5.7)
            add(parent,center-3.05,.25,-3,6.1,.55,6,'gold')
            add(parent,center-2.55,.9,-2.45,5.1,2,4.9)
            add(parent,center-2.4,5,-2.4,4.8,3.4,4.8)
            add(parent,center-2.6,7.8,-2.6,5.2,.65,5.2,'gold')
            add(parent,center-.7,5.7,-2.85,1.4,1.4,.7,'crystal',45)
            # Float beside the torso, not on a swinging arm: fragments cannot
            # sweep across the wearer's face while attacking or raising a tool.
            add('body',side*7.3-.65,-3.5,-.6,1.3,1.7,1.3,'crystal',45,'shards','shoulder_spark_'+str(side))
            add(parent,center-2.3,-2.95,-3.0,4.6,.5,.5,'gold')
    elif slot=='leggings':
        add('body',-4.6,9.05,-2.65,9.2,1.1,5.3,'gold')
        add('body',-4.45,10.2,-2.6,8.9,1.3,5.2)
        add('body',-.85,9.1,-3,1.7,1.7,.8,'gold',45)
        add('body',-.5,9.4,-3.5,1,1,1,'crystal',45,'core','belt_core')
        for s in (-1,1):
            add('body',s*4.3-.9,10.4,-2.95,1.8,3.8,.9,'obsidian',s*22.5)
            add('body',s*5.45-.45,9.9,-1.3,.9,1.45,.9,'crystal',45,'shards','hip_spark_'+str(s))
        for parent in ('left_leg','right_leg'):
            add(parent,-2.4,.2,-2.4,4.8,4.6,4.8)
            add(parent,-2.55,3.7,-2.55,5.1,.6,5.1,'gold')
            add(parent,-2.3,4.5,-2.5,4.6,2.8,4.7)
            add(parent,-1.5,4.6,-3,3,2.6,.8,'gold')
            add(parent,-.6,5,-3.5,1.2,1.2,.75,'crystal',45,'core','knee_core')
    elif slot=='boots':
        for parent in ('left_leg','right_leg'):
            add(parent,-2.45,7.3,-2.45,4.9,4.6,4.9)
            add(parent,-2.65,10.2,-3.5,5.3,1.7,6)
            add(parent,-2.8,11.65,-3.65,5.6,.65,6.4,'leather')
            add(parent,-2.65,7.3,-2.65,5.3,.6,5.3,'gold')
            add(parent,-2.6,10.65,-3.65,5.2,.65,.7,'gold')
            add(parent,-.7,8.5,-3.1,1.4,1.4,.9,'crystal',45,'core','boot_core')
            add(parent,-2.65,9.2,1.8,.7,1,.7,'rune',0,'shards','heel_spark')
    return b


ORIGINS={'head':[0,0,0],'body':[0,0,0],'right_arm':[-5,2,0],'left_arm':[5,2,0],
         'right_leg':[-1.9,12,0],'left_leg':[1.9,12,0]}


def armor_item(slot):
    b=armor(slot)
    # Invert humanoid Y/Z into vanilla item model space, preserving thickness.
    center_y={'helmet':-6,'chestplate':3.8,'leggings':14.4,'boots':21.1}[slot]
    scale={'helmet':1.08,'chestplate':.86,'leggings':.9,'boots':1.28}[slot]
    converted=[]
    for e in b:
        ox,oy,oz=ORIGINS[e['parent']]
        x,y,z=e['from_'];xx,yy,zz=e['to']
        out=box(8+(x+ox)*scale,8-(yy+oy-center_y)*scale,8-(zz+oz)*scale,
                (xx-x)*scale,(yy-y)*scale,(zz-z)*scale,e['material'],-e['rotation'],bone=e['bone'],name=e['name'])
        out['pivot']=[8+(e['pivot'][0]+ox)*scale,8-(e['pivot'][1]+oy-center_y)*scale,8-(e['pivot'][2]+oz)*scale]
        converted.append(out)
    return converted,[8,8,8]


def texture_assets():
    # Tile colors are shared by item faces and armor bones. Subtle pixel facets
    # retain Minecraft's material language without losing the layered silhouette.
    atlas=Canvas(256,128)
    for index,(mat,pal) in enumerate(MATERIALS.items()):
        tex=Canvas(16,16)
        for y in range(16):
            for x in range(16):
                highlight=(x*7+y*11)%31==0
                color=pal[2] if highlight else pal[1] if (x+y*3)%9<2 else pal[0]
                if mat in ('metal','gold'): color=pal[2] if y in (1,2) else pal[1] if x<10 else pal[0]
                tex.pixel(x,y,color)
        write(RES/f'assets/{NS}/textures/item/gear/{mat}.png',tex.png())
        ox=(index%4)*64;oy=(index//4)*64
        for y in range(64):
            for x in range(64): atlas.pixels[oy+y][ox+x]=tex.pixels[y%16][x%16]
    for layer in (1,2):
        write(RES/f'assets/{NS}/textures/models/armor/lord_layer_{layer}.png',atlas.png())
        kind='humanoid' if layer==1 else 'humanoid_leggings'
        write(ROOT/f'ports/1.21.11/resources/assets/{NS}/textures/entity/equipment/{kind}/lord.png',atlas.png())


def element(e):
    # Explicit UV bounds prevent elements beyond the normal 0..16 item cube
    # from sampling neighboring atlas sprites (green streaks on the metal).
    out={'from':e['from_'],'to':e['to'],'faces':{f:{'texture':'#'+e['material'],'uv':[0,0,16,16]} for f in ('north','south','east','west','up','down')}}
    if e['rotation']:out['rotation']={'origin':e['pivot'],'axis':e['axis'],'angle':e['rotation'],'rescale':False}
    return out


def display(kind):
    weapon=kind.startswith('dimension_')
    if weapon:
        # Both weapon meshes now put their actual grip at (8,8,8). First-person
        # and third-person offsets no longer compensate for the whole object's
        # center, which previously put the palm on the guard / upper shaft.
        # Enlarge the blade around its grip; keep its inventory icon inside the slot.
        size=1.5 if kind=='dimension_blade' else 1.0
        hand_scale=(.65 if kind=='dimension_pickaxe' else .57)*size
        return {
            'gui':dict(rotation=[18,-32,-38],translation=[-.9,-1.2,0] if kind=='dimension_pickaxe' else [-2.3,-3.0,0],scale=[.52]*3),
            'firstperson_righthand':dict(rotation=[0,-45,12],translation=[.2,1.6,-1.0],scale=[hand_scale]*3),
            'firstperson_lefthand':dict(rotation=[0,45,-12],translation=[.2,1.6,-1.0],scale=[hand_scale]*3),
            'thirdperson_righthand':dict(rotation=[0,-90,-48],translation=[0,0,0],scale=[.74*size]*3),
            'thirdperson_lefthand':dict(rotation=[0,90,48],translation=[0,0,0],scale=[.74*size]*3),
            'ground':dict(rotation=[0,0,-35],translation=[-1,1,0],scale=[.31*size]*3),
            'fixed':dict(rotation=[0,180,-35],translation=[-2,-2,0],scale=[.5*size]*3)}
    return {k:dict(rotation=rot,translation=[0,0,0],scale=[scale]*3) for k,rot,scale in
            [('gui',[18,-30,0],.7),('ground',[0,0,0],.3),('fixed',[0,180,0],.7),
             ('firstperson_righthand',[0,-45,0],.65),('firstperson_lefthand',[0,45,0],.65),
             ('thirdperson_righthand',[0,-90,0],.55),('thirdperson_lefthand',[0,90,0],.55)]}


def java_geometry():
    lines=['package com.xfestudio.mydimensionlord.client.gear;',
        'import net.minecraft.client.model.geom.PartPose;',
        'import net.minecraft.client.model.geom.builders.*;',
        'import net.minecraft.world.entity.EquipmentSlot;',
        '/** Generated from generate_gear_models.py; the face region contains no armor cubes. */',
        'public final class LordArmorGeometry {',
        '    private LordArmorGeometry() {}',
        '    public static LayerDefinition create(EquipmentSlot slot) {',
        '        MeshDefinition mesh = new MeshDefinition();',
        '        PartDefinition root = mesh.getRoot();']
    for parent,pos in ORIGINS.items():
        p=','.join(f'{v}F' for v in pos)
        lines.append(f'        PartDefinition {parent} = root.addOrReplaceChild("{parent}", CubeListBuilder.create(), PartPose.offset({p}));')
    lines += ['        root.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);',
              '        head.addOrReplaceChild("hat", CubeListBuilder.create(), PartPose.ZERO);',
              '        switch (slot) {']
    for slot,constant in [('helmet','HEAD'),('chestplate','CHEST'),('leggings','LEGS'),('boots','FEET')]:
        lines.append(f'            case {constant} -> {{')
        for i,e in enumerate(armor(slot)):
            coords=e['from_'];size=[b-a for a,b in zip(coords,e['to'])]
            mat=list(MATERIALS).index(e['material']);u=(mat%4)*64;v=(mat//4)*64
            name=e['name'] or f'panel_{i}'
            floats=','.join(f'{round(x,5)}F' for x in coords+size)
            # Boxes rotate around their own center rather than the limb pivot.
            if e['rotation']:
                cx,cy,cz=e['pivot'];rel=[coords[0]-cx,coords[1]-cy,coords[2]-cz]+size
                floats=','.join(f'{round(x,5)}F' for x in rel)
                pp=f'PartPose.offsetAndRotation({cx}F,{cy}F,{cz}F,0F,0F,{round(math.radians(e["rotation"]),7)}F)'
            else: pp='PartPose.ZERO'
            lines.append(f'                {e["parent"]}.addOrReplaceChild("{name}", CubeListBuilder.create().texOffs({u},{v}).addBox({floats}), {pp});')
        lines.append('            }')
    lines += ['            default -> {}','        }','        return LayerDefinition.create(mesh, 256, 128);','    }','}']
    write(ROOT/'src/main/java/com/xfestudio/mydimensionlord/client/gear/LordArmorGeometry.java',('\n'.join(lines)+'\n').encode())


def main():
    # Concept must exist before any model is generated.
    assert (ROOT/'design/concepts/lord-gear-concept-v1.png').exists(), 'Generate concept art first'
    texture_assets();java_geometry()
    manifest={'concept':'../concepts/lord-gear-concept-v1.png','worn_armor':{s:armor(s) for s in ('helmet','chestplate','leggings','boots')},'items':{}}
    for kind in KINDS:
        boxes,pivot=blade() if kind=='dimension_blade' else pickaxe() if kind=='dimension_pickaxe' else armor_item(kind[5:])
        if kind.startswith('dimension_'):
            # Model origin is a hand anchor, not the bounding-box center. Scale
            # uniformly around it to retain vanilla's supported -16..32 bounds.
            grip_y=-3.0 if kind=='dimension_blade' else 2.5
            def anchored(point): return [8+(point[0]-8)*.7,8+(point[1]-grip_y)*.7,8+(point[2]-8)*.7]
            for e in boxes:
                e['from_']=anchored(e['from_']);e['to']=anchored(e['to']);e['pivot']=anchored(e['pivot'])
            pivot=anchored(pivot)
        for e in boxes:
            assert all(-16 <= x <= 32 for x in e['from_']+e['to']), (kind,e)
        manifest['items'][kind]={'pivot':pivot,'boxes':boxes}
        if kind.startswith('dimension_'): manifest['items'][kind]['grip']=[8,8,8]
        textures={k:f'{NS}:item/gear/{k}' for k in MATERIALS};textures['particle']=f'{NS}:item/gear/obsidian'
        # Body model remains a usable static 3D fallback; the actual item model
        # invokes the renderer, which independently transforms the three bones.
        for part in PARTS:
            elements=[element(e) for e in boxes if e['bone']==part]
            # Armor has floating runes but no circular halo. The unused bone is
            # omitted by renderers; it is not a missing-model placeholder.
            write(RES/f'assets/{NS}/models/item/gear/{kind}_{part}.json',{'textures':textures,'elements':elements})
            write(ROOT/f'ports/1.21.11/resources/assets/{NS}/items/gear_parts/{kind}_{part}.json',
                  {'model':{'type':'minecraft:model','model':f'{NS}:item/gear/{kind}_{part}'}})
        write(RES/f'assets/{NS}/models/item/{kind}.json',{'parent':'builtin/entity','gui_light':'front',
              'textures':textures,'display':display(kind)})
        write(ROOT/f'ports/1.21.11/resources/assets/{NS}/items/{kind}.json',{'model':{'type':'minecraft:special',
              'base':f'{NS}:item/{kind}','model':{'type':f'{NS}:animated_gear','gear':kind}}})
    write(ROOT/'design/models/lord-gear.geometry.json',manifest)
    write(RES/f'assets/{NS}/gear/geometry.json',manifest)
    print('Generated six animated item meshes and four articulated worn-armor meshes from the concept sheet.')


if __name__=='__main__': main()