예제 #1
0
        public static void Init(int width, int height)
        {
            m_Game = new Game();
            m_Content = m_Game.Content;
            m_Content.RootDirectory = "Content";

            m_Graphics = new GraphicsDeviceManager(m_Game);
            m_Graphics.PreferredBackBufferFormat = SurfaceFormat.Color;
            m_Graphics.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
            m_Graphics.PreferredBackBufferWidth = width;
            m_Graphics.PreferredBackBufferHeight = height;
            m_Graphics.SynchronizeWithVerticalRetrace = false;
            m_Graphics.PreferMultiSampling = false;
            m_Graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(PreparingDeviceSettings);

            m_Graphics.ApplyChanges();

            if (!m_Graphics.SynchronizeWithVerticalRetrace)
                m_Game.IsFixedTimeStep = false;

            m_DeviceService = (IGraphicsDeviceService)m_Game.Services.GetService(typeof(IGraphicsDeviceService));

            // just to preload the asset. m_Content will return a cached copy later on
            Effect domeFX = m_Content.Load<Effect>("Dome");
            Texture2D texture = m_Content.Load<Texture2D>("Sprite");

            domeFX.Parameters["ParticleSize"].SetValue(2.5f);
            domeFX.Parameters["Texture"].SetValue(texture);
        }
 protected GameComponent( IGraphicsDeviceService graphicsDeviceService, IEventAggregator eventAggregator )
 {
     this._eventAggregator = eventAggregator;
     this._graphicsDeviceService = graphicsDeviceService.NotNull();
     this._graphicsDeviceService.DeviceCreated += this.DeviceCreated;
     this._graphicsDeviceService.DeviceDisposing += this.DeviceDisposing;
 }
예제 #3
0
        public override void Initialize()
        {
            // A reference to the graphics service is mandatory since we need to get the graphics device after it's destroyed
            graphicsService = Game.Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
            graphicsDevice = graphicsService.GraphicsDevice;

            // Those three events are necessary to keep a "fresh" state, see individual methods
            graphicsService.DeviceCreated += delegate { OnDeviceCreated(); };
            graphicsService.DeviceResetting += delegate { OnDeviceResetting(); };
            graphicsService.DeviceReset += delegate { OnDeviceReset(); };

            // Here's the trick... We know it's a form, so let's cast it as a form!
            // No need to say that this won't work on the Xbox 360...
            windowsGameForm = Control.FromHandle(Game.Window.Handle) as Form;

            // After, we add up our own components to it
            InitializeComponent();
            Game.Window.Title = "nu";

            // We can then map events to the components like in a normal Windows Forms context
            //someButton.Click += new EventHandler(someButton_Click);
            //quitMenuItem.Click += delegate { Game.Exit(); };

            // And force a reset so that we set the right target to begin with
            graphicsDevice.Reset();

            base.Initialize();
        }
예제 #4
0
        internal WindowManager(IGraphicsDeviceService graphicsDeviceService)
        {
            if (graphicsDeviceService == null)
                throw new ArgumentNullException("graphicsDeviceService");

            GraphicsDeviceService = graphicsDeviceService;
        }
예제 #5
0
        public override void Initialize()
        {
            base.Initialize();

            isInitialized = true;

            // Get graphics device service
            graphicsDeviceService = Services.GetSafeServiceAs<IGraphicsDeviceService>();

#if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
            Enabled = true;
            directoryWatcher = new DirectoryWatcher("*.xksl");
            directoryWatcher.Modified += FileModifiedEvent;
            // TODO: xkfx too
#endif

            // Setup shader compiler settings from a compilation mode. 
            // TODO: We might want to provide overrides on the GameSettings to specify debug and/or optim level specifically.
            if (Game != null && (((Game)Game).Settings != null))
            {
                effectCompilerParameters.ApplyCompilationMode(((Game)Game).Settings.CompilationMode);
            }

            // Make sure default compiler is created (local if possible otherwise none) if nothing else was explicitely set/requested (i.e. by GameSettings)
            if (Compiler == null)
                Compiler = CreateEffectCompiler();
        }
예제 #6
0
 public override void Initialize()
 {
     // Gets the graphics device service
     graphicsDeviceService = (IGraphicsDeviceService)base.Services.GetService(typeof(IGraphicsDeviceService));
     this.Visible = true;
     base.Initialize();
 }
예제 #7
0
파일: Core.cs 프로젝트: unsign3d/SpaceCore
 public Core(Game game)
     : base(game)
 {
     svc = (IGraphicsDeviceService)game.Services.GetService(typeof(IGraphicsDeviceService));
     graphics =  (GraphicsDeviceManager)svc;
     //remember wich level we are playing
     this.game = game;
 }
예제 #8
0
        internal OpenTKWindowManager(IGraphicsDeviceService graphicsDeviceService, GameWindow gameWindow)
            : base(graphicsDeviceService)
        {
            if (gameWindow == null)
                throw new ArgumentNullException("gameWindow");

            _gameWindow = gameWindow;
        }
예제 #9
0
 public ScreenManager( Game game )
     : base(game)
 {
     graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService(
                                                 typeof( IGraphicsDeviceService ) );
     content = new ContentManager( game.Services );
     content.RootDirectory = "Content";
     current_game = game;
 }
        public VertexPositionTextureDrawer( Camera3D camera3D, IGraphicsDeviceService graphicsDeviceService )
        {
            this._graphicsDeviceService = graphicsDeviceService;
            this._camera = camera3D.NotNull();
            this._camera.Changed += this.UpdateBasicEffect;

            this._graphicsDeviceService.DeviceCreated += this.RecreateBassicEffect;
            this.CreateBasicEffect();
        }
예제 #11
0
        /// <summary>
        /// Constructs a render coordinator. A render manager and synchronous draw methods are automatically provided for you.
        /// </summary>
        /// <param name="deviceService"></param>
        public RenderCoordinator(IGraphicsDeviceService deviceService)
        {
            Manager = new RenderManager(deviceService.GraphicsDevice);

            _SyncBeginDraw = DefaultBeginDraw;
            _SyncEndDraw = DefaultEndDraw;

            CoreInitialize();
        }
        public VertexPositionColorDrawer( IGraphicsDeviceService deviceService, Camera3D camera3D )
        {
            this._camera = camera3D.NotNull();
            this._camera.Changed += this.UpdateBasicEffect;
            this._graphicsDeviceService = deviceService;
            this._graphicsDeviceService.DeviceCreated += this.RecreateBassicEffect;
            this.CreateBasicEffect();

            this.CreateBasicEffect();
        }
예제 #13
0
        /// <summary>Initializes a new frame rate tracking component</summary>
        /// <param name="graphicsDeviceService">
        ///   Graphics device service the counter uses for rendering
        /// </param>
        public FpsComponent(
          IGraphicsDeviceService graphicsDeviceService, string contentRootDirectory
        )
            : base(null)
        {
            this.graphicsDeviceService = graphicsDeviceService;
            this.contentRoot = contentRootDirectory;

            this.frameTimes = new Queue<long>();
            Visible = true;
        }
예제 #14
0
        public DXControlLite(IGraphicsDeviceService deviceService)
        {
            InitializeComponent();

            this.deviceService = deviceService;
            this.Loaded += DXControlLite_Loaded;

            this.deviceService.DeviceCreated += deviceService_DeviceCreated;
            this.deviceService.DeviceLost += deviceService_DeviceLost;
            this.deviceService.DeviceDisposing += deviceService_DeviceDisposing;
        }
예제 #15
0
        /// <summary>
        /// Constructs a new screen manager component.
        /// </summary>
        public ScreenManager(Game game)
            : base(game)
        {
            content = new ContentManager(game.Services, "Content");

            graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService(
                                                        typeof(IGraphicsDeviceService));

            if (graphicsDeviceService == null)
                throw new InvalidOperationException("No graphics device service.");
        }
