Browse Source

PEP8 clean up for python tools

PEP8 (Python style guide)
https://www.python.org/dev/peps/pep-0008/

- Move imports to top
  https://www.python.org/dev/peps/pep-0008/#imports
- Fix tabs/indentation
  https://www.python.org/dev/peps/pep-0008/#indentation
- Remove unused modules
- Use ``import __future__`` for python 2 compatibility (most POSIX systems
  haven't switched to python 3 by default yet)
- Use ``class ClassName(object)`` for python 2 backward compatibility
- Add source file encoding tag
  https://www.python.org/dev/peps/pep-0008/#source-file-encoding
- Shebang to #!/usr/bin/env python for portability
- Where possible trim line length to 79 char
  https://www.python.org/dev/peps/pep-0008/#maximum-line-length
Tony Narlock 10 years ago
parent
commit
de0fc0e503

+ 126 - 121
tools/gen_template.py

@@ -1,31 +1,41 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 
-from string import Template
 import os
 import io
 import glob
 import shutil
-from mimetypes import guess_type
-from mimetypes import add_type
+import random
+import argparse
+import sys
+
+from string import Template
+from mimetypes import add_type, guess_type
 
+if sys.version_info[0] >= 3:
+    unicode = str
 
 
 platforms = ("win32", "android", "macosx", "ios", "cmake", "emscripten", "all")
 
+
 def relpath(a, b):
     try:
         return os.path.relpath(a, b)
     except ValueError:
-        pass   
+        pass
     return a
 
+
 def unixpath(path):
     return path.replace("\\", "/")
 
+
 def run(args):
     if args.hello:
         dest = args.dest
-        
+
         local = os.path.dirname(__file__)
         if not local:
             local = "."
@@ -42,7 +52,7 @@ def run(args):
             shutil.copytree(data, dest + "/data")
         except OSError:
             pass
-        
+
         for p in platforms:
             if p == "all":
                 continue
@@ -52,23 +62,23 @@ def run(args):
             _run(args)
     else:
         _run(args)
-            
+
 
 def _run(args):
     name = args.name
     project = "proj." + args.type + "/"
-    values = {"PROJECT":name}
-
+    values = {"PROJECT": name}
 
-    text = (".properties", ".cmd", ".mk", ".java", ".sln", ".vcxproj", ".filters", ".user", ".plist", ".pch", ".json", ".pbxproj")
+    text = (".properties", ".cmd", ".mk", ".java", ".sln", ".vcxproj",
+            ".filters", ".user", ".plist", ".pch", ".json", ".pbxproj")
     for t in text:
         add_type("text/plain", t)
 
     try:
         os.makedirs(args.dest)
     except OSError:
-        #print "folder already exists"
-        #return
+        # print "folder already exists"
+        # return
         pass
 
     templates_path = os.path.dirname(__file__)
@@ -76,30 +86,27 @@ def _run(args):
         templates_path = "."
     templates_path += "/templates/"
     ox_path = templates_path + "/../../"
-    root_path = ox_path + "../"    
+    root_path = ox_path + "../"
     root_path = os.path.abspath(root_path)
     ox_path = os.path.abspath(ox_path)
 
-
     dest_path = os.path.abspath(args.dest) + "/"
 
     root_path = relpath(root_path, dest_path) + "/"
     ox_path = relpath(ox_path, dest_path) + "/"
 
-
     values["OXYGINE"] = unixpath(ox_path)
     values["ROOT"] = unixpath(root_path)
 
-
-    def process(template, relto, path, gl, fn = None):
+    def process(template, relto, path, gl, fn=None):
         res = ""
         for src in gl:
             ext = os.path.splitext(src)[1]
             if ext in (".icf", ".orig"):
                 continue
 
-            rel_src_path = relpath(src, relto)    
-            data = {"FILE":unixpath(rel_src_path), "FULLFILE":src}
+            rel_src_path = relpath(src, relto)
+            data = {"FILE": unixpath(rel_src_path), "FULLFILE": src}
             if fn:
                 data = fn(data)
             t = Template(template)
@@ -112,16 +119,16 @@ def _run(args):
 
     data = "../data"
     abs_data = os.path.normpath(args.dest + "/" + data)
-    
+
     data_files_ = sorted(glob.glob(abs_data + "/*"))
     data_files = []
     for d in data_files_:
-        if os.path.splitext(d)[1]  in (".dll", ".lib"):
+        if os.path.splitext(d)[1] in (".dll", ".lib"):
             continue
         data_files.append(d)
 
     cpp_files = sorted(glob.glob(args.src + "/*.cpp"))
-    h_files = sorted(glob.glob(args.src + "/*.h") )   
+    h_files = sorted(glob.glob(args.src + "/*.h"))
 
     values["PBXBuildFile"] = ""
     values["PBXFileReference"] = ""
@@ -129,42 +136,41 @@ def _run(args):
     values["PBXGroupSupporting"] = ""
     values["PBXResourcesBuildPhase"] = ""
     values["PBXSourcesBuildPhase"] = ""
-    
 
     if args.src:
-        
+
         relto = dest_path
 
         if args.type == "android":
             tmsrc = "${FILE} "
             relto = dest_path + "/jni/src/"
-            
+
             SRC = process(tmsrc, relto, args.src, cpp_files)
-            #INCLUDE = process(tminc, relto, args.src, h_files)              
+            # INCLUDE = process(tminc, relto, args.src, h_files)
 
         if args.type == "cmake" or args.type == "emscripten":
             tmsrc = "${FILE} "
             relto = dest_path
-            
+
             SRC = process(tmsrc, relto, args.src, cpp_files)
-            INCLUDE = process(tmsrc, relto, args.src, h_files)              
-            
+            INCLUDE = process(tmsrc, relto, args.src, h_files)
+
         if args.type == "win32":
             tmsrc = """<ClCompile Include="${FILE}" />"""
             tminc = """<ClInclude Include="${FILE}" />"""
-            
+
             SRC = process(tmsrc, relto, args.src, cpp_files)
-            INCLUDE = process(tminc, relto, args.src, h_files)              
-            
+            INCLUDE = process(tminc, relto, args.src, h_files)
 
         if args.type in ("macosx", "ios"):
-            import random            
             r = random.Random()
             r.seed(1)
 
-            class Refs:
+            class Refs(object):
+
                 def __init__(self):
                     self._refs = []
+
                 def getObject(self, file):
                     for ref in self._refs:
                         if ref[0] == file:
@@ -174,13 +180,13 @@ def _run(args):
                         obj += r.choice("0123456789ABCDEF")
                     self._refs.append((file, obj))
                     return obj
-                def getFile(obj):
+
+                def getFile(self, obj):
                     for ref in self._refs:
                         if ref[1] == obj:
                             return ref[0]
                     raise KeyError
 
-
             globalRefs = Refs()
             fileRefs = Refs()
 
@@ -200,91 +206,90 @@ def _run(args):
                     if ext == ".h":
                         tp = "sourcecode.c.h"
 
-
                 values["TYPE"] = tp
                 return values
 
+            # 0405A0061872139000BA6557 /* demo in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0021872139000BA6557 /* demo */; };
+            # 0405A0071872139000BA6557 /* ext in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0031872139000BA6557 /* ext */; };
+            # 0405A0081872139000BA6557 /* images in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0041872139000BA6557 /* images */; };
+            # 0405A0091872139000BA6557 /* xmls in Resources */ = {isa =
+            # PBXBuildFile; fileRef = 0405A0051872139000BA6557 /* xmls */; };
+
+            # 04A57D601871FF9F0068B1E5 /* entry_point.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */; };
+            # 04A57D621871FF9F0068B1E5 /* example.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04A57D3C1871FF9F0068B1E5 /* example.cpp */; };
+            # 04A57D651871FF9F0068B1E5 /* test.cpp in Sources */ = {isa =
+            # PBXBuildFile; fileRef = 04A57D401871FF9F0068B1E5 /* test.cpp */;
+            # };
+
+            tm = "\t\t${GREF} /* ${FILE} in Sources */ = {isa = PBXBuildFile; fileRef = ${FREF} /* ${FILE} */; };\n"
+            values["PBXBuildFile"] = process(
+                tm, relto, args.src, cpp_files, fn)
+            values[
+                "PBXBuildFile"] += process(tm, relto, abs_data, data_files, fn)
+
+            # 04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = entry_point.cpp; path = ../../src/entry_point.cpp; sourceTree = "<group>"; };
+            # 04A57D3C1871FF9F0068B1E5 /* example.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = example.cpp; path = ../../src/example.cpp; sourceTree = "<group>"; };
+            # 04A57D3E1871FF9F0068B1E5 /* example.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = example.h; path = ../../src/example.h; sourceTree = "<group>"; };
+            # 04A57D401871FF9F0068B1E5 /* test.cpp */ = {isa =
+            # PBXFileReference; fileEncoding = 4; lastKnownFileType =
+            # sourcecode.cpp.cpp; name = test.cpp; path = ../../src/test.cpp;
+            # sourceTree = "<group>"; };
+
+            # 0405A0021872139000BA6557 /* demo */ = {isa = PBXFileReference; lastKnownFileType = folder; name = demo; path = ../../data/demo; sourceTree = "<group>"; };
+            # 0405A0031872139000BA6557 /* ext */ = {isa = PBXFileReference; lastKnownFileType = folder; name = ext; path = ../../data/ext; sourceTree = "<group>"; };
+            # 0405A0041872139000BA6557 /* images */ = {isa = PBXFileReference; lastKnownFileType = folder; name = images; path = ../../data/images; sourceTree = "<group>"; };
+            # 0405A0051872139000BA6557 /* xmls */ = {isa = PBXFileReference;
+            # lastKnownFileType = folder; name = xmls; path = ../../data/xmls;
+            # sourceTree = "<group>"; };
 
-            #0405A0061872139000BA6557 /* demo in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0021872139000BA6557 /* demo */; };
-            #0405A0071872139000BA6557 /* ext in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0031872139000BA6557 /* ext */; };
-            #0405A0081872139000BA6557 /* images in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0041872139000BA6557 /* images */; };
-            #0405A0091872139000BA6557 /* xmls in Resources */ = {isa = PBXBuildFile; fileRef = 0405A0051872139000BA6557 /* xmls */; };
-
-
-            #04A57D601871FF9F0068B1E5 /* entry_point.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */; };
-            #04A57D621871FF9F0068B1E5 /* example.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04A57D3C1871FF9F0068B1E5 /* example.cpp */; };
-            #04A57D651871FF9F0068B1E5 /* test.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 04A57D401871FF9F0068B1E5 /* test.cpp */; };     	    
-
-            tm = "\t\t${GREF} /* ${FILE} in Sources */ = {isa = PBXBuildFile; fileRef = ${FREF} /* ${FILE} */; };\n"  
-            values["PBXBuildFile"] = process(tm, relto, args.src, cpp_files, fn)
-            values["PBXBuildFile"]+= process(tm, relto, abs_data, data_files, fn)
-
-
-            #04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = entry_point.cpp; path = ../../src/entry_point.cpp; sourceTree = "<group>"; };
-            #04A57D3C1871FF9F0068B1E5 /* example.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = example.cpp; path = ../../src/example.cpp; sourceTree = "<group>"; };
-            #04A57D3E1871FF9F0068B1E5 /* example.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = example.h; path = ../../src/example.h; sourceTree = "<group>"; };
-            #04A57D401871FF9F0068B1E5 /* test.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = test.cpp; path = ../../src/test.cpp; sourceTree = "<group>"; };
-
-            #0405A0021872139000BA6557 /* demo */ = {isa = PBXFileReference; lastKnownFileType = folder; name = demo; path = ../../data/demo; sourceTree = "<group>"; };
-            #0405A0031872139000BA6557 /* ext */ = {isa = PBXFileReference; lastKnownFileType = folder; name = ext; path = ../../data/ext; sourceTree = "<group>"; };
-            #0405A0041872139000BA6557 /* images */ = {isa = PBXFileReference; lastKnownFileType = folder; name = images; path = ../../data/images; sourceTree = "<group>"; };
-            #0405A0051872139000BA6557 /* xmls */ = {isa = PBXFileReference; lastKnownFileType = folder; name = xmls; path = ../../data/xmls; sourceTree = "<group>"; };	    
-
-            
             files = []
             files.extend(cpp_files)
             files.extend(h_files)
             files.extend(data_files)
-            
-            tm = """\t\t${FREF} /* ${FILE} */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = ${TYPE}; name = ${NAME}; path = ${FILE}; sourceTree = "<group>"; };""" + "\n"              
-            values["PBXFileReference"] = process(tm, relto, args.src, files, fn)
 
+            tm = """\t\t${FREF} /* ${FILE} */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = ${TYPE}; name = ${NAME}; path = ${FILE}; sourceTree = "<group>"; };""" + "\n"
+            values["PBXFileReference"] = process(
+                tm, relto, args.src, files, fn)
 
-            #04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */,
-            #04A57D3C1871FF9F0068B1E5 /* example.cpp */,
-            #04A57D3E1871FF9F0068B1E5 /* example.h */,
-            #04A57D401871FF9F0068B1E5 /* test.cpp */,   
+            # 04A57D3A1871FF9F0068B1E5 /* entry_point.cpp */,
+            # 04A57D3C1871FF9F0068B1E5 /* example.cpp */,
+            # 04A57D3E1871FF9F0068B1E5 /* example.h */,
+            # 04A57D401871FF9F0068B1E5 /* test.cpp */,
 
-            tm = "\t\t\t\t${FREF} /* ${NAME} */, \n"   
+            tm = "\t\t\t\t${FREF} /* ${NAME} */, \n"
 
             files = []
             files.extend(cpp_files)
             files.extend(h_files)
-            values["PBXGroup_src"] = process(tm, relto, args.src, files, fn)	    
-
-
-
-            #0405A0021872139000BA6557 /* demo */,
-            #0405A0031872139000BA6557 /* ext */,
-            #0405A0041872139000BA6557 /* images */,
-            #0405A0051872139000BA6557 /* xmls */,     
-
-            values["PBXGroupSupporting"] = process(tm, relto, abs_data, data_files, fn)
-
-
-            #0405A0081872139000BA6557 /* images in Resources */,
-            #0405A0071872139000BA6557 /* ext in Resources */,
-            #0405A0061872139000BA6557 /* demo in Resources */,				
-            #0405A0091872139000BA6557 /* xmls in Resources */,	
-            tm = "\t\t\t\t${GREF} /* ${NAME} */, \n" 
-            values["PBXResourcesBuildPhase"] = process(tm, relto, abs_data, data_files, fn)
-
-            #04A57D621871FF9F0068B1E5 /* example.cpp in Sources */,
-            #04A57D601871FF9F0068B1E5 /* entry_point.cpp in Sources */,
-            #04A57D651871FF9F0068B1E5 /* test.cpp in Sources */,     
-            values["PBXSourcesBuildPhase"] = process(tm, relto, args.src, cpp_files, fn)
-
-
-
-            
+            values["PBXGroup_src"] = process(tm, relto, args.src, files, fn)
+
+            # 0405A0021872139000BA6557 /* demo */,
+            # 0405A0031872139000BA6557 /* ext */,
+            # 0405A0041872139000BA6557 /* images */,
+            # 0405A0051872139000BA6557 /* xmls */,
+
+            values["PBXGroupSupporting"] = process(
+                tm, relto, abs_data, data_files, fn)
+
+            # 0405A0081872139000BA6557 /* images in Resources */,
+            # 0405A0071872139000BA6557 /* ext in Resources */,
+            # 0405A0061872139000BA6557 /* demo in Resources */,
+            # 0405A0091872139000BA6557 /* xmls in Resources */,
+            tm = "\t\t\t\t${GREF} /* ${NAME} */, \n"
+            values["PBXResourcesBuildPhase"] = process(
+                tm, relto, abs_data, data_files, fn)
+
+            # 04A57D621871FF9F0068B1E5 /* example.cpp in Sources */,
+            # 04A57D601871FF9F0068B1E5 /* entry_point.cpp in Sources */,
+            # 04A57D651871FF9F0068B1E5 /* test.cpp in Sources */,
+            values["PBXSourcesBuildPhase"] = process(
+                tm, relto, args.src, cpp_files, fn)
 
     values["SRC"] = SRC
     values["INCLUDE"] = INCLUDE
 
-
     values["DATA"] = "../data"
 
-
     def process_folder(path, dest):
         try:
             os.mkdir(dest)
@@ -292,21 +297,19 @@ def _run(args):
             pass
 
         for src in os.listdir(path):
-            src_path = path + src         
+            src_path = path + src
             t = Template(src)
             dest_local = t.substitute(**values)
 
             if os.path.isdir(src_path):
 
-                process_folder(src_path + "/", dest + dest_local + "/")         
+                process_folder(src_path + "/", dest + dest_local + "/")
                 continue
 
             dest_path = dest + dest_local
 
             ext = os.path.splitext(dest_path)[1]
 
-
-            from mimetypes import guess_type
             print("src " + src_path)
             tp = guess_type(src_path)
 
@@ -325,46 +328,48 @@ def _run(args):
                 print("creating file: " + dest_path)
                 src_data = open(src_path, "r").read()
                 t = Template(src_data)
-                dest_data = t.safe_substitute(**values)                 
+                dest_data = t.safe_substitute(**values)
 
                 ext = os.path.splitext(dest_path)[1]
 
-                if args.type == "ios" or args.type == "macosx" or ext==".sh":
+                if args.type == "ios" or args.type == "macosx" or ext == ".sh":
                     dest_file = io.open(dest_path, "w", newline="\n")
                     try:
-                        dest_file.write(dest_data) 
+                        dest_file.write(dest_data)
                     except TypeError:
-                        dest_file.write(unicode(dest_data, encoding='utf-8')) 
+                        dest_file.write(unicode(dest_data, encoding='utf-8'))
 
                 else:
                     dest_file = open(dest_path, "w")
-                    dest_file.write(dest_data)      
+                    dest_file.write(dest_data)
 
                 shutil.copystat(src_path, dest_path)
-                
+
             else:
-                print("copying file: " + dest_path)                                
+                print("copying file: " + dest_path)
                 shutil.copyfile(src_path, dest_path)
 
-
     top_path = templates_path + project + "/"
 
     process_folder(top_path, args.dest + "/")
 
 
 if __name__ == "__main__":
-    import argparse	
-    parser = argparse.ArgumentParser(description="oxygine projects template generator")
-    parser.add_argument("-t", "--type", help = "choose your IDE/build tools", 
-                        choices = platforms, default = "win32")
+    parser = argparse.ArgumentParser(
+        description="oxygine projects template generator")
+    parser.add_argument("-t", "--type", help="choose your IDE/build tools",
+                        choices=platforms, default="win32")
 
-    parser.add_argument("-s", "--src", help = "folder with already created source files", default = "")   
+    parser.add_argument(
+        "-s", "--src", help="folder with already created source files", default="")
 
-    parser.add_argument("-d", "--dest", help = "destination location", default = ".")
+    parser.add_argument(
+        "-d", "--dest", help="destination location", default=".")
 
-    parser.add_argument("--hello", help = "generates full copy of HelloWorld example. It includes all platforms, data and src folder", action="store_true", default = False)
+    parser.add_argument("--hello", help="generates full copy of HelloWorld example. It includes all platforms, data and src folder",
+                        action="store_true", default=False)
 
     parser.add_argument("name")
 
     args = parser.parse_args()
-    run(args)
+    run(args)

+ 99 - 82
tools/gen_view_code.py

@@ -1,27 +1,37 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 import os
+import sys
+
 from xml.dom import minidom
+
+from jinja2 import Environment, FileSystemLoader
+
 from gen_view_code.class_type import class_type
-import sys
-PY3 = sys.version > '3'
 
-class class_member:
+PY3 = sys.version_info[0] > '3'
+
+
+class class_member(object):
+
     def __init__(self, name, ct):
         self.name = name
         self.class_type = ct
 
-def get_plain_actors(root, res):    
-    for node in root.childNodes:        
+
+def get_plain_actors(root, res):
+    for node in root.childNodes:
         if node.nodeType == node.TEXT_NODE:
-            continue        
+            continue
         res.append(node)
         get_plain_actors(node, res)
-                
-def save_if_changed(name, content):    
+
+
+def save_if_changed(name, content):
     try:
         with open(name, "r") as rd:
-            data = rd.read()            
+            data = rd.read()
             if data == content:
                 return
     except IOError:
@@ -31,7 +41,6 @@ def save_if_changed(name, content):
         rd.write(content)
 
 
-
 mp_actor = class_type("spActor", "Actor", "Actor.h")
 mp_button = class_type("spButton", "Button", "Button.h")
 mp_text = class_type("spTextField", "TextField", "TextField.h")
@@ -39,24 +48,26 @@ mp_bar = class_type("spProgressBar", "ProgressBar", "ProgressBar.h")
 mp_clip = class_type("spClipRectActor", "ClipRectActor", "ClipRectActor.h")
 mp_sprite = class_type("spSprite", "Sprite", "Sprite.h")
 mp_sliding = class_type("spSlidingActor", "SlidingActor", "SlidingActor.h")
-mp_color = class_type("spColorRectSprite", "ColorRectSprite", "ColorRectSprite.h")
-mp_box9sprite = class_type("spBox9Sprite", "Box9Sprite", "Box9Sprite.h")    
-mp_polygon = class_type("spPolygon", "Polygon", "Polygon.h")    
-mp_msprite = class_type("spMaskedSprite", "MaskedSprite", "MaskedSprite.h")    
-mp_view = class_type("spView", "View", "View.h")    
+mp_color = class_type("spColorRectSprite",
+                      "ColorRectSprite", "ColorRectSprite.h")
+mp_box9sprite = class_type("spBox9Sprite", "Box9Sprite", "Box9Sprite.h")
+mp_polygon = class_type("spPolygon", "Polygon", "Polygon.h")
+mp_msprite = class_type("spMaskedSprite", "MaskedSprite", "MaskedSprite.h")
+mp_view = class_type("spView", "View", "View.h")
 
 def_mappings = (mp_bar,
                 mp_clip,
                 mp_button,
                 mp_text,
                 mp_actor,
-                mp_sprite, 
+                mp_sprite,
                 mp_sliding,
                 mp_color,
                 mp_box9sprite,
                 mp_polygon,
                 mp_msprite)
 
+
 def get_mapping(lst, name):
     for m in lst:
         if m.className == name:
@@ -65,6 +76,8 @@ def get_mapping(lst, name):
     return None
 
 user_mp = None
+
+
 def find_mapping(name, classes):
     if user_mp:
         mp = get_mapping(user_mp, name)
@@ -74,111 +87,112 @@ def find_mapping(name, classes):
     mp = get_mapping(def_mappings, name)
     if mp:
         return mp
-    
+
     mp = get_mapping(classes, name)
     if mp:
         return mp
 
-    return None            
+    return None
+
 
 def gen_classes(nodes, ct, classes):
     classes.add(ct)
-    
+
     for child in nodes:
         class_mapping = mp_actor
 
         member = child.attrib["member"]
-        
+
         res_id = ""
         if "id" in child.attrib:
             res_id = child.attrib["id"]
 
         if not res_id:
             res_id = os.path.splitext(child.attrib["file"])[0]
-            class_mapping = mp_sprite        
+            class_mapping = mp_sprite
 
         if "ref" in child.attrib:
-            class_mapping = mp_sprite        
+            class_mapping = mp_sprite
 
         try:
-            #print res_id
-            
+            # print res_id
+
             class_name = child.attrib["class"]
             class_mapping = find_mapping(class_name, classes)
 
-            
             if not class_mapping:
                 if class_name.endswith("<"):
                     class_name = class_name.rstrip("<")
-                    class_mapping = class_type(class_name, "sp" + class_name, class_name, class_name + ".h", ns = "", member = res_id, parent = mp_sprite, generated=True)
+                    class_mapping = class_type(
+                        class_name, "sp" + class_name, class_name,
+                        class_name + ".h", ns="", member=res_id,
+                        parent=mp_sprite, generated=True)
                     gen_classes(nodes, class_mapping, classes)
                 elif class_name.startswith(">"):
                     return
-                else:                        
-                    class_mapping = class_type(class_name, "sp" + class_name, class_name, class_name + ".h", ns = "")
-                
+                else:
+                    class_mapping = class_type(
+                        class_name, "sp" + class_name, class_name,
+                        class_name + ".h", ns="")
+
         except KeyError:
             pass
-        
+
         classes.add(class_mapping)
-        
+
+        # note: unused variable
         index = child.attrib["order"]
         ct.members.append(class_member(member, class_mapping, res_id))
 
 
-def gen2(xml_res_file, dest_folder, mappings):    
+def gen2(xml_res_file, dest_folder, mappings):
     global user_mp
     user_mp = mappings
-    import os
-    from jinja2 import Environment, FileSystemLoader    
 
     if not os.path.exists(dest_folder):
         os.makedirs(dest_folder)
 
     xml_res_file = os.path.normpath(xml_res_file)
     xml_res_file = xml_res_file.replace("\\", "/")
-    
-    from os import path
+
     doc = minidom.parse(xml_res_file)
     root = doc.documentElement
 
-
     folder = os.path.split(__file__)[0] + "/gen_view_code/templates"
-    env = Environment(trim_blocks = True, lstrip_blocks = True, loader = FileSystemLoader(folder))
+    env = Environment(trim_blocks=True, lstrip_blocks=True,
+                      loader=FileSystemLoader(folder))
 
     class_h_template = env.get_template("class.h")
     class_cpp_template = env.get_template("class.cpp")
 
-    
-    
     import io
 
     classes_node = root.getElementsByTagName("class")[0]
-    
+
     classes = set()
-    
-    for class_node in classes_node.childNodes:        
+
+    for class_node in classes_node.childNodes:
         if class_node.nodeType == class_node.TEXT_NODE:
             continue
         res = []
         get_plain_actors(class_node, res)
-        
+
         class_name = class_node.getAttribute("class")
-        
-    
-        local_classes = set()    
-        
+
+        local_classes = set()
+
         parent = find_mapping(class_node.nodeName, classes)
-        
-        custom_class = class_type("sp" + class_name, class_name, class_name + ".h", ns = "", member = "", parent = parent, generated=True)
 
+        custom_class = class_type(
+            "sp" + class_name, class_name, class_name +
+            ".h", ns="", member="", parent=parent, generated=True)
 
         classes.add(custom_class)
         local_classes.add(custom_class)
-    
+
         header = io.StringIO()
         cpp = io.StringIO()
-        
+
         for node in res:
             name = node.getAttribute("name")
             ct = find_mapping(node.nodeName, classes)
@@ -188,6 +202,7 @@ def gen2(xml_res_file, dest_folder, mappings):
 
         cls = list(local_classes)
         q = 0
+
         def ff(a, b):
             def cmp(a, b):
                 if a < b:
@@ -198,27 +213,27 @@ def gen2(xml_res_file, dest_folder, mappings):
             return cmp(b.ns, a.ns) or cmp(b.primary, a.primary) or cmp(a.className, b.className)
 
         import functools
-        cls.sort(key = functools.cmp_to_key(ff))
-        
-        includes = [inc for inc in cls if inc.header]    
-        
-        args = {"types":cls, 
-                "ct":custom_class,
-                "includes":includes}
-        
-        header.write(env.get_template("header.h").render(**args))        
+        cls.sort(key=functools.cmp_to_key(ff))
+
+        includes = [inc for inc in cls if inc.header]
+
+        args = {"types": cls,
+                "ct": custom_class,
+                "includes": includes}
+
+        header.write(env.get_template("header.h").render(**args))
         cpp.write(env.get_template("header.cpp").render(**args))
-        
-        args = {"ct":custom_class,
-                "xml":xml_res_file,
-                "members":custom_class.members}                
-        
-        header.write(class_h_template.render(**args))        
+
+        args = {"ct": custom_class,
+                "xml": xml_res_file,
+                "members": custom_class.members}
+
+        header.write(class_h_template.render(**args))
         cpp.write(class_cpp_template.render(**args))
-        
+
         header_name = class_name + ".h"
-        cpp_name = class_name + ".cpp"        
-        
+        cpp_name = class_name + ".cpp"
+
         gen_code = class_node.getAttribute("gencode")
         if gen_code == "false":
             continue
@@ -227,31 +242,33 @@ def gen2(xml_res_file, dest_folder, mappings):
 
 
 if __name__ == "__main__":
-    import argparse	
-    parser = argparse.ArgumentParser(description="generates h/cpp files from oxygine xml")
-    parser.add_argument("xml", help = "xml file to process")
-    parser.add_argument("-d", "--dest", help = "destination folder for generated classes", default = ".")
+    import argparse
+    parser = argparse.ArgumentParser(
+        description="generates h/cpp files from oxygine xml")
+    parser.add_argument("xml", help="xml file to process")
+    parser.add_argument(
+        "-d", "--dest", help="destination folder for generated classes", default=".")
     """
     parser.add_argument("-mw", "--max_width", help = "max atlas width", type=int, default = 2048)
     parser.add_argument("-mh", "--max_height", help = "max atlas height", type=int, default = 2048)
     parser.add_argument("-s", "--scale", help = "scale factor", type=float, default = 1.0)
     parser.add_argument("-r", "--resize", help = "downscale/upscale by scale factor", action="store_true", default = False)
     parser.add_argument("-us", "--upscale", help = "allow upscale. good option for very HD displays with texture compression", action="store_true", default = False)
-    parser.add_argument("-c", "--compression", help = "type of images compression. default is pure rgba8888 packed to png", 
+    parser.add_argument("-c", "--compression", help = "type of images compression. default is pure rgba8888 packed to png",
                         choices = ["pvrtc", "etc1", "no"], default = "")
-    parser.add_argument("-np", "--nopng", help = "store images without packing to png", 
-                            action="store_true", default = False)    
-    parser.add_argument("-q", "--quality", help = "select quality to compressed textures", 
+    parser.add_argument("-np", "--nopng", help = "store images without packing to png",
+                            action="store_true", default = False)
+    parser.add_argument("-q", "--quality", help = "select quality to compressed textures",
                         choices = ["default", "fast", "best"], default = "default")
     parser.add_argument("-d", "--dither", help = "added dithering to compressed textures (pvr option)", action="store_true", default = False)
     #parser.add_argument("--android_sdk", help = "path to android sdk", default = "")
     parser.add_argument("-debug", "--debug", help = "debug mode", action="store_true", default = False)
     parser.add_argument("-w", "--warnings", help = "show warnings", action="store_true", default = False)
     parser.add_argument("-v", "--verbosity", help = "verbosity level. 1 - only errors, 2 - normal. Default value is 2", type=int, default = 2)
-    parser.add_argument("--md5", help = "generates md5 lists for some special files", type=bool, default = False)        
+    parser.add_argument("--md5", help = "generates md5 lists for some special files", type=bool, default = False)
 
     gen2(".", "test.xml", "./", "Qwe", None)
     """
-    
+
     args = parser.parse_args()
-    gen2(args.xml, args.dest + "/", None)
+    gen2(args.xml, args.dest + "/", None)

+ 8 - 4
tools/gen_view_code/class_type.py

@@ -1,5 +1,8 @@
-class class_type:
-    def __init__(self, spClassName, className, header, ns = "oxygine", member = "", parent = None, generated = False):
+# -*- coding: utf-8 -*-
+
+class class_type(object):
+
+    def __init__(self, spClassName, className, header, ns="oxygine", member="", parent=None, generated=False):
         self.spClassName = spClassName
         self.className = className
         self.header = header
@@ -10,9 +13,10 @@ class class_type:
             self.primary = False
         else:
             self.primary = True
-            
+
         self.parent = parent
         self.generated = generated
 
+
 def user_class(*args):
-    return class_type(*args, ns = "")
+    return class_type(*args, ns="")

+ 8 - 4
tools/install.py

@@ -1,9 +1,13 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 import os
+
 oxygine_path = os.path.realpath(".\\..\\")
+
 if os.name == "posix":
-	cmd = "export OXYGINE=%(path)s" % {"path":oxygine_path, }
+    cmd = "export OXYGINE=%(path)s" % {"path": oxygine_path, }
 else:
-	cmd = "setx OXYGINE %(path)s" % {"path":oxygine_path, }
-os.system(cmd)
+    cmd = "setx OXYGINE %(path)s" % {"path": oxygine_path, }
+
+os.system(cmd)

+ 42 - 35
tools/others/build_oxygine_with_sdl.py

@@ -1,3 +1,8 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
 import os
 import sys
 import shutil
@@ -5,39 +10,38 @@ import zipfile
 import time
 
 
-def recursive_zip(zipf, directory, folder = ""):
+def recursive_zip(zipf, directory, folder=""):
     for item in os.listdir(directory):
         if os.path.isfile(os.path.join(directory, item)):
             src = os.path.join(directory, item)
             dest = folder + os.sep + item
             ext = os.path.splitext(dest)[1]
-            
+
             st = os.stat(src)
             mtime = time.localtime(st.st_mtime)
-            date_time = mtime[0:6]            
+            date_time = mtime[0:6]
 
             info = zipfile.ZipInfo(dest, date_time)
             bts = open(src, "rb").read()
             if ext == ".sh" or item in ("PVRTexToolCLI", "oxyresbuild.py", "gen_template.py", "png_strip.py"):
-                info.external_attr = 0755 << 16L #a+x
-            #zipf.writestr(info, bts, zipfile.ZIP_DEFLATED)
+                info.external_attr = 0755 << 16L  # a+x
+            # zipf.writestr(info, bts, zipfile.ZIP_DEFLATED)
             zipf.write(os.path.join(directory, item), folder + os.sep + item)
-            
-            
+
         elif os.path.isdir(os.path.join(directory, item)):
-            recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item)
-            
+            recursive_zip(zipf, os.path.join(
+                directory, item), folder + os.sep + item)
 
 
 def buildzip(name):
     print("building zip: " + name)
     destzip = "../../" + name
