Esempio n. 1
0
        public SceneRenderer(GameSettingsAsset gameSettings)
        {
            if (gameSettings == null) throw new ArgumentNullException(nameof(gameSettings));

            // Initialize services
            Services = new ServiceRegistry();
            ContentManager = new ContentManager(Services);

            var renderingSettings = gameSettings.Get<RenderingSettings>();
            GraphicsDevice = GraphicsDevice.New(DeviceCreationFlags.None, new[] { renderingSettings.DefaultGraphicsProfile });

            var graphicsDeviceService = new GraphicsDeviceServiceLocal(Services, GraphicsDevice);
            EffectSystem = new EffectSystem(Services);
            GraphicsContext = new GraphicsContext(GraphicsDevice);
            Services.AddService(typeof(GraphicsContext), GraphicsContext);

            SceneSystem = new SceneSystem(Services);

            // Create game systems
            GameSystems = new GameSystemCollection(Services);
            GameSystems.Add(new GameFontSystem(Services));
            GameSystems.Add(new UISystem(Services));
            GameSystems.Add(EffectSystem);
            GameSystems.Add(SceneSystem);
            GameSystems.Initialize();

            // Fake presenter
            // TODO GRAPHICS REFACTOR: This is needed be for render stage setup
            GraphicsDevice.Presenter = new RenderTargetGraphicsPresenter(GraphicsDevice,
                Texture.New2D(GraphicsDevice, renderingSettings.DefaultBackBufferWidth, renderingSettings.DefaultBackBufferHeight,
                    renderingSettings.ColorSpace == ColorSpace.Linear ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget),
                PixelFormat.D24_UNorm_S8_UInt);

            SceneSystem.MainRenderFrame = RenderFrame.FromTexture(GraphicsDevice.Presenter.BackBuffer, GraphicsDevice.Presenter.DepthStencilBuffer);
        }
Esempio n. 2
0
        public GameEngineBase(ContentManager contentManager, IServiceRegistry services, GameSystemCollection gameSystems = null)
        {
            Logger = GlobalLogger.GetLogger(GetType().GetTypeInfo().Name);

            GameClockManager = new GameClockManager(PhysicsGameTime);
            _targetTimeDriftAdjustmentThreshold = GameClockManager.SimulationDeltaTime.Ticks / 10;     // 10% of a single sim step

            Services    = (ServiceRegistry)services;
            Content     = contentManager;
            GameSystems = gameSystems ?? new GameSystemCollection(Services);

            // Replacing existing IGameSystemCollection with our own
            var existingGameSystems = Services.GetService <IGameSystemCollection>();

            if (existingGameSystems != null)
            {
                Services.RemoveService <IGameSystemCollection>();
            }
            Services.AddOrOverwriteService <IGameSystemCollection>(GameSystems);

            var networkAssetDatabase = new NetworkAssetDatabase(Content, assetFolderUrls: new[] { "Prefabs", "Scenes" });

            Services.AddOrOverwriteService(networkAssetDatabase);

            Services.AddOrOverwriteService(GameClockManager);

            var gameSettingsService = services.GetSafeServiceAs <IGameSettingsService>();

            Settings = gameSettingsService.Settings;
        }