예제 #16
0
        /// <summary>
        /// Constructs a new screen manager component.
        /// </summary>
        /// <exception cref="InvalidOperationException">No graphics device service.</exception>
        public ScreenManager(Game game)
            : base(game)
        {
            ContentManager = new ContentManager(game.Services);
            _graphicsDeviceService = (IGraphicsDeviceService) game.Services.GetService(
                                                                  typeof (IGraphicsDeviceService));
            game.Exiting += Game_Exiting;

            if (_graphicsDeviceService == null)
                throw new InvalidOperationException("No graphics device service.");
        }
예제 #17
0
        public static WindowManager Create(IGraphicsDeviceService graphicsDeviceService, IntPtr windowHandle)
        {
            if (graphicsDeviceService is GraphicsDeviceManager)
                throw new NotImplementedException("This is not implemented. You need to use the Game instead of the GameWindow.Handle.");

            //Get a Windows.Form
            var window = Control.FromHandle(windowHandle) as Form;
            if (window == null)
                throw new ArgumentException("The windowHandle is not a valid Windows.Form handle.");

            return new FormWindowManager(graphicsDeviceService, window);
        }
		protected override void Initialize()
		{
			base.Initialize();
			_graphicsDeviceManager = new WpfGraphicsDeviceService(this);

			_texture = Content.Load<Texture2D>("hello");

			_spriteBatch = new SpriteBatch(GraphicsDevice);

			_keyboard = new WpfKeyboard(this);
			_mouse = new WpfMouse(this);
		}
예제 #19
0
        /// <summary>
        /// Create an instance of an UI element renderer.
        /// </summary>
        /// <param name="services">The list of registered services</param>
        public ElementRenderer(IServiceRegistry services)
        {
            Content = services.GetSafeServiceAs<IContentManager>();
            GraphicsDeviceService = services.GetSafeServiceAs<IGraphicsDeviceService>();

            UI = services.GetServiceAs<UISystem>();
            if (UI == null)
            {
                UI = new UISystem(services);
                var gameSystems = services.GetServiceAs<IGameSystemCollection>();
                gameSystems?.Add(UI);
            }
        }
    /// <summary>Initializes a new particle system manager</summary>
    /// <param name="graphicsDeviceService">
    ///   Graphics device service being used to render the particle systems
    /// </param>
    public ParticleSystemManager(IGraphicsDeviceService graphicsDeviceService) :
      base(graphicsDeviceService) {

      this.particleSystems = new Dictionary<object, IParticleSystemHolder>();
      this.primitiveBatches = new Dictionary<Type, PrimitiveBatchHolder>();

      this.pruneAsyncResult = new PruneAsyncResult(this);
      this.updateAsyncResult = new UpdateAsyncResult(this);

      this.particleSystemHolders = new IParticleSystemHolder[16];
      this.primitiveBatchHolders = new PrimitiveBatchHolder[4];

      this.holderArraysDirty = true;
    }
예제 #21
0
        public GraphicsContext(IGraphicsDeviceService service, Device d3dDevice, DeviceContext d3dContext)
        {
            this.RenderContext = new RenderContext();

            this.GraphicsService = service;
            this.Device = service.GraphicsDevice;
            this.D3D11Device = d3dDevice;
            this.D3D11Context = d3dContext;

            this.SpriteBatch = new SpriteBatch(service.GraphicsDevice);

            this.GBuffer = new GeometryBuffer(this);
            this.CurrentCamera = new PlanetCamera(6359.99);
        }
예제 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EffectInstallerBase"/> class.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <exception cref="System.ArgumentNullException">services</exception>
        /// <exception cref="System.ArgumentException">Cannot locate IGraphicsDeviceService;services</exception>
        protected EffectInstallerBase(IServiceRegistry services)
        {
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }

            Services = services;
            graphicsDeviceService = (IGraphicsDeviceService)services.GetService(typeof(IGraphicsDeviceService));

            if (graphicsDeviceService == null)
            {
                throw new ArgumentException("Cannot locate IGraphicsDeviceService", "services");
            }
        }
예제 #23
0
        public GraphicsResourceContainer( IGraphicsDeviceService gds )
        {
            if( gds == null )
                throw new ArgumentNullException( "gds" );

            this.gds = gds;

            gds.DeviceCreated += new EventHandler( gds_DeviceCreated );
            gds.DeviceDestroyed += new EventHandler( gds_DeviceDestroyed );
            gds.DeviceLost += new EventHandler( gds_DeviceLost );
            gds.DeviceReset += new EventHandler( gds_DeviceReset );

            if( gds.State == Gui.GraphicsDeviceState.Created )
                gds_DeviceCreated( gds, EventArgs.Empty );
        }
예제 #24
0
        internal void Initialize(IServiceRegistry registry)
        {
            Services = registry;

            graphicsDeviceService = Services.GetSafeServiceAs<IGraphicsDeviceService>();

            Game = Services.GetSafeServiceAs<IGame>();
            Content = (ContentManager)Services.GetSafeServiceAs<IAssetManager>();
            Input = Services.GetSafeServiceAs<InputManager>();
            Script = Services.GetSafeServiceAs<ScriptSystem>();
            SceneSystem = Services.GetSafeServiceAs<SceneSystem>();
            EffectSystem = Services.GetSafeServiceAs<EffectSystem>();
            Audio = Services.GetSafeServiceAs<AudioSystem>();
            SpriteAnimation = Services.GetSafeServiceAs<SpriteAnimationSystem>();
        }
        public override void Initialize()
        {
            if (!_initialized)
            {
                _graphicsDeviceService = _services.Get<IGraphicsDeviceService>();
                Ensure.NotNull(_graphicsDeviceService, "Graphics device service is missing");

                _graphicsDeviceService.DeviceCreated += new EventHandler<EventArgs>(this.GraphicsDeviceCreated);
                _graphicsDeviceService.DeviceDisposing += new EventHandler<EventArgs>(this.GraphicsDeviceDisposing);
                if (_graphicsDeviceService.GraphicsDevice != null)
                {
                    this.LoadContent();
                }
            }
        }
 public ScreenManager(Game game, GraphicsDeviceManager graphics)
 {
     this.content = new ContentManager(game.Services, "Content");
     this.GraphicsDevice = graphics.GraphicsDevice;
     this.graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService(typeof(IGraphicsDeviceService));
     if (this.graphicsDeviceService == null)
     {
         throw new InvalidOperationException("No graphics device service.");
     }
     this.lightingSystemManager = new LightingSystemManager(game.Services);
     this.sceneState = new SceneState();
     this.inter = new SceneInterface(graphics);
     this.inter.CreateDefaultManagers(false, false, true);
     this.editor = new LightingSystemEditor(game.Services, graphics, game)
     {
         UserHandledView = true
     };
     this.inter.AddManager(this.editor);
 }
예제 #27
0
        public override void Initialize()
        {
            base.Initialize();

            isInitialized = true;

            // Get graphics device service
            graphicsDeviceService = Services.GetSafeServiceAs<IGraphicsDeviceService>();

#if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
            Enabled = true;
            directoryWatcher = new DirectoryWatcher("*.xksl");
            directoryWatcher.Modified += FileModifiedEvent;
            // TODO: xkfx too
#endif

            // Make sure default compiler is created (local if possible otherwise none) if nothing else was explicitely set/requested (i.e. by GameSettings)
            if (Compiler == null)
                Compiler = CreateEffectCompiler();
        }
예제 #28
0
        public static WindowManager Create(IGraphicsDeviceService graphicsDeviceService, GameWindow gameWindow)
        {
            if (graphicsDeviceService is GraphicsDeviceManager)
                throw new NotImplementedException("This is not implemented. You need to use the Game instead of the GameWindow.");

            //Get a OpenTKGameWindow
            var form = gameWindow.GetForm();
            if (form != null)
                return new OpenTKWindowManager(graphicsDeviceService as GraphicsDeviceService, form);

            //Get a Windows.Form
            try
            {
                return Create(graphicsDeviceService, gameWindow.Handle);
            }
            catch (ArgumentException) { }

            //Could not find a window...
            throw new ArgumentException("The game window could not be found."); //TODO: Add a more meaningful message?
        }
