Beispiel #1
0
        public GameStudioPreviewService(SessionViewModel session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            this.session         = session;
            Dispatcher           = session.Dispatcher;
            AssetBuilderService  = session.ServiceProvider.Get <GameStudioBuilderService>();
            gameSettingsProvider = session.ServiceProvider.Get <GameSettingsProviderService>();

            Logger          = GlobalLogger.GetLogger("Preview");
            loggerDebugPage = EditorDebugTools.CreateLogDebugPage(Logger, "Preview");

            previewGameSettings = GameSettingsFactory.Create();
            previewGameSettings.GetOrCreate <RenderingSettings>().DefaultGraphicsProfile = GraphicsProfile.Level_11_0;
            UpdateGameSettings(gameSettingsProvider.CurrentGameSettings);
            previewCompileContext.SetGameSettingsAsset(previewGameSettings);
            previewCompileContext.CompilationContext = typeof(PreviewCompilationContext);

            previewGameThread = new Thread(SafeAction.Wrap(StrideUIThread))
            {
                IsBackground = true, Name = "PreviewGame Thread"
            };
            previewGameThread.SetApartmentState(ApartmentState.STA);
            previewGameThread.Start();

            // Wait for the window handle to be generated on the proper thread
            initializationSignal.WaitOne();
            host = new GameEngineHost(windowHandle);

            session.AssetPropertiesChanged           += OnAssetPropertyChanged;
            gameSettingsProvider.GameSettingsChanged += OnGameSettingsChanged;
        }
 private void InitializeInternal()
 {
     watcherCheckThread = new Thread(SafeAction.Wrap(RunCheckWatcher))
     {
         IsBackground = true, Name = "RunCheckWatcher thread"
     };
     watcherCheckThread.Start();
 }
Beispiel #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DynamicBuilder"/> class.
 /// </summary>
 /// <param name="name">The name of this instance. Used to name the created thread.</param>
 /// <param name="builder">The builder to use.</param>
 /// <param name="buildStepProvider">The build step provider to use.</param>
 public DynamicBuilder(Builder builder, IBuildStepProvider buildStepProvider, string name = null)
 {
     this.builder     = builder;
     dynamicBuildStep = new DynamicBuildStep(buildStepProvider, builder.ThreadCount);
     builderThread    = new Thread(SafeAction.Wrap(BuilderThread))
     {
         IsBackground = true
     };
     if (!string.IsNullOrEmpty(name))
     {
         builderThread.Name = name;
     }
 }
Beispiel #4
0
        private FileVersionManager()
        {
            // Environment.SpecialFolder.ApplicationData
            asyncRequestAvailable = new AutoResetEvent(false);
            asyncRequests         = new ConcurrentQueue <AsyncRequest>();

            // Loads the file version cache
            tracker     = FileVersionTracker.GetDefault();
            asyncRunner = new Thread(SafeAction.Wrap(ComputeFileHashAsyncRunner))
            {
                Name = "File Version Manager", IsBackground = true
            };
            asyncRunner.Start();
        }
Beispiel #5
0
        public async Task StartClient(IPAddress address, int port)
        {
            var clientDone = new TaskCompletionSource <bool>();

            // note: we wrap in a thread because we use Connect (not async) and then MessageLoop is sync.
            // we should switch to ConnectAsync, and start thread only if MessageLoop is reached
            new Thread(() =>
            {
                SafeAction.Wrap(() => ClientThread(address, port).Wait())();
                clientDone.TrySetResult(true);
            }).Start();

            await clientDone.Task;
        }
        public void Start()
        {
            startTime = DateTime.Now;
            running   = true;

            monitorThread = new Thread(SafeAction.Wrap(() =>
            {
                if (TryConnectMonitor())
                {
                    buildMonitorRemote.StartBuild(builderId, startTime);
                }

                int delay = 300;
                while (running)
                {
                    Thread.Sleep(delay);
                    delay = SendThreadUpdate() ? 300 : 1000;
                }
                SendThreadUpdate();

                if (TryConnectMonitor())
                {
                    buildMonitorRemote.EndBuild(builderId, DateTime.Now);
                }

                try
                {
                    // ReSharper disable SuspiciousTypeConversion.Global
                    var communicationObj = buildMonitorRemote as ICommunicationObject;
                    // ReSharper restore SuspiciousTypeConversion.Global
                    if (communicationObj != null)
                    {
                        communicationObj.Close();
                    }
                }
                // We don't know the layer to close under the client channel so it might throw potentially any exception.
                // Let's ignore them all because at this step we're just cleaning up things.
                // ReSharper disable EmptyGeneralCatchClause
                catch
                // ReSharper restore EmptyGeneralCatchClause
                { }
            }))
            {
                IsBackground = true, Name = "Monitor Thread"
            };

            monitorThread.Start();
        }
Beispiel #7
0
        /// <summary>
        /// Create an empty register.
        /// </summary>
        public FontManager(IDatabaseFileProviderService fileProviderService)
        {
            contentManager = new ContentManager(fileProviderService);

            // Preload proper freetype native library (depending on CPU type)
            NativeLibraryHelper.Load("freetype.dll", typeof(FontManager));

            // create a freetype library used to generate the bitmaps
            freetypeLibrary = new Library();

            // launch the thumbnail builder thread
            bitmapBuilderThread = new Thread(SafeAction.Wrap(BuildBitmapThread))
            {
                IsBackground = true, Name = "Bitmap Builder thread"
            };
            bitmapBuilderThread.Start();
        }
Beispiel #8
0
        /// <summary>
        /// Create an empty register.
        /// </summary>
        public FontManager()
        {
            assetManager = new AssetManager();

            // Preload proper freetype native library (depending on CPU type)
            Core.NativeLibrary.PreloadLibrary("freetype.dll");

            // create a freetype library used to generate the bitmaps
            freetypeLibrary = new Library();

#if SILICONSTUDIO_PLATFORM_WINDOWS_RUNTIME
            Windows.System.Threading.ThreadPool.RunAsync(operation => SafeAction.Wrap(BuildBitmapThread)());
#else
            // launch the thumbnail builder thread
            bitmapBuilderThread = new Thread(SafeAction.Wrap(BuildBitmapThread))
            {
                IsBackground = true, Name = "Bitmap Builder thread"
            };
            bitmapBuilderThread.Start();
#endif
        }
Beispiel #9
0
        /// <summary>
        /// Create an empty register.
        /// </summary>
        public FontManager(IDatabaseFileProviderService fileProviderService)
        {
            contentManager = new ContentManager(fileProviderService);

            // Preload proper freetype native library (depending on CPU type)
            Core.NativeLibrary.PreloadLibrary("freetype.dll", typeof(FontManager));

            // create a freetype library used to generate the bitmaps
            freetypeLibrary = new Library();

#if XENKO_PLATFORM_UWP
            Windows.System.Threading.ThreadPool.RunAsync(operation => SafeAction.Wrap(BuildBitmapThread)());
#else
            // launch the thumbnail builder thread
            bitmapBuilderThread = new Thread(SafeAction.Wrap(BuildBitmapThread))
            {
                IsBackground = true, Name = "Bitmap Builder thread"
            };
            bitmapBuilderThread.Start();
#endif
        }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EditorGameController{TEditorGame}"/> class.
        /// </summary>
        /// <param name="asset">The asset associated with this instance.</param>
        /// <param name="editor">The editor associated with this instance.</param>
        /// <param name="gameFactory">The factory to create the editor game.</param>
        protected EditorGameController([NotNull] AssetViewModel asset, [NotNull] GameEditorViewModel editor, [NotNull] EditorGameFactory <TEditorGame> gameFactory)
        {
            if (asset == null)
            {
                throw new ArgumentNullException(nameof(asset));
            }
            if (editor == null)
            {
                throw new ArgumentNullException(nameof(editor));
            }

            Asset  = asset;
            Editor = editor;
            GameSideNodeContainer = new SessionNodeContainer(asset.Session)
            {
                NodeBuilder = { NodeFactory = new AssetNodeFactory() }
            };

            //Logger = GlobalLogger.GetLogger("Scene");
            Logger    = new LoggerResult();
            debugPage = EditorDebugTools.CreateLogDebugPage(Logger, "Scene");

            // Create the game
            var builderService = asset.ServiceProvider.Get <GameStudioBuilderService>();

            Game = gameFactory(gameContentLoadedTaskSource, builderService.EffectCompiler, builderService.EffectLogPath);
            Game.PackageSettings = asset.ServiceProvider.Get <GameSettingsProviderService>();
            sceneGameThread      = new Thread(SafeAction.Wrap(SceneGameRunThread))
            {
                IsBackground = true, Name = $"EditorGameThread ({asset.Url})"
            };
            sceneGameThread.SetApartmentState(ApartmentState.STA);

            Debug  = new EditorGameDebugService();
            Loader = new EditorContentLoader(this, Logger, asset, Game);
        }
Beispiel #11
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        public BuildResultCode Run(Mode mode, bool writeIndexFile = true)
        {
            // When we setup the database ourself we have to take responsibility to close it after
            var shouldCloseDatabase = ObjectDatabase == null;

            OpenObjectDatabase(buildPath, indexName);

            PreRun();

            runMode = mode;

            if (IsRunning)
            {
                throw new InvalidOperationException("An instance of this Builder is already running.");
            }

            // reset build cache from previous build run
            cancellationTokenSource = new CancellationTokenSource();
            Cancelled = false;
            IsRunning = true;
            DisableCompressionIds.Clear();

            // Reseting result map
            var inputHashes = FileVersionTracker.GetDefault();
            {
                var builderContext = new BuilderContext(inputHashes, TryExecuteRemote);

                resultMap = ObjectDatabase;

                scheduler = new Scheduler();

                // Schedule the build
                ScheduleBuildStep(builderContext, null, Root, InitialVariables);

                // Create threads
                var threads = Enumerable.Range(0, ThreadCount).Select(x => new Thread(SafeAction.Wrap(RunUntilEnd))
                {
                    IsBackground = true
                }).ToArray();

                // Start threads
                int threadId = 0;
                foreach (var thread in threads)
                {
                    thread.Name = (BuilderName ?? "Builder") + " worker thread " + (++threadId);
                    thread.Start();
                }

                // Wait for all threads to finish
                foreach (var thread in threads)
                {
                    thread.Join();
                }
            }

            BuildResultCode result;

            if (runMode == Mode.Build)
            {
                if (cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Error("Build cancelled.");
                    result = BuildResultCode.Cancelled;
                }
                else if (stepCounter.Get(ResultStatus.Failed) > 0 || stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed) > 0)
                {
                    Logger.Error($"Build finished in {stepCounter.Total} steps. Command results: {stepCounter.Get(ResultStatus.Successful)} succeeded, {stepCounter.Get(ResultStatus.NotTriggeredWasSuccessful)} up-to-date, {stepCounter.Get(ResultStatus.Failed)} failed, {stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed)} not triggered due to previous failure.");
                    Logger.Error("Build failed.");
                    result = BuildResultCode.BuildError;
                }
                else
                {
                    Logger.Info($"Build finished in {stepCounter.Total} steps. Command results: {stepCounter.Get(ResultStatus.Successful)} succeeded, {stepCounter.Get(ResultStatus.NotTriggeredWasSuccessful)} up-to-date, {stepCounter.Get(ResultStatus.Failed)} failed, {stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed)} not triggered due to previous failure.");
                    Logger.Info("Build is successful.");
                    result = BuildResultCode.Successful;
                }
            }
            else
            {
                string modeName;
                switch (runMode)
                {
                case Mode.Clean:
                    modeName = "Clean";
                    break;

                case Mode.CleanAndDelete:
                    modeName = "Clean-and-delete";
                    break;

                default:
                    throw new InvalidOperationException("Builder executed in unknown mode.");
                }

                if (cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Error(modeName + " has been cancelled.");
                    result = BuildResultCode.Cancelled;
                }
                else if (stepCounter.Get(ResultStatus.Failed) > 0 || stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed) > 0)
                {
                    Logger.Error(modeName + " has failed.");
                    result = BuildResultCode.BuildError;
                }
                else
                {
                    Logger.Error(modeName + " has been successfully completed.");
                    result = BuildResultCode.Successful;
                }
            }
            scheduler = null;
            resultMap = null;
            IsRunning = false;

            if (shouldCloseDatabase)
            {
                CloseObjectDatabase();
            }

            return(result);
        }
Beispiel #12
0
 public async Task StartClient(IPAddress address, int port)
 {
     clientConnected = new TaskCompletionSource <bool>();
     new Thread(SafeAction.Wrap(() => ClientThread(address, port))).Start();
     await clientConnected.Task;
 }
Beispiel #13
0
 public void StartServer(int port)
 {
     new Thread(SafeAction.Wrap(() => ServerThread(port))).Start();
 }
Beispiel #14
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        public BuildResultCode Run(Mode mode, bool writeIndexFile = true, bool enableMonitor = true)
        {
            runMode = mode;

            if (IsRunning)
            {
                throw new InvalidOperationException("An instance of this Builder is already running.");
            }

            // reset build cache from previous build run
            var parameters = new BuildParameterCollection();

            cancellationTokenSource = new CancellationTokenSource();
            Cancelled = false;
            IsRunning = true;
            DisableCompressionIds.Clear();

            // Reseting result map
            var inputHashes = FileVersionTracker.GetDefault();

            {
                var builderContext = new BuilderContext(buildPath, buildProfile, inputHashes, parameters, MaxParallelProcesses, SlaveBuilderPath);
                if (!string.IsNullOrWhiteSpace(MetadataDatabaseDirectory))
                {
                    var metadataProvider = new QueryMetadataProvider();
                    if (metadataProvider.Open(Path.Combine(MetadataDatabaseDirectory, QueryMetadataProvider.DefaultDatabaseFilename), false))
                    {
                        builderContext.MetadataProvider = metadataProvider;
                    }
                }

                resultMap = IndexFileCommand.ObjectDatabase;

                scheduler = new Scheduler();
                if (enableMonitor)
                {
                    threadMonitors.Add(new BuildThreadMonitor(scheduler, BuilderId));
                    foreach (var monitorPipeName in MonitorPipeNames)
                    {
                        threadMonitors.Add(new BuildThreadMonitor(scheduler, BuilderId, monitorPipeName));
                    }

                    foreach (var threadMonitor in threadMonitors)
                    {
                        threadMonitor.Start();
                    }
                }

                ScheduleBuildStep(builderContext, null, Root, InitialVariables);

                // Create threads
                var threads = Enumerable.Range(0, ThreadCount).Select(x => new Thread(SafeAction.Wrap(RunUntilEnd))
                {
                    IsBackground = true
                }).ToArray();

                // Start threads
                int threadId = 0;
                foreach (var thread in threads)
                {
                    thread.Name = "Builder thread " + (++threadId);
                    thread.Start();
                }

                // Wait for all threads to finish
                foreach (var thread in threads)
                {
                    thread.Join();
                }

                foreach (var threadMonitor in threadMonitors)
                {
                    threadMonitor.Finish();
                }

                foreach (var threadMonitor in threadMonitors)
                {
                    threadMonitor.Join();
                }
            }

            threadMonitors.Clear();
            BuildResultCode result;

            if (runMode == Mode.Build)
            {
                Logger.Info("");
                if (cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Error("Build cancelled.");
                    result = BuildResultCode.Cancelled;
                }
                else if (stepCounter.Get(ResultStatus.Failed) > 0 || stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed) > 0)
                {
                    Logger.Error("Build finished in {0} steps. Command results: {1} succeeded, {2} up-to-date, {3} failed, {4} not triggered due to previous failure.",
                                 stepCounter.Total, stepCounter.Get(ResultStatus.Successful), stepCounter.Get(ResultStatus.NotTriggeredWasSuccessful),
                                 stepCounter.Get(ResultStatus.Failed), stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed));

                    Logger.Error("Build failed.");
                    result = BuildResultCode.BuildError;
                }
                else
                {
                    Logger.Info("Build finished in {0} steps. Command results: {1} succeeded, {2} up-to-date, {3} failed, {4} not triggered due to previous failure.",
                                stepCounter.Total, stepCounter.Get(ResultStatus.Successful), stepCounter.Get(ResultStatus.NotTriggeredWasSuccessful),
                                stepCounter.Get(ResultStatus.Failed), stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed));

                    Logger.Info("Build is successful.");
                    result = BuildResultCode.Successful;
                }
            }
            else
            {
                // Clean input hashes file
                if (VirtualFileSystem.FileExists(InputHashesFileFullPath))
                {
                    try
                    {
                        VirtualFileSystem.FileDelete(InputHashesFileFullPath);
                    }
                    catch (IOException)
                    {
                        return(BuildResultCode.BuildError);
                    }
                }
                string modeName;
                switch (runMode)
                {
                case Mode.Clean:
                    modeName = "Clean";
                    break;

                case Mode.CleanAndDelete:
                    modeName = "Clean-and-delete";
                    break;

                default:
                    throw new InvalidOperationException("Builder executed in unknown mode.");
                }

                if (cancellationTokenSource.IsCancellationRequested)
                {
                    Logger.Error(modeName + " has been cancelled.");
                    result = BuildResultCode.Cancelled;
                }
                else if (stepCounter.Get(ResultStatus.Failed) > 0 || stepCounter.Get(ResultStatus.NotTriggeredPrerequisiteFailed) > 0)
                {
                    Logger.Error(modeName + " has failed.");
                    result = BuildResultCode.BuildError;
                }
                else
                {
                    Logger.Error(modeName + " has been successfully completed.");
                    result = BuildResultCode.Successful;
                }
            }
            scheduler = null;
            resultMap = null;
            IsRunning = false;

            return(result);
        }