-    with zipfile.ZipFile(destzip, "w", compression = zipfile.ZIP_DEFLATED) as zp:
+    with zipfile.ZipFile(destzip, "w", compression=zipfile.ZIP_DEFLATED) as zp:
         recursive_zip(zp, "../../temp")
-    
-    #return
+
+    # return
     try:
-        shutil.copyfile(destzip, "../../../gdrive/oxygine/" + name)        
+        shutil.copyfile(destzip, "../../../gdrive/oxygine/" + name)
     except IOError, e:
         pass
 
@@ -46,11 +50,9 @@ def buildzip(name):
     except IOError, e:
         pass
 
-        
     print("zip created: " + name)
-    
-    
-    
+
+
 temp = "../../temp"
 SDL_dest = temp + "/SDL"
 OXYGINE_dest = temp + "/oxygine-framework/"
@@ -60,14 +62,16 @@ FLOW_dest = temp + "/oxygine-flow/"
 print("cleaning temp...")
 shutil.rmtree(temp, True)
 
+
 def export(repo, dest):
-    cmd = "git -C %s checkout-index -a -f --prefix=%s/" % ("d:/" + repo, "d:/oxygine-framework/temp/" + dest)
+    cmd = "git -C %s checkout-index -a -f --prefix=%s/" % (
+        "d:/" + repo, "d:/oxygine-framework/temp/" + dest)
     os.system(cmd)
 
 export("oxygine-framework", "oxygine-framework")
 buildzip("oxygine-framework.zip")
 
