public override void Reset()
        {
            base.Reset();

            getInfo = TimeInfo.TimeSinceLevelLoad;
            storeValue = null;
        }
 private static void FillInTimeInfo(ref TimeInfo timeInfo, byte[] timeBytes, int length, byte scale)
 {
     long num = (timeBytes[0] + (timeBytes[1] << 8)) + (timeBytes[2] << 0x10);
     if (length > 3)
     {
         num += timeBytes[3] << 0x18;
     }
     if (length > 4)
     {
         num += timeBytes[4] << 0x20;
     }
     timeInfo.ticks = num * TdsEnums.TICKS_FROM_SCALE[scale];
     timeInfo.scale = scale;
 }
Esempio n. 3
0
        public void CheckAddingResults()
        {
            var sut  = new TestRun("someFileName", "myComputer");
            var time = new TimeInfo(DateTime.Now - new TimeSpan(500), DateTime.Now);

            sut.AddTestResult("MyTest", true, time, "All fine", "");

            Assert.That(sut.Results.UnitTestResults.Count, Is.EqualTo(1), "No results added to unittestresults");
            Assert.That(sut.TestDefinitions.UnitTests.Count, Is.EqualTo(1), "No testdefinitions added");
            Assert.That(sut.TestEntries.TestEntryList.Count, Is.EqualTo(1), "No test entries added");

            var utr = sut.Results.UnitTestResults.First();

            Assert.That(utr, Is.Not.Null, "UnitTestResult is empty/null");

            var xml = sut.SerializeObjectWithOutNamespace(ns);

            Assert.That(xml.Contains("UnitTestResults"), Is.False,
                        "Contains UnitTestResults string, should only be array elements");
            Assert.That(xml.Contains("<UnitTestResult"), "xml.Contains('<UnitTestResult')");
            var tr = ExtractSegment(xml, "<UnitTestResult", "</UnitTestResult");

            Assert.That(tr.Contains("testName=\"MyTest"), "tr.Contains('testName=\'MyTest')");
        }
 public override void Reset()
 {
     getInfo = TimeInfo.TimeSinceLevelLoad;
     storeValue = null;
     everyFrame = false;
     updateType = PlayMakerActionsUtils.EveryFrameUpdateSelector.OnUpdate;
 }
Esempio n. 5
0
        private static void FillInTimeInfo(ref TimeInfo timeInfo, byte[] timeBytes, int length, byte scale, byte denormalizedScale) {
            Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length);
            Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale);
            Debug.Assert(0 <= denormalizedScale && denormalizedScale <= 7, "invalid denormalized scale: " + denormalizedScale);

            Int64 tickUnits = (Int64)timeBytes[0] + ((Int64)timeBytes[1] << 8) + ((Int64)timeBytes[2] << 16);
            if (length > 3) {
                tickUnits += ((Int64)timeBytes[3] << 24);
            }
            if (length > 4) {
                tickUnits += ((Int64)timeBytes[4] << 32);
            }
            timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale];

            // Once the deserialization has been completed using the value scale, we need to set the actual denormalized scale, 
            // coming from the data type, on the original result, so that it has the proper scale setting.
            // This only applies for values that got serialized/deserialized for encryption. Otherwise, both scales should be equal.
            timeInfo.scale = denormalizedScale;
        }
Esempio n. 6
0
    private async Task <ICollection <StackSummaryModel> > GetStackSummariesAsync(ICollection <Stack> stacks, IReadOnlyCollection <KeyedBucket <string> > stackTerms, AppFilter sf, TimeInfo ti)
    {
        if (stacks.Count == 0)
        {
            return(new List <StackSummaryModel>(0));
        }

        var totalUsers = await GetUserCountByProjectIdsAsync(stacks, sf, ti.Range.UtcStart, ti.Range.UtcEnd);

        return(stacks.Join(stackTerms, s => s.Id, tk => tk.Key, (stack, term) => {
            var data = _formattingPluginManager.GetStackSummaryData(stack);
            var summary = new StackSummaryModel {
                TemplateKey = data.TemplateKey,
                Data = data.Data,
                Id = stack.Id,
                Title = stack.Title,
                Status = stack.Status,
                FirstOccurrence = term.Aggregations.Min <DateTime>("min_date").Value,
                LastOccurrence = term.Aggregations.Max <DateTime>("max_date").Value,
                Total = (long)(term.Aggregations.Sum("sum_count").Value ?? term.Total.GetValueOrDefault()),

                Users = term.Aggregations.Cardinality("cardinality_user").Value.GetValueOrDefault(),
                TotalUsers = totalUsers.GetOrDefault(stack.ProjectId)
            };

            return summary;
        }).ToList());
    }
Esempio n. 7
0
    private async Task <ActionResult <IReadOnlyCollection <Stack> > > GetInternalAsync(AppFilter sf, TimeInfo ti, string filter = null, string sort = null, string mode = null, int page = 1, int limit = 10)
    {
        page  = GetPage(page);
        limit = GetLimit(limit);
        int skip = GetSkip(page, limit);

        if (skip > MAXIMUM_SKIP)
        {
            return(Ok(EmptyModels));
        }

        var pr = await _validator.ValidateQueryAsync(filter);

        if (!pr.IsValid)
        {
            return(BadRequest(pr.Message));
        }

        sf.UsesPremiumFeatures = pr.UsesPremiumFeatures;

        try {
            var results = await _repository.FindAsync(q => q.AppFilter(ShouldApplySystemFilter(sf, filter) ? sf : null).FilterExpression(filter).SortExpression(sort).DateRange(ti.Range.UtcStart, ti.Range.UtcEnd, ti.Field), o => o.PageNumber(page).PageLimit(limit));

            var stacks = results.Documents.Select(s => s.ApplyOffset(ti.Offset)).ToList();
            if (!String.IsNullOrEmpty(mode) && String.Equals(mode, "summary", StringComparison.OrdinalIgnoreCase))
            {
                return(OkWithResourceLinks(await GetStackSummariesAsync(stacks, sf, ti), results.HasMore && !NextPageExceedsSkipLimit(page, limit), page));
            }

            return(OkWithResourceLinks(stacks, results.HasMore && !NextPageExceedsSkipLimit(page, limit), page));
        }
        catch (ApplicationException ex) {
            using (_logger.BeginScope(new ExceptionlessState().Property("Search Filter", new { SystemFilter = sf, UserFilter = filter, Time = ti, Page = page, Limit = limit }).Tag("Search").Identity(CurrentUser.EmailAddress).Property("User", CurrentUser).SetHttpContext(HttpContext)))
                _logger.LogError(ex, "An error has occurred. Please check your search filter.");

            return(BadRequest("An error has occurred. Please check your search filter."));
        }
    }
Esempio n. 8
0
        public static RealTimeCore Run(
            ConfigurationProvider <RealTimeConfig> configProvider,
            string rootPath,
            ILocalizationProvider localizationProvider,
            bool setDefaultTime,
            Compatibility compatibility)
        {
            if (configProvider == null)
            {
                throw new ArgumentNullException(nameof(configProvider));
            }

            if (string.IsNullOrEmpty(rootPath))
            {
                throw new ArgumentException("The root path cannot be null or empty string", nameof(rootPath));
            }

            if (localizationProvider == null)
            {
                throw new ArgumentNullException(nameof(localizationProvider));
            }

            if (compatibility == null)
            {
                throw new ArgumentNullException(nameof(compatibility));
            }

            var patches = GetMethodPatches(compatibility);
            var patcher = new MethodPatcher(HarmonyId, patches);

            var appliedPatches = patcher.Apply();

            if (!CheckRequiredMethodPatches(appliedPatches))
            {
                Log.Error("The 'Real Time' mod failed to perform method redirections for required methods");
                patcher.Revert();
                return(null);
            }

            if (StorageBase.CurrentLevelStorage != null)
            {
                LoadStorageData(new[] { configProvider }, StorageBase.CurrentLevelStorage);
            }

            localizationProvider.SetEnglishUSFormatsState(configProvider.Configuration.UseEnglishUSFormats);

            var timeInfo        = new TimeInfo(configProvider.Configuration);
            var buildingManager = new BuildingManagerConnection();
            var randomizer      = new GameRandomizer();

            var weatherInfo = new WeatherInfo(new WeatherManagerConnection(), randomizer);

            var gameConnections = new GameConnections <Citizen>(
                timeInfo,
                new CitizenConnection(),
                new CitizenManagerConnection(),
                buildingManager,
                randomizer,
                new TransferManagerConnection(),
                weatherInfo);

            var eventManager = new RealTimeEventManager(
                configProvider.Configuration,
                CityEventsLoader.Instance,
                new EventManagerConnection(),
                buildingManager,
                randomizer,
                timeInfo,
                Constants.MaxTravelTime);

            if (!SetupCustomAI(timeInfo, configProvider.Configuration, gameConnections, eventManager, compatibility))
            {
                Log.Error("The 'Real Time' mod failed to setup the customized AI and will now be deactivated.");
                patcher.Revert();
                return(null);
            }

            var timeAdjustment = new TimeAdjustment(configProvider.Configuration);
            var gameDate       = timeAdjustment.Enable(setDefaultTime);

            SimulationHandler.CitizenProcessor.UpdateFrameDuration();

            CityEventsLoader.Instance.ReloadEvents(rootPath);

            var customTimeBar = new CustomTimeBar();

            customTimeBar.Enable(gameDate);
            customTimeBar.CityEventClick += CustomTimeBarCityEventClick;

            var vanillaEvents = VanillaEvents.Customize();

            var result = new RealTimeCore(timeAdjustment, customTimeBar, eventManager, patcher, vanillaEvents);

            eventManager.EventsChanged += result.CityEventsChanged;

            var statistics = new Statistics(timeInfo, localizationProvider);

            if (statistics.Initialize())
            {
                statistics.RefreshUnits();
            }
            else
            {
                statistics = null;
            }

            SimulationHandler.NewDay += result.CityEventsChanged;

            SimulationHandler.TimeAdjustment    = timeAdjustment;
            SimulationHandler.DayTimeSimulation = new DayTimeSimulation(configProvider.Configuration);
            SimulationHandler.EventManager      = eventManager;
            SimulationHandler.WeatherInfo       = weatherInfo;
            SimulationHandler.Buildings         = BuildingAIPatch.RealTimeAI;
            SimulationHandler.Buildings.UpdateFrameDuration();

            if (appliedPatches.Contains(CitizenManagerPatch.CreateCitizenPatch1))
            {
                CitizenManagerPatch.NewCitizenBehavior = new NewCitizenBehavior(randomizer, configProvider.Configuration);
            }

            if (appliedPatches.Contains(BuildingAIPatch.GetColor))
            {
                SimulationHandler.Buildings.InitializeLightState();
            }

            SimulationHandler.Statistics = statistics;

            if (appliedPatches.Contains(WorldInfoPanelPatch.UpdateBindings))
            {
                WorldInfoPanelPatch.CitizenInfoPanel     = CustomCitizenInfoPanel.Enable(ResidentAIPatch.RealTimeAI, localizationProvider);
                WorldInfoPanelPatch.VehicleInfoPanel     = CustomVehicleInfoPanel.Enable(ResidentAIPatch.RealTimeAI, localizationProvider);
                WorldInfoPanelPatch.CampusWorldInfoPanel = CustomCampusWorldInfoPanel.Enable(localizationProvider);
            }

            AwakeSleepSimulation.Install(configProvider.Configuration);

            var schedulesStorage = ResidentAIPatch.RealTimeAI.GetStorageService(
                schedules => new CitizenScheduleStorage(schedules, gameConnections.CitizenManager.GetCitizensArray, timeInfo));

            result.storageData.Add(schedulesStorage);
            result.storageData.Add(eventManager);
            if (StorageBase.CurrentLevelStorage != null)
            {
                StorageBase.CurrentLevelStorage.GameSaving += result.GameSaving;
                LoadStorageData(result.storageData, StorageBase.CurrentLevelStorage);
            }

            result.storageData.Add(configProvider);
            result.Translate(localizationProvider);
            result.IsRestrictedMode = appliedPatches.Count != patches.Count;

            return(result);
        }
Esempio n. 9
0
 public void SetData(TimeInfo t)
 {
     hour   = t.hour;
     minute = t.minute;
 }
Esempio n. 10
0
 public override void Handle(GameSession session, PacketReader packet)
 {
     session.Player.HouseDoctorAccessTime = TimeInfo.Now();
 }
Esempio n. 11
0
        public static RealTimeCore Run(RealTimeConfig config, string rootPath, ILocalizationProvider localizationProvider)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (string.IsNullOrEmpty(rootPath))
            {
                throw new ArgumentException("The root path cannot be null or empty string", nameof(rootPath));
            }

            if (localizationProvider == null)
            {
                throw new ArgumentNullException(nameof(localizationProvider));
            }

            var patcher = new MethodPatcher(
                BuildingAIPatches.PrivateConstructionTime,
                BuildingAIPatches.PrivateHandleWorkers,
                BuildingAIPatches.CommercialSimulation,
                ResidentAIPatch.Location,
                ResidentAIPatch.ArriveAtDestination,
                TouristAIPatch.Location,
                UIGraphPatches.MinDataPoints,
                UIGraphPatches.VisibleEndTime,
                UIGraphPatches.BuildLabels);

            try
            {
                patcher.Apply();
                Log.Info("The 'Real Time' successfully performed the methods redirections");
            }
            catch (Exception ex)
            {
                Log.Error("The 'Real Time' mod failed to perform method redirections: " + ex);
                patcher.Revert();
                return(null);
            }

            var timeInfo        = new TimeInfo(config);
            var buildingManager = new BuildingManagerConnection();
            var randomizer      = new GameRandomizer();

            var weatherInfo = new WeatherInfo(new WeatherManagerConnection());

            var gameConnections = new GameConnections <Citizen>(
                timeInfo,
                new CitizenConnection(),
                new CitizenManagerConnection(),
                buildingManager,
                randomizer,
                new TransferManagerConnection(),
                weatherInfo);

            var eventManager = new RealTimeEventManager(
                config,
                CityEventsLoader.Instance,
                new EventManagerConnection(),
                buildingManager,
                randomizer,
                timeInfo);

            if (!SetupCustomAI(timeInfo, config, gameConnections, eventManager))
            {
                Log.Error("The 'Real Time' mod failed to setup the customized AI and will now be deactivated.");
                patcher.Revert();
                return(null);
            }

            var      timeAdjustment = new TimeAdjustment(config);
            DateTime gameDate       = timeAdjustment.Enable();

            SimulationHandler.CitizenProcessor.SetFrameDuration(timeAdjustment.HoursPerFrame);

            CityEventsLoader.Instance.ReloadEvents(rootPath);

            var customTimeBar = new CustomTimeBar();

            customTimeBar.Enable(gameDate);
            customTimeBar.CityEventClick += CustomTimeBarCityEventClick;

            var result = new RealTimeCore(timeAdjustment, customTimeBar, eventManager, patcher);

            eventManager.EventsChanged += result.CityEventsChanged;
            SimulationHandler.NewDay   += result.CityEventsChanged;

            SimulationHandler.TimeAdjustment    = timeAdjustment;
            SimulationHandler.DayTimeSimulation = new DayTimeSimulation(config);
            SimulationHandler.EventManager      = eventManager;
            SimulationHandler.WeatherInfo       = weatherInfo;
            SimulationHandler.Buildings         = BuildingAIPatches.RealTimeAI;

            AwakeSleepSimulation.Install(config);

            RealTimeStorage.CurrentLevelStorage.GameSaving += result.GameSaving;
            result.storageData.Add(eventManager);
            result.storageData.Add(ResidentAIPatch.RealTimeAI.GetStorageService());
            result.LoadStorageData();

            result.Translate(localizationProvider);

            return(result);
        }
Esempio n. 12
0
 public void GetLunisolarYearTest()
 {
     Assert.AreEqual("丁酉", TimeInfo.GetLunisolarYear(2017));
 }
Esempio n. 13
0
 public void GetChineseZodiacTest()
 {
     Assert.AreEqual("鸡", TimeInfo.GetChineseZodiac(2017));
 }
Esempio n. 14
0
 public void GetChineseDateTimeTest()
 {
     Assert.AreEqual("丁酉[鸡]年三月初九", TimeInfo.GetChineseDateTime(new DateTime(2017, 4, 5)));
 }
Esempio n. 15
0
 public void GetLunisolarMonthTest()
 {
     Assert.AreEqual("腊", TimeInfo.GetLunisolarMonth(12));
     Assert.AreEqual("十一", TimeInfo.GetLunisolarMonth(11));
 }
Esempio n. 16
0
 public override void Reset()
 {
     base.Reset();
     getInfo    = TimeInfo.TimeSinceLevelLoad;
     storeValue = null;
 }
Esempio n. 17
0
 public override void Reset()
 {
     getInfo = TimeInfo.TimeSinceLevelLoad;
     storeValue = null;
     everyFrame = false;
 }
Esempio n. 18
0
    private static void HandleAddExplorationQuests(GameSession session, PacketReader packet)
    {
        int listSize = packet.ReadInt();

        for (int i = 0; i < listSize; i++)
        {
            int questId = packet.ReadInt();
            session.Player.QuestData.TryGetValue(questId, out QuestStatus questStatus);

            if (questStatus is null)
            {
                questStatus = new(session.Player.CharacterId, questId, QuestState.Started, TimeInfo.Now(), accepted : true);
                session.Player.QuestData.Add(questId, questStatus);
                session.Send(QuestPacket.AcceptQuest(questStatus));
                continue;
            }

            questStatus.State          = QuestState.Started;
            questStatus.StartTimestamp = TimeInfo.Now();
            questStatus.Accepted       = true;
            DatabaseManager.Quests.Update(questStatus);
            session.Send(QuestPacket.AcceptQuest(questStatus));
        }
    }
Esempio n. 19
0
        private static bool SetupCustomAI(
            TimeInfo timeInfo,
            RealTimeConfig config,
            GameConnections <Citizen> gameConnections,
            RealTimeEventManager eventManager,
            Compatibility compatibility)
        {
            var residentAIConnection = ResidentAIPatch.GetResidentAIConnection();

            if (residentAIConnection == null)
            {
                return(false);
            }

            float travelDistancePerCycle = compatibility.IsAnyModActive(WorkshopMods.RealisticWalkingSpeed)
                ? Constants.AverageTravelDistancePerCycle * 0.583f
                : Constants.AverageTravelDistancePerCycle;

            var spareTimeBehavior = new SpareTimeBehavior(config, timeInfo);
            var travelBehavior    = new TravelBehavior(gameConnections.BuildingManager, travelDistancePerCycle);
            var workBehavior      = new WorkBehavior(config, gameConnections.Random, gameConnections.BuildingManager, timeInfo, travelBehavior);

            ParkPatch.SpareTimeBehavior = spareTimeBehavior;
            OutsideConnectionAIPatch.SpareTimeBehavior = spareTimeBehavior;

            var realTimePrivateBuildingAI = new RealTimeBuildingAI(
                config,
                timeInfo,
                gameConnections.BuildingManager,
                new ToolManagerConnection(),
                workBehavior,
                travelBehavior);

            BuildingAIPatch.RealTimeAI      = realTimePrivateBuildingAI;
            BuildingAIPatch.WeatherInfo     = gameConnections.WeatherInfo;
            TransferManagerPatch.RealTimeAI = realTimePrivateBuildingAI;

            var realTimeResidentAI = new RealTimeResidentAI <ResidentAI, Citizen>(
                config,
                gameConnections,
                residentAIConnection,
                eventManager,
                realTimePrivateBuildingAI,
                workBehavior,
                spareTimeBehavior,
                travelBehavior);

            ResidentAIPatch.RealTimeAI         = realTimeResidentAI;
            SimulationHandler.CitizenProcessor = new CitizenProcessor <ResidentAI, Citizen>(
                realTimeResidentAI, timeInfo, spareTimeBehavior, travelBehavior);

            var touristAIConnection = TouristAIPatch.GetTouristAIConnection();

            if (touristAIConnection == null)
            {
                return(false);
            }

            var realTimeTouristAI = new RealTimeTouristAI <TouristAI, Citizen>(
                config,
                gameConnections,
                touristAIConnection,
                eventManager,
                spareTimeBehavior);

            TouristAIPatch.RealTimeAI = realTimeTouristAI;
            return(true);
        }
Esempio n. 20
0
        public static RealTimeCore Run(RealTimeConfig config, string rootPath, LocalizationProvider localizationProvider)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (string.IsNullOrEmpty(rootPath))
            {
                throw new ArgumentException("The root path cannot be null or empty string", nameof(rootPath));
            }

            if (localizationProvider == null)
            {
                throw new ArgumentNullException(nameof(localizationProvider));
            }

            try
            {
                int redirectedCount = Redirector.PerformRedirections();
                Log.Info($"Successfully redirected {redirectedCount} methods.");
            }
            catch (Exception ex)
            {
                Log.Error("Failed to perform method redirections: " + ex.Message);
                return(null);
            }

            var      timeAdjustment = new TimeAdjustment();
            DateTime gameDate       = timeAdjustment.Enable();

            var timeInfo          = new TimeInfo();
            var buildingManager   = new BuildingManagerConnection();
            var simulationManager = new SimulationManagerConnection();

            var gameConnections = new GameConnections <Citizen>(
                timeInfo,
                new CitizenConnection(),
                new CitizenManagerConnection(),
                buildingManager,
                simulationManager,
                new TransferManagerConnection());

            var eventManager = new RealTimeEventManager(
                config,
                CityEventsLoader.Istance,
                new EventManagerConnection(),
                buildingManager,
                simulationManager,
                timeInfo);

            SetupCustomAI(timeInfo, config, gameConnections, eventManager);

            CityEventsLoader.Istance.ReloadEvents(rootPath);

            var customTimeBar = new CustomTimeBar();

            customTimeBar.Enable(gameDate);
            customTimeBar.CityEventClick += CustomTimeBarCityEventClick;

            var result = new RealTimeCore(timeAdjustment, customTimeBar, eventManager);

            eventManager.EventsChanged += result.CityEventsChanged;
            SimulationHandler.NewDay   += result.CityEventsChanged;

            SimulationHandler.DayTimeSimulation = new DayTimeSimulation();
            SimulationHandler.EventManager      = eventManager;
            SimulationHandler.CommercialAI      = new CommercialAI(timeInfo, buildingManager);

            RealTimeStorage.Instance.GameSaving += result.GameSaving;
            result.storageData.Add(eventManager);
            result.LoadStorageData();

            result.Translate(localizationProvider);

            return(result);
        }
        /// <summary>
        /// Default constructor of the adapter
        /// </summary>
        private TestBedAdapter()
        {
            try
            {
                // Create a new configuration, including the read in external settings
                _configuration = new Configuration();

                // Initialize the empty producer and consumer dictionaries
                _producers = new Dictionary <string, IAbstractProducer>();
                _consumers = new Dictionary <string, List <IAbstractConsumer> >();

                // Create the producers for the system topics
                _heartbeatProducer = new ProducerBuilder <EDXLDistribution, eu.driver.model.core.Heartbeat>(_configuration.ProducerConfig)
                                     .SetKeySerializer(new AvroSerializer <EDXLDistribution>(_configuration.SchemaRegistryClient))
                                     .SetValueSerializer(new AvroSerializer <eu.driver.model.core.Heartbeat>(_configuration.SchemaRegistryClient))
                                     // Raised on critical errors, e.g.connection failures or all brokers down.
                                     .SetErrorHandler(Adapter_Error)
                                     // Raised when there is information that should be logged.
                                     .SetLogHandler(Adapter_Log)
                                     .Build();

                _logProducer = new ProducerBuilder <EDXLDistribution, Log>(_configuration.ProducerConfig)
                               .SetKeySerializer(new AvroSerializer <EDXLDistribution>(_configuration.SchemaRegistryClient))
                               .SetValueSerializer(new AvroSerializer <Log>(_configuration.SchemaRegistryClient))
                               // Raised on critical errors, e.g.connection failures or all brokers down.
                               .SetErrorHandler(Adapter_Error)
                               // Raised when there is information that should be logged.
                               .SetLogHandler(Adapter_Log)
                               .Build();

                // Initialize the consumers for the system topics
                // Whenever bypassing the adming tool, don't listen to the admin tool control topics
                if (!_configuration.Settings.directconnect)
                {
                    _heartbeatConsumer = new ConsumerBuilder <EDXLDistribution, AdminHeartbeat>(_configuration.ConsumerConfig)
                                         .SetKeyDeserializer(new AvroDeserializer <EDXLDistribution>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                         .SetValueDeserializer(new AvroDeserializer <AdminHeartbeat>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                         // Raised on critical errors, e.g.connection failures or all brokers down.
                                         .SetErrorHandler(Adapter_Error)
                                         // Raised when there is information that should be logged.
                                         .SetLogHandler(Adapter_Log)
                                         .Build();

                    _topicInviteConsumer = new ConsumerBuilder <EDXLDistribution, TopicInvite>(_configuration.ConsumerConfig)
                                           .SetKeyDeserializer(new AvroDeserializer <EDXLDistribution>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                           .SetValueDeserializer(new AvroDeserializer <TopicInvite>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                           // Raised on critical errors, e.g.connection failures or all brokers down.
                                           .SetErrorHandler(Adapter_Error)
                                           // Raised when there is information that should be logged.
                                           .SetLogHandler(Adapter_Log)
                                           .Build();
                }

                _timeConsumer = new ConsumerBuilder <EDXLDistribution, TimeManagement>(_configuration.ConsumerConfig)
                                .SetKeyDeserializer(new AvroDeserializer <EDXLDistribution>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                .SetValueDeserializer(new AvroDeserializer <TimeManagement>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                // Raised on critical errors, e.g.connection failures or all brokers down.
                                .SetErrorHandler(Adapter_Error)
                                // Raised when there is information that should be logged.
                                .SetLogHandler(Adapter_Log)
                                .Build();

                _timeControlConsumer = new ConsumerBuilder <EDXLDistribution, TimeControl>(_configuration.ConsumerConfig)
                                       .SetKeyDeserializer(new AvroDeserializer <EDXLDistribution>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                       .SetValueDeserializer(new AvroDeserializer <TimeControl>(_configuration.SchemaRegistryClient).AsSyncOverAsync())
                                       // Raised on critical errors, e.g.connection failures or all brokers down.
                                       .SetErrorHandler(Adapter_Error)
                                       // Raised when there is information that should be logged.
                                       .SetLogHandler(Adapter_Log)
                                       .Build();

                _cancellationTokenSource = new CancellationTokenSource();
                CancellationToken token = _cancellationTokenSource.Token;

                // Start listening to the topics
                // Whenever bypassing the adming tool, don't listen to the admin tool control topics
                if (!_configuration.Settings.directconnect)
                {
                    _heartbeatConsumer.Subscribe(Configuration.CoreTopics["admin-heartbeat"]);
                    _topicInviteConsumer.Subscribe(Configuration.CoreTopics["topic-access-invite"]);
                }
                _timeConsumer.Subscribe(Configuration.CoreTopics["time"]);
                _timeControlConsumer.Subscribe(Configuration.CoreTopics["time-control"]);

                // Whenever bypassing the adming tool, don't listen to the admin tool control topics
                if (!_configuration.Settings.directconnect)
                {
                    Task.Factory.StartNew((cancelToken) => { AdminCheck((CancellationToken)cancelToken); }, token, token);
                    Task.Factory.StartNew((cancelToken) => { ConsumeHeartbeatMessage((CancellationToken)cancelToken); }, token, token);
                    Task.Factory.StartNew((cancelToken) => { ConsumeTopicInviteMessage((CancellationToken)cancelToken); }, token, token);
                }
                Task.Factory.StartNew((cancelToken) => { ConsumeTimeMessage((CancellationToken)cancelToken); }, token, token);
                Task.Factory.StartNew((cancelToken) => { ConsumeTimeControlMessage((CancellationToken)cancelToken); }, token, token);

                // Start the heart beat to indicate the connector is still alive
                Task.Factory.StartNew((cancelToken) => { Heartbeat((CancellationToken)cancelToken); }, token, token);

                _lastAdminHeartbeat = DateTime.MinValue;
                _startTime          = DateTime.UtcNow;
                _currentTime        = new TimeInfo()
                {
                    //ElapsedTime = TimeSpan.FromMilliseconds(0),
                    UpdatedAt      = DateTime.UtcNow,
                    TrialTime      = DateTime.MinValue,
                    TrialTimeSpeed = 1f,
                    TimeState      = TimeState.Initialization
                };

                _allowedTopicsSend    = new List <string>();
                _allowedTopicsReceive = new List <string>();

                // When we are directly connecting, ignoring the admin tool, go right into DEBUG mode
                if (_configuration.Settings.directconnect)
                {
                    _state = States.Debug;
                }
            }
            catch (Exception e)
            {
                Log(log4net.Core.Level.Critical, e.ToString());
            }

            // Try to derive the origin of this app, first checking IP address, then local machine name.
            // If that even fails, origin will be the application identifier
            try
            {
                IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        _appOrigin += ip.ToString() + "    ";
                    }
                }
            }
            catch
            {
                Log(log4net.Core.Level.Info, "Could not obtain IP address for application origin");
            }
            try
            {
                _appOrigin += Environment.MachineName;
            }
            catch
            {
                Log(log4net.Core.Level.Info, "Could not obtain local machine name for application origin");
                _appOrigin += _configuration.Settings.clientid;
            }
        }
    private static void HandleSelectRpsChoice(GameSession session, PacketReader packet)
    {
        session.Player.RPSSelection = (RpsChoice)packet.ReadInt();

        // delay for 1 sec for opponent to update their selection
        Task.Run(async() =>
        {
            await Task.Delay(1000);
        });

        // confirm if opponent is still in the map
        Player opponent = session.FieldManager.State.Players
                          .FirstOrDefault(x => x.Value.Value.CharacterId == session.Player.RPSOpponentId).Value?.Value;

        if (opponent == null)
        {
            return;
        }

        // handle choices
        RpsResult[,] resultMatrix =
        {
            {
                RpsResult.Draw, RpsResult.Lose, RpsResult.Win
            },
            {
                RpsResult.Win, RpsResult.Draw, RpsResult.Lose
            },
            {
                RpsResult.Lose, RpsResult.Win, RpsResult.Draw
            }
        };

        RpsResult result = resultMatrix[(int)session.Player.RPSSelection, (int)opponent.RPSSelection];

        RPS rpsEvent = DatabaseManager.Events.FindRockPaperScissorsEvent();

        if (rpsEvent is null)
        {
            return;
        }

        Item voucher = session.Player.Inventory.GetById(rpsEvent.VoucherId);

        if (voucher is null)
        {
            return;
        }

        session.Player.Inventory.ConsumeItem(session, voucher.Uid, 1);

        GameEventUserValue dailyMatches = GameEventHelper.GetUserValue(session.Player, rpsEvent.Id,
                                                                       TimeInfo.Tomorrow(), GameEventUserValueType.RPSDailyMatches);

        int.TryParse(dailyMatches.EventValue, out int dailyMatchCount);

        dailyMatchCount++;

        dailyMatches.UpdateValue(session, dailyMatchCount);
        session.Send(RockPaperScissorsPacket.MatchResults(result, session.Player.RPSSelection, opponent.RPSSelection));
    }
Esempio n. 23
0
    private async Task <ICollection <StackSummaryModel> > GetStackSummariesAsync(ICollection <Stack> stacks, AppFilter eventSystemFilter, TimeInfo ti)
    {
        if (stacks.Count == 0)
        {
            return(new List <StackSummaryModel>());
        }

        var systemFilter = new RepositoryQuery <PersistentEvent>().AppFilter(eventSystemFilter).DateRange(ti.Range.UtcStart, ti.Range.UtcEnd, (PersistentEvent e) => e.Date).Index(ti.Range.UtcStart, ti.Range.UtcEnd);
        var stackTerms   = await _eventRepository.CountAsync(q => q.SystemFilter(systemFilter).FilterExpression(String.Join(" OR ", stacks.Select(r => $"stack:{r.Id}"))).AggregationsExpression($"terms:(stack_id~{stacks.Count} cardinality:user sum:count~1 min:date max:date)"));

        return(await GetStackSummariesAsync(stacks, stackTerms.Aggregations.Terms <string>("terms_stack_id").Buckets, eventSystemFilter, ti));
    }
Esempio n. 24
0
        /// <summary>
        /// Calculates the Bar-Beat-Tick representation of a time using the given bpm remains constant
        /// </summary>
        /// <param name="time">Time offset to calculate</param>
        /// <param name="timeSignatureOrTempoChange">Tempo/Time signature at time</param>
        /// <param name="calculatedTimeSignatureOrTempoChangeOffset">Beat-Bar-Tick offset for timeSignatureOrTempoChange</param>
        /// <param name="ticksPerBeat">Number of ticks per beat (default 24000)</param>
        /// <returns>Bar-Beat-Tick representation of the time</returns>
        public static BarBeatTick CalculateBarBeatTickWithVariableTimeSignatureOrTempo(double time, TimeInfo timeSignatureOrTempoChange, BarBeatTick calculatedTimeSignatureOrTempoChangeOffset,
                                                                                       ushort ticksPerBeat = 24000)
        {
            var adjustedTime = time - timeSignatureOrTempoChange.Time;
            var offset       = CalculateBarBeatTickWithConstantTempo(adjustedTime, timeSignatureOrTempoChange.Tempo, timeSignatureOrTempoChange.BeatsPerBar, ticksPerBeat);

            return(offset.Add(calculatedTimeSignatureOrTempoChangeOffset));
        }
Esempio n. 25
0
 static void SetTimeAndWeather()
 {
     TimeInfo = new TimeInfo(Now);
     Weather  = new Weather(TimeInfo);
 }
Esempio n. 26
0
    private static void HandleAddExplorationQuests(GameSession session, PacketReader packet)
    {
        int listSize = packet.ReadInt();

        for (int i = 0; i < listSize; i++)
        {
            int questId = packet.ReadInt();
            session.Player.QuestData.TryGetValue(questId, out QuestStatus questStatus);

            session.Send(QuestPacket.AcceptQuest(questId));
            if (questStatus is null)
            {
                QuestMetadata metadata = QuestMetadataStorage.GetMetadata(questId);
                session.Player.QuestData.Add(questId, new(session.Player, metadata, QuestState.Started, TimeInfo.Now()));
                continue;
            }

            questStatus.State = QuestState.Started;
            DatabaseManager.Quests.Update(questStatus);
        }
    }
Esempio n. 27
0
    public override void Execute(GameCommandTrigger trigger)
    {
        int questId = trigger.Get <int>("id");

        if (questId == 0)
        {
            trigger.Session.SendNotice("Type an quest id.");
            return;
        }
        QuestMetadata quest = QuestMetadataStorage.GetMetadata(questId);

        if (quest == null)
        {
            trigger.Session.Send(NoticePacket.Notice($"Quest not found with id: {questId.ToString().Color(Color.Aquamarine)}.", NoticeType.Chat));
            return;
        }
        if (trigger.Session.Player.QuestData.ContainsKey(questId))
        {
            trigger.Session.Send(NoticePacket.Notice($"You already have quest: {questId.ToString().Color(Color.Aquamarine)}.", NoticeType.Chat));
            return;
        }

        trigger.Session.Player.QuestData.Add(questId, new(trigger.Session.Player, quest, QuestState.Started, TimeInfo.Now()));
        trigger.Session.Send(QuestPacket.AcceptQuest(questId));
    }
    public static PacketWriter WriteCharacterInfo(long characterId, Player player)
    {
        PacketWriter pWriter = PacketWriter.Of(SendOp.CharInfo);

        pWriter.WriteLong(characterId);
        pWriter.WriteBool(player != null);
        if (player == null)
        {
            return(pWriter);
        }
        pWriter.WriteLong(); // unknown
        pWriter.WriteLong(player.CharacterId);
        pWriter.WriteLong(TimeInfo.Now());

        PacketWriter characterBuffer = new();

        characterBuffer.WriteLong(player.AccountId);
        characterBuffer.WriteLong(player.CharacterId);
        characterBuffer.WriteUnicodeString(player.Name);
        characterBuffer.WriteShort(player.Levels.Level);
        characterBuffer.Write(player.Job);
        characterBuffer.Write(player.JobCode);
        characterBuffer.WriteInt((int)player.Gender);
        characterBuffer.WriteInt(player.Levels.PrestigeLevel);
        characterBuffer.WriteByte();
        WriteStats(characterBuffer, player);

        // Unknown data
        characterBuffer.WriteZero(1300);

        characterBuffer.WriteUnicodeString(player.ProfileUrl);
        characterBuffer.WriteUnicodeString(player.Motto);

        if (player.Guild == null)
        {
            characterBuffer.WriteUnicodeString(string.Empty);
            characterBuffer.WriteUnicodeString(string.Empty);
        }
        else
        {
            characterBuffer.WriteUnicodeString(player.Guild.Name);
            characterBuffer.WriteUnicodeString(player.Guild.Ranks[player.GuildMember.Rank].Name);
        }

        characterBuffer.WriteUnicodeString(player.Account.Home?.Name ?? string.Empty);
        characterBuffer.WriteZero(12);
        characterBuffer.WriteInt(player.TitleId);
        characterBuffer.WriteInt(player.Titles.Count);
        foreach (int titleId in player.Titles)
        {
            characterBuffer.WriteInt(titleId);
        }
        characterBuffer.WriteInt(player.TrophyCount.Sum());
        characterBuffer.WriteInt();  // gear score
        characterBuffer.WriteLong(); // timestamp
        characterBuffer.WriteLong();
        characterBuffer.Write(player.SkinColor);
        characterBuffer.WriteZero(14);

        pWriter.WriteInt(characterBuffer.Length);
        pWriter.WriteBytes(characterBuffer.ToArray());

        PacketWriter appearanceBuffer = new();

        CharacterListPacket.WriteEquipsAndCosmetics(appearanceBuffer, player);

        appearanceBuffer.WriteByte(1);
        appearanceBuffer.WriteLong();
        appearanceBuffer.WriteLong();
        appearanceBuffer.WriteByte();

        pWriter.WriteInt(appearanceBuffer.Length);
        pWriter.WriteBytes(appearanceBuffer.ToArray());

        PacketWriter badgeBuffer = new();

        CharacterListPacket.WriteBadges(badgeBuffer, player);

        pWriter.WriteInt(badgeBuffer.Length);
        pWriter.WriteBytes(badgeBuffer.ToArray());

        return(pWriter);
    }
Esempio n. 29
0
 public void TimeHasChanged(object observable, TimeInfo timeInfo)
 {
     Console.WriteLine("Current time: {0}:{1}:{2}", timeInfo.hour, timeInfo.minute, timeInfo.second);
 }
    public List <BlackMarketListing> GetSearchedListings(List <string> itemCategories, int minLevel, int maxLevel, int rarity, string name, JobFlag jobFlag,
                                                         int minEnchantLevel, int maxEnchantLevel, byte minSockets, byte maxSockets, int startPage, long sort, bool searchStat, List <ItemStat> searchedStats)
    {
        List <BlackMarketListing> allResults = new();

        foreach (BlackMarketListing listing in Listings.Values)
        {
            Item item = listing.Item;

            if (TimeInfo.Now() > listing.ExpiryTimestamp ||
                !itemCategories.Contains(item.BlackMarketCategory) ||
                item.Level < minLevel ||
                item.Level > maxLevel ||
                item.Rarity < rarity ||
                item.EnchantLevel < minEnchantLevel ||
                item.EnchantLevel > maxEnchantLevel ||
                item.Stats.GemSockets.Count < minSockets ||
                item.Stats.GemSockets.Count > maxSockets ||
                !item.Name.ToLower().Contains(name.ToLower()))
            {
                continue;
            }

            // Check job
            if (!JobHelper.CheckJobFlagForJob(item.RecommendJobs, jobFlag))
            {
                continue;
            }

            if (!searchStat)
            {
                allResults.Add(listing);
                continue;
            }

            // find if stats contains all values inside searchedStats
            bool containsAll = true;
            foreach (ItemStat searchedStat in searchedStats)
            {
                ICollection <Dictionary <StatAttribute, ItemStat> > stats = new List <Dictionary <StatAttribute, ItemStat> >();
                stats.Add(item.Stats.Constants);
                stats.Add(item.Stats.Statics);
                stats.Add(item.Stats.Randoms);
                foreach (Dictionary <StatAttribute, ItemStat> statCollection in stats)
                {
                    if (!statCollection.ContainsKey(searchedStat.ItemAttribute))
                    {
                        containsAll = false;
                        break;
                    }
                    if (statCollection[searchedStat.ItemAttribute].Flat < searchedStat.Flat &&
                        statCollection[searchedStat.ItemAttribute].Rate < searchedStat.Rate)
                    {
                        containsAll = false;
                        break;
                    }
                }
            }

            if (containsAll)
            {
                allResults.Add(listing);
            }
        }

        BlackMarketSort blackmarketSort = (BlackMarketSort)sort;

        switch (blackmarketSort)
        {
        case BlackMarketSort.PriceLowToHigh:
            allResults = allResults.OrderBy(x => x.Price).ToList();
            break;

        case BlackMarketSort.PriceHighToLow:
            allResults = allResults.OrderByDescending(x => x.Price).ToList();
            break;

        case BlackMarketSort.LevelLowToHigh:
            allResults = allResults.OrderBy(x => x.Item.Level).ToList();
            break;

        case BlackMarketSort.LevelHighToLow:
            allResults = allResults.OrderByDescending(x => x.Item.Level).ToList();
            break;
        }

        int count  = startPage * 7 - 7;
        int offset = count;
        int limit  = 70 + Math.Min(0, count);

        return(allResults.Skip(offset).Take(limit).ToList());
    }
Esempio n. 31
0
 public virtual void Update(TimeInfo time)
 {
     CheckScreenTimer(time);
 }
Esempio n. 32
0
        private static bool SetupCustomAI(
            TimeInfo timeInfo,
            RealTimeConfig config,
            GameConnections<Citizen> gameConnections,
            RealTimeEventManager eventManager)
        {
            ResidentAIConnection<ResidentAI, Citizen> residentAIConnection = ResidentAIPatch.GetResidentAIConnection();
            if (residentAIConnection == null)
            {
                return false;
            }

            var spareTimeBehavior = new SpareTimeBehavior(config, timeInfo);
            var travelBehavior = new TravelBehavior(gameConnections.BuildingManager);
            var workBehavior = new WorkBehavior(config, gameConnections.Random, gameConnections.BuildingManager, timeInfo, travelBehavior);

            ParkPatches.SpareTimeBehavior = spareTimeBehavior;
            OutsideConnectionAIPatch.SpareTimeBehavior = spareTimeBehavior;

            var realTimePrivateBuildingAI = new RealTimeBuildingAI(
                config,
                timeInfo,
                gameConnections.BuildingManager,
                new ToolManagerConnection(),
                workBehavior,
                travelBehavior);

            BuildingAIPatches.RealTimeAI = realTimePrivateBuildingAI;
            BuildingAIPatches.WeatherInfo = gameConnections.WeatherInfo;
            TransferManagerPatch.RealTimeAI = realTimePrivateBuildingAI;

            var realTimeResidentAI = new RealTimeResidentAI<ResidentAI, Citizen>(
                config,
                gameConnections,
                residentAIConnection,
                eventManager,
                realTimePrivateBuildingAI,
                workBehavior,
                spareTimeBehavior,
                travelBehavior);

            ResidentAIPatch.RealTimeAI = realTimeResidentAI;
            SimulationHandler.CitizenProcessor = new CitizenProcessor<ResidentAI, Citizen>(
                realTimeResidentAI, timeInfo, spareTimeBehavior, travelBehavior);

            TouristAIConnection<TouristAI, Citizen> touristAIConnection = TouristAIPatch.GetTouristAIConnection();
            if (touristAIConnection == null)
            {
                return false;
            }

            var realTimeTouristAI = new RealTimeTouristAI<TouristAI, Citizen>(
                config,
                gameConnections,
                touristAIConnection,
                eventManager,
                spareTimeBehavior);

            TouristAIPatch.RealTimeAI = realTimeTouristAI;
            return true;
        }
Esempio n. 33
0
        private static void FillInTimeInfo(ref TimeInfo timeInfo, byte[] timeBytes, int length, byte scale)
        {
            Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length);
            Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale);

            Int64 tickUnits = (Int64)timeBytes[0] + ((Int64)timeBytes[1] << 8) + ((Int64)timeBytes[2] << 16);
            if (length > 3)
            {
                tickUnits += ((Int64)timeBytes[3] << 24);
            }
            if (length > 4)
            {
                tickUnits += ((Int64)timeBytes[4] << 32);
            }
            timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale];
            timeInfo.scale = scale;
        }
Esempio n. 34
0
            public static TimeInfo Now()
            {
                TimeInfo nowTime = new TimeInfo(DateTime.Now);

                return(nowTime);
            }
Esempio n. 35
0
 public override void Reset()
 {
     getInfo    = TimeInfo.TimeSinceLevelLoad;
     storeValue = null;
     everyFrame = false;
 }
Esempio n. 36
0
    private static string GetDateString(ScoreEntry entry)
    {
        string   dateTime;
        TimeSpan ts       = DateTime.Now - entry.entryIRL_Time;
        TimeInfo timeInfo = GetTimeInfo(ts);

        if (entry.isLast)
        {
            dateTime = "a second ago";
        }
        else if (timeInfo.years > 0)
        {
            if (timeInfo.years == 1)
            {
                dateTime = $"1 year ago";
            }
            else
            {
                dateTime = $"{timeInfo.years} years ago";
            }
        }
        else if (timeInfo.months > 0)
        {
            if (timeInfo.months == 1)
            {
                dateTime = $"1 month ago";
            }
            else
            {
                dateTime = $"{timeInfo.months} months ago";
            }
        }
        else if (timeInfo.days > 0)
        {
            if (timeInfo.days == 1)
            {
                dateTime = $"1 day ago";
            }
            else
            {
                dateTime = $"{timeInfo.days} days ago";
            }
        }
        else if (timeInfo.hours > 0)
        {
            if (timeInfo.hours == 1)
            {
                dateTime = $"1 hour ago";
            }
            else
            {
                dateTime = $"{timeInfo.hours} hours ago";
            }
        }
        else if (timeInfo.minutes > 0)
        {
            if (timeInfo.minutes == 1)
            {
                dateTime = $"1 minute ago";
            }
            else
            {
                dateTime = $"{timeInfo.minutes} minutes ago";
            }
        }
        else
        {
            if (timeInfo.seconds == 1)
            {
                dateTime = "1337"; // easter egg
            }
            else
            {
                dateTime = $"{timeInfo.seconds} seconds ago";
            }
        }
        return(dateTime);
    }