source: trunk/game/utilities/agentXmlGen.py @ 316

Revision 316, 6.1 KB checked in by orlandov, 10 years ago (diff)

Patch by or1landov:

  • Run the agentXmlGen against the NPC animations
  • Fix a small bug in agentXmlGen
  • Add the NPC's we have to date into the test map
  • Ran "xmllint --format" on the map file
  • Property svn:executable set to *
Line 
1#!/usr/bin/python
2
3#   This program is free software: you can redistribute it and/or modify
4#   it under the terms of the GNU General Public License as published by
5#   the Free Software Foundation, either version 3 of the License, or
6#   (at your option) any later version.
7
8#   This program is distributed in the hope that it will be useful,
9#   but WITHOUT ANY WARRANTY; without even the implied warranty of
10#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#   GNU General Public License for more details.
12
13#   You should have received a copy of the GNU General Public License
14#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16import os, sys, getopt, logging, re
17
18log = logging.getLogger("agentxml")
19log.setLevel(logging.DEBUG)
20
21def generateAgent(path, delay, xoff, yoff):
22    """ Generates the agent XML file and creates animation
23    XML files for found children.
24    @type path: string
25    @param path: Agent path
26    @type delay: string
27    @param delay: Animation delay (used in animation.xml)
28    @type xoff: string
29    @param xoff: X offset (used in animation.xml)
30    @type yoff: string
31    @param yoff: Y offset (used in animation.xml)
32    @return True on success, False on failure
33    """
34    # Name is the last subdirectory
35    name=os.path.split(os.path.abspath(path))[1]
36    log.debug("Doing animation for agent: %s", name)
37
38    f = open(os.path.join(path,name + ".xml"), 'w')           
39    log.debug("Opened " + os.path.join(path,name + ".xml"))
40    f.write('<?fife type="object"?>\n')
41    f.write('<object id="%s" namespace="PARPG" blocking="1" static="0">\n' % (name,))
42
43    # Iterate the animations
44    anims = os.listdir(path)
45    anims.sort()
46    for anim in anims:
47        animpath=os.path.join(path,anim)
48        if os.path.isdir(animpath) and anim.find("svn")==-1:
49            log.debug("Found animation: %s", anim)
50            f.write('\t<action id="' + anim +'">\n')
51            angles = os.listdir(animpath)
52            angles.sort()
53            for angle in angles:
54                anglepath=os.path.join(animpath,angle)
55                if os.path.isdir(anglepath) and angle.find("svn")==-1:
56                    log.debug("Found angle: %s", angle)
57                    f.write('\t\t<animation source="' + anim + '/' + angle
58                            + '/animation.xml" direction="' 
59                            + str(int(angle)) + '" />\n')
60                    if not generateAnimation(anglepath,delay,xoff,yoff):
61                        log.error("Failed to create animation for " + anum + " (angle: " + angle + ")")
62            f.write('\t</action>\n')
63    f.write('</object>\n')
64    f.close()
65    log.info("Wrote " + os.path.join(path,name + ".xml"))
66    return True
67
68def imageCompare(x,y):
69    """ Compares two filenames containing a number
70    @type x: string
71    @param x: First filename
72    @type y: string
73    @param y: second filename
74    @return 1 of x>y, 0 when x==y,  -1 when y<x.
75    """
76    regex="[^0-9]*([0-9]*).*"
77    try:
78        intX=int(re.sub(regex,"\\1",x))
79    except:
80        intX=-1
81
82    try:
83        intY=int(re.sub(regex,"\\1",y))
84    except:
85        intY=-1
86   
87    if intX>intY:
88        return 1
89    elif intX<intY:
90        return -1;
91   
92    return 0
93
94def generateAnimation(path, delay, xoff, yoff):
95    """ Generate animation.xml for a given path.
96    @type path: string
97    @param path: Agent path
98    @type delay: string
99    @param delay: Animation delay
100    @type xoff: string
101    @param xoff: X offset
102    @type yoff: string
103    @param yoff: Y offset
104    @return True on success, False on failure """
105
106    (tmp,angle)=os.path.split(os.path.abspath(path))
107    (tmp,anim)=os.path.split(tmp)
108    (tmp,agent)=os.path.split(tmp)
109    id="%s:%s:%s"%(agent,anim,angle)
110    log.debug("Doing animation with id: %s" % (id))
111
112    images=os.listdir(path)
113    # Get those with the correct extension
114    imagesfiltered=[]
115    for image in images:
116        if image.endswith(".png"):
117            imagesfiltered.append(image)
118
119
120    f = open(os.path.join(path,"animation.xml"), 'w')   
121    log.debug("Opened: " + os.path.join("animation.xml"))
122    f.write('<animation delay="' + delay + '" namespace="PAPRG" id="' + id 
123            + '" x_offset="' + xoff
124            + '" y_offset="' + yoff + '">\n')
125
126    # Sort them
127    imagesfiltered.sort(cmp=imageCompare)
128    for image in imagesfiltered:
129        log.debug("Found image: %s" % image)
130        f.write('\t<frame source="' + image + '" />\n')
131
132    f.write('</animation>\n')
133    f.close()
134    log.info("Wrote: " + os.path.join(path,"animation.xml"))
135    return True 
136
137def usage():
138    """ Prints the help message. """
139    print "Usage: %s [options]" % sys.argv[0]
140    print "Options:"
141    print "   --verbose, -v      Verbose"
142    print "   --help, -h         This help message"
143    print "   --path DIR, -p     Root path of the agent (default .)"
144    print "   --delay DLY, -d    Delay value (default 100)"
145    print "   --x_offset OFF, -x X Offset (default 0)"
146    print "   --y_offset OFF, -y Y Offset (default 0)"
147
148def main(argv):
149    """ Main function, parses the command line arguments
150    and launches the xml file creation logic. """
151
152    try:
153        opts, args = getopt.getopt(argv, "hp:d:x:y:v", 
154        ["help","path","delay", "x_offset", "y_offset", "verbose"])
155    except getopt.GetoptError:
156        usage()
157        sys.exit(2)
158
159    agentpath="."
160    delay="100"
161    x_offset="0"
162    y_offset="0"
163    verbose=False
164
165    ch = logging.StreamHandler()
166    ch.setLevel(logging.INFO)
167
168    for opt, arg in opts:       
169        if opt in ("-p","--path"):
170            agentpath=path
171        elif opt in ("-d","--delay"):
172            delay=arg
173        elif opt in ("-x","--x_offset"):
174            x_offset=arg
175        elif opt in ("-y","--y_offset"):
176            y_offset=arg
177        elif opt in ("-v","--verbose"):
178            ch.setLevel(logging.DEBUG)
179        else:
180            usage()
181            sys.exit()
182
183    formatter = logging.Formatter("%(levelname)s: %(message)s")
184    ch.setFormatter(formatter)
185    log.addHandler(ch)
186
187    log.debug("Going to generate animation for %s" %(agentpath))
188    generateAgent(agentpath, delay, x_offset, y_offset)
189    log.info("Done");
190
191if __name__ == '__main__':
192    main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.