コード例 #1
0
        /// <summary>
        /// Get the current luminosity rating of the place you're in
        /// </summary>
        /// <returns>The current Luminosity</returns>
        public override float GetCurrentLuminosity()
        {
            IZoneTemplate zD        = Template <IZoneTemplate>();
            float         lumins    = 0;
            bool          canSeeSky = IsOutside();

            //TODO: Add cloud cover. Commented out for testing purposes ATM
            if (canSeeSky)
            {
                IGaia world = GetWorld();
                if (world != null)
                {
                    IEnumerable <ICelestialPosition> celestials = world.CelestialPositions;
                    float rotationalPosition = world.PlanetaryRotation;
                    float orbitalPosition    = world.OrbitalPosition;

                    foreach (ICelestialPosition celestial in celestials)
                    {
                        float celestialAffectModifier = AstronomicalUtilities.GetCelestialLuminosityModifier(celestial.CelestialObject, celestial.Position, rotationalPosition, orbitalPosition
                                                                                                             , zD.Hemisphere, world.Template <IGaiaTemplate>().RotationalAngle);

                        lumins += celestial.CelestialObject.Luminosity * celestialAffectModifier;
                    }
                }
            }

            return(lumins);
        }
コード例 #2
0
        public ActionResult EditWorld(string birthMark, ViewGaiaViewModel vModel)
        {
            ApplicationUser authedUser = UserManager.FindById(User.Identity.GetUserId());

            IGaia  obj = LiveCache.Get <IGaia>(new LiveCacheKey(typeof(Gaia), birthMark));
            string message;

            if (obj == null)
            {
                message = "That does not exist";
                return(RedirectToAction("Index", new { Message = message }));
            }

            obj.RotationalAngle     = vModel.DataObject.RotationalAngle;
            obj.OrbitalPosition     = vModel.DataObject.OrbitalPosition;
            obj.Macroeconomy        = vModel.DataObject.Macroeconomy;
            obj.CelestialPositions  = vModel.DataObject.CelestialPositions;
            obj.MeterologicalFronts = vModel.DataObject.MeterologicalFronts;
            obj.CurrentTimeOfDay    = vModel.DataObject.CurrentTimeOfDay;

            obj.Qualities = vModel.DataObject.Qualities;

            if (obj.Save())
            {
                LoggingUtility.LogAdminCommandUsage("*WEB* - LIVE DATA - EditGaia[" + obj.BirthMark + "]", authedUser.GameAccount.GlobalIdentityHandle);
                message = "Edit Successful.";
            }
            else
            {
                message = "Error; Edit failed.";
            }

            return(RedirectToAction("World", new { Message = message, birthMark }));
        }
コード例 #3
0
        public void GetFromWorldOrSpawn()
        {
            //Try to see if they are already there
            IGaia me = LiveCache.Get <IGaia>(TemplateId, typeof(GaiaTemplate));

            //Isn't in the world currently
            if (me == default(IGaia))
            {
                SpawnNewInWorld();
            }
            else
            {
                BirthMark           = me.BirthMark;
                Birthdate           = me.Birthdate;
                TemplateId          = me.TemplateId;
                Keywords            = me.Keywords;
                CurrentLocation     = null;
                CurrentTimeOfDay    = me.CurrentTimeOfDay;
                MeterologicalFronts = me.MeterologicalFronts;
                Macroeconomy        = me.Macroeconomy;
                CelestialPositions  = me.CelestialPositions;
                RotationalAngle     = me.RotationalAngle;

                Qualities = me.Qualities;

                CurrentLocation = null;
                KickoffProcesses();
            }
        }
コード例 #4
0
        /// <summary>
        /// Get the visibile celestials. Depends on luminosity, viewer perception and celestial positioning
        /// </summary>
        /// <param name="viewer">Whom is looking</param>
        /// <returns>What celestials are visible</returns>
        public override IEnumerable <ICelestial> GetVisibileCelestials(IEntity viewer)
        {
            IZoneTemplate zD        = Template <IZoneTemplate>();
            bool          canSeeSky = IsOutside(); //TODO: cloud cover

            List <ICelestial> returnList = new List <ICelestial>();

            if (!canSeeSky)
            {
                return(returnList);
            }

            IGaia world = GetWorld();
            IEnumerable <ICelestialPosition> celestials = world.CelestialPositions;

            if (celestials.Count() > 0)
            {
                //TODO: Add cloud cover stuff
                float rotationalPosition = world.PlanetaryRotation;
                float orbitalPosition    = world.OrbitalPosition;
                float currentBrightness  = GetCurrentLuminosity();

                foreach (ICelestialPosition celestial in celestials)
                {
                    float celestialLumins = celestial.CelestialObject.Luminosity * AstronomicalUtilities.GetCelestialLuminosityModifier(celestial.CelestialObject, celestial.Position, rotationalPosition, orbitalPosition
                                                                                                                                        , zD.Hemisphere, world.Template <IGaiaTemplate>().RotationalAngle);

                    //how washed out is this thing compared to how bright the room is
                    if (celestialLumins / currentBrightness > 0.01)
                    {
                        returnList.Add(celestial.CelestialObject);
                    }
                }
            }

            return(returnList);
        }
コード例 #5
0
ファイル: HotBackup.cs プロジェクト: envis10n/Warrens
        /// <summary>
        /// Something went wrong with restoring the live backup, this loads all persistence singeltons from the database (rooms, paths, spawns)
        /// </summary>
        /// <returns>success state</returns>
        public bool NewWorldFallback()
        {
            LiveData liveDataAccessor = new LiveData();

            //This means we delete the entire Current livedata dir since we're falling back.
            string currentLiveDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName;

            //No backup directory? No live data.
            if (Directory.Exists(currentLiveDirectory))
            {
                DirectoryInfo currentDir = new DirectoryInfo(currentLiveDirectory);

                LoggingUtility.Log("Current Live directory deleted during New World Fallback Procedures.", LogChannels.Backup, true);

                try
                {
                    currentDir.Delete(true);
                }
                catch
                {
                    //occasionally will be pissy in an async situation
                }
            }

            //Only load in stuff that is static and spawns as singleton
            //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\
            foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>())
            {
                IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia;
            }

            foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>())
            {
                IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone;
            }

            foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>())
            {
                ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale;

                entityThing.ParentLocation = entityThing.Template <ILocaleTemplate>().ParentLocation.GetLiveInstance();
                entityThing.GetFromWorldOrSpawn();
            }

            foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>())
            {
                IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom;

                entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance();
                entityThing.GetFromWorldOrSpawn();
            }

            foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>())
            {
                IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway;
            }

            ParseDimension();

            LoggingUtility.Log("World restored from data fallback.", LogChannels.Backup, true);

            return(true);
        }
コード例 #6
0
ファイル: HotBackup.cs プロジェクト: envis10n/Warrens
        /// <summary>
        /// Restores live entity backup from Current
        /// </summary>
        /// <returns>Success state</returns>
        public bool RestoreLiveBackup()
        {
            LiveData liveDataAccessor = new LiveData();

            string currentBackupDirectory = liveDataAccessor.BaseDirectory + liveDataAccessor.CurrentDirectoryName;

            //No backup directory? No live data.
            if (!Directory.Exists(currentBackupDirectory))
            {
                return(false);
            }

            LoggingUtility.Log("World restored from current live INITIATED.", LogChannels.Backup, false);

            try
            {
                //dont load players here
                List <IEntity>     entitiesToLoad   = new List <IEntity>();
                IEnumerable <Type> implimentedTypes = typeof(EntityPartial).Assembly.GetTypes().Where(ty => ty.GetInterfaces().Contains(typeof(IEntity)) &&
                                                                                                      ty.IsClass &&
                                                                                                      !ty.IsAbstract &&
                                                                                                      !ty.GetCustomAttributes <IgnoreAutomatedBackupAttribute>().Any());

                foreach (Type type in implimentedTypes.OrderByDescending(type => type == typeof(Gaia) ? 6 :
                                                                         type == typeof(Zone) ? 5 :
                                                                         type == typeof(Locale) ? 3 :
                                                                         type == typeof(Room) ? 3 :
                                                                         type == typeof(Pathway) ? 2 : 0))
                {
                    if (!Directory.Exists(currentBackupDirectory + type.Name))
                    {
                        continue;
                    }

                    DirectoryInfo entityFilesDirectory = new DirectoryInfo(currentBackupDirectory + type.Name);

                    foreach (FileInfo file in entityFilesDirectory.EnumerateFiles())
                    {
                        entitiesToLoad.Add(liveDataAccessor.ReadEntity(file, type));
                    }
                }

                //Check we found actual data
                if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Gaia)))
                {
                    throw new Exception("No Worlds found, failover.");
                }

                if (!entitiesToLoad.Any(ent => ent.GetType() == typeof(Zone)))
                {
                    throw new Exception("No zones found, failover.");
                }

                //Shove them all into the live system first
                foreach (IEntity entity in entitiesToLoad.OrderBy(ent => ent.Birthdate))
                {
                    entity.UpsertToLiveWorldCache();
                    entity.KickoffProcesses();
                }

                //We need to pick up any places that aren't already live from the file system incase someone added them during the last session\
                foreach (IGaiaTemplate thing in TemplateCache.GetAll <IGaiaTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised)))
                {
                    IGaia entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IGaia;

                    entityThing.SpawnNewInWorld();
                }

                foreach (IZoneTemplate thing in TemplateCache.GetAll <IZoneTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised)))
                {
                    IZone entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IZone;

                    entityThing.SpawnNewInWorld();
                }

                foreach (ILocaleTemplate thing in TemplateCache.GetAll <ILocaleTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised)))
                {
                    ILocale entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as ILocale;

                    entityThing.ParentLocation = entityThing.ParentLocation.GetLiveInstance();
                    entityThing.SpawnNewInWorld();
                }

                foreach (IRoomTemplate thing in TemplateCache.GetAll <IRoomTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised)))
                {
                    IRoom entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IRoom;

                    entityThing.ParentLocation = entityThing.Template <IRoomTemplate>().ParentLocation.GetLiveInstance();
                    entityThing.SpawnNewInWorld();
                }

                foreach (IPathwayTemplate thing in TemplateCache.GetAll <IPathwayTemplate>().Where(dt => !entitiesToLoad.Any(ent => ent.TemplateId.Equals(dt.Id) && ent.Birthdate >= dt.LastRevised)))
                {
                    IPathway entityThing = Activator.CreateInstance(thing.EntityClass, new object[] { thing }) as IPathway;

                    entityThing.SpawnNewInWorld();
                }

                //We have the containers contents and the birthmarks from the deserial
                //I don't know how we can even begin to do this type agnostically since the collections are held on type specific objects without some super ugly reflection
                foreach (Room entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Room)))
                {
                    foreach (IInanimate obj in entity.Contents.EntitiesContained())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }

                    foreach (INonPlayerCharacter obj in entity.MobilesInside.EntitiesContained())
                    {
                        INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }
                }

                foreach (NonPlayerCharacter entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(NonPlayerCharacter)))
                {
                    foreach (IInanimate obj in entity.Inventory.EntitiesContained())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj));
                        entity.MoveFrom(obj);
                        entity.MoveInto(fullObj);
                    }
                }

                foreach (Inanimate entity in entitiesToLoad.Where(ent => ent.GetType() == typeof(Inanimate)))
                {
                    foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName())
                    {
                        IInanimate fullObj = LiveCache.Get <IInanimate>(new LiveCacheKey(obj.Item2));
                        entity.MoveFrom(obj.Item2);
                        entity.MoveInto(fullObj, obj.Item1);
                    }

                    foreach (Tuple <string, IInanimate> obj in entity.Contents.EntitiesContainedByName())
                    {
                        INonPlayerCharacter fullObj = LiveCache.Get <INonPlayerCharacter>(new LiveCacheKey(obj.Item2));
                        entity.MoveFrom((INonPlayerCharacter)obj.Item2);
                        entity.MoveInto(fullObj, obj.Item1);
                    }
                }

                //We need to poll the WorldMaps here and give all the rooms their coordinates as well as the zones their sub-maps
                ParseDimension();

                LoggingUtility.Log("World restored from current live.", LogChannels.Backup, false);
                return(true);
            }
            catch (Exception ex)
            {
                LoggingUtility.LogError(ex);
            }

            return(false);
        }
コード例 #7
0
        /// <summary>
        /// Wraps sending messages to the connected descriptor
        /// </summary>
        /// <param name="strings">the output</param>
        /// <returns>success status</returns>
        public bool SendOutput(IEnumerable <string> strings)
        {
            //TODO: Stop hardcoding this but we have literally no sense of injury/self status yet
            SelfStatus self = new SelfStatus
            {
                Body = new BodyStatus
                {
                    Health  = _currentPlayer.CurrentHealth == 0 ? 100 : 100 / (2M * _currentPlayer.CurrentHealth),
                    Stamina = _currentPlayer.CurrentStamina,
                    Overall = OverallStatus.Excellent,
                    Anatomy = new AnatomicalPart[] {
                        new AnatomicalPart {
                            Name    = "Arm",
                            Overall = OverallStatus.Good,
                            Wounds  = new string[] {
                                "Light scrape"
                            }
                        },
                        new AnatomicalPart {
                            Name    = "Leg",
                            Overall = OverallStatus.Excellent,
                            Wounds  = new string[] {
                            }
                        }
                    }
                },
                CurrentActivity = _currentPlayer.CurrentAction,
                Balance         = _currentPlayer.Balance.ToString(),
                CurrentArt      = _currentPlayer.LastAttack?.Name ?? "",
                CurrentCombo    = _currentPlayer.LastCombo?.Name ?? "",
                CurrentTarget   = _currentPlayer.GetTarget() == null ? ""
                                                                   : _currentPlayer.GetTarget() == _currentPlayer
                                                                        ? "Your shadow"
                                                                        : _currentPlayer.GetTarget().GetDescribableName(_currentPlayer),
                CurrentTargetHealth = _currentPlayer.GetTarget() == null || _currentPlayer.GetTarget() == _currentPlayer ? double.PositiveInfinity
                                                                        : _currentPlayer.GetTarget().CurrentHealth == 0 ? 100 : 100 / (2 * _currentPlayer.CurrentHealth),
                Position  = _currentPlayer.StancePosition.ToString(),
                Stance    = _currentPlayer.Stance,
                Stagger   = _currentPlayer.Stagger.ToString(),
                Qualities = string.Join("", _currentPlayer.Qualities.Where(quality => quality.Visible).Select(quality => string.Format("<div class='qualityRow'><span>{0}</span><span>{1}</span></div>", quality.Name, quality.Value))),
                CurrentTargetQualities = _currentPlayer.GetTarget() == null || _currentPlayer.GetTarget() == _currentPlayer ? ""
                                                                            : string.Join("", _currentPlayer.GetTarget().Qualities.Where(quality => quality.Visible).Select(quality => string.Format("<div class='qualityRow'><span>{0}</span><span>{1}</span></div>", quality.Name, quality.Value))),
                Mind = new MindStatus
                {
                    Overall = OverallStatus.Excellent,
                    States  = new string[]
                    {
                        "Fearful"
                    }
                }
            };

            IGlobalPosition currentLocation  = _currentPlayer.CurrentLocation;
            IContains       currentContainer = currentLocation.CurrentLocation();
            IZone           currentZone      = currentContainer.CurrentLocation.CurrentZone;
            ILocale         currentLocale    = currentLocation.CurrentLocale;
            IRoom           currentRoom      = currentLocation.CurrentRoom;
            IGaia           currentWorld     = currentZone.GetWorld();

            IEnumerable <string> pathways  = Enumerable.Empty <string>();
            IEnumerable <string> inventory = Enumerable.Empty <string>();
            IEnumerable <string> populace  = Enumerable.Empty <string>();
            string locationDescription     = string.Empty;

            LexicalContext lexicalContext = new LexicalContext(_currentPlayer)
            {
                Language    = _currentPlayer.Template <IPlayerTemplate>().Account.Config.UILanguage,
                Perspective = NarrativePerspective.SecondPerson,
                Position    = LexicalPosition.Near
            };

            Message toCluster = new Message(currentContainer.RenderToVisible(_currentPlayer));

            if (currentContainer != null)
            {
                pathways            = ((ILocation)currentContainer).GetPathways().Select(data => data.GetDescribableName(_currentPlayer));
                inventory           = currentContainer.GetContents <IInanimate>().Select(data => data.GetDescribableName(_currentPlayer));
                populace            = currentContainer.GetContents <IMobile>().Where(player => !player.Equals(_currentPlayer)).Select(data => data.GetDescribableName(_currentPlayer));
                locationDescription = toCluster.Unpack(TargetEntity.Actor, lexicalContext);
            }

            LocalStatus local = new LocalStatus
            {
                ZoneName            = currentZone?.TemplateName,
                LocaleName          = currentLocale?.TemplateName,
                RoomName            = currentRoom?.TemplateName,
                Inventory           = inventory.ToArray(),
                Populace            = populace.ToArray(),
                Exits               = pathways.ToArray(),
                LocationDescriptive = locationDescription
            };

            //The next two are mostly hard coded, TODO, also fix how we get the map as that's an admin thing
            ExtendedStatus extended = new ExtendedStatus
            {
                Horizon = new string[]
                {
                    "A hillside",
                    "A dense forest"
                },
                VisibleMap = currentLocation.CurrentRoom == null ? string.Empty : currentLocation.CurrentRoom.RenderCenteredMap(3, true)
            };

            string timeOfDayString = string.Format("The hour of {0} in the day of {1} in {2} in the year of {3}", currentWorld.CurrentTimeOfDay.Hour
                                                   , currentWorld.CurrentTimeOfDay.Day
                                                   , currentWorld.CurrentTimeOfDay.MonthName()
                                                   , currentWorld.CurrentTimeOfDay.Year);

            string sun              = "0";
            string moon             = "0";
            string visibilityString = "5";
            Tuple <string, string, string[]> weatherTuple = new Tuple <string, string, string[]>("", "", new string[] { });

            if (currentZone != null)
            {
                Tuple <PrecipitationAmount, PrecipitationType, HashSet <WeatherType> > forecast = currentZone.CurrentForecast();
                weatherTuple = new Tuple <string, string, string[]>(forecast.Item1.ToString(), forecast.Item2.ToString(), forecast.Item3.Select(wt => wt.ToString()).ToArray());

                visibilityString = currentZone.GetCurrentLuminosity().ToString();

                if (currentWorld != null)
                {
                    IEnumerable <ICelestial> bodies = currentZone.GetVisibileCelestials(_currentPlayer);
                    ICelestial theSun  = bodies.FirstOrDefault(cest => cest.Name.Equals("sun", StringComparison.InvariantCultureIgnoreCase));
                    ICelestial theMoon = bodies.FirstOrDefault(cest => cest.Name.Equals("moon", StringComparison.InvariantCultureIgnoreCase));

                    if (theSun != null)
                    {
                        ICelestialPosition celestialPosition = currentWorld.CelestialPositions.FirstOrDefault(celest => celest.CelestialObject == theSun);

                        sun = AstronomicalUtilities.GetCelestialLuminosityModifier(celestialPosition.CelestialObject, celestialPosition.Position, currentWorld.PlanetaryRotation
                                                                                   , currentWorld.OrbitalPosition, currentZone.Template <IZoneTemplate>().Hemisphere, currentWorld.Template <IGaiaTemplate>().RotationalAngle).ToString();
                    }

                    if (theMoon != null)
                    {
                        ICelestialPosition celestialPosition = currentWorld.CelestialPositions.FirstOrDefault(celest => celest.CelestialObject == theMoon);

                        moon = AstronomicalUtilities.GetCelestialLuminosityModifier(celestialPosition.CelestialObject, celestialPosition.Position, currentWorld.PlanetaryRotation
                                                                                    , currentWorld.OrbitalPosition, currentZone.Template <IZoneTemplate>().Hemisphere, currentWorld.Template <IGaiaTemplate>().RotationalAngle).ToString();
                    }
                }
            }

            EnvironmentStatus environment = new EnvironmentStatus
            {
                Sun         = sun,
                Moon        = moon,
                Visibility  = visibilityString,
                Weather     = weatherTuple,
                Temperature = currentZone.EffectiveTemperature().ToString(),
                Humidity    = currentZone.EffectiveHumidity().ToString(),
                TimeOfDay   = timeOfDayString
            };

            OutputStatus outputFormat = new OutputStatus
            {
                Occurrence  = EncapsulateOutput(strings),
                Self        = self,
                Local       = local,
                Extended    = extended,
                Environment = environment
            };

            Send(Utility.SerializationUtility.Serialize(outputFormat));

            return(true);
        }