-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathView.hs
1645 lines (1506 loc) · 57.5 KB
/
View.hs
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE OverloadedStrings #-}
-- |
-- SPDX-License-Identifier: BSD-3-Clause
--
-- Code for drawing the TUI.
module Swarm.TUI.View (
drawUI,
drawTPS,
-- * Dialog box
drawDialog,
chooseCursor,
-- * Key hint menu
drawKeyMenu,
drawModalMenu,
drawKeyCmd,
-- * World
drawWorldPane,
-- * Robot panel
drawRobotPanel,
drawItem,
renderDutyCycle,
-- * Info panel
drawInfoPanel,
explainFocusedItem,
-- * REPL
drawREPL,
) where
import Brick hiding (Direction, Location)
import Brick.Focus
import Brick.Forms
import Brick.Widgets.Border (
hBorder,
hBorderWithLabel,
joinableBorder,
vBorder,
)
import Brick.Widgets.Center (center, centerLayer, hCenter)
import Brick.Widgets.Dialog
import Brick.Widgets.Edit (getEditContents, renderEditor)
import Brick.Widgets.List qualified as BL
import Brick.Widgets.Table qualified as BT
import Control.Lens as Lens hiding (Const, from)
import Control.Monad (guard)
import Data.Array (range)
import Data.Bits (shiftL, shiftR, (.&.))
import Data.Foldable (toList)
import Data.Foldable qualified as F
import Data.Functor (($>))
import Data.IntMap qualified as IM
import Data.List (intersperse)
import Data.List qualified as L
import Data.List.Extra (enumerate)
import Data.List.NonEmpty (NonEmpty (..))
import Data.List.NonEmpty qualified as NE
import Data.List.Split (chunksOf)
import Data.Map qualified as M
import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe, maybeToList)
import Data.Semigroup (sconcat)
import Data.Sequence qualified as Seq
import Data.Set qualified as Set (toList)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Time (NominalDiffTime, defaultTimeLocale, formatTime)
import Linear
import Network.Wai.Handler.Warp (Port)
import Numeric (showFFloat)
import Swarm.Constant
import Swarm.Game.CESK (CESK (..))
import Swarm.Game.Device (commandCost, commandsForDeviceCaps, enabledCommands, getMap, ingredients)
import Swarm.Game.Display
import Swarm.Game.Entity as E
import Swarm.Game.Ingredients
import Swarm.Game.Land
import Swarm.Game.Location
import Swarm.Game.Recipe
import Swarm.Game.Robot
import Swarm.Game.Robot.Activity
import Swarm.Game.Robot.Concrete
import Swarm.Game.Scenario (
scenarioAuthor,
scenarioCreative,
scenarioDescription,
scenarioKnown,
scenarioLandscape,
scenarioMetadata,
scenarioName,
scenarioObjectives,
scenarioOperation,
scenarioSeed,
scenarioTerrainAndEntities,
)
import Swarm.Game.Scenario.Scoring.Best
import Swarm.Game.Scenario.Scoring.CodeSize
import Swarm.Game.Scenario.Scoring.ConcreteMetrics
import Swarm.Game.Scenario.Scoring.GenericMetrics
import Swarm.Game.Scenario.Status
import Swarm.Game.Scenario.Topography.Center
import Swarm.Game.Scenario.Topography.Structure.Recognition (automatons)
import Swarm.Game.Scenario.Topography.Structure.Recognition.Type
import Swarm.Game.ScenarioInfo (
ScenarioItem (..),
scenarioItemName,
)
import Swarm.Game.State
import Swarm.Game.State.Landscape
import Swarm.Game.State.Robot
import Swarm.Game.State.Runtime
import Swarm.Game.State.Substate
import Swarm.Game.Tick (TickNumber (..), addTicks)
import Swarm.Game.Universe
import Swarm.Game.World.Coords
import Swarm.Game.World.Gen (Seed)
import Swarm.Language.Capability (Capability (..), constCaps)
import Swarm.Language.Pretty (prettyText, prettyTextLine, prettyTextWidth)
import Swarm.Language.Syntax
import Swarm.Language.Typecheck (inferConst)
import Swarm.Log
import Swarm.TUI.Border
import Swarm.TUI.Controller (ticksPerFrameCap)
import Swarm.TUI.Controller.EventHandlers (allEventHandlers, mainEventHandlers, replEventHandlers, robotEventHandlers, worldEventHandlers)
import Swarm.TUI.Controller.Util (hasDebugCapability)
import Swarm.TUI.Editor.Model
import Swarm.TUI.Editor.View qualified as EV
import Swarm.TUI.Inventory.Sorting (renderSortMethod)
import Swarm.TUI.Launch.Model
import Swarm.TUI.Launch.View
import Swarm.TUI.Model
import Swarm.TUI.Model.Event qualified as SE
import Swarm.TUI.Model.Goal (goalsContent, hasAnythingToShow)
import Swarm.TUI.Model.KeyBindings (handlerNameKeysDescription)
import Swarm.TUI.Model.Repl
import Swarm.TUI.Model.UI
import Swarm.TUI.Panel
import Swarm.TUI.View.Achievement
import Swarm.TUI.View.Attribute.Attr
import Swarm.TUI.View.CellDisplay
import Swarm.TUI.View.Logo
import Swarm.TUI.View.Objective qualified as GR
import Swarm.TUI.View.Popup
import Swarm.TUI.View.Structure qualified as SR
import Swarm.TUI.View.Util as VU
import Swarm.Util
import Swarm.Util.UnitInterval
import Swarm.Util.WindowedCounter qualified as WC
import Swarm.Version (NewReleaseFailure (..))
import System.Clock (TimeSpec (..))
import Text.Printf
import Text.Wrap
import Witch (into)
-- | The main entry point for drawing the entire UI.
drawUI :: AppState -> [Widget Name]
drawUI s = drawPopups s : mainLayers
where
mainLayers
| s ^. uiState . uiPlaying = drawGameUI s
| otherwise = drawMenuUI s
drawMenuUI :: AppState -> [Widget Name]
drawMenuUI s = case s ^. uiState . uiMenu of
-- We should never reach the NoMenu case if uiPlaying is false; we would have
-- quit the app instead. But just in case, we display the main menu anyway.
NoMenu -> [drawMainMenuUI s (mainMenu NewGame)]
MainMenu l -> [drawMainMenuUI s l]
NewGameMenu stk -> drawNewGameMenuUI stk $ s ^. uiState . uiLaunchConfig
AchievementsMenu l -> [drawAchievementsMenuUI s l]
MessagesMenu -> [drawMainMessages s]
AboutMenu -> [drawAboutMenuUI (s ^. runtimeState . appData . at "about")]
drawMainMessages :: AppState -> Widget Name
drawMainMessages s = renderDialog dial . padBottom Max . scrollList $ drawLogs ls
where
ls = reverse $ s ^. runtimeState . eventLog . notificationsContent
dial = dialog (Just $ str "Messages") Nothing maxModalWindowWidth
scrollList = withVScrollBars OnRight . vBox
drawLogs = map (drawLogEntry True)
drawMainMenuUI :: AppState -> BL.List Name MainMenuEntry -> Widget Name
drawMainMenuUI s l =
vBox . catMaybes $
[ drawLogo <$> logo
, hCenter . padTopBottom 2 <$> newVersionWidget version
, Just . centerLayer . vLimit 6 . hLimit 20 $
BL.renderList (const (hCenter . drawMainMenuEntry s)) True l
]
where
logo = s ^. runtimeState . appData . at "logo"
version = s ^. runtimeState . upstreamRelease
newVersionWidget :: Either NewReleaseFailure String -> Maybe (Widget n)
newVersionWidget = \case
Right ver -> Just . txt $ "New version " <> T.pack ver <> " is available!"
Left (OnDevelopmentBranch _b) -> Just . txt $ "Good luck developing!"
Left (FailedReleaseQuery _f) -> Nothing
Left (NoMainUpstreamRelease _fails) -> Nothing
Left (OldUpstreamRelease _up _my) -> Nothing
-- | When launching a game, a modal prompt may appear on another layer
-- to input seed and/or a script to run.
drawNewGameMenuUI ::
NonEmpty (BL.List Name ScenarioItem) ->
LaunchOptions ->
[Widget Name]
drawNewGameMenuUI (l :| ls) launchOptions = case displayedFor of
Nothing -> pure mainWidget
Just _ -> drawLaunchConfigPanel launchOptions <> pure mainWidget
where
displayedFor = launchOptions ^. controls . isDisplayedFor
mainWidget =
vBox
[ padLeftRight 20
. centerLayer
$ hBox
[ vBox
[ withAttr boldAttr . txt $ breadcrumbs ls
, txt " "
, vLimit 20
. hLimit 35
. withLeftPaddedVScrollBars
. padLeft (Pad 1)
. padTop (Pad 1)
. BL.renderList (const $ padRight Max . drawScenarioItem) True
$ l
]
, padLeft (Pad 5) (maybe (txt "") (drawDescription . snd) (BL.listSelectedElement l))
]
, launchOptionsMessage
]
launchOptionsMessage = case (displayedFor, snd <$> BL.listSelectedElement l) of
(Nothing, Just (SISingle _)) -> hCenter $ txt "Press 'o' for launch options, or 'Enter' to launch with defaults"
_ -> txt " "
drawScenarioItem (SISingle (s, si)) = padRight (Pad 1) (drawStatusInfo s si) <+> txt (s ^. scenarioMetadata . scenarioName)
drawScenarioItem (SICollection nm _) = padRight (Pad 1) (withAttr boldAttr $ txt " > ") <+> txt nm
drawStatusInfo s si = case si ^. scenarioStatus of
NotStarted -> txt " ○ "
Played _initialScript (Metric Attempted _) _ -> case s ^. scenarioOperation . scenarioObjectives of
[] -> withAttr cyanAttr $ txt " ◉ "
_ -> withAttr yellowAttr $ txt " ◎ "
Played _initialScript (Metric Completed _) _ -> withAttr greenAttr $ txt " ● "
describeStatus :: ScenarioStatus -> Widget n
describeStatus = \case
NotStarted -> withAttr cyanAttr $ txt "not started"
Played _initialScript pm _best -> describeProgress pm
breadcrumbs :: [BL.List Name ScenarioItem] -> Text
breadcrumbs =
T.intercalate " > "
. ("Scenarios" :)
. reverse
. mapMaybe (fmap (scenarioItemName . snd) . BL.listSelectedElement)
drawDescription :: ScenarioItem -> Widget Name
drawDescription (SICollection _ _) = txtWrap " "
drawDescription (SISingle (s, si)) =
vBox
[ drawMarkdown (nonBlank (s ^. scenarioOperation . scenarioDescription))
, hCenter . padTop (Pad 1) . vLimit 6 $ hLimitPercent 60 worldPeek
, padTop (Pad 1) table
]
where
vc = determineStaticViewCenter (s ^. scenarioLandscape) worldTuples
worldTuples = buildWorldTuples $ s ^. scenarioLandscape
theWorlds =
genMultiWorld worldTuples $
fromMaybe 0 $
s ^. scenarioLandscape . scenarioSeed
entIsKnown =
getEntityIsKnown $
EntityKnowledgeDependencies
{ isCreativeMode = s ^. scenarioOperation . scenarioCreative
, globallyKnownEntities = s ^. scenarioLandscape . scenarioKnown
, theFocusedRobot = Nothing
}
tm = s ^. scenarioLandscape . scenarioTerrainAndEntities . terrainMap
ri = RenderingInput theWorlds entIsKnown tm
renderCoord = renderDisplay . displayLocRaw (WorldOverdraw False mempty) ri []
worldPeek = worldWidget renderCoord vc
firstRow =
( withAttr dimAttr $ txt "Author:"
, withAttr dimAttr . txt <$> s ^. scenarioMetadata . scenarioAuthor
)
secondRow =
( txt "last:"
, Just $ describeStatus $ si ^. scenarioStatus
)
padTopLeft = padTop (Pad 1) . padLeft (Pad 1)
tableRows =
map (map padTopLeft . pairToList) $
mapMaybe sequenceA $
firstRow : secondRow : makeBestScoreRows (si ^. scenarioStatus)
table =
BT.renderTable
. BT.surroundingBorder False
. BT.rowBorders False
. BT.columnBorders False
. BT.alignRight 0
. BT.alignLeft 1
. BT.table
$ tableRows
nonBlank "" = " "
nonBlank t = t
pairToList :: (a, a) -> [a]
pairToList (x, y) = [x, y]
describeProgress :: ProgressMetric -> Widget n
describeProgress (Metric p (ProgressStats _startedAt (AttemptMetrics (DurationMetrics e t) maybeCodeMetrics))) = case p of
Attempted ->
withAttr yellowAttr . vBox $
[ txt "in progress"
, txt $ parens $ T.unwords ["played for", formatTimeDiff e]
]
Completed ->
withAttr greenAttr . vBox $
[ txt $ T.unwords ["completed in", formatTimeDiff e]
, txt . (" " <>) . parens $ T.unwords [T.pack $ drawTime t True, "ticks"]
]
<> maybeToList (sizeDisplay <$> maybeCodeMetrics)
where
sizeDisplay (ScenarioCodeMetrics myCharCount myAstSize) =
withAttr greenAttr $
vBox $
map
txt
[ T.unwords
[ "Code:"
, T.pack $ show myCharCount
, "chars"
]
, (" " <>) $
parens $
T.unwords
[ T.pack $ show myAstSize
, "AST nodes"
]
]
where
formatTimeDiff :: NominalDiffTime -> Text
formatTimeDiff = T.pack . formatTime defaultTimeLocale "%hh %Mm %Ss"
-- | If there are multiple different games that each are \"best\"
-- by different criteria, display them all separately, labeled
-- by which criteria they were best in.
--
-- On the other hand, if all of the different \"best\" criteria are for the
-- same game, consolidate them all into one entry and don't bother
-- labelling the criteria.
makeBestScoreRows ::
ScenarioStatus ->
[(Widget n1, Maybe (Widget n2))]
makeBestScoreRows scenarioStat =
maybe [] makeBestRows getBests
where
getBests = case scenarioStat of
NotStarted -> Nothing
Played _initialScript _ best -> Just best
makeBestRows b = map (makeBestRow hasMultiple) groups
where
groups = getBestGroups b
hasMultiple = length groups > 1
makeBestRow hasDistinctByCriteria (b, criteria) =
( hLimit (maxLeftColumnWidth + 2) $
vBox $
[ padLeft Max $ txt "best:"
]
<> elaboratedCriteria
, Just $ describeProgress b
)
where
maxLeftColumnWidth = maximum (map (T.length . describeCriteria) enumerate)
mkCriteriaRow =
withAttr dimAttr
. padLeft Max
. txt
. mconcat
. pairToList
. fmap (\x -> T.singleton $ if x == 0 then ',' else ' ')
elaboratedCriteria =
if hasDistinctByCriteria
then
map mkCriteriaRow
. flip zip [(0 :: Int) ..]
. NE.toList
. NE.reverse
. NE.map describeCriteria
$ criteria
else []
drawMainMenuEntry :: AppState -> MainMenuEntry -> Widget Name
drawMainMenuEntry s = \case
NewGame -> txt "New game"
Tutorial -> txt "Tutorial"
Achievements -> txt "Achievements"
About -> txt "About"
Messages -> highlightMessages $ txt "Messages"
Quit -> txt "Quit"
where
highlightMessages =
if s ^. runtimeState . eventLog . notificationsCount > 0
then withAttr notifAttr
else id
drawAboutMenuUI :: Maybe Text -> Widget Name
drawAboutMenuUI Nothing = centerLayer $ txt "About swarm!"
drawAboutMenuUI (Just t) = centerLayer . vBox . map (hCenter . txt . nonblank) $ T.lines t
where
-- Turn blank lines into a space so they will take up vertical space as widgets
nonblank "" = " "
nonblank s = s
-- | Draw the main game UI. Generates a list of widgets, where each
-- represents a layer. Right now we just generate two layers: the
-- main layer and a layer for a floating dialog that can be on top.
drawGameUI :: AppState -> [Widget Name]
drawGameUI s =
[ joinBorders $ drawDialog s
, joinBorders $
hBox
[ hLimitPercent 25 $
vBox
[ vLimitPercent 50
$ panel
highlightAttr
fr
(FocusablePanel RobotPanel)
( plainBorder
& bottomLabels . centerLabel
.~ fmap
(txt . (" Search: " <>) . (<> " "))
(s ^. uiState . uiGameplay . uiInventory . uiInventorySearch)
)
$ drawRobotPanel s
, panel
highlightAttr
fr
(FocusablePanel InfoPanel)
plainBorder
$ drawInfoPanel s
, hCenter
. clickable (FocusablePanel WorldEditorPanel)
. EV.drawWorldEditor fr
$ s ^. uiState
]
, vBox rightPanel
]
]
where
addCursorPos = bottomLabels . leftLabel ?~ padLeftRight 1 widg
where
widg = case s ^. uiState . uiGameplay . uiWorldCursor of
Nothing -> str $ renderCoordsString $ s ^. gameState . robotInfo . viewCenter
Just coord -> clickable WorldPositionIndicator $ drawWorldCursorInfo (s ^. uiState . uiGameplay . uiWorldEditor . worldOverdraw) (s ^. gameState) coord
-- Add clock display in top right of the world view if focused robot
-- has a clock equipped
addClock = topLabels . rightLabel ?~ padLeftRight 1 (drawClockDisplay (s ^. uiState . uiGameplay . uiTiming . lgTicksPerSecond) $ s ^. gameState)
fr = s ^. uiState . uiGameplay . uiFocusRing
showREPL = s ^. uiState . uiGameplay . uiShowREPL
rightPanel = if showREPL then worldPanel ++ replPanel else worldPanel ++ minimizedREPL
minimizedREPL = case focusGetCurrent fr of
(Just (FocusablePanel REPLPanel)) -> [separateBorders $ clickable (FocusablePanel REPLPanel) (forceAttr highlightAttr hBorder)]
_ -> [separateBorders $ clickable (FocusablePanel REPLPanel) hBorder]
worldPanel =
[ panel
highlightAttr
fr
(FocusablePanel WorldPanel)
( plainBorder
& bottomLabels . rightLabel ?~ padLeftRight 1 (drawTPS s)
& topLabels . leftLabel ?~ drawModalMenu s
& addCursorPos
& addClock
)
(drawWorldPane (s ^. uiState . uiGameplay) (s ^. gameState))
, drawKeyMenu s
]
replPanel =
[ clickable (FocusablePanel REPLPanel) $
panel
highlightAttr
fr
(FocusablePanel REPLPanel)
( plainBorder
& topLabels . rightLabel .~ (drawType <$> (s ^. uiState . uiGameplay . uiREPL . replType))
)
( vLimit replHeight
. padBottom Max
. padLeft (Pad 1)
$ drawREPL s
)
]
renderCoordsString :: Cosmic Location -> String
renderCoordsString (Cosmic sw coords) =
unwords $ VU.locationToString coords : suffix
where
suffix = case sw of
DefaultRootSubworld -> []
SubworldName swName -> ["in", T.unpack swName]
drawWorldCursorInfo :: WorldOverdraw -> GameState -> Cosmic Coords -> Widget Name
drawWorldCursorInfo worldEditor g cCoords =
case getStatic g coords of
Just s -> renderDisplay $ displayStatic s
Nothing -> hBox $ tileMemberWidgets ++ [coordsWidget]
where
Cosmic _ coords = cCoords
coordsWidget = str $ renderCoordsString $ fmap coordsToLoc cCoords
tileMembers = terrain : mapMaybe merge [entity, robot]
tileMemberWidgets =
map (padRight $ Pad 1)
. concat
. reverse
. zipWith f tileMembers
$ ["at", "on", "with"]
where
f cell preposition = [renderDisplay cell, txt preposition]
ri =
RenderingInput
(g ^. landscape . multiWorld)
(getEntityIsKnown $ mkEntityKnowledge g)
(g ^. landscape . terrainAndEntities . terrainMap)
terrain = displayTerrainCell worldEditor ri cCoords
entity = displayEntityCell worldEditor ri cCoords
robot = displayRobotCell g cCoords
merge = fmap sconcat . NE.nonEmpty . filter (not . (^. invisible))
-- | Format the clock display to be shown in the upper right of the
-- world panel.
drawClockDisplay :: Int -> GameState -> Widget n
drawClockDisplay lgTPS gs = hBox . intersperse (txt " ") $ catMaybes [clockWidget, pauseWidget]
where
clockWidget = maybeDrawTime (gs ^. temporal . ticks) (gs ^. temporal . paused || lgTPS < 3) gs
pauseWidget = guard (gs ^. temporal . paused) $> txt "(PAUSED)"
-- | Check whether the currently focused robot (if any) has a clock
-- device equipped.
clockEquipped :: GameState -> Bool
clockEquipped gs = case focusedRobot gs of
Nothing -> False
Just r
| countByName "clock" (r ^. equippedDevices) > 0 -> True
| otherwise -> False
-- | Format a ticks count as a hexadecimal clock.
drawTime :: TickNumber -> Bool -> String
drawTime (TickNumber t) showTicks =
mconcat $
intersperse
":"
[ printf "%x" (t `shiftR` 20)
, printf "%02x" ((t `shiftR` 12) .&. ((1 `shiftL` 8) - 1))
, printf "%02x" ((t `shiftR` 4) .&. ((1 `shiftL` 8) - 1))
]
++ if showTicks then [".", printf "%x" (t .&. ((1 `shiftL` 4) - 1))] else []
-- | Return a possible time display, if the currently focused robot
-- has a clock device equipped. The first argument is the number
-- of ticks (e.g. 943 = 0x3af), and the second argument indicates
-- whether the time should be shown down to single-tick resolution
-- (e.g. 0:00:3a.f) or not (e.g. 0:00:3a).
maybeDrawTime :: TickNumber -> Bool -> GameState -> Maybe (Widget n)
maybeDrawTime t showTicks gs = guard (clockEquipped gs) $> str (drawTime t showTicks)
-- | Draw info about the current number of ticks per second.
drawTPS :: AppState -> Widget Name
drawTPS s = hBox (tpsInfo : rateInfo)
where
tpsInfo
| l >= 0 = hBox [str (show n), txt " ", tpsIndicator s, txt (number n "tick"), txt " / s"]
-- \| l >= 0 = hBox [str (show n), txt " ", txt (number n "tick"), txt " / s"]
| otherwise = hBox [txt "1 tick / ", str (show n), txt " s"]
rateInfo
| s ^. uiState . uiGameplay . uiTiming . uiShowFPS =
[ txt " ("
, (if tpf >= fromIntegral ticksPerFrameCap then withAttr redAttr else id)
(str (printf "%0.1f" tpf))
, txt " tpf, "
, str (printf "%0.1f" (s ^. uiState . uiGameplay . uiTiming . uiFPS))
, txt " fps)"
]
| otherwise = []
tpf = s ^. uiState . uiGameplay . uiTiming . uiTPF
l = s ^. uiState . uiGameplay . uiTiming . lgTicksPerSecond
n = 2 ^ abs l
tpsIndicator :: AppState -> Widget Name
tpsIndicator s =
hBox [txt "(", str $ show tps, txt ") "]
where
-- = str (show $ round tps )
-- \| (tps / target) < 0.9 = str (show $ round tps )
-- \| otherwise = emptyWidget
tpf = s ^. uiState . uiGameplay . uiTiming . uiTPF
fps = s ^. uiState . uiGameplay . uiTiming . uiFPS
tps = tpf * fps
-- l = s ^. uiState . uiGameplay . uiTiming . lgTicksPerSecond
-- target = 2 ^^ l
-- | The height of the REPL box. Perhaps in the future this should be
-- configurable.
replHeight :: Int
replHeight = 10
-- | Hide the cursor when a modal is set
chooseCursor :: AppState -> [CursorLocation n] -> Maybe (CursorLocation n)
chooseCursor s locs = case s ^. uiState . uiGameplay . uiModal of
Nothing -> showFirstCursor s locs
Just _ -> Nothing
-- | Draw a dialog window, if one should be displayed right now.
drawDialog :: AppState -> Widget Name
drawDialog s = case s ^. uiState . uiGameplay . uiModal of
Just (Modal mt d) -> renderDialog d $ case mt of
GoalModal -> drawModal s mt
_ -> maybeScroll ModalViewport $ drawModal s mt
Nothing -> emptyWidget
-- | Draw one of the various types of modal dialog.
drawModal :: AppState -> ModalType -> Widget Name
drawModal s = \case
HelpModal -> helpWidget (s ^. gameState . randomness . seed) (s ^. runtimeState . webPort) (s ^. keyEventHandling)
RobotsModal -> robotsListWidget s
RecipesModal -> availableListWidget (s ^. gameState) RecipeList
CommandsModal -> commandsListWidget (s ^. gameState)
MessagesModal -> availableListWidget (s ^. gameState) MessageList
StructuresModal -> SR.renderStructuresDisplay (s ^. gameState) (s ^. uiState . uiGameplay . uiStructure)
ScenarioEndModal outcome ->
padBottom (Pad 1) $
vBox $
map
(hCenter . txt)
content
where
content = case outcome of
WinModal -> ["Congratulations!"]
LoseModal ->
[ "Condolences!"
, "This scenario is no longer winnable."
]
DescriptionModal e -> descriptionWidget s e
QuitModal -> padBottom (Pad 1) $ hCenter $ txt (quitMsg (s ^. uiState . uiMenu))
GoalModal ->
GR.renderGoalsDisplay (s ^. uiState . uiGameplay . uiGoal) $
view (scenarioOperation . scenarioDescription) . fst <$> s ^. uiState . uiGameplay . scenarioRef
KeepPlayingModal ->
padLeftRight 1 $
displayParagraphs $
pure
"Have fun! Hit Ctrl-Q whenever you're ready to proceed to the next challenge or return to the menu."
TerrainPaletteModal -> EV.drawTerrainSelector s
EntityPaletteModal -> EV.drawEntityPaintSelector s
-- | Render the percentage of ticks that this robot was active.
-- This indicator can take some time to "warm up" and stabilize
-- due to the sliding window.
--
-- == Use of previous tick
-- The 'Swarm.Game.Step.gameTick' function runs all robots, then increments the current tick.
-- So at the time we are rendering a frame, the current tick will always be
-- strictly greater than any ticks stored in the 'WC.WindowedCounter' for any robot;
-- hence 'WC.getOccupancy' will never be @1@ if we use the current tick directly as
-- obtained from the 'ticks' function.
-- So we "rewind" it to the previous tick for the purpose of this display.
renderDutyCycle :: GameState -> Robot -> Widget Name
renderDutyCycle gs robot =
withAttr dutyCycleAttr . str . flip (showFFloat (Just 1)) "%" $ dutyCyclePercentage
where
curTicks = gs ^. temporal . ticks
window = robot ^. activityCounts . activityWindow
-- Rewind to previous tick
latestRobotTick = addTicks (-1) curTicks
dutyCycleRatio = WC.getOccupancy latestRobotTick window
dutyCycleAttr = safeIndex dutyCycleRatio meterAttributeNames
dutyCyclePercentage :: Double
dutyCyclePercentage = 100 * getValue dutyCycleRatio
robotsListWidget :: AppState -> Widget Name
robotsListWidget s = hCenter table
where
table =
BT.renderTable
. BT.columnBorders False
. BT.setDefaultColAlignment BT.AlignCenter
-- Inventory count is right aligned
. BT.alignRight 4
. BT.table
$ map (padLeftRight 1) <$> (headers : robotsTable)
headings =
[ "Name"
, "Age"
, "Pos"
, "Items"
, "Status"
, "Actns"
, "Cmds"
, "Cycles"
, "Activity"
, "Log"
]
headers = withAttr robotAttr . txt <$> applyWhen cheat ("ID" :) headings
robotsTable = mkRobotRow <$> robots
mkRobotRow robot =
applyWhen cheat (idWidget :) cells
where
cells =
[ nameWidget
, str ageStr
, locWidget
, padRight (Pad 1) (str $ show rInvCount)
, statusWidget
, str $ show $ robot ^. activityCounts . tangibleCommandCount
, -- TODO(#1341): May want to expose the details of this histogram in
-- a per-robot pop-up
str . show . sum . M.elems $ robot ^. activityCounts . commandsHistogram
, str $ show $ robot ^. activityCounts . lifetimeStepCount
, renderDutyCycle (s ^. gameState) robot
, txt rLog
]
idWidget = str $ show $ robot ^. robotID
nameWidget =
hBox
[ renderDisplay (robot ^. robotDisplay)
, highlightSystem . txt $ " " <> robot ^. robotName
]
highlightSystem = if robot ^. systemRobot then withAttr highlightAttr else id
ageStr
| age < 60 = show age <> "sec"
| age < 3600 = show (age `div` 60) <> "min"
| age < 3600 * 24 = show (age `div` 3600) <> "hour"
| otherwise = show (age `div` 3600 * 24) <> "day"
where
TimeSpec createdAtSec _ = robot ^. robotCreatedAt
TimeSpec nowSec _ = s ^. uiState . uiGameplay . uiTiming . lastFrameTime
age = nowSec - createdAtSec
rInvCount = sum $ map fst . E.elems $ robot ^. robotEntity . entityInventory
rLog
| robot ^. robotLogUpdated = "x"
| otherwise = " "
locWidget = hBox [worldCell, str $ " " <> locStr]
where
rCoords = fmap locToCoords rLoc
rLoc = robot ^. robotLocation
worldCell =
drawLoc
(s ^. uiState . uiGameplay)
g
rCoords
locStr = renderCoordsString rLoc
statusWidget = case robot ^. machine of
Waiting {} -> txt "waiting"
_
| isActive robot -> withAttr notifAttr $ txt "busy"
| otherwise -> withAttr greenAttr $ txt "idle"
basePos :: Point V2 Double
basePos = realToFrac <$> fromMaybe origin (g ^? baseRobot . robotLocation . planar)
-- Keep the base and non system robot (e.g. no seed)
isRelevant robot = robot ^. robotID == 0 || not (robot ^. systemRobot)
-- Keep the robot that are less than 32 unit away from the base
isNear robot = creative || distance (realToFrac <$> robot ^. robotLocation . planar) basePos < 32
robots :: [Robot]
robots =
filter (\robot -> debugging || (isRelevant robot && isNear robot))
. IM.elems
$ g ^. robotInfo . robotMap
creative = g ^. creativeMode
cheat = s ^. uiState . uiCheatMode
debugging = creative && cheat
g = s ^. gameState
helpWidget :: Seed -> Maybe Port -> KeyEventHandlingState -> Widget Name
helpWidget theSeed mport keyState =
padLeftRight 2 . vBox $ padTop (Pad 1) <$> [info, helpKeys, tips]
where
tips =
vBox
[ heading boldAttr "Have questions? Want some tips? Check out:"
, txt " - The Swarm wiki, " <+> hyperlink wikiUrl (txt wikiUrl)
, txt " - The Swarm Discord server at " <+> hyperlink swarmDiscord (txt swarmDiscord)
]
info =
vBox
[ heading boldAttr "Configuration"
, txt ("Seed: " <> into @Text (show theSeed))
, txt ("Web server port: " <> maybe "none" (into @Text . show) mport)
]
helpKeys =
vBox
[ heading boldAttr "Keybindings"
, keySection "Main (always active)" mainEventHandlers
, keySection "REPL panel" replEventHandlers
, keySection "World view panel" worldEventHandlers
, keySection "Robot inventory panel" robotEventHandlers
]
keySection name handlers =
padBottom (Pad 1) $
vBox
[ heading italicAttr name
, mkKeyTable handlers
]
mkKeyTable =
BT.renderTable
. BT.surroundingBorder False
. BT.rowBorders False
. BT.table
. map (toRow . keyHandlerToText)
heading attr = padBottom (Pad 1) . withAttr attr . txt
toRow (n, k, d) =
[ padRight (Pad 1) $ txtFilled maxN n
, padLeftRight 1 $ txtFilled maxK k
, padLeft (Pad 1) $ txtFilled maxD d
]
keyHandlerToText = handlerNameKeysDescription (keyState ^. keyConfig)
-- Get maximum width of the table columns so it all neatly aligns
txtFilled n t = padRight (Pad $ max 0 (n - textWidth t)) $ txt t
(maxN, maxK, maxD) = map3 (maximum . map textWidth) . unzip3 $ keyHandlerToText <$> allEventHandlers
map3 f (n, k, d) = (f n, f k, f d)
data NotificationList = RecipeList | MessageList
availableListWidget :: GameState -> NotificationList -> Widget Name
availableListWidget gs nl = padTop (Pad 1) $ vBox widgetList
where
widgetList = case nl of
RecipeList -> mkAvailableList gs (discovery . availableRecipes) renderRecipe
MessageList -> messagesWidget gs
renderRecipe = padLeftRight 18 . drawRecipe Nothing (fromMaybe E.empty inv)
inv = gs ^? to focusedRobot . _Just . robotInventory
mkAvailableList :: GameState -> Lens' GameState (Notifications a) -> (a -> Widget Name) -> [Widget Name]
mkAvailableList gs notifLens notifRender = map padRender news <> notifSep <> map padRender knowns
where
padRender = padBottom (Pad 1) . notifRender
count = gs ^. notifLens . notificationsCount
(news, knowns) = splitAt count (gs ^. notifLens . notificationsContent)
notifSep
| count > 0 && not (null knowns) =
[ padBottom (Pad 1) (withAttr redAttr $ hBorderWithLabel (padLeftRight 1 (txt "new↑")))
]
| otherwise = []
commandsListWidget :: GameState -> Widget Name
commandsListWidget gs =
hCenter $
vBox
[ table
, padTop (Pad 1) $ txt "For the full list of available commands see the Wiki at:"
, txt wikiCheatSheet
]
where
commands = gs ^. discovery . availableCommands . notificationsContent
table =
BT.renderTable
. BT.surroundingBorder False
. BT.columnBorders False
. BT.rowBorders False
. BT.setDefaultColAlignment BT.AlignLeft
. BT.alignRight 0
. BT.table
$ headers : commandsTable
headers =
withAttr robotAttr
<$> [ txt "command name"
, txt " : type"
, txt "Enabled by"
]
commandsTable = mkCmdRow <$> commands
mkCmdRow cmd =
map
(padTop $ Pad 1)
[ txt $ syntax $ constInfo cmd
, padRight (Pad 2) . withAttr magentaAttr . txt $ " : " <> prettyTextLine (inferConst cmd)
, listDevices cmd
]
base = gs ^? baseRobot
entsByCap = case base of
Just r ->
M.map NE.toList $
entitiesByCapability $
(r ^. equippedDevices) `union` (r ^. robotInventory)
Nothing -> mempty
listDevices cmd = vBox $ map drawLabelledEntityName providerDevices
where
providerDevices =
concatMap (flip (M.findWithDefault []) entsByCap) $
maybeToList $
constCaps cmd
-- | Generate a pop-up widget to display the description of an entity.
descriptionWidget :: AppState -> Entity -> Widget Name
descriptionWidget s e = padLeftRight 1 (explainEntry s e)
-- | Draw a widget with messages to the current robot.
messagesWidget :: GameState -> [Widget Name]
messagesWidget gs = widgetList
where
widgetList = focusNewest . map drawLogEntry' $ gs ^. messageNotifications . notificationsContent
focusNewest = if gs ^. temporal . paused then id else over _last visible
drawLogEntry' e =
withAttr (colorLogs e) $
hBox
[ fromMaybe (txt "") $ maybeDrawTime (e ^. leTime) True gs
, padLeft (Pad 2) . txt $ brackets $ e ^. leName
, padLeft (Pad 1) . txt2 $ e ^. leText
]
txt2 = txtWrapWith indent2
colorLogs :: LogEntry -> AttrName
colorLogs e = case e ^. leSource of
SystemLog -> colorSeverity (e ^. leSeverity)
RobotLog rls rid _loc -> case rls of
Said -> robotColor rid
Logged -> notifAttr
RobotError -> colorSeverity (e ^. leSeverity)
CmdStatus -> notifAttr
where
-- color each robot message with different color of the world
robotColor = indexWrapNonEmpty messageAttributeNames
colorSeverity :: Severity -> AttrName
colorSeverity = \case
Info -> infoAttr
Debug -> dimAttr
Warning -> yellowAttr
Error -> redAttr
Critical -> redAttr
-- | Draw the F-key modal menu. This is displayed in the top left world corner.
drawModalMenu :: AppState -> Widget Name
drawModalMenu s = vLimit 1 . hBox $ map (padLeftRight 1 . drawKeyCmd) globalKeyCmds
where
notificationKey :: Getter GameState (Notifications a) -> SE.MainEvent -> Text -> Maybe (KeyHighlight, Text, Text)
notificationKey notifLens key name
| null (s ^. gameState . notifLens . notificationsContent) = Nothing
| otherwise =
let highlight
| s ^. gameState . notifLens . notificationsCount > 0 = Alert
| otherwise = NoHighlight
in Just (highlight, keyM key, name)
-- Hides this key if the recognizable structure list is empty
structuresKey =
if null $ s ^. gameState . discovery . structureRecognition . automatons . originalStructureDefinitions
then Nothing
else Just (NoHighlight, keyM SE.ViewStructuresEvent, "Structures")
globalKeyCmds =
catMaybes
[ Just (NoHighlight, keyM SE.ViewHelpEvent, "Help")
, Just (NoHighlight, keyM SE.ViewRobotsEvent, "Robots")
, notificationKey (discovery . availableRecipes) SE.ViewRecipesEvent "Recipes"
, notificationKey (discovery . availableCommands) SE.ViewCommandsEvent "Commands"
, notificationKey messageNotifications SE.ViewMessagesEvent "Messages"
, structuresKey
]
keyM = VU.bindingText s . SE.Main
-- | Draw a menu explaining what key commands are available for the