Esempio n. 3
0
        public SceneRenderer(GameSettingsAsset gameSettings)
        {
            if (gameSettings == null)
            {
                throw new ArgumentNullException(nameof(gameSettings));
            }

            // Initialize services
            Services       = new ServiceRegistry();
            ContentManager = new ContentManager(Services);
            Services.AddService(typeof(IContentManager), ContentManager);
            Services.AddService(typeof(ContentManager), ContentManager);

            var renderingSettings = gameSettings.GetOrCreate <RenderingSettings>();

            GraphicsDevice = GraphicsDevice.New(DeviceCreationFlags.Debug, new[] { renderingSettings.DefaultGraphicsProfile });

            var graphicsDeviceService = new GraphicsDeviceServiceLocal(Services, GraphicsDevice);

            Services.AddService(typeof(IGraphicsDeviceService), graphicsDeviceService);
            EffectSystem = new EffectSystem(Services);
            Services.AddService(typeof(EffectSystem), EffectSystem);

            GraphicsContext = new GraphicsContext(GraphicsDevice);
            Services.AddService(typeof(GraphicsContext), GraphicsContext);

            SceneSystem = new SceneSystem(Services);
            Services.AddService(typeof(SceneSystem), SceneSystem);

            // Create game systems
            GameSystems = new GameSystemCollection(Services);
            Services.AddService(typeof(IGameSystemCollection), GameSystems);

            var gameFontSystem = new GameFontSystem(Services);

            Services.AddService(typeof(FontSystem), gameFontSystem.FontSystem);
            Services.AddService(typeof(IFontFactory), gameFontSystem.FontSystem);
            GameSystems.Add(gameFontSystem);

            var uiSystem = new UISystem(Services);

            Services.AddService(typeof(UISystem), uiSystem);
            GameSystems.Add(uiSystem);

            GameSystems.Add(EffectSystem);
            GameSystems.Add(SceneSystem);
            GameSystems.Initialize();

            // Fake presenter
            // TODO GRAPHICS REFACTOR: This is needed be for render stage setup
            GraphicsDevice.Presenter = new RenderTargetGraphicsPresenter(GraphicsDevice,
                                                                         Texture.New2D(GraphicsDevice, renderingSettings.DefaultBackBufferWidth, renderingSettings.DefaultBackBufferHeight,
                                                                                       renderingSettings.ColorSpace == ColorSpace.Linear ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget),
                                                                         PixelFormat.D24_UNorm_S8_UInt);

            GraphicsContext.CommandList.SetRenderTarget(GraphicsDevice.Presenter.DepthStencilBuffer, GraphicsDevice.Presenter.BackBuffer);
        }
Esempio n. 4
0
        /// <inheritdoc />
        protected override void OnSystemAdd()
        {
            gameSystemCollection = Services.GetService <IGameSystemCollection>() as GameSystemCollection;
            if (gameSystemCollection == null)
            {
                throw new Exception("NavigationProcessor can not access the game systems collection");
            }

            gameSystemCollection.CollectionChanged += GameSystemsOnCollectionChanged;
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Game" /> class.
        /// </summary>
        public Game()
        {
            // Internals
            drawableGameSystems          = new List <IDrawable>();
            currentlyContentGameSystems  = new List <IContentable>();
            currentlyDrawingGameSystems  = new List <IDrawable>();
            pendingGameSystems           = new List <IGameSystem>();
            updateableGameSystems        = new List <IUpdateable>();
            currentlyUpdatingGameSystems = new List <IUpdateable>();
            contentableGameSystems       = new List <IContentable>();
            contentCollector             = new DisposeCollector();
            gameTime                 = new GameTime();
            totalGameTime            = new TimeSpan();
            timer                    = new TimerTick();
            IsFixedTimeStep          = false;
            maximumElapsedTime       = TimeSpan.FromMilliseconds(500.0);
            TargetElapsedTime        = TimeSpan.FromTicks(10000000 / 60); // target elapsed time is by default 60Hz
            lastUpdateCount          = new int[4];
            nextLastUpdateCountIndex = 0;

            // Calculate the updateCountAverageSlowLimit (assuming moving average is >=3 )
            // Example for a moving average of 4:
            // updateCountAverageSlowLimit = (2 * 2 + (4 - 2)) / 4 = 1.5f
            const int BadUpdateCountTime = 2; // number of bad frame (a bad frame is a frame that has at least 2 updates)
            var       maxLastCount       = 2 * Math.Min(BadUpdateCountTime, lastUpdateCount.Length);

            updateCountAverageSlowLimit = (float)(maxLastCount + (lastUpdateCount.Length - maxLastCount)) / lastUpdateCount.Length;

            // Externals
            Services         = new GameServiceRegistry();
            Content          = new ContentManager(Services);
            LaunchParameters = new LaunchParameters();
            GameSystems      = new GameSystemCollection();

            // Create Platform
            gamePlatform                = GamePlatform.Create(this);
            gamePlatform.Activated     += gamePlatform_Activated;
            gamePlatform.Deactivated   += gamePlatform_Deactivated;
            gamePlatform.Exiting       += gamePlatform_Exiting;
            gamePlatform.WindowCreated += GamePlatformOnWindowCreated;

            // By default, add a FileResolver for the ContentManager
            Content.Resolvers.Add(new FileSystemContentResolver(gamePlatform.DefaultAppDirectory));

            // Setup registry
            Services.AddService(typeof(IServiceRegistry), Services);
            Services.AddService(typeof(IContentManager), Content);
            Services.AddService(typeof(IGamePlatform), gamePlatform);

            // Register events on GameSystems.
            GameSystems.ItemAdded   += GameSystems_ItemAdded;
            GameSystems.ItemRemoved += GameSystems_ItemRemoved;

            IsActive = true;
        }
Esempio n. 6
0
 public static void TryAdd <T>(this GameSystemCollection gameSystems, T gameSystem)
     where T : GameSystemBase
 {
     for (int i = 0; i < gameSystems.Count; i++)
     {
         if (gameSystems[i] == gameSystem)
         {
             return;
         }
     }
     gameSystems.Add(gameSystem);
 }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Game"/> class.
        /// </summary>
        public HeadlessGame()
        {
            // Internals
            Log                = GlobalLogger.GetLogger(GetType().GetTypeInfo().Name);
            UpdateTime         = new GameTime();
            autoTickTimer      = new TimerTick();
            IsFixedTimeStep    = true;
            maximumElapsedTime = TimeSpan.FromMilliseconds(500.0);
            TargetElapsedTime  = TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 60); // target elapsed time is by default 60Hz

            // Externals
            Services = new ServiceRegistry();

            GraphicsDevice = GraphicsDevice.New(DeviceCreationFlags.VideoSupport, new GraphicsProfile[]
            {
                GraphicsProfile.Level_11_0,
                GraphicsProfile.Level_11_1,
                GraphicsProfile.Level_11_2
            });
            Services.AddService <IGraphicsDeviceService>(new GraphicsDeviceServiceLocal(GraphicsDevice));

            // Database file provider
            Services.AddService <IDatabaseFileProviderService>(new DatabaseFileProviderService(null));

            GameSystems = new GameSystemCollection(Services);
            Services.AddService <IGameSystemCollection>(GameSystems);

            // Setup registry
            Services.AddService <IGame>(this);

            // Register the logger backend before anything else
            logListener = GetLogListener();

            if (logListener != null)
            {
                GlobalLogger.GlobalMessageLogged += logListener;
            }

            // Create all core services, except Input which is created during `Initialize'.
            // Registration takes place in `Initialize'.
            Script = new ScriptSystem(Services);
            Services.AddService(Script);

            SceneSystem = new SceneSystem(Services);
            Services.AddService(SceneSystem);

            Streaming = new StreamingManager(Services);
        }
Esempio n. 8
0
        public ThumbnailGenerator(EffectCompilerBase effectCompiler)
        {
            // create base services
            Services = new ServiceRegistry();
            Services.AddService(MicrothreadLocalDatabases.ProviderService);
            ContentManager = new ContentManager(Services);
            Services.AddService <IContentManager>(ContentManager);
            Services.AddService(ContentManager);

            GraphicsDevice      = GraphicsDevice.New();
            GraphicsContext     = new GraphicsContext(GraphicsDevice);
            GraphicsCommandList = GraphicsContext.CommandList;
            Services.AddService(GraphicsContext);
            sceneSystem = new SceneSystem(Services);
            Services.AddService(sceneSystem);
            fontSystem = new GameFontSystem(Services);
            Services.AddService(fontSystem.FontSystem);
            Services.AddService <IFontFactory>(fontSystem.FontSystem);

            GraphicsDeviceService = new GraphicsDeviceServiceLocal(Services, GraphicsDevice);
            Services.AddService(GraphicsDeviceService);

            var uiSystem = new UISystem(Services);

            Services.AddService(uiSystem);

            var physicsSystem = new Bullet2PhysicsSystem(Services);

            Services.AddService <IPhysicsSystem>(physicsSystem);

            gameSystems = new GameSystemCollection(Services)
            {
                fontSystem, uiSystem, physicsSystem
            };
            Services.AddService <IGameSystemCollection>(gameSystems);
            Simulation.DisableSimulation = true; //make sure we do not simulate physics within the editor

            // initialize base services
            gameSystems.Initialize();

            // create remaining services
            EffectSystem = new EffectSystem(Services);
            Services.AddService(EffectSystem);

            gameSystems.Add(EffectSystem);
            gameSystems.Add(sceneSystem);
            EffectSystem.Initialize();

            // Mount the same database for the cache
            EffectSystem.Compiler = EffectCompilerFactory.CreateEffectCompiler(effectCompiler.FileProvider, EffectSystem);

            // Deactivate the asynchronous effect compilation
            ((EffectCompilerCache)EffectSystem.Compiler).CompileEffectAsynchronously = false;

            // load game system content
            gameSystems.LoadContent();

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 22;
            DefaultFont            = OfflineRasterizedFontCompiler.Compile(fontSystem.FontSystem, fontItem, true);

            // create utility members
            nullGameTime = new GameTime();
            SpriteBatch  = new SpriteBatch(GraphicsDevice);
            UIBatch      = new UIBatch(GraphicsDevice);

            // create the pipeline
            SetUpPipeline();
        }
Esempio n. 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameBase" /> class.
        /// </summary>
        protected GameBase()
        {
            // Internals
            Log = GlobalLogger.GetLogger(GetType().GetTypeInfo().Name);
            updateTime = new GameTime();
            drawTime = new GameTime();
            playTimer = new TimerTick();
            updateTimer = new TimerTick();
            totalUpdateTime = new TimeSpan();
            timer = new TimerTick();
            IsFixedTimeStep = false;
            maximumElapsedTime = TimeSpan.FromMilliseconds(500.0);
            TargetElapsedTime = TimeSpan.FromTicks(10000000 / 60); // target elapsed time is by default 60Hz
            lastUpdateCount = new int[4];
            nextLastUpdateCountIndex = 0;

            // Calculate the updateCountAverageSlowLimit (assuming moving average is >=3 )
            // Example for a moving average of 4:
            // updateCountAverageSlowLimit = (2 * 2 + (4 - 2)) / 4 = 1.5f
            const int BadUpdateCountTime = 2; // number of bad frame (a bad frame is a frame that has at least 2 updates)
            var maxLastCount = 2 * Math.Min(BadUpdateCountTime, lastUpdateCount.Length);
            updateCountAverageSlowLimit = (float)(maxLastCount + (lastUpdateCount.Length - maxLastCount)) / lastUpdateCount.Length;

            // Externals
            Services = new ServiceRegistry();

            // Asset manager
            Asset = new AssetManager(Services);

            LaunchParameters = new LaunchParameters();
            GameSystems = new GameSystemCollection();

            // Create Platform
            gamePlatform = GamePlatform.Create(this);
            gamePlatform.Activated += gamePlatform_Activated;
            gamePlatform.Deactivated += gamePlatform_Deactivated;
            gamePlatform.Exiting += gamePlatform_Exiting;
            gamePlatform.WindowCreated += GamePlatformOnWindowCreated;

            // Setup registry
            Services.AddService(typeof(IGame), this);
            Services.AddService(typeof(IGamePlatform), gamePlatform);

            IsActive = true;
        }
Esempio n. 10
0
        public GameEngineClient(ContentManager contentManager, IServiceRegistry services, GameSystemCollection gameSystems)
            : base(contentManager, services, gameSystems)
        {
            // Note that IGame already part of Services in the client engine because Stride specific systems depends
            // on IGame's existence, however be aware this is NOT included in GameEngineServer, so you must be careful
            // not to get IGame in server side systems.
            Services.AddOrOverwriteService(new GameEngineContext(isClient: true));

            _networkSystem = CreateKeyValue(() => new NetworkSystem(Services));

            _debugTextSystem = CreateKeyValue(() => new DebugTextSystem(Services));
            Services.AddOrOverwriteService(_debugTextSystem.System);

            _physicsSystem         = CreateKeyValue(() => new Bullet2PhysicsSystem(Services));
            _sceneSystem           = CreateKeyValue(() => new SceneSystem(Services));
            _scenePreUpdateSystem  = CreateKeyValue(() => new ScenePreUpdateSystem(Services, _sceneSystem.System));
            _scenePostUpdateSystem = CreateKeyValue(() => new ScenePostUpdateSystem(Services, _sceneSystem.System));

            _scriptSystem = CreateKeyValue(() => new ScriptSystem(Services));
            Services.AddOrOverwriteService(_scriptSystem.System);

            var inputSystem = gameSystems.First(x => x is InputSystem) as InputSystem;

            _inputSystem = CreateKeyValue(inputSystem);
            var inputManager = inputSystem.Manager;

            inputManager.VirtualButtonConfigSet = new VirtualButtonConfigSet();

            _streamingManager = CreateKeyValue(() => new StreamingManager(Services));

            _audioSystem = CreateKeyValue(() => new AudioSystem(Services));
            Services.AddOrOverwriteService(_audioSystem.System);
            Services.AddOrOverwriteService <IAudioEngineProvider>(_audioSystem.System);

            _effectSystem = CreateKeyValue(() => new EffectSystem(Services));
            Services.AddOrOverwriteService(_effectSystem.System);

            _gameFontSystem = CreateKeyValue(() => new GameFontSystem(Services));
            Services.AddOrOverwriteService(_gameFontSystem.System.FontSystem);
            Services.AddOrOverwriteService <IFontFactory>(_gameFontSystem.System.FontSystem);

            _spriteAnimationSystem = CreateKeyValue(() => new SpriteAnimationSystem(Services));
            Services.AddOrOverwriteService(_spriteAnimationSystem.System);

            _uiSystem = CreateKeyValue(() => new UISystem(Services));
            Services.AddOrOverwriteService(_uiSystem.System);

            _profilingSystem = CreateKeyValue(() => new GameProfilingSystem(Services));
            Services.AddOrOverwriteService(_profilingSystem.System);

            //_vrDeviceSystem = CreateKeyValue(() => new VRDeviceSystem(Services));
            //Services.AddOrOverwriteService(_vrDeviceSystem.System);

            // Copy access to the graphics device manager
            Services.AddOrOverwriteService(services.GetSafeServiceAs <IGraphicsDeviceManager>());
            Services.AddOrOverwriteService(services.GetSafeServiceAs <IGraphicsDeviceService>());

            //_dynamicNavigationMeshSystem = CreateKeyValue(() => new DynamicNavigationMeshSystem(Services));
        }
        public async Task Run()
        {
            Services = new ServiceRegistry();

            // Database file provider
            Services.AddService <IDatabaseFileProviderService>(new DatabaseFileProviderService(new DatabaseFileProvider(ObjectDatabase.CreateDefaultDatabase())));

            // Content manager
            Content = new ContentManager(Services);
            Services.AddService <IContentManager>(Content);
            Services.AddService(Content);

            //Services.AddService<IGraphicsDeviceService>(new GraphicsDeviceServiceLocal(null));

            // Game systems
            var gameSystems = new GameSystemCollection(Services);

            Services.AddService <IGameSystemCollection>(gameSystems);
            gameSystems.Initialize();

            // Load scene (physics only)
            var loadSettings = new ContentManagerLoaderSettings
            {
                // Ignore all references (Model, etc...)
                ContentFilter = ContentManagerLoaderSettings.NewContentFilterByType()
            };
            var scene = await Content.LoadAsync <Scene>("MainScene", loadSettings);

            var sceneInstance = new SceneInstance(Services, scene, ExecutionMode.None);
            var sceneSystem   = new SceneSystem(Services)
            {
                SceneInstance = sceneInstance,
            };

            Services.AddService(sceneSystem);

            var physics = new PhysicsProcessor();

            sceneInstance.Processors.Add(physics);

            var socket = new SimpleSocket();

            socket.Connected += clientSocket =>
            {
                Console.WriteLine("Client connected");

                var reader = new BinarySerializationReader(clientSocket.ReadStream);
                while (true)
                {
                    // Receive ray start/end
                    var start = reader.Read <Vector3>();
                    var end   = reader.Read <Vector3>();
                    // Raycast
                    var result = physics.Simulation.Raycast(start, end);
                    Console.WriteLine($"Performing raycast: {(result.Succeeded ? "hit" : "miss")}");
                    // Send result
                    clientSocket.WriteStream.WriteByte((byte)(result.Succeeded ? 1 : 0));
                    clientSocket.WriteStream.Flush();
                }
            };
            await socket.StartServer(2655, false);

            Console.WriteLine("Server listening, press a key to exit");
            Console.ReadKey();
        }