public SpiralWorker(StarGenerator starGenerator, GalaxyMap map, System.Windows.Forms.TextBox textbox = null, int _starsPerArm = 1000, int _nebulaPerArm = 1000, int _Arms = 8, float _spin = 1.8f, double _armspread = 0.03d, double _nebulaspread = 0.03d, double _starsAtCenterRatio = 0.6d, double _nebulaAtCenterRatio = 0.6d, float _mapSize = 500.0f ) { StarGenerator = starGenerator; //stars = _stars; Map = map; Textbox = textbox; starsPerArm = _starsPerArm; nebulaPerArm = _nebulaPerArm; Arms = _Arms; spin = _spin; armspread = _armspread; nebulaspread = _nebulaspread; starsAtCenterRatio = _starsAtCenterRatio; nebulaAtCenterRatio = _nebulaAtCenterRatio; mapSize = _mapSize; }
public UserInterface init(StatusScreen statusScreen, StarSystem starSystem, PlayerShip ship) { this.statusScreen = statusScreen; this.ship = ship; if (ship != null) { updateShip(); } textColor = messengerStyle.normal.textColor; GetComponent <Messenger>().init(this); minimap = GetComponent <Minimap>(); if (starSystem != null) { galaxyMap = GameObject.Find("Galaxy Map").GetComponent <GalaxyMap>().init(ship.jumpController); minimap.init(starSystem, galaxyMap, ship.transform, ship.radarRange); planetDescriptor = GetComponent <StarSystemPlanetDescriptor>().init(starSystem); } else { minimap.enabled = false; GetComponent <StarSystemPlanetDescriptor>().enabled = false; } showBars = starSystem != null; gameObject.SetActive(true); showInterface = true; return(this); }
public NebulaFieldsWorker(StarGenerator starGenerator, Settings spreadContract, GalaxyMap map, System.Windows.Forms.TextBox textbox = null) { stars = new List <Star>(); StarGenerator = starGenerator; Contract = spreadContract; StarsPerPlayer = Contract.StarsPerPlayer; minDistance = Contract.minDistance; distanceBetweenSuns = Contract.distanceBetweenSuns; starsInRow = Contract.starsInRow; xAxis = Contract.xAxis; Textbox = textbox; Map = map; //used to get the IDs of the neighbouring stars neighbours.Add((-starsInRow) - 1); neighbours.Add((-starsInRow)); neighbours.Add((-starsInRow) + 1); neighbours.Add(-1); neighbours.Add(1); neighbours.Add(starsInRow - 1); neighbours.Add(starsInRow); neighbours.Add(starsInRow + 1); }
public SpreadController(StarGenerator starGenerator, Settings settings, GalaxyMap map) { Settings = settings; InitializeComponent(); StarGenerator = starGenerator; Map = map; }
public void TestMethodTravelPlanetToSolarTestMap() { var map = new GalaxyMap(); map.ReadDbData(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\global.db")); Assert.AreEqual("Beta [5 LY]", map.Navigate("Haven", "Beta", 50 * Const.SectorsPerLY).Aggregate((string)null, (s, n) => s == null ? n.ToString() : $"{s} -> {n}")); }
public void init(StarSystem starSystem, GalaxyMap galaxyMap, Transform playerShip, float radarRange) { this.starSystem = starSystem; this.galaxyMap = galaxyMap; this.playerShip = playerShip; this.radarRange = radarRange; // loadSystem(); }
/// <summary> /// Applies the connections of wormhole endpoints. /// </summary> /// <param name="connections">The connections.</param> /// <param name="map">The galaxy map.</param> private void ApplyConnections(IList <GalaxyMapConnection> connections, GalaxyMap map) { foreach (GalaxyMapConnection connection in connections) { logger.Info("Connectiong: {0}", connection); connection.ConnectWormhole(map); } }
//TODO: Thread-safe state indication of GameServer instance. public void Initialize() { CurrentInstance = this; logger.Info("Game server initialization."); logger.Debug("Referential time: {0}", GameTime.REFERENTIAL_TIME); logger.Info("Reading configuration:"); string assetsPath = GameServerConfiguration.GameServerConfig.Assets.Path; string galaxyMapName = GameServerConfiguration.GameServerConfig.Map.Name; logger.Info("Compiling scripts:"); ScriptManager scriptManager = new ScriptManager(); scriptManager.CompileScripts(".\\scripts", SCRIPT_TARGET_ASSEMBLY, new string[] { "SpaceTraffic.Core.dll", "SpaceTraffic.GameServer.exe" }); logger.Debug("CONFIG: Assets path: {0}", assetsPath); logger.Debug("CONFIG: Map name: {0}", galaxyMapName); logger.Info("Initializing Asset Manager."); this.assetManager = new AssetManager(assetsPath); this.assetManager.Initialize(); logger.Info("Initializing Persistence."); try { this.persistenceManager = new PersistenceManager(); this.persistenceManager.Initialize(); } catch (Exception ex) { logger.Fatal("Persistence initialization failed: {0}", ex.Message, ex); throw; } scriptManager.RunScript("SpaceTraffic.Scripts.Testing.TestDataGenerator"); logger.Info("Restoring game world."); this.worldManager = new WorldManager(); GalaxyMap galaxyMap = this.assetManager.LoadGalaxyMap(galaxyMapName); this.worldManager.Map = galaxyMap; // Inicializace herního světa. this.gameManager = new GameManager(this); this.gameManager.RestoreGameState(); serviceManager = new ServiceManager(); //Načíst servisy z konfigurace serviceManager.ServiceList = new List <Type>(new Type[] { typeof(AccountService), typeof(GameService), typeof(HelloWorldService) }); serviceManager.Initialize(); }
public void SpreadNebula() { GalaxyMap temporaryNebulas = new GalaxyMap(Map.Settings); foreach (var star in Map.stars) { if (star.StarNebulaType == 1) { continue; } //spread temporary nebula (StarNebulaType = 3) in a circle with a radius of 4 fields: for (int x = star.X - 4; x < star.X + 4; x++) { for (int y = star.Y - 4; y < star.Y + 4; y++) { if (x == star.X && y == star.Y) { continue; } var distance = Math.Sqrt(((star.X - x) * (star.X - x)) + ((star.Y - y) * (star.Y - y))); var probability = (1 / distance) * 30; //try to find; //Star checker = new Star(x, y, 3, this); Star checker = StarGenerator.MakeStarXY(false, x, y); checker.StarNebulaType = 3; temporaryNebulas.addStar(checker, false, false); checker.NebulaPercentage += (int)probability; } } } Random r = new Random(); //temporaryNebulas.stars.ForEach(e => Map.addStar(e,false,false)); //stars.AddRange(toAdd); foreach (var star in temporaryNebulas.stars) { if (star.NebulaPercentage < 8) { continue; } int percentage = Math.Min(star.NebulaPercentage, 90); int rand = r.Next(100); if (rand < percentage) { star.StarNebulaType = 2; Map.addStar(star, false, true); } } //this.Refresh(); }
public void TestMethodTravelTestMap() { var map = new GalaxyMap(); map.ReadDbData(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\global.db")); Assert.AreEqual("Beta [5 LY]", map.Navigate("Alpha", "Beta", 50 * Const.SectorsPerLY).Aggregate((string)null, (s, n) => s == null ? n.ToString() : $"{s} -> {n}")); Assert.AreEqual("Naphona [43 LY] -> Cyrimudai [17 LY] -> Malphukaltho [49 LY] -> Rangudra [39 LY] -> Naamadhaka [45 LY] -> Mastiless [49 LY] -> Farr [49 LY]", map.Navigate("Alpha", "Farr", 50 * Const.SectorsPerLY).Aggregate((string)null, (s, n) => s == null ? n.ToString() : $"{s} -> {n}")); }
public SpiralController(StarGenerator starGenerator, Settings settings, GalaxyMap map) { InitializeComponent(); StarGenerator = starGenerator; //stars = _stars; //DrawAreaSize = panel1.Width; readConfig2(settings); DrawAreaSize = panel1.Width; Map = map; Settings = settings; }
public void GalaxyLoadTest() { TestGalaxyMapDataStreamProvider provider = new TestGalaxyMapDataStreamProvider(".//..//..//..//..//assets"); provider.Initialize(); GalaxyMapLoader loader = new GalaxyMapLoader(); map = loader.LoadGalaxyMap("GalaxyMap", provider); Debug.Assert((map.Count > 0), "No starsystem was loaded."); Debug.Assert((map.GetStarSystemConnections("Solar System").Count > 0), "Starsystem connections cannot be loaded."); }
public PathPlannerTests() { testShip = new Spaceship(0, "TestShip"); testPath = new NavPath(); TestGalaxyMapDataStreamProvider provider = new TestGalaxyMapDataStreamProvider(".//..//..//..//..//assets"); provider.Initialize(); GalaxyMapLoader loader = new GalaxyMapLoader(); map = loader.LoadGalaxyMap("GalaxyMap", provider); Debug.Assert((map.Count > 0), "No starsystem was loaded."); }
/// <summary> /// Metoda pro nacteni seznamu starsystemu /// </summary> public void StarSystemListLoader() { GalaxyMap map = Editor.GalaxyMap; ListView view = this.GetStarSystemList(); foreach (StarSystem starSystem in map) { ListViewItem starSystemItem = new ListViewItem(); starSystemItem.Content = starSystem.Name; starSystemItem.Tag = starSystem; starSystemItem.GotFocus += new RoutedEventHandler(SetStarSystemListFocus); view.Items.Add(starSystemItem); } }
/// <summary> /// Metoda pro nacteni galaxie /// </summary> /// <param name="galaxyName">Jmeno galaxie</param> /// <returns>Mapa galaxie</returns> public static GalaxyMap LoadGalaxy(String galaxyName) { StreamDataProvider provider = new StreamDataProvider(".//Assets"); provider.Initialize(); GalaxyMapLoader loader = new GalaxyMapLoader(); GalaxyMap galaxyMap = loader.LoadGalaxyMap(galaxyName, provider); if (galaxyMap.Count == 0) { Console.WriteLine("Nezdarilo se otevrit zadny ze zadanych souboru!"); } return(galaxyMap); }
/// <summary> /// Metoda starajici se o pripravu editoru /// </summary> public static void Preload() { Log("Inicializuji editor"); Names = new Names(NAMESFILEPATH); GalaxyMap = new GalaxyMap(); dataPresenter = new DataPresenter(); //vytvorim instance vsech editoru StarSystemEditor = new StarSystemEditorEntity(); PlanetEditor = new PlanetEditorEntity(); StarEditor = new StarEditorEntity(); WormholeEditor = new WormholeEditorEntity(); CircleOrbitEditor = new CircleEditorEntity(); EllipseOrbitEditor = new EllipseEditorEntity(); StacionaryOrbitEditor = new StacionaryEditorEntity(); IsLoaded = false; Time = 0; Log("Inicializace dokoncena"); }
/// <summary> /// Metoda pro vytvoreni xml s mapou starsystemu /// </summary> /// <param name="map">Mapa pro ulozeni</param> private static void CreateGalaxyMapXml(GalaxyMap map) { FileStream fileStream = new FileStream(".\\saveddata\\maps\\" + map.MapName + ".xml", FileMode.Create); XNamespace defaultNamespace = XNamespace.Get("SpaceTrafficData"); XElement doc = new XElement( new XElement(defaultNamespace + "stdata", new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"), new XAttribute(XNamespace.Xmlns + "html", "http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd"), new XAttribute(XNamespace.Xmlns + "st", "SpaceTrafficData"), new XAttribute("version", "1.2") ) ); XElement root = new XElement("galaxy"); root.Add(new XAttribute("name", map.MapName)); XElement starSystems = new XElement("starSystems"); XElement wormholes = new XElement("wormholes"); foreach (StarSystem starSystem in map.GetStarSystems()) { XElement item = new XElement("starsystem"); item.Add(new XAttribute("name", starSystem.Name)); starSystems.Add(item); CreateStarSystemXml(starSystem); // XElement wormhole = new XElement("wormhole"); // map.GetStarSystemConnections(starSystem.Name). // foreach (WormholeEndpointDestination destination in map.GetStarSystemConnections(starSystem.Name)) // { // wormholes.Add(destination); // } // wormholes.Add(WormholesToElement(map.GetStarSystemConnections(starSystem.Name))); } root.Add(starSystems); doc.Add(root); doc.Save(fileStream); }
public GalaxyMap LoadGalaxyMap(string mapName, IGalaxyMapDataStreamProvider dataService) { using (Stream stream = dataService.GetGalaxyMapStream(mapName)) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; using (XmlReader reader = XmlReader.Create(stream, readerSettings)) { XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlNode galaxyNode = doc.GetElementsByTagName("galaxy")[0]; GalaxyMap map = new GalaxyMap(); map.MapName = galaxyNode.Attributes["name"].Value.ToString(); IList <string> starSystemNames = null; IList <GalaxyMapConnection> connections = null; foreach (XmlNode childNode in galaxyNode.ChildNodes) { switch (childNode.Name.ToLowerInvariant()) { case "starsystems": starSystemNames = childNode.ParseStarSystems(); break; case "wormholes": connections = childNode.ParseWormholes(); break; default: throw new XmlException("Unexpected childNode."); } } Debug.Assert(starSystemNames != null, "starSystemNames is null"); Debug.Assert(connections != null, "connections is null"); this.LoadStarSystems(starSystemNames, dataService, map); this.ApplyConnections(connections, map); return(map); } } }
public GalaxyMap LoadGalaxyMap(string galaxyMapName) { GalaxyMap galaxyMap = null; try { GalaxyMapLoader mapLoader = new GalaxyMapLoader(); galaxyMap = mapLoader.LoadGalaxyMap(galaxyMapName, this); galaxyMap.Lock(); } catch (XmlException ex) { throw; } catch (GalaxyMapBuildingException ex) { throw; } return(galaxyMap); }
public GalaxyMap LoadGalaxyMap(string galaxyMapName) { logger.Info("Loading map: {0}", galaxyMapName); GalaxyMap galaxyMap = null; try { GalaxyMapLoader mapLoader = new GalaxyMapLoader(); galaxyMap = mapLoader.LoadGalaxyMap(galaxyMapName, this); galaxyMap.Lock(); } catch (XmlException ex) { logger.Fatal("Map loading failed: {0}", ex.Message, ex); throw; } catch (GalaxyMapBuildingException ex) { logger.Fatal("Map building failed: {0}", ex.Message, ex); throw; } return(galaxyMap); }
/// <summary> /// Connects the wormhole in given map according to connection defined in this instance. /// </summary> /// <param name="map">The map on which this connection will be realised.</param> public void ConnectWormhole(GalaxyMap map) { WormholeEndpoint endpoint1 = GetConnectionEndpoint(map, this[0]); WormholeEndpoint endpoint2 = GetConnectionEndpoint(map, this[1]); if (endpoint1.IsConnected) { throw new GalaxyMapBuildingException( String.Format("Endpoint already connected: {0} to {1}. Connection {2} cannot be set.", endpoint1, endpoint1.Destination, this) ); } if (endpoint2.IsConnected) { throw new GalaxyMapBuildingException( String.Format("Endpoint already connected: {0} to {1}. Connection {2} cannot be set.", endpoint2, endpoint2.Destination, this) ); } endpoint1.ConnectTo(endpoint2); }
/// <summary> /// Gets the connection endpoint. /// </summary> /// <param name="map">The map.</param> /// <param name="end">The end.</param> /// <returns></returns> /// <exception cref="GalaxyMapBuildingException">If endpoint cannot be found.</exception> private WormholeEndpoint GetConnectionEndpoint(GalaxyMap map, GalaxyMapConnectionEnd end) { StarSystem starSystem = map[end.StarSystemName]; if (starSystem == null) { throw new GalaxyMapBuildingException( String.Format("Invalid connection: {0}, star system '{1}' not found.", this, end.StarSystemName) ); } WormholeEndpoint endpoint = starSystem.WormholeEndpoints[end.WormholeEndpointId]; if (endpoint == null) { throw new GalaxyMapBuildingException( String.Format("Invalid connection: {0}, wormhole endpoint '{1}' not found in star system '{2}'.", this, end.WormholeEndpointId, end.StarSystemName) ); } return(endpoint); }
/// <summary> /// Metoda pro nacteni souboru s galaxii, jeho zpracovani a pak ulozeni do pameti /// </summary> public static void LoadGalaxyFile() { prepareDataFolder(); //Log("dialog"); OpenFileDialog dlg = new OpenFileDialog(); dlg.DefaultExt = ".xml"; dlg.Filter = "GalaxyMap XML File(.xml)|*.xml"; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.IgnoreComments = true; // Open document string filename = dlg.FileName; FileStream fs = new FileStream(filename, FileMode.Open); //Editor.Log(dlg.InitialDirectory); GalaxyMap map = new GalaxyMap(); List <string> starSystemNamesList = new List <string> { }; List <string> loadList = new List <string> { }; using (XmlReader reader = XmlReader.Create(fs, readerSettings)) { XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlNode galaxyNode = doc.GetElementsByTagName("galaxy")[0]; if (galaxyNode == null) { throw new FileFormatException("This file doesn't contain galaxy map!"); } map.MapName = galaxyNode.Attributes["name"].Value.ToString(); foreach (XmlNode childNode in galaxyNode.ChildNodes) { switch (childNode.Name.ToLowerInvariant()) { case "starsystems": foreach (XmlNode starSystemNode in childNode.ChildNodes) { string starSystemFileName = starSystemNode.Attributes["name"].Value.ToString(); starSystemNamesList.Add(starSystemFileName); //Editor.Log(starSystemFileName); if (File.Exists(dlg.FileName.Replace(dlg.SafeFileName, "") + Path.DirectorySeparatorChar + starSystemFileName + ".xml")) { Editor.Log("parsing"); loadList.Add(starSystemFileName); } else { StarSystem starSystem = new StarSystem(); starSystem.Name = starSystemFileName; Star star = new Star(); star.Name = starSystemFileName; starSystem.Star = star; map.Add(starSystem); } } break; case "wormholes": //TODO: Implementation //connections = childNode.ParseWormholes(); break; default: throw new XmlException("Unexpected childNode."); } } } fs.Close(); foreach (String starSystemName in loadList) { String starSystemPath = (dlg.FileName.Replace(dlg.SafeFileName, "") + starSystemName + ".xml"); map.Add(LoadStarSystem(starSystemPath, readerSettings)); } Editor.GalaxyMap = map; } }
private static void Create_NewGame() { #region Prepare UI and get menu result ZConsoleMain.ClearScreen(); Draw_Interface(); Draw_Credits(); var loadGameFileName = MainMenu(); #endregion #region Create Galaxy, Player and all area handlers GameConfig.Reset(); Galaxy = GalaxyModel.Create(GameConfig.CurrentGalaxySizeX, GameConfig.CurrentGalaxySizeY); Player = PlayerModel.Create(); CurrentStarSystem.IsExplored = true; GalaxyMap = new GalaxyMap(GalaxyArea, GameConfig.CurrentGalaxySizeX, GameConfig.CurrentGalaxySizeY); EventLog = new EventLog(EventArea); ActionPanel = new ActionPanel(ActionArea); PlayerStats = new PlayerStats(PlayerStatsArea); BattleStats = new BattleStats(BattleStatsArea); EventLog.ClearArea(); #endregion #region Load game or show Intro Text and get Player name if (!string.IsNullOrEmpty(loadGameFileName)) { SaveLoad.LoadGame(loadGameFileName); } else { PrintIntroText(); EventLog.Print("Common_EnterYourName"); ZCursor.SetCursorVisibility(true); Player.Name = ZInput.ReadLine(2 + Lang["Common_EnterYourName"].Length, 7, 9, Color.Yellow, Color.Black, false, "Jameson"); ZCursor.SetCursorVisibility(false); } #endregion #region Prepare UI, draw galaxy, etc. Draw_Controls(true); GlobalEvent.Create(Galaxy, CurrentStarSystem); ActionPanel.ClearArea(); PlayerStats.Draw_PlayerStats(); GalaxyMap.Draw_GalaxyMap(); GalaxyMap.HighlightArea(); EventLog.Print("Galaxy_ChooseSystem"); #endregion }
/// <summary> /// Loads the star systems defined in the map. /// </summary> /// <param name="starSystems">The list of star systems.</param> /// <param name="streamProvider">Provider of map data streams.</param> /// <param name="map">The map.</param> private void LoadStarSystems(IList <string> starSystems, IGalaxyMapDataStreamProvider streamProvider, GalaxyMap map) { StarSystemLoader loader = new StarSystemLoader(); StarSystem starSystem; foreach (string starSystemName in starSystems) { starSystem = loader.LoadStarSystem(starSystemName, streamProvider); if (map.ContainsKey(starSystem.Name)) { throw new XmlException("Duplicate star system name in starsystems"); } else { map.Add(starSystem); } } }
/// <summary> /// Metoda pro vytvoreni xml souboru objektu ulozenych v pameti /// </summary> /// <param name="map">Mapa pro ulozeni</param> public static void CreateXml(GalaxyMap map) { PrepareSaveFolder(); CreateGalaxyMapXml(map); }
void LoadGalaxy(PackedScene galaxyScene) { GalaxyMap = galaxyScene.Instance() as GalaxyMap; hudRoot.AddChild(GalaxyMap); GalaxyMap.Visible = false; //Randomize galaxy map edge weights? if (simulationMode == SimulationMode.Gamma && galaxySeed != 0) { GalaxyMap.RandomizeEdgeWeights(galaxySeed); } foreach (GalaxyMapNode mapNode in GalaxyMap.Nodes) { var newSolarSystem = LoadSolarSystemIntoViewportContainer(mapNode.Name); } var startingViewportContainer = SolarSystemViewportContainersByName[GalaxyMap.StartingNode.Name]; MoveChild(startingViewportContainer, GetChildCount() - 1); //Spawn colony ships ColonyShip firstColonyShip = null; for (int i = 0; i < colonyShipScenes.Count; i++) { var newColonyShip = colonyShipScenes[i].Instance() as ColonyShip; //newColonyShip.LandingSequenceTriggered += HandleColonyShipLandingSequenceTriggered; ColonyShips.Add(newColonyShip.ShipName, newColonyShip); //Move colony ship back to origin if (newColonyShip != null) { if (newColonyShip.GetParent() != null) { newColonyShip.GetParent().RemoveChild(newColonyShip); } SolarSystemViewportContainersByName[GalaxyMap.StartingNode.Name].GetChild(0).AddChild(newColonyShip); //gameObjectsRoot.AddChild(newColonyShip); newColonyShip.CurrentSolarSystemName = GalaxyMap.StartingNode.Name; newColonyShip.GlobalPosition = Vector2.Left * 100f + Vector2.Up * 100f * i; } OnColonyShipSpawned?.Invoke(newColonyShip); if (firstColonyShip == null) { firstColonyShip = newColonyShip; } } //Set camera/info panel focus ColonyShip focusShip = null; foreach (var pair in ColonyShips) { if (pair.Key == startFocusedOnShip) { focusShip = pair.Value; } } if (focusShip == null) { GD.PrintErr("No focus ship designed in GameCore inspector panel. Choosing Nostromo by default."); focusShip = ColonyShips[ShipNames.Nostromo]; } else { shipInfoPanels.FocusShip = focusShip; } }
//similar to Ship.createSpaceStation(), but not easily generalizable public bool build2(int shipTemplateId, int _userId, int _colonyId, bool fastBuild, ref int newShipId, ref ShipBuildErrorCode errorCode, ref int errorValue) { Core core = Core.Instance; GalaxyMap galaxyMap = null; // lock colony and field Colony colony = core.colonies[_colonyId]; if (colony == null) { return(false); } if (colony.userId != _userId) { return(false); } Field field = colony.field; ShipTemplate template = core.shipTemplate[shipTemplateId]; if (!(this.checkFreeOrbit(field, _userId, colony.systemXY(), ref errorCode, ref errorValue) && this.checkGoodsAvailability(colony, template, fastBuild, ref errorCode, ref errorValue) && this.checkSpaceport(colony, ref errorCode, ref errorValue) && this.checkTechnology(template, _userId, fastBuild, ref errorCode, ref errorValue) && this.checkUniqueness(field, template, colony.systemXY(), ref errorCode, ref errorValue))) { return(false); } //Lock List <Lockable> elementsToLock = new List <Lockable>(3); elementsToLock.Add(colony); elementsToLock.Add(field); //check for transcendence //ToDo: replace 220 with a sql data field if (template.hullid == 220 && core.GalaxyMap.transcendenceRequirement == 0) { galaxyMap = core.GalaxyMap; elementsToLock.Add(galaxyMap); } if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } newShipId = (int)Core.Instance.identities.shipLock.getNext(); try { //all checks again inside of lock if (!(this.checkFreeOrbit(field, _userId, colony.systemXY(), ref errorCode, ref errorValue) && this.checkGoodsAvailability(colony, template, fastBuild, ref errorCode, ref errorValue) && this.checkSpaceport(colony, ref errorCode, ref errorValue) && this.checkTechnology(template, _userId, fastBuild, ref errorCode, ref errorValue) && this.checkUniqueness(field, template, colony.systemXY(), ref errorCode, ref errorValue))) { return(false); } //everything checked and locked //now do the work Ship newShip = buildShip(newShipId, template, field, _userId, colony, fastBuild); newShip.SetTranscension(galaxyMap); //write SQL Core.Instance.dataConnection.insertShip(newShip); Core.Instance.dataConnection.saveColonyGoods(colony); } catch (Exception ex) { SpacegameServer.Core.Core.Instance.writeExceptionToLog(ex); } finally { //release the ressources LockingManager.unlockAll(elementsToLock); } return(true); }