controller.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. w, h = self.mapwindows[i].GetClientSize()
  271. regions = anim.GetRegions(w, h)
  272. self.animations[i].SetFrames([HashCmds(cmdList, region)
  273. for cmdList, region in zip(anim.cmdMatrix, regions)])
  274. self.animations[i].SetActive(True)
  275. else:
  276. for i in range(len(self.animations)):
  277. if i not in activeIndices:
  278. self.animations[i].SetActive(False)
  279. continue
  280. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  281. w, h = self.mapwindows[i].GetClientSize()
  282. regions = anim.GetRegions(w, h)
  283. identifiers = sampleCmdMatrixAndCreateNames(anim.cmdMatrix,
  284. mapNamesDict[anim.firstStdsNameType[0]],
  285. regions)
  286. self.animations[i].SetFrames(identifiers)
  287. self.animations[i].SetActive(True)
  288. def _updateWindows(self, activeIndices):
  289. # add or remove window
  290. for windowIndex in range(len(self.animations)):
  291. if not self.frame.IsWindowShown(windowIndex) and windowIndex in activeIndices:
  292. self.frame.AddWindow(windowIndex)
  293. elif self.frame.IsWindowShown(windowIndex) and windowIndex not in activeIndices:
  294. self.frame.RemoveWindow(windowIndex)
  295. def _updateBitmapData(self):
  296. # unload previous data
  297. self.bitmapProvider.Unload()
  298. # load new data
  299. for animData in self.animationData:
  300. if animData.viewMode == '2d':
  301. self._set2DData(animData)
  302. else:
  303. self._load3DData(animData)
  304. self._loadLegend(animData)
  305. color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
  306. self.bitmapProvider.Load(nprocs=getCpuCount(), bgcolor=color)
  307. # clear pools
  308. self.bitmapPool.Clear()
  309. self.mapFilesPool.Clear()
  310. def _set2DData(self, animationData):
  311. opacities = [layer.opacity for layer in animationData.layerList if layer.active]
  312. w, h = self.mapwindows[animationData.GetWindowIndex()].GetClientSize()
  313. regions = animationData.GetRegions(w, h)
  314. self.bitmapProvider.SetCmds(animationData.cmdMatrix, opacities, regions)
  315. def _load3DData(self, animationData):
  316. nviz = animationData.GetNvizCommands()
  317. self.bitmapProvider.SetCmds3D(nviz['commands'], nviz['region'])
  318. def _loadLegend(self, animationData):
  319. if animationData.legendCmd:
  320. try:
  321. bitmap = self.bitmapProvider.LoadOverlay(animationData.legendCmd)
  322. try:
  323. from PIL import Image
  324. for param in animationData.legendCmd:
  325. if param.startswith('at'):
  326. b, t, l, r = param.split('=')[1].split(',')
  327. x, y = float(l) / 100., 1 - float(t) / 100.
  328. break
  329. except ImportError:
  330. x, y = 0, 0
  331. self.mapwindows[animationData.windowIndex].SetOverlay(bitmap, x, y)
  332. except GException:
  333. GError(message=_("Failed to display legend."))
  334. else:
  335. self.mapwindows[animationData.windowIndex].ClearOverlay()
  336. def EvaluateInput(self, animationData):
  337. stds = 0
  338. maps = 0
  339. mapCount = set()
  340. tempManager = None
  341. windowIndex = []
  342. for anim in animationData:
  343. for layer in anim.layerList:
  344. if layer.active and hasattr(layer, 'maps'):
  345. if layer.mapType in ('strds', 'stvds', 'str3ds'):
  346. stds += 1
  347. else:
  348. maps += 1
  349. mapCount.add(len(layer.maps))
  350. windowIndex.append(anim.windowIndex)
  351. if maps and stds:
  352. temporalMode = TemporalMode.NONTEMPORAL
  353. elif maps:
  354. temporalMode = TemporalMode.NONTEMPORAL
  355. elif stds:
  356. temporalMode = TemporalMode.TEMPORAL
  357. else:
  358. temporalMode = None
  359. if temporalMode == TemporalMode.NONTEMPORAL:
  360. if len(mapCount) > 1:
  361. raise GException(_("Inconsistent number of maps, please check input data."))
  362. elif temporalMode == TemporalMode.TEMPORAL:
  363. tempManager = TemporalManager()
  364. # these raise GException:
  365. for anim in animationData:
  366. tempManager.AddTimeSeries(*anim.firstStdsNameType)
  367. message = tempManager.EvaluateInputData()
  368. if message:
  369. GMessage(parent=self.frame, message=message)
  370. return temporalMode, tempManager
  371. def Reload(self):
  372. self.EndAnimation()
  373. color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
  374. self.bitmapProvider.Load(nprocs=getCpuCount(), bgcolor=color, force=True)
  375. self.EndAnimation()
  376. def Export(self):
  377. if not self.animationData:
  378. GMessage(parent=self.frame, message=_("No animation to export."))
  379. return
  380. if 'export' in self._dialogs:
  381. self._dialogs['export'].Show()
  382. self._dialogs['export'].Raise()
  383. else:
  384. dlg = ExportDialog(self.frame, temporal=self.temporalMode,
  385. timeTick=self.timeTick)
  386. dlg.CenterOnParent()
  387. dlg.doExport.connect(self._export)
  388. self._dialogs['export'] = dlg
  389. dlg.Show()
  390. def _export(self, exportInfo, decorations):
  391. size = self.frame.animationPanel.GetSize()
  392. if self.temporalMode == TemporalMode.TEMPORAL:
  393. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  394. frameCount = len(timeLabels)
  395. else:
  396. frameCount = self.animationData[0].mapCount # should be the same for all
  397. animWinSize = []
  398. animWinPos = []
  399. animWinIndex = []
  400. legends = [anim.legendCmd for anim in self.animationData]
  401. # determine position and sizes of bitmaps
  402. for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
  403. if anim.IsActive():
  404. pos = win.GetPosition()
  405. animWinPos.append(pos)
  406. animWinSize.append(win.GetSize())
  407. animWinIndex.append(i)
  408. images = []
  409. busy = wx.BusyInfo(message=_("Preparing export, please wait..."), parent=self.frame)
  410. wx.Yield()
  411. for frameIndex in range(frameCount):
  412. image = wx.EmptyImage(*size)
  413. image.Replace(0, 0, 0, 255, 255, 255)
  414. # collect bitmaps of all windows and paste them into the one
  415. for i in animWinIndex:
  416. frameId = self.animations[i].GetFrame(frameIndex)
  417. if not UserSettings.Get(group='animation', key='temporal',
  418. subkey=['nodata', 'enable']):
  419. if frameId is not None:
  420. bitmap = self.bitmapProvider.GetBitmap(frameId)
  421. else:
  422. bitmap = self.bitmapProvider.GetBitmap(frameId)
  423. im = wx.ImageFromBitmap(bitmap)
  424. # add legend if used
  425. legend = legends[i]
  426. if legend:
  427. legendBitmap = self.bitmapProvider.LoadOverlay(legend)
  428. x, y = self.mapwindows[i].GetOverlayPos()
  429. legImage = wx.ImageFromBitmap(legendBitmap)
  430. # not so nice result, can we handle the transparency otherwise?
  431. legImage.ConvertAlphaToMask()
  432. im.Paste(legImage, x, y)
  433. if im.GetSize() != animWinSize[i]:
  434. im.Rescale(*animWinSize[i])
  435. image.Paste(im, *animWinPos[i])
  436. # paste decorations
  437. for decoration in decorations:
  438. # add image
  439. x = decoration['pos'][0] / 100. * size[0]
  440. y = decoration['pos'][1] / 100. * size[1]
  441. if decoration['name'] == 'image':
  442. decImage = wx.Image(decoration['file'])
  443. elif decoration['name'] == 'time':
  444. timeLabel = timeLabels[frameIndex]
  445. if timeLabel[1]: # interval
  446. text = _("%(from)s %(dash)s %(to)s") % \
  447. {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
  448. else:
  449. if self.temporalManager.GetTemporalType() == TemporalType.ABSOLUTE:
  450. text = timeLabel[0]
  451. else:
  452. text = _("%(start)s %(unit)s") % \
  453. {'start': timeLabel[0], 'unit': timeLabel[2]}
  454. decImage = RenderText(text, decoration['font']).ConvertToImage()
  455. elif decoration['name'] == 'text':
  456. text = decoration['text']
  457. decImage = RenderText(text, decoration['font']).ConvertToImage()
  458. image.Paste(decImage, x, y)
  459. images.append(image)
  460. del busy
  461. # export
  462. pilImages = [WxImageToPil(image) for image in images]
  463. busy = wx.BusyInfo(message=_("Exporting animation, please wait..."),
  464. parent=self.frame)
  465. wx.Yield()
  466. try:
  467. if exportInfo['method'] == 'sequence':
  468. filename = os.path.join(exportInfo['directory'],
  469. exportInfo['prefix'] + '.' + exportInfo['format'].lower())
  470. writeIms(filename=filename, images=pilImages)
  471. elif exportInfo['method'] == 'gif':
  472. writeGif(filename=exportInfo['file'], images=pilImages,
  473. duration=self.timeTick / float(1000), repeat=True)
  474. elif exportInfo['method'] == 'swf':
  475. writeSwf(filename=exportInfo['file'], images=pilImages,
  476. duration=self.timeTick / float(1000), repeat=True)
  477. elif exportInfo['method'] == 'avi':
  478. writeAvi(filename=exportInfo['file'], images=pilImages,
  479. duration=self.timeTick / float(1000),
  480. encoding=exportInfo['encoding'],
  481. inputOptions=exportInfo['options'])
  482. except Exception as e:
  483. del busy
  484. GError(parent=self.frame, message=str(e))
  485. return
  486. del busy