-
Notifications
You must be signed in to change notification settings - Fork 4
/
atlas.py
318 lines (281 loc) · 13 KB
/
atlas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import gtk
import logging
import os
from xml.etree.ElementTree import Element
from utils import make_ui_path, is_contained_by
from signallable import Signallable
from loggable import Loggable
from sprite import Sprite, Animation
from selection import Selection
class Atlas(Signallable, Loggable):
__signals__ = {
'sprite-added': ['sprite'],
'sprite-removed': ['sprite']
}
def __init__(self, factory):
"""
An atlas is a collection of :class: sprites, organized inside it by
their coordinates and dimensions.
it to the atlas
"""
self.drawable = None
self.width = 0
self.height = 0
self.xoffset = 0
self.yoffset = 0
self.maxOffset = 0
self.xmlNode = None
self.sprites = []
self.animations = []
self.currentSprite = 0
self.factory = factory
self.selection = Selection()
def setDrawable(self, drawable):
self.drawable = drawable
def setXmlNode(self, node):
self.xmlNode = node
def addSprite(self, src, path):
"""
:param src: image to merge
:param path: Path of the resource.
"""
dest = self.drawable.image
coords = {}
if self.xoffset + src.size[0] > dest.size[0]:
self.xoffset = 0
self.yoffset += self.maxOffset
self.maxOffset = 0
if self.yoffset > dest.size[1]:
self.logger.warning("Space in Pixbuf exceeded, NOT ADDING : %s", path)
return None
coords["x"] = self.xoffset
coords["y"] = self.yoffset
coords["width"] = src.size[0]
coords["height"] = src.size[1]
sprite = Sprite(path, self.xoffset, self.yoffset, src.size[0], src.size[1])
dest.paste(src, (self.xoffset, self.yoffset))
self.xoffset += src.size[0]
if src.size[1] > self.maxOffset:
self.maxOffset = src.size[1]
self._updateXmlNode(sprite)
#self.logger.debug("Space in pixbuf OK, ADDING : %s", path)
self.sprites.append(sprite)
self.emit("sprite-added", sprite)
return coords
#sprite = Sprite(path, width, height)
def removeSprite(self, sprite):
"""
Will remove the sprite matching the coordinates if existing.
:param x: X coordinate in the atlas.
:param y: Y coordinate in the atlas.
"""
print sprite.texturex, sprite.texturey, sprite.textureh, sprite.texturew
try:
self.sprites.remove(sprite)
except ValueError:
print "investigate"
for elem in self.xmlNode.findall("sprite"):
if elem.attrib["path"] == sprite.path and\
elem.attrib["texturex"] == str(sprite.texturex) and \
elem.attrib["texturey"] == str(sprite.texturey):
self.xmlNode.remove(elem)
image = self.factory.makeNewDrawable(sprite.texturew, sprite.textureh)
self.drawable.image.paste(image.image, (sprite.texturex, sprite.texturey))
self.xoffset = self.xoffset - sprite.texturew
if self.xoffset < 0:
self.xoffset = 0
self.xmlNode.attrib["xoffset"] = str(self.xoffset)
self.emit("sprite-removed", sprite)
def readdSprite(self, sprite):
print sprite.texturew, sprite.textureh
drawable = self.factory.makeDrawableFromPath(sprite.path, sprite.texturew, sprite.textureh)
self.addSprite(drawable.image, sprite.path)
def loadSprites(self, node):
for elem in node.findall("sprite"):
sprite = Sprite(elem.attrib["path"], elem.attrib["texturex"],
elem.attrib["texturey"], elem.attrib["texturew"],
elem.attrib["textureh"])
self.sprites.append(sprite)
sprite.xmlNode = elem
self.emit("sprite-added", sprite)
for elem in node.findall("animation"):
anim = Animation(elem.attrib["path"], elem.attrib["texturex"],
elem.attrib["texturey"], elem.attrib["texturew"],
elem.attrib["textureh"], elem.attrib["tilelen"])
self.animations.append(anim)
anim.xmlNode = elem
self.emit("sprite-added", anim)
def unreferenceSprite(self, sprite):
self.xmlNode.remove(sprite.xmlNode)
self.sprites.remove(sprite)
def referenceSprite(self, coordinates):
sprite = Sprite("NoResource", coordinates[2],
coordinates[3], coordinates[0],
coordinates[1])
self.sprites.append(sprite)
newNode = Element("sprite", attrib = {"name" : "",
"path" : str(sprite.path),
"texturex" : str(sprite.texturex),
"texturey" : str(sprite.texturey),
"texturew" : str(sprite.texturew),
"textureh" : str(sprite.textureh)})
self.xmlNode.append(newNode)
sprite.xmlNode = newNode
return sprite
#self.emit("sprite-referenced", sprite)
def referenceAnimation(self, coordinates, tilelen):
anim = Animation("NoResource", coordinates[2],
coordinates[3], coordinates[0],
coordinates[1], tilelen)
self.animations.append(anim)
newNode = Element("animation", attrib = {"name" : "",
"path" : str(anim.path),
"texturex" : str(anim.texturex),
"texturey" : str(anim.texturey),
"texturew" : str(anim.texturew),
"textureh" : str(anim.textureh),
"tilelen" : str(tilelen)})
self.xmlNode.append(newNode)
anim.xmlNode = newNode
return anim
def extendSprites(self, size, alignment):
for sprite in self.sprites:
vdiff = size - (sprite.texturew % size)
hdiff = size - (sprite.textureh % size)
sprite.texturex -= vdiff / 2
sprite.texturew += vdiff
if alignment == 0: #BASELINE
sprite.texturey -= hdiff
sprite.textureh += hdiff
elif alignment == 1: #CENTERED
sprite.texturey -= hdiff / 2
sprite.textureh += hdiff
elif alignment == 2: #TOP
sprite.textureh += hdiff
sprite.updateXmlNode()
def coords_compare(self, elem1, elem2):
if elem1.texturey - elem2.texturey > 10: # NEXT LINE
return 1
elif elem1.texturey - elem2.texturey < -10: #PREVIOUS LINE
return -1
return elem1.texturex - elem2.texturex # SAME LINE
def sortSprites(self):
self.sprites = sorted(self.sprites, cmp = self.coords_compare)
def getSpriteForXY(self, x, y, isCurrent = False):
#FIXME : hack, accounting for the possible margin between the
# event box bounds and the atlas bounds. I'm ashamed
for i, sprite in enumerate(self.sprites):
try:
if is_contained_by(x, y,
sprite.texturex,
sprite.texturey,
sprite.texturew,
sprite.textureh):
if isCurrent:
self.currentSprite = i
return sprite
except KeyError:
pass
def getAnimForXY(self, x, y, isCurrent = False):
#FIXME : hack, accounting for the possible margin between the
# event box bounds and the atlas bounds. I'm ashamed
for i, anim in enumerate(self.animations):
try:
if is_contained_by(x, y,
anim.texturex,
anim.texturey,
anim.texturew * anim.tilelen,
anim.textureh):
if isCurrent:
self.currentAnim = i
return anim
except KeyError:
pass
def getCurrentSprite(self):
return self.sprites[self.currentSprite]
def getNextSprite(self):
if self.currentSprite == len(self.sprites) - 1:
return self.sprites[self.currentSprite]
self.currentSprite += 1
return self.sprites[self.currentSprite]
def getPreviousSprite(self):
if self.currentSprite == 0:
return self.sprites[self.currentSprite]
self.currentSprite -= 1
return self.sprites[self.currentSprite]
def _updateXmlNode(self, sprite):
self.xmlNode.attrib["xoffset"] = str(self.xoffset)
self.xmlNode.attrib["yoffset"] = str(self.yoffset)
self.xmlNode.attrib["maxoffset"] = str(self.maxOffset)
newNode = Element("sprite", attrib = {"name" : "",
"path" : str(sprite.path),
"texturex" : str(sprite.texturex),
"texturey" : str(sprite.texturey),
"texturew" : str(sprite.texturew),
"textureh" : str(sprite.textureh)})
self.xmlNode.append(newNode)
sprite.xmlNode = newNode
class AtlasCreator(gtk.Builder):
def __init__(self, instance):
gtk.Builder.__init__(self)
self.logger = logging.getLogger("KRFEditor")
self.logger.debug("Atlas Creator opened")
self.add_from_file(make_ui_path("atlas_creator"))
self.location = os.getcwd() + "/auto"
self.app = instance
self.get_object("assistant1").connect("prepare", self._prepareCb)
self.get_object("assistant1").connect("apply", self._applyCb)
self.get_object("assistant1").connect("close", self._closeCb)
self.get_object("assistant1").connect("delete-event", self._closeCb)
self.get_object("assistant1").connect("cancel", self._closeCb)
self.get_object("button1").connect("clicked", self._newFileChooserCb)
self.get_object("assistant1").set_transient_for(self.app.app.window)
self.height = 1024
self.width = 1024
adj = gtk.Adjustment(1024.0, 1.0, 102400.0, 1.0, 5.0, 0.0)
spinbutton = gtk.SpinButton(adj, 0, 0)
spinbutton.set_wrap(True)
spinbutton.show()
spinbutton.connect("value_changed", self._widthChangedCb)
self.get_object("vbox3").pack_end(spinbutton)
adj = gtk.Adjustment(1024.0, 1.0, 102400.0, 1.0, 5.0, 0.0)
spinbutton = gtk.SpinButton(adj, 0, 0)
spinbutton.set_wrap(True)
spinbutton.show()
spinbutton.connect("value_changed", self._heightChangedCb)
self.get_object("vbox3").pack_end(spinbutton)
# INTERNAL
def _widthChangedCb(self, spinner):
self.width = int(spinner.get_value())
def _heightChangedCb(self, spinner):
self.height = int(spinner.get_value())
def _newFileChooserCb(self, button):
chooser = gtk.FileChooserDialog(title = "Choose location", action = gtk.FILE_CHOOSER_ACTION_SAVE,
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))
if chooser.run() == gtk.RESPONSE_ACCEPT:
self.location = chooser.get_filename()
self.logger.info("User chose location %s", self.location)
button.set_label(self.location)
# Will pop a warning. Harmless, see http://dev.blankonlinux.or.id/browser/rote/kazam/README?rev=current%3A
# for example.
chooser.destroy()
print self.location
def _applyCb(self, assistant):
self.location += ".png"
self.logger.info("creating new atlas at %s with width = %d and height = %d",
self.location, self.width, self.height)
options = {}
options["location"] = self.location
options["width"] = self.width
options["height"] = self.height
options["name"] = self.location.split("/")[-1]
self.app.createAtlas(options)
def _closeCb(self, assistant, unused = None):
assistant.destroy()
def _prepareCb(self, assistant, page):
assistant.set_page_complete(page, True)
return True
def _createAtlasCb(self, unused):
self.logger.info("Created Atlas")
self.get_object("dialog").destroy()