controller.py 21 KB

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