Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Created January 8, 2010 22:13
Show Gist options
  • Save hugowetterberg/272485 to your computer and use it in GitHub Desktop.
Save hugowetterberg/272485 to your computer and use it in GitHub Desktop.
Probably of limited interest for other people, but this is a small recipe for turning svg paths into chipmunk consumable shape coordinates using python and xslt. The svg was created using the GLIPS Graffiti editor http://glipssvgeditor.sourceforge.net
{
"player": [
[
0.0,
0.0
],
[
10.0,
-30.0
],
[
10.0,
-130.0
],
[
0.0,
-160.0
]
],
"powerup": [
[
0.0,
0.0
],
[
30.0,
0.0
],
[
30.0,
-30.0
],
[
0.0,
-30.0
]
],
"opponent": [
[
10.0,
-160.0
],
[
0.0,
-130.0
],
[
0.0,
-30.0
],
[
10.0,
0.0
]
]
}
#!/usr/bin/env python
import subprocess
import json
import re
X, Y = 0, 1
def is_clockwise(points):
"""
Check if the points given forms a clockwise polygon
Taken from the pymunk project http://pymunk.googlecode.com/svn/tags/pymunk-0.8.4/pymunk/util.py
:return: True if the points forms a clockwise polygon
"""
a = 0
i, j = 0, 0
for i in range(len(points)):
j = i + 1
if j == len(points): j = 0
a += points[i][X]*points[j][Y] - points[i][Y]*points[j][X]
return a <= 0 #or is it the other way around?
proc = subprocess.Popen(["xsltproc", "Shapes.xslt", "Shapes.svg"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = proc.communicate()
shapes = json.loads(output)
for shape_id in shapes:
m = re.findall('(\d+(?:\.\d+)?)\s(\d+(?:\.\d+)?)', shapes[shape_id])
# Invert the y coordinates and find the minimum x and y coordinate
inverted = []
minx = 480
miny = 320
for coord in m:
x = float(coord[X])
y = float(coord[Y])
inverted.append((x, y))
minx = min(x, minx)
miny = min(y, miny)
# Align the shape to the lower left corner
aligned = []
for coord in inverted:
aligned.append((coord[X]-minx, -coord[Y]+miny))
# Make sure that our polygon is clockwise
if not is_clockwise(aligned):
aligned.reverse()
shapes[shape_id] = aligned
f = open('Shapes.json', 'w')
f.write(json.dumps(shapes, indent=2))
f.close()
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg">
<xsl:output method="text" />
<xsl:template match="/">{
<xsl:for-each select="//svg:path"><xsl:text> </xsl:text>"<xsl:value-of select="@id"/>": "<xsl:value-of select="@d"/>"<xsl:if test="position() != last()">,</xsl:if><xsl:text>
</xsl:text>
</xsl:for-each>}
</xsl:template>
</xsl:stylesheet>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment