Пример #1
0
        public MainMenu(RenderWindow window, ImageManager imageManager, Client client, Server server)
            : base(window, imageManager)
        {
            imageManager = new ImageManager();
            p = new Player(null, imageManager);
            mouse = new Sprite(imageManager.GetImage("mouse"));
            pImage = new RenderImage(window.Width, window.Height);
            pImage.DefaultView.Zoom(0.08F);
            pImage.DefaultView.Center = p.Center + new Vector2f(0, -30);
            pImage.SetView(pImage.DefaultView);

            this.window = window;
            this.client = client;
            this.server = server;
            items = new MenuItem[nbrItem];
            items[0] = new MenuItem("Local Game", new Vector2f(0, 100), StartLocal);
            items[1] = new MenuItem("Connect", new Vector2f(0, 130), Connect);
            items[2] = new MenuItem("Options", new Vector2f(0, 160), Option);
            items[3] = new MenuItem("Load map", new Vector2f(0, 190), LoadMap);
            items[4] = new MenuItem("Save map", new Vector2f(0, 220), SaveMap);
            items[5] = new MenuItem("Exit", new Vector2f(0, 280), Exit);

            foreach (MenuItem i in items)
                i.CenterX((int)window.Width);
        }
Пример #2
0
        public Client(RenderWindow window, ImageManager imageManager)
            : base(window, imageManager)
        {
            this.window = window;
            world = new RenderImage(800, 600);

            inputManager = new InputManager(this);

            ticker = new Ticker();

            window.ShowMouseCursor (false);
            window.SetFramerateLimit (60);

            NetPeerConfiguration netConfiguration = new NetPeerConfiguration("2dThing");
            client = new NetClient(netConfiguration);

            uMsgBuffer = new UserMessageBuffer();
            otherClients = new Dictionary<int, NetworkClient>();
            chat = new Chat(this);

            LoadRessources();

            blockTypeDisplay = new Cube(blockType, imageManager);
            blockTypeDisplay.Position = new Vector2f(window.Width - 2*Cube.WIDTH, window.Height - 2* Cube.HEIGHT);
            layerDisplay = new LayerDisplay(imageManager);
            layerDisplay.Position = blockTypeDisplay.Position - new Vector2f(0, 50);

            mouse = new Sprite (imageManager.GetImage("mouse"));
        }
Пример #3
0
 internal ScreenBuffer(float scaler)
 {
     this.is_main_window = false;
     this.scaler = scaler;
     this.autoscales = true;
     this.w = (uint)(screen_w * scaler);
     this.h = (uint)(screen_h * scaler);
     _image = new RenderImage(w, h);
 }
Пример #4
0
 ////////////////////////////////////////////////////////////
 /// <summary>
 /// Render the object into the given render image
 /// </summary>
 /// <param name="target">Target render image</param>
 /// <param name="shader">Shader to apply</param>
 ////////////////////////////////////////////////////////////
 internal override void Render(RenderImage target, Shader shader)
 {
     if (shader == null)
     {
         sfRenderImage_DrawText(target.This, This);
     }
     else
     {
         sfRenderImage_DrawTextWithShader(target.This, This, shader.This);
     }
 }
Пример #5
0
            internal ScreenBuffer(bool iswindow, uint w, uint h)
            {
                is_main_window = iswindow;

                this.w = w;
                this.h = h;
                if (!is_main_window)
                {
                    var z = Graphics.Pipeline.print_buffers;
                    _image = new RenderImage(w, h);
                }

                autoscales = false;
            }
Пример #6
0
 public ConnectMenu(RenderWindow window, ImageManager imageManager, Client client, Server server)
     : base(window, imageManager)
 {
     this.server = server;
     this.client = client;
     p = new Player(null, imageManager);
     randomiser = new Random();
     pImage = new RenderImage(window.Width, window.Height);
     pImage.DefaultView.Zoom(0.08F);
     pImage.DefaultView.Center = p.Center + new Vector2f(0, -40);
     pImage.DefaultView.Rotate(135);
     pImage.SetView(pImage.DefaultView);
     mouse = new Sprite(imageManager.GetImage("mouse"));
     title = new MenuItem("Enter an IP to connect to...", new Vector2f(0, 100), null);
     title.CenterX((int)window.Width);
     ip = new MenuItem("", new Vector2f(0, 150), null);
     ip.CenterX((int)window.Width);
     connecting = new MenuItem("Connecting...", new Vector2f(0, 180), null);
     connecting.CenterX((int)window.Width);
 }
Пример #7
0
        private void Resize(uint width, uint height)
        {
            View newView = new View(new FloatRect(0,0,width, height));
            window.SetView(newView);

            world = new RenderImage(width, height);
            world.DefaultView.Center = player.Center;
            world.DefaultView.Zoom(zoom);

            blockTypeDisplay.Position = new Vector2f(window.Width - 2*Cube.WIDTH, window.Height - 2* Cube.HEIGHT);
            layerDisplay.Position = blockTypeDisplay.Position - new Vector2f(0, 50);
        }
        /// <summary>
        /// Initializes the internal components of the buffer. This only needs to be called once.
        /// </summary>
        /// <param name="window">The <see cref="Window"/> to use.</param>
        protected void InitializeRenderBuffer(Window window)
        {
            if (_window == window)
                return;

            // Set the new Window
            _window = window;

            // Force the buffer to be rebuilt
            if (_ri != null)
            {
                // Dispose of the old buffer
                try
                {
                    if (!_ri.IsDisposed)
                        _ri.Display();
                }
                catch (Exception ex)
                {
                    const string errmsg = "Failed to dispose RenderImage `{0}`. Exception: {1}";
                    if (log.IsWarnEnabled)
                        log.WarnFormat(errmsg, _ri, ex);
                    Debug.Fail(string.Format(errmsg, _ri, ex));
                }

                // Set to null to force rebuild when needed
                _ri = null;
            }
        }
        /// <summary>
        /// Makes sure the internal buffer is ready then returns a <see cref="RenderImage"/> to draw to it.
        /// </summary>
        /// <returns>The <see cref="RenderImage"/> to use, or null if the buffer could not be prepared.</returns>
        RenderImage GetRenderImage()
        {
            var oldRI = _ri;
            _ri = _window.CreateBufferRenderImage(_ri);

            if (_ri == null)
                return null;

            if (!BypassClear || _ri != oldRI)
                _ri.Clear(BufferClearColor);

            return _ri;
        }
Пример #10
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            // Create the main window
            RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML.Net Shader");

            // Setup event handlers
            window.Closed     += new EventHandler(OnClosed);
            window.KeyPressed += new EventHandler<KeyEventArgs>(OnKeyPressed);

            // Check that the system can use shaders
            if (Shader.IsAvailable == false)
            {
                DisplayError(window);
                return;
            }

            // Create the render image
            RenderImage image = new RenderImage(window.Width, window.Height);

            // Load a background image to display
            Sprite background = new Sprite(new Image("resources/background.jpg"));
            background.Image.Smooth = false;

            // Load a sprite which we'll move into the scene
            Sprite entity = new Sprite(new Image("resources/sprite.png"));

            // Load the text font
            Font font = new Font("resources/arial.ttf");

            // Load the image needed for the wave effect
            Image waveImage = new Image("resources/wave.jpg");

            // Load all effects
            shaders = new Dictionary<string, Shader>();
            shaders["nothing"]  = new Shader("resources/nothing.sfx");
            shaders["blur"]     = new Shader("resources/blur.sfx");
            shaders["colorize"] = new Shader("resources/colorize.sfx");
            shaders["fisheye"]  = new Shader("resources/fisheye.sfx");
            shaders["wave"]     = new Shader("resources/wave.sfx");
            shaders["pixelate"] = new Shader("resources/pixelate.sfx");
            backgroundShader = new ShaderSelector(shaders);
            entityShader     = new ShaderSelector(shaders);
            globalShader     = new ShaderSelector(shaders);

            // Do specific initializations
            shaders["nothing"].SetTexture("texture", Shader.CurrentTexture);
            shaders["blur"].SetTexture("texture", Shader.CurrentTexture);
            shaders["blur"].SetParameter("offset", 0.0F);
            shaders["colorize"].SetTexture("texture", Shader.CurrentTexture);
            shaders["colorize"].SetParameter("color", 1.0F, 1.0F, 1.0F);
            shaders["fisheye"].SetTexture("texture", Shader.CurrentTexture);
            shaders["wave"].SetTexture("texture", Shader.CurrentTexture);
            shaders["wave"].SetTexture("wave", waveImage);
            shaders["pixelate"].SetTexture("texture", Shader.CurrentTexture);

            // Define a string for displaying current effect description
            shaderText = new Text();
            shaderText.Font = font;
            shaderText.Size = 20;
            shaderText.Position = new Vector2(5.0F, 0.0F);
            shaderText.Color = new Color(250, 100, 30);
            shaderText.DisplayedString = "Background shader: \"" + backgroundShader.Name + "\"\n" +
                                         "Flower shader: \"" + entityShader.Name + "\"\n" +
                                         "Global shader: \"" + globalShader.Name + "\"\n";

            // Define a string for displaying help
            Text infoText = new Text();
            infoText.Font = font;
            infoText.Size = 20;
            infoText.Position = new Vector2(5.0F, 500.0F);
            infoText.Color = new Color(250, 100, 30);
            infoText.DisplayedString = "Move your mouse to change the shaders' parameters\n" +
                                       "Press numpad 1 to change the background shader\n" +
                                       "Press numpad 2 to change the flower shader\n" +
                                       "Press numpad 3 to change the global shader";

            // Start the game loop
            float time = 0.0F;
            while (window.IsOpened())
            {
                // Process events
                window.DispatchEvents();

                // TOFIX -- using window.Input together with image.Draw apparently causes a memory corruption
                // Get the mouse position in the range [0, 1]
                //float x = window.Input.GetMouseX() / (float)window.Width;
                //float y = window.Input.GetMouseY() / (float)window.Height;
                float x = (float)(Math.Cos(time * 1.3) + 1) * 0.5F;
                float y = (float)(Math.Sin(time * 0.8) + 1) * 0.5F;

                // Update the shaders
                backgroundShader.Update(x, y);
                entityShader.Update(x, y);
                globalShader.Update(x, y);

                // Animate the sprite
                time += window.GetFrameTime();
                float entityX = (float)(Math.Cos(time * 1.3) + 1.2) * 300;
                float entityY = (float)(Math.Cos(time * 0.8) + 1.2) * 200;
                entity.Position = new Vector2(entityX, entityY);
                entity.Rotation = time * 100;

                // Draw the background and the moving entity to the render image
                image.Draw(background, backgroundShader.Shader);
                image.Draw(entity, entityShader.Shader);
                image.Display();

                // Draw the contents of the render image to the window
                window.Draw(new Sprite(image.Image), globalShader.Shader);

                // Draw interface texts
                window.Draw(shaderText);
                window.Draw(infoText);

                // Finally, display the rendered frame on screen
                window.Display();
            }
        }
Пример #11
0
 ////////////////////////////////////////////////////////////
 /// <summary>
 /// Render the object into the given render image
 /// </summary>
 /// <param name="target">Target render image</param>
 /// <param name="shader">Shader to apply</param>
 ////////////////////////////////////////////////////////////
 internal abstract void Render(RenderImage target, Shader shader);
Пример #12
0
 ////////////////////////////////////////////////////////////
 /// <summary>
 /// Render the object into the given render image
 /// </summary>
 /// <param name="target">Target render image</param>
 /// <param name="shader">Shader to apply</param>
 ////////////////////////////////////////////////////////////
 internal override void Render(RenderImage target, Shader shader)
 {
     if (shader == null)
         sfRenderImage_DrawShape(target.This, This);
     else
         sfRenderImage_DrawShapeWithShader(target.This, This, shader.This);
 }
Пример #13
0
 ////////////////////////////////////////////////////////////
 /// <summary>
 /// Render the object into the given render image
 /// </summary>
 /// <param name="target">Target render image</param>
 /// <param name="shader">Shader to apply</param>
 ////////////////////////////////////////////////////////////
 internal abstract void Render(RenderImage target, Shader shader);
Пример #14
0
        /// <summary>
        /// Creates a <see cref="RenderImage"/> for a <see cref="Window"/> that can be used as a buffer for the <see cref="Window"/>.
        /// </summary>
        /// <param name="w">The <see cref="Window"/> to create the <see cref="RenderImage"/> for.</param>
        /// <param name="ri">An optional, pre-existing <see cref="RenderImage"/> to try to use. If this <see cref="RenderImage"/>
        /// instance is already set up as needed, it will be used instead of creating a new <see cref="RenderImage"/>. This is
        /// primarily provided so you can pass a previous output from this method back into it.</param>
        /// <param name="disposeExisting">If <paramref name="ri"/> does not work for the <paramref name="w"/> and a new
        /// <see cref="RenderImage"/> has to be created, if this value is true, then the <paramref name="ri"/> will be
        /// disposed of. If false, it will not be disposed of.</param>
        /// <returns>
        /// A <see cref="RenderImage"/> that can be used as a buffer for the <paramref name="w"/>, or null if the
        /// <see cref="RenderImage"/> could needed to be recreated but could not be. Usually, it is okay to try again later
        /// (such as the next frame) if the <see cref="RenderImage"/> failed to be created.
        /// </returns>
        public static RenderImage CreateBufferRenderImage(this Window w, RenderImage ri = null, bool disposeExisting = true)
        {
            try
            {
                // Check if the provided RenderImage works for our needs
                var mustRecreate = false;
                try
                {
                    if (ri == null || ri.IsDisposed || ri.Width != w.Width || ri.Height != w.Height)
                        mustRecreate = true;
                }
                catch (InvalidOperationException)
                {
                    // Common exception that occurs when the RenderImage is invalid or corrupt - recreate and do not report
                    mustRecreate = true;
                }
                catch (AccessViolationException)
                {
                    // Common exception that occurs when the RenderImage is invalid or corrupt - recreate and do not report
                    mustRecreate = true;
                }
                catch (Exception ex)
                {
                    // Recreate during any exception, but when its not one we know is fine to ignore, report it
                    const string errmsg =
                        "Unexpected exception when reading properties of a RenderImage. Forcing recreation. Exception: {0}";
                    if (log.IsWarnEnabled)
                        log.WarnFormat(errmsg, ex);

                    mustRecreate = true;
                }

                // Create the buffer RenderImage if needed
                if (!mustRecreate)
                    return ri;

                // If there is an old Image, make sure to dispose of it... or at least try to
                if (ri != null && disposeExisting)
                {
                    try
                    {
                        if (!ri.IsDisposed)
                            ri.Dispose();
                    }
                    catch (Exception ex)
                    {
                        const string errmsg = "Failed to dispose RenderImage. This is usually not a concern. Exception: {0}";

                        // Ignore failure to dispose
                        if (log.IsInfoEnabled)
                            log.InfoFormat(errmsg, ex);
                    }
                }

                // Get the size to make the new RenderImage (same size of the window)
                uint width;
                uint height;
                try
                {
                    width = w.Width;
                    height = w.Height;
                }
                catch (InvalidOperationException ex)
                {
                    const string errmsg =
                        "Failed to create window buffer render image" +
                        " - failed to get Window width/height. Will attempt again next frame. Exception: {0}";
                    if (log.IsWarnEnabled)
                        log.WarnFormat(errmsg, ex);
                    return null;
                }

                // Check for a valid RenderWindow size. These can be 0 when the window has been minimized.
                if (width <= 0 || height <= 0)
                {
                    const string errmsg =
                        "Unable to create window buffer render image" +
                        " - invalid Width/Height ({0},{1}) returned from Window. Most likely, the form was minimized.";
                    if (log.IsInfoEnabled)
                        log.InfoFormat(errmsg, width, height);
                    return null;
                }

                // Create the new RenderImage
                try
                {
                    ri = new RenderImage(width, height);
                }
                catch (LoadingFailedException ex)
                {
                    const string errmsg =
                        "Failed to create window buffer render image" + " - construction of Image failed. Exception: {0}";
                    if (log.IsWarnEnabled)
                        log.WarnFormat(errmsg, ex);
                    return null;
                }
            }
            catch (Exception ex)
            {
                const string errmsg = "Completely unexpected exception in CreateBufferRenderImage. Exception: {0}";
                if (log.IsErrorEnabled)
                    log.ErrorFormat(errmsg, ex);
                Debug.Fail(string.Format(errmsg, ex));
                return null;
            }

            return ri;
        }
Пример #15
0
 internal void on_resize()
 {
     if (autoscales)
     {
         w = (uint)(screen_w * scaler);
         h = (uint)(screen_h * scaler);
         _image = new RenderImage(w,h);
     }
 }
Пример #16
0
 public void force_resize(uint w, uint h)
 {
     this.w = w;
     this.h = h;
     _image = new RenderImage(w, h);
 }
Пример #17
0
        /// <summary>
        /// Begins drawing of the world.
        /// </summary>
        /// <param name="camera">The camera describing the the current view of the world.</param>
        /// <returns>
        /// The <see cref="ISpriteBatch"/> to use to draw the world objects, or null if an unexpected
        /// error was encountered when preparing the <see cref="ISpriteBatch"/>. When null, all drawing
        /// should be aborted completely instead of trying to draw with a different <see cref="ISpriteBatch"/>
        /// or manually recovering the error.
        /// </returns>
        /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to
        /// <see cref="DrawingManagerState.Idle"/>.</exception>
        public ISpriteBatch BeginDrawWorld(ICamera2D camera)
        {
            if (State != DrawingManagerState.Idle)
                throw new InvalidOperationException("This method cannot be called while already busy drawing.");

            try
            {
                // Ensure the RenderWindow is available
                if (!IsRenderWindowAvailable())
                {
                    if (log.IsInfoEnabled)
                        log.Info("Skipping BeginDrawWorld() call - the RenderWindow is not available.");
                    _state = DrawingManagerState.Idle;
                    return null;
                }

                _worldCamera = camera;

                // No matter what the last draw was, we clear the screen when drawing the world since the world drawing
                // always comes first or not at all (makes no sense to draw the GUI then the world)
                _rw.Clear(BackgroundColor);

                _lastDrawWasToWorld = true;

                // Ensure the buffer is set up
                _buffer = _rw.CreateBufferRenderImage(_buffer);
                _sb.RenderTarget = _buffer;

                if (_buffer == null)
                    return null;

                _buffer.Clear(BackgroundColor);

                // Start up the SpriteBatch
                _sb.Begin(BlendMode.Alpha, camera);

                // Change the state
                _state = DrawingManagerState.DrawingWorld;
            }
            catch (AccessViolationException ex)
            {
                // More frequent and less concerning exception
                const string errmsg = "Failed to start drawing world on `{0}`. Device was probably lost. Exception: {1}";
                if (log.IsInfoEnabled)
                    log.InfoFormat(errmsg, this, ex);
                _state = DrawingManagerState.Idle;
                SafeEndSpriteBatch(_sb);
                return null;
            }
            catch (Exception ex)
            {
                // Unexpected exception
                const string errmsg = "Failed to start drawing world on `{0}` due to unexpected exception. Exception: {1}";
                if (log.IsErrorEnabled)
                    log.ErrorFormat(errmsg, this, ex);
                Debug.Fail(string.Format(errmsg, this, ex));
                _state = DrawingManagerState.Idle;
                SafeEndSpriteBatch(_sb);
                return null;
            }

            return _sb;
        }
Пример #18
0
        /// <summary>
        /// Begins drawing the graphical user interface, which is not affected by the camera.
        /// </summary>
        /// <param name="clearBuffer">When true, the buffer will be cleared before drawing. When false, the contents of the previous
        /// frame will remain in the buffer, only if the last draw was also to the GUI. When the last draw call was to the
        /// world, then this will have no affect. Useful for when you want to draw multiple GUI screens on top of one another.</param>
        /// <returns>
        /// The <see cref="ISpriteBatch"/> to use to draw the GUI, or null if an unexpected
        /// error was encountered when preparing the <see cref="ISpriteBatch"/>. When null, all drawing
        /// should be aborted completely instead of trying to draw with a different <see cref="ISpriteBatch"/>
        /// or manually recovering the error.
        /// </returns>
        /// <exception cref="InvalidOperationException"><see cref="IDrawingManager.State"/> is not equal to
        /// <see cref="DrawingManagerState.Idle"/>.</exception>
        public ISpriteBatch BeginDrawGUI(bool clearBuffer = true)
        {
            if (State != DrawingManagerState.Idle)
                throw new InvalidOperationException("This method cannot be called while already busy drawing.");

            try
            {
                // Ensure the RenderWindow is available
                if (!IsRenderWindowAvailable())
                {
                    if (log.IsInfoEnabled)
                        log.Info("Skipping BeginDrawGUI() call - the RenderWindow is not available.");
                    _state = DrawingManagerState.Idle;
                    return null;
                }

                if (clearBuffer)
                {
                    // If the last draw was also to the GUI, clear the screen
                    if (!_lastDrawWasToWorld)
                        _rw.Clear(BackgroundColor);
                }

                _lastDrawWasToWorld = false;

                // Ensure the buffer is set up
                _buffer = _rw.CreateBufferRenderImage(_buffer);
                _sb.RenderTarget = _buffer;

                if (_buffer == null)
                    return null;

                // Always clear the GUI with alpha = 0 since we will be copying it over the screen
                _buffer.Clear(_clearGUIBufferColor);

                // Start up the SpriteBatch
                _sb.Begin(BlendMode.Alpha);

                // Change the state
                _state = DrawingManagerState.DrawingGUI;
            }
            catch (AccessViolationException ex)
            {
                // More frequent and less concerning exception
                const string errmsg = "Failed to start drawing GUI on `{0}`. Device was probably lost. Exception: {1}";
                if (log.IsInfoEnabled)
                    log.InfoFormat(errmsg, this, ex);
                _state = DrawingManagerState.Idle;
                SafeEndSpriteBatch(_sb);
                return null;
            }
            catch (Exception ex)
            {
                // Unexpected exception
                const string errmsg = "Failed to start drawing GUI on `{0}` due to unexpected exception. Exception: {1}";
                if (log.IsErrorEnabled)
                    log.ErrorFormat(errmsg, this, ex);
                Debug.Fail(string.Format(errmsg, this, ex));
                _state = DrawingManagerState.Idle;
                SafeEndSpriteBatch(_sb);
                return null;
            }

            return _sb;
        }