Inheritance: AllScopeIDImpl
        /// <summary>
        ///     Create a scene and its initial base structures.
        /// </summary>
        /// <param name="regionInfo"></param>
        /// <param name="configSource"></param>
        /// <returns></returns>
        public IScene CreateScene(ISimulationDataStore dataStore, RegionInfo regionInfo)
        {
            AgentCircuitManager circuitManager = new AgentCircuitManager();
            List<IClientNetworkServer> clientServers = UniverseModuleLoader.PickupModules<IClientNetworkServer>();
            List<IClientNetworkServer> allClientServers = new List<IClientNetworkServer>();
            foreach (IClientNetworkServer clientServer in clientServers)
            {
                clientServer.Initialize((uint)regionInfo.RegionPort, m_configSource, circuitManager);
                allClientServers.Add(clientServer);
            }

            AsyncScene scene = new AsyncScene();
            scene.AddModuleInterfaces(m_simBase.ApplicationRegistry.GetInterfaces());
            scene.Initialize(regionInfo, dataStore, circuitManager, allClientServers);

            return scene;
        }
        /// <summary>
        /// Creates/updates a region from console.
        /// </summary>
        /// <returns>The region from console.</returns>
        /// <param name="info">Info.</param>
        /// <param name="prompt">If set to <c>true</c> prompt.</param>
        /// <param name="currentInfo">Current info.</param>
        RegionInfo CreateRegionFromConsole(RegionInfo info, Boolean prompt, Dictionary<string, int> currentInfo)
        {
            if (info == null || info.NewRegion)
            {
                if (info == null)
                    info = new RegionInfo();

                info.RegionID = UUID.Random();

                if (currentInfo != null)
                {
                    info.RegionLocX = currentInfo ["minX"] > 0 ? currentInfo ["minX"] : 1000 * Constants.RegionSize;
                    info.RegionLocY = currentInfo ["minY"] > 0 ? currentInfo ["minY"] : 1000 * Constants.RegionSize;
                    info.RegionPort = currentInfo ["port"] > 0 ? currentInfo ["port"] + 1 : 9000;
                } else
                {
                    info.RegionLocX = 1000 * Constants.RegionSize;
                    info.RegionLocY = 1000 * Constants.RegionSize;
                    info.RegionPort = 9000;

                }
                prompt = true;
            }

            // prompt for user input
            if (prompt)
            {
                Utilities.MarkovNameGenerator rNames = new Utilities.MarkovNameGenerator();
                string regionName = rNames.FirstName (m_regionNameSeed == null ? Utilities.RegionNames: m_regionNameSeed, 3,7);
                if (info.RegionName != "")
                    regionName = info.RegionName;

                do
                {
                    info.RegionName = MainConsole.Instance.Prompt ("Region Name (? for suggestion)", regionName);
                    if (info.RegionName == "" || info.RegionName == "?")
                    {
                        regionName = rNames.NextName;
                        info.RegionName = "";
                        continue;
                    }
                }
                while (info.RegionName == "");
                rNames.Reset();

                info.RegionLocX =
                    int.Parse (MainConsole.Instance.Prompt ("Region Location X",
                    ((info.RegionLocX == 0
                            ? 1000
                            : info.RegionLocX / Constants.RegionSize)).ToString ())) * Constants.RegionSize;

                info.RegionLocY =
                    int.Parse (MainConsole.Instance.Prompt ("Region location Y",
                    ((info.RegionLocY == 0
                            ? 1000
                            : info.RegionLocY / Constants.RegionSize)).ToString ())) * Constants.RegionSize;

                var haveSize = true;
                var sizeCheck = "";
                do
                {
                    info.RegionSizeX = int.Parse (MainConsole.Instance.Prompt ("Region size X", info.RegionSizeX.ToString ()));
                    if (info.RegionSizeX > Constants.MaxRegionSize)
                    {
                        MainConsole.Instance.CleanInfo ("    The currently recommended maximum size is " + Constants.MaxRegionSize);
                        sizeCheck =  MainConsole.Instance.Prompt ("Continue with the X size of " + info.RegionSizeX + "? (yes/no)", "no");
                        haveSize = sizeCheck.ToLower().StartsWith("y");
                    }
                } while (! haveSize);

                // assume square regions
                info.RegionSizeY = info.RegionSizeX;

                do
                {
                    info.RegionSizeY = int.Parse (MainConsole.Instance.Prompt ("Region size Y", info.RegionSizeY.ToString ()));
                    if ( (info.RegionSizeY > info.RegionSizeX) && (info.RegionSizeY > Constants.MaxRegionSize) )
                    {
                        MainConsole.Instance.CleanInfo ("    The currently recommended maximum size is " + Constants.MaxRegionSize);
                        sizeCheck =  MainConsole.Instance.Prompt ("Continue with the Y size of " + info.RegionSizeY + "? (yes/no)", "no");
                        haveSize = sizeCheck.ToLower().StartsWith("y");
                    }
                } while (! haveSize);

                bool bigRegion = ((info.RegionSizeX > Constants.MaxRegionSize) || (info.RegionSizeY > Constants.MaxRegionSize));

                // * Mainland / Full Region (Private)
                // * Mainland / Homestead
                // * Mainland / Openspace
                //
                // * Estate / Full Region   (Private)
                info.RegionType = MainConsole.Instance.Prompt ("Region Type (Mainland/Estate)",
                    (info.RegionType == "" ? "Estate" : info.RegionType));

                // Region presets or advanced setup
                string setupMode;
                string terrainOpen = "Grassland";
                string terrainFull = "Grassland";
                var responses = new List<string>();
                if (info.RegionType.ToLower().StartsWith("m"))
                {
                    // Mainland regions
                    info.RegionType = "Mainland / ";
                    responses.Add("Full Region");
                    responses.Add("Homestead");
                    responses.Add ("Openspace");
                    responses.Add ("Universe");                            // TODO: remove?
                    responses.Add ("Custom");
                    setupMode = MainConsole.Instance.Prompt("Mainland region type?", "Full Region", responses).ToLower ();

                    // allow specifying terrain for Openspace
                    if (bigRegion)
                        terrainOpen = "flatland";
                    else if (setupMode.StartsWith("o"))
                        terrainOpen = MainConsole.Instance.Prompt("Openspace terrain ( Grassland, Swamp, Aquatic)?", terrainOpen).ToLower();

                } else
                {
                    // Estate regions
                    info.RegionType = "Estate / ";
                    responses.Add("Full Region");
                    responses.Add ("Universe");                            // TODO: Universe 'standard' setup, rename??
                    responses.Add ("Custom");
                    setupMode = MainConsole.Instance.Prompt("Estate region type?","Full Region", responses).ToLower();
                }

                // terrain can be specified for Full or custom regions
                if (bigRegion)
                    terrainFull = "Flatland";
                else if (setupMode.StartsWith ("f") || setupMode.StartsWith ("c"))
                {
                    var tresp = new List<string>();
                    tresp.Add ("Flatland");
                    tresp.Add ("Grassland");
                    tresp.Add ("Hills");
                    tresp.Add ("Mountainous");
                    tresp.Add ("Island");
                    tresp.Add ("Swamp");
                    tresp.Add ("Aquatic");
                    string tscape = MainConsole.Instance.Prompt ("Terrain Type?", terrainFull,tresp);
                    terrainFull = tscape;
                    // TODO: This would be where we allow selection of preset terrain files
                }

                if (setupMode.StartsWith("c"))
                {
                    info.RegionType = info.RegionType + "Custom";
                    info.RegionTerrain = terrainFull;

                    // allow port selection
                    info.RegionPort = int.Parse (MainConsole.Instance.Prompt ("Region Port", info.RegionPort.ToString ()));

                    // Startup mode
                    string scriptStart = MainConsole.Instance.Prompt (
                        "Region Startup - Normal or Delayed startup (normal/delay) : ","normal").ToLower();
                    info.Startup = scriptStart.StartsWith ("n") ? StartupType.Normal : StartupType.Medium;

                    info.SeeIntoThisSimFromNeighbor =  MainConsole.Instance.Prompt (
                        "See into this sim from neighbors (yes/no)",
                        info.SeeIntoThisSimFromNeighbor ? "yes" : "no").ToLower() == "yes";

                    info.InfiniteRegion = MainConsole.Instance.Prompt (
                        "Make an infinite region (yes/no)",
                        info.InfiniteRegion ? "yes" : "no").ToLower () == "yes";

                    info.ObjectCapacity =
                        int.Parse (MainConsole.Instance.Prompt ("Object capacity",
                        info.ObjectCapacity == 0
                                               ? "50000"
                                               : info.ObjectCapacity.ToString ()));
                }

                if (setupMode.StartsWith("w"))
                {
                    // 'standard' setup
                    info.RegionType = info.RegionType + "Universe";
                    //info.RegionPort;            // use auto assigned port
                    info.RegionTerrain = "Flatland";
                    info.Startup = StartupType.Normal;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = false;
                    info.ObjectCapacity = 50000;

                }
                if (setupMode.StartsWith("o"))
                {
                    // 'Openspace' setup
                    info.RegionType = info.RegionType + "Openspace";
                    //info.RegionPort;            // use auto assigned port

                    if (terrainOpen.StartsWith("a"))
                        info.RegionTerrain = "Aquatic";
                    else if (terrainOpen.StartsWith("s"))
                        info.RegionTerrain = "Swamp";
                    else if (terrainOpen.StartsWith("g"))
                        info.RegionTerrain = "Grassland";
                    else
                        info.RegionTerrain = "Flatland";

                    info.Startup = StartupType.Medium;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = false;
                    info.ObjectCapacity = 750;
                    info.RegionSettings.AgentLimit = 10;
                    info.RegionSettings.AllowLandJoinDivide = false;
                    info.RegionSettings.AllowLandResell = false;
                                   }
                if (setupMode.StartsWith("h"))
                {
                    // 'Homestead' setup
                    info.RegionType = info.RegionType + "Homestead";
                    //info.RegionPort;            // use auto assigned port
                    if (bigRegion)
                        info.RegionTerrain = "Flatland";
                    else
                        info.RegionTerrain = "Homestead";

                    info.Startup = StartupType.Medium;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = false;
                    info.ObjectCapacity = 3750;
                    info.RegionSettings.AgentLimit = 20;
                    info.RegionSettings.AllowLandJoinDivide = false;
                    info.RegionSettings.AllowLandResell = false;
                }

                if (setupMode.StartsWith("f"))
                {
                    // 'Full Region' setup
                    info.RegionType = info.RegionType + "Full Region";
                    //info.RegionPort;            // use auto assigned port
                    info.RegionTerrain = terrainFull;
                    info.Startup = StartupType.Normal;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = false;
                    info.ObjectCapacity = 15000;
                    info.RegionSettings.AgentLimit = 100;
                    if (info.RegionType.StartsWith ("M"))                           // defaults are 'true'
                    {
                        info.RegionSettings.AllowLandJoinDivide = false;
                        info.RegionSettings.AllowLandResell = false;
                    }
                }

            }

            // are we updating or adding?
            if (m_scene != null)
            {
                IGridRegisterModule gridRegister = m_scene.RequestModuleInterface<IGridRegisterModule>();
                //Re-register so that if the position has changed, we get the new neighbors
                gridRegister.RegisterRegionWithGrid(m_scene, true, false, null);

                // Tell clients about changes
                IEstateModule es = m_scene.RequestModuleInterface<IEstateModule> ();
                if (es != null)
                    es.sendRegionHandshakeToAll ();

                // in case we have changed the name
                if (m_scene.SimulationDataService.BackupFile != info.RegionName)
                {
                    string oldFile = BuildSaveFileName (m_scene.SimulationDataService.BackupFile);
                    if (File.Exists (oldFile))
                        File.Delete (oldFile);
                    m_scene.SimulationDataService.BackupFile = info.RegionName;
                }

                m_scene.SimulationDataService.ForceBackup();

                MainConsole.Instance.InfoFormat("[FileBasedSimulationData]: Save of {0} completed.",info.RegionName);
            }

            return info;
        }
 public override void Initialize(IMesher meshmerizer, IScene scene)
 {
     m_region = scene.RegionInfo;
 }
        /// <summary>
        /// Creates and adds a region from supplied regioninfo.
        /// </summary>
        /// <param name="regionInfo">Region info.</param>
        public bool CreateRegion(RegionInfo regionInfo)
        {
            if (regionInfo == null)
                return false;

            if (RegionNameExists(regionInfo.RegionName))
            {
                MainConsole.Instance.InfoFormat ("[SceneManager]: A region already exists with the name '{0}'",
                    regionInfo.RegionName);
                return false;
            }

            if ( RegionAtLocationExists(regionInfo.RegionLocX, regionInfo.RegionLocY))
            {
            MainConsole.Instance.InfoFormat ("[SceneManager]: A region at @ {0},{1} already exists",
                regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize);
                return false;
            }

            // we should be ok..
            MainConsole.Instance.InfoFormat ("[SceneManager]: Creating new region \"{0}\" at @ {1},{2}",
                regionInfo.RegionName, regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize);

            var currentInfo = FindCurrentRegionInfo ();
            var regions = new List<KeyValuePair<ISimulationDataStore, RegionInfo>> ();
            ISimulationDataStore store = m_selectedDataService.Copy ();

            regions.Add (new KeyValuePair<ISimulationDataStore, RegionInfo> (store, store.CreateNewRegion (m_SimBase, regionInfo, currentInfo)));
            StartRegion (store, regionInfo);

            return true;
        }
        /// <summary>
        ///     Use the asset set information at path to load assets
        /// </summary>
        /// <param name="iarFileName"></param>
        protected void LoadLibraries(string iarFileName)
        {
            RegionInfo regInfo = new RegionInfo();
            IScene m_MockScene = null;
            //Make the scene for the IAR loader
            if (m_registry is IScene)
                m_MockScene = (IScene) m_registry;
            else
            {
                m_MockScene = new Scene();
                m_MockScene.Initialize(regInfo);
                m_MockScene.AddModuleInterfaces(m_registry.GetInterfaces());
            }

            UserAccount uinfo = m_MockScene.UserAccountService.GetUserAccount(null, m_service.LibraryOwner);
            //Make the user account for the default IAR
            if (uinfo == null)
            {
                MainConsole.Instance.Warn("Creating user " + m_service.LibraryOwnerName);
                m_MockScene.UserAccountService.CreateUser(m_service.LibraryOwner, UUID.Zero, m_service.LibraryOwnerName,
                                                          "", "");
                uinfo = m_MockScene.UserAccountService.GetUserAccount(null, m_service.LibraryOwner);
                m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false);
            }
            if (m_MockScene.InventoryService.GetRootFolder(m_service.LibraryOwner) == null)
                m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false);

            List<InventoryFolderBase> rootFolders = m_MockScene.InventoryService.GetFolderFolders(uinfo.PrincipalID,
                                                                                                  UUID.Zero);
            bool alreadyExists = rootFolders.Any(folder => folder.Name == iarFileName);

            if (alreadyExists)
            {
                MainConsole.Instance.InfoFormat("[LIBRARY INVENTORY]: Found previously loaded iar file {0}, ignoring.",
                                                iarFileName);
                return;
            }

            MainConsole.Instance.InfoFormat("[LIBRARY INVENTORY]: Loading iar file {0}", iarFileName);
            InventoryFolderBase rootFolder = m_MockScene.InventoryService.GetRootFolder(uinfo.PrincipalID);

            if (null == rootFolder)
            {
                //We need to create the root folder, otherwise the IAR freaks
                m_MockScene.InventoryService.CreateUserInventory(uinfo.PrincipalID, false);
            }

            InventoryArchiveReadRequest archread = new InventoryArchiveReadRequest(m_MockScene, uinfo, "/", iarFileName,
                                                                                   false, m_service.LibraryOwner);

            try
            {
                archread.ReplaceAssets = true; //Replace any old assets
                List<InventoryNodeBase> nodes = new List<InventoryNodeBase>(archread.Execute(true));
                if (nodes.Count == 0)
                    return;
                InventoryFolderBase f = (InventoryFolderBase) nodes[0];
                UUID IARRootID = f.ID;

                TraverseFolders(IARRootID, m_MockScene);
                FixParent(IARRootID, m_MockScene, m_service.LibraryRootFolderID);
                f.Name = iarFileName;
                f.ParentID = UUID.Zero;
                f.ID = m_service.LibraryRootFolderID;
                f.Type = (int) AssetType.RootFolder;
                f.Version = 1;
                m_MockScene.InventoryService.UpdateFolder(f);
            }
            catch (Exception e)
            {
                MainConsole.Instance.DebugFormat("[LIBRARY MODULE]: Exception when processing archive {0}: {1}",
                                                 iarFileName,
                                                 e.StackTrace);
            }
            finally
            {
                archread.Close();
            }
        }
        public void Initialize(RegionInfo regionInfo, ISimulationDataStore dataStore,
            AgentCircuitManager authen, List<IClientNetworkServer> clientServers)
        {
            Initialize(regionInfo);

            //Set up the clientServer
            m_clientServers = clientServers;
            foreach (IClientNetworkServer clientServer in clientServers)
                clientServer.AddScene(this);

            m_sceneManager = RequestModuleInterface<ISceneManager>();
            m_simDataStore = dataStore;

            m_config = m_sceneManager.ConfigSource;
            m_authenticateHandler = authen;

            m_UniverseEventManager = new UniverseEventManager();
            m_eventManager = new EventManager();
            m_permissions = new ScenePermissions(this);

            m_sceneGraph = new SceneGraph(this, m_regInfo);

            #region Region Config

            IConfig packetConfig = m_config.Configs["PacketPool"];
            if (packetConfig != null)
            {
                PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
                PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
            }

            #endregion Region Config

            m_basesimfps = 45f;
            m_basesimphysfps = 45f;

            m_basesimphysfps = Config.Configs["Physics"].GetFloat("BasePhysicsFPS", 45f);
            m_basesimfps = Config.Configs["Protection"].GetFloat("BaseRateFramesPerSecond", 45f);
            if (m_basesimphysfps > 45f)
                m_basesimphysfps = 45f;
            if (m_basesimfps > 45f)
                m_basesimfps = 45f;

            if (m_basesimphysfps > m_basesimfps)
                m_basesimphysfps = m_basesimfps;

            m_updatetimespan = 1000/m_basesimfps;
            m_physicstimespan = 1000/m_basesimphysfps;

            #region Startup Complete config

            EventManager.OnAddToStartupQueue += AddToStartupQueue;
            EventManager.OnModuleFinishedStartup += FinishedStartup;
            //EventManager.OnStartupComplete += StartupComplete;

            AddToStartupQueue("Startup");

            #endregion
        }
        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
                                               OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
                                               ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();
            var gridService = webInterface.Registry.RequestModuleInterface<IGridService> ();

            if (requestParameters.ContainsKey("Submit"))
            {

                string RegionServerURL = requestParameters["RegionServerURL"].ToString();
                // required
                if (RegionServerURL == "")  {
                    response = "<h3>" + translator.GetTranslatedString ("RegionServerURLError") + "</h3>";
                    return null;
                }

                string RegionName = requestParameters["RegionName"].ToString();
                //string OwnerUUID = requestParameters["OwnerUUID"].ToString();
                string RegionLocX = requestParameters["RegionLocX"].ToString();
                string RegionLocY = requestParameters["RegionLocY"].ToString();
                string RegionSizeX = requestParameters["RegionSizeX"].ToString();
                string RegionSizeY = requestParameters["RegionSizeY"].ToString();

                string RegionType = requestParameters["RegionType"].ToString();
                string RegionPresetType = requestParameters["RegionPresetType"].ToString();
                string RegionTerrain = requestParameters["RegionTerrain"].ToString();

                string RegionLoadTerrain = requestParameters.ContainsKey("RegionLoadTerrain")
                    ? requestParameters["RegionLoadTerrain"].ToString()
                    : "";
                //bool ToSAccept = requestParameters.ContainsKey("ToSAccept") &&
                //    requestParameters["ToSAccept"].ToString() == "Accepted";

               // string UserType = requestParameters.ContainsKey("UserType")         // only admins can set membership
               //     ? requestParameters ["UserType"].ToString ()
               //     : "Resident";

                // a bit of idiot proofing
                if (RegionName == "")  {
                    response = "<h3>" + translator.GetTranslatedString ("RegionNameError") + "</h3>";
                    return null;
                }
                if ( (RegionLocX == "") || (RegionLocY == "") )
                {
                    response = "<h3>" + translator.GetTranslatedString ("RegionLocationError") + "</h3>";
                    return null;
                }

                // so far so good...
                // build the new region details
                int RegionPort = int.Parse (requestParameters ["RegionPort"].ToString ());

                var newRegion = new RegionInfo();

                newRegion.RegionName = RegionName;
                newRegion.RegionType = RegionType;
                newRegion.RegionLocX = int.Parse (RegionLocX);
                newRegion.RegionLocY = int.Parse (RegionLocY);
                newRegion.RegionSizeX = int.Parse (RegionSizeX);
                newRegion.RegionSizeY = int.Parse (RegionSizeY);

                newRegion.RegionPort = RegionPort;
                newRegion.SeeIntoThisSimFromNeighbor = true;
                newRegion.InfiniteRegion = false;
                newRegion.ObjectCapacity = 50000;
                newRegion.Startup = StartupType.Normal;

                var regionPreset = RegionPresetType.ToLower ();
                if (regionPreset.StartsWith ("c"))
                {
                    newRegion.RegionPort = int.Parse( requestParameters["RegionPort"].ToString() );
                    newRegion.SeeIntoThisSimFromNeighbor = (requestParameters["RegionVisibility"].ToString().ToLower() == "yes");
                    newRegion.InfiniteRegion = (requestParameters["RegionInfinite"].ToString().ToLower() == "yes");
                    newRegion.ObjectCapacity = int.Parse( requestParameters["RegionCapacity"].ToString() );

                    string delayStartup = requestParameters["RegionDelayStartup"].ToString();
                    newRegion.Startup = delayStartup.StartsWith ("n") ? StartupType.Normal : StartupType.Medium;

                }

                if (regionPreset.StartsWith("w"))
                {
                    // 'standard' setup
                    newRegion.RegionType = newRegion.RegionType + "Whitecore";
                    //info.RegionPort;            // use auto assigned port
                    newRegion.RegionTerrain = "Flatland";
                    newRegion.Startup = StartupType.Normal;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 50000;
                    newRegion.RegionPort = RegionPort;

                }
                if (regionPreset.StartsWith("o"))
                {
                    // 'Openspace' setup
                    newRegion.RegionType = newRegion.RegionType + "Openspace";
                    //newRegion.RegionPort;            // use auto assigned port
                    if (RegionTerrain.StartsWith("a"))
                        newRegion.RegionTerrain = "Aquatic";
                    else
                        newRegion.RegionTerrain = "Grassland";
                    newRegion.Startup = StartupType.Medium;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 750;
                    newRegion.RegionSettings.AgentLimit = 10;
                    newRegion.RegionSettings.AllowLandJoinDivide = false;
                    newRegion.RegionSettings.AllowLandResell = false;
                }
                if (regionPreset.StartsWith("h"))
                {
                    // 'Homestead' setup
                    newRegion.RegionType = newRegion.RegionType + "Homestead";
                    //info.RegionPort;            // use auto assigned port
                    newRegion.RegionTerrain = "Homestead";
                    newRegion.Startup = StartupType.Medium;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 3750;
                    newRegion.RegionSettings.AgentLimit = 20;
                    newRegion.RegionSettings.AllowLandJoinDivide = false;
                    newRegion.RegionSettings.AllowLandResell = false;
                }

                if (regionPreset.StartsWith("f"))
                {
                    // 'Full Region' setup
                    newRegion.RegionType = newRegion.RegionType + "Full Region";
                    //newRegion.RegionPort;            // use auto assigned port
                    newRegion.RegionTerrain = RegionTerrain;
                    newRegion.Startup = StartupType.Normal;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 15000;
                    newRegion.RegionSettings.AgentLimit = 100;
                    if (newRegion.RegionType.StartsWith ("M"))                           // defaults are 'true'
                    {
                        newRegion.RegionSettings.AllowLandJoinDivide = false;
                        newRegion.RegionSettings.AllowLandResell = false;
                    }
                }

                if (RegionLoadTerrain.Length > 0)
                {
                    // we are loading terrain from a file... handled later
                    newRegion.RegionTerrain = "Custom";
                }

                /* Disabled as this is a work in progress and will break with the current scenemanager (Dec 5 - greythane-
                // TODO: !!! Assumes everything is local for now !!!
                ISceneManager scenemanager = webInterface.Registry.RequestModuleInterface<ISceneManager> ();
                if (scenemanager.CreateRegion(newRegion))
                {
                    IGridRegisterModule gridRegister = webInterface.Registry.RequestModuleInterface<IGridRegisterModule>();
                    if( gridRegister.RegisterRegionWithGrid(null, true, false, null))
                    {

                        response = "<h3>Successfully created region, redirecting to main page</h3>" +
                            "<script language=\"javascript\">" +
                            "setTimeout(function() {window.location.href = \"index.html\";}, 3000);" +
                            "</script>";
                    }
                    else
            //                        response = "<h3>" + error + "</h3>";
                            response = "<h3> Error registering region with grid</h3>";
                }
                else
            */
                response = "<h3>Error creating this region.</h3>";
                return null;
            }

            // we have or need data
            if (httpRequest.Query.ContainsKey ("regionid"))
            {
                var region = gridService.GetRegionByUUID (null, UUID.Parse (httpRequest.Query ["regionid"].ToString ()));

                IEstateConnector estateConnector = Framework.Utilities.DataManager.RequestPlugin<IEstateConnector> ();
                EstateSettings estate = estateConnector.GetEstateSettings (region.RegionID);

                vars.Add ("RegionName", region.RegionName);
                vars.Add ("OwnerUUID", estate.EstateOwner);

                var estateOwnerAccount = webInterface.Registry.RequestModuleInterface<IUserAccountService> ().
                    GetUserAccount (null, estate.EstateOwner);
                vars.Add ("OwnerName", estateOwnerAccount == null ? "No account found" : estateOwnerAccount.Name);
                vars.Add ("RegionLocX", region.RegionLocX / Constants.RegionSize);
                vars.Add ("RegionLocY", region.RegionLocY / Constants.RegionSize);
                vars.Add ("RegionSizeX", region.RegionSizeX);
                vars.Add ("RegionSizeY", region.RegionSizeY);
                vars.Add ("RegionType", region.RegionType);
                vars.Add ("RegionTerrain", region.RegionTerrain);
                vars.Add ("RegionOnline",
                    (region.Flags & (int)RegionFlags.RegionOnline) ==
                    (int)RegionFlags.RegionOnline
                    ? translator.GetTranslatedString ("Online")
                    : translator.GetTranslatedString ("Offline"));

                IWebHttpTextureService webTextureService = webInterface.Registry.
                    RequestModuleInterface<IWebHttpTextureService> ();
                if (webTextureService != null && region.TerrainMapImage != UUID.Zero)
                    vars.Add ("RegionImageURL", webTextureService.GetTextureURL (region.TerrainMapImage));
                else
                    vars.Add ("RegionImageURL", "images/icons/no_picture.jpg");
            }
            else
            {
                // default values

                // check for user name seed
                string[] m_regionNameSeed = null;
                /*IConfig regionConfig =
                    webInterface.Registry.RequestModuleInterface<ISimulationBase>().ConfigSource.Configs["LoginService"];

                 if (loginServerConfig != null)
                {
                    string userNameSeed = loginServerConfig.GetString ("UserNameSeed", "");
                    if (userNameSeed != "")
                        m_userNameSeed = userNameSeed.Split (',');
                }
            */
                Utilities.MarkovNameGenerator rNames = new Utilities.MarkovNameGenerator();
                string regionName = rNames.FirstName (m_regionNameSeed == null ? Utilities.RegionNames: m_regionNameSeed, 3,7);
                vars.Add ("RegionName", regionName);

                //var scenemanager = webInterface.Registry.RequestModuleInterface<ISceneManager> ();
                var gconnector = Framework.Utilities.DataManager.RequestPlugin<IGenericsConnector>();
                var settings = gconnector.GetGeneric<WebUISettings>(UUID.Zero, "WebUISettings", "Settings");

                // get some current details
                //List<GridRegion> regions = gridService.GetRegionsByName(null, "", null,null);

            //                var currentInfo = scenemanager.FindCurrentRegionInfo ();
                Dictionary<string, int> currentInfo = null;
                if (currentInfo != null)
                {
                    vars.Add ("RegionLocX", currentInfo ["minX"] > 0 ? currentInfo ["minX"] : settings.MapCenter.X);
                    vars.Add ("RegionLocY", currentInfo ["minY"] > 0 ? currentInfo ["minY"] : settings.MapCenter.Y);
                    vars.Add("RegionPort", currentInfo ["port"] > 0 ? currentInfo ["port"] + 1 : 9000);
                } else
                {
                    vars.Add ("RegionLocX", settings.MapCenter.X);
                    vars.Add ("RegionLocY", settings.MapCenter.Y);
                    vars.Add("RegionPort", 9000);

                }

                vars.Add ("RegionSizeX", Constants.RegionSize);
                vars.Add ("RegionSizeY", Constants.RegionSize);
                vars.Add ("RegionType", webInterface.RegionTypeArgs(translator));
                vars.Add ("RegionPresetType", webInterface.RegionPresetArgs(translator));
                vars.Add ("RegionTerrain", webInterface.RegionTerrainArgs(translator));

            }

                // Labels
                //vars.Add ("RegionInformationText", translator.GetTranslatedString ("RegionInformationText"));
            vars.Add ("RegionNameText", translator.GetTranslatedString ("RegionNameText"));
            vars.Add ("RegionLocationText", translator.GetTranslatedString ("RegionLocationText"));
            vars.Add ("RegionSizeText", translator.GetTranslatedString ("RegionSizeText"));
            vars.Add ("RegionTypeText", translator.GetTranslatedString ("RegionTypeText"));
            vars.Add ("RegionPresetText", translator.GetTranslatedString ("RegionPresetText"));
            vars.Add ("RegionTerrainText", translator.GetTranslatedString ("RegionTerrainText"));
            vars.Add ("OwnerNameText", translator.GetTranslatedString ("OwnerNameText"));
            vars.Add ("RegionPortText", translator.GetTranslatedString ("RegionPortText"));
            vars.Add ("RegionDelayStartupText", translator.GetTranslatedString ("RegionDelayStartupText"));
            vars.Add ("RegionVisibilityText", translator.GetTranslatedString ("RegionVisibilityText"));
            vars.Add ("RegionInfiniteText", translator.GetTranslatedString ("RegionInfiniteText"));
            vars.Add ("RegionCapacityText", translator.GetTranslatedString ("RegionCapacityText"));
            vars.Add ("Yes", translator.GetTranslatedString ("Yes"));
            vars.Add ("No", translator.GetTranslatedString ("No"));
            vars.Add("Accept", translator.GetTranslatedString("Accept"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));
            vars.Add("SubmitURL", "home.html");
            vars.Add("ErrorMessage", "");

            return vars;
        }
        /// <summary>
        /// Modifies the region settings.
        /// </summary>
        /// <returns>The region settings.</returns>
        /// <param name="regInfo">Reg info.</param>
        /// <param name="advanced">If set to <c>true</c> advanced.</param>
        bool ModifyRegionSettings(ref RegionInfo regInfo, bool advanced)
        {
            bool updated = false;
            if (regInfo == null || regInfo.NewRegion)
                return updated;

            updated |= GetRegionName (ref regInfo);
            updated |= GetRegionLocation (ref regInfo);
            updated |= GetRegionSize (ref regInfo);

            if (advanced)
            {
                // region type
                var oldType = regInfo.RegionType;
                regInfo.RegionType = MainConsole.Instance.Prompt ("Region Type (Mainland/Estate)",
                    (regInfo.RegionType == "" ? "Estate" : regInfo.RegionType));
                if (regInfo.RegionType != oldType)
                    updated = true;

                updated |= GetRegionOptional (ref regInfo);
             }

             return updated;
        }
 public void Dispose()
 {
     Groups = null;
     Parcels = null;
     Water = null;
     RevertWater = null;
     Terrain = null;
     RevertTerrain = null;
     RegionInfo = null;
 }
        /// <summary>
        /// Gets the region optional settings.
        /// </summary>
        /// <returns><c>true</c>, if region optional was gotten, <c>false</c> otherwise.</returns>
        /// <param name="regInfo">Reg info.</param>
        bool GetRegionOptional(ref RegionInfo regInfo)
        {
            var updated = false;

            // allow port selection
            var oldPort = regInfo.RegionPort;
            regInfo.RegionPort = int.Parse (MainConsole.Instance.Prompt ("Region Port (Only change if necessary)", regInfo.RegionPort.ToString ()));
            if (regInfo.RegionPort != oldPort)
                updated = true;

            var oldStart = regInfo.Startup;
            // Startup mode
            string scriptStart = MainConsole.Instance.Prompt (
                "Region Startup - Normal or Delayed startup (normal/delay) : ", "normal").ToLower ();
            regInfo.Startup = scriptStart.StartsWith ("n") ? StartupType.Normal : StartupType.Medium;
            if (regInfo.Startup != oldStart)
                updated = true;

            var oldSwitch = regInfo.SeeIntoThisSimFromNeighbor;
            regInfo.SeeIntoThisSimFromNeighbor = MainConsole.Instance.Prompt (
                "See into this sim from neighbors (yes/no)",
                regInfo.SeeIntoThisSimFromNeighbor ? "yes" : "no").ToLower () == "yes";
            if (regInfo.SeeIntoThisSimFromNeighbor != oldSwitch)
                updated = true;

            oldSwitch = regInfo.InfiniteRegion;
            regInfo.InfiniteRegion = MainConsole.Instance.Prompt (
                "Make an infinite region (yes/no)",
                regInfo.InfiniteRegion ? "yes" : "no").ToLower () == "yes";
            if (regInfo.InfiniteRegion != oldSwitch)
                updated = true;

            var oldCap = regInfo.ObjectCapacity;
            regInfo.ObjectCapacity =
                int.Parse (MainConsole.Instance.Prompt ("Object capacity",
                    regInfo.ObjectCapacity == 0
                    ? "50000"
                    : regInfo.ObjectCapacity.ToString ()));
            if (regInfo.ObjectCapacity != oldCap)
                updated = true;

            return updated;
        }
        /// <summary>
        /// Gets the size of the region.
        /// </summary>
        /// <returns><c>true</c>, if region size was gotten, <c>false</c> otherwise.</returns>
        /// <param name="RegionInfo">Region info.</param>
        bool GetRegionSize(ref RegionInfo regInfo)
        {
            var updated = false;
            var haveSize = true;
            var sizeCheck = "";
            var oldSize = regInfo.RegionSizeX;
            do
            {
                regInfo.RegionSizeX = int.Parse (MainConsole.Instance.Prompt ("Region size X", regInfo.RegionSizeX.ToString ()));
                if (regInfo.RegionSizeX > Constants.MaxRegionSize)
                {
                    MainConsole.Instance.CleanInfo ("    The currently recommended maximum size is " + Constants.MaxRegionSize);
                    sizeCheck = MainConsole.Instance.Prompt ("Continue with the X size of " + regInfo.RegionSizeX + "? (yes/no)", "no");
                    haveSize = sizeCheck.ToLower ().StartsWith ("y");
                }
            } while (!haveSize);
            if (regInfo.RegionSizeX != oldSize)
                updated = true;

            // assume square regions
            regInfo.RegionSizeY = regInfo.RegionSizeX;
            oldSize = regInfo.RegionSizeY;
            do
            {
                regInfo.RegionSizeY = int.Parse (MainConsole.Instance.Prompt ("Region size Y", regInfo.RegionSizeY.ToString ()));
                if ((regInfo.RegionSizeY > regInfo.RegionSizeX) && (regInfo.RegionSizeY > Constants.MaxRegionSize))
                {
                    MainConsole.Instance.CleanInfo ("    The currently recommended maximum size is " + Constants.MaxRegionSize);
                    sizeCheck = MainConsole.Instance.Prompt ("Continue with the Y size of " + regInfo.RegionSizeY + "? (yes/no)", "no");
                    haveSize = sizeCheck.ToLower ().StartsWith ("y");
                }
            } while (!haveSize);
            if (regInfo.RegionSizeY != oldSize)
                updated = true;

            return updated;
        }
        /// <summary>
        /// Gets the name of the region.
        /// </summary>
        /// <returns><c>true</c>, if region name was gotten, <c>false</c> otherwise.</returns>
        /// <param name="regInfo">Reg info.</param>
        bool GetRegionName(ref RegionInfo regInfo)
        {
            var updated = false;

            Utilities.MarkovNameGenerator rNames = new Utilities.MarkovNameGenerator ();
            string regionName = rNames.FirstName (m_regionNameSeed == null ? Utilities.RegionNames : m_regionNameSeed, 3, 7);

            regionName = regInfo.RegionName;
            var oldName = regionName;

            do
            {
                regInfo.RegionName = MainConsole.Instance.Prompt ("Region Name (? for suggestion)", regionName);
                if (regInfo.RegionName == "" || regInfo.RegionName == "?")
                {
                    regionName = rNames.NextName;
                    regInfo.RegionName = "";
                    continue;
                }
            } while (regInfo.RegionName == "");
            rNames.Reset ();
            if (regInfo.RegionName != oldName)
                updated = true;

            return updated;
        }
        /// <summary>
        /// Gets the region location.
        /// </summary>
        /// <returns><c>true</c>, if region location was gotten, <c>false</c> otherwise.</returns>
        /// <param name="regInfo">Reg info.</param>
        bool GetRegionLocation(ref RegionInfo regInfo)
        {
            var updated = false;
            var loc = regInfo.RegionLocX;
            regInfo.RegionLocX =
                int.Parse (MainConsole.Instance.Prompt ("Region Location X",
                    ((regInfo.RegionLocX == 0
                        ? 1000
                        : regInfo.RegionLocX / Constants.RegionSize)).ToString ())) * Constants.RegionSize;
            if (regInfo.RegionLocX != loc)
                updated = true;

            loc = regInfo.RegionLocY;
            regInfo.RegionLocY =
                int.Parse (MainConsole.Instance.Prompt ("Region location Y",
                    ((regInfo.RegionLocY == 0
                        ? 1000
                        : regInfo.RegionLocY / Constants.RegionSize)).ToString ())) * Constants.RegionSize;
            if (regInfo.RegionLocY != loc)
                updated = true;

            //loc = regInfo.RegionLocZ;
            //regInfo.RegionLocZ =
            //        int.Parse (MainConsole.Instance.Prompt ("Region location Z",
            //            ((regInfo.RegionLocZ == 0
            //            ? 0
            //            : regInfo.RegionLocZ / Constants.RegionSize)).ToString ())) * Constants.RegionSize;
            //if (regInfo.RegionLocZ != loc)
            //    updated = true;

            return updated;
        }
        private void ReadOpenRegionSettings(IConfig instanceSettings, ref RegionInfo region)
        {
            if (instanceSettings == null)
                return;
            region.OpenRegionSettings.MaxDragDistance = instanceSettings.GetFloat("MaxDragDistance",
                                                                                  region.OpenRegionSettings
                                                                                        .MaxDragDistance);
            region.OpenRegionSettings.DefaultDrawDistance = instanceSettings.GetFloat("DefaultDrawDistance",
                                                                                      region.OpenRegionSettings
                                                                                            .DefaultDrawDistance);

            region.OpenRegionSettings.MaximumPrimScale = instanceSettings.GetFloat("MaximumPrimScale",
                                                                                   region.OpenRegionSettings
                                                                                         .MaximumPrimScale);
            region.OpenRegionSettings.MinimumPrimScale = instanceSettings.GetFloat("MinimumPrimScale",
                                                                                   region.OpenRegionSettings
                                                                                         .MinimumPrimScale);
            region.OpenRegionSettings.MaximumPhysPrimScale = instanceSettings.GetFloat("MaximumPhysPrimScale",
                                                                                       region.OpenRegionSettings
                                                                                             .MaximumPhysPrimScale);

            region.OpenRegionSettings.MaximumHollowSize = instanceSettings.GetFloat("MaximumHollowSize",
                                                                                    region.OpenRegionSettings
                                                                                          .MaximumHollowSize);
            region.OpenRegionSettings.MinimumHoleSize = instanceSettings.GetFloat("MinimumHoleSize",
                                                                                  region.OpenRegionSettings
                                                                                        .MinimumHoleSize);

            region.OpenRegionSettings.MaximumLinkCount = instanceSettings.GetInt("MaximumLinkCount",
                                                                                 region.OpenRegionSettings
                                                                                       .MaximumLinkCount);
            region.OpenRegionSettings.MaximumLinkCountPhys = instanceSettings.GetInt("MaximumLinkCountPhys",
                                                                                     region.OpenRegionSettings
                                                                                           .MaximumLinkCountPhys);

            region.OpenRegionSettings.RenderWater = instanceSettings.GetBoolean("RenderWater",
                                                                                region.OpenRegionSettings.RenderWater);
            region.OpenRegionSettings.MaximumInventoryItemsTransfer =
                instanceSettings.GetInt("MaximumInventoryItemsTransfer",
                                        region.OpenRegionSettings.MaximumInventoryItemsTransfer);
            region.OpenRegionSettings.DisplayMinimap = instanceSettings.GetBoolean("DisplayMinimap",
                                                                                   region.OpenRegionSettings
                                                                                         .DisplayMinimap);
            region.OpenRegionSettings.AllowPhysicalPrims = instanceSettings.GetBoolean("AllowPhysicalPrims",
                                                                                       region.OpenRegionSettings
                                                                                             .AllowPhysicalPrims);
            region.OpenRegionSettings.ForceDrawDistance = instanceSettings.GetBoolean("ForceDrawDistance",
                                                                                      region.OpenRegionSettings
                                                                                            .ForceDrawDistance);

            string offset = instanceSettings.GetString("OffsetOfUTC", region.OpenRegionSettings.OffsetOfUTC.ToString());
            int off;
            if (!int.TryParse(offset, out off))
            {
                if (offset == "SLT" || offset == "PST" || offset == "PDT")
                    off = -8;
                else if (offset == "UTC" || offset == "GMT")
                    off = 0;
            }
            region.OpenRegionSettings.OffsetOfUTC = off;
            region.OpenRegionSettings.OffsetOfUTCDST = instanceSettings.GetBoolean("OffsetOfUTCDST",
                                                                                   region.OpenRegionSettings
                                                                                         .OffsetOfUTCDST);
            region.OpenRegionSettings.EnableTeenMode = instanceSettings.GetBoolean("EnableTeenMode",
                                                                                   region.OpenRegionSettings
                                                                                         .EnableTeenMode);
            region.OpenRegionSettings.ShowTags = instanceSettings.GetInt("ShowTags", region.OpenRegionSettings.ShowTags);
            region.OpenRegionSettings.MaxGroups = instanceSettings.GetInt("MaxGroups",
                                                                          region.OpenRegionSettings.MaxGroups);

            string defaultunderpants = instanceSettings.GetString("DefaultUnderpants",
                                                                  region.OpenRegionSettings.DefaultUnderpants.ToString());
            UUID.TryParse(defaultunderpants, out region.OpenRegionSettings.m_DefaultUnderpants);
            string defaultundershirt = instanceSettings.GetString("DefaultUndershirt",
                                                                  region.OpenRegionSettings.DefaultUndershirt.ToString());
            UUID.TryParse(defaultundershirt, out region.OpenRegionSettings.m_DefaultUndershirt);
        }
        protected internal SceneGraph (IScene parent, RegionInfo regInfo)
        {
            Random random = new Random ();
            m_lastAllocatedLocalId = ((uint)random.NextDouble () * (uint.MaxValue / 2)) + uint.MaxValue / 4;
            m_parentScene = parent;
            m_regInfo = regInfo;

            //Subscript to the scene events
            m_parentScene.EventManager.OnNewClient += SubscribeToClientEvents;
            m_parentScene.EventManager.OnClosingClient += UnSubscribeToClientEvents;

            IConfig universestartupConfig = parent.Config.Configs ["UniverseStartup"];
            if (universestartupConfig != null) {
                m_DefaultObjectName = universestartupConfig.GetString ("DefaultObjectName", m_DefaultObjectName);
                EnableFakeRaycasting = universestartupConfig.GetBoolean ("EnableFakeRaycasting", false);
            }
        }
        public virtual RegionInfo CreateNewRegion(ISimulationBase simBase, string regionName, Dictionary<string, int> currentInfo)
        {
            ReadConfig(simBase);
            _regionData = new RegionData();
            _regionData.Init();
            RegionInfo info = new RegionInfo();
            info.RegionName = regionName;
            info.NewRegion = true;

            info = CreateRegionFromConsole(info, true, currentInfo);
            if (info == null)
                return CreateNewRegion(simBase, info, currentInfo);

            BackupFile = info.RegionName;
            return info;
        }
 public void Initialize(RegionInfo regionInfo)
 {
     m_regInfo = regionInfo;
 }
        /// <summary>
        /// Initializes a new region using the passed regioninfo
        /// </summary>
        /// <returns></returns>
        /// <param name="simBase">Sim base.</param>
        /// <param name="regionInfo">Region info.</param>
        /// <param name="currentInfo">Current region info.</param>
        public virtual RegionInfo CreateNewRegion(ISimulationBase simBase, RegionInfo regionInfo, Dictionary<string, int> currentInfo)
        {
            ReadConfig(simBase);
            _regionData = new RegionData();
            _regionData.Init();

            // something wrong here, prompt for details
            if (regionInfo == null)
                return CreateNewRegion(simBase, currentInfo );

            BackupFile = regionInfo.RegionName;

            if (m_scene != null)
            {
                IGridRegisterModule gridRegister = m_scene.RequestModuleInterface<IGridRegisterModule>();
                //Re-register so that if the position has changed, we get the new neighbors
                gridRegister.RegisterRegionWithGrid(m_scene, true, false, null);

                ForceBackup();

                MainConsole.Instance.Info("[File Based Simulation Data]: Save completed.");
            }

            return regionInfo;
        }
 /// <summary>
 /// Loads the estate settings from an archive.
 /// </summary>
 /// <param name="data">Data.</param>
 /// <param name="filePath">File path.</param>
 /// <param name="type">Type.</param>
 /// <param name="scene">Scene.</param>
 public void LoadModuleFromArchive(byte[] data, string filePath, TarArchiveReader.TarEntryType type, IScene scene)
 {
     if (filePath.StartsWith("estatesettings/"))
     {
         EstateSettings settings = new EstateSettings();
         settings.FromOSD((OSDMap) OSDParser.DeserializeLLSDBinary(data));
         scene.RegionInfo.EstateSettings = settings;
     }
     else if (filePath.StartsWith("regioninfo/"))
     {
         string m_merge =
             MainConsole.Instance.Prompt(
                 "Should we load the region information from the archive (region name, region position, etc)?",
                 "false");
         RegionInfo settings = new RegionInfo();
         settings.UnpackRegionInfoData((OSDMap) OSDParser.DeserializeLLSDBinary(data));
         if (m_merge == "false")
         {
             //Still load the region settings though
             scene.RegionInfo.RegionSettings = settings.RegionSettings;
             return;
         }
         settings.RegionSettings = scene.RegionInfo.RegionSettings;
         settings.EstateSettings = scene.RegionInfo.EstateSettings;
         scene.RegionInfo = settings;
     }
 }
        /// <summary>
        /// Creates/updates a region from console.
        /// </summary>
        /// <returns>The region from console.</returns>
        /// <param name="info">Info.</param>
        /// <param name="prompt">If set to <c>true</c> prompt.</param>
        /// <param name="currentInfo">Current info.</param>
        RegionInfo CreateRegionFromConsole(RegionInfo info, Boolean prompt, Dictionary<string, int> currentInfo)
        {
            if (info == null || info.NewRegion)
            {
                if (info == null)
                    info = new RegionInfo();

                info.RegionID = UUID.Random();

                if (currentInfo != null)
                {
                    info.RegionLocX = currentInfo ["minX"] > 0 ? currentInfo ["minX"] : 1000 * Constants.RegionSize;
                    info.RegionLocY = currentInfo ["minY"] > 0 ? currentInfo ["minY"] : 1000 * Constants.RegionSize;
                    info.RegionPort = currentInfo ["port"] > 0 ? currentInfo ["port"] + 1 : 9000;
                } else
                {
                    info.RegionLocX = 1000 * Constants.RegionSize;
                    info.RegionLocY = 1000 * Constants.RegionSize;
                    info.RegionPort = 9000;

                }
                prompt = true;
            }

            // prompt for user input
            if (prompt)
            {
                GetRegionName (ref info);
                GetRegionLocation (ref info);
                GetRegionSize (ref info);

                bool bigRegion = ((info.RegionSizeX > Constants.MaxRegionSize) || (info.RegionSizeY > Constants.MaxRegionSize));

                // * Mainland / Full Region (Private)
                // * Mainland / Homestead
                // * Mainland / Openspace
                //
                // * Estate / Full Region   (Private)
                // * Estate / Homestead
                // * Estate / Openspace
                //
                // * Universe Home / Full Region (Private)
                //
                info.RegionType = MainConsole.Instance.Prompt ("Region Type (Mainland / Estate / Homes)",
                    (info.RegionType == "" ? "Estate" : info.RegionType));

                // Region presets or advanced setup
                string setupMode;
                string terrainOpen = "Grassland";
                string terrainFull = "Grassland";
                var responses = new List<string>();
                if (info.RegionType.ToLower().StartsWith("m"))
                {
                    // Mainland regions
                    info.RegionType = "Mainland / ";
                    responses.Add("Full Region");
                    responses.Add("Homestead");
                    responses.Add("Openspace");
                    setupMode = MainConsole.Instance.Prompt("Mainland region type?", "Full Region", responses).ToLower ();

                    // allow specifying terrain for Openspace
                    if (bigRegion)
                        terrainOpen = "flatland";
                    else if (setupMode.StartsWith("o"))
                        terrainOpen = MainConsole.Instance.Prompt("Openspace terrain ( Grassland, Swamp, Aquatic)?", terrainOpen).ToLower();

                }
                else if (info.RegionType.ToLower().StartsWith("e"))
                {
                    // Estate regions
                    info.RegionType = "Estate / ";
                    responses.Add("Full Region");
                    responses.Add("Homestead");
                    responses.Add("Openspace");
                    setupMode = MainConsole.Instance.Prompt("Estate region type?","Full Region", responses).ToLower();
                }
                else
                {
                    info.RegionType = "Universe Homes / ";
                    responses.Add("Full Region");
                    setupMode = MainConsole.Instance.Prompt("Estate region type?","Full Region", responses).ToLower();
                }

                // terrain can be specified for Full or custom regions
                if (bigRegion)
                    terrainFull = "Flatland";
                if (setupMode.StartsWith ("f"))
                {
                    // 'Region land types' setup
                    var tresp = new List<string>();
                    tresp.Add ("Flatland");
                    tresp.Add ("Grassland");
                    tresp.Add ("Hills");
                    tresp.Add ("Mountainous");
                    tresp.Add ("Island");
                    tresp.Add ("Swamp");
                    tresp.Add ("Aquatic");
                    string tscape = MainConsole.Instance.Prompt ("Terrain Type?", terrainFull,tresp);
                    terrainFull = tscape;
                    // TODO: This would be where we allow selection of preset terrain files
                }

                if (setupMode.StartsWith("o"))
                {
                    // 'Openspace' setup
                    info.RegionType = info.RegionType + "Openspace";

                    if (terrainOpen.StartsWith("a"))
                        info.RegionTerrain = "Aquatic";
                    else if (terrainOpen.StartsWith("s"))
                        info.RegionTerrain = "Swamp";
                    else if (terrainOpen.StartsWith("g"))
                        info.RegionTerrain = "Grassland";
                    else
                        info.RegionTerrain = "Flatland";

                    info.Startup = StartupType.Medium;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = true;
                    info.ObjectCapacity = 750;
                    info.RegionSettings.AgentLimit = 10;
                    info.RegionSettings.AllowLandJoinDivide = false;
                    info.RegionSettings.AllowLandResell = false;
                }

                if (setupMode.StartsWith("h"))
                {
                    // 'Homestead' setup
                    info.RegionType = info.RegionType + "Homestead";
                    if (bigRegion)
                        info.RegionTerrain = "Flatland";
                    else
                        info.RegionTerrain = "Homestead";

                    info.Startup = StartupType.Medium;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = true;
                    info.ObjectCapacity = 3750;
                    info.RegionSettings.AgentLimit = 20;
                    info.RegionSettings.AllowLandJoinDivide = false;
                    info.RegionSettings.AllowLandResell = false;
                }

                if (setupMode.StartsWith("f"))
                {
                    // 'Full Region' setup
                    info.RegionType = info.RegionType + "Full Region";
                    info.RegionTerrain = terrainFull;
                    info.Startup = StartupType.Normal;
                    info.SeeIntoThisSimFromNeighbor = true;
                    info.InfiniteRegion = true;
                    info.ObjectCapacity = 15000;
                    info.RegionSettings.AgentLimit = 100;
                    if (info.RegionType.StartsWith ("M"))                           // defaults are 'true'
                    {
                        info.RegionSettings.AllowLandJoinDivide = false;
                        info.RegionSettings.AllowLandResell = false;
                    }
                    else if (info.RegionType.StartsWith ("H"))						// Homes always have 25000 prims
                    {
                        info.ObjectCapacity = 25000;
                    }
                }

                // re-proportion allocations based on actual region area <> std area
                var regFactor = ( info.RegionSizeX * info.RegionSizeY) / (Constants.RegionSize * Constants.RegionSize);
                info.ObjectCapacity = (int)Math.Round ((float)(info.ObjectCapacity * regFactor));
                info.RegionSettings.AgentLimit = (int) Math.Round ((float)(info.RegionSettings.AgentLimit * regFactor));
            }

            // are we updating or adding??
            if (m_scene != null)
            {
                IGridRegisterModule gridRegister = m_scene.RequestModuleInterface<IGridRegisterModule>();
                //Re-register so that if the position has changed, we get the new neighbors
                gridRegister.RegisterRegionWithGrid(m_scene, true, false, null);

                // Tell clients about changes
                IEstateModule es = m_scene.RequestModuleInterface<IEstateModule> ();
                if (es != null)
                    es.sendRegionHandshakeToAll ();

                // in case we have changed the name
                if (m_scene.SimulationDataService.BackupFile != info.RegionName)
                {
                    string oldFile = BuildSaveFileName (m_scene.SimulationDataService.BackupFile);
                    if (File.Exists (oldFile))
                        File.Delete (oldFile);
                    m_scene.SimulationDataService.BackupFile = info.RegionName;
                }

                m_scene.SimulationDataService.ForceBackup();

                MainConsole.Instance.InfoFormat("[File Based Simulation Data]: Save of {0} completed.",info.RegionName);
            }

            return info;
        }
        /// <summary>
        /// Creates the new region using addition options.
        /// </summary>
        /// <param name="scene">Scene.</param>
        /// <param name="cmd">Cmd.</param>
        void CreateNewRegionExtended(IScene scene, string[] cmd)
        {
            string defaultDir = "";
            string defaultExt = ".xml";
            string regionName = "";
            string regionFile = "";

            List<string> newParams = new List<string>(cmd);
            foreach (string param in cmd)
            {
                if (param.StartsWith("--config", StringComparison.CurrentCultureIgnoreCase))
                {
                    regionFile = param.Remove(0, 9);
                    newParams.Remove(param);
                }
            }

            if (newParams.Count == 3)
            {
                regionName = newParams [2];
            }

            if (regionFile == "" )
            {
                CreateNewRegion (regionName);
                return;
            }

            // we have a config file and possibly a region name
            IConfig config = m_config.Configs["FileBasedSimulationData"];
            if (config != null)
                defaultDir = PathHelpers.ComputeFullPath (config.GetString ("StoreBackupDirectory", "Regions"));

            regionFile = PathHelpers.VerifyReadFile (regionFile, defaultExt, defaultDir);
            if (regionFile == "")
                return;

            // let's do it...
            MainConsole.Instance.Info ( "[SceneManager]: Loading region definition...." );
            RegionInfo loadRegion = new RegionInfo ();
            loadRegion.LoadRegionConfig( regionFile );

            if (loadRegion.RegionName != regionName)
            {
                if ( MainConsole.Instance.Prompt("You have specified a different name than what is specified in the configuration file\n"+
                    "Do you wish to rename the region to '" + regionName +"'? (yes/no): ") == "yes" )
                {
                    loadRegion.RegionName = regionName;
                }
            }

            //check for an existing Scene
            IScene region = m_scenes.Find((s) => s.RegionInfo.RegionName.ToLower() == regionName);
            if (region != null)
            {
                MainConsole.Instance.InfoFormat(
                    "ERROR: The region '{0}' already exists, please retry", regionName);
                return;
            }

            // indicate this is a new region
            loadRegion.NewRegion = true;

            // get some current details
            var currentInfo = FindCurrentRegionInfo ();

            // let's do it
            ISimulationDataStore store = m_selectedDataService.Copy ();

            var newRegion = store.CreateNewRegion (m_SimBase, loadRegion, currentInfo);
            if (newRegion.RegionName != "abort")
            {
                StartRegion (store, newRegion);

                // backup all our work
                foreach (ISimulationDataStore st in m_simulationDataServices)
                    st.ForceBackup ();
            }
        }
 public GridRegion(RegionInfo ConvertFrom)
 {
     Flags = 0;
     RegionName = ConvertFrom.RegionName;
     RegionType = ConvertFrom.RegionType;
     RegionLocX = ConvertFrom.RegionLocX;
     RegionLocY = ConvertFrom.RegionLocY;
     RegionLocZ = ConvertFrom.RegionLocZ;
     InternalPort = ConvertFrom.RegionPort;
     ExternalHostName = MainServer.Instance.HostName.Replace ("https://", "").Replace ("http://", "");
     HttpPort = MainServer.Instance.Port;
     RegionID = ConvertFrom.RegionID;
     TerrainImage = ConvertFrom.RegionSettings.TerrainImageID;
     TerrainMapImage = ConvertFrom.RegionSettings.TerrainMapImageID;
     ParcelMapImage = ConvertFrom.RegionSettings.ParcelMapImageID;
     Access = ConvertFrom.AccessLevel;
     if (ConvertFrom.EstateSettings != null)
         EstateOwner = ConvertFrom.EstateSettings.EstateOwner;
     RegionSizeX = ConvertFrom.RegionSizeX;
     RegionSizeY = ConvertFrom.RegionSizeY;
     RegionSizeZ = ConvertFrom.RegionSizeZ;
     ScopeID = ConvertFrom.ScopeID;
     AllScopeIDs = ConvertFrom.AllScopeIDs;
     SessionID = ConvertFrom.GridSecureSessionID;
     //            Flags |= (int) RegionFlags.RegionOnline;
     Flags |= ConvertFrom.RegionFlags;                           // not sure why we don't pass all the flags??
     RegionTerrain = ConvertFrom.RegionTerrain;
     RegionArea = ConvertFrom.RegionArea;
 }
        public void StartRegion(ISimulationDataStore simData, RegionInfo regionInfo)
        {
            MainConsole.Instance.InfoFormat("[SceneManager]: Starting region \"{0}\" at @ {1},{2}",
                                            regionInfo.RegionName,
                                            regionInfo.RegionLocX/256, regionInfo.RegionLocY/256);
            ISceneLoader sceneLoader = m_SimBase.ApplicationRegistry.RequestModuleInterface<ISceneLoader>();
            if (sceneLoader == null)
                throw new Exception("No Scene Loader Interface!");

            //Get the new scene from the interface
            IScene scene = sceneLoader.CreateScene(simData, regionInfo);
            m_scenes.Add(scene);

            MainConsole.Instance.ConsoleScenes = m_scenes;
            simData.SetRegion(scene);
            m_simulationDataServices.Add(simData);

            if (OnAddedScene != null)
                OnAddedScene(scene);

            StartModules(scene);

            if (OnFinishedAddingScene != null)
                OnFinishedAddingScene(scene);

            //Start the heartbeats
            scene.StartHeartbeat();
            //Tell the scene that the startup is complete
            // Note: this event is added in the scene constructor
            scene.FinishedStartup("Startup", new List<string>());
        }
        public RegionData LoadBackup(string file)
        {
            if (!File.Exists(file))
                return null;

            var stream = ArchiveHelpers.GetStream(file);
            if (stream == null)
                return null;

            MainConsole.Instance.Warn("[TarRegionDataLoader]: loading region data: " + file);

            GZipStream m_loadStream = new GZipStream(stream, CompressionMode.Decompress);
            TarArchiveReader reader = new TarArchiveReader(m_loadStream);
            List<uint> foundLocalIDs = new List<uint>();
            RegionData regiondata = new RegionData();
            regiondata.Init();

            byte[] data;
            string filePath;
            TarArchiveReader.TarEntryType entryType;
            System.Collections.Concurrent.ConcurrentQueue<byte[]> groups =
                new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
            //Load the archive data that we need
            while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
            {
                MainConsole.Instance.Warn(".");
               	if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
                    continue;

                if (filePath.StartsWith("parcels/"))
                {
                    //Only use if we are not merging
                    LandData parcel = new LandData();
                    OSD parcelData = OSDParser.DeserializeLLSDBinary(data);
                    parcel.FromOSD((OSDMap) parcelData);
                    if (parcel.OwnerID != UUID.Parse("05948863-b678-433e-87a4-e44d17678d1d"))
                        //The default owner of the 'default' region
                        regiondata.Parcels.Add(parcel);
                }
                else if (filePath.StartsWith("newstyleterrain/"))
                {
                    regiondata.Terrain = data;
                }
                else if (filePath.StartsWith("newstylerevertterrain/"))
                {
                    regiondata.RevertTerrain = data;
                }
                else if (filePath.StartsWith("newstylewater/"))
                {
                    regiondata.Water = data;
                }
                else if (filePath.StartsWith("newstylerevertwater/"))
                {
                    regiondata.RevertWater = data;
                }
                else if (filePath.StartsWith("entities/"))
                {
                    groups.Enqueue(data);
                }
                else if (filePath.StartsWith("regioninfo/"))
                {
                    RegionInfo info = new RegionInfo();
                    info.FromOSD((OSDMap) OSDParser.DeserializeLLSDBinary(data));
                    regiondata.RegionInfo = info;
                }
                data = null;
            }
            m_loadStream.Close();
            m_loadStream = null;

            int threadCount = groups.Count > 16 ? 16 : groups.Count;
            System.Threading.Thread[] threads = new System.Threading.Thread[threadCount];
            for (int i = 0; i < threadCount; i++)
            {
                threads[i] = new System.Threading.Thread(() =>
                                                             {
                                                                 byte[] groupData;
                                                                 while (groups.TryDequeue(out groupData))
                                                                 {
                                                                     MemoryStream ms = new MemoryStream(groupData);
                                                                     ISceneEntity sceneObject =
                                                                         SceneEntitySerializer.SceneObjectSerializer
                                                                                              .FromXml2Format(ref ms,
                                                                                                              null);
                                                                     ms.Close();
                                                                     ms = null;
                                                                     data = null;
                                                                     if (sceneObject != null)
                                                                     {
                                                                         foreach (
                                                                             ISceneChildEntity part in
                                                                                 sceneObject.ChildrenEntities())
                                                                         {
                                                                             lock (foundLocalIDs)
                                                                             {
                                                                                 if (
                                                                                     !foundLocalIDs.Contains(
                                                                                         part.LocalId))
                                                                                     foundLocalIDs.Add(part.LocalId);
                                                                                 else
                                                                                     part.LocalId = 0;
                                                                                         //Reset it! Only use it once!
                                                                             }
                                                                         }
                                                                         regiondata.Groups.Add(
                                                                             sceneObject as SceneObjectGroup);
                                                                     }
                                                                 }
                                                             });
                threads[i].Start();
            }
            for (int i = 0; i < threadCount; i++)
                threads[i].Join();

            foundLocalIDs.Clear();

            MainConsole.Instance.Warn("[TarRegionDataLoader]: completed: ");

            return regiondata;
        }
 // Initialize the mesh plugin
 public override void Initialize(IMesher meshmerizer, IScene scene)
 {
     mesher = meshmerizer;
     m_region = scene.RegionInfo;
     m_scene = scene;
     WorldExtents = new Vector2(m_region.RegionSizeX, m_region.RegionSizeY);
 }
        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
            OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
            ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();
            var gridService = webInterface.Registry.RequestModuleInterface<IGridService> ();

            if (requestParameters.ContainsKey("Submit"))
            {

                string RegionServerURL = requestParameters["RegionServerURL"].ToString();
                // required
                if (RegionServerURL == "")  {
                    response = "<h3>" + translator.GetTranslatedString ("RegionServerURLError") + "</h3>";
                    return null;
                }

                string RegionName = requestParameters["RegionName"].ToString();
                string RegionLocX = requestParameters["RegionLocX"].ToString();
                string RegionLocY = requestParameters["RegionLocY"].ToString();
                string RegionSizeX = requestParameters["RegionSizeX"].ToString();
                string RegionSizeY = requestParameters["RegionSizeY"].ToString();

                string RegionType = requestParameters["RegionType"].ToString();
                string RegionPresetType = requestParameters["RegionPresetType"].ToString();
                string RegionTerrain = requestParameters["RegionTerrain"].ToString();

                string RegionLoadTerrain = requestParameters.ContainsKey("RegionLoadTerrain")
                    ? requestParameters["RegionLoadTerrain"].ToString()
                    : "";

                // a bit of idiot proofing
                if (RegionName == "")  {
                    response = "<h3>" + translator.GetTranslatedString ("RegionNameError") + "</h3>";
                    return null;
                }
                if ( (RegionLocX == "") || (RegionLocY == "") )
                {
                    response = "<h3>" + translator.GetTranslatedString ("RegionLocationError") + "</h3>";
                    return null;
                }

                // so far so good...
                // build the new region details
                int RegionPort = int.Parse (requestParameters ["RegionPort"].ToString ());

                var newRegion = new RegionInfo();

                newRegion.RegionName = RegionName;
                newRegion.RegionType = RegionType;
                newRegion.RegionLocX = int.Parse (RegionLocX);
                newRegion.RegionLocY = int.Parse (RegionLocY);
                newRegion.RegionSizeX = int.Parse (RegionSizeX);
                newRegion.RegionSizeY = int.Parse (RegionSizeY);

                newRegion.RegionPort = RegionPort;
                newRegion.SeeIntoThisSimFromNeighbor = true;
                newRegion.InfiniteRegion = false;
                newRegion.ObjectCapacity = 50000;
                newRegion.Startup = StartupType.Normal;

                var regionPreset = RegionPresetType.ToLower ();
                if (regionPreset.StartsWith ("c"))
                {
                    newRegion.RegionPort = int.Parse( requestParameters["RegionPort"].ToString() );
                    newRegion.SeeIntoThisSimFromNeighbor = (requestParameters["RegionVisibility"].ToString().ToLower() == "yes");
                    newRegion.InfiniteRegion = (requestParameters["RegionInfinite"].ToString().ToLower() == "yes");
                    newRegion.ObjectCapacity = int.Parse( requestParameters["RegionCapacity"].ToString() );

                    string delayStartup = requestParameters["RegionDelayStartup"].ToString();
                    newRegion.Startup = delayStartup.StartsWith ("n") ? StartupType.Normal : StartupType.Medium;

                }

                if (regionPreset.StartsWith("w"))
                {
                    // 'standard' setup
                    newRegion.RegionType = newRegion.RegionType + "Universe";
                    newRegion.RegionTerrain = "Flatland";
                    newRegion.Startup = StartupType.Normal;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 50000;
                    newRegion.RegionPort = RegionPort;

                }
                if (regionPreset.StartsWith("o"))
                {
                    // 'Openspace' setup
                    newRegion.RegionType = newRegion.RegionType + "Openspace";
                    if (RegionTerrain.StartsWith("a"))
                        newRegion.RegionTerrain = "Aquatic";
                    else
                        newRegion.RegionTerrain = "Grassland";
                    newRegion.Startup = StartupType.Medium;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 750;
                    newRegion.RegionSettings.AgentLimit = 10;
                    newRegion.RegionSettings.AllowLandJoinDivide = false;
                    newRegion.RegionSettings.AllowLandResell = false;
                }
                if (regionPreset.StartsWith("h"))
                {
                    // 'Homestead' setup
                    newRegion.RegionType = newRegion.RegionType + "Homestead";
                    newRegion.RegionTerrain = "Homestead";
                    newRegion.Startup = StartupType.Medium;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 3750;
                    newRegion.RegionSettings.AgentLimit = 20;
                    newRegion.RegionSettings.AllowLandJoinDivide = false;
                    newRegion.RegionSettings.AllowLandResell = false;
                }

                if (regionPreset.StartsWith("f"))
                {
                    // 'Full Region' setup
                    newRegion.RegionType = newRegion.RegionType + "Full Region";
                    newRegion.RegionTerrain = RegionTerrain;
                    newRegion.Startup = StartupType.Normal;
                    newRegion.SeeIntoThisSimFromNeighbor = true;
                    newRegion.InfiniteRegion = false;
                    newRegion.ObjectCapacity = 15000;
                    newRegion.RegionSettings.AgentLimit = 100;
                    if (newRegion.RegionType.StartsWith ("M")) // defaults are 'true'
                    {
                        newRegion.RegionSettings.AllowLandJoinDivide = false;
                        newRegion.RegionSettings.AllowLandResell = false;
                    }
                }

                if (RegionLoadTerrain.Length > 0)
                {
                    // we are loading terrain from a file... handled later
                    newRegion.RegionTerrain = "Custom";
                }

                response = "<h3>Error creating this region.</h3>";
                return null;
            }

            // we have or need data
            if (httpRequest.Query.ContainsKey ("regionid"))
            {
                var region = gridService.GetRegionByUUID (null, UUID.Parse (httpRequest.Query ["regionid"].ToString ()));

                IEstateConnector estateConnector = Framework.Utilities.DataManager.RequestPlugin<IEstateConnector> ();
                EstateSettings estate = estateConnector.GetEstateSettings (region.RegionID);

                vars.Add ("RegionName", region.RegionName);
                vars.Add ("OwnerUUID", estate.EstateOwner);

                var estateOwnerAccount = webInterface.Registry.RequestModuleInterface<IUserAccountService> ().
                    GetUserAccount (null, estate.EstateOwner);
                vars.Add ("OwnerName", estateOwnerAccount == null ? "No account found" : estateOwnerAccount.Name);
                vars.Add ("RegionLocX", region.RegionLocX / Constants.RegionSize);
                vars.Add ("RegionLocY", region.RegionLocY / Constants.RegionSize);
                vars.Add ("RegionSizeX", region.RegionSizeX);
                vars.Add ("RegionSizeY", region.RegionSizeY);
                vars.Add ("RegionType", region.RegionType);
                vars.Add ("RegionTerrain", region.RegionTerrain);
                vars.Add ("RegionOnline",
                    (region.Flags & (int)RegionFlags.RegionOnline) ==
                    (int)RegionFlags.RegionOnline
                    ? translator.GetTranslatedString ("Online")
                    : translator.GetTranslatedString ("Offline"));

                IWebHttpTextureService webTextureService = webInterface.Registry.
                    RequestModuleInterface<IWebHttpTextureService> ();
                if (webTextureService != null && region.TerrainMapImage != UUID.Zero)
                    vars.Add ("RegionImageURL", webTextureService.GetTextureURL (region.TerrainMapImage));
                else
                    vars.Add ("RegionImageURL", "images/icons/no_picture.jpg");
            }
            else
            {
                // default values

                // check for user name seed
                string[] m_regionNameSeed = null;

                Utilities.MarkovNameGenerator rNames = new Utilities.MarkovNameGenerator();
                string regionName = rNames.FirstName (m_regionNameSeed == null ? Utilities.RegionNames: m_regionNameSeed, 3,7);
                vars.Add ("RegionName", regionName);

                var gconnector = Framework.Utilities.DataManager.RequestPlugin<IGenericsConnector>();
                var settings = gconnector.GetGeneric<WebUISettings>(UUID.Zero, "WebUISettings", "Settings");

                Dictionary<string, int> currentInfo = null;
                if (currentInfo != null)
                {
                    vars.Add ("RegionLocX", currentInfo ["minX"] > 0 ? currentInfo ["minX"] : settings.MapCenter.X);
                    vars.Add ("RegionLocY", currentInfo ["minY"] > 0 ? currentInfo ["minY"] : settings.MapCenter.Y);
                    vars.Add("RegionPort", currentInfo ["port"] > 0 ? currentInfo ["port"] + 1 : 9000);
                } else
                {
                    vars.Add ("RegionLocX", settings.MapCenter.X);
                    vars.Add ("RegionLocY", settings.MapCenter.Y);
                    vars.Add("RegionPort", 9000);

                }

                vars.Add ("RegionSizeX", Constants.RegionSize);
                vars.Add ("RegionSizeY", Constants.RegionSize);
                vars.Add ("RegionType", webInterface.RegionTypeArgs(translator));
                vars.Add ("RegionPresetType", webInterface.RegionPresetArgs(translator));
                vars.Add ("RegionTerrain", webInterface.RegionTerrainArgs(translator));

            }

            // Labels
            vars.Add ("RegionNameText", translator.GetTranslatedString ("RegionNameText"));
            vars.Add ("RegionLocationText", translator.GetTranslatedString ("RegionLocationText"));
            vars.Add ("RegionSizeText", translator.GetTranslatedString ("RegionSizeText"));
            vars.Add ("RegionTypeText", translator.GetTranslatedString ("RegionTypeText"));
            vars.Add ("RegionPresetText", translator.GetTranslatedString ("RegionPresetText"));
            vars.Add ("RegionTerrainText", translator.GetTranslatedString ("RegionTerrainText"));
            vars.Add ("OwnerNameText", translator.GetTranslatedString ("OwnerNameText"));
            vars.Add ("RegionPortText", translator.GetTranslatedString ("RegionPortText"));
            vars.Add ("RegionDelayStartupText", translator.GetTranslatedString ("RegionDelayStartupText"));
            vars.Add ("RegionVisibilityText", translator.GetTranslatedString ("RegionVisibilityText"));
            vars.Add ("RegionInfiniteText", translator.GetTranslatedString ("RegionInfiniteText"));
            vars.Add ("RegionCapacityText", translator.GetTranslatedString ("RegionCapacityText"));
            vars.Add ("Yes", translator.GetTranslatedString ("Yes"));
            vars.Add ("No", translator.GetTranslatedString ("No"));
            vars.Add("Accept", translator.GetTranslatedString("Accept"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));
            vars.Add("SubmitURL", "home.html");
            vars.Add("ErrorMessage", "");
            return vars;
        }