/// <summary>
        /// Verify  the profiler service XEvent session factory
        /// </summary>
        //[Fact]
        public void TestCreateXEventSession()
        {
            var             liveConnection  = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ProfilerService profilerService = new ProfilerService();
            IXEventSession  xeSession       = profilerService.CreateXEventSession(liveConnection.ConnectionInfo);

            Assert.NotNull(xeSession);
            Assert.NotNull(xeSession.GetTargetXml());
        }
Пример #2
0
        public ChunkManager(Alex alex, GraphicsDevice graphics, AlexOptions option, IWorld world)
        {
            Game            = alex;
            Graphics        = graphics;
            World           = world;
            Options         = option;
            ProfilerService = alex.Services.GetService <ProfilerService>();

            Chunks = new ConcurrentDictionary <ChunkCoordinates, IChunkColumn>();

            var fogStart = 0;

            TransparentEffect = new AlphaTestEffect(Graphics)
            {
                Texture            = alex.Resources.Atlas.GetStillAtlas(),
                VertexColorEnabled = true,
                World          = Matrix.Identity,
                AlphaFunction  = CompareFunction.Greater,
                ReferenceAlpha = 127,
                FogStart       = fogStart,
                FogEnabled     = false
            };

            AnimatedEffect = new AlphaTestEffect(Graphics)
            {
                Texture            = alex.Resources.Atlas.GetAtlas(0),
                VertexColorEnabled = true,
                World          = Matrix.Identity,
                AlphaFunction  = CompareFunction.Greater,
                ReferenceAlpha = 127,
                FogStart       = fogStart,
                FogEnabled     = false
            };

            OpaqueEffect = new BasicEffect(Graphics)
            {
                TextureEnabled     = true,
                Texture            = alex.Resources.Atlas.GetStillAtlas(),
                FogStart           = fogStart,
                VertexColorEnabled = true,
                LightingEnabled    = true,
                FogEnabled         = false
            };

            //if (alex.)

            FrameCount = alex.Resources.Atlas.GetFrameCount();

            ChunkManagementThread = new Thread(ChunkUpdateThread)
            {
                IsBackground = true,
                Name         = "Chunk Management"
            };

            HighestPriority = new ConcurrentQueue <ChunkCoordinates>();
        }
Пример #3
0
        public MainWindowViewModel(
            StoryService storyService,
            GameScriptService gameScriptService,
            ProfilerService profilerService,
            ScreenViewModel screenViewModel,
            ProfilerViewModel profilerViewModel,
            GameInfoDialogViewModel gameInfoDialogViewModel,
            GameScriptDialogViewModel gameScriptDialogViewModel)
            : base("MainWindowView")
        {
            this.storyService               = storyService;
            this.storyService.StoryOpened  += StoryService_StoryOpened;
            this.storyService.StoryClosing += StoryService_StoryClosing;

            this.gameScriptService = gameScriptService;

            this.profilerService = profilerService;

            this.screenViewModel           = screenViewModel;
            this.profilerViewModel         = profilerViewModel;
            this.gameInfoDialogViewModel   = gameInfoDialogViewModel;
            this.gameScriptDialogViewModel = gameScriptDialogViewModel;

            this.OpenStoryCommand = RegisterCommand(
                text: "Open",
                name: "Open",
                executed: OpenStoryExecuted,
                canExecute: OpenStoryCanExecute,
                inputGestures: new KeyGesture(Key.O, ModifierKeys.Control));

            this.EditGameScriptCommand = RegisterCommand(
                text: "EditGameScript",
                name: "Edit Game Script",
                executed: EditGameScriptExecuted,
                canExecute: EditGameScriptCanExecute);

            this.ExitCommand = RegisterCommand(
                text: "Exit",
                name: "Exit",
                executed: ExitExecuted,
                canExecute: ExitCanExecute,
                inputGestures: new KeyGesture(Key.F4, ModifierKeys.Alt));

            this.StopCommand = RegisterCommand(
                text: "Stop",
                name: "Stop",
                executed: StopExecuted,
                canExecute: StopCanExecute);

            this.AboutGameCommand = RegisterCommand(
                text: "AboutGame",
                name: "About Game",
                executed: AboutGameExecuted,
                canExecute: AboutGameCanExecute);
        }
