Editor.icl 22.5 KB
Newer Older
1 2 3
implementation module C2.Apps.ShipAdventure.Editor

import iTasks
Bas Lijnse's avatar
Bas Lijnse committed
4 5 6
import iTasks.Extensions.SVG.SVGEditor
import iTasks.Extensions.JSONFile
import iTasks.Internal.IWorld
7
import iTasks.UI.Layout, iTasks.UI.Definition
Bas Lijnse's avatar
Bas Lijnse committed
8
import System.Directory, System.File, System.FilePath
9 10 11 12 13 14 15 16 17
import Text
import StdArray, StdFile
import StdMisc
import C2.Framework.MapEnvironment
import C2.Apps.ShipAdventure.Types
import C2.Apps.ShipAdventure.Images
import qualified Data.Map as DM
import qualified Data.IntMap.Strict as DIS
import qualified Data.Set as DS
Mart Lubbers's avatar
Mart Lubbers committed
18 19 20 21 22

import Graphics.Scalable.Image => qualified grid
import Graphics.Scalable.Types
//from Graphics.Scalable import normalFontDef, above, class margin(..), instance margin (Span,Span), px
//from Graphics.Scalable import :: ImageOffset, :: Host(..)
Bas Lijnse's avatar
Bas Lijnse committed
23 24 25

derive JSEncode Map2D, Section, Maybe, Coord2D, Borders, Border, IntMap, Device, DeviceType, DeviceKind, CableType, Map
derive JSEncode Network, Cable, Object, ObjectType, MapAction, SectionStatus, Dir
26 27 28 29 30 31 32 33 34

shipEditorTabs		:: Task ()
shipEditorTabs		= allTasks [ viewLayout          <<@ Title "View Ship"
                               , editLayout          <<@ Title "Edit Ship"
                               , editSectionContents <<@ Title "Edit Section Contents"
                               , manageDevices       <<@ Title "Manage Devices"
                               , manageCables        <<@ Title "Manage Cables"
                               , exportShip          <<@ Title "Export"
                               , importShip          <<@ Title "Import"
Bas Lijnse's avatar
Bas Lijnse committed
35
                               ] <<@ ArrangeWithTabs False @! ()
36 37 38 39 40 41 42 43 44 45 46 47 48

exportShip :: Task ()
exportShip
  =                enterInformation "Enter file name" []
  >>= \fileName -> get (myInventoryMap |*| myNetwork |*| myCables |*| myDevices |*| maps2DShare)
  >>- \data     -> exportJSONFile (fileName +++ ".map") data
  >>|              viewInformation "Success!" [] "File exported"
  >>|              exportShip @! ()

importShip :: Task ()
importShip
  =                getMapNames
  >>= \mapNames -> enterChoice "Select file" [] mapNames
Bas Lijnse's avatar
Bas Lijnse committed
49 50
  >>*              [ OnAction (Action "Import") (hasValue doImport)
                   , OnAction (Action "Refresh list") (always importShip)
51 52 53 54 55
                   ]
  where
  doImport :: !String -> Task ()
  doImport mapName
    =            getMap mapName
Haye Böhm's avatar
Fix CI  
Haye Böhm committed
56
    >>- \data -> set data (myInventoryMap >*< myNetwork >*< myCables >*< myDevices >*< maps2DShare)
57 58 59 60
    >>|          viewInformation "Ship imported" [] "Ship imported"
    >>|          importShip @! ()