-#################### ALL IN ONE
+# ALL IN ONE
 cmd = "hg archive -R ../../../SDL %s" % (SDL_dest, )
 os.system(cmd)
 export("oxygine-sound", "oxygine-sound")
@@ -76,32 +80,36 @@ export("oxygine-flow", "oxygine-flow")
 
 shutil.rmtree(SDL_dest + "/test")
 
+
 def fix_file(name, cb):
-    data = open(name, "rb").read()    
+    data = open(name, "rb").read()
     data = cb(data)
     open(name, "wb").write(data)
-    
 
 
-fix_file(SDL_dest + "/include/SDL_config_windows.h", 
-         lambda data: data.replace("#define SDL_AUDIO_DRIVER_XAUDIO2", "//#define SDL_AUDIO_DRIVER_XAUDIO2")
+fix_file(SDL_dest + "/include/SDL_config_windows.h",
+         lambda data: data.replace(
+             "#define SDL_AUDIO_DRIVER_XAUDIO2", "//#define SDL_AUDIO_DRIVER_XAUDIO2")
          )
 
-fix_file(SDL_dest + "/src/video/uikit/SDL_uikitview.h", 
-         lambda data: data.replace("#define IPHONE_TOUCH_EFFICIENT_DANGEROUS", "//#define IPHONE_TOUCH_EFFICIENT_DANGEROUS")
+fix_file(SDL_dest + "/src/video/uikit/SDL_uikitview.h",
+         lambda data: data.replace(
+             "#define IPHONE_TOUCH_EFFICIENT_DANGEROUS", "//#define IPHONE_TOUCH_EFFICIENT_DANGEROUS")
          )
 
+
 def enum(folder, cb):
-    for item in os.listdir(folder):        
-        path = folder + item 
+    for item in os.listdir(folder):
+        path = folder + item
         if os.path.isdir(path):
             if item == "data":
                 cb(path)
             enum(path + "/", cb)
-            
+
+
 def copy(path):
     win32 = OXYGINE_dest + "/oxygine/third_party/win32/dlls/"
-    items = (win32 + "zlib.dll", 
+    items = (win32 + "zlib.dll",
              win32 + "pthreadVCE2.dll",
              "../../libs/SDL2.dll")
 
@@ -111,14 +119,13 @@ def copy(path):
     for item in items:
         name = os.path.split(item)[1]
         shutil.copy(item, path + "/" + name)
-        
-    
-        
+
+
 enum(OXYGINE_dest + "/examples/", copy)
 enum(SOUND_dest + "/examples/", copy)
 enum(FLOW_dest + "/examples/", copy)
 
-shutil.copy(SDL_dest + "/android-project/src/org/libsdl/app/SDLActivity.java", 
+shutil.copy(SDL_dest + "/android-project/src/org/libsdl/app/SDLActivity.java",
             OXYGINE_dest + "/oxygine/SDL/android/lib/src/org/libsdl/app/SDLActivity.java")
 
 libs = ("SDL2.lib", "SDL2main.lib", )
@@ -127,8 +134,8 @@ for lib in libs:
 """
 libs = ("libSDL2main.a", "libSDL2.dll", "libSDL2.dll.a")
 for lib in libs:
-    shutil.copy("../../libs/" + lib, OXYGINE_dest + "/libs/" + lib)    
+    shutil.copy("../../libs/" + lib, OXYGINE_dest + "/libs/" + lib)
 """
 buildzip("oxygine-framework-with-sdl.zip")
 
-print("done.")
+print("done.")

+ 84 - 67
tools/others/convert_font2sd.py

@@ -1,7 +1,20 @@
-import Image
-from xml.dom import minidom
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
 import os
 import math
+import sys
+from xml.dom import minidom
+
+import Image
+
+if sys.version_info[0] < 3:
+    xrange = xrange
+else:
+    xrange = range
+
 
 def _open_xml(path):
     file = open(path, "r")
@@ -11,36 +24,39 @@ def _open_xml(path):
 
 
 class point:
+
     def __init__(self, x, y):
         self.dx = x
         self.dy = y
-        
+
     def distSq(self):
         return self.dx * self.dx + self.dy * self.dy
-        
+
     def copy(self):
         return point(self.dx, self.dy)
 
+
 def compare(g, p, x, y, offsetX, offsetY):
     other = g.get(x + offsetX, y + offsetY)
     other.dx += offsetX
     other.dy += offsetY
-    
+
     if other.distSq() < p.distSq():
         return other
-    
+
     return p
 
-    
+
 class grid:
+
     def __init__(self, w, h):
         self.data = [None for x in range(w) for y in range(h)]
         self.w = w
         self.h = h
 
     def put(self, x, y, val):
-        self.data[x + y * self.w] = val#.copy()
-        
+        self.data[x + y * self.w] = val  # .copy()
+
     def get(self, x, y):
         if x < 0 or y < 0:
             return point(9999, 9999)
@@ -48,46 +64,48 @@ class grid:
             return point(9999, 9999)
         return self.data[x + y * self.w].copy()
 
+
 def generateSD_pass(g):
     print("generateSD_pass...")
     get = g.get
     put = g.put
-    
+
     w = g.w
     h = g.h
     cmp = compare
-    
+
     xr = xrange
-    
+
     for y in xr(h):
-        for x in xr(w):    
+        for x in xr(w):
             p = get(x, y)
             p = cmp(g, p, x, y, -1, 0)
             p = cmp(g, p, x, y, 0, -1)
             p = cmp(g, p, x, y, -1, -1)
             p = cmp(g, p, x, y, 1, -1)
-            
+
             put(x, y, p)
-            
+
         for x in xr(w - 1, -1, -1):
             p = get(x, y)
             p = cmp(g, p, x, y, 1, 0)
             put(x, y, p)
-            
+
     for y in xr(h - 1, -1, -1):
-        for x in xr(w-1, -1, -1):    
+        for x in xr(w - 1, -1, -1):
             p = get(x, y)
             p = cmp(g, p, x, y, 1, 0)
             p = cmp(g, p, x, y, 0, 1)
             p = cmp(g, p, x, y, -1, 1)
             p = cmp(g, p, x, y, 1, 1)
-            
+
             put(x, y, p)
-            
+
         for x in xr(w):
             p = get(x, y)
             p = cmp(g, p, x, y, 1, 0)
-            put(x, y, p)    
+            put(x, y, p)
+
 
 def generateSD(image):
     w = image.size[0]
@@ -102,9 +120,9 @@ def generateSD(image):
     g1put = grid1.put
     g2put = grid2.put
 
-    pZero = point(0,0)
-    pInf = point(9999,9999)
-    
+    pZero = point(0, 0)
+    pInf = point(9999, 9999)
+
     for y in range(h):
         for x in range(w):
             alpha = getpixel((x, y))[3]
@@ -114,19 +132,17 @@ def generateSD(image):
             else:
                 g1put(x, y, pInf)
                 g2put(x, y, pZero)
-                
-                
+
     generateSD_pass(grid1)
     generateSD_pass(grid2)
-    
-    
+
     sd_image = Image.new("L", (w, h))
     data = sd_image.getdata()
-    
+
     putpixel = sd_image.im.putpixel
-    
+
     for y in range(h):
-        for x in range(w):    
+        for x in range(w):
             dist1 = int(math.sqrt(grid1.get(x, y).distSq()))
             dist2 = int(math.sqrt(grid2.get(x, y).distSq()))
             dist = dist1 - dist2
@@ -137,18 +153,20 @@ def generateSD(image):
                 dist = 0
             if dist > 255:
                 dist = 255
-            putpixel((x,y), dist)
-            
+            putpixel((x, y), dist)
+
     return sd_image
 
+
 def downscaleAttr(el, attr, ds):
     v = el.getAttribute(attr)
-    el.setAttribute(attr, str(int(v)/ds))
-    
+    el.setAttribute(attr, str(int(v) / ds))
+
+
 def convert(args):
     xml_doc = _open_xml(args.bmfont)
     xml = xml_doc.documentElement
-    
+
     folder, file = os.path.split(args.bmfont)
     if folder:
         folder += "/"
@@ -156,25 +174,26 @@ def convert(args):
 
     downscale = args.scale
     for page in pages:
-    
-        image_file_name = page.getAttribute("file")            
-    
+
+        image_file_name = page.getAttribute("file")
+
         image = Image.open(folder + image_file_name)
-        image.load()    
-        
+        image.load()
+
         #image = image.crop((0,0, 256, 256))
-        
+
         w = image.size[0]
         h = image.size[1]
-        
+
         sd_image = generateSD(image)
-        sd_image = sd_image.resize((w/downscale, h/downscale), Image.ANTIALIAS)
-        
+        sd_image = sd_image.resize(
+            (w / downscale, h / downscale), Image.ANTIALIAS)
+
         sd_image_name = "sd_" + image_file_name
-        sd_image.save(folder + sd_image_name, "PNG")    
-        
+        sd_image.save(folder + sd_image_name, "PNG")
+
         page.setAttribute("file", sd_image_name)
-        
+
     info_el = xml.getElementsByTagName("info")[0]
     downscaleAttr(info_el, "size", downscale)
     common_el = xml.getElementsByTagName("common")[0]
@@ -182,34 +201,32 @@ def convert(args):
     downscaleAttr(common_el, "base", downscale)
     downscaleAttr(common_el, "scaleW", downscale)
     downscaleAttr(common_el, "scaleH", downscale)
-        
+
     new_font_xml = folder + "sd_" + file
-    fileh= open(new_font_xml, "w")
+    fileh = open(new_font_xml, "w")
     xml_doc.writexml(fileh)
-    
-    
 
-if __name__ == "__main__": 
-    import os   
+
+if __name__ == "__main__":
+    import os
     import sys
-    
-    folder = os.path.split(os.path.abspath(__file__))[0] + "\\src"  
+
+    folder = os.path.split(os.path.abspath(__file__))[0] + "\\src"
     sys.path.append(folder)
-    
-    #print sys.path
-    
-    import argparse	
-    parser = argparse.ArgumentParser(description="convert xml bmfont to signed distance font")
-    
+
+    # print sys.path
+
+    import argparse
+    parser = argparse.ArgumentParser(
+        description="convert xml bmfont to signed distance font")
+
     parser.add_argument("bmfont", help="src font")
-    parser.add_argument("-s", "--scale", help = "scale factor", type=int, default = 1)
-    
-    
+    parser.add_argument(
+        "-s", "--scale", help="scale factor", type=int, default=1)
+
     import xml_processor
 
     args = parser.parse_args()
     convert(args)
     #p = xml_processor.XmlProcessor(args)
-    #p.process()
-    
-    
+    # p.process()

+ 19 - 12
tools/others/embed_folder_js.py

@@ -1,17 +1,22 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
 
 import os
+import argparse
 
 SKIP_EXT = (".dll", ".py", ".icf", ".py", ".js", ".ogg")
 
+
 def do(src, dest):
     def listdir(path, data):
         for f in os.listdir(path):
-            if path != ".":        
+            if path != ".":
                 full = path + "/" + f
             else:
                 full = f
-                
+
             if os.path.isdir(full):
                 listdir(full, data)
             else:
@@ -26,20 +31,22 @@ def do(src, dest):
     s = ""
     for f in files:
         s = s + " --embed " + f
-        
-    cmd = "python \"" + os.environ["EMSCRIPTEN"] + "/tools/file_packager.py\" test --lz4  --js-output=\"%s\" %s" % (dest, s)
+
+    cmd = "python \"" + os.environ["EMSCRIPTEN"] + \
+        "/tools/file_packager.py\" test --lz4  --js-output=\"%s\" %s" % (
+            dest, s)
     print(cmd)
     os.system(cmd)
 
-    
+
 if __name__ == "__main__":
+    parser = argparse.ArgumentParser(
+        description="embedding folder into one js file")
+    parser.add_argument("-s", "--src", help="source folder", default=".")
+    parser.add_argument(
+        "-o", "--output", help="destination js file", default="data.js")
 
-    import argparse 
-    parser = argparse.ArgumentParser(description = "embedding folder into one js file")
-    parser.add_argument("-s", "--src", help = "source folder", default = ".")
-    parser.add_argument("-o", "--output", help = "destination js file", default = "data.js")
-    
     args = parser.parse_args()
     output = os.path.relpath(args.output, args.src)
     os.chdir(args.src)
-    do(".", output)
+    do(".", output)

+ 11 - 6
tools/others/fileslist.py

@@ -1,17 +1,22 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import os
 import sys
+
 path = sys.argv[1]
 prefix = sys.argv[2]
 ls = os.listdir(path)
 ext = [".c", ".cpp", ".h"]
 fn = open("ls.txt", "w")
 
+
 def write(*ext):
-	for name in ls:		
-	    e = os.path.splitext(name)[1]
-	    if e in ext:
-	        nm = "\t" + prefix + "/" + name
-	        fn.write(nm + " \ \n")
+    for name in ls:
+        e = os.path.splitext(name)[1]
+        if e in ext:
+            nm = "\t" + prefix + "/" + name
+            fn.write(nm + " \ \n")
 
 write(".c", ".cpp")
-write(".h", ".hpp")
+write(".h", ".hpp")

+ 8 - 4
tools/others/gen_includes.py

@@ -1,8 +1,12 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import os
 
+
 def rec(path, local):
     for item in os.listdir(path):
-        if item in ("winnie_alloc", "minizip", "dev_tools", "gl", "android", 
+        if item in ("winnie_alloc", "minizip", "dev_tools", "gl", "android",
                     "closure", "pugixml", "text_utils", ):
             continue
         name = path + item
@@ -10,9 +14,9 @@ def rec(path, local):
         if os.path.isdir(name):
             rec(name + "/", local_name + "/")
         else:
-            a,b = os.path.splitext(item)
+            a, b = os.path.splitext(item)
             if b == ".h":
                 c = "#include \"%s\"" % (local_name, )
                 open("../../oxygine/include/oxygine/" + a, "w").write(c)
-        
-rec("../../oxygine/src/", "")
+
+rec("../../oxygine/src/", "")

+ 36 - 34
tools/others/gen_templates.py

@@ -1,43 +1,45 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 import os
-def gen(path, project = ""):
-	if not project:
-		project = path
 
-	projs = ("win32", "android", "macosx", "ios", "cmake", "emscripten")
-	
-	#projs = ("ios", "macosx")
-	#projs = ("ios", )
-	#projs = ("macosx", )	
-	projs = ("win32", )
-	#projs = ("cmake", )	
-	#projs = ("android", )
-	#projs = ("emscripten", )
 
-	for platform in projs:
-		dest = "../../examples/" + path + "/proj." + platform
-		src =  "../../examples/" + path + "/src"
-		import shutil
-		shutil.rmtree(dest, True)
-		cmd = "python ../gen_template.py %s -d %s -s %s -t %s" % (project, dest, src, platform)
-		print(cmd)
-		os.system(cmd)
+def gen(path, project=""):
+    if not project:
+        project = path
 
+    projs = ("win32", "android", "macosx", "ios", "cmake", "emscripten")
 
+    # projs = ("ios", "macosx")
+    # projs = ("ios", )
+    # projs = ("macosx", )
+    projs = ("win32", )
+    # projs = ("cmake", )
+    # projs = ("android", )
+    # projs = ("emscripten", )
+
+    for platform in projs:
+        dest = "../../examples/" + path + "/proj." + platform
+        src = "../../examples/" + path + "/src"
+        import shutil
+        shutil.rmtree(dest, True)
+        cmd = "python ../gen_template.py %s -d %s -s %s -t %s" % (
+            project, dest, src, platform)
+        print(cmd)
+        os.system(cmd)
 
 
 if 1:
-	gen("Demo")
-	gen("DemoBox2D")
-	gen("Game/part1", "GamePart1")
-	gen("Game/part2", "GamePart2")
-	gen("Game/part3", "GamePart3")
-	gen("Game/part4", "GamePart4")
-	gen("Game/part5", "GamePart5")
-	gen("HelloWorld")
-	gen("Match3")
-
-
-#gen("Demo")
-#gen("HelloWorld")
+    gen("Demo")
+    gen("DemoBox2D")
+    gen("Game/part1", "GamePart1")
+    gen("Game/part2", "GamePart2")
+    gen("Game/part3", "GamePart3")
+    gen("Game/part4", "GamePart4")
+    gen("Game/part5", "GamePart5")
+    gen("HelloWorld")
+    gen("Match3")
+
+
+# gen("Demo")
+# gen("HelloWorld")

+ 33 - 25
tools/others/gen_xml_resources.py

@@ -1,3 +1,5 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 """
     typical usage example
 
@@ -14,20 +16,21 @@
 
 """
 
+from __future__ import print_function, unicode_literals
+
 import os
-import shutil
 import glob
 
+
 def gen_xml(args):
     wildcard = "*.*"
     path = args.data + "/" + args.images
     filelist = glob.glob(path + "/" + args.wildcard)
-    print filelist
-    print path
-    
+    print(filelist)
+    print(path)
+
     dest = open(args.data + "/" + args.out, "w")
     write = dest.write
-    
 
     write("<resources>\n")
     write("\t<set path=\"%s\"/>\n" % (args.images, ))
@@ -36,38 +39,43 @@ def gen_xml(args):
 
     if not args.load:
         write("\t<set load=\"false\"/>\n")
-            
-    
+
     if not args.atlasses:
-        write("\t<atlas>\n")        
+        write("\t<atlas>\n")
 
-    for file in filelist:        
+    for file in filelist:
         name = os.path.split(file)[1]
         if args.atlasses:
             write("\t<atlas>\n\t")
         write("\t\t<image file='%s'/>\n" % (name))
         if args.atlasses:
             write("\t</atlas>\n")
-            
+
     if not args.atlasses:
-        write("\t</atlas>\n")        
-        
-    write("</resources>\n")    
+        write("\t</atlas>\n")
+
+    write("</resources>\n")
     dest.close()
 
-    
-if __name__ == "__main__":
 
-    import argparse 
-    parser = argparse.ArgumentParser(description = "generates xml file with image resources")
-    parser.add_argument("-d", "--data", help = "root data folder", default = ".", required = True)
-    parser.add_argument("-s", "--sfactor", help = "scale factor", default = 1)
-    parser.add_argument("-i", "--images", help = "folder with images. path relative to --data", default = ".")
-    parser.add_argument("-o", "--out", help = "output xml file name", default = "out.xml")
-    parser.add_argument("-w", "--wildcard", help = "default is '*.png'", default = "*.png")
-    parser.add_argument("-l", "--load", help = "preload files?", action="store_true", default = True)
-    parser.add_argument("-a", "--atlasses", help = "separate atlasses for each file?", action="store_true", default = False)
+if __name__ == "__main__":
 
+    import argparse
+    parser = argparse.ArgumentParser(
+        description="generates xml file with image resources")
+    parser.add_argument(
+        "-d", "--data", help="root data folder", default=".", required=True)
+    parser.add_argument("-s", "--sfactor", help="scale factor", default=1)
+    parser.add_argument(
+        "-i", "--images", help="folder with images. path relative to --data", default=".")
+    parser.add_argument(
+        "-o", "--out", help="output xml file name", default="out.xml")
+    parser.add_argument("-w", "--wildcard",
+                        help="default is '*.png'", default="*.png")
+    parser.add_argument("-l", "--load", help="preload files?",
+                        action="store_true", default=True)
+    parser.add_argument("-a", "--atlasses", help="separate atlasses for each file?",
+                        action="store_true", default=False)
 
     args = parser.parse_args()
-    gen_xml(args)
+    gen_xml(args)

+ 102 - 98
tools/others/genfn.py

@@ -1,44 +1,48 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
 
 import cStringIO
+
 lines = open("../../../SDL/include/SDL_opengl_glext.h").readlines()
-funcs = ["glShaderSource", 
-         "glUseProgram", 
-         "glVertexAttribPointer", 
-         "glActiveTexture", 
-         "glEnableVertexAttribArray", 
-         "glDisableVertexAttribArray", 
-         "glDeleteProgram", 
-         "glGetShaderiv", 
-         "glGetShaderInfoLog", 
-         "glCreateShader", 
-         "glCreateProgram", 
+funcs = ["glShaderSource",
+         "glUseProgram",
+         "glVertexAttribPointer",
+         "glActiveTexture",
+         "glEnableVertexAttribArray",
+         "glDisableVertexAttribArray",
+         "glDeleteProgram",
+         "glGetShaderiv",
+         "glGetShaderInfoLog",
+         "glCreateShader",
+         "glCreateProgram",
          "glAttachShader",
-         "glCompileShader", 
-         "glBindAttribLocation", 
-         "glLinkProgram", 
-         "glUniform1i", 
+         "glCompileShader",
+         "glBindAttribLocation",
+         "glLinkProgram",
+         "glUniform1i",
          "glUniform2fv",
          "glUniform3fv",
-         "glUniform4fv", 
-         "glUniform1f", 
-         "glUniformMatrix4fv", 
-         "glBindFramebuffer", 
-         "glGenFramebuffer", 
-         "glGenFramebuffers", 
-         "glCheckFramebufferStatus", 
-         "glDeleteFramebuffers", 
-         "glGetUniformLocation", 
-         "glFramebufferTexture2D", 
-         "glCompressedTexImage2D", 
+         "glUniform4fv",
+         "glUniform1f",
+         "glUniformMatrix4fv",
+         "glBindFramebuffer",
+         "glGenFramebuffer",
+         "glGenFramebuffers",
+         "glCheckFramebufferStatus",
+         "glDeleteFramebuffers",
+         "glGetUniformLocation",
+         "glFramebufferTexture2D",
+         "glCompressedTexImage2D",
          "glBindBuffer",
          "glGenBuffers",
          "glBufferData",
          "glDeleteBuffers"]
 
 
-#GLAPI void APIENTRY glDeleteProgram (GLuint program);
-#PFNGLDELETEPROGRAMPROC
+# GLAPI void APIENTRY glDeleteProgram (GLuint program);
+# PFNGLDELETEPROGRAMPROC
 
 base = cStringIO.StringIO()
 defl = cStringIO.StringIO()
@@ -47,92 +51,92 @@ extern = cStringIO.StringIO()
 define = cStringIO.StringIO()
 
 
-
 init.write("""
 void initGLExtensions(myGetProcAdress func)
 {
     if (_glUseProgram)
         return;
 
-""");
+""")
 
 base.write("""
-extern "C" 
+extern "C"
 {
 """)
 
+
 def get(name):
-	shname = name[2:len(name)]
-	up = shname.upper()	
-	proc = "PFNGL" + up + "PROC"
-	nm = " " + name + " "
-	for l in lines:
-		if l.find(nm) != -1:
-			st = l
-			if 0:
-				st = ""				
-				
-			st = st[0:-2]
-
-
-			#PFNGLSHADERSOURCEPROC _glShaderSource = 0;			
-			base.write("%s _%s = 0;\n" % (proc, name))
-			#base.write(st + "\n")
-
-			extern.write("extern %s _%s;\n" % (proc, name))
-			define.write("#define ox%s DECLARE_GLEXT(%s)\n" % (name, name))
-			#extern.write(st + "\n")
-
-			stf = st.replace(name, "def_" + name)
-			
-			defl.write(stf + "\n")
-			#base.write("{\n")
-			defl.write("{")
-			
-			args = st[st.find("(") + 1:st.find(")")]
-			args = args.split(",")
-			
-			allargs = []
-			for ar in args:
-				sp = ar.split(" ")
-				q = sp[-1].split("*")[-1]
-				if q == "void":
-					continue
-				allargs.append(q)
-			
-			"""
-			base.write("\t")
-			if not st.startswith("GLAPI void"):
-				base.write("return ");				
-				defl.write("return 0;")
-			base.write("_%s(" %(name, ))
-			
-			d = ""
-			for ar in allargs:
-				d += ar + ","
-				
-			d = d[0:-1] + ");\n"
-			
-			base.write(d)				
-
-			base.write("}\n")			
-			"""
-			defl.write("}\n")			
-
-			init.write("GETFUNC(_%s, def_%s, %s, \"%s\");\n" % (name, name, proc, name))
-			
-			#st.replace(name, )
-			
+    shname = name[2:len(name)]
+    up = shname.upper()
+    proc = "PFNGL" + up + "PROC"
+    nm = " " + name + " "
+    for l in lines:
+        if l.find(nm) != -1:
+            st = l
+            if 0:
+                st = ""
+
+            st = st[0:-2]
+
+            # PFNGLSHADERSOURCEPROC _glShaderSource = 0;
+            base.write("%s _%s = 0;\n" % (proc, name))
+            # base.write(st + "\n")
+
+            extern.write("extern %s _%s;\n" % (proc, name))
+            define.write("#define ox%s DECLARE_GLEXT(%s)\n" % (name, name))
+            # extern.write(st + "\n")
+
+            stf = st.replace(name, "def_" + name)
+
+            defl.write(stf + "\n")
+            # base.write("{\n")
+            defl.write("{")
+
+            args = st[st.find("(") + 1:st.find(")")]
+            args = args.split(",")
+
+            allargs = []
+            for ar in args:
+                sp = ar.split(" ")
+                q = sp[-1].split("*")[-1]
+                if q == "void":
+                    continue
+                allargs.append(q)
+
+            """
+            base.write("\t")
+            if not st.startswith("GLAPI void"):
+                base.write("return ");
+                defl.write("return 0;")
+            base.write("_%s(" %(name, ))
+
+            d = ""
+            for ar in allargs:
+                d += ar + ","
+
+            d = d[0:-1] + ");\n"
+
+            base.write(d)
+
+            base.write("}\n")
+            """
+            defl.write("}\n")
+
+            init.write("GETFUNC(_%s, def_%s, %s, \"%s\");\n" %
+                       (name, name, proc, name))
+
+            # st.replace(name, )
+
 for f in funcs:
-	get(f)
+    get(f)
 
 base.write("""
 }
 """)
-	
-print defl.getvalue()
-print base.getvalue()
-print init.getvalue()
+
+print(defl.getvalue())
+print(base.getvalue())
+print(init.getvalue())
 
 open("res.cpp", "w").write(defl.getvalue() + base.getvalue() + init.getvalue())
 open("res.h", "w").write(extern.getvalue() + define.getvalue())

+ 7 - 3
tools/others/include.py

@@ -1,7 +1,11 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import os
 import glob
 
-def process(path):    
+
+def process(path):
     files = os.listdir(path)
     for f in files:
         name = path + f
@@ -13,8 +17,8 @@ def process(path):
                 with open(name, "w") as fh:
                     lines.insert(1, "#include \"oxygine_include.h\"\n")
                     fh.writelines(lines)
-                    
+
         else:
             process(name + "/")
-        
+
 process("./")

+ 60 - 52
tools/others/oxyresbuild_tests.py

@@ -1,116 +1,124 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
 import sys
-import os
+import unittest
+
+import oxyresbuild
+from resbuild import process_atlas
 
-#sys.path.append(os.path.split(__file__)[0] + "/..")
+
+# sys.path.append(os.path.split(__file__)[0] + "/..")
 sys.path.append("d:/oxygine-framework/tools")
 
 
-import unittest
-import oxyresbuild
-from resbuild import process_atlas
+class ResAnim(object):
 
-class ResAnim:
     def __init__(self, data):
         items = data.split(",")
         self.columns = int(items[0])
         self.rows = int(items[1])
         self.frame_size = (int(items[2]), int(items[3]))
-        self.frame_scale = float(items[4]) 
+        self.frame_scale = float(items[4])
         pass
-    
-class Frame:
+
+
+class Frame(object):
+
     def __init__(self, data):
         data = data[0:-1]
-        items = data.split(",")        
+        items = data.split(",")
         self.atlas_id = int(items[0])
         self.src_pos = (int(items[1]), int(items[2]))
         self.src_destpos = (int(items[3]), int(items[4]))
         self.dest_size = (int(items[5]), int(items[6]))
-        self.src = (self.src_pos[0], self.src_pos[1],  self.dest_size[0], self.dest_size[1], )       
-    
+        self.src = (self.src_pos[0], self.src_pos[1],
+                    self.dest_size[0], self.dest_size[1], )
+
 
 class MyTest(unittest.TestCase):
+
     def setUp(self):
         pass
-    
+
     def getResult(self):
         from xml.dom import minidom
-        with  open("tests/%s.ox/meta.xml" % (self.xml, ), "r") as file:
+        with open("tests/%s.ox/meta.xml" % (self.xml, ), "r") as file:
             doc = minidom.parse(file)
             atlas = doc.documentElement.getElementsByTagName("atlas")[0]
             image = atlas.getElementsByTagName("image")[0]
             fs = image.getAttribute("fs")
             data = image.childNodes[0].data
-        
+
         return (ResAnim(fs), Frame(data))
-    
+
     def process(self, xml, args):
         self.xml = xml
-        import oxyresbuild
-        oxyresbuild.process("-x %s --src_data tests --dest_data tests --debug " % (xml, ) + args )        
+        oxyresbuild.process(
+            "-x %s --src_data tests --dest_data tests --debug " %
+            (xml, ) + args
+        )
         return self.getResult()
-    
+
     def testNoScaleFactor(self):
         xml = "res1.xml"
-        
+
         anim, frame = self.process(xml, "")
-        
-        if 0: anim = ResAnim(); frame = Frame()
-            
+
+        if 0:
+            anim = ResAnim()
+            frame = Frame()
+
         self.assertEqual(anim.frame_size, (128, 128))
-        self.assertEqual(frame.src, (0, 0, 64, 64))        
-        
+        self.assertEqual(frame.src, (0, 0, 64, 64))
+
         anim, frame = self.process(xml, "-r ")
 
         self.assertEqual(anim.frame_size, (128, 128))
-        self.assertEqual(frame.src, (0, 0, 64, 64))        
-        
+        self.assertEqual(frame.src, (0, 0, 64, 64))
+
         anim, frame = self.process(xml, "-r -s 1")
 
         self.assertEqual(anim.frame_size, (128, 128))
         self.assertEqual(frame.src, (0, 0, 64, 64))
-        
+
     def testScaleFactor(self):
         xml = "res2.xml"
-        
-        if 0: anim = ResAnim(); frame = Frame()
-        
-        anim, frame = self.process(xml, "-r -s 3 -us")        
+
+        if 0:
+            anim = ResAnim()
+            frame = Frame()
+
+        anim, frame = self.process(xml, "-r -s 3 -us")
         self.assertEqual(anim.frame_size, (64, 64))
         self.assertEqual(frame.src, (0, 0, 99, 99))
-        self.assertAlmostEqual(anim.frame_scale, 1/3.0, delta = 0.0001)
-        
-      
-        anim, frame = self.process(xml, "-r -s 3")        
+        self.assertAlmostEqual(anim.frame_scale, 1 / 3.0, delta=0.0001)
+
+        anim, frame = self.process(xml, "-r -s 3")
         self.assertEqual(anim.frame_size, (64, 64))
         self.assertEqual(frame.src, (0, 0, 64, 64))
         self.assertEqual(anim.frame_scale, 0.5)
-        
-        
-        
-        anim, frame = self.process(xml, "-r -s 2")        
+
+        anim, frame = self.process(xml, "-r -s 2")
         self.assertEqual(anim.frame_size, (64, 64))
         self.assertEqual(frame.src, (0, 0, 64, 64))
         self.assertEqual(anim.frame_scale, 0.5)
-        
-        
-        
+
         anim, frame = self.process(xml, "-r")
-        
-        #<image debug_image="test.png" fs="1,1,64,64,0.500000">0,0,0,13,15,37,37;</image>
-        #0, (0,0), (13,15), 37,37
+
+        # <image debug_image="test.png" fs="1,1,64,64,0.500000">0,0,0,13,15,37,37;</image>
+        # 0, (0,0), (13,15), 37,37
         #
-        
+
         self.assertEqual(anim.frame_size, (64, 64))
         self.assertEqual(frame.src, (0, 0, 34, 34))
         self.assertEqual(anim.frame_scale, 1.0)
-        
-        anim, frame = self.process(xml, "-r -s 0.5")        
+
+        anim, frame = self.process(xml, "-r -s 0.5")
         self.assertEqual(anim.frame_size, (64, 64))
         self.assertEqual(frame.src, (0, 0, 18, 18))
         self.assertEqual(anim.frame_scale, 2)
-        
-        
+
 
 if __name__ == "__main__":
-    unittest.main()
+    unittest.main()

+ 20 - 12
tools/others/png_strip.py

@@ -1,14 +1,20 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
-import Image
 import glob
 import argparse
 
+import Image
+
 if __name__ == "__main__":
-    import argparse	
-    parser = argparse.ArgumentParser(description="Generates single png strip from multiple images. Just copy it to folder and run.")
-    parser.add_argument("-p", "--pattern", help = "searching files pattern ", default = "*.png")
-    parser.add_argument("-d", "--dest", help="destination file", default = "anim.png")
+    parser = argparse.ArgumentParser(
+        description="Generates single png strip from multiple images. Just "
+                    "copy it to folder and run."
+    )
+    parser.add_argument("-p", "--pattern",
+                        help="searching files pattern ", default="*.png")
+    parser.add_argument(
+        "-d", "--dest", help="destination file", default="anim.png")
     args = parser.parse_args()
 
     images = []
@@ -16,14 +22,15 @@ if __name__ == "__main__":
     h = 0
     size = None
     for g in sorted(glob.glob(args.pattern)):
-        im = Image.open(g)        
+        im = Image.open(g)
         images.append(im)
-        h = max(h, im.size[1])        
+        h = max(h, im.size[1])
         w += im.size[0]
         if not size:
-            size = im.size        
-        print(("appending image: '{}' with size ({}, {}) ".format(g, im.size[0], im.size[1])))
-        
+            size = im.size
+        print(("appending image: '{}' with size ({}, {}) ".format(
+            g, im.size[0], im.size[1])))
+
         if size[0] != im.size[0]:
             print(("warning! width should be {}".format(size[0])))
 
@@ -35,5 +42,6 @@ if __name__ == "__main__":
             anim.paste(im, (w, 0))
             w += im.size[0]
 
-        print(("writing result...\nfile=\"{}\" cols=\"{}\"".format(args.dest, len(images))))
+        print(("writing result...\nfile=\"{}\" cols=\"{}\"".format(
+            args.dest, len(images))))
         anim.save(args.dest)

+ 8 - 5
tools/others/single_strip.py

@@ -1,7 +1,11 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
 
-import Image
 import sys
+import Image
+
 image = sys.argv[1]
 cols = int(sys.argv[2])
 rows = int(sys.argv[3])
@@ -13,11 +17,10 @@ fh = src.size[1] / rows
 dest = Image.new("RGBA", (fw * cols * rows, fh))
 w = 0
 for row in range(rows):
-    for col in range(cols):  
+    for col in range(cols):
         frame = src.crop((fw * col, fh * row, fw * (col + 1), fh * (row + 1)))
         dest.paste(frame, (w, 0))
         w += fw
-    
+
 dest.save("anim.png")
 print("cols = %d" % (rows * cols, ))
-    

+ 19 - 18
tools/others/update_examples_entry.py

@@ -1,4 +1,5 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
 
 examples = "../../examples/"
 
@@ -6,21 +7,22 @@ demo = examples + "Demo/"
 parent = "../../../"
 
 items = (
-     examples + "DemoBox2D",
-     examples + "Game/Part1",
-     examples + "Game/Part2",
-     examples + "Game/Part3",
-     examples + "Game/Part4",
-     examples + "Game/Part5",
-     examples + "HelloWorld",
-     examples + "Match3",
-     examples + "TutorialResources",
-     parent + "oxygine-frame/examples/example1",
-     parent + "oxygine-frame/examples/example2",
-     parent + "oxygine-magicparticles/example/MPHello",
-     parent + "oxygine-pipeline/example/game/project/",
-     parent + "oxygine-sound/examples/SoundDemo/",
-     )
+    examples + "DemoBox2D",
+    examples + "Game/Part1",
+    examples + "Game/Part2",
+    examples + "Game/Part3",
+    examples + "Game/Part4",
+    examples + "Game/Part5",
+    examples + "HelloWorld",
+    examples + "Match3",
+    examples + "TutorialResources",
+    parent + "oxygine-frame/examples/example1",
+    parent + "oxygine-frame/examples/example2",
+    parent + "oxygine-magicparticles/example/MPHello",
+    parent + "oxygine-pipeline/example/game/project/",
+    parent + "oxygine-sound/examples/SoundDemo/",
+)
+
 
 def copy(item, name):
     import shutil
@@ -28,5 +30,4 @@ def copy(item, name):
 
 for item in items:
     copy(item, "src/entry_point.cpp")
-    #copy(item, "data/app.icf")
-    
+    # copy(item, "data/app.icf")

+ 16 - 6
tools/oxygine.py

@@ -1,9 +1,19 @@
-#this file is part of oxygine-framework. Copy it from oxygine-framework/tools/ to your folder and import for usage
+# -*- coding: utf-8 -*-
+"""
+    this file is part of oxygine-framework. Copy it from
+    oxygine-framework/tools/ to your folder and import for usage
+"""
+
+from __future__ import unicode_literals, print_function
+
+
 VERSION = 1
 _helper = None
-def helper(root = ""):
+
+
+def helper(root=""):
     global _helper
-    if not _helper:        
+    if not _helper:
         if not root:
             import os
             if "OXYGINE" in os.environ:
@@ -16,13 +26,13 @@ def helper(root = ""):
                     if parent == cur:
                         break
                     cur = parent
-                    
+
                     ox = cur + "/oxygine-framework"
                     if os.path.isdir(ox):
                         print("oxygine-framework folder found at " + ox)
                         root = ox
                         break
-                    #print cur
+                    # print cur
         import sys
         p = root + "/tools/"
         sys.path.append(p)
@@ -33,4 +43,4 @@ def helper(root = ""):
     return _helper
 
 
-#helper()
+# helper()

+ 72 - 30
tools/oxyresbuild.py

@@ -1,42 +1,85 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
+import time
+import resbuild.xml_processor as xml_processor
+
 
 def str2bool(v):
     return v.lower() in ("yes", "true", "t", "1")
 
+
 def get_parser():
-    import argparse	
-    parser = argparse.ArgumentParser(description="oxyresbuild is being used to processing and optimizing xml resources file. It generated <xml-name>.ox folder with meta.xml file inside. Meta file has optimized information about resources, atlasses.")
-    parser.add_argument("--src_data", help = "root data folder contains all resources", default = ".")
-    parser.add_argument("--dest_data", help = "destination data folder for generated files", default = ".")
-    parser.add_argument("-x", "--xml", help = "xml file to process", default = ".", required = True)
-    parser.add_argument("-mw", "--max_width", help = "max atlas width", type=int, default = 2048)
-    parser.add_argument("-mh", "--max_height", help = "max atlas height", type=int, default = 2048)
-    parser.add_argument("-s", "--scale", help = "Scale value applied when resizing images. Value > 1 - upscale, Value < 1 - downscale. Should be used with --resize", type=float, default = 1.0)
-    parser.add_argument("-r", "--resize", help = "Resize images by scale value", action="store_true", default = False)
-    parser.add_argument("-us", "--upscale", help = "allow upscale. good option for very HD displays with texture compression", action="store_true", default = False)
-    parser.add_argument("-c", "--compression", help = "type of images compression. default is pure rgba8888 packed to png", 
-                        choices = ["pvrtc", "pvrtc2", "etc1", "no"], default = "")
-    parser.add_argument("--npot", help = "not power of two atlasses", action="store_true", default = False)    
-    parser.add_argument("-q", "--quality", help = "select quality to compressed textures (default is not best)", 
-                        choices = ["default", "fast", "best"], default = "default")
-    parser.add_argument("-d", "--dither", help = "added dithering to compressed textures (pvr option)", action="store_true", default = False)    
-    parser.add_argument("-w", "--warnings", help = "show warnings", action="store_true", default = False)
-    parser.add_argument("-v", "--verbosity", help = "verbosity level. 1 - only errors, 2 - normal. Default value is 2", type=int, default = 2)
-    parser.add_argument("--hash", help = "enables creating md5 hash lists for some special files", action="store_true", default = False)
-    parser.add_argument("--debug", help = "debug mode", action="store_true", default = False)
-    parser.add_argument("--no_hit_test", help = "disables generation hit_test data by default", action="store_true", default = False)
-    parser.add_argument("--nopng", help = "stores images without packing to png. TGA will be used if compressiong disabled.", 
-                        action="store_true", default = False)            
+    import argparse
+    parser = argparse.ArgumentParser(
+        description="oxyresbuild is being used to processing and optimizing "
+        "xml resources file. It generated <xml-name>.ox folder with "
+        "meta.xml file inside. Meta file has optimized information "
+        "about resources, atlasses."
+    )
+    parser.add_argument(
+        "--src_data", help="root data folder contains all resources",
+        default="."
+    )
+    parser.add_argument(
+        "--dest_data", help="destination data folder for generated files",
+        default="."
+    )
+    parser.add_argument(
+        "-x", "--xml", help="xml file to process", default=".", required=True)
+    parser.add_argument("-mw", "--max_width",
+                        help="max atlas width", type=int, default=2048)
+    parser.add_argument("-mh", "--max_height",
+                        help="max atlas height", type=int, default=2048)
+    parser.add_argument(
+        "-s", "--scale", help="Scale value applied when resizing images. "
+        "Value > 1 - upscale, Value < 1 - downscale. Should be used "
+        "with --resize", type=float, default=1.0
+    )
+    parser.add_argument("-r", "--resize", help="Resize images by scale value",
+                        action="store_true", default=False)
+    parser.add_argument("-us", "--upscale",
+                        help="allow upscale. good option for very HD "
+                        "displays with texture compression",
+                        action="store_true", default=False)
+    parser.add_argument("-c", "--compression", help="type of images "
+                        "compression. default is pure rgba8888 packed to png",
+                        choices=["pvrtc", "pvrtc2", "etc1", "no"], default="")
+    parser.add_argument("--npot", help="not power of two atlasses",
+                        action="store_true", default=False)
+    parser.add_argument("-q", "--quality", help="select quality to "
+                        "compressed textures (default is not best)",
+                        choices=["default", "fast", "best"], default="default")
+    parser.add_argument("-d", "--dither", help="added dithering to "
+                        "compressed textures (pvr option)",
+                        action="store_true", default=False)
+    parser.add_argument("-w", "--warnings", help="show warnings",
+                        action="store_true", default=False)
+    parser.add_argument(
+        "-v", "--verbosity", help="verbosity level. 1 - only errors, "
+        "2 - normal. Default value is 2", type=int, default=2)
+    parser.add_argument("--hash", help="enables creating md5 hash lists for "
+                        "some special files",
+                        action="store_true", default=False)
+    parser.add_argument("--debug", help="debug mode",
+                        action="store_true", default=False)
+    parser.add_argument("--no_hit_test", help="disables generation "
+                        "hit_test data by default",
+                        action="store_true", default=False)
+    parser.add_argument("--nopng", help="stores images without "
+                        "packing to png. TGA will be used if "
+                        "compressiong disabled.",
+                        action="store_true", default=False)
     return parser
 
-def do(args):
-    import os   
-    import sys
 
-    import resbuild.xml_processor as xml_processor
+def do(args):
     p = xml_processor.XmlProcessor(args)
     p.process()
 
+
 def process(values):
     ar = values.split(" ")
     args = []
@@ -53,9 +96,8 @@ def process(values):
 if __name__ == "__main__":
     parser = get_parser()
 
-    import time
     dt = time.clock()
     do(parser.parse_args())
     dt = time.clock() - dt
 
-    #print "total time: " + str(dt)
+    # print("total time: " + str(dt))

+ 87 - 76
tools/resbuild/atlas.py

@@ -1,8 +1,28 @@
+# -*- coding: utf-8 -*-
 
-import sys
+from __future__ import unicode_literals, print_function
 
-class rect:
-    def __init__(self, x = 0, y = 0, w = 0, h = 0):
+import Image
+import ImageDraw
+
+# SCALE = 50
+# OFFSET = 5
+SCALE = 1
+OFFSET = 0
+
+
+def conv(*xyxy):
+    return xyxy[0] * SCALE, xyxy[1] * SCALE, xyxy[2] * SCALE, xyxy[3] * SCALE
+
+
+def conv_in(*xyxy):
+    return xyxy[0] * SCALE + OFFSET, xyxy[1] * SCALE + OFFSET, \
+        xyxy[2] * SCALE - OFFSET, xyxy[3] * SCALE - OFFSET
+
+
+class rect(object):
+
+    def __init__(self, x=0, y=0, w=0, h=0):
         self.x = x
         self.y = y
         self.w = w
@@ -30,17 +50,17 @@ class rect:
         return self.y
 
     def is_empty(self):
-        return self.w <=0 or self.h <= 0
+        return self.w <= 0 or self.h <= 0
 
     def is_contains(self, r):
         return r.x >= self.x and r.y >= self.y and\
             r.get_bottom() <= self.get_bottom() and\
             r.get_right() <= self.get_right()
-    
+
     def is_contained(self, r):
         return self.x >= r.x and self.y >= r.y and\
-               self.get_bottom() <= r.get_bottom() and\
-               self.get_right() <= r.get_right()        
+            self.get_bottom() <= r.get_bottom() and\
+            self.get_right() <= r.get_right()
 
     def get_intersection(self, rc):
         c = rect(self.x, self.y, self.w, self.h)
@@ -70,37 +90,42 @@ class rect:
 
     def __repr__(self):
         return "(%d, %d, %d, %d)" % (self.x, self.y, self.w, self.h)
-        
- 
 
-class frame:
+
+class frame(object):
+
     def __init__(self, w, h):
         self.w = w
         self.h = h
 
 
-
 class MyException(Exception):
+
     def __init__(self, free):
         self.free = free
 
-class Node:
+
+class Node(object):
+
     def __init__(self, rect, atl, data):
         self.rect = rect
         self.atlas = atl
         self.data = data
-        
-class Atlas:
+
+
+class Atlas(object):
     n = 0
+
     def __init__(self, padding, w, h):
         self.w = w
         self.h = h
         self.free_rects = []
-        self.free_rects.append(rect(padding, padding, w - padding, h - padding))
+        self.free_rects.append(
+            rect(padding, padding, w - padding, h - padding))
         self.nodes = []
         self.bounds = rect()
         Atlas.n += 1
-        
+
     @staticmethod
     def optimize(clipped):
         res = []
@@ -116,71 +141,57 @@ class Atlas:
                     add = False
                     break
             if add:
-                append(r)       
-                
+                append(r)
+
         return res
-        
+
     def save(self):
-        #return
-        import Image, ImageDraw
-        
-        #SCALE = 50
-        #OFFSET = 5
-        SCALE = 1
-        OFFSET = 0
-        def conv(*xyxy):
-            return xyxy[0] * SCALE, xyxy[1] * SCALE, xyxy[2] * SCALE, xyxy[3] * SCALE
-        
-        def conv_in(*xyxy):        
-            return xyxy[0] * SCALE + OFFSET, xyxy[1] * SCALE + OFFSET, \
-                   xyxy[2] * SCALE - OFFSET, xyxy[3] * SCALE - OFFSET        
-        
         im = Image.new("RGBA", (self.w * SCALE, self.h * SCALE))
-        
-        draw = ImageDraw.Draw(im)        
-        draw.rectangle(conv(0, 0, self.w, self.h), fill="white")        
+
+        draw = ImageDraw.Draw(im)
+        draw.rectangle(conv(0, 0, self.w, self.h), fill="white")
 
         for src_rect in self.rects:
-            draw.rectangle(conv(*src_rect.xyxy()), fill = "red", outline="black")
-            
+            draw.rectangle(conv(*src_rect.xyxy()), fill="red", outline="black")
+
         imcopy = im.copy()
-        drawcopy = ImageDraw.Draw(imcopy)
-        
+        ImageDraw.Draw(imcopy)
+
         for fr in self.free_rects:
             rim = Image.new("RGBA", im.size)
             rimdraw = ImageDraw.Draw(rim)
-            rimdraw.rectangle(conv_in(*fr.xyxy()), fill = "green", outline="black")
+            rimdraw.rectangle(conv_in(*fr.xyxy()),
+                              fill="green", outline="black")
             mask = Image.new("RGBA", im.size, "white")
             maskdraw = ImageDraw.Draw(mask)
-            maskdraw.rectangle(conv_in(*fr.xyxy()), fill = "#c01010")
+            maskdraw.rectangle(conv_in(*fr.xyxy()), fill="#c01010")
             mask = mask.split()[0]
 
-            imcopy = Image.composite(imcopy, rim, mask)        
-            
-        imcopy.save("png/%s.png" %(self.n, ))
-        
+            imcopy = Image.composite(imcopy, rim, mask)
+
+        imcopy.save("png/%s.png" % (self.n, ))
+
     def add(self, w, h, data):
 
         dest_rect = None
         mn = 0xffffffffffffffff
 
-        
         for r in self.free_rects:
             if r.w >= w and r.h >= h:
-                #v = min((r.w - w), (r.h - h))
-                #v = r.w * r.h - w * h
+                # v = min((r.w - w), (r.h - h))
+                # v = r.w * r.h - w * h
                 v = r.y * r.x * r.x
                 if v < mn:
-                #if 1:
+                    # if 1:
                     mn = v
                     dest_rect = r
                 #    break
-                #break
-            
+                # break
+
         if not dest_rect:
-            #self.save()
+            # self.save()
             return None
-        
+
         src_rect = rect(dest_rect.x, dest_rect.y, w, h)
 
         clipped = []
@@ -204,7 +215,7 @@ class Atlas:
                 append(r4)
 
         self.free_rects = self.optimize(clipped)
-        
+
         node = Node(src_rect, self, data)
         self.nodes.append(node)
         return node
@@ -215,35 +226,35 @@ if __name__ == "__main__":
     fr = []
     random.seed(0)
     for x in range(200):
-        fr.append(frame(random.randint(10,60), random.randint(10,60)))
-    
-    
-    fr = [frame(1, 2), frame(2, 3), frame(2, 3), frame(3, 3), frame(8, 2), frame(4, 1), frame(4, 2), frame(1, 1), frame(3, 3),frame(3, 3),frame(3, 3),]
-    #fr = [frame(2, 2), frame(3, 3), frame(2, 2), ]
-    #fr = [frame(1, 1), frame(6, 3),  frame(8, 1), frame(2,2)]
-    
-    #fr = fr #30223
-    #fr = sorted(fr, key = lambda v: -max(v.h, v.w)) #21450
-    #fr = sorted(fr, key = lambda v: -v.h * v.w) #22492
-    #fr = sorted(fr, key = lambda v: -v.h) #21880
-    #fr = sorted(fr, key = lambda v: -v.w) #20573
-    
+        fr.append(frame(random.randint(10, 60), random.randint(10, 60)))
+
+    fr = [frame(1, 2), frame(2, 3), frame(2, 3), frame(3, 3), frame(8, 2),
+          frame(4, 1), frame(4, 2), frame(1, 1), frame(3, 3), frame(3, 3),
+          frame(3, 3), ]
+    # fr = [frame(2, 2), frame(3, 3), frame(2, 2), ]
+    # fr = [frame(1, 1), frame(6, 3),  frame(8, 1), frame(2,2)]
+
+    # fr = fr #30223
+    # fr = sorted(fr, key = lambda v: -max(v.h, v.w)) #21450
+    # fr = sorted(fr, key = lambda v: -v.h * v.w) #22492
+    # fr = sorted(fr, key = lambda v: -v.h) #21880
+    # fr = sorted(fr, key = lambda v: -v.w) #20573
+
     im = Image.new("RGBA", (r.w * SCALE, r.h * SCALE))
     draw = ImageDraw.Draw(im)
-    
-    draw.rectangle(conv(0,0,r.w,r.h), fill="white")
-    
+
+    draw.rectangle(conv(0, 0, r.w, r.h), fill="white")
+
     exc = ""
     atlas = Atlas(0, r.w, r.h)
     for f in fr:
         node = atlas.add(f.w, f.h)
         if not node:
             break
-        
+
     s = 0
     for f in fr:
-        s += f.w * f.h   
-    
+        s += f.w * f.h
+
     print("left: " + str(s))
-    im.save("image-%s.png" %(s, ))
-    
+    im.save("image-%s.png" % (s, ))

+ 7 - 5
tools/resbuild/oxygine_helper.py

@@ -1,8 +1,10 @@
 import os
 import sys
 
-class helper:
-    def __init__(self, root, version = 0):
+
+class helper(object):
+
+    def __init__(self, root, version=0):
         self.path_root = root + "/"
         self.path_process_xml = self.path_root + "tools/oxyresbuild.py"
         self.path_bmfont = self.path_root + "/3rdPartyTools/BMFont/bmfont.com"
@@ -13,12 +15,12 @@ class helper:
             self.path_pvrtextool = self.path_root + "/3rdPartyTools/linux/PVRTexToolCLI "
         else:
             self.path_pvrtextool = self.path_root + "/3rdPartyTools/PVRTexToolCL.exe "
-        
-    def process_xml(self, embedded, args):        
+
+    def process_xml(self, embedded, args):
         if embedded:
             folder = self.path_root + "tools"
             if folder not in sys.path:
-                sys.path.append(folder)            
+                sys.path.append(folder)
             import oxyresbuild
             oxyresbuild.process(args)
         else:

+ 173 - 169
tools/resbuild/process_atlas.py

@@ -1,28 +1,33 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
 
 try:
     import Image
 except ImportError:
     from PIL import Image
 
-from xml.dom import minidom
 import os
+import struct
+import base64
+
 from . import atlas
 from . import process
 
-import struct
-import base64
 
-def as_int(attr, df = 0):
+def as_int(attr, df=0):
     if not attr:
         return df
     return int(attr)
 
-def as_float(attr, df = 0):
+
+def as_float(attr, df=0):
     if not attr:
         return df
-    return float(attr)    
+    return float(attr)
 
-def as_bool(attr, df = False):
+
+def as_bool(attr, df=False):
     if not attr:
         return df
     lw = attr.lower()
@@ -36,35 +41,41 @@ def fixImage(image):
     data = image.load()
     for y in range(image.size[1]):
         for x in range(image.size[0]):
-            a = data[x,y][3]
-            #if a == 0 or a == 1:
+            a = data[x, y][3]
+            # if a == 0 or a == 1:
             if a == 0:
-                data[x, y] = (0,0,0,0)
+                data[x, y] = (0, 0, 0, 0)
     return image
 
+
 def premultipliedAlpha(image):
     if image.mode != "RGBA":
-        return image    
+        return image
     data = image.load()
     for y in range(image.size[1]):
         for x in range(image.size[0]):
-            dt = data[x,y]
+            dt = data[x, y]
             a = dt[3]
-            data[x, y] = ((dt[0] * a) / 255, (dt[1] * a) / 255, (dt[2] * a) / 255, a)
+            data[x, y] = ((dt[0] * a) / 255, (dt[1] * a) /
+                          255, (dt[2] * a) / 255, a)
+
+    return image
 
-    return image    
 
 def bbox(x, y, w, h):
     return (x, y, x + w, y + h)
 
-class alphaData:
+
+class alphaData(object):
+
     def __init__(self, w, h, data):
         self.w = w
         self.h = h
         self.data = data
 
 
-class frame:
+class frame(object):
+
     def __init__(self, image, bbox, image_element, rs, adata):
 
         self.image = image
@@ -77,15 +88,17 @@ class frame:
         self.border_right = self.border_bottom = 1
 
         if not bbox:
-            bbox = (0,0,1,1)
+            bbox = (0, 0, 1, 1)
 
         self.bbox = bbox
 
-class ResAnim:
+
+class ResAnim(object):
+
     def __init__(self):
         self.frames = []
         self.name = ""
-        self.frame_size2 = (1, 1)#original size * scale_factor
+        self.frame_size2 = (1, 1)  # original size * scale_factor
         self.frame_scale2 = 1.0
         self.columns = 0
         self.rows = 0
@@ -95,6 +108,7 @@ class ResAnim:
 def frame_cmp_sort(f1, f2):
     return f2.image.size[0] - f1.image.size[0]
 
+
 def applyScale(intVal, scale):
     return int(intVal * scale + 0.5)
 
@@ -103,35 +117,37 @@ def applyScale2(x, scale):
     initialX = x
     best = None
     while 1:
-        X = x * scale        
+        X = x * scale
         d = abs(X - int(X))
 
         if not best:
-            best = (d, X)        
+            best = (d, X)
 
         if best[0] > d:
-            best = (d, X)        
+            best = (d, X)
 
         eps = 0.00000001
         if d < eps:
-            return int(X)        
-
+            return int(X)
 
         if x > initialX * 2:
             return int(best[1])
 
         x += 1
 
+
 def nextPOT(v):
-    v = v - 1;
-    v = v | (v >> 1);
-    v = v | (v >> 2);
-    v = v | (v >> 4);
-    v = v | (v >> 8);
-    v = v | (v >>16);
+    v = v - 1
+    v = v | (v >> 1)
+    v = v | (v >> 2)
+    v = v | (v >> 4)
+    v = v | (v >> 8)
+    v = v | (v >> 16)
     return v + 1
 
-class settings:
+
+class settings(object):
+
     def __init__(self):
         self.get_size = None
         self.set_node = None
@@ -141,77 +157,77 @@ class settings:
         self.atlasses = []
         self.square = False
         self.npot = False
-        
+
+
 def makeAlpha(a):
-    
+
     def roundUp(v, multiple):
         if multiple == 0:
             return v
         rem = v % multiple
         if rem == 0:
-            return v     
+            return v
         res = v + multiple - rem
-        return res                
-    
-    asmall = a.resize((int(a.size[0]/4), int(a.size[1]/4)), Image.ANTIALIAS)
+        return res
 
+    asmall = a.resize(
+        (int(a.size[0] / 4), int(a.size[1] / 4)), Image.ANTIALIAS)
 
     b = asmall.getextrema()
-    
+
     if not b:
         return None
 
     if b[0] > 10:
         return None
 
-    asmall_size = asmall.size                    
+    asmall_size = asmall.size
 
     BITS = 32
 
     val = roundUp(asmall_size[0], BITS)
     lineLen = val // BITS
 
-
     buff = b''
 
     for y in range(asmall_size[1]):
 
-        line = [0 for x in range(lineLen)]                    
+        line = [0 for x in range(lineLen)]
         for x in range(asmall_size[0]):
-            p = asmall.getpixel((x,y))
-            if p > 5:                            
+            p = asmall.getpixel((x, y))
+            if p > 5:
                 n = x // BITS
-                b = x % BITS                            
+                b = x % BITS
                 line[n] |= 1 << b
 
-
         for v in line:
             buff += struct.pack("<I", v)
 
-    adata = alphaData(asmall_size[0], asmall_size[1], buff)                        
+    adata = alphaData(asmall_size[0], asmall_size[1], buff)
     return adata
 
-def pack(st, frames, sw, sh):                       
 
-    atl = atlas.Atlas(st.padding, sw, sh)            
+def pack(st, frames, sw, sh):
+
+    atl = atlas.Atlas(st.padding, sw, sh)
 
-    not_packed = []    
+    not_packed = []
     for fr in frames:
         ns = st.get_size(fr)
         node = atl.add(ns[0], ns[1], fr)
         if not node:
             not_packed.append(fr)
         else:
-            st.set_node(fr, node)   
+            st.set_node(fr, node)
 
-    #atl.add(250, 250)
-    #atl.save()
+    # atl.add(250, 250)
+    # atl.save()
 
     return not_packed, atl
 
 
 def get_pow2list(npot, mn, mx):
-    #ls = []    
+    # ls = []
     if npot:
         while 1:
             yield mn
@@ -228,7 +244,8 @@ def get_pow2list(npot, mn, mx):
             if mn > mx:
                 break
 
-def pck(st, frames):        
+
+def pck(st, frames):
     if 0:
         st = settings()
     while frames:
@@ -252,15 +269,15 @@ def pck(st, frames):
                     continue
 
                 if sw * sh < sq and not end:
-                    continue                
+                    continue
 
                 not_packed, bn = pack(st, frames, sw, sh)
                 st.atlasses.append(bn)
                 if not not_packed:
                     return
 
-                if end:                    
-                    frames = not_packed   
+                if end:
+                    frames = not_packed
                 else:
                     st.atlasses.pop()
 
@@ -275,51 +292,46 @@ def processRS(context, walker):
 
     file_path = walker.getPath("file")
 
-
-    #print image_path
+    # print image_path
 
     image = None
 
-    #fn = self._getExistsFile(image_path)
+    # fn = self._getExistsFile(image_path)
 
-    #virtual_width = 1        
-    #virtual_height = 1
+    # virtual_width = 1
+    # virtual_height = 1
     path = context.src_data + file_path
     try:
         image = Image.open(path)
-    except IOError:      
+    except IOError:
         pass
 
-
     if image:
         #   virtual_width = int(image.size[0] * scale + 0.001)
-        #   virtual_height= int(image.size[1] * scale + 0.001)    
+        #   virtual_height= int(image.size[1] * scale + 0.001)
         pass
     else:
         context.error("can't find image:\n%s\n" % (path, ))
-        image = Image.new("RGBA", (0, 0))        
+        image = Image.new("RGBA", (0, 0))
 
-    resAnim = ResAnim()            
+    resAnim = ResAnim()
     resAnim.walker = walker
     resAnim.image = image
-    resAnim.name = image_name                        
-
-
+    resAnim.name = image_name
 
     columns = as_int(image_el.getAttribute("cols"))
     frame_width = as_int(image_el.getAttribute("frame_width"))
     rows = as_int(image_el.getAttribute("rows"))
     frame_height = as_int(image_el.getAttribute("frame_height"))
     border = as_int(image_el.getAttribute("border"))
-    #sq = as_float(image_el.getAttribute("scale_quality"), 1)
-    #next.scale_quality *= sq
+    # sq = as_float(image_el.getAttribute("scale_quality"), 1)
+    # next.scale_quality *= sq
 
     if not columns:
         columns = 1
     if not rows:
         rows = 1
 
-
     if frame_width:
         columns = image.size[0] / frame_width
     else:
@@ -334,18 +346,20 @@ def processRS(context, walker):
 
     if frame_width * columns != image.size[0]:
         size_warning = True
-        context.warning("image has width %d and %d columns:" % (image.size[0], columns))
+        context.warning("image has width %d and %d columns:" %
+                        (image.size[0], columns))
     if frame_height * rows != image.size[1]:
         size_warning = True
-        context.warning("<image has height %d and %d rows:" % (image.size[1], rows))
+        context.warning("<image has height %d and %d rows:" %
+                        (image.size[1], rows))
 
     if size_warning:
         context.warnings += 1
 
-    scale_factor = walker.scale_factor    
+    scale_factor = walker.scale_factor
 
-    resAnim.frame_scale2 = scale_factor        
-    finalScale = 1    
+    resAnim.frame_scale2 = scale_factor
+    finalScale = 1
 
     upscale = False
 
@@ -364,38 +378,36 @@ def processRS(context, walker):
 
         finalScale = finalScale * scale_factor
 
-
     frame_size = (applyScale(frame_width, finalScale),
                   applyScale(frame_height, finalScale))
 
     resAnim.frame_size2 = (applyScale(frame_width, scale_factor),
-                           applyScale(frame_height, scale_factor))            
+                           applyScale(frame_height, scale_factor))
 
     resAnim.columns = columns
     resAnim.rows = rows
 
-
     for row in range(rows):
         for col in range(columns):
 
             rect = (int(col * frame_width),
                     int(row * frame_height),
-                    int((col + 1) * frame_width), 
+                    int((col + 1) * frame_width),
                     int((row + 1) * frame_height))
 
-
-            frame_image = image.crop(rect)      
-
+            frame_image = image.crop(rect)
 
             def resize():
-                ax = applyScale2(frame_width, finalScale);
-                ay = applyScale2(frame_height, finalScale);
+                ax = applyScale2(frame_width, finalScale)
+                ay = applyScale2(frame_height, finalScale)
                 bx = int(ax / finalScale)
                 by = int(ay / finalScale)
                 im = Image.new("RGBA", (bx, by))
-                im.paste(frame_image, (0, 0, frame_image.size[0], frame_image.size[1]))
+                im.paste(frame_image, (0, 0, frame_image.size[
+                         0], frame_image.size[1]))
                 frame_image = im.resize((ax, ay), Image.ANTIALIAS)
-                frame_image = frame_image.crop((0, 0, frame_size[0], frame_size[1]))                        
+                frame_image = frame_image.crop(
+                    (0, 0, frame_size[0], frame_size[1]))
 
             resize_filter = Image.ANTIALIAS
             if upscale:
@@ -403,24 +415,26 @@ def processRS(context, walker):
 
             if context.args.resize:
                 if as_bool(image_el.getAttribute("trueds")):
-                    frame_image = frame_image.resize((frame_size[0], frame_size[1]), resize_filter)
+                    frame_image = frame_image.resize(
+                        (frame_size[0], frame_size[1]), resize_filter)
                 else:
-                    ax = applyScale2(frame_width, finalScale);
-                    ay = applyScale2(frame_height, finalScale);
+                    ax = applyScale2(frame_width, finalScale)
+                    ay = applyScale2(frame_height, finalScale)
                     bx = int(ax / finalScale)
                     by = int(ay / finalScale)
                     im = Image.new("RGBA", (bx, by))
-                    im.paste(frame_image, (0, 0, frame_image.size[0], frame_image.size[1]))
+                    im.paste(frame_image, (0, 0, frame_image.size[
+                             0], frame_image.size[1]))
                     frame_image = im.resize((ax, ay), resize_filter)
-                    frame_image = frame_image.crop((0, 0, frame_size[0], frame_size[1]))
+                    frame_image = frame_image.crop(
+                        (0, 0, frame_size[0], frame_size[1]))
 
             trim = as_bool(image_el.getAttribute("trim"), True)
 
-
             adata = None
 
             if image.mode == "RGBA" and trim:
-                r,g,b,a = frame_image.split()
+                r, g, b, a = frame_image.split()
                 a = a.point(lambda p: p - 2)
 
                 if walker.hit_test:
@@ -428,14 +442,14 @@ def processRS(context, walker):
 
                 frame_bbox = a.getbbox()
             else:
-                frame_bbox = (0,0,frame_image.size[0],frame_image.size[1])
+                frame_bbox = (0, 0, frame_image.size[0], frame_image.size[1])
 
             if not frame_bbox:
-                frame_bbox = (0,0,0,0)
+                frame_bbox = (0, 0, 0, 0)
 
+            # note: neither of these variables are used
             w = frame_bbox[2] - frame_bbox[0]
-            h = frame_bbox[3] - frame_bbox[1]                    
-
+            h = frame_bbox[3] - frame_bbox[1]
 
             frame_image = frame_image.crop(frame_bbox)
 
@@ -443,11 +457,9 @@ def processRS(context, walker):
             if border:
                 fr.border_left = fr.border_right = fr.border_top = fr.border_bottom = border
 
-
-
             resAnim.frames.append(fr)
 
-    return resAnim                    
+    return resAnim
 
 
 class atlas_Processor(process.Process):
@@ -456,19 +468,15 @@ class atlas_Processor(process.Process):
     def __init__(self):
         self.atlas_group_id = 0
 
-
-    def process(self, context, walker):        
+    def process(self, context, walker):
         self.atlas_group_id += 1
 
-        #meta = context.add_meta()
+        # meta = context.add_meta()
 
         anims = []
         frames = []
 
-
-        import struct
-
-        alphaData = ""        
+        alphaData = ""
 
         while True:
             next = walker.next()
@@ -483,22 +491,21 @@ class atlas_Processor(process.Process):
 
             if anim:
                 anims.append(anim)
-                frames.extend(anim.frames)            
-
+                frames.extend(anim.frames)
 
-        #sort frames by size
+        # sort frames by size
         #frames = sorted(frames, key = lambda fr: -fr.image.size[1])
         #frames = sorted(frames, key = lambda fr: -fr.image.size[0])
-        frames = sorted(frames, key = lambda fr: -1 * max(fr.image.size[0], fr.image.size[1]) * max(fr.image.size[0], fr.image.size[1]))
+        frames = sorted(frames, key=lambda fr: -1 * max(
+            fr.image.size[0], fr.image.size[1]) * max(fr.image.size[0], fr.image.size[1]))
 
         sq = 0
         for f in frames:
             sq += f.image.size[0] * f.image.size[1]
 
-
         compression = context.compression
 
-        def get_aligned_frame_size(frame):            
+        def get_aligned_frame_size(frame):
             def align_pixel(p):
                 if not compression or compression == "no":
                     return p + 1
@@ -516,7 +523,6 @@ class atlas_Processor(process.Process):
             sz = frame.image.size
             return sz
 
-
         def set_node(frame, node):
             frame.node = node
 
@@ -528,13 +534,13 @@ class atlas_Processor(process.Process):
         st.max_h = context.args.max_height
         st.square = context.compression == "pvrtc"
         st.padding = 0
-        
+
         if len(frames) == 1:
-            st.get_size = get_original_frame_size            
+            st.get_size = get_original_frame_size
 
-        pck(st, frames) 
+        pck(st, frames)
 
-        #print "done"
+        # print "done"
 
         for atlas_id, atl in enumerate(st.atlasses):
             image = Image.new("RGBA", (atl.w, atl.h))
@@ -545,35 +551,36 @@ class atlas_Processor(process.Process):
                 y = node.rect.y + fr.border_top
                 sz = fr.image.size
                 rect = bbox(x, y, sz[0], sz[1])
-                
+
                 part = fr.image.crop(bbox(0, 0,     sz[0], 1))
                 image.paste(part,    bbox(x, y - 1, sz[0], 1))
 
                 part = fr.image.crop(bbox(0, sz[1] - 1, sz[0], 1))
                 image.paste(part,    bbox(x, y + sz[1], sz[0], 1))
 
-
-                part = fr.image.crop(bbox(0    , 0,     1, sz[1]))
+                part = fr.image.crop(bbox(0, 0,     1, sz[1]))
                 image.paste(part,    bbox(x - 1, y,     1, sz[1]))
-                
-                part = fr.image.crop(bbox(sz[0]- 1, 0,  1, sz[1]))
-                image.paste(part,    bbox(x+sz[0],  y,  1, sz[1]))
+
+                part = fr.image.crop(bbox(sz[0] - 1, 0,  1, sz[1]))
+                image.paste(part,    bbox(x + sz[0],  y,  1, sz[1]))
 
                 image.paste(fr.image, rect)
 
                 fr.atlas_id = atlas_id
 
-            image_atlas_el = walker.root_meta.ownerDocument.createElement("atlas")                
-            walker.root_meta.insertBefore(image_atlas_el,  anims[0].walker.root_meta)
-            #meta.appendChild(image_atlas_el)            
-
+            image_atlas_el = walker.root_meta.ownerDocument.createElement(
+                "atlas")
+            walker.root_meta.insertBefore(
+                image_atlas_el,  anims[0].walker.root_meta)
+            # meta.appendChild(image_atlas_el)
 
             base_name = "%d_%d" % (self.atlas_group_id, atlas_id)
             ox_fmt = "r8g8b8a8"
 
             def compress(src, dest, fmt):
-                cmd = context.helper.path_pvrtextool + " -i %s -f %s,UBN,lRGB -o %s" % (src, fmt, dest)
-                cmd += " -l" #alpha bleed
+                cmd = context.helper.path_pvrtextool + \
+                    " -i %s -f %s,UBN,lRGB -o %s" % (src, fmt, dest)
+                cmd += " -l"  # alpha bleed
 
                 if context.args.quality == "best":
                     cmd += " -q pvrtcbest"
@@ -581,15 +588,15 @@ class atlas_Processor(process.Process):
                     cmd += " -q pvrtcfast"
 
                 if context.args.dither:
-                    cmd += " -dither"                            
-                cmd += " -shh" #silent
+                    cmd += " -dither"
+                cmd += " -shh"  # silent
                 os.system(cmd)
 
             if compression == "etc1":
-                #premultipliedAlpha(v)
+                # premultipliedAlpha(v)
                 r, g, b, a = image.split()
                 rgb = Image.merge("RGB", (r, g, b))
-                alpha = Image.merge("RGB", (a,a,a))
+                alpha = Image.merge("RGB", (a, a, a))
                 base_alpha_name = base_name + "_alpha"
                 alpha_path = context.get_inner_dest(base_alpha_name + ".png")
                 alpha.save(alpha_path)
@@ -601,7 +608,7 @@ class atlas_Processor(process.Process):
                 rs = ".pvr"
 
                 rgb_path = context.get_inner_dest(path_base)
-                path = context.get_inner_dest(path_base)                
+                path = context.get_inner_dest(path_base)
                 rgb.save(path)
                 pkm_rgb = base_name + rs
                 pkm_alpha = base_alpha_name + rs
@@ -610,16 +617,15 @@ class atlas_Processor(process.Process):
                     compress(src, dest, "etc1")
                     #os.system(context.etc1tool + "%s -o %s -f etc1" %(src, dest))
 
-
                 ox_fmt = "ETC1"
 
-                compress_etc1(rgb_path, context.get_inner_dest() + pkm_rgb)                    
+                compress_etc1(rgb_path, context.get_inner_dest() + pkm_rgb)
                 os.remove(rgb_path)
-                image_atlas_el.setAttribute("file", pkm_rgb)                
+                image_atlas_el.setAttribute("file", pkm_rgb)
 
                 compress_etc1(alpha_path, context.get_inner_dest() + pkm_alpha)
                 os.remove(alpha_path)
-                image_atlas_el.setAttribute("alpha", pkm_alpha)            
+                image_atlas_el.setAttribute("alpha", pkm_alpha)
             else:
                 if context.args.nopng:
                     path_base = base_name + ".tga"
@@ -628,71 +634,69 @@ class atlas_Processor(process.Process):
 
                 path = context.get_inner_dest(path_base)
                 image_atlas_el.setAttribute("file", path_base)
-                image.save(path)            
+                image.save(path)
 
                 if context.compression == "pvrtc":
                     ox_fmt = "PVRTC_4RGBA"
 
-                    compress(path, context.get_inner_dest(base_name + ".pvr"), "PVRTC1_4")
+                    compress(path, context.get_inner_dest(
+                        base_name + ".pvr"), "PVRTC1_4")
                     image_atlas_el.setAttribute("file", base_name + ".pvr")
                     os.remove(path)
 
                 if context.compression == "pvrtc2":
                     ox_fmt = "PVRTC2_4RGBA"
 
-                    compress(path, context.get_inner_dest(base_name + ".pvr"), "PVRTC2_4")
+                    compress(path, context.get_inner_dest(
+                        base_name + ".pvr"), "PVRTC2_4")
                     image_atlas_el.setAttribute("file", base_name + ".pvr")
-                    os.remove(path)                
-
-
-
+                    os.remove(path)
 
             image_atlas_el.setAttribute("format", ox_fmt)
 
             image_atlas_el.setAttribute("w", str(image.size[0]))
-            image_atlas_el.setAttribute("h", str(image.size[1]))  
-
+            image_atlas_el.setAttribute("h", str(image.size[1]))
 
         alpha = b''
-        
 
-        for anim in anims:           
+        for anim in anims:
 
             if 0:
                 anim = ResAnim()
-                
+
             image_frames_el = anim.walker.root_meta
 
-            image_frames_el.setAttribute("fs", "%d,%d,%d,%d,%f" % (anim.columns, anim.rows, 
-                                                                   anim.frame_size2[0], anim.frame_size2[1], 
-                                                                   anim.frame_scale2)) 
+            image_frames_el.setAttribute("fs", "%d,%d,%d,%d,%f" % (anim.columns, anim.rows,
+                                                                   anim.frame_size2[
+                                                                       0], anim.frame_size2[1],
+                                                                   anim.frame_scale2))
             adata = anim.frames[0].adata
             if adata:
-                image_frames_el.setAttribute("ht", "%d,%d,%d,%d" % (len(alpha), len(adata.data), adata.w, adata.h))
+                image_frames_el.setAttribute("ht", "%d,%d,%d,%d" % (
+                    len(alpha), len(adata.data), adata.w, adata.h))
 
             if context.debug:
                 image_frames_el.setAttribute("debug_image", anim.name)
 
-
             data = ""
             for fr in anim.frames:
-                data += "%d,%d,%d,%d,%d,%d,%d;" %(fr.atlas_id, 
-                                                  fr.node.rect.x + fr.border_left, fr.node.rect.y + fr.border_top, 
-                                                  fr.bbox[0], fr.bbox[1],
-                                                  fr.bbox[2] - fr.bbox[0], fr.bbox[3] - fr.bbox[1])
+                data += "%d,%d,%d,%d,%d,%d,%d;" % (fr.atlas_id,
+                                                   fr.node.rect.x + fr.border_left, fr.node.rect.y + fr.border_top,
+                                                   fr.bbox[0], fr.bbox[1],
+                                                   fr.bbox[2] - fr.bbox[0], fr.bbox[3] - fr.bbox[1])
                 if fr.adata:
                     alpha += fr.adata.data
 
             text = image_frames_el.ownerDocument.createTextNode(data)
             image_frames_el.appendChild(text)
-        
+
         if alpha:
             doc = walker.root_meta.ownerDocument
-    
-            alpha_el = doc.createElement("ht")            
+
+            alpha_el = doc.createElement("ht")
             adata_str = base64.b64encode(alpha)
             text = doc.createTextNode(adata_str.decode("utf-8"))
             alpha_el.setAttribute("len", str(len(adata_str)))
-            alpha_el.appendChild(text)        
-    
-            walker.root_meta.appendChild(alpha_el)
+            alpha_el.appendChild(text)
+
+            walker.root_meta.appendChild(alpha_el)

+ 51 - 38
tools/resbuild/process_font.py

@@ -1,3 +1,7 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
 try:
     import Image
 except ImportError:
@@ -9,52 +13,57 @@ import tempfile
 import hashlib
 from . import process
 
+
 class bmfc_font_Processor(process.Process):
     node_id = "bmfc_font"
-    
+
     def __init__(self):
         pass
-    
+
     def process(self, context, walker):
         el = walker.root
         file_name = el.getAttribute("file")
         id = el.getAttribute("id")
         if not id:
             id = os.path.split(os.path.splitext(file_name)[0])[1]
-            
+
         path_font = context.src_data + walker.getPath("file")
         chars = walker.getPath("chars")
-        scale = context.scale * walker.scale_quality *  walker.scale_factor
-        build_bmfont(context.args.hash, 
-                     context.get_inner_dest(id + ".fnt"), 
-                     path_font, 
-                     context.get_inner_dest(""), 
-                     scale, 
+        scale = context.scale * walker.scale_quality * walker.scale_factor
+        build_bmfont(context.args.hash,
+                     context.get_inner_dest(id + ".fnt"),
+                     path_font,
+                     context.get_inner_dest(""),
+                     scale,
                      context.src_data + chars)
-        
+
         meta = walker.root_meta
         ns = get_bmfc_fontSize(path_font)
         font_size = int(ns * walker.scale_factor)
         meta.setAttribute("size", str(font_size))
         meta.setAttribute("sf", str(scale))
-        
+
+
 class font_Processor(process.Process):
     create_folder = False
     node_id = "font"
+
     def __init__(self):
         pass
-    
+
     def process(self, context, walker):
         el = walker.root
-        file_name = el.getAttribute("file")            
+
+        # note: variable unused
+        file_name = el.getAttribute("file")
 
         meta = walker.root_meta
-    
+
         font_doc = context._open_xml(context.src_data + walker.getPath("file"))
-    
+
         font_info = font_doc.getElementsByTagName("info")[0]
         size = -int(int(font_info.getAttribute("size")) * walker.scale_factor)
-        meta.setAttribute("size", str(size))        
+        meta.setAttribute("size", str(size))
         meta.setAttribute("sf", str(1))
 
 
@@ -73,33 +82,35 @@ def get_bmfc_fontSize(bm_config):
         if spl[0] == "fontSize":
             return abs(int(spl[1]))
 
+
 def build_bmfont(need_md5, fnt, bm_config, ext_folder, scale, font_chars):
-    #open config file and apply scale to size 
+    # open config file and apply scale to size
     if not os.path.exists(font_chars):
         print("error! you didn't set to bmfont 'chars'")
 
-    bm_config_temp = tempfile.NamedTemporaryFile(prefix="oxygine", delete = False)
+    bm_config_temp = tempfile.NamedTemporaryFile(
+        prefix="oxygine", delete=False)
     bm_config_temp.close()
     bm_config_temp = bm_config_temp.name
-    
-    #font_size = get_bmfc_fontSize(bm_config)
-    
+
+    # font_size = get_bmfc_fontSize(bm_config)
+
     def rewrite_config(bm_original, bm_new, pngHeight):
         font_file = open(bm_original, "r")
 
         scaled_font_file = open(bm_new, "w")
         lines = font_file.readlines()
         for line in lines:
-            #line = ""
+            # line = ""
             spl = line.split("=")
             if spl[0] == "fontSize":
                 new_size = int(abs(int(spl[1])) * scale + 0.5)
                 new_size = -new_size
 
-                line = "fontSize=%(size)d\n" % {"size":new_size}
+                line = "fontSize=%(size)d\n" % {"size": new_size}
 
-            if spl[0] == "outHeight":                
-                line = "outHeight=%(pngHeight)d\n" % {"pngHeight":pngHeight}
+            if spl[0] == "outHeight":
+                line = "outHeight=%(pngHeight)d\n" % {"pngHeight": pngHeight}
 
             scaled_font_file.write(line)
         font_file.close()
@@ -108,8 +119,10 @@ def build_bmfont(need_md5, fnt, bm_config, ext_folder, scale, font_chars):
     rewrite_config(bm_config, bm_config_temp, 1024)
 
     lang = font_chars
-    bmfont = os.path.split(__file__)[0] + "/../../3rdPartyTools/BMFont/bmfont.com"
-    cmd = "%(bmfont)s -t %(lang)s -c %(bmfc)s -o %(fnt)s" % {"bmfont":bmfont, "bmfc":bm_config_temp, "fnt":fnt, "lang":lang}
+    bmfont = os.path.split(__file__)[0] + \
+        "/../../3rdPartyTools/BMFont/bmfont.com"
+    cmd = "%(bmfont)s -t %(lang)s -c %(bmfc)s -o %(fnt)s" % {
+        "bmfont": bmfont, "bmfc": bm_config_temp, "fnt": fnt, "lang": lang}
     cmd = cmd.replace("/", "\\")
     os.system(cmd)
 
@@ -118,34 +131,34 @@ def build_bmfont(need_md5, fnt, bm_config, ext_folder, scale, font_chars):
     font_image.load()
     _, _, _, a = font_image.split()
     bbox = a.getbbox()
-    h = bbox[3] + 2     
+    h = bbox[3] + 2
     if h > 512:
-        h = 1024                
+        h = 1024
     elif h > 256:
-        h = 512                
+        h = 512
     elif h > 128:
         h = 256
     elif h > 64:
-        h = 128                
+        h = 128
     elif h < 64:
-        h = 64              
+        h = 64
     del font_image
 
     rewrite_config(bm_config, bm_config_temp, h)
     os.system(cmd)
 
     if need_md5:
-    #if 0:
+        # if 0:
         md = hashlib.md5()
         md.update(open(bm_config_temp).read())
         md.update(open(lang).read())
-        
+
         with open(os.path.split(fnt)[0] + "/md5.oxygine", "a") as m:
             m.write("%s\n%s\n" % (os.path.split(png_file)[1], md.hexdigest()))
             m.write("%s\n%s\n" % (os.path.split(fnt)[1], md.hexdigest()))
-    
+
     file = open(fnt, "r")
-    doc = minidom.parse(file)    
+    doc = minidom.parse(file)
     kern = doc.documentElement.getElementsByTagName("kernings")
     if kern:
         el = kern[0]
@@ -155,8 +168,8 @@ def build_bmfont(need_md5, fnt, bm_config, ext_folder, scale, font_chars):
         fn = os.path.split(page.getAttribute("file"))[1]
         page.setAttribute("file", fn)
     file.close()
-    
+
     file = open(fnt, "w")
     doc.writexml(file)
     file.close()
-    os.remove(bm_config_temp)
+    os.remove(bm_config_temp)

+ 14 - 7
tools/resbuild/process_starling_atlas.py

@@ -1,29 +1,36 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
+import os
+
 try:
     import Image
 except ImportError:
     from PIL import Image
-    
+
 from . import process
-import os
+
 
 class starling_atlas_Processor(process.Process):
     node_id = "starling"
+
     def __init__(self):
         pass
-    
+
     def process(self, context, walker):
-       
+
         meta = walker.root_meta
         xml_path = walker.getPath("file")
         folder = os.path.split(xml_path)[0] + "/"
         file_doc = context._open_xml(context.src_data + xml_path)
-        
+
         file_root = file_doc
         image_name = file_root.getAttribute("imagePath")
         image_path = context.src_data + folder + image_name
-        
+
         image = Image.open(image_path)
         image.load()
-                
+
         meta.setAttribute("tw", str(image.size[0]))
         meta.setAttribute("th", str(image.size[1]))

+ 107 - 102
tools/resbuild/xml_processor.py

@@ -1,10 +1,17 @@
-from xml.dom import minidom
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals, print_function
+
+
 import os
 import shutil
-from . import process_atlas
-from . import process_font
-from . import process_starling_atlas
-from . import oxygine_helper
+
+from xml.dom import minidom
+
+from . import (
+    process_atlas, process_font, process_starling_atlas, oxygine_helper
+)
+
 
 def as_bool(attr):
     if not attr:
@@ -12,41 +19,41 @@ def as_bool(attr):
     lw = attr.lower()
     return lw == "true" or lw == "1"
 
+
 class XmlWalker:
+
     def __init__(self, src, xml_folder, path, scale_factor, node, meta_node, scale_quality, hit_test):
         self.xml_folder = xml_folder
         self.path = path
         self.scale_factor = scale_factor
-        self.root = node        
+        self.root = node
         self.last = None
         self.root_meta = meta_node
-        self.last_meta = None        
+        self.last_meta = None
         self.src = src
         self.scale_quality = scale_quality
         self.hit_test = hit_test
         self.checkSetAttributes()
-    
+
     def getType(self):
         return self.root
 
     def getXMLFolder(self):
         return self.xml_folder
-    
+
     def getPath(self, attr):
         path = self.root.getAttribute(attr)
         if path.startswith("./") or path.startswith(".\\"):
             return self.xml_folder + path[2:len(path)]
-            
+
         return self.path + path
-    
+
     def setSrcFullPath(self, path):
         return self.src + path
-                       
-            
-    
+
     def checkSetAttributes(self):
         self._checkSetAttributes(self.root)
-        
+
     def _checkSetAttributes(self, node):
         path = node.getAttribute("path")
         if path:
@@ -59,93 +66,92 @@ class XmlWalker:
         scale_factor = node.getAttribute("scale_factor")
         if scale_factor:
             self.scale_factor = float(scale_factor)
-            
+
         scale_quality = node.getAttribute("scale_quality")
         if scale_quality:
-            self.scale_quality = float(scale_quality)        
+            self.scale_quality = float(scale_quality)
 
         attr = node.getAttribute("hit_test")
         if attr:
             self.hit_test = as_bool(attr)
-    
+
     def next(self):
         while True:
             if not self.last:
                 if len(self.root.childNodes) == 0:
-                    return None                
+                    return None
                 self.last = self.root.childNodes[0]
             else:
-                self.last = self.last.nextSibling                
-                
+                self.last = self.last.nextSibling
+
             if not self.last:
                 return None
-            
+
             if self.last.nodeType == self.last.TEXT_NODE:
                 continue
-            
+
             if self.last.nodeType == self.last.COMMENT_NODE:
-                continue            
-            
-            meta = self.root_meta.ownerDocument.createElement(self.last.nodeName)
+                continue
+
+            meta = self.root_meta.ownerDocument.createElement(
+                self.last.nodeName)
             self.root_meta.appendChild(meta)
             self.last_meta = meta
-            
-                
+
             if self.last.nodeName == "set":
                 self._checkSetAttributes(self.last)
                 continue
-                
+
             break
-            
+
         return XmlWalker(self.src, self.xml_folder, self.path, self.scale_factor, self.last, self.last_meta, self.scale_quality, self.hit_test)
-                
-            
-        
 
-class XmlProcessor:
+
+class XmlProcessor(object):
+
     def __init__(self, args):
         self.src_data = args.src_data + "/"
         self.dest_data = args.dest_data + "/"
         self.compression = args.compression.lower()
-        #self.etc1tool = args.android_sdk + "\\tools\\etc1tool.exe "
-        #if self.compression == "etc1":
+        # self.etc1tool = args.android_sdk + "\\tools\\etc1tool.exe "
+        # if self.compression == "etc1":
         #    if not os.path.exists(self.etc1tool):
         #        raise Exception("can't find etc1tool. please pass correct path to android_sdk")
-        
+
         self.path_xml = args.xml
         self.xml_name = os.path.split(self.path_xml)[1]
         self.atlas_group_id = 0
         self.args = args
-        self.verbosity = args.verbosity 
-        
+        self.verbosity = args.verbosity
+
         self.warnings = 0
         self.errors = 0
         #self.scale_factor = 1.0
         #self.scale_quality = 1.0
-        self.scale = args.scale        
+        self.scale = args.scale
         self.debug = args.debug
-        
+
         self.processors = {}
         #self.path_current = ""
 
         self._meta_doc = None
         self._npot = args.npot
         #self._meta_element = None
-        
-        self.helper = oxygine_helper.helper(os.path.split(__file__)[0] + "/../../")
 
-       
+        self.helper = oxygine_helper.helper(
+            os.path.split(__file__)[0] + "/../../")
+
         self.register_processor(process_font.bmfc_font_Processor())
         self.register_processor(process_font.font_Processor())
         self.register_processor(process_atlas.atlas_Processor())
-        self.register_processor(process_starling_atlas.starling_atlas_Processor())
-        
+        self.register_processor(
+            process_starling_atlas.starling_atlas_Processor())
+
         self._current_processor = None
-        
 
     def register_processor(self, processor):
         self.processors[processor.node_id] = processor
-        
+
     def get_apply_scale(self, applyScaleFactor, walker):
         """
         returns scale should be applied to image
@@ -154,85 +160,83 @@ class XmlProcessor:
         if applyScaleFactor:
             v *= walker.scale_factor
         return v
-    
+
     """
     def add_meta(self, node_id = ""):
         if not node_id:
             node_id = self._current_processor.node_id
         meta = self._meta_doc.createElement(node_id)
-        self._meta_element.appendChild(meta) 
-        
+        self._meta_element.appendChild(meta)
+
         return meta
 
     def get_meta_doc(self):
-        return self._meta_doc    
+        return self._meta_doc
         """
 
     """
-    def _process_set(self, el):        
+    def _process_set(self, el):
         path = el.getAttribute("path")
         if path:
             if path.startswith(".\\") or path.startswith("./"):
                 path = self.path_current + path
-    
+
             path = os.path.normpath(path) + "/"
             self.path_current = path
-            
+
         scale_factor = el.getAttribute("scale_factor")
         if scale_factor:
             self.scale_factor = float(scale_factor)
-        
+
         scale_quality = el.getAttribute("scale_quality")
         if scale_quality:
             self.scale_quality = float(scale_quality)
-            
+
         self.add_meta("set");
         """
-            
 
     def _open_xml(self, path):
         with open(path, "r") as file:
             font_doc = minidom.parse(file)
             return font_doc.documentElement
-        
-    
+
     def _get_src_path(self, local_path):
         return self.src_data + local_path
-    
+
     def _get_dest_path(self, local_path):
         return self.dest_data + local_path
-    
-    
+
     def _get_meta_xml_path(self, local_path):
         return self._get_dest_path(self.xml_name) + ".ox" + "/" + local_path
-    """    
+    """
     def get_current_src_path(self, local = ""):
-        return self._get_src_path(self.path_current + local)    
+        return self._get_src_path(self.path_current + local)
     """
-    def get_inner_dest(self, inner_local_path = ""):
+
+    def get_inner_dest(self, inner_local_path=""):
         return self._get_meta_xml_path(self._current_processor.node_id + "/" + inner_local_path)
-    
-    
+
     def log(self, st):
         print(st)
-        
+
     def warning(self, st):
-        if self.args.warnings:        
+        if self.args.warnings:
             print("warning: " + st)
+
     def error(self, st):
         print("error: " + st)
-                
+
     def process(self):
-        #print self.path_data
-        #print self.path_xml
-        #print self.path_atlasses
-        
+        # print self.path_data
+        # print self.path_xml
+        # print self.path_atlasses
+
         try:
             nm = self._get_src_path(self.path_xml)
             file = open(nm, "r")
         except IOError:
             print("can't open file: " + nm)
-            return 
+            return
         doc = minidom.parse(file)
         del file
 
@@ -240,35 +244,37 @@ class XmlProcessor:
         meta_element = self._meta_doc.createElement("resources")
         meta_element.setAttribute("version", "2")
         self._meta_doc.appendChild(meta_element)
-        
+
+        # note: variable unused
         totalAtlasses = 0
 
         folder = self._get_meta_xml_path("")
         shutil.rmtree(folder, True)
-            
+
         try:
             os.makedirs(folder)
         except OSError:
             pass
-        
+
         xml_folder = os.path.split(self.path_xml)[0] + "/"
-        
+
         hit_test = True
         if self.args.no_hit_test:
             hit_test = False
-            
-        walker = XmlWalker(self.src_data, xml_folder, "", 1.0, doc.documentElement, meta_element, 1.0, hit_test)
-        
+
+        walker = XmlWalker(self.src_data, xml_folder, "", 1.0,
+                           doc.documentElement, meta_element, 1.0, hit_test)
+
         while True:
-            next = walker.next();
+            next = walker.next()
             if not next:
                 break
-            
+
             name = next.root.nodeName
-            
+
             if name in self.processors:
                 proc = self.processors[name]
-                self._current_processor = proc                
+                self._current_processor = proc
                 try:
                     if proc.create_folder:
                         os.makedirs(self.get_inner_dest(""))
@@ -279,37 +285,36 @@ class XmlProcessor:
         """
         for el in doc.documentElement.childNodes:
             name = el.nodeName
-            
+
             if name in self.processors:
                 proc = self.processors[name]
-                self._current_processor = proc                
+                self._current_processor = proc
                 try:
                     if proc.create_folder:
                         os.makedirs(self.get_inner_dest(""))
                 except OSError:
                     pass
                 proc.process(self, el)
-                
-            if name == "set":                   
-                self._process_set(el)                
-            if name == "sdfont":      
-                self._process_sdf_font(el)      
+
+            if name == "set":
+                self._process_set(el)
+            if name == "sdfont":
+                self._process_sdf_font(el)
         """
 
         path_ox_dest = self._get_meta_xml_path("meta.xml")
-        
+
         file = open(path_ox_dest, "w")
         if self.verbosity > 1:
             print("saving ox file: \n" + os.path.normpath(path_ox_dest))
-            
+
         if self.args.debug:
             meta_element.writexml(file, "\t", "\t", "\n")
         else:
             meta_element.writexml(file)
-        
-                
-        #if self.verbosity > 1:
-        #    print "created %d atlasses" % (totalAtlasses, )  
-                
+
+        # if self.verbosity > 1:
+        #    print "created %d atlasses" % (totalAtlasses, )
+
         if self.warnings or self.errors:
-            print("warnings %d, errors %d" % (self.warnings, self.errors))
+            print("warnings %d, errors %d" % (self.warnings, self.errors))