Пример #4
0
        public ProfilerViewModel(
            ProfilerService profilerService,
            StoryService storyService)
            : base("ProfilerView")
        {
            this.profilerService = profilerService;
            this.storyService    = storyService;

            this.profilerService.Starting += ProfilerService_Starting;
            this.profilerService.Stopped  += ProfilerService_Stopped;
        }
        public async Task TestStopProfilingRequest()
        {
            bool   success = false;
            bool   stopped = false;
            string testUri = "test_session";

            // capture stopping results
            var requestContext = new Mock <RequestContext <StopProfilingResult> >();

            requestContext.Setup(rc => rc.SendResult(It.IsAny <StopProfilingResult>()))
            .Returns <StopProfilingResult>((result) =>
            {
                success = true;
                return(Task.FromResult(0));
            });

            // capture if session was stopped
            var mockSession = new Mock <IXEventSession>();

            mockSession.Setup(p => p.Stop()).Callback(() =>
            {
                stopped = true;
            });

            var sessionListener = new TestSessionListener();
            var profilerService = new ProfilerService();

            profilerService.SessionMonitor.AddSessionListener(sessionListener);
            profilerService.ConnectionServiceInstance = TestObjects.GetTestConnectionService();
            ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();

            profilerService.ConnectionServiceInstance.OwnerToConnectionMap.Add(testUri, connectionInfo);
            profilerService.XEventSessionFactory = new TestXEventSessionFactory();

            var requestParams = new StopProfilingParams();

            requestParams.OwnerUri = testUri;

            profilerService.SessionMonitor.StartMonitoringSession(testUri, mockSession.Object);

            await profilerService.HandleStopProfilingRequest(requestParams, requestContext.Object);

            requestContext.VerifyAll();

            // check that session was succesfully stopped and stop was called
            Assert.True(success);
            Assert.True(stopped);

            // should not be able to remove the session, it should already be gone
            ProfilerSession ps;

            Assert.False(profilerService.SessionMonitor.StopMonitoringSession(testUri, out ps));
        }