getMap :: !String -> Task (!(!(!(!MySectionInventoryMap, !Network), !IntMap Cable), !IntMap Device), !Maps2D)
Bas Lijnse's avatar
Bas Lijnse committed
61
getMap mapName = get applicationDirectory >>- \curDir -> accWorldError (getMap` mapName curDir) id
62
  where
Bas Lijnse's avatar
Bas Lijnse committed
63 64 65
  getMap` :: !String !String !*World -> *(!MaybeError String (!(!(!(!MySectionInventoryMap, !Network), !IntMap Cable), !IntMap Device), !Maps2D), !*World)
  getMap` mapName dir world
    # (mjson, world) = readFile (dir </> (mapName +++ ".map")) world
66 67
    = case mjson of
        Ok json   -> case fromJSON (fromString json) of
Bas Lijnse's avatar
Bas Lijnse committed
68 69 70
                       Just gg  -> (Ok gg, world)
                       _        -> err ("Failed to deserialize JSON: " +++ json) world
        Error msg -> err (toString msg) world
71
    where
Bas Lijnse's avatar
Bas Lijnse committed
72
    err msg world
73
      # msg = "Failed to load map file " +++ mapName
Bas Lijnse's avatar
Bas Lijnse committed
74
      = (Error msg, world)
75 76

getMapNames :: Task [String]
Bas Lijnse's avatar
Bas Lijnse committed
77
getMapNames = get applicationDirectory >>- \curDir -> accWorldError (getMapNames curDir) id
78
  where
Bas Lijnse's avatar
Bas Lijnse committed
79 80 81
  getMapNames :: !String !*World -> *(!MaybeError String [String], !*World)
  getMapNames dir world
    # (mfs, world)  = readDirectory dir world
82 83
    = case mfs of
        Ok fs
Bas Lijnse's avatar
Bas Lijnse committed
84
          = (Ok (map dropExtension (filter (\x -> noDots x && onlyMaps x) fs)), world)
85 86
        Error _
          # msg = "Failed to read Tonic directory"
Bas Lijnse's avatar
Bas Lijnse committed
87
          = (Error  msg, world)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  onlyMaps :: !String -> Bool
  onlyMaps str = endsWith ".map" str

  noDots :: !String -> Bool
  noDots str = not (str.[0] == '.')

mapFont p			= normalFontDef "Verdana" p
mapTitleFontSize    =: 10.0

/********************************************************************************************************************
*
* Viewing the layout of a map
*
********************************************************************************************************************/
viewLayout = updateMapStatus EditMode @! ()

Haye Böhm's avatar
Fix CI  
Haye Böhm committed
104
sharedMapAction :: SDSLens () (MapAction SectionStatus) (MapAction SectionStatus)
105 106
sharedMapAction = sharedStore "sharedMapAction" (FocusOnMap 0)	// start at the top-level (all maps)

Haye Böhm's avatar
Fix CI  
Haye Böhm committed
107 108
sharedEditShip :: SDSParallel () (Maps2D,MapAction SectionStatus) (Maps2D,MapAction SectionStatus)
sharedEditShip = maps2DShare >*< sharedMapAction
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

manageDevices :: Task ()
manageDevices
  #! cos = [ChooseFromGrid deviceToEditDevice]
  #! eos = [EnterAs editDeviceToDevice]
  #! vos = [ViewAs deviceToEditDevice]
  #! uos = [UpdateAs deviceToEditDevice (const editDeviceToDevice)]
  = intMapCrudWith "Devices" cos eos vos uos (\dev -> dev.Device.deviceId) myDevices @! ()

deviceToEditDevice :: !Device -> EditDevice
deviceToEditDevice dev
  = { EditDevice
    | description = dev.Device.description
    , deviceType  = deviceTypeToEditDeviceType dev.Device.deviceType
    , deviceId    = dev.Device.deviceId
    , inCables    = dev.Device.inCables
    , outCables   = dev.Device.outCables
    }
  where
  deviceTypeToEditDeviceType :: !DeviceType -> EditDeviceType
  deviceTypeToEditDeviceType devType
    = { EditDeviceType
      | kind     = devType.DeviceType.kind
      , requires = 'DM'.toList devType.DeviceType.requires
      , produces = 'DM'.toList devType.DeviceType.produces
      }


editDeviceToDevice :: !EditDevice -> Device
editDeviceToDevice dev
  = { Device
    | description = dev.EditDevice.description
    , deviceType  = editDeviceTypeToDeviceType dev.EditDevice.deviceType
    , deviceId    = dev.EditDevice.deviceId
    , inCables    = dev.EditDevice.inCables
    , outCables   = dev.EditDevice.outCables
    }
  where
  editDeviceTypeToDeviceType :: !EditDeviceType -> DeviceType
  editDeviceTypeToDeviceType devType
    = { DeviceType
      | kind     = devType.EditDeviceType.kind
      , requires = 'DM'.fromList devType.EditDeviceType.requires
      , produces = 'DM'.fromList devType.EditDeviceType.produces
      }

:: EditDeviceType =
  { kind     ::  !DeviceKind
  , requires ::  ![(!CableType, !Capacity)]
  , produces ::  ![(!CableType, !Capacity)]
  }

:: EditDevice =
  { description ::  !String
  , deviceType  ::  !EditDeviceType
  , deviceId    ::  !DeviceId
  , inCables    ::  ![CableId]
  , outCables   ::  ![CableId]
  }
derive class iTask EditDeviceType, EditDevice

manageCables :: Task ()
manageCables = intMapCrudWith "Cables" [ChooseFromGrid id] [] [] [] (\cable -> cable.Cable.cableId) myCables @! ()

Haye Böhm's avatar
Fix CI  
Haye Böhm committed
173
intMapCrud :: !String !(r -> Int) !(SDSLens () (IntMap r) (IntMap r)) -> Task r | iTask r
174 175 176 177 178 179 180
intMapCrud descr mkId share = crud descr 'DIS'.elems (putItem mkId) (delItem mkId) share
  where
  putItem :: !(r -> Int) !r !(IntMap r) -> IntMap r
  putItem mkId item allItems = 'DIS'.put (mkId item) item allItems
  delItem :: !(r -> Int) !r !(IntMap r) -> IntMap r
  delItem mkId item allItems = 'DIS'.del (mkId item) allItems

Haye Böhm's avatar
Fix CI  
Haye Böhm committed
181
intMapCrudWith :: !String ![ChoiceOption r] [EnterOption r] [ViewOption r] [UpdateOption r r] !(r -> Int) !(SDSLens () (IntMap r) (IntMap r)) -> Task r | iTask r
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
intMapCrudWith descr cos eos vos uos mkId share = crudWith descr cos eos vos uos 'DIS'.elems (putItem mkId) (delItem mkId) share
  where
  putItem :: !(r -> Int) !r !(IntMap r) -> IntMap r
  putItem mkId item allItems = 'DIS'.put (mkId item) item allItems
  delItem :: !(r -> Int) !r !(IntMap r) -> IntMap r
  delItem mkId item allItems = 'DIS'.del (mkId item) allItems

graphicalMapEditor :: Task ()
graphicalMapEditor
  = updateSharedInformation (Title "Graphical map editor")
      [UpdateUsing id (const fst) imageEditor]
      (sharedEditShip >*| (myInventoryMap |*| myNetwork |*| myDevices)) @! ()
	  @! ()
where
	imageEditor = fromSVGEditor
		{ initView       = fst
198
		, renderImage    = \((_, act), ((inventoryMap, network), allDevices)) (ms2d, _) _ ->
Mart Lubbers's avatar
Mart Lubbers committed
199 200
		//TODO	above [] [] [margin (px 5.0, px zero) (editLayoutImage act allDevices network inventoryMap idx m2d) \\ m2d <- ms2d & idx <- [0..]] NoHost
			above [] [] Nothing [] [margin (px 5.0, px zero) (editLayoutImage act allDevices network inventoryMap idx m2d) \\ m2d <- ms2d & idx <- [0..]] NoHost
201 202 203 204 205 206 207 208 209 210 211
		, updView        = \m v -> fst m
		, updModel       = \(_,data) newClSt -> (newClSt,data)
		}

editLayout :: Task ()
editLayout
  = allTasks [ graphicalMapEditor
             , updateSharedInformation (Title "Edit map dimensions") [UpdateAs toMapsForm fromMapsForm] maps2DShare @! ()
             , updateSharedInformation (Title "Edit map") [UpdateAs toMapActionForm fromMapActionForm] sharedEditShip @! ()
             , (watch maps2DShare
               -&&- enterChoiceWithShared (Title "Quick borders") [] (mapRead (\ship -> [mapId \\ {Map2D | mapId} <- ship]) maps2DShare)
Bas Lijnse's avatar
Bas Lijnse committed
212 213
               >>* [ OnAction (Action "Add outer borders"    ) (hasValue (uncurry (editOuterBorders Wall)))
                   , OnAction (Action "Remove outer borders" ) (hasValue (uncurry (editOuterBorders Open)))
214 215
                   ]
               ) @! ()
Mart Lubbers's avatar
Mart Lubbers committed
216 217
             ] @! ()//TODO <<@ ApplyLayout layout @! ()
/*
218
where
Bas Lijnse's avatar
Bas Lijnse committed
219
	layout = idLayout
220 221 222 223 224 225 226
	layout = sequenceLayouts
		[ insertSubAt [1] (ui UIContainer) // Group the 'tool' tasks
		, moveSubAt[2] [1,0]
		, moveSubAt[2] [1,1]
		, moveSubAt[2] [1,2]
		, arrangeWithSideBar 1 LeftSide 350 False //Move the 'tool' tasks to the side
		]
Bas Lijnse's avatar
Bas Lijnse committed
227
*/
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

editOuterBorders :: !Border !Maps2D !MapID -> Task ()
editOuterBorders border ship mapID = case getMap2DIndex mapID ship of
                                         Just idx = set (updMap2D idx (editBorders border) ship) maps2DShare @! ()
                                         _        = return ()
    where
    editBorders :: !Border !Map2D -> Map2D
    editBorders border m2d=:{map2D = rows=:[cols : _]}
      #! lastRowIdx = length rows - 1
      #! lastColIdx = length cols - 1
      #! m2d = foldr (\colIdx -> updSection {row = 0,          col = colIdx}     (editBorder N border)) m2d [0..lastColIdx]
      #! m2d = foldr (\rowIdx -> updSection {row = rowIdx,     col = 0}          (editBorder W border)) m2d [0..lastRowIdx]
      #! m2d = foldr (\colIdx -> updSection {row = lastRowIdx, col = colIdx}     (editBorder S border)) m2d [0..lastColIdx]
      #! m2d = foldr (\rowIdx -> updSection {row = rowIdx,     col = lastColIdx} (editBorder E border)) m2d [0..lastRowIdx]
      = m2d
    editBorders _ m2d = m2d
244

245 246
    editBorder :: !Dir !Border !Section -> Section
    editBorder dir border s = {Section | s & borders = edit dir border s.Section.borders}
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    edit :: !Dir !Border !Borders -> Borders
    edit N border b = {Borders | b & n = border}
    edit E border b = {Borders | b & e = border}
    edit W border b = {Borders | b & w = border}
    edit S border b = {Borders | b & s = border}

editSectionContents :: Task ()
editSectionContents
  = allTasks [ graphicalMapEditor
             , withSelectedSection (
                 \mid c2d -> updateSharedInformation (Title (mkDesc mid c2d "Inventory")) [UpdateAs fromInv toInv] (sdsFocus (mid, c2d) inventoryInSectionShare)
               )
             , withSelectedSection (
                 \mid c2d -> let focusedShare = sdsFocus (mid, c2d) devicesInSectionShare
                             in  updateSectionEditor (mkDesc mid c2d "Devices")
                                   [ChooseFromCheckGroup (\d -> d.Device.description)]
Haye Böhm's avatar
Fix CI  
Haye Böhm committed
264
                                   (mapRead mrf (myDevices |*< focusedShare)) focusedShare
265 266 267 268 269
               )
             , withSelectedSection (
                 \mid c2d -> let focusedShare = sdsFocus (mid, c2d) cablesInSectionShare
                             in  updateSectionEditor (mkDesc mid c2d "Cables")
                                   [ChooseFromCheckGroup (\d -> d.Cable.description)]
Haye Böhm's avatar
Fix CI  
Haye Böhm committed
270
                                   (mapRead ('DIS'.elems o fst) (myCables |*< focusedShare)) focusedShare
271
               )
Mart Lubbers's avatar
Mart Lubbers committed
272
             ] @! () //TODO <<@ ApplyLayout layout @! ()
273
  where
Haye Böhm's avatar
Fix CI  
Haye Böhm committed
274
  updateSectionEditor :: !String ![ChoiceOption a] (sds1 () [a] [a]) (sds2 () [a] [a]) -> Task [a] | iTask a & RWShared sds1 & RWShared sds2
275 276 277 278 279 280 281 282 283 284 285
  updateSectionEditor d updOpts listShare focusedShare
	= editSharedMultipleChoiceWithShared (Title d) updOpts listShare focusedShare

  withSelectedSection :: !(Int Coord2D -> Task a) -> Task () | iTask a
  withSelectedSection f
    = whileUnchanged sharedMapAction
        (\editLayout -> case editLayout of
           FocusOnSection (mid, c2d) = f mid c2d @! ()
           _                         = viewInformation (Title "Please select section") [] "Please select section" @! ()
        )

Bas Lijnse's avatar
Bas Lijnse committed
286
/*
Mart Lubbers's avatar
Mart Lubbers committed
287
  layout = idLayout
288 289 290 291 292 293 294
  layout = sequenceLayouts
		[insertSubAt [1] (uia UIContainer (directionAttr Horizontal))
		,moveSubAt [2] [1,0]
		,moveSubAt [2] [1,1]
		,moveSubAt [2] [1,2]
		,arrangeWithSideBar 1 BottomSide 250 False
		]
Bas Lijnse's avatar
Bas Lijnse committed
295
*/
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

  mkDesc :: !Int !Coord2D !String -> String
  mkDesc mid c2d str = str +++ " in section " +++ toString c2d +++ " on deck " +++ toString mid

  mrf :: !(!IntMap Device, a) -> [Device]
  mrf (ds, _) = filter (\d -> not (isDetector d.Device.deviceType.DeviceType.kind)) ('DIS'.elems ds)

  fromInv :: !(IntMap MyObject) -> [ObjectType]
  fromInv inv = map (\item -> item.objType) ('DIS'.elems inv)

  toInv :: a ![ObjectType] -> IntMap MyObject
  toInv _ tfd = 'DIS'.fromList (map (\(idx, item) -> (idx, { Object | objId = idx, objType = item})) (zip2 [0..] tfd))

:: EditMaps =
  { noOfMaps    :: !Int  // the number of maps    (> 0)
  , noOfRows    :: !Int  // the number of rows    (> 0)
  , noOfColumns :: !Int  // the number of columns (> 0)
  , mapWidth    :: !Real // the width of the map  (> 0.0)
  , mapHeight   :: !Real // the height of the map (> 0.0)
  , doorWidth   :: !Real // the width of drawn doors
  , doorDepth   :: !Real // the depth of drawn doors
  }
:: EditForm =
Bas Lijnse's avatar
Bas Lijnse committed
319 320
  { map2DIndex  :: !Maps2DIndex            // the index position of this map within Maps2D
  , mapId       :: !MapID                  // the identification of the map containing this section
321
  , newMapId    :: !MapID                  // new identification of this map
Bas Lijnse's avatar
Bas Lijnse committed
322
  , section     :: !Coord2D                // the unique identification of the section
323
  , sectionName :: !Maybe String           // descriptive name, need not be unique
Bas Lijnse's avatar
Bas Lijnse committed
324 325
  , up          :: !Bool                   // you can go down (except bottom floor)
  , down        :: !Bool                   // you can go up   (except top floor)
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
  , outline     :: !Maybe Shape2D
  }
derive class iTask EditMaps, EditForm

toMapsForm :: !Maps2D -> EditMaps
toMapsForm []
  = { EditMaps | noOfMaps    = 1
	           , noOfRows    = 1
	           , noOfColumns = 1
	           , mapWidth    = fst initMap2DSize
	           , mapHeight   = snd initMap2DSize
	           , doorWidth   = fst initDoors2DSize
	           , doorDepth   = snd initDoors2DSize
	  }
toMapsForm maps
  = { EditMaps | noOfMaps    = length maps
               , noOfRows    = rows
               , noOfColumns = columns
               , mapWidth    = w
               , mapHeight   = h
               , doorWidth   = dw
               , doorDepth   = dh
      }
where
	(columns,rows) = dimension (hd maps)
	(w, h )        = (hd maps).size2D
	(dw,dh)        = (hd maps).doors2D

fromMapsForm :: !Maps2D !EditMaps -> Maps2D
fromMapsForm maps mapE=:{EditMaps | noOfMaps, noOfRows, noOfColumns, mapWidth, mapHeight, doorWidth, doorDepth}
  = updateNoOfMaps noOfMaps (map updateMap2D maps)
where
	newNoOfMaps		= max 1 noOfMaps
	newNoOfRows		= max 1 noOfRows
	newNoOfCols		= max 1 noOfColumns
	newMapWidth		= max 10.0 mapWidth
	newMapHeight	= max 10.0 mapHeight
	newColWidth		= newMapWidth  / toReal newNoOfCols
	newRowHeight	= newMapHeight / toReal newNoOfRows
	newDoorWidth	= minList [newColWidth,newRowHeight,max 1.0 doorWidth]
	newDoorDepth	= minList [newColWidth,newRowHeight,max 1.0 doorDepth]
	updateMap2D map	= {Map2D | map & map2D   = updateSections newNoOfRows newNoOfCols map.Map2D.map2D
	                               , size2D  = (newMapWidth, newMapHeight)
	                               , doors2D = (newDoorWidth,newDoorDepth)
                                 , shape2D = Just [(dx*newMapWidth,dy*newMapHeight) \\ (dx,dy) <- frigate_outline]
	                  }

	updateSections :: !Int !Int ![[Section]] -> [[Section]]
	updateSections newNoOfRows newNoOfColumns sections
						= widen (heighten sections)
	where
		curNoOfRows		= length sections
		curNoOfColumns	= length (hd sections)
379

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	    heighten :: ![[Section]] -> [[Section]]
		heighten sects	= if (newNoOfRows < curNoOfRows) (take newNoOfRows sects)
						 (if (newNoOfRows > curNoOfRows) (sects ++ [  [  initSection
						                                              \\ col_no <- [0..curNoOfColumns-1]
						                                              ]
						                                           \\ row_no <- [curNoOfRows .. newNoOfRows-1]
						                                           ])
						                                 sects)
	    widen :: ![[Section]] -> [[Section]]
		widen    sects	= if (newNoOfColumns < curNoOfColumns) (map (take newNoOfColumns) sects)
						 (if (newNoOfColumns > curNoOfColumns) [  row ++ [  initSection
						                                                 \\ col_no <- [curNoOfColumns..newNoOfColumns-1]
						                                                 ]
						                                       \\ row <- sects & row_no <- [0..]
						                                       ]
						                                       sects)
396

397 398 399 400 401 402 403 404 405 406 407 408 409 410
	updateNoOfMaps :: !Int !Maps2D -> Maps2D
	updateNoOfMaps newNoOfMaps maps
	| newNoOfMaps <= 0	= maps
	| newNoOfMaps < curNoOfMaps
						= updMap2D topfloor (updSections noUpStairs) (take newNoOfMaps maps)
	| newNoOfMaps > curNoOfMaps
						= maps ++ [initMap2D dim mapsize doorsize ("new map " +++ toString no) \\ no <- [curNoOfMaps+1 .. newNoOfMaps]]
	| otherwise			= maps
	where
		curNoOfMaps		= length maps
		topfloor		= newNoOfMaps-1
		(dim,mapsize,doorsize)
						= if (isEmpty maps) ((1,1),initMap2DSize,initDoors2DSize)
						     (let map = hd maps in (dimension map,map.Map2D.size2D,map.Map2D.doors2D))
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
		noUpStairs :: !Section -> Section
		noUpStairs s=:{Section | hops}
						= {Section | s & hops = filter (\(idx,_) -> idx <= topfloor) hops}

toMapActionForm :: !(!Maps2D, !MapAction SectionStatus) -> EditForm
toMapActionForm ([], _) = defaultEditForm
toMapActionForm (maps, FocusOnMap idx)
  = toMapActionForm (maps, FocusOnSection (idx, zero))
toMapActionForm (maps, FocusOnSection c3d=:(0, {col = 0, row = 0}))
  = case getSectionFromMap c3d maps of
      Just section = editFormFromSection maps c3d section
      _            = defaultEditForm
toMapActionForm (maps, FocusOnSection (idx, c2d))
  = case getMap2D idx maps of
      Nothing = toMapActionForm (maps, FocusOnSection (0, zero))
      Just map2D
        = case getSection c2d map2D of
            Just section = editFormFromSection maps (idx, c2d) section
            Nothing      = toMapActionForm (maps, FocusOnSection (idx, zero))
toMapActionForm (maps, _) = toMapActionForm (maps, FocusOnSection (0, zero))

editFormFromSection maps (idx, c2d) {Section | sectionName, hops}
  # mapID       = fromJust (getMapID idx maps)
  # bottomFloor = length maps - 1
Bas Lijnse's avatar
Bas Lijnse committed
436 437
  = { EditForm | map2DIndex  = idx
               , mapId       = mapID
438
               , newMapId    = mapID
Bas Lijnse's avatar
Bas Lijnse committed
439
               , section     = c2d
440
               , sectionName = if (sectionName == "") Nothing (Just sectionName)
Bas Lijnse's avatar
Bas Lijnse committed
441 442
               , up          = (isMember (idx-1, c2d) hops)
               , down        = (isMember (idx+1, c2d) hops)
443 444 445
               , outline     = Nothing
               }

Bas Lijnse's avatar
Bas Lijnse committed
446 447
defaultEditForm = { EditForm | map2DIndex  = 0
                             , mapId       = "ERROR"
448
                             , newMapId    = "ERROR"
Bas Lijnse's avatar
Bas Lijnse committed
449
                             , section     = {col = 0, row = 0}
450
                             , sectionName = Nothing
Bas Lijnse's avatar
Bas Lijnse committed
451 452
                             , up          = False
                             , down        = False
453 454 455 456 457 458
                             , outline     = Nothing
                             }


fromMapActionForm :: !(!Maps2D, !MapAction SectionStatus) !EditForm -> (!Maps2D, !MapAction SectionStatus)
//fromMapActionForm m v = m
Bas Lijnse's avatar
Bas Lijnse committed
459
fromMapActionForm (maps,edit) sectionE=:{EditForm | map2DIndex = idx,section=c,newMapId,up,down}
460 461
  = (updMap2D idx ((updateMapID newMapId) o (updSection c (updateSection (idx,c) sectionE))) (updHops (idx,c) up down maps),updateSelection (idx,c) edit)
where
Bas Lijnse's avatar
Bas Lijnse committed
462
	new_hops	= if up [(idx-1,c)] [] ++ if down [(idx+1,c)] []
463

Bas Lijnse's avatar
Bas Lijnse committed
464
	updHops :: !Coord3D !Bool !Bool !Maps2D -> Maps2D
465 466 467 468 469 470 471 472 473 474 475 476
	updHops source=:(idx,c) up down maps
	  = case getMap2D idx maps of
	  	  Just map = case getSection c map of
	  	               Just {Section | hops=old_hops}
                         # deleted_hops = removeMembers old_hops new_hops
	  	                 # added_hops   = removeMembers new_hops old_hops
	  	                 = foldl (removeHop source) (foldl (addHop source) maps added_hops) deleted_hops
	  	               _ = maps
	  	  nope = maps
	where
		removeHop c maps (idx,c`) = updMap2D idx (updSection c` (\s=:{Section | hops} -> {Section | s & hops = removeMember c hops})) maps
		addHop c maps (idx,c`) = updMap2D idx (updSection c` (\s=:{Section | hops} -> {Section | s & hops = [c:hops]})) maps
477

478 479
	updateMapID :: !MapID !Map2D -> Map2D
	updateMapID newId map = {Map2D | map & mapId = newId}
480

481 482 483
	updateSection :: !Coord3D !EditForm !Section -> Section
	updateSection (idx,c) {EditForm | sectionName,up,down} s
		= {Section | s & sectionName=fromMaybe "" sectionName,hops = new_hops}
484

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
	updateSelection :: !Coord3D !(MapAction s) -> MapAction s
	updateSelection c3d (FocusOnMap     _)	= FocusOnSection c3d
	updateSelection c3d (FocusOnSection _)	= FocusOnSection c3d
	updateSelection _   action				= action
fromMapActionForm x _ = x

initMap2DSize		=: (100.0, 100.0)
initDoors2DSize     =: ( 10.0,   3.0)
initMap2D (cols,rows) mapsize=:(w,h) doorsize id
					= {Map2D   | mapId       = id
					           , map2D       = [[initSection \\ _ <- [1..cols]] \\ _ <- [1..rows]]
					           , size2D      = mapsize
					           , doors2D     = doorsize
					           , shape2D     = Just [(dx*w,dy*h) \\ (dx,dy) <- frigate_outline]
					  }
initSection    		= {Section | sectionName = ""
					           , borders     = initBorders
					           , hops        = []
					   }
Mart Lubbers's avatar
Mart Lubbers committed
504
initBorders			= {Borders|n=Open,e=Open,s=Open,w=Open}
505 506 507 508
frigate_outline		=: [(0.0,0.5)] ++ port ++ [(1.0,0.5)] ++ starboard
where
	port			= [(0.006,0.048),(0.107,0.01),(0.179,0.0),(0.684,0.0),(0.719,0.01),(0.752,0.029),(0.787,0.067),(0.829,0.106),(0.852,0.135),(0.898,0.212),(0.926,0.279),(0.999,0.462)]
	starboard		= [(dx,1.0-dy) \\ (dx,dy) <- reverse port]