mirror of
https://github.com/burrow-dev/burrow-server.git
synced 2026-11-18 17:27:50 -05:00
Brought up to date with the private repository (a06d3c5)
This commit is contained in:
commit
eda992fcff
144 files changed
+31026
No files matched your search
@@ -0,0 +1,85 @@
|
||||
import sys, pickle, os
|
||||
import xml.etree.ElementTree as ET
|
||||
here=os.path.dirname(os.path.abspath(__file__))
|
||||
pk=os.path.join(here,"hud.pickle")
|
||||
if os.path.exists(pk):
|
||||
D=pickle.load(open(pk,"rb"))
|
||||
else:
|
||||
root=ET.parse(os.path.join(here,"hud.xml")).getroot()
|
||||
tags=root.find("tags")
|
||||
D={"sprites":{}, "shapes":{}, "texts":{}, "names":{}}
|
||||
def rect(e):
|
||||
return tuple(int(e.get(k))/20 for k in ("Xmin","Ymin","Xmax","Ymax"))
|
||||
for it in tags:
|
||||
t=it.get("type")
|
||||
if t=="SymbolClassTag":
|
||||
ids=[int(x.text) for x in it.find("tags")]
|
||||
names=[x.text for x in it.find("names")]
|
||||
for i,n in zip(ids,names): D["names"][n]=i
|
||||
elif t=="DefineSpriteTag":
|
||||
sid=int(it.get("spriteId"))
|
||||
frames=[]; cur={}; labels={}
|
||||
disp={}
|
||||
fi=0
|
||||
for st in it.find("subTags"):
|
||||
tt=st.get("type")
|
||||
if tt in ("PlaceObject2Tag","PlaceObject3Tag"):
|
||||
depth=int(st.get("depth"))
|
||||
prev=disp.get(depth,{})
|
||||
o=dict(prev)
|
||||
if st.get("placeFlagHasCharacter")=="true": o["cid"]=int(st.get("characterId"))
|
||||
if st.get("placeFlagHasName")=="true": o["name"]=st.get("name")
|
||||
m=st.find("matrix")
|
||||
if st.get("placeFlagHasMatrix")=="true" and m is not None:
|
||||
o["x"]=int(m.get("translateX"))/20; o["y"]=int(m.get("translateY"))/20
|
||||
o["sx"]=float(m.get("scaleX")) if m.get("hasScale")=="true" else 1.0
|
||||
o["sy"]=float(m.get("scaleY")) if m.get("hasScale")=="true" else 1.0
|
||||
disp[depth]=o
|
||||
elif tt=="RemoveObject2Tag":
|
||||
disp.pop(int(st.get("depth")),None)
|
||||
elif tt=="FrameLabelTag":
|
||||
labels[st.get("name")]=fi
|
||||
elif tt=="ShowFrameTag":
|
||||
frames.append({d:dict(o) for d,o in disp.items()}); fi+=1
|
||||
D["sprites"][sid]={"frames":frames,"labels":labels}
|
||||
elif t and t.startswith("DefineShape"):
|
||||
D["shapes"][int(it.get("shapeId"))]=rect(it.find("shapeBounds"))
|
||||
elif t=="DefineEditTextTag":
|
||||
D["texts"][int(it.get("characterID"))]=(rect(it.find("bounds")), it.get("variableName"), it.get("initialText"), it.get("fontHeight"))
|
||||
pickle.dump(D,open(pk,"wb"))
|
||||
def bounds(cid, frame=0, seen=()):
|
||||
if cid in D["shapes"]: return D["shapes"][cid]
|
||||
if cid in D["texts"]: return D["texts"][cid][0]
|
||||
sp=D["sprites"].get(cid)
|
||||
if not sp or not sp["frames"] or cid in seen: return None
|
||||
b=None
|
||||
for o in sp["frames"][min(frame,len(sp["frames"])-1)].values():
|
||||
if "cid" not in o: continue
|
||||
cb=bounds(o["cid"],0,seen+(cid,))
|
||||
if not cb: continue
|
||||
x=o.get("x",0); y=o.get("y",0); sx=o.get("sx",1); sy=o.get("sy",1)
|
||||
xs=sorted([x+cb[0]*sx,x+cb[2]*sx]); ys=sorted([y+cb[1]*sy,y+cb[3]*sy])
|
||||
r=(xs[0],ys[0],xs[1],ys[1])
|
||||
b=r if b is None else (min(b[0],r[0]),min(b[1],r[1]),max(b[2],r[2]),max(b[3],r[3]))
|
||||
return b
|
||||
def fmt(b): return "?" if not b else "[%.0f,%.0f %.0fx%.0f]"%(b[0],b[1],b[2]-b[0],b[3]-b[1])
|
||||
def dump(cid, depth, maxd, frame=0, ind=""):
|
||||
sp=D["sprites"].get(cid)
|
||||
if not sp: return
|
||||
if sp["labels"]: print(ind+" labels:", ",".join(f"{k}@{v}" for k,v in list(sp["labels"].items())[:30]), "frames", len(sp["frames"]))
|
||||
for d,o in sorted(sp["frames"][min(frame,len(sp["frames"])-1)].items()):
|
||||
c=o.get("cid"); kind="sprite" if c in D["sprites"] else "text" if c in D["texts"] else "shape"
|
||||
extra=""
|
||||
if kind=="text": extra=" text=%r h=%s"%(D["texts"][c][2], D["texts"][c][3])
|
||||
print(f'{ind} d{d} {o.get("name","-")} ({kind} {c}) at {o.get("x",0):.0f},{o.get("y",0):.0f} scale {o.get("sx",1):.2f},{o.get("sy",1):.2f} bounds {fmt(bounds(c))}{extra}')
|
||||
if kind=="sprite" and depth<maxd: dump(c, depth+1, maxd, 0, ind+" ")
|
||||
if __name__=="__main__":
|
||||
name=sys.argv[1]; maxd=int(sys.argv[2]) if len(sys.argv)>2 else 2; frame=sys.argv[3] if len(sys.argv)>3 else "0"
|
||||
if name=="--list":
|
||||
for n in sorted(D["names"]):
|
||||
if maxd==0 or sys.argv[3].lower() in n.lower(): print(n, D["names"][n], fmt(bounds(D["names"][n])))
|
||||
sys.exit()
|
||||
cid=D["names"][name]; sp=D["sprites"][cid]
|
||||
f=sp["labels"].get(frame, int(frame) if frame.isdigit() else 0)
|
||||
print(name,"id",cid,"bounds",fmt(bounds(cid,f)),"frame",f)
|
||||
dump(cid,0,maxd,f)
|
||||
@@ -0,0 +1,168 @@
|
||||
"""transplant-nametag.py old.xml now.xml out.xml
|
||||
|
||||
Puts the name tags of the March 2014 HUDAssets.swf into today's. Both files
|
||||
are given as the XML `ffdec-cli -swf2xml` writes; the result goes back
|
||||
through `-xml2swf`. Everything is found by symbol and instance name, so it
|
||||
does not depend on either file's character ids.
|
||||
|
||||
What changes, and only this:
|
||||
|
||||
member tag The 2014 left cap and bar ("e" and "n" of memberNameBar, a
|
||||
clip each with one hand-drawn frame per colour) are copied
|
||||
in under new ids and added as a child named "old" on top of
|
||||
what today's "e" and "m" already hold. Nothing of today's is
|
||||
taken out: avatar.NameBar reaches into those two for a child
|
||||
called "mouse", and no login survives its absence. The old
|
||||
clips carry the same offsets inside as today's parts, so
|
||||
they go in at 0,0. swf-src/hud/memberNameBar.as shows the
|
||||
right frame and hides today's drawing.
|
||||
picker The ten samples in the animal editor (namebar_<colour>Cont):
|
||||
the "up" and "mouse" drawings inside each one's "mouse" clip
|
||||
are swapped for the 2014 ones, which sit at the same places.
|
||||
free tag Its drawing has not changed since 2014, pixel for pixel; the
|
||||
name on it was in the regular weight then and is bold now.
|
||||
The text field goes back to the regular font.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
old_path, now_path, out_path = sys.argv[1:4]
|
||||
COLOURS = ["black", "blue", "brown", "gold", "green", "pink", "purple", "red", "teal", "white"]
|
||||
OLD_DEPTH = 40 # above the parts already in today's cap and bar
|
||||
ID_ATTRS = ("spriteId", "shapeId", "characterId", "characterID", "bitmapId", "fontId", "buttonId")
|
||||
|
||||
|
||||
def read(path):
|
||||
"""-> (definitions by character id, character id by symbol name)"""
|
||||
tags = ET.parse(path).getroot().find("tags")
|
||||
defs, names = {}, {}
|
||||
for item in tags:
|
||||
kind = item.get("type", "")
|
||||
if kind == "SymbolClassTag":
|
||||
ids = [entry.text for entry in item.find("tags")]
|
||||
for cid, name in zip(ids, (entry.text for entry in item.find("names"))):
|
||||
names[name] = cid
|
||||
elif kind.startswith("Define"):
|
||||
for attr in ("spriteId", "shapeId", "characterID", "buttonId", "fontId"):
|
||||
if item.get(attr):
|
||||
defs.setdefault(item.get(attr), item)
|
||||
return defs, names
|
||||
|
||||
|
||||
def child(defs, sprite_id, name):
|
||||
"""Character id of the child called `name` on a sprite's first frame."""
|
||||
for tag in defs[sprite_id].find("subTags"):
|
||||
if tag.get("type") == "ShowFrameTag":
|
||||
break
|
||||
if tag.get("name") == name and tag.get("characterId"):
|
||||
return tag.get("characterId")
|
||||
raise SystemExit(f"sprite {sprite_id} has no child called {name}")
|
||||
|
||||
|
||||
old, old_names = read(old_path)
|
||||
now, now_names = read(now_path)
|
||||
|
||||
wanted = {}
|
||||
old_tag, now_tag = old_names["memberNameBar"], now_names["memberNameBar"]
|
||||
add_old = { # today's sprite -> the 2014 clip it gets as "old"
|
||||
child(now, now_tag, "e"): child(old, old_tag, "e"),
|
||||
child(now, now_tag, "m"): child(old, old_tag, "n"),
|
||||
}
|
||||
retarget = {} # (today's sprite, child name) -> the 2014 character to place there
|
||||
for colour in COLOURS:
|
||||
symbol = f"namebar_{colour}Cont"
|
||||
old_states = child(old, old_names[symbol], "mouse")
|
||||
now_states = child(now, now_names[symbol], "mouse")
|
||||
for state in ("up", "mouse"):
|
||||
retarget[(now_states, state)] = child(old, old_states, state)
|
||||
for cid in list(add_old.values()) + list(retarget.values()):
|
||||
wanted[cid] = True
|
||||
|
||||
|
||||
def references(element):
|
||||
found = set()
|
||||
for sub in element.iter():
|
||||
if sub is element:
|
||||
continue
|
||||
for attr in ("characterId", "bitmapId", "fontId"):
|
||||
value = sub.get(attr)
|
||||
if value and value != "65535":
|
||||
found.add(value)
|
||||
return found
|
||||
|
||||
|
||||
order, seen = [], set()
|
||||
|
||||
|
||||
def visit(cid):
|
||||
if cid in seen:
|
||||
return
|
||||
if cid not in old:
|
||||
raise SystemExit(f"the 2014 file has no definition for character {cid}")
|
||||
seen.add(cid)
|
||||
for ref in sorted(references(old[cid]), key=int):
|
||||
visit(ref)
|
||||
order.append(cid) # what a thing is made of comes before it
|
||||
|
||||
|
||||
for cid in wanted:
|
||||
visit(cid)
|
||||
kinds = {}
|
||||
for cid in order:
|
||||
kinds[old[cid].get("type")] = kinds.get(old[cid].get("type"), 0) + 1
|
||||
print("copying", len(order), "definitions:", kinds)
|
||||
|
||||
text = open(now_path, encoding="utf8").read()
|
||||
highest = max(int(value) for value in re.findall(r'(?:spriteId|shapeId|characterID|buttonId|fontId|characterId)="(\d+)"', text) if int(value) < 60000)
|
||||
new_id = {cid: str(highest + 1 + index) for index, cid in enumerate(order)}
|
||||
chunks = []
|
||||
for cid in order:
|
||||
element = old[cid]
|
||||
for sub in element.iter():
|
||||
for attr in ID_ATTRS:
|
||||
if sub.get(attr) in new_id:
|
||||
sub.set(attr, new_id[sub.get(attr)])
|
||||
chunks.append(ET.tostring(element, encoding="unicode").strip())
|
||||
|
||||
|
||||
def sprite_span(source, sprite_id):
|
||||
"""(start, end) of a sprite's definition in the XML text."""
|
||||
start = re.search(r'[ \t]*<item type="DefineSpriteTag"[^>]*spriteId="%s"[^>]*>' % sprite_id, source)
|
||||
assert start, f"sprite {sprite_id} not found in today's file"
|
||||
indent = re.match(r'[ \t]*', start.group(0)).group(0)
|
||||
closing = "\n" + indent + "</item>"
|
||||
return start.start(), source.index(closing, start.end()) + len(closing)
|
||||
|
||||
|
||||
free_text = child(now, child(now, now_names["FreeNameBar"], "c"), "txt")
|
||||
field = re.search(r'<item type="DefineEditTextTag"[^>]*characterID="%s"[^>]*>' % free_text, text)
|
||||
assert field and 'fontClass="CCDigitalDeliveryBold"' in field.group(0)
|
||||
plain = field.group(0).replace('fontClass="CCDigitalDeliveryBold"', 'fontClass="CCDigitalDeliveryRegular"').replace("<b>", "").replace("</b>", "")
|
||||
text = text[:field.start()] + plain + text[field.end():]
|
||||
|
||||
for (sprite_id, name), old_cid in retarget.items():
|
||||
start, end = sprite_span(text, sprite_id)
|
||||
sprite = text[start:end]
|
||||
pattern = re.compile(r'(<item type="PlaceObject[23]Tag"[^>]*?)characterId="\d+"([^>]*?name="%s")' % name)
|
||||
sprite, count = pattern.subn(lambda match: f'{match.group(1)}characterId="{new_id[old_cid]}"{match.group(2)}', sprite)
|
||||
assert count == 1, (sprite_id, name, count)
|
||||
text = text[:start] + sprite + text[end:]
|
||||
|
||||
for sprite_id, old_cid in add_old.items():
|
||||
start, end = sprite_span(text, sprite_id)
|
||||
show = text.index('<item type="ShowFrameTag"', start)
|
||||
assert show < end
|
||||
place = ('<item type="PlaceObject2Tag" characterId="%s" depth="%d" forceWriteAsLong="true" name="old" '
|
||||
'placeFlagHasCharacter="true" placeFlagHasClipActions="false" placeFlagHasClipDepth="false" '
|
||||
'placeFlagHasColorTransform="false" placeFlagHasMatrix="true" placeFlagHasName="true" '
|
||||
'placeFlagHasRatio="false" placeFlagMove="false">'
|
||||
'<matrix type="MATRIX" hasRotate="false" hasScale="false" nRotateBits="0" nScaleBits="0" '
|
||||
'nTranslateBits="0" translateX="0" translateY="0"/></item>\n ') % (new_id[old_cid], OLD_DEPTH)
|
||||
text = text[:show] + place + text[show:]
|
||||
|
||||
first = min(sprite_span(text, sprite_id)[0] for sprite_id in list(add_old) + [key[0] for key in retarget])
|
||||
indent = re.match(r'[ \t]*', text[first:]).group(0)
|
||||
text = text[:first] + "".join(indent + chunk + "\n" for chunk in chunks) + text[first:]
|
||||
open(out_path, "w", encoding="utf8").write(text)
|
||||
print("written", out_path)
|
||||
Reference in new issue
Block a user