Пример #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ProfilerService.RegisterInternalEvent("MainActivity OnCreate Init");

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Forms.SetFlags("FastRenderers_Experimental");
            Forms.Init(this, savedInstanceState);
            DependencyService.Register <ProfilerService>();
            LoadApplication(new App());

            ProfilerService.RegisterInternalEvent("MainActivity OnCreate End");
        }
        public async Task TestStoppedSessionNotification()
        {
            bool   sessionStopped = false;
            string testUri        = "profiler_uri";

            // capture listener event notifications
            var mockSession = new Mock <IXEventSession>();

            mockSession.Setup(p => p.GetTargetXml()).Callback(() =>
            {
                throw new XEventException();
            });

            var mockListener = new Mock <IProfilerSessionListener>();

            mockListener.Setup(p => p.SessionStopped(It.IsAny <string>(), It.IsAny <int>())).Callback(() =>
            {
                sessionStopped = true;
            });

            var profilerService = new ProfilerService();

            profilerService.SessionMonitor.AddSessionListener(mockListener.Object);
            profilerService.ConnectionServiceInstance = TestObjects.GetTestConnectionService();
            ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();

            profilerService.ConnectionServiceInstance.OwnerToConnectionMap.Add(testUri, connectionInfo);

            // start monitoring test session
            profilerService.SessionMonitor.StartMonitoringSession(testUri, mockSession.Object);

            // wait for polling to finish, or for timeout
            System.Timers.Timer pollingTimer = new System.Timers.Timer();
            pollingTimer.Interval = 10000;
            pollingTimer.Start();
            bool timeout = false;

            pollingTimer.Elapsed += new System.Timers.ElapsedEventHandler((s_, e_) => { timeout = true; });
            while (sessionStopped == false && !timeout)
            {
                Thread.Sleep(250);
            }
            pollingTimer.Stop();

            // check that a stopped session notification was sent
            Assert.True(sessionStopped);
        }
        /// <summary>
        /// Verify that a start profiling request starts a profiling session
        /// </summary>
        //[Fact]
        public async Task TestHandleStartAndStopProfilingRequests()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync("master", queryTempFile.FilePath);

                ProfilerService profilerService = new ProfilerService();

                // start a new session
                var startParams = new StartProfilingParams();
                startParams.OwnerUri     = connectionResult.ConnectionInfo.OwnerUri;
                startParams.TemplateName = "Standard";

                string sessionId    = null;
                var    startContext = new Mock <RequestContext <StartProfilingResult> >();
                startContext.Setup(rc => rc.SendResult(It.IsAny <StartProfilingResult>()))
                .Returns <StartProfilingResult>((result) =>
                {
                    // capture the session id for sending the stop message
                    sessionId = result.SessionId;
                    return(Task.FromResult(0));
                });

                await profilerService.HandleStartProfilingRequest(startParams, startContext.Object);

                startContext.VerifyAll();

                // wait a bit for the session monitoring to initialize
                Thread.Sleep(TimeSpan.FromHours(1));

                // stop the session
                var stopParams = new StopProfilingParams()
                {
                    OwnerUri = sessionId
                };

                var stopContext = new Mock <RequestContext <StopProfilingResult> >();
                stopContext.Setup(rc => rc.SendResult(It.IsAny <StopProfilingResult>()))
                .Returns(Task.FromResult(0));

                await profilerService.HandleStopProfilingRequest(stopParams, stopContext.Object);

                stopContext.VerifyAll();
            }
        }
Пример #9
0
        private void ConfigureServices()
        {
            XBLMSAService msa;
            var           storage = new StorageSystem(LaunchSettings.WorkDir);

            ProfileManager = new ProfileManager(this, storage);


            Services.AddService <IStorageSystem>(storage);

            var optionsProvider = new OptionsProvider(storage);

            //optionsProvider.Load();

            optionsProvider.AlexOptions.VideoOptions.UseVsync.Bind((value, newValue) => { SetVSync(newValue); });
            if (optionsProvider.AlexOptions.VideoOptions.UseVsync.Value)
            {
                SetVSync(true);
            }

            optionsProvider.AlexOptions.VideoOptions.Fullscreen.Bind((value, newValue) => { SetFullscreen(newValue); });
            if (optionsProvider.AlexOptions.VideoOptions.Fullscreen.Value)
            {
                SetFullscreen(true);
            }

            Services.AddService <IOptionsProvider>(optionsProvider);

            Services.AddService <IListStorageProvider <SavedServerEntry> >(new SavedServerDataProvider(storage));

            Services.AddService(msa = new XBLMSAService());

            Services.AddService <IServerQueryProvider>(new ServerQueryProvider(this));
            Services.AddService <IPlayerProfileService>(ProfileService = new PlayerProfileService(msa, ProfileManager));

            var profilingService = new ProfilerService();

            Services.AddService <ProfilerService>(profilingService);

            Storage = storage;
        }
