controller.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. """!
  2. @package animation.controller
  3. @brief Animations management
  4. Classes:
  5. - controller::AnimationController
  6. (C) 2012 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Anna Kratochvilova <kratochanna gmail.com>
  10. """
  11. import os
  12. import wx
  13. try:
  14. import visvis.vvmovie as vv
  15. hasVisvis = True
  16. except ImportError:
  17. # if visvis.vvmovie is in grass python library
  18. # import grass.visvis as vv
  19. #
  20. # question: if integrate visvis, if integrate visvis.vvmovie or only
  21. # images2swf.py, images2gif.py?
  22. hasVisvis = False
  23. from core.gcmd import GException, GError, GMessage
  24. import grass.script as grass
  25. from temporal_manager import TemporalManager
  26. from dialogs import InputDialog, EditDialog, AnimationData, ExportDialog
  27. from utils import TemporalMode, Orientation, RenderText, WxImageToPil
  28. class AnimationController(wx.EvtHandler):
  29. def __init__(self, frame, sliders, animations, mapwindows, providers, bitmapPool):
  30. wx.EvtHandler.__init__(self)
  31. self.mapwindows = mapwindows
  32. self.frame = frame
  33. self.sliders = sliders
  34. self.slider = self.sliders['temporal']
  35. self.animationToolbar = None
  36. self.temporalMode = None
  37. self.animationData = []
  38. self.timer = wx.Timer(self, id = wx.NewId())
  39. self.animations = animations
  40. self.bitmapPool = bitmapPool
  41. self.bitmapProviders = providers
  42. for anim, win, provider in zip(self.animations, self.mapwindows, self.bitmapProviders):
  43. anim.SetCallbackUpdateFrame(lambda index, dataId, win = win, provider = provider : self.UpdateFrame(index, win, provider, dataId))
  44. anim.SetCallbackEndAnimation(lambda index, dataId, win = win, provider = provider: self.UpdateFrameEnd(index, win, provider, dataId))
  45. anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
  46. for slider in self.sliders.values():
  47. slider.SetCallbackSliderChanging(self.SliderChanging)
  48. slider.SetCallbackSliderChanged(self.SliderChanged)
  49. slider.SetCallbackFrameIndexChanged(self.ChangeFrame)
  50. self.runAfterReleasingSlider = None
  51. self.temporalManager = TemporalManager()
  52. self.Bind(wx.EVT_TIMER, self.OnTimerTick, self.timer)
  53. self.timeTick = 200
  54. def SetAnimationToolbar(self, toolbar):
  55. self.animationToolbar = toolbar
  56. def GetTimeTick(self):
  57. return self._timeTick
  58. def SetTimeTick(self, value):
  59. self._timeTick = value
  60. if self.timer.IsRunning():
  61. self.timer.Stop()
  62. self.timer.Start(self._timeTick)
  63. self.DisableSliderIfNeeded()
  64. timeTick = property(fget = GetTimeTick, fset = SetTimeTick)
  65. def OnTimerTick(self, event):
  66. for anim in self.animations:
  67. anim.Update()
  68. def StartAnimation(self):
  69. # if self.timer.IsRunning():
  70. # self.timer.Stop()
  71. for anim in self.animations:
  72. if self.timer.IsRunning():
  73. anim.NextFrameIndex()
  74. anim.Start()
  75. if not self.timer.IsRunning():
  76. self.timer.Start(self.timeTick)
  77. self.DisableSliderIfNeeded()
  78. def PauseAnimation(self, paused):
  79. if paused:
  80. if self.timer.IsRunning():
  81. self.timer.Stop()
  82. self.DisableSliderIfNeeded()
  83. else:
  84. if not self.timer.IsRunning():
  85. self.timer.Start(self.timeTick)
  86. self.DisableSliderIfNeeded()
  87. for anim in self.animations:
  88. anim.Pause(paused)
  89. def EndAnimation(self):
  90. if self.timer.IsRunning():
  91. self.timer.Stop()
  92. self.DisableSliderIfNeeded()
  93. for anim in self.animations:
  94. anim.Stop()
  95. def UpdateFrameEnd(self, index, win, provider, dataId):
  96. if self.timer.IsRunning():
  97. self.timer.Stop()
  98. self.DisableSliderIfNeeded()
  99. self.animationToolbar.Stop()
  100. self.UpdateFrame(index, win, provider, dataId)
  101. def UpdateFrame(self, index, win, provider, dataId):
  102. bitmap = provider.GetBitmap(dataId)
  103. if dataId is None:
  104. dataId = ''
  105. win.DrawBitmap(bitmap, dataId)
  106. # self.frame.SetStatusText(dataId)
  107. self.slider.UpdateFrame(index)
  108. def SliderChanging(self, index):
  109. if self.runAfterReleasingSlider is None:
  110. self.runAfterReleasingSlider = self.timer.IsRunning()
  111. self.PauseAnimation(True)
  112. self.ChangeFrame(index)
  113. def SliderChanged(self):
  114. if self.runAfterReleasingSlider:
  115. self.PauseAnimation(False)
  116. self.runAfterReleasingSlider = None
  117. def ChangeFrame(self, index):
  118. for anim in self.animations:
  119. anim.FrameChangedFromOutside(index)
  120. def DisableSliderIfNeeded(self):
  121. if self.timer.IsRunning() and self._timeTick < 100:
  122. self.slider.EnableSlider(False)
  123. else:
  124. self.slider.EnableSlider(True)
  125. def OrientationChangedInReverseMode(self, mode):
  126. if mode == Orientation.FORWARD:
  127. self.animationToolbar.PlayForward()
  128. elif mode == Orientation.BACKWARD:
  129. self.animationToolbar.PlayBack()
  130. def SetReplayMode(self, mode):
  131. for anim in self.animations:
  132. anim.replayMode = mode
  133. def SetOrientation(self, mode):
  134. for anim in self.animations:
  135. anim.orientation = mode
  136. def SetTemporalMode(self, mode):
  137. self._temporalMode = mode
  138. def GetTemporalMode(self):
  139. return self._temporalMode
  140. temporalMode = property(fget = GetTemporalMode, fset = SetTemporalMode)
  141. def GetTimeGranularity(self):
  142. if self.temporalMode == TemporalMode.TEMPORAL:
  143. return self.temporalManager.GetGranularity()
  144. return None
  145. def EditAnimations(self):
  146. # running = False
  147. # if self.timer.IsRunning():
  148. # running = True
  149. self.EndAnimation()
  150. dlg = EditDialog(parent = self.frame, evalFunction = self.EvaluateInput,
  151. animationData = self.animationData, maxAnimations = len(self.animations))
  152. if dlg.ShowModal() == wx.ID_CANCEL:
  153. dlg.Destroy()
  154. return
  155. self.animationData, self.temporalMode, self.temporalManager = dlg.GetResult()
  156. dlg.Destroy()
  157. self._setAnimations()
  158. def AddAnimation(self):
  159. # check if we can add more animations
  160. found = False
  161. indices = [anim.windowIndex for anim in self.animationData]
  162. for windowIndex in range(len(self.animations)):
  163. if windowIndex not in indices:
  164. found = True
  165. break
  166. if not found:
  167. GMessage(parent = self.frame, message = _("Maximum number of animations is %s.") % len(self.animations))
  168. return
  169. # running = False
  170. # if self.timer.IsRunning():
  171. # running = True
  172. self.EndAnimation()
  173. # self.PauseAnimation(True)
  174. animData = AnimationData()
  175. # number of active animations
  176. animationIndex = len([anim for anim in self.animations if anim.IsActive()])
  177. animData.SetDefaultValues(windowIndex, animationIndex)
  178. dlg = InputDialog(parent = self.frame, mode = 'add', animationData = animData)
  179. if dlg.ShowModal() == wx.ID_CANCEL:
  180. dlg.Destroy()
  181. return
  182. dlg.Destroy()
  183. # check compatibility
  184. if animData.windowIndex in indices:
  185. GMessage(parent = self.frame, message = _("More animations are using one window."
  186. " Please select different window for each animation."))
  187. return
  188. try:
  189. temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData])
  190. except GException, e:
  191. GError(parent = self.frame, message = e.value, showTraceback = False)
  192. return
  193. # if ok, set temporal mode
  194. self.temporalMode = temporalMode
  195. self.temporalManager = tempManager
  196. # add data
  197. windowIndex = animData.windowIndex
  198. self.animationData.append(animData)
  199. self._setAnimations()
  200. def SetAnimations(self, inputs=None, dataType=None):
  201. """!Set animation data directly.
  202. @param raster list of lists of raster maps or None
  203. @param strds list of strds or None
  204. @param inputs list of lists of raster maps or vector maps,
  205. or a space time raster or vector dataset
  206. @param dataType The type of the input data must be one of 'rast', 'vect', 'strds' or 'strds'
  207. """
  208. try:
  209. animationData = []
  210. for i in range(len(self.animations)):
  211. if inputs is not None and inputs[i]:
  212. if dataType == 'rast' or dataType == 'vect':
  213. if type(inputs[i]) == list:
  214. anim = AnimationData()
  215. anim.SetDefaultValues(i, i)
  216. anim.inputMapType = dataType
  217. anim.inputData = ','.join(inputs[i])
  218. animationData.append(anim)
  219. elif dataType == 'strds' or dataType == 'stvds':
  220. anim = AnimationData()
  221. anim.SetDefaultValues(i, i)
  222. anim.inputMapType = dataType
  223. anim.inputData = inputs[i]
  224. animationData.append(anim)
  225. except (GException, ValueError, IOError) as e:
  226. GError(parent = self.frame, message = str(e),
  227. showTraceback = False, caption = _("Invalid input"))
  228. return
  229. try:
  230. temporalMode, tempManager = self.EvaluateInput(animationData)
  231. except GException, e:
  232. GError(parent = self.frame, message = e.value, showTraceback = False)
  233. return
  234. self.animationData = animationData
  235. self.temporalManager = tempManager
  236. self.temporalMode = temporalMode
  237. self._setAnimations()
  238. def _setAnimations(self):
  239. indices = [anim.windowIndex for anim in self.animationData]
  240. self._updateWindows(activeIndices = indices)
  241. if self.temporalMode == TemporalMode.TEMPORAL:
  242. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  243. else:
  244. timeLabels, mapNamesDict = None, None
  245. self._updateSlider(timeLabels = timeLabels)
  246. self._updateAnimations(activeIndices = indices, mapNamesDict = mapNamesDict)
  247. wx.Yield()
  248. self._updateBitmapData()
  249. # if running:
  250. # self.PauseAnimation(False)
  251. # # self.StartAnimation()
  252. # else:
  253. self.EndAnimation()
  254. def _updateSlider(self, timeLabels = None):
  255. if self.temporalMode == TemporalMode.NONTEMPORAL:
  256. self.frame.SetSlider('nontemporal')
  257. self.slider = self.sliders['nontemporal']
  258. frameCount = len(self.animationData[0].mapData) # should be the same for all
  259. self.slider.SetFrames(frameCount)
  260. elif self.temporalMode == TemporalMode.TEMPORAL:
  261. self.frame.SetSlider('temporal')
  262. self.slider = self.sliders['temporal']
  263. self.slider.SetTemporalType(self.temporalManager.temporalType)
  264. self.slider.SetFrames(timeLabels)
  265. else:
  266. self.frame.SetSlider(None)
  267. self.slider = None
  268. def _updateAnimations(self, activeIndices, mapNamesDict = None):
  269. if self.temporalMode == TemporalMode.NONTEMPORAL:
  270. for i in range(len(self.animations)):
  271. if i not in activeIndices:
  272. self.animations[i].SetActive(False)
  273. continue
  274. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  275. self.animations[i].SetFrames(anim.mapData)
  276. self.animations[i].SetActive(True)
  277. else:
  278. for i in range(len(self.animations)):
  279. if i not in activeIndices:
  280. self.animations[i].SetActive(False)
  281. continue
  282. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  283. self.animations[i].SetFrames(mapNamesDict[anim.inputData])
  284. self.animations[i].SetActive(True)
  285. def _updateWindows(self, activeIndices):
  286. # add or remove window
  287. for windowIndex in range(len(self.animations)):
  288. if not self.frame.IsWindowShown(windowIndex) and windowIndex in activeIndices:
  289. self.frame.AddWindow(windowIndex)
  290. elif self.frame.IsWindowShown(windowIndex) and windowIndex not in activeIndices:
  291. self.frame.RemoveWindow(windowIndex)
  292. def _updateBitmapData(self):
  293. # unload data:
  294. for prov in self.bitmapProviders:
  295. prov.Unload()
  296. # load data
  297. for animData in self.animationData:
  298. if animData.viewMode == '2d':
  299. self._load2DData(animData)
  300. else:
  301. self._load3DData(animData)
  302. # clear bitmapPool
  303. usedNames = []
  304. for prov in self.bitmapProviders:
  305. names = prov.GetDataNames()
  306. if names:
  307. usedNames.extend(names)
  308. self.bitmapPool.Clear(usedNames)
  309. def _load2DData(self, animationData):
  310. prov = self.bitmapProviders[animationData.windowIndex]
  311. prov.SetData(datasource = animationData.mapData, dataType=animationData.inputMapType)
  312. self.bitmapProviders[animationData.windowIndex].Load()
  313. def _load3DData(self, animationData):
  314. prov = self.bitmapProviders[animationData.windowIndex]
  315. nviz = animationData.GetNvizCommands()
  316. prov.SetData(datasource = nviz['commands'],
  317. dataNames = animationData.mapData, dataType = 'nviz',
  318. suffix = animationData.nvizParameter,
  319. nvizRegion = nviz['region'])
  320. self.bitmapProviders[animationData.windowIndex].Load()
  321. def EvaluateInput(self, animationData):
  322. stds = 0
  323. maps = 0
  324. mapCount = set()
  325. tempManager = None
  326. windowIndex = []
  327. for anim in animationData:
  328. mapCount.add(len(anim.mapData))
  329. windowIndex.append(anim.windowIndex)
  330. if anim.inputMapType in ('rast', 'vect'):
  331. maps += 1
  332. elif anim.inputMapType in ('strds', 'stvds'):
  333. stds += 1
  334. if maps and stds:
  335. temporalMode = TemporalMode.NONTEMPORAL
  336. elif maps:
  337. temporalMode = TemporalMode.NONTEMPORAL
  338. elif stds:
  339. temporalMode = TemporalMode.TEMPORAL
  340. else:
  341. temporalMode = None
  342. if temporalMode == TemporalMode.NONTEMPORAL:
  343. if len(mapCount) > 1:
  344. raise GException(_("Inconsistent number of maps, please check input data."))
  345. elif temporalMode == TemporalMode.TEMPORAL:
  346. tempManager = TemporalManager()
  347. # these raise GException:
  348. for anim in animationData:
  349. if anim.inputMapType not in ('strds', 'stvds'):
  350. continue
  351. tempManager.AddTimeSeries(anim.inputData, anim.inputMapType)
  352. message = tempManager.EvaluateInputData()
  353. if message:
  354. GMessage(parent = self.frame, message = message)
  355. return temporalMode, tempManager
  356. def Reload(self):
  357. self.EndAnimation()
  358. activeIndices = [anim.windowIndex for anim in self.animationData]
  359. for index in activeIndices:
  360. self.bitmapProviders[index].Load(force = True)
  361. self.EndAnimation()
  362. def Export(self):
  363. if not self.animationData:
  364. GMessage(parent = self.frame, message = _("No animation to export."))
  365. return
  366. dlg = ExportDialog(self.frame, temporal = self.temporalMode,
  367. timeTick = self.timeTick, visvis = hasVisvis)
  368. if dlg.ShowModal() == wx.ID_OK:
  369. decorations = dlg.GetDecorations()
  370. exportInfo = dlg.GetExportInformation()
  371. dlg.Destroy()
  372. else:
  373. dlg.Destroy()
  374. return
  375. self._export(exportInfo, decorations)
  376. def _export(self, exportInfo, decorations):
  377. size = self.frame.animationPanel.GetSize()
  378. if self.temporalMode == TemporalMode.TEMPORAL:
  379. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  380. frameCount = len(timeLabels)
  381. else:
  382. frameCount = len(self.animationData[0].mapData) # should be the same for all
  383. animWinSize = []
  384. animWinPos = []
  385. animWinIndex = []
  386. # determine position and sizes of bitmaps
  387. for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
  388. if anim.IsActive():
  389. pos = tuple([pos1 + pos2 for pos1, pos2 in zip(win.GetPosition(), win.GetAdjustedPosition())])
  390. animWinPos.append(pos)
  391. animWinSize.append(win.GetAdjustedSize())
  392. animWinIndex.append(i)
  393. images = []
  394. for frameIndex in range(frameCount):
  395. image = wx.EmptyImage(*size)
  396. image.Replace(0, 0, 0, 255, 255, 255)
  397. # collect bitmaps of all windows and paste them into the one
  398. for i in range(len(animWinSize)):
  399. frameId = self.animations[animWinIndex[i]].GetFrame(frameIndex)
  400. bitmap = self.bitmapProviders[animWinIndex[i]].GetBitmap(frameId)
  401. im = wx.ImageFromBitmap(bitmap)
  402. if im.GetSize() != animWinSize[i]:
  403. im.Rescale(*animWinSize[i])
  404. image.Paste(im, *animWinPos[i])
  405. # paste decorations
  406. for decoration in decorations:
  407. # add image
  408. x = decoration['pos'][0] / 100. * size[0]
  409. y = decoration['pos'][1] / 100. * size[1]
  410. if decoration['name'] == 'image':
  411. decImage = wx.Image(decoration['file'])
  412. elif decoration['name'] == 'time':
  413. timeLabel = timeLabels[frameIndex]
  414. if timeLabel[1]:
  415. text = _("%(from)s %(dash)s %(to)s") % \
  416. {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
  417. else:
  418. text = _("%(start)s %(unit)s") % \
  419. {'start': timeLabel[0], 'unit': timeLabel[2]}
  420. decImage = RenderText(text, decoration['font']).ConvertToImage()
  421. elif decoration['name'] == 'text':
  422. text = decoration['text']
  423. decImage = RenderText(text, decoration['font']).ConvertToImage()
  424. image.Paste(decImage, x, y)
  425. images.append(image)
  426. # export
  427. if exportInfo['method'] == 'sequence':
  428. busy = wx.BusyInfo(message = _("Exporting images, please wait..."), parent = self.frame)
  429. wx.Yield()
  430. zeroPadding = len(str(len(images)))
  431. for i, image in enumerate(images):
  432. filename = "%s_%s.%s" % (exportInfo['prefix'], str(i + 1).zfill(zeroPadding),
  433. exportInfo['format']['ext'])
  434. image.SaveFile(os.path.join(exportInfo['directory'], filename), exportInfo['format']['type'])
  435. busy.Destroy()
  436. elif exportInfo['method'] in ('gif', 'swf', 'avi'):
  437. pilImages = [WxImageToPil(image) for image in images]
  438. busy = wx.BusyInfo(message = _("Exporting animation, please wait..."), parent = self.frame)
  439. wx.Yield()
  440. try:
  441. if exportInfo['method'] == 'gif':
  442. vv.writeGif(filename = exportInfo['file'], images = pilImages,
  443. duration = self.timeTick / float(1000), repeat = True)
  444. elif exportInfo['method'] == 'swf':
  445. vv.writeSwf(filename = exportInfo['file'], images = pilImages,
  446. duration = self.timeTick / float(1000), repeat = True)
  447. elif exportInfo['method'] == 'avi':
  448. vv.writeAvi(filename = exportInfo['file'], images = pilImages,
  449. duration = self.timeTick / float(1000),
  450. encoding = exportInfo['encoding'],
  451. inputOptions = '-sameq')
  452. except Exception, e:
  453. del busy
  454. GError(parent = self.frame, message = str(e))
  455. return
  456. del busy
  457. # image.SaveFile('/home/anna/testy/grass/export/export_%s.png' % frameIndex, wx.BITMAP_TYPE_PNG)
  458. # for anim in self.animationData
  459. #def test():
  460. # import gettext
  461. # gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  462. #
  463. # import grass.script as grass
  464. # import wx
  465. # app = wx.PySimpleApp()
  466. # wx.InitAllImageHandlers()
  467. # # app.MainLoop()
  468. #
  469. # bitmaps = {}
  470. # rasters = ['elevation.dem']
  471. # # rasters = ['streams']
  472. # # rasters = grass.read_command("g.mlist", type = 'rast', fs = ',', quiet = True).strip().split(',')
  473. #
  474. # # print nrows, ncols
  475. # size = (300,100)
  476. # newSize, scale = ComputeScale(size)
  477. # # print scale
  478. # LoadRasters(rasters = rasters, bitmaps = bitmaps, scale = scale, size = newSize)
  479. #
  480. # for b in bitmaps.keys():
  481. # bitmaps[b].SaveFile('/home/anna/testy/ctypes/' + b + '.png', wx.BITMAP_TYPE_PNG)
  482. #
  483. #if __name__ == '__main__':
  484. #
  485. # test()