controller.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. """!
  2. @package animation.controller
  3. @brief Animations management
  4. Classes:
  5. - controller::AnimationController
  6. (C) 2013 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 Petrasova <kratochanna gmail.com>
  10. """
  11. import os
  12. import wx
  13. from core.gcmd import GException, GError, GMessage
  14. from core.utils import _
  15. from grass.imaging import writeAvi, writeGif, writeIms, writeSwf
  16. from core.settings import UserSettings
  17. from animation.temporal_manager import TemporalManager
  18. from animation.dialogs import InputDialog, EditDialog, ExportDialog
  19. from animation.utils import TemporalMode, TemporalType, Orientation, RenderText, WxImageToPil, \
  20. sampleCmdMatrixAndCreateNames, layerListToCmdsMatrix, HashCmds, getCpuCount
  21. from animation.data import AnimationData
  22. class AnimationController(wx.EvtHandler):
  23. def __init__(self, frame, sliders, animations, mapwindows, provider, bitmapPool, mapFilesPool):
  24. wx.EvtHandler.__init__(self)
  25. self.mapwindows = mapwindows
  26. self.frame = frame
  27. self.sliders = sliders
  28. self.slider = self.sliders['temporal']
  29. self.animationToolbar = None
  30. self.temporalMode = None
  31. self.animationData = []
  32. self.timer = wx.Timer(self, id=wx.NewId())
  33. self.animations = animations
  34. self.bitmapPool = bitmapPool
  35. self.mapFilesPool = mapFilesPool
  36. self.bitmapProvider = provider
  37. for anim, win in zip(self.animations, self.mapwindows):
  38. anim.SetCallbackUpdateFrame(
  39. lambda index, dataId, win=win: self.UpdateFrame(index, win, dataId))
  40. anim.SetCallbackEndAnimation(
  41. lambda index, dataId, win=win: self.UpdateFrameEnd(index, win, dataId))
  42. anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
  43. for slider in self.sliders.values():
  44. slider.SetCallbackSliderChanging(self.SliderChanging)
  45. slider.SetCallbackSliderChanged(self.SliderChanged)
  46. slider.SetCallbackFrameIndexChanged(self.ChangeFrame)
  47. self.runAfterReleasingSlider = None
  48. self.temporalManager = TemporalManager()
  49. self.Bind(wx.EVT_TIMER, self.OnTimerTick, self.timer)
  50. self.timeTick = 200
  51. self._dialogs = {}
  52. def SetAnimationToolbar(self, toolbar):
  53. self.animationToolbar = toolbar
  54. def GetTimeTick(self):
  55. return self._timeTick
  56. def SetTimeTick(self, value):
  57. self._timeTick = value
  58. if self.timer.IsRunning():
  59. self.timer.Stop()
  60. self.timer.Start(self._timeTick)
  61. self.DisableSliderIfNeeded()
  62. timeTick = property(fget=GetTimeTick, fset=SetTimeTick)
  63. def OnTimerTick(self, event):
  64. for anim in self.animations:
  65. anim.Update()
  66. def StartAnimation(self):
  67. # if self.timer.IsRunning():
  68. # self.timer.Stop()
  69. for anim in self.animations:
  70. if self.timer.IsRunning():
  71. anim.NextFrameIndex()
  72. anim.Start()
  73. if not self.timer.IsRunning():
  74. self.timer.Start(self.timeTick)
  75. self.DisableSliderIfNeeded()
  76. def PauseAnimation(self, paused):
  77. if paused:
  78. if self.timer.IsRunning():
  79. self.timer.Stop()
  80. self.DisableSliderIfNeeded()
  81. else:
  82. if not self.timer.IsRunning():
  83. self.timer.Start(self.timeTick)
  84. self.DisableSliderIfNeeded()
  85. for anim in self.animations:
  86. anim.Pause(paused)
  87. def EndAnimation(self):
  88. if self.timer.IsRunning():
  89. self.timer.Stop()
  90. self.DisableSliderIfNeeded()
  91. for anim in self.animations:
  92. anim.Stop()
  93. def UpdateFrameEnd(self, index, win, dataId):
  94. if self.timer.IsRunning():
  95. self.timer.Stop()
  96. self.DisableSliderIfNeeded()
  97. self.animationToolbar.Stop()
  98. self.UpdateFrame(index, win, dataId)
  99. def UpdateFrame(self, index, win, dataId):
  100. bitmap = self.bitmapProvider.GetBitmap(dataId)
  101. if not UserSettings.Get(group='animation', key='temporal',
  102. subkey=['nodata', 'enable']):
  103. if dataId is not None:
  104. win.DrawBitmap(bitmap)
  105. else:
  106. win.DrawBitmap(bitmap)
  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. dlg.CenterOnParent()
  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,
  169. message=_("Maximum number of animations is %s.") % len(self.animations))
  170. return
  171. # running = False
  172. # if self.timer.IsRunning():
  173. # running = True
  174. self.EndAnimation()
  175. # self.PauseAnimation(True)
  176. animData = AnimationData()
  177. # number of active animations
  178. animationIndex = len([anim for anim in self.animations if anim.IsActive()])
  179. animData.SetDefaultValues(windowIndex, animationIndex)
  180. dlg = InputDialog(parent=self.frame, mode='add', animationData=animData)
  181. dlg.CenterOnParent()
  182. if dlg.ShowModal() == wx.ID_CANCEL:
  183. dlg.Destroy()
  184. return
  185. dlg.Destroy()
  186. # check compatibility
  187. if animData.windowIndex in indices:
  188. GMessage(parent=self.frame, message=_("More animations are using one window."
  189. " Please select different window for each animation."))
  190. return
  191. try:
  192. temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData])
  193. except GException as e:
  194. GError(parent=self.frame, message=e.value, showTraceback=False)
  195. return
  196. # if ok, set temporal mode
  197. self.temporalMode = temporalMode
  198. self.temporalManager = tempManager
  199. # add data
  200. windowIndex = animData.windowIndex
  201. self.animationData.append(animData)
  202. self._setAnimations()
  203. def SetAnimations(self, layerLists):
  204. """!Set animation data directly.
  205. @param layerLists list of layerLists
  206. """
  207. try:
  208. animationData = []
  209. for i in range(len(self.animations)):
  210. if layerLists[i]:
  211. anim = AnimationData()
  212. anim.SetDefaultValues(i, i)
  213. anim.SetLayerList(layerLists[i])
  214. animationData.append(anim)
  215. except (GException, ValueError, IOError) as e:
  216. GError(parent=self.frame, message=str(e),
  217. showTraceback=False, caption=_("Invalid input"))
  218. return
  219. try:
  220. temporalMode, tempManager = self.EvaluateInput(animationData)
  221. except GException as e:
  222. GError(parent=self.frame, message=e.value, showTraceback=False)
  223. return
  224. self.animationData = animationData
  225. self.temporalManager = tempManager
  226. self.temporalMode = temporalMode
  227. self._setAnimations()
  228. def _setAnimations(self):
  229. indices = [anim.windowIndex for anim in self.animationData]
  230. self._updateWindows(activeIndices=indices)
  231. if self.temporalMode == TemporalMode.TEMPORAL:
  232. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  233. else:
  234. timeLabels, mapNamesDict = None, None
  235. for anim in self.animationData:
  236. if anim.viewMode == '2d':
  237. anim.cmdMatrix = layerListToCmdsMatrix(anim.layerList)
  238. else:
  239. anim.cmdMatrix = [(cmd,) for cmd in anim.GetNvizCommands()['commands']]
  240. self._updateSlider(timeLabels=timeLabels)
  241. self._updateAnimations(activeIndices=indices, mapNamesDict=mapNamesDict)
  242. wx.Yield()
  243. self._updateBitmapData()
  244. # if running:
  245. # self.PauseAnimation(False)
  246. # # self.StartAnimation()
  247. # else:
  248. self.EndAnimation()
  249. def _updateSlider(self, timeLabels=None):
  250. if self.temporalMode == TemporalMode.NONTEMPORAL:
  251. self.frame.SetSlider('nontemporal')
  252. self.slider = self.sliders['nontemporal']
  253. frameCount = self.animationData[0].mapCount
  254. self.slider.SetFrames(frameCount)
  255. elif self.temporalMode == TemporalMode.TEMPORAL:
  256. self.frame.SetSlider('temporal')
  257. self.slider = self.sliders['temporal']
  258. self.slider.SetTemporalType(self.temporalManager.temporalType)
  259. self.slider.SetFrames(timeLabels)
  260. else:
  261. self.frame.SetSlider(None)
  262. self.slider = None
  263. def _updateAnimations(self, activeIndices, mapNamesDict=None):
  264. if self.temporalMode == TemporalMode.NONTEMPORAL:
  265. for i in range(len(self.animations)):
  266. if i not in activeIndices:
  267. self.animations[i].SetActive(False)
  268. continue
  269. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  270. regions = anim.GetRegions()
  271. self.animations[i].SetFrames([HashCmds(cmdList, region)
  272. for cmdList, region in zip(anim.cmdMatrix, regions)])
  273. self.animations[i].SetActive(True)
  274. else:
  275. for i in range(len(self.animations)):
  276. if i not in activeIndices:
  277. self.animations[i].SetActive(False)
  278. continue
  279. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  280. regions = anim.GetRegions()
  281. identifiers = sampleCmdMatrixAndCreateNames(anim.cmdMatrix,
  282. mapNamesDict[anim.firstStdsNameType[0]],
  283. regions)
  284. self.animations[i].SetFrames(identifiers)
  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 previous data
  295. self.bitmapProvider.Unload()
  296. # load new data
  297. for animData in self.animationData:
  298. if animData.viewMode == '2d':
  299. self._set2DData(animData)
  300. else:
  301. self._load3DData(animData)
  302. self._loadLegend(animData)
  303. color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
  304. self.bitmapProvider.Load(nprocs=getCpuCount(), bgcolor=color)
  305. # clear pools
  306. self.bitmapPool.Clear()
  307. self.mapFilesPool.Clear()
  308. def _set2DData(self, animationData):
  309. opacities = [layer.opacity for layer in animationData.layerList if layer.active]
  310. regions = animationData.GetRegions()
  311. self.bitmapProvider.SetCmds(animationData.cmdMatrix, opacities, regions)
  312. def _load3DData(self, animationData):
  313. nviz = animationData.GetNvizCommands()
  314. self.bitmapProvider.SetCmds3D(nviz['commands'], nviz['region'])
  315. def _loadLegend(self, animationData):
  316. if animationData.legendCmd:
  317. try:
  318. bitmap = self.bitmapProvider.LoadOverlay(animationData.legendCmd)
  319. try:
  320. from PIL import Image
  321. for param in animationData.legendCmd:
  322. if param.startswith('at'):
  323. b, t, l, r = param.split('=')[1].split(',')
  324. x, y = float(l) / 100., 1 - float(t) / 100.
  325. break
  326. except ImportError:
  327. x, y = 0, 0
  328. self.mapwindows[animationData.windowIndex].SetOverlay(bitmap, x, y)
  329. except GException:
  330. GError(message=_("Failed to display legend."))
  331. else:
  332. self.mapwindows[animationData.windowIndex].ClearOverlay()
  333. def EvaluateInput(self, animationData):
  334. stds = 0
  335. maps = 0
  336. mapCount = set()
  337. tempManager = None
  338. windowIndex = []
  339. for anim in animationData:
  340. for layer in anim.layerList:
  341. if layer.active and hasattr(layer, 'maps'):
  342. if layer.mapType in ('strds', 'stvds', 'str3ds'):
  343. stds += 1
  344. else:
  345. maps += 1
  346. mapCount.add(len(layer.maps))
  347. windowIndex.append(anim.windowIndex)
  348. if maps and stds:
  349. temporalMode = TemporalMode.NONTEMPORAL
  350. elif maps:
  351. temporalMode = TemporalMode.NONTEMPORAL
  352. elif stds:
  353. temporalMode = TemporalMode.TEMPORAL
  354. else:
  355. temporalMode = None
  356. if temporalMode == TemporalMode.NONTEMPORAL:
  357. if len(mapCount) > 1:
  358. raise GException(_("Inconsistent number of maps, please check input data."))
  359. elif temporalMode == TemporalMode.TEMPORAL:
  360. tempManager = TemporalManager()
  361. # these raise GException:
  362. for anim in animationData:
  363. tempManager.AddTimeSeries(*anim.firstStdsNameType)
  364. message = tempManager.EvaluateInputData()
  365. if message:
  366. GMessage(parent=self.frame, message=message)
  367. return temporalMode, tempManager
  368. def Reload(self):
  369. self.EndAnimation()
  370. color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
  371. self.bitmapProvider.Load(nprocs=getCpuCount(), bgcolor=color, force=True)
  372. self.EndAnimation()
  373. def Export(self):
  374. if not self.animationData:
  375. GMessage(parent=self.frame, message=_("No animation to export."))
  376. return
  377. if 'export' in self._dialogs:
  378. self._dialogs['export'].Show()
  379. self._dialogs['export'].Raise()
  380. else:
  381. dlg = ExportDialog(self.frame, temporal=self.temporalMode,
  382. timeTick=self.timeTick)
  383. dlg.CenterOnParent()
  384. dlg.doExport.connect(self._export)
  385. self._dialogs['export'] = dlg
  386. dlg.Show()
  387. def _export(self, exportInfo, decorations):
  388. size = self.frame.animationPanel.GetSize()
  389. if self.temporalMode == TemporalMode.TEMPORAL:
  390. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  391. frameCount = len(timeLabels)
  392. else:
  393. frameCount = self.animationData[0].mapCount # should be the same for all
  394. animWinSize = []
  395. animWinPos = []
  396. animWinIndex = []
  397. legends = [anim.legendCmd for anim in self.animationData]
  398. # determine position and sizes of bitmaps
  399. for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
  400. if anim.IsActive():
  401. pos = win.GetPosition()
  402. animWinPos.append(pos)
  403. animWinSize.append(win.GetSize())
  404. animWinIndex.append(i)
  405. images = []
  406. busy = wx.BusyInfo(message=_("Preparing export, please wait..."), parent=self.frame)
  407. wx.Yield()
  408. for frameIndex in range(frameCount):
  409. image = wx.EmptyImage(*size)
  410. image.Replace(0, 0, 0, 255, 255, 255)
  411. # collect bitmaps of all windows and paste them into the one
  412. for i in animWinIndex:
  413. frameId = self.animations[i].GetFrame(frameIndex)
  414. if not UserSettings.Get(group='animation', key='temporal',
  415. subkey=['nodata', 'enable']):
  416. if frameId is not None:
  417. bitmap = self.bitmapProvider.GetBitmap(frameId)
  418. else:
  419. bitmap = self.bitmapProvider.GetBitmap(frameId)
  420. im = wx.ImageFromBitmap(bitmap)
  421. # add legend if used
  422. legend = legends[i]
  423. if legend:
  424. legendBitmap = self.bitmapProvider.LoadOverlay(legend)
  425. x, y = self.mapwindows[i].GetOverlayPos()
  426. legImage = wx.ImageFromBitmap(legendBitmap)
  427. # not so nice result, can we handle the transparency otherwise?
  428. legImage.ConvertAlphaToMask()
  429. im.Paste(legImage, x, y)
  430. if im.GetSize() != animWinSize[i]:
  431. im.Rescale(*animWinSize[i])
  432. image.Paste(im, *animWinPos[i])
  433. # paste decorations
  434. for decoration in decorations:
  435. # add image
  436. x = decoration['pos'][0] / 100. * size[0]
  437. y = decoration['pos'][1] / 100. * size[1]
  438. if decoration['name'] == 'image':
  439. decImage = wx.Image(decoration['file'])
  440. elif decoration['name'] == 'time':
  441. timeLabel = timeLabels[frameIndex]
  442. if timeLabel[1]: # interval
  443. text = _("%(from)s %(dash)s %(to)s") % \
  444. {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
  445. else:
  446. if self.temporalManager.GetTemporalType() == TemporalType.ABSOLUTE:
  447. text = timeLabel[0]
  448. else:
  449. text = _("%(start)s %(unit)s") % \
  450. {'start': timeLabel[0], 'unit': timeLabel[2]}
  451. decImage = RenderText(text, decoration['font']).ConvertToImage()
  452. elif decoration['name'] == 'text':
  453. text = decoration['text']
  454. decImage = RenderText(text, decoration['font']).ConvertToImage()
  455. image.Paste(decImage, x, y)
  456. images.append(image)
  457. del busy
  458. # export
  459. pilImages = [WxImageToPil(image) for image in images]
  460. busy = wx.BusyInfo(message=_("Exporting animation, please wait..."),
  461. parent=self.frame)
  462. wx.Yield()
  463. try:
  464. if exportInfo['method'] == 'sequence':
  465. filename = os.path.join(exportInfo['directory'],
  466. exportInfo['prefix'] + '.' + exportInfo['format'].lower())
  467. writeIms(filename=filename, images=pilImages)
  468. elif exportInfo['method'] == 'gif':
  469. writeGif(filename=exportInfo['file'], images=pilImages,
  470. duration=self.timeTick / float(1000), repeat=True)
  471. elif exportInfo['method'] == 'swf':
  472. writeSwf(filename=exportInfo['file'], images=pilImages,
  473. duration=self.timeTick / float(1000), repeat=True)
  474. elif exportInfo['method'] == 'avi':
  475. writeAvi(filename=exportInfo['file'], images=pilImages,
  476. duration=self.timeTick / float(1000),
  477. encoding=exportInfo['encoding'],
  478. inputOptions=exportInfo['options'])
  479. except Exception as e:
  480. del busy
  481. GError(parent=self.frame, message=str(e))
  482. return
  483. del busy