Пример #10
0
        /// <summary>
        /// Test starting a profiling session and receiving event callback
        /// </summary>
        /// <returns></returns>
        // TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/459
        //[Fact]
        public async Task TestStartProfilingRequest()
        {
            string sessionId      = null;
            string testUri        = "profiler_uri";
            var    requestContext = new Mock <RequestContext <StartProfilingResult> >();

            requestContext.Setup(rc => rc.SendResult(It.IsAny <StartProfilingResult>()))
            .Returns <StartProfilingResult>((result) =>
            {
                // capture the session id for sending the stop message
                sessionId = result.SessionId;
                return(Task.FromResult(0));
            });

            var sessionListener = new TestSessionListener();

            var profilerService = new ProfilerService();

            profilerService.SessionMonitor.AddSessionListener(sessionListener);
            profilerService.ConnectionServiceInstance = TestObjects.GetTestConnectionService();
            ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();

            profilerService.ConnectionServiceInstance.OwnerToConnectionMap.Add(testUri, connectionInfo);
            profilerService.XEventSessionFactory = new TestXEventSessionFactory();

            var requestParams = new StartProfilingParams();

            requestParams.OwnerUri     = testUri;
            requestParams.TemplateName = "Standard";

            await profilerService.HandleStartProfilingRequest(requestParams, requestContext.Object);

            // wait a bit for profile sessions to be polled
            Thread.Sleep(500);

            requestContext.VerifyAll();

            Assert.Equal(sessionListener.PreviousSessionId, sessionId);
            Assert.Equal(sessionListener.PreviousEvents.Count, 1);
        }
        /// <summary>
        /// Test starting a profiling session and receiving event callback
        /// </summary>
        /// <returns></returns>
        // TODO: Fix flaky test. See https://github.com/Microsoft/sqltoolsservice/issues/459
        //[Fact]
        public async Task TestStartProfilingRequest()
        {
            string sessionId      = null;
            bool   recievedEvents = false;
            string testUri        = "profiler_uri";
            var    requestContext = new Mock <RequestContext <StartProfilingResult> >();

            requestContext.Setup(rc => rc.SendResult(It.IsAny <StartProfilingResult>()))
            .Returns <StartProfilingResult>((result) =>
            {
                // capture the session id for sending the stop message
                sessionId = result.SessionId;
                return(Task.FromResult(0));
            });

            // capture listener event notifications
            var mockListener = new Mock <IProfilerSessionListener>();

            mockListener.Setup(p => p.EventsAvailable(It.IsAny <string>(), It.IsAny <List <ProfilerEvent> >(), It.IsAny <bool>())).Callback(() =>
            {
                recievedEvents = true;
            });

            var profilerService = new ProfilerService();

            profilerService.SessionMonitor.AddSessionListener(mockListener.Object);
            profilerService.ConnectionServiceInstance = TestObjects.GetTestConnectionService();
            ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();

            profilerService.ConnectionServiceInstance.OwnerToConnectionMap.Add(testUri, connectionInfo);
            profilerService.XEventSessionFactory = new TestXEventSessionFactory();

            var requestParams = new StartProfilingParams();

            requestParams.OwnerUri     = testUri;
            requestParams.TemplateName = "Standard";

            // start profiling session
            await profilerService.HandleStartProfilingRequest(requestParams, requestContext.Object);

            profilerService.SessionMonitor.PollSession(1);
            // simulate a short polling delay
            Thread.Sleep(200);
            profilerService.SessionMonitor.PollSession(1);

            // wait for polling to finish, or for timeout
            System.Timers.Timer pollingTimer = new System.Timers.Timer();
            pollingTimer.Interval = 10000;
            pollingTimer.Start();
            bool timeout = false;

            pollingTimer.Elapsed += new System.Timers.ElapsedEventHandler((s_, e_) => { timeout = true; });
            while (sessionId == null && !timeout)
            {
                Thread.Sleep(250);
            }
            pollingTimer.Stop();

            requestContext.VerifyAll();

            // Check that the correct XEvent session was started
            Assert.Equal(sessionId, "1");

            // check that the proper owner Uri was used
            Assert.True(recievedEvents);
        }
        public async Task TestPauseProfilingRequest()
        {
            bool   success        = false;
            string testUri        = "test_session";
            bool   recievedEvents = false;

            // capture pausing results
            var requestContext = new Mock <RequestContext <PauseProfilingResult> >();

            requestContext.Setup(rc => rc.SendResult(It.IsAny <PauseProfilingResult>()))
            .Returns <PauseProfilingResult>((result) =>
            {
                success = true;
                return(Task.FromResult(0));
            });

            // capture listener event notifications
            var mockListener = new Mock <IProfilerSessionListener>();

            mockListener.Setup(p => p.EventsAvailable(It.IsAny <string>(), It.IsAny <List <ProfilerEvent> >(), It.IsAny <bool>())).Callback(() =>
            {
                recievedEvents = true;
            });

            // setup profiler service
            var profilerService = new ProfilerService();

            profilerService.SessionMonitor.AddSessionListener(mockListener.Object);
            profilerService.ConnectionServiceInstance = TestObjects.GetTestConnectionService();
            ConnectionInfo connectionInfo = TestObjects.GetTestConnectionInfo();

            profilerService.ConnectionServiceInstance.OwnerToConnectionMap.Add(testUri, connectionInfo);

            var requestParams = new PauseProfilingParams();

            requestParams.OwnerUri = testUri;

            // begin monitoring session
            profilerService.SessionMonitor.StartMonitoringSession(testUri, new TestXEventSession1());

            // poll the session
            profilerService.SessionMonitor.PollSession(1);
            Thread.Sleep(500);
            profilerService.SessionMonitor.PollSession(1);

            // wait for polling to finish, or for timeout
            System.Timers.Timer pollingTimer = new System.Timers.Timer();
            pollingTimer.Interval = 10000;
            pollingTimer.Start();
            bool timeout = false;

            pollingTimer.Elapsed += new System.Timers.ElapsedEventHandler((s_, e_) => { timeout = true; });
            while (!recievedEvents && !timeout)
            {
                Thread.Sleep(250);
            }
            pollingTimer.Stop();

            // confirm that polling works
            Assert.True(recievedEvents);

            // pause viewer
            await profilerService.HandlePauseProfilingRequest(requestParams, requestContext.Object);

            Assert.True(success);

            recievedEvents = false;
            success        = false;

            profilerService.SessionMonitor.PollSession(1);

            // confirm that no events were sent to paused listener
            Assert.False(recievedEvents);

            // unpause viewer
            await profilerService.HandlePauseProfilingRequest(requestParams, requestContext.Object);

            Assert.True(success);

            profilerService.SessionMonitor.PollSession(1);

            // wait for polling to finish, or for timeout
            timeout = false;
            pollingTimer.Start();
            while (!recievedEvents && !timeout)
            {
                Thread.Sleep(250);
            }

            // check that events got sent to listener
            Assert.True(recievedEvents);

            requestContext.VerifyAll();
        }
Пример #13
0
        static void Main(string[] args)
        {
            LoggerProvider lp = new LoggerProvider();


            var solution = @"EPPlus.sln";
            CSharpRecognitionContext ctx = new CSharpRecognitionContext("EPPlus");



            ProfilerService.Init(typeof(NullProfiler), (s, t) => { });

            using (ProfilerService.Current.Section("Total"))
            {
                using (ProfilerService.Current.Section("GetCompilations"))
                {
                    ctx.Compilations = CSharpModelBuilder.GetRecognitionContextInputFromSolution(solution);
                }
                using (ProfilerService.Current.Section("Init"))
                {
                    ctx.Init(lp);
                }
                SingletonRecognizer srec = new SingletonRecognizer();
                srec.Context = ctx;

                CompositeRecognizer crec = new CompositeRecognizer();
                crec.Context = ctx;

                //ProxyRecognizer prec = new ProxyRecognizer();
                //prec.Context = ctx;

                ChainOfResponsiblityRecognizer correc = new ChainOfResponsiblityRecognizer();
                correc.Context = ctx;

                FactoryMethodRecognizer frec = new FactoryMethodRecognizer();
                frec.Context = ctx;

                DecoratorRecognizer drec = new DecoratorRecognizer();
                drec.Context = ctx;

                MediatorRecognizer mmrec = new MediatorRecognizer();
                mmrec.Context = ctx;

                Console.Clear();

                using (var fres = File.CreateText("results.txt"))
                {
                    foreach (var item in ctx.Types)
                    {
                        try
                        {
                            if (mmrec.IsInstance(item))
                            {
                                Console.WriteLine("{0} is a mediator base", item.ToString());
                                fres.WriteLine(string.Format("{0} is a singleton", item.ToString()));
                            }
                        }
                        catch
                        { }

                        try
                        {
                            if (srec.IsInstance(item))
                            {
                                Console.WriteLine(string.Format("{0} is a singleton", item.ToString()));
                                fres.WriteLine(string.Format("{0} is a singleton", item.ToString()));
                            }
                        }
                        catch (Exception)
                        { }


                        try
                        {
                            if (crec.IsInstance(item))
                            {
                                Console.WriteLine(string.Format("{0} is a composite", item.ToString()));
                                fres.WriteLine(string.Format("{0} is a composite", item.ToString()));
                            }
                        }
                        catch (Exception)
                        {
                        }

                        //if (prec.isinstance(item))
                        //{
                        //    console.writeline(string.format("{0} is a proxy", item.tostring()));
                        //    fres.writeline(string.format("{0} is a proxy", item.tostring()));
                        //}
                        try
                        {
                            if (correc.IsInstance(item))
                            {
                                Console.WriteLine(string.Format("{0} is a chain of responsiblity base", item.ToString()));
                                fres.WriteLine(string.Format("{0} is a chain of responsiblity base", item.ToString()));
                            }
                        }
                        catch (Exception)
                        {
                        }

                        try
                        {
                            if (drec.IsInstance(item))
                            {
                                Console.WriteLine(string.Format("{0} is a decorator", item.ToString()));
                                fres.WriteLine(string.Format("{0} is a decorator", item.ToString()));
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }



                    foreach (var item in ctx.Types.SelectMany(t => t.Methods))
                    {
                        try
                        {
                            if (frec.IsInstance(item))
                            {
                                Console.WriteLine(string.Format("{0} is a factory method", item.ToString()));
                                fres.WriteLine(string.Format("{0} is a factory method", item.ToString()));
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            Console.ReadLine();
        }
Пример #14
0
        internal bool UpdateChunk(ChunkCoordinates coordinates, IChunkColumn c)
        {
            var chunk = c as ChunkColumn;

            if (!Monitor.TryEnter(chunk.UpdateLock))
            {
                Interlocked.Decrement(ref _chunkUpdates);
                return(false); //Another thread is already updating this chunk, return.
            }

            var       scheduleType = chunk.Scheduled;
            var       profiler     = MiniProfiler.StartNew("chunk.update");
            ChunkData data         = null;
            bool      force        = !_chunkData.TryGetValue(coordinates, out data);

            try
            {
                //chunk.UpdateChunk(Graphics, World);

                var currentChunkY = Math.Min(((int)Math.Round(_cameraPosition.Y)) >> 4, (chunk.GetHeighest() >> 4) - 2);
                if (currentChunkY < 0)
                {
                    currentChunkY = 0;
                }

                List <ChunkMesh> meshes = new List <ChunkMesh>();
                using (profiler.Step("chunk.sections"))
                {
                    for (var i = chunk.Sections.Length - 1; i >= 0; i--)
                    {
                        if (i < 0)
                        {
                            break;
                        }
                        var section = chunk.Sections[i] as ChunkSection;
                        if (section == null || section.IsEmpty())
                        {
                            continue;
                        }

                        if (i != currentChunkY && i != 0)
                        {
                            using (profiler.Step("chunk.neighboring"))
                            {
                                if (i > 0 && i < chunk.Sections.Length - 1)
                                {
                                    var neighbors = chunk.CheckNeighbors(section, i, World).ToArray();

                                    if (!section.HasAirPockets && neighbors.Length == 6) //All surrounded by solid.
                                    {
                                        // Log.Info($"Found section with solid neigbors, skipping.");
                                        continue;
                                    }

                                    if (i < currentChunkY && neighbors.Length >= 6)
                                    {
                                        continue;
                                    }
                                }
                                else if (i < currentChunkY)
                                {
                                    continue;
                                }
                            }
                        }

                        //if (i == 0) force = true;

                        if (force || !section.ScheduledUpdates.IsZero || section.IsDirty)
                        {
                            using (profiler.Step("chunk.meshing"))
                            {
                                var sectionMesh = GenerateSectionMesh(World, scheduleType,
                                                                      new Vector3(chunk.X * 16f, 0, chunk.Z * 16f), ref section, i);

                                meshes.Add(sectionMesh);
                            }
                        }
                    }
                }

                List <VertexPositionNormalTextureColor> vertices = new List <VertexPositionNormalTextureColor>();
                List <int> transparentIndexes = new List <int>();
                List <int> solidIndexes       = new List <int>();
                List <int> animatedIndexes    = new List <int>();

                foreach (var mesh in meshes)
                {
                    var startVerticeIndex = vertices.Count;
                    vertices.AddRange(mesh.Vertices);

                    solidIndexes.AddRange(mesh.SolidIndexes.Select(a => startVerticeIndex + a));

                    transparentIndexes.AddRange(mesh.TransparentIndexes.Select(a => startVerticeIndex + a));

                    animatedIndexes.AddRange(mesh.AnimatedIndexes.Select(a => startVerticeIndex + a));
                }

                if (vertices.Count > 0)
                {
                    ProfilerService.ReportCount("chunk.vertexCount", vertices.Count);

                    using (profiler.Step("chunk.buffer"))
                    {
                        var vertexArray      = vertices.ToArray();
                        var solidArray       = solidIndexes.ToArray();
                        var transparentArray = transparentIndexes.ToArray();
                        var animatedArray    = animatedIndexes.ToArray();

                        if (data == null)
                        {
                            data = new ChunkData()
                            {
                                Buffer = GpuResourceManager.GetBuffer(this, Graphics,
                                                                      VertexPositionNormalTextureColor.VertexDeclaration, vertexArray.Length,
                                                                      BufferUsage.WriteOnly),
                                SolidIndexBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                     IndexElementSize.ThirtyTwoBits,
                                                                                     solidArray.Length, BufferUsage.WriteOnly),
                                TransparentIndexBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                           IndexElementSize.ThirtyTwoBits,
                                                                                           transparentArray.Length, BufferUsage.WriteOnly),
                                AnimatedIndexBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                        IndexElementSize.ThirtyTwoBits,
                                                                                        animatedArray.Length, BufferUsage.WriteOnly)
                            };
                        }

                        PooledVertexBuffer oldBuffer = data.Buffer;

                        PooledVertexBuffer newVertexBuffer           = null;
                        PooledIndexBuffer  newsolidIndexBuffer       = null;
                        PooledIndexBuffer  newTransparentIndexBuffer = null;
                        PooledIndexBuffer  newAnimatedIndexBuffer    = null;

                        PooledIndexBuffer oldAnimatedIndexBuffer    = data.AnimatedIndexBuffer;
                        PooledIndexBuffer oldSolidIndexBuffer       = data.SolidIndexBuffer;
                        PooledIndexBuffer oldTransparentIndexBuffer = data.TransparentIndexBuffer;

                        using (profiler.Step("chunk.buffer.check"))
                            if (vertexArray.Length >= data.Buffer.VertexCount)
                            {
                                // var oldBuffer = data.Buffer;
                                PooledVertexBuffer newBuffer = GpuResourceManager.GetBuffer(this, Graphics,
                                                                                            VertexPositionNormalTextureColor.VertexDeclaration, vertexArray.Length,
                                                                                            BufferUsage.WriteOnly);

                                newBuffer.SetData(vertexArray);
                                newVertexBuffer = newBuffer;
                                //  data.Buffer = newBuffer;
                                //  oldBuffer?.Dispose();

                                ProfilerService.ReportCount("chunk.bufferSize", data.Buffer.MemoryUsage);

                                ProfilerService.TriggerCounter("chunk.bufferResize");
                            }
                            else
                            {
                                data.Buffer.SetData(vertexArray);
                                ProfilerService.ReportCount("chunk.bufferSize", data.Buffer.MemoryUsage);
                            }

                        using (profiler.Step("Chunk Solid indexbuffer check"))
                            if (solidArray.Length > data.SolidIndexBuffer.IndexCount)
                            {
                                //  var old = data.SolidIndexBuffer;
                                var newSolidBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                       IndexElementSize.ThirtyTwoBits,
                                                                                       solidArray.Length,
                                                                                       BufferUsage.WriteOnly);

                                newSolidBuffer.SetData(solidArray);
                                newsolidIndexBuffer = newSolidBuffer;
                                //  data.SolidIndexBuffer = newSolidBuffer;
                                //   old?.Dispose();
                            }
                            else
                            {
                                data.SolidIndexBuffer.SetData(solidArray);
                            }

                        using (profiler.Step("Chunk Transparent indexbuffer check"))
                            if (transparentArray.Length > data.TransparentIndexBuffer.IndexCount)
                            {
                                //  var old = data.TransparentIndexBuffer;
                                var newTransparentBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                             IndexElementSize.ThirtyTwoBits,
                                                                                             transparentArray.Length,
                                                                                             BufferUsage.WriteOnly);

                                newTransparentBuffer.SetData(transparentArray);
                                newTransparentIndexBuffer = newTransparentBuffer;
                            }
                            else
                            {
                                data.TransparentIndexBuffer.SetData(transparentArray);
                            }

                        using (profiler.Step("Chunk Animated indexbuffer check"))
                            if (animatedArray.Length > data.AnimatedIndexBuffer.IndexCount)
                            {
                                //  var old = data.TransparentIndexBuffer;
                                var newTransparentBuffer = GpuResourceManager.GetIndexBuffer(this, Graphics,
                                                                                             IndexElementSize.ThirtyTwoBits,
                                                                                             animatedArray.Length,
                                                                                             BufferUsage.WriteOnly);

                                newTransparentBuffer.SetData(animatedArray);
                                newAnimatedIndexBuffer = newTransparentBuffer;
                            }
                            else
                            {
                                data.AnimatedIndexBuffer.SetData(animatedArray);
                            }

                        using (profiler.Step("chunk.buffer.dispose"))
                        {
                            if (newVertexBuffer != null)
                            {
                                data.Buffer = newVertexBuffer;
                                oldBuffer?.MarkForDisposal();
                            }

                            if (newTransparentIndexBuffer != null)
                            {
                                data.TransparentIndexBuffer = newTransparentIndexBuffer;
                                oldTransparentIndexBuffer?.MarkForDisposal();
                            }

                            if (newAnimatedIndexBuffer != null)
                            {
                                data.AnimatedIndexBuffer = newAnimatedIndexBuffer;
                                oldAnimatedIndexBuffer?.MarkForDisposal();
                            }

                            if (newsolidIndexBuffer != null)
                            {
                                data.SolidIndexBuffer = newsolidIndexBuffer;
                                oldSolidIndexBuffer?.MarkForDisposal();
                            }
                        }
                    }
                }
                else
                {
                    if (data != null)
                    {
                        data.Dispose();
                        data = null;
                    }
                }

                chunk.IsDirty   = chunk.HasDirtySubChunks; //false;
                chunk.Scheduled = ScheduleType.Unscheduled;

                if (data != null)
                {
                    data.Coordinates = coordinates;
                }

                _chunkData.AddOrUpdate(coordinates, data, (chunkCoordinates, chunkData) => data);

                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"Exception while updating chunk: {ex.ToString()}");
            }
            finally
            {
                //Enqueued.Remove(new ChunkCoordinates(chunk.X, chunk.Z));
                Interlocked.Decrement(ref _chunkUpdates);
                Monitor.Exit(chunk.UpdateLock);

                profiler.Stop();

                //   Log.Info(MiniProfiler.Current.RenderPlainText());
            }

            return(false);
        }
Пример #15
0
 public MainActivity()
 {
     ProfilerService.RegisterInternalEvent("MainActivity Constructor");
 }