예제 #29
0
        public CCApplication(Game game, IGraphicsDeviceService service)
            : base(game)
        {
            if (Game.Services.GetService(typeof(IGraphicsDeviceService)) == null)
            {
                Game.Services.AddService(typeof(IGraphicsDeviceService), service);
            }

            CCDrawManager.Init(service);

            Content = game.Content;
            HandleMediaStateAutomatically = true;

            game.IsFixedTimeStep = true;

            TouchPanel.EnabledGestures = GestureType.Tap;

            game.Activated += GameActivated;
            game.Deactivated += GameDeactivated;
            game.Exiting += GameExiting;
        }
예제 #30
0
        void InitializeOther(bool useTestGraphicsDeviceManager)
        {
            graphics = useTestGraphicsDeviceManager ? (IGraphicsDeviceService)new DummyGraphicsDeviceManager(this) : new GraphicsDeviceManager(this);

            content = new ContentManager(Services);
            TargetElapsedTime = TimeSpan.FromMilliseconds(100);

            //Components.Add(new MyComponent(this));
            //Components.Add(new MyDrawable(this));
            //Components.Add(new Invisible(this));
            //Components.Add(new NotEnabled(this));
            //Components.Add(new Ordered(this, 20));
            //Components.Add(new Ordered(this, 15));
            //Components.Add(new Ordered(this, 10));
            
            #region Mono.Xna specific
#if !MSXNAONLY
            Window = _window = new TestGameWindow(this);
#endif
            #endregion Mono.Xna specific
        }
예제 #31
0
파일: GameBase.cs 프로젝트: sonicviz/xenko
        internal void InitializeBeforeRun()
        {
            try
            {
                using (var profile = Profiler.Begin(GameProfilingKeys.GameInitialize))
                {
                    // Initialize this instance and all game systems before trying to create the device.
                    Initialize();

                    // Make sure that the device is already created
                    graphicsDeviceManager.CreateDevice();

                    // Gets the graphics device service
                    graphicsDeviceService = Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                    if (graphicsDeviceService == null)
                    {
                        throw new InvalidOperationException("No GraphicsDeviceService found");
                    }

                    // Checks the graphics device
                    if (graphicsDeviceService.GraphicsDevice == null)
                    {
                        throw new InvalidOperationException("No GraphicsDevice found");
                    }

                    // Setup the graphics device if it was not already setup.
                    SetupGraphicsDeviceEvents();

                    // Bind Graphics Context enabling initialize to use GL API eg. SetData to texture ...etc
                    BeginDraw();

                    LoadContentInternal();

                    IsRunning = true;

                    BeginRun();

                    timer.Reset();
                    updateTime.Reset(totalUpdateTime);

                    // Run the first time an update
                    updateTimer.Reset();
                    using (Profiler.Begin(GameProfilingKeys.GameUpdate))
                    {
                        Update(updateTime);
                    }
                    updateTimer.Tick();
                    singleFrameUpdateTime += updateTimer.ElapsedTime;

                    // Reset PlayTime
                    playTimer.Reset();

                    // Unbind Graphics Context without presenting
                    EndDraw(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Unexpected exception", ex);
                throw;
            }
        }
예제 #32
0
 public ServiceProvider(IGraphicsDeviceService deviceService)
 {
     this.deviceService = deviceService;
 }
예제 #33
0
 /// <summary>Creates a new ellipse renderer for the given game.</summary>
 /// <param name="content">The content manager to use for loading assets.</param>
 /// <param name="graphics">The graphics device service.</param>
 public FilledEllipse(ContentManager content, IGraphicsDeviceService graphics)
     : base(content, graphics, "Shaders/FilledCircle")
 {
     // Set defaults.
     Gradient = 1f;
 }
예제 #34
0
 public virtual void Initialize()
 {
     // Gets the graphics device service
     graphicsDeviceService = (IGraphicsDeviceService)registry.GetService(typeof(IGraphicsDeviceService));
 }
예제 #35
0
 public ServiceProvider(IGraphicsDeviceService graphicsDeviceService)
 {
     GraphicsDeviceService = graphicsDeviceService;
 }
예제 #36
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            object result = null;

            // FIXME: Should this block be here? -flibit
            if (graphicsDeviceService == null)
            {
                graphicsDeviceService = ServiceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            Stream stream            = null;
            string modifiedAssetName = String.Empty;             // Will be used if we have to guess a filename

            try
            {
                stream = OpenStream(assetName);
            }
            catch (Exception e)
            {
                // Okay, so we couldn’t open it. Maybe it needs a different extension?
                // FIXME: Normalizing checks for a file on the disk, what about custom streams? -flibit
                modifiedAssetName = FileHelpers.NormalizeFilePathSeparators(
                    Path.Combine(RootDirectoryFullPath, assetName)
                    );
                if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                {
                    modifiedAssetName = Texture2DReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(SoundEffect)))
                {
                    modifiedAssetName = SoundEffectReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Effect)))
                {
                    modifiedAssetName = EffectReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Song)))
                {
                    modifiedAssetName = SongReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Video)))
                {
                    modifiedAssetName = VideoReader.Normalize(modifiedAssetName);
                }

                // Did we get anything…?
                if (String.IsNullOrEmpty(modifiedAssetName))
                {
                    // Nope, nothing we’re aware of!
                    throw new ContentLoadException(
                              "Could not load asset " + assetName + "! Error: " + e.Message,
                              e
                              );
                }

                stream = File.OpenRead(modifiedAssetName);
            }

            using (BinaryReader xnbReader = new BinaryReader(stream))
            {
                try
                {
                    // Try to load as XNB file
                    using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                    {
                        result = reader.ReadAsset <T>();
                        GraphicsResource resource = result as GraphicsResource;
                        if (resource != null)
                        {
                            resource.Name = assetName;
                        }
                    }
                }
                catch (Exception e)
                {
                    // FIXME: Assuming seekable streams! -flibit
                    stream.Seek(0, SeekOrigin.Begin);

                    // Try to load as a raw asset
                    if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                    {
                        Texture2D texture = Texture2D.FromStream(
                            graphicsDeviceService.GraphicsDevice,
                            stream
                            );
                        texture.Name = assetName;
                        result       = texture;
                    }
                    else if ((typeof(T) == typeof(SoundEffect)))
                    {
                        result = SoundEffect.FromStream(stream);
                    }
                    else if ((typeof(T) == typeof(Effect)))
                    {
                        byte[] data = new byte[stream.Length];
                        stream.Read(data, 0, (int)stream.Length);
                        result = new Effect(graphicsDeviceService.GraphicsDevice, data);
                    }
                    else if ((typeof(T) == typeof(Song)))
                    {
                        // FIXME: Not using the stream! -flibit
                        result = new Song(modifiedAssetName);
                    }
                    else if ((typeof(T) == typeof(Video)))
                    {
                        // FIXME: Not using the stream! -flibit
                        result = new Video(modifiedAssetName);
                    }
                    else
                    {
                        // We dunno WTF this is, give them the XNB Exception.
                        throw e;
                    }

                    /* Because Raw Assets skip the ContentReader step, they need to have their
                     * disposables recorded here. Doing it outside of this catch will
                     * result in disposables being logged twice.
                     */
                    IDisposable disposableResult = result as IDisposable;
                    if (disposableResult != null)
                    {
                        if (recordDisposableObject != null)
                        {
                            recordDisposableObject(disposableResult);
                        }
                        else
                        {
                            disposableAssets.Add(disposableResult);
                        }
                    }
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + assetName + " asset!");
            }

            return((T)result);
        }
예제 #37
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException();
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Replace Windows path separators with local path separators
            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar));

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream       stream    = OpenStream(assetName);
                BinaryReader xnbReader = new BinaryReader(stream);

                // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                byte[] headerBuffer = new byte[3];
                xnbReader.Read(headerBuffer, 0, 3);

                string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                byte platform = xnbReader.ReadByte();

                if (string.Compare(headerString, "XNB") != 0 ||
                    !(platform == 'w' || platform == 'x' || platform == 'm'))
                {
                    throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                }

                ushort version         = xnbReader.ReadUInt16();
                int    graphicsProfile = version & 0x7f00;
                version &= 0x80ff;

                bool compressed = false;
                if (version == 0x8005 || version == 0x8004)
                {
                    compressed = true;
                }
                else if (version != 5 && version != 4)
                {
                    throw new ContentLoadException("Invalid XNB version");
                }

                // The next int32 is the length of the XNB file
                int xnbLength = xnbReader.ReadInt32();

                ContentReader reader;
                if (compressed)
                {
                    //decompress the xnb
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    int compressedSize   = xnbLength - 14;
                    int decompressedSize = xnbReader.ReadInt32();
                    int newFileSize      = decompressedSize + 10;

                    MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                    LzxDecoder dec          = new LzxDecoder(16);
                    int        decodedBytes = 0;
                    int        pos          = 0;

                    while (pos < compressedSize)
                    {
                        // let's seek to the correct position
                        stream.Seek(pos + 14, SeekOrigin.Begin);
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000;
                        if (hi == 0xFF)
                        {
                            hi         = lo;
                            lo         = (byte)stream.ReadByte();
                            frame_size = (hi << 8) | lo;
                            hi         = (byte)stream.ReadByte();
                            lo         = (byte)stream.ReadByte();
                            block_size = (hi << 8) | lo;
                            pos       += 5;
                        }
                        else
                        {
                            pos += 2;
                        }

                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos          += block_size;
                        decodedBytes += frame_size;
                    }

                    if (decompressedStream.Position != decompressedSize)
                    {
                        throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                       " Try decompressing with nativeDecompressXnb first.");
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                }
                else
                {
                    reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                }

                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = OpenStream(assetName);
                    Bitmap  image       = BitmapFactory.DecodeStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }

            /*else
             * {
             *      // Load a XNB file
             * //Loads from Assets directory + /assetName
             *  Stream assetStream = OpenStream(assetName);
             *
             * ContentReader reader = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
             *      ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
             *      reader.TypeReaders = typeManager.LoadAssetReaders(reader);
             * foreach (ContentTypeReader r in reader.TypeReaders)
             * {
             * r.Initialize(typeManager);
             * }
             * // we need to read a byte here for things to work out, not sure why
             * reader.ReadByte();
             *
             *      // Get the 1-based index of the typereader we should use to start decoding with
             * int index = reader.ReadByte();
             *      ContentTypeReader contentReader = reader.TypeReaders[index - 1];
             * result = reader.ReadObject<T>(contentReader);
             *
             *      reader.Close();
             *      assetStream.Close();
             * }*/

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            // Store references to the asset for later use
            T asset = (T)result;

            if (asset is IDisposable && recordDisposableObject != null)
            {
                recordDisposableObject(asset as IDisposable);
            }
            else
            {
                disposableAssets.Add(asset as IDisposable);
            }
            loadedAssets.Add(originalAssetName, asset);

            return((T)result);
        }
예제 #38
0
 public EmulatorControls(Game game) : base(game)
 {
     graphicsService = game.Services.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
     graphics        = graphicsService.GraphicsDevice;
 }
예제 #39
0
 public MonoGameViewModel(IGraphicsDeviceService graphicsDeviceService = null)
 {
     GraphicsDeviceService = graphicsDeviceService;
 }
예제 #40
0
 internal override void Initialize(GameContext gameContext)
 {
     drawingSurface        = (DrawingSurface)gameContext.Control;
     graphicsDeviceService = (IGraphicsDeviceService)Services.GetService(typeof(IGraphicsDeviceService));
     graphicsDeviceManager = (IGraphicsDeviceManager)Services.GetService(typeof(IGraphicsDeviceManager));
 }
예제 #41
0
 /// <summary>
 ///   Initializes a new embedded content manager using a directly specified
 ///   graphics device service for the resources.
 /// </summary>
 /// <param name="graphicsDeviceService">
 ///   Graphics device service to load the content asset in
 /// </param>
 public MemoryContentManager(IGraphicsDeviceService graphicsDeviceService) :
     this(
         GraphicsDeviceServiceHelper.MakePrivateServiceProvider(graphicsDeviceService)
         )
 {
 }
예제 #42
0
        protected virtual void ReloadAsset <T>(string originalAssetName, T currentAsset)
        {
            string assetName = originalAssetName;

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            Stream stream = null;

            try
            {
                //try load it traditionally
                stream = OpenStream(assetName);

                // Try to load as XNB file
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, null))
                        {
                            reader.InitializeTypeReaders();
                            reader.ReadObject <T>(currentAsset);
                            reader.ReadSharedResources();
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException)
            {
                // Try to reload as a non-xnb file.
                // Just textures supported for now.

                assetName = TitleContainer.GetFilename(Path.Combine(RootDirectoryFullPath, assetName));

                assetName = Normalize <T>(assetName);

                ReloadRawAsset(currentAsset, assetName, originalAssetName);
            }
        }
예제 #43
0
 public SpriteBatch(IGraphicsDeviceService graphicsDevice)
 {
     _spriteBatch = new NoSpriteBatch();
     _create      = () => new InternalSpriteBatch(graphicsDevice.GraphicsDevice);
     graphicsDevice.DeviceCreated += OnGraphicsDeviceCreated;
 }
예제 #44
0
 /// <summary>Initializes a new drawable component</summary>
 /// <param name="graphicsDeviceService">
 ///   Graphics device service the component will use
 /// </param>
 /// <remarks>
 ///   This constructor is mainly relevant for users of IoC containers which
 ///   can wire up components to each other automatically. For the XNA
 ///   game services model, the service provider-based constructor should
 ///   be used instead because it uses a two-stage initialization process
 ///   where components wire up to each other in <see cref=" Initialize" />.
 /// </remarks>
 public GraphicsDeviceDrawableComponent(IGraphicsDeviceService graphicsDeviceService)
 {
     this.graphicsDeviceService = graphicsDeviceService;
 }
예제 #45
0
 public SpriteBatch(IGraphicsDeviceService graphicsDevice, int capacity)
 {
     _spriteBatch = new NoSpriteBatch();
     _create      = () => new InternalSpriteBatch(graphicsDevice.GraphicsDevice, capacity);
 }
예제 #46
0
        public CCApplication(Game game, IGraphicsDeviceService service)
            : base(game)
        {
            m_graphicsService = service;
            Content           = game.Content;

            if (m_graphicsService.GraphicsDevice != null)
            {
                try
                {
                    Game.Services.AddService(typeof(IGraphicsDeviceService), m_graphicsService);
                }
                catch (ArgumentException)
                {
                    // Already contains the graphics device service.
                }
                CCDrawManager.Init(m_graphicsService.GraphicsDevice);
            }
            else
            {
                service.DeviceCreated += ServiceDeviceCreated;
            }

            if (service is GraphicsDeviceManager)
            {
                ((GraphicsDeviceManager)service).PreparingDeviceSettings += GraphicsPreparingDeviceSettings;
            }

            game.IsFixedTimeStep = true;

            TouchPanel.EnabledGestures = GestureType.Tap;

            game.Activated   += GameActivated;
            game.Deactivated += GameDeactivated;
            game.Exiting     += GameExiting;

#if IOS || WINDOWS_PHONE8
            // Please read the following discussions for the reasons of this.
            // http://monogame.codeplex.com/discussions/393775
            // http://monogame.codeplex.com/discussions/396792
            //
            // https://github.com/mono/MonoGame/pull/726
            //
            // Also search Google for -> ContentTypeReaderManager.AddTypeCreator

            // .FNT Reader
            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.DictionaryReader`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Cocos2D.CCBMFontConfiguration+CCBMFontDef, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new DictionaryReader <Int32, CCBMFontConfiguration.CCBMFontDef> ()

                );

            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.DictionaryReader`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[Cocos2D.CCBMFontConfiguration+CCKerningHashElement, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new DictionaryReader <Int32, CCBMFontConfiguration.CCKerningHashElement> ()

                );
            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Cocos2D.CCRect, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new CCRectReader()

                );

            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Cocos2D.CCPoint, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new CCPointReader()

                );
            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Cocos2D.CCSize, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new CCSizeReader()

                );

            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Cocos2D.CCBMFontConfiguration+CCKerningHashElement, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new KerningHashElementReader()

                );

            ContentTypeReaderManager.AddTypeCreator(
                "Microsoft.Xna.Framework.Content.ReflectiveReader`1[[Cocos2D.CCBMFontConfiguration+CCBMFontPadding, cocos2d-xna, Version=2.0.3.0, Culture=neutral, PublicKeyToken=null]]",
                () => new CCBMFontPaddingtReader()

                );
#endif
        }
예제 #47
0
파일: Sun.cs 프로젝트: matrix4x4/Space
 /// <summary>
 ///     Initializes a new instance of the <see cref="Sun"/> class.
 /// </summary>
 /// <param name="content">The content manager to use for loading assets.</param>
 /// <param name="graphics">The graphics device to render to.</param>
 public Sun(ContentManager content, IGraphicsDeviceService graphics)
     : base(content, graphics, "Shaders/Sun")
 {
     graphics.DeviceReset += GraphicsOnDeviceReset;
 }
예제 #48
0
        public void Initialize(IServiceRegistry registry, string effectFilename = null, string[] optionalFeatures = null)
        {
            // Missing features compared to before: ZInverse support, Picking/Wireframe, Heat Shimmering and light shafts bounding boxes.
            // Other stuff to implement: Enable features by RenderPipeline, reloading, access of plugins through a flexible interface, yebis config.
            renderSystem          = registry.GetSafeServiceAs <IRenderSystem>();
            graphicsDeviceService = registry.GetSafeServiceAs <IGraphicsDeviceService>();
            this.effectSystemOld  = registry.GetSafeServiceAs <IEffectSystemOld>();
            entitySystem          = registry.GetSafeServiceAs <IEntitySystem>();

            var rootRenderPass = renderSystem.RootRenderPass;
            var dataContext    = RenderConfigContext = renderSystem.ConfigContext;
            var graphicsDevice = graphicsDeviceService.GraphicsDevice;

            if (effectFilename == null)
            {
                effectFilename = Path.Combine("/shaders/effects.xml");
            }

            var context          = new XenkoXamlSchemaContext(dataContext);
            var xamlObjectWriter = new XamlObjectWriter(context);

            using (var fileStream = VirtualFileSystem.OpenStream(effectFilename, VirtualFileMode.Open, VirtualFileAccess.Read))
                XamlServices.Transform(new XamlXmlReader(fileStream, context), xamlObjectWriter);

            var effectConfig = (RenderConfig)xamlObjectWriter.Result;

            foreach (var renderPass in effectConfig.Content.OfType <RenderPass>())
            {
                dataContext.RenderPasses.Add(renderPass.Name, renderPass);
                rootRenderPass.AddPass(renderPass);
            }

            foreach (var item in effectConfig.Content)
            {
                var plugin = item as RenderPassPlugin;
                if (plugin != null)
                {
                    dataContext.RenderPassPlugins.Add(plugin.Name, plugin);
                }

                var setter = item as Setter;
                if (setter != null)
                {
                    PropertyPath.SetNextValue(setter.Target, setter.Property, setter.Value);
                }
            }

            MainPlugin       = dataContext.RenderPassPlugins.Select(x => x.Value).OfType <MainPlugin>().First();
            MainTargetPlugin = dataContext.RenderPassPlugins.Select(x => x.Value).OfType <RenderTargetsPlugin>().FirstOrDefault(x => x.Name == "MainTargetPlugin");

            var mainBackBuffer = graphicsDevice.BackBuffer;

            MainPlugin.RenderTarget = graphicsDevice.BackBuffer;

            // Depth Stencil target needs to be shader resource only if Yebis or GBuffer is active (need more robust way to decide)
            var depthStencilTexture = Texture.New2D(graphicsDevice, mainBackBuffer.Width, mainBackBuffer.Height, PixelFormat.D32_Float,
                                                    (RenderConfigContext.RenderPassPlugins.Any(x => x.Value is YebisPlugin || x.Value is GBufferPlugin) ? TextureFlags.ShaderResource : 0) | TextureFlags.DepthStencil);

            MainPlugin.DepthStencil = depthStencilTexture.ToDepthStencilBuffer(false);

            if (DepthStencilBuffer.IsReadOnlySupported(graphicsDevice))
            {
                MainPlugin.DepthStencilReadOnly = depthStencilTexture.ToDepthStencilBuffer(true);
            }

            // TODO: Temporary setup (should be done through an Entity and its Manager)
            HeatShimmerPlugin heatShimmerPlugin;

            if (RenderConfigContext.RenderPassPlugins.TryGetValueCast("HeatShimmerPlugin", out heatShimmerPlugin))
            {
                throw new NotImplementedException();
                //heatShimmerPlugin.BoundingBoxes.Add(new MeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollectionData { { TransformationKeys.World, Matrix.Scaling(8200, 3000, 1500) * Matrix.Translation(2700, 0, 300) } } });
                //heatShimmerPlugin.BoundingBoxes.Add(new MeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollectionData { { TransformationKeys.World, Matrix.Scaling(2000, 2000, 3500) * Matrix.RotationZ(0.5f) * Matrix.Translation(-7000, -4000, 1500) } } });
                //heatShimmerPlugin.BoundingBoxes.Add(new MeshData { MeshData = MeshDataHelper.CreateBox(1, 1, 1, Color.White, true), Parameters = new ParameterCollectionData { { TransformationKeys.World, Matrix.Scaling(2000, 3000, 3500) * Matrix.Translation(-7800, 900, 1500) } } });
            }

            // Generates intermediate render targets
            var plugins = dataContext.RenderPassPlugins
                          .OrderBy(x => rootRenderPass.Passes.IndexOf(x.Value.RenderPass)).ToArray();

            // Weave render targets from last to first plugin.
            // TODO: Instead of guessing through interface and non-null/null values, it would be better if plugin had flags to inform of its intentions.
            var currentTarget = mainBackBuffer;

            for (int i = plugins.Length - 1; i >= 0; --i)
            {
                var plugin = plugins[i];

                var targetPlugin = plugin.Value as IRenderPassPluginTarget;
                if (targetPlugin != null)
                {
                    if (targetPlugin.RenderTarget == null)
                    {
                        targetPlugin.RenderTarget = currentTarget;
                    }

                    currentTarget = targetPlugin.RenderTarget;
                }

                var sourcePlugin = plugin.Value as IRenderPassPluginSource;
                if (sourcePlugin != null)
                {
                    if (sourcePlugin.RenderSource == null)
                    {
                        sourcePlugin.RenderSource = Texture.New2D(graphicsDevice, mainBackBuffer.Width, mainBackBuffer.Height, PixelFormat.R16G16B16A16_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget);
                    }

                    currentTarget = sourcePlugin.RenderSource.ToRenderTarget();
                }
            }

            foreach (var plugin in dataContext.RenderPassPlugins)
            {
                renderSystem.RenderPassPlugins.Add(plugin.Value);
            }

            foreach (var effectBuilder in effectConfig.Content.OfType <EffectBuilder>())
            {
                foreach (var plugin in effectBuilder.Plugins)
                {
                    plugin.Services = registry;
                }
                this.effectSystemOld.Effects.Add(effectBuilder);
            }

#if XENKO_YEBIS
            YebisPlugin yebisPlugin;
            if (RenderConfigContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin))
            {
                yebisPlugin.AntiAlias = true;

                yebisPlugin.ToneMap.Gamma = 2.2f;
                yebisPlugin.ToneMap.Type  = ToneMapType.SensiToMetric;
                yebisPlugin.ToneMap.AutoExposure.Enable                    = true;
                yebisPlugin.ToneMap.AutoExposure.MiddleGray                = 0.25f;
                yebisPlugin.ToneMap.AutoExposure.AdaptationSensitivity     = 0.5f;
                yebisPlugin.ToneMap.AutoExposure.AdaptationScale           = 0.8f;
                yebisPlugin.ToneMap.AutoExposure.AdaptationSpeedLimit      = 4.0f;
                yebisPlugin.ToneMap.AutoExposure.DarkAdaptationSensitivity = 0.9f;
                yebisPlugin.ToneMap.AutoExposure.DarkAdaptationScale       = 0.6f;
                yebisPlugin.ToneMap.AutoExposure.DarkAdaptationSpeedLimit  = 4.0f;
                yebisPlugin.ToneMap.AutoExposure.LightDarkExposureBorder   = 1.0f;

                yebisPlugin.Glare.Enable = true;
                //yebisPlugin.Glare.RemapFactor = 1.0f;
                //yebisPlugin.Glare.Threshold = 0.0f;

                yebisPlugin.Lens.Vignette.Enable = true;

                yebisPlugin.Lens.Distortion.Enable         = false;
                yebisPlugin.Lens.Distortion.Power          = 0.2f;
                yebisPlugin.Lens.Distortion.EdgeSmoothness = 0.2f;

                yebisPlugin.DepthOfField.Enable            = true;
                yebisPlugin.DepthOfField.AutoFocus         = true;
                yebisPlugin.DepthOfField.Aperture          = 2.0f;
                yebisPlugin.DepthOfField.ImageSensorHeight = 40.0f;

                //yebisPlugin.ColorCorrection.ColorTemperature = 4500;

                yebisPlugin.HeatShimmer.Enable = false;
                //YebisPlugin.LightShaft.Enable = true;
                //YebisPlugin.LightShaft.ScreenPosition = new Vector2(0.5f, 0.1f);
            }
#endif

            // Adds the particle system if the ParticlePlugin is used in the config
            ParticlePlugin particlePlugin;
            if (RenderConfigContext.RenderPassPlugins.TryGetValueCast("ParticlePlugin", out particlePlugin))
            {
                var particleSystem = new ParticleProcessor(particlePlugin);
                entitySystem.Processors.Add(particleSystem);
            }
        }
예제 #49
0
        /// <summary>
        /// Creats a new CubeComponent.
        /// </summary>
        /// <param name="game">The game to which this component will be attached.</param>
        /// <param name="color">The color of the cube.</param>
        /// <param name="sideLength">The length of one side of the cube.</param>
        public CubeComponent(Game game,
                             Color color,
                             float sideLength)
            : base(game)
        {
            this.sideLength = sideLength;
            this.graphics   = (IGraphicsDeviceService)game.Services.GetService(
                typeof(IGraphicsDeviceService));
            effect = new BasicEffect(graphics.GraphicsDevice);


            indices = new int[]
            {
                0, 1, 2, // left face
                2, 3, 0,

                3, 2, 6, // top face
                6, 7, 3,

                7, 6, 5, // right face
                5, 4, 7,

                4, 5, 1, // bottom face
                1, 0, 4,

                5, 6, 2, // back face
                2, 1, 5,

                7, 4, 0, // front face
                0, 3, 7
            };


            Vector3[] originalVerts = new Vector3[]
            {
                new Vector3(-1, -1, 1),  // 0 - front bottom left
                new Vector3(-1, -1, -1), // 1 - back bottom left
                new Vector3(-1, 1, -1),  // 2 - back top left
                new Vector3(-1, 1, 1),   // 3 - front top left

                new Vector3(1, -1, 1),   // 4 - front bottom right
                new Vector3(1, -1, -1),  // 5 - back bottom right
                new Vector3(1, 1, -1),   // 6 - back top right
                new Vector3(1, 1, 1)     // 7 - front top right
            };

            for (int i = 0; i < originalVerts.Length; i++)
            {
                originalVerts[i].X *= sideLength / 2;
                originalVerts[i].Y *= sideLength / 2;
                originalVerts[i].Z *= sideLength / 2;
            }
            vertexDeclaration = new VertexDeclaration(VertexPositionColor.VertexDeclaration.GetVertexElements());
            verts             = new VertexPositionColor[8];
            buffer            = new Vector3[8];
            for (int i = 0; i < verts.Length; i++)
            {
                verts[i].Position = originalVerts[i];
                verts[i].Color    = color;
            }

            vertexBuffer.SetData(verts);

            effect.VertexColorEnabled = true;
            game.Components.Add(this);
        }
예제 #50
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentException("assetname");
            }

            if (!string.IsNullOrEmpty(_rootDirectory))
            {
                assetName = _rootDirectory + Path.DirectorySeparatorChar + assetName;
            }

            // Check for windows-style directory separator character
            assetName = assetName.Replace('\\', Path.DirectorySeparatorChar);

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                using (FileStream stream = new FileStream(assetName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (ContentReader reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice))
                    {
                        ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                        reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                        foreach (ContentTypeReader r in reader.TypeReaders)
                        {
                            r.Initialize(typeManager);
                        }
                        // we need to read a byte here for things to work out, not sure why
                        reader.ReadByte();

                        // Get the 1-based index of the typereader we should use to start decoding with
                        int index = reader.ReadByte();
                        ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                        result = reader.ReadObject <T>(contentReader);
                    }
                }
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    result = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName);
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
예제 #51
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            Stream stream = null;

            try
            {
                //try load it traditionally
                stream = OpenStream(assetName);

                // Try to load as XNB file
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                        {
                            result = reader.ReadAsset <T>();
                            if (result is GraphicsResource)
                            {
                                ((GraphicsResource)result).Name = originalAssetName;
                            }
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException ex)
            {
                //MonoGame try to load as a non-content file

                assetName = TitleContainer.GetFilename(Path.Combine(RootDirectoryFullPath, assetName));

                assetName = Normalize <T>(assetName);

                if (string.IsNullOrEmpty(assetName))
                {
                    throw new ContentLoadException("Could not load " + originalAssetName + " asset as a non-content file!", ex);
                }

                result = ReadRawAsset <T>(assetName, originalAssetName);

                // Because Raw Assets skip the ContentReader step, they need to have their
                // disopsables recorded here. Doing it outside of this catch will
                // result in disposables being logged twice.
                if (result is IDisposable)
                {
                    if (recordDisposableObject != null)
                    {
                        recordDisposableObject(result as IDisposable);
                    }
                    else
                    {
                        disposableAssets.Add(result as IDisposable);
                    }
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
 public override void Initialize()
 {
     base.Initialize();
     graphicsDeviceService = Services.GetSafeServiceAs <IGraphicsDeviceService>();
 }
예제 #53
0
 /// <summary>
 /// 新建SpriteFontX..
 /// </summary>
 /// <param name="fontName">字体名字</param>
 /// <param name="size">    字体大小</param>
 /// <param name="gds">     建纹理时用到的IGraphicsDeviceService</param>
 /// <param name="trh">     指定文本呈现的质量</param>
 public SpriteFontX(String fontName, Single size, IGraphicsDeviceService gds, TextRenderingHint trh = TextRenderingHint.AntiAliasGridFit)
 {
     Initialize(new Font(fontName, size), gds, trh);
 }
예제 #54
0
 internal InvalidationService(IGraphicsDeviceService graphics, SwapChainRenderTarget_GL swapChainRenderTarget)
 {
     // Initialize GFX-System
     InitializeGFX_GL(graphics, swapChainRenderTarget);
 }
예제 #55
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentException("assetname");
            }

            if (!string.IsNullOrEmpty(_rootDirectory))
            {
                assetName = _rootDirectory + Path.DirectorySeparatorChar + assetName;
            }

            // Check for windows-style directory separator character
            assetName = assetName.Replace('\\', Path.DirectorySeparatorChar);

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                FileStream   stream    = new FileStream(assetName, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader xnbReader = new BinaryReader(stream);

                // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                byte[] headerBuffer = new byte[3];
                xnbReader.Read(headerBuffer, 0, 3);

                string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                byte platform = xnbReader.ReadByte();

                if (string.Compare(headerString, "XNB") != 0 ||
                    !(platform == 'w' || platform == 'x' || platform == 'm'))
                {
                    throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                }

                ushort version         = xnbReader.ReadUInt16();
                int    graphicsProfile = version & 0x7f00;
                version &= 0x80ff;

                bool compressed = false;
                if (version == 0x8005 || version == 0x8004)
                {
                    compressed = true;
                }
                else if (version != 5 && version != 4)
                {
                    throw new ContentLoadException("Invalid XNB version");
                }

                // The next int32 is the length of the XNB file
                int xnbLength = xnbReader.ReadInt32();

                ContentReader reader;
                if (compressed)
                {
                    //decompress the xnb
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    int compressedSize   = xnbLength - 14;
                    int decompressedSize = xnbReader.ReadInt32();
                    int newFileSize      = decompressedSize + 10;

                    MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                    LzxDecoder dec          = new LzxDecoder(16);
                    int        decodedBytes = 0;
                    int        pos          = 0;

                    while (pos < compressedSize)
                    {
                        // let's seek to the correct position
                        stream.Seek(pos + 14, SeekOrigin.Begin);
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000;
                        if (hi == 0xFF)
                        {
                            hi         = lo;
                            lo         = (byte)stream.ReadByte();
                            frame_size = (hi << 8) | lo;
                            hi         = (byte)stream.ReadByte();
                            lo         = (byte)stream.ReadByte();
                            block_size = (hi << 8) | lo;
                            pos       += 5;
                        }
                        else
                        {
                            pos += 2;
                        }

                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos          += block_size;
                        decodedBytes += frame_size;
                    }

                    if (decompressedStream.Position != decompressedSize)
                    {
                        throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                       " Try decompressing with nativeDecompressXnb first.");
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                }
                else
                {
                    reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                }

                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    result = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName);
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
                if ((typeof(T) == typeof(Effect)))
                {
                    result = new Effect(graphicsDeviceService.GraphicsDevice, assetName);
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
예제 #56
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 = EffectSystem.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();
        }
예제 #57
0
        /// <summary>
        /// Draws the console to the screen if the console is currently open
        /// </summary>
        /// <param name="gameTime">The current game time</param>
        public override void Draw(GameTime gameTime)
        {
            if (!isEnabled)
            {
                return;
            }

            IGraphicsDeviceService graphics =
                (IGraphicsDeviceService)Game.Services.GetService(typeof(IGraphicsDeviceService));

            // measure the height of a line in the current font
            float height = (mFontHeight + mVerticalSpacing) * (mVisibleLineCount + 1);

            // create vertices for the background quad
            Vector3[] vertices = new Vector3[]
            {
                new Vector3(0, 0, 0),
                new Vector3(graphics.GraphicsDevice.Viewport.Width, 0, 0),
                new Vector3(graphics.GraphicsDevice.Viewport.Width, height, 0),
                new Vector3(0, height, 0),
            };

            // create indices for the background quad
            short[] indices = new short[] { 0, 1, 2, 2, 3, 0 };

            // set the vertex declaration
            graphics.GraphicsDevice.VertexDeclaration = mVertexDeclaration;

            // create an orthographic projection to draw the quad as a sprite
            mEffect.Projection = Matrix.CreateOrthographicOffCenter(0,
                                                                    graphics.GraphicsDevice.Viewport.Width,
                                                                    graphics.GraphicsDevice.Viewport.Height, 0,
                                                                    0, 1);

            mEffect.DiffuseColor = mBackgroundColor.ToVector3();
            mEffect.Alpha        = mBackgroundAlpha;

            // save current blending mode
            bool blend = graphics.GraphicsDevice.RenderState.AlphaBlendEnable;

            // enable alpha blending
            graphics.GraphicsDevice.RenderState.AlphaBlendEnable          = true;
            graphics.GraphicsDevice.RenderState.AlphaBlendOperation       = BlendFunction.Add;
            graphics.GraphicsDevice.RenderState.SourceBlend               = Blend.SourceAlpha;
            graphics.GraphicsDevice.RenderState.DestinationBlend          = Blend.InverseSourceAlpha;
            graphics.GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;

            mEffect.Begin();

            // draw the quad
            foreach (EffectPass pass in mEffect.CurrentTechnique.Passes)
            {
                pass.Begin();

                graphics.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList,
                                                                  vertices, 0, 4, indices, 0, 2);

                pass.End();
            }

            mEffect.End();

            // restore previous alpha blend
            graphics.GraphicsDevice.RenderState.AlphaBlendEnable = blend;

            // begin drawing the console text
            mSpriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                               SpriteSortMode.Immediate, SaveStateMode.None);

            // measure and draw the prompt
            float   promptsize = mFont.MeasureString(mInputPrompt + " ").X;
            Vector2 position   = new Vector2(mHorizontalPadding, height - mFontHeight - mVerticalSpacing);

            mSpriteBatch.DrawString(mFont, mInputPrompt + " ", position, mDefaultTextColor);
            position.X += promptsize;

            // measure and draw the current input text
            string current = mCurrentText.ToString();

            float cursorpos = position.X;

            cursorpos += mFont.MeasureString(current.Substring(0, mInputPosition)).X;

            if (cursorpos >= (graphics.GraphicsDevice.Viewport.Width - mHorizontalPadding))
            {
                position.X -= (cursorpos - (graphics.GraphicsDevice.Viewport.Width - mHorizontalPadding));
            }

            mSpriteBatch.DrawString(mFont, current, position, mDefaultTextColor);
            position.Y -= (mFontHeight + mVerticalSpacing);
            position.X  = mHorizontalPadding;

            // draw log text
            int messageIndex = (mLog.Count > 0) ? (mCurrentLine) : (-1);
            int lineIndex    = mVisibleLineCount;

            while ((messageIndex >= 0) && (lineIndex > 0))
            {
                if ((mDisplayLevelThreshold > 0) && (mLog[messageIndex].Level > (uint)mDisplayLevelThreshold))
                {
                    messageIndex--;
                    continue;
                }

                string text      = mLog[messageIndex].Text;
                Color  textcolor = (mTextColors.ContainsKey(mLog[messageIndex].Level))
                    ? (mTextColors[mLog[messageIndex].Level])
                    : (mDefaultTextColor);

                if ((mDisplayOptions & ConsoleDisplayOptions.LogLevel) == ConsoleDisplayOptions.LogLevel)
                {
                    text = text.Insert(0, string.Format("[{0}] ", mLog[messageIndex].Level));
                }

                if ((mDisplayOptions & ConsoleDisplayOptions.TimeStamp) == ConsoleDisplayOptions.TimeStamp)
                {
                    TimeSpan time      = mLog[messageIndex].RealTime;
                    string   timestamp = mTimestampFormat;

                    timestamp = timestamp.Replace("{Hr}", time.Hours.ToString());
                    timestamp = timestamp.Replace("{Min}", time.Minutes.ToString());
                    timestamp = timestamp.Replace("{Sec}", time.Seconds.ToString());
                    timestamp = timestamp.Replace("{Ms}", time.Milliseconds.ToString());

                    text = text.Insert(0, timestamp + " ");
                }

                List <string> lines = GetLines(graphics.GraphicsDevice.Viewport.Width, text);

                for (int i = lines.Count - 1; i >= 0; --i)
                {
                    mSpriteBatch.DrawString(mFont, lines[i], position, textcolor);

                    position.Y -= (mFontHeight + mVerticalSpacing);

                    if (--lineIndex <= 0)
                    {
                        break;
                    }
                }

                messageIndex--;
            }

            mSpriteBatch.End();

            // draw the cursor
            if (mDrawCursor)
            {
                position.Y           = height - mFontHeight - mVerticalSpacing;
                mEffect.DiffuseColor = mDefaultTextColor.ToVector3();
                mEffect.Alpha        = 1.0f;

                if (cursorpos >= (graphics.GraphicsDevice.Viewport.Width - mHorizontalPadding))
                {
                    cursorpos -= cursorpos - (graphics.GraphicsDevice.Viewport.Width - mHorizontalPadding);
                }

                Vector3[] cursorverts = new Vector3[]
                {
                    new Vector3(cursorpos, position.Y, 0),
                    new Vector3(cursorpos, position.Y + mFontHeight, 0),
                };

                graphics.GraphicsDevice.VertexDeclaration = mVertexDeclaration;

                mEffect.Begin();
                foreach (EffectPass pass in mEffect.CurrentTechnique.Passes)
                {
                    pass.Begin();
                    graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList,
                                                               cursorverts, 0, 1);
                    pass.End();
                }
                mEffect.End();
            }

            // Handle out-of-page notification
            if (mDrawNotify && (mCurrentLine < mLog.Count - 1))
            {
                float yofs = height - mFontHeight - (mVerticalSpacing * 1.5f);
                mEffect.DiffuseColor = mDefaultTextColor.ToVector3();
                mEffect.Alpha        = 1.0f;

                Vector3[] notifyverts = new Vector3[]
                {
                    new Vector3(0, yofs, 0),
                    new Vector3(graphics.GraphicsDevice.Viewport.Width, yofs, 0),
                };

                graphics.GraphicsDevice.VertexDeclaration = mVertexDeclaration;

                mEffect.Begin();
                foreach (EffectPass pass in mEffect.CurrentTechnique.Passes)
                {
                    pass.Begin();
                    graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList,
                                                               notifyverts, 0, 1);
                    pass.End();
                }
                mEffect.End();
            }

            base.Draw(gameTime);
        }
예제 #58
0
        /// <summary>
        /// Renders this The ship upgrade screen. Current money and settings come from the static SpacewarGame object
        /// </summary>
        public override void Render()
        {
            IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)GameInstance.Services.GetService(typeof(IGraphicsDeviceService));

            GraphicsDevice device = graphicsService.GraphicsDevice;

            SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.Opaque);

            //Sprites will always be at the back.
            device.DepthStencilState = DepthStencilState.DepthRead;

            //Main background
            SpriteBatch.Draw(mainTexture, Vector2.Zero, new Rectangle(0, 0, 1280, 720), Color.White);

            SpriteBatch.End();

            //New sprite to ensure they are drawn on top
            SpriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend);

            for (int player = 0; player < 2; player++)
            {
                for (int weapon = 1; weapon < 5; weapon++)
                {
                    //Grey out weapons when you are ready
                    if ((player1Ready && player == 0) || (player2Ready && player == 1))
                    {
                        SpriteBatch.Draw(mainTexture, weaponPositions[player, weapon - 1], readySprite(player, weapon), Color.White);
                    }
                    //Show purchased weapon
                    else if ((int)purchasedWeapon[player] == weapon)
                    {
                        SpriteBatch.Draw(mainTexture, weaponPositions[player, weapon - 1], selectedSprite(player, weapon), new Color(new Vector4(1f, 1f, 1f, flashPercent[player])));
                    }
                    //Disable weapons you can't afford
                    else if (SpacewarGame.Players[player].Cash < SpacewarGame.Settings.Weapons[weapon].Cost)
                    {
                        SpriteBatch.Draw(mainTexture, weaponPositions[player, weapon - 1], disabledSprite(player, weapon), Color.White);
                    }
                }
            }

            //Ready buttons
            if (player1Ready)
            {
                SpriteBatch.Draw(mainTexture, new Vector2(55, 620), new Rectangle(10, 1205, 190, 70), Color.White);
            }

            if (player2Ready)
            {
                SpriteBatch.Draw(mainTexture, new Vector2(1040, 620), new Rectangle(330, 1205, 190, 70), Color.White);
            }

            SpriteBatch.End();

            Font.Begin(); //Could reuse the sprite above but things may be drawn in the wrong order

            //Current cash and weapon costs
            //Ensure we use US number formatting
            for (int i = 0; i < 621; i += 620)
            {
                if ((!player1Ready && i == 0) || (!player2Ready && i == 620))
                {
                    Font.Draw(FontStyle.WeaponSmall, 296 + i, 255, String.Format("{0:$##,##0}", SpacewarGame.Settings.Weapons[1].Cost), upgradeFontColor);
                    Font.Draw(FontStyle.WeaponSmall, 110 + i, 438, String.Format("{0:$##,##0}", SpacewarGame.Settings.Weapons[2].Cost), upgradeFontColor);
                    Font.Draw(FontStyle.WeaponSmall, 480 + i, 438, String.Format("{0:$##,##0}", SpacewarGame.Settings.Weapons[3].Cost), upgradeFontColor);
                    Font.Draw(FontStyle.WeaponSmall, 296 + i, 621, String.Format("{0:$##,##0}", SpacewarGame.Settings.Weapons[4].Cost), upgradeFontColor);
                }
            }

            Font.Draw(FontStyle.WeaponLarge, 322, 40, "$", upgradeFontColor);
            Font.Draw(FontStyle.WeaponLarge, 346, 40, String.Format("{0:##,##0}", playerCashCount[0]), upgradeFontColor);
            Font.Draw(FontStyle.WeaponLarge, 840, 40, "$", upgradeFontColor);
            Font.Draw(FontStyle.WeaponLarge, 866, 40, String.Format("{0:##,##0}", playerCashCount[1]), upgradeFontColor);

            //Score buttons
            Font.Draw(FontStyle.ScoreButtons, 60 + 349, 70 + 24, scoreLookup[SpacewarGame.Players[0].Score]);
            Font.Draw(FontStyle.ScoreButtons, 1140 - 351, 70 + 24, scoreLookup[SpacewarGame.Players[1].Score]);

            Font.End();

            base.Render();
        }
예제 #59
0
 /// <summary>Called when the graphics device has been (re)created, and assets should be loaded.</summary>
 /// <param name="content">The content manager.</param>
 /// <param name="graphics">The graphics device service.</param>
 private void LoadContent(ContentManager content, IGraphicsDeviceService graphics)
 {
     SpriteBatch = new SpriteBatch(graphics.GraphicsDevice);
     Font        = content.Load <SpriteFont>("Fonts/visitor");
 }
예제 #60
0
 /// <summary>
 /// 新建SpriteFontX..
 /// </summary>
 /// <param name="font">字体</param>
 /// <param name="gds"> 建纹理时用到的IGraphicsDeviceService</param>
 /// <param name="trh"> 指定文本呈现的质量</param>
 public SpriteFontX(Font font, IGraphicsDeviceService gds, TextRenderingHint trh = TextRenderingHint.AntiAliasGridFit)
 {
     Initialize(font, gds, trh);
 }