コード例 #1
0
ファイル: RenderSystem.cs プロジェクト: klutch/StasisEngine
        public RenderSystem(LoderGame game, SystemManager systemManager, EntityManager entityManager)
        {
            _game = game;
            _systemManager = systemManager;
            _entityManager = entityManager;
            _animationManager = game.animationManager;
            //_sortedRenderablePrimitives = new SortedDictionary<float, List<IRenderablePrimitive>>();
            _cameraSystem = _systemManager.getSystem(SystemType.Camera) as CameraSystem;
            _graphicsDevice = game.GraphicsDevice;
            _spriteBatch = game.spriteBatch;
            _backgroundRenderer = new BackgroundRenderer(_spriteBatch);
            _fluidRenderTarget = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _renderedFluid = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _debugFluid = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _postSourceUnder = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _postSourceOver = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);

            _contentManager = new ContentManager(game.Services);
            _contentManager.RootDirectory = "Content";
            _fluidEffect = _contentManager.Load<Effect>("fluid_effect");
            _fluidParticleTexture = _contentManager.Load<Texture2D>("fluid_particle");
            _reticle = _contentManager.Load<Texture2D>("reticle");
            _materialRenderer = new MaterialRenderer(game.GraphicsDevice, _contentManager, game.spriteBatch);
            _primitivesEffect = _contentManager.Load<Effect>("effects/primitives");
            _pixel = new Texture2D(_graphicsDevice, 1, 1);
            _pixel.SetData<Color>(new [] { Color.White });
            _circle = _contentManager.Load<Texture2D>("circle");
            _tooltipFont = _contentManager.Load<SpriteFont>("shared_ui/tooltip_font");
        }
コード例 #2
0
 private void SetBackground()
 {
     if (TileMapControl != null)
     {
         TileMapControl.BackgroundImage = BackgroundRenderer.
                                          RenderImage();
     }
 }
コード例 #3
0
 /// <summary>
 /// Allows the game to perform any initialization it needs to before starting to run.
 /// This is where it can query for any required services and load any non-graphic
 /// related content.  Calling base.Initialize will enumerate through any components
 /// and initialize them as well.
 /// </summary>
 protected override void Initialize()
 {
     // TODO: Add your initialization logic here
     backgroundRenderer = new BackgroundRenderer();
     player             = new Player("PNG/playerShip1_blue", MathHelper.ToRadians(90));
     asteroids          = new List <Asteroid>();
     base.Initialize();
 }
コード例 #4
0
ファイル: BezelDrawingArea.cs プロジェクト: codecopy/core-1
 public PointLocation GetPointLocation(Gdk.Point point)
 {
     if (BackgroundRenderer.GetPointLocation(drawing_area, point) == PointLocation.Outside)
     {
         return(PointLocation.Outside);
     }
     return(TitleBarRenderer.GetPointLocation(drawing_area, point));
 }
コード例 #5
0
        public void Load(string mapName)
        {
            MapName = mapName;

            var mapLoader = new MapLoader($"data/maps/{MapName}.tmx");

            Background = BackgroundRenderer.Render(mapLoader, 2f);
        }
コード例 #6
0
 void Awake()
 {
     instance       = this;
     _tile          = Material.Instantiate(_tile) as Material;
     _funkySun      = Material.Instantiate(_funkySun) as Material;
     targetSunValue = sunValue = minSunValue;
     GetComponent <Renderer>().material.SetFloat("Value", 0.8f);
     AudioMenu.OnNextBeat += OnNextBeat;
     _currentPivotY        = _targetPivotY = pivotY;
 }
コード例 #7
0
        public UCTextEditor()
        {
            InitializeComponent();

            EditPageRow.Height = new GridLength(0);
            textEditor.TextArea.TextEntered  += TextArea_TextEntered;
            textEditor.TextArea.TextEntering += TextArea_TextEntering;
            BackgroundRenderer = new BackgroundRenderer(textEditor);
            textEditor.TextArea.TextView.BackgroundRenderers.Add(BackgroundRenderer);
        }
コード例 #8
0
    private void OnEnable()
    {
        Logger.Log("Lighting system enabled.", Category.Lighting);
        //don't run lighting system on headless
        if (GameData.IsHeadlessServer)
        {
            return;
        }

        if (!SystemInfo.supportsAsyncGPUReadback)
        {
            Logger.LogWarning("LightingSystem: Async GPU Readback not supported on this machine, slower synchronous readback will" +
                              " be used instead.", Category.Lighting);
        }
        HandlePPPositionRequest += ProviderPPPosition;

        // Initialize members.
        mMainCamera = gameObject.GetComponent <Camera>();

        if (mMainCamera == null)
        {
            throw new Exception("FovSystemManager require Camera component to operate.");
        }

        ValidateMainCamera(mMainCamera, renderSettings);

        if (mOcclusionRenderer == null)
        {
            mOcclusionRenderer = OcclusionMaskRenderer.InitializeMaskRenderer(gameObject, renderSettings.occlusionLayers, materialContainer.OcclusionMaskShader);
        }

        if (mLightMaskRenderer == null)
        {
            mLightMaskRenderer = LightMaskRenderer.InitializeMaskRenderer(gameObject);
        }

        if (mBackgroundRenderer == null)
        {
            mBackgroundRenderer = BackgroundRenderer.InitializeMaskRenderer(gameObject);
        }

        if (mPostProcessingStack == null)
        {
            mPostProcessingStack = new PostProcessingStack(materialContainer);
        }

        if (!renderSettings.disableAsyncGPUReadback && SystemInfo.supportsAsyncGPUReadback)
        {
            mTextureDataRequest = new TextureDataRequest();
        }

        operationParameters = new OperationParameters(mMainCamera, renderSettings, matrixRotationMode);;

        ResolveRenderingTextures(operationParameters);
    }
コード例 #9
0
        public override void Start()
        {
            var compositor = ((Xenko.Engine.Game)Game).SceneSystem.GraphicsCompositor;
            var collection = ((SceneRendererCollection)compositor.Game).Children;

            render        = (RenderTextureSceneRenderer)collection[0];
            collection[1] = blit = new BackgroundRenderer();
            DoBackgroundBufferResize();
            Game.Window.AllowUserResizing  = true;
            Game.Window.ClientSizeChanged += BackgroundBufferResize;
        }
コード例 #10
0
        protected virtual void OnRenderCompleted(RenderResult result)
        {
            if (result.IsSuccess)
            {
                _completedRequest  = result.Request;
                _completedBitmap   = result.Bitmap;
                _bitmapInvalidated = false;

                InvalidateVisual();
                BackgroundRenderer.RaiseRenderingFinished(this);
            }
        }
コード例 #11
0
        protected override void Initialize()
        {
            if (!IsDesignerHosted)
            {
                _spriteBatch        = new SpriteBatch(GraphicsDevice);
                _backgroundRenderer = new BackgroundRenderer(_spriteBatch);

                System.Windows.Forms.Application.Idle += delegate { Invalidate(); };
                MouseMove          += new System.Windows.Forms.MouseEventHandler(BackgroundDisplay_MouseMove);
                FindForm().KeyDown += new System.Windows.Forms.KeyEventHandler(Parent_KeyDown);
                FindForm().KeyUp   += new System.Windows.Forms.KeyEventHandler(Parent_KeyUp);
            }
        }
コード例 #12
0
        public KinectCanvas(KinectSensor kinectSensor, Size displaySize)
        {
            this.kinectSensor = kinectSensor;
            this.mapper       = new KinectMapper(kinectSensor);
            this.displaySize  = displaySize;

            this.drawingGroup       = new DrawingGroup();
            this.backgroundRenderer = new BackgroundRenderer(displaySize);
            this.skeletonRenderer   = new SkeletonRenderer(displaySize);
            this.jointsRenderer     = new JointsRenderer(displaySize);
            this.handsRenderer      = new HandsRenderer(displaySize);
            this.edgeRenderer       = new EdgeRenderer(displaySize);
        }
コード例 #13
0
        protected virtual void OnRenderCompleted(RenderResult result)
        {
            if (IsDisposed)
            {
                return;
            }

            completedRequest  = result.Request;
            completedBitmap   = result.Bitmap;
            bitmapInvalidated = false;

            InvalidateVisual();
            BackgroundRenderer.RaiseRenderingFinished(this);
        }
コード例 #14
0
        public VideoPlayer()
        {
            _bg = new BackgroundRenderer(
                UrhoApplication.VIDEO_WIDTH_LOW, UrhoApplication.VIDEO_HEIGHT_LOW);

            _texture = new Texture2D();
            _texture.SetSize(
                UrhoApplication.VIDEO_WIDTH_LOW, UrhoApplication.VIDEO_HEIGHT_LOW,
                Graphics.RGBAFormat, TextureUsage.Rendertarget);

            _texture.FilterMode = TextureFilterMode.Nearest;

            var renderSurface = _texture.RenderSurface;

            renderSurface.UpdateMode = RenderSurfaceUpdateMode.Updatealways;
        }
コード例 #15
0
ファイル: LightingSystem.cs プロジェクト: grigb/unitystation
    private void OnEnable()
    {
        //don't run lighting system on headless
        if (GameData.IsHeadlessServer)
        {
            return;
        }

        if (!SystemInfo.supportsAsyncGPUReadback)
        {
            UnityEngine.Debug.LogWarning("LightingSystem: Async GPU Readback not supported on this machine, slower synchronous readback will" +
                                         " be used instead.");
        }
        HandlePPPositionRequest += ProviderPPPosition;

        // Initialize members.
        mMainCamera = gameObject.GetComponent <Camera>();

        if (mMainCamera == null)
        {
            throw new Exception("FovSystemManager require Camera component to operate.");
        }

        ValidateMainCamera(mMainCamera, renderSettings);

        if (mOcclusionRenderer == null)
        {
            mOcclusionRenderer = OcclusionMaskRenderer.InitializeMaskRenderer(gameObject, renderSettings.occlusionLayers, materialContainer.OcclusionMaskShader);
        }

        if (mLightMaskRenderer == null)
        {
            mLightMaskRenderer = LightMaskRenderer.InitializeMaskRenderer(gameObject);
        }

        if (mBackgroundRenderer == null)
        {
            mBackgroundRenderer = BackgroundRenderer.InitializeMaskRenderer(gameObject);
        }

        if (mPostProcessingStack == null)
        {
            mPostProcessingStack = new PostProcessingStack(materialContainer);
        }
    }
コード例 #16
0
        private void RenderToBitmapCore(TileIndex id)
        {
            rendering = true;
            var visible = GetTileBounds(id);

            Debug.WriteLine(string.Format("Visible is {0} for id={1}", visible.ToString(), id.ToString()));

            plotter.Visible = visible;
            //plotter.InvalidateVisual();

            if (!BackgroundRenderer.GetUsesBackgroundRendering(child))
            {
                // this is done to make all inside plotter to perform measure and arrange procedures
                plotter.Dispatcher.Invoke(() => { }, DispatcherPriority.Input);
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)tileSize.Width, (int)tileSize.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(plotter);
                bmp.Freeze();
                ReportSuccessAsync(null, bmp, id);
                rendering = false;
            }
        }
コード例 #17
0
        private void RenderChildToBitmap(TileIndex id)
        {
            if (rendering)
            {
                waitingIndexes.Enqueue(id);
                return;
            }

            renderingID = id;

            if (!BackgroundRenderer.GetUsesBackgroundRendering(child))
            {
                plotter.Dispatcher.BeginInvoke((Action)(() =>
                {
                    RenderToBitmapCore(id);
                }), DispatcherPriority.Background);
            }
            else
            {
                RenderToBitmapCore(id);
            }
        }
コード例 #18
0
        private static void Go(string filename, ICollection <string> filenames, int width, int height, int fps,
                               string background,
                               string logo, string vgmFile, int previewFrameskip, float highPassFrequency, float scale,
                               Type triggerAlgorithm, int viewSamples, int numColumns, string ffMpegPath, string ffMpegExtraArgs,
                               string masterAudioFilename, float autoScale, Color gridColor, float gridWidth, bool gridOuter,
                               Color zeroLineColor, float zeroLineWidth, float lineWidth)
        {
            filename = Path.GetFullPath(filename);
            var waitForm = new WaitForm();

            waitForm.Show();

            int sampleRate;

            using (var reader = new WaveFileReader(filenames.First()))
            {
                sampleRate = reader.WaveFormat.SampleRate;
            }

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            int stepsPerFile  = 1 + (highPassFrequency > 0 ? 1 : 0) + 2;
            int totalProgress = filenames.Count * stepsPerFile;
            int progress      = 0;

            var loadTask = Task.Run(() =>
            {
                // Do a parallel read of all files
                var channels = filenames.AsParallel().Select((wavFilename, channelIndex) =>
                {
                    var reader = new WaveFileReader(wavFilename);
                    var buffer = new float[reader.SampleCount];

                    // We read the file and convert to mono
                    reader.ToSampleProvider().ToMono().Read(buffer, 0, (int)reader.SampleCount);
                    Interlocked.Increment(ref progress);

                    // We don't care about ones where the samples are all equal
                    // ReSharper disable once CompareOfFloatsByEqualityOperator
                    if (buffer.Length == 0 || buffer.All(s => s == buffer[0]))
                    {
                        // So we skip steps here
                        reader.Dispose();
                        Interlocked.Add(ref progress, stepsPerFile - 1);
                        return(null);
                    }

                    if (highPassFrequency > 0)
                    {
                        // Apply the high pass filter
                        var filter = BiQuadFilter.HighPassFilter(reader.WaveFormat.SampleRate, highPassFrequency, 1);
                        for (int i = 0; i < buffer.Length; ++i)
                        {
                            buffer[i] = filter.Transform(buffer[i]);
                        }

                        Interlocked.Increment(ref progress);
                    }

                    float max = float.MinValue;
                    foreach (var sample in buffer)
                    {
                        max = Math.Max(max, Math.Abs(sample));
                    }

                    return(new { Data = buffer, WavReader = reader, Max = max });
                }).Where(ch => ch != null).ToList();

                if (autoScale > 0 || scale > 1)
                {
                    // Calculate the multiplier
                    float multiplier = 1.0f;
                    if (autoScale > 0)
                    {
                        multiplier = autoScale / channels.Max(channel => channel.Max);
                    }

                    if (scale > 1)
                    {
                        multiplier *= scale;
                    }

                    // ...and we apply it
                    channels.AsParallel().Select(channel => channel.Data).ForAll(samples =>
                    {
                        for (int i = 0; i < samples.Length; ++i)
                        {
                            samples[i] *= multiplier;
                        }

                        Interlocked.Increment(ref progress);
                    });
                }

                return(channels.ToList());
            });

            while (!loadTask.IsCompleted)
            {
                Application.DoEvents();
                Thread.Sleep(1);
                waitForm.Progress("Reading data...", (double)progress / totalProgress);
            }

            var voiceData = loadTask.Result.Select(channel => channel.Data).ToList();

            waitForm.Close();

            // Emit normalised data to a WAV file for later mixing
            if (masterAudioFilename == null)
            {
                // Generate a temp filename
                masterAudioFilename = filename + ".wav";
                // Mix the audio. We should probably not be re-reading it here... should do this in one pass.
                foreach (var reader in loadTask.Result.Select(channel => channel.WavReader))
                {
                    reader.Position = 0;
                }
                var mixer     = new MixingSampleProvider(loadTask.Result.Select(channel => channel.WavReader.ToSampleProvider()));
                var length    = (int)loadTask.Result.Max(channel => channel.WavReader.SampleCount);
                var mixedData = new float[length * mixer.WaveFormat.Channels];
                mixer.Read(mixedData, 0, mixedData.Length);
                // Then we want to deinterleave it
                var leftChannel  = new float[length];
                var rightChannel = new float[length];
                for (int i = 0; i < length; ++i)
                {
                    leftChannel[i]  = mixedData[i * 2];
                    rightChannel[i] = mixedData[i * 2 + 1];
                }
                // Then Replay Gain it
                // The +3 is to make it at "YouTube loudness", which is a lot louder than ReplayGain defaults to.
                var replayGain = new TrackGain(sampleRate);
                replayGain.AnalyzeSamples(leftChannel, rightChannel);
                float multiplier = (float)Math.Pow(10, (replayGain.GetGain() + 3) / 20);
                Debug.WriteLine($"ReplayGain multiplier is {multiplier}");
                // And apply it
                for (int i = 0; i < mixedData.Length; ++i)
                {
                    mixedData[i] *= multiplier;
                }
                WaveFileWriter.CreateWaveFile(
                    masterAudioFilename,
                    new FloatArraySampleProvider(mixedData, sampleRate).ToWaveProvider());
            }

            var backgroundImage = new BackgroundRenderer(width, height, Color.Black);

            if (background != null)
            {
                using (var bm = Image.FromFile(background))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.MiddleCenter, true, DockStyle.None, 0.5f));
                }
            }

            if (logo != null)
            {
                using (var bm = Image.FromFile(logo))
                {
                    backgroundImage.Add(new ImageInfo(bm, ContentAlignment.BottomRight, false, DockStyle.None, 1));
                }
            }

            if (vgmFile != null)
            {
                var gd3     = Gd3Tag.LoadFromVgm(vgmFile);
                var gd3Text = gd3.ToString();
                if (gd3Text.Length > 0)
                {
                    backgroundImage.Add(new TextInfo(gd3Text, "Tahoma", 16, ContentAlignment.BottomLeft, FontStyle.Regular,
                                                     DockStyle.Bottom, Color.White));
                }
            }

            var renderer = new WaveformRenderer
            {
                BackgroundImage            = backgroundImage.Image,
                Columns                    = numColumns,
                FramesPerSecond            = fps,
                Width                      = width,
                Height                     = height,
                SamplingRate               = sampleRate,
                RenderedLineWidthInSamples = viewSamples,
                RenderingBounds            = backgroundImage.WaveArea
            };

            if (gridColor != Color.Empty && gridWidth > 0)
            {
                renderer.Grid = new WaveformRenderer.GridConfig
                {
                    Color      = gridColor,
                    Width      = gridWidth,
                    DrawBorder = gridOuter
                };
            }

            if (zeroLineColor != Color.Empty && zeroLineWidth > 0)
            {
                renderer.ZeroLine = new WaveformRenderer.ZeroLineConfig
                {
                    Color = zeroLineColor,
                    Width = zeroLineWidth
                };
            }

            foreach (var channel in voiceData)
            {
                renderer.AddChannel(new Channel(channel, Color.White, lineWidth, "Hello world", Activator.CreateInstance(triggerAlgorithm) as ITriggerAlgorithm, 0));
            }

            var outputs = new List <IGraphicsOutput>();

            if (ffMpegPath != null)
            {
                outputs.Add(new FfmpegOutput(ffMpegPath, filename, width, height, fps, ffMpegExtraArgs, masterAudioFilename));
            }

            if (previewFrameskip > 0)
            {
                outputs.Add(new PreviewOutput(previewFrameskip));
            }

            try
            {
                renderer.Render(outputs);
            }
            catch (Exception)
            {
                // Should mean it was cancelled
            }
            finally
            {
                foreach (var graphicsOutput in outputs)
                {
                    graphicsOutput.Dispose();
                }
            }
        }
コード例 #19
0
ファイル: BezelDrawingArea.cs プロジェクト: codecopy/core-1
        void Paint()
        {
            if (!IsDrawable)
            {
                return;
            }
            using (var cr2 = Gdk.CairoHelper.Create(GdkWindow)) {
                //Much kudos to Ian McIntosh
                if (surface == null)
                {
                    surface = cr2.CreateSimilarToTarget(WindowWidth, WindowHeight);
                }

                using (var cr = new Context(surface)) {
                    if (preview)
                    {
                        Gdk.Color bgColor;
                        using (Gtk.Style rcstyle = Gtk.Rc.GetStyle(this)) {
                            bgColor = rcstyle.Backgrounds [(int)StateType.Normal];
                        }
                        cr.SetSourceRGBA(bgColor.ConvertToCairo(1));
                    }
                    else
                    {
                        cr.SetSourceRGBA(0, 0, 0, 0);
                    }
                    cr.Operator = Cairo.Operator.Source;
                    cr.Paint();
                    cr.Operator = Cairo.Operator.Over;

                    BackgroundRenderer.RenderItem(cr, drawing_area);

                    RenderTitleBar(cr);
                    do
                    {
                        if (text_box_scale > 0)
                        {
                            RenderTextModeOverlay(cr);
                            if (text_box_scale == 1)
                            {
                                RenderTextModeText(cr);
                                continue;
                            }
                        }

                        if (BezelDefaults.RenderDescriptionText)
                        {
                            RenderDescriptionText(cr);
                        }
                        //--------------First Pane---------------
                        RenderPane(Pane.First, cr);
                        //------------Second Pane----------------
                        RenderPane(Pane.Second, cr);
                        //------------Third Pane-----------------
                        if (ThirdPaneVisible)
                        {
                            RenderPane(Pane.Third, cr);
                        }

                        if (text_box_scale > 0)
                        {
                            RenderTextModeOverlay(cr);
                        }
                    } while (false);

                    if (DrawShadow)
                    {
                        Util.Appearance.DrawShadow(cr, drawing_area.X, drawing_area.Y, drawing_area.Width,
                                                   drawing_area.Height, WindowRadius, new Util.ShadowParameters(.5, ShadowRadius));
                    }

                    if (window_scale != 1)                      //we are likely in preview mode, though this can be set on the fly
                    {
                        cr2.Scale(window_scale, window_scale);
                    }
                    cr2.SetSourceSurface(surface, 0, 0);
                    cr2.Operator = Operator.Source;
                    cr2.Paint();
                }
            }
        }
コード例 #20
0
        public override void Run(Size size)
        {
            _gui = _guiManager.Create(size, ViewModel);
            Glfw.Init();
            // Create GLFW window
            _window = Glfw.CreateWindow(size.Width, size.Height, "OpenCAD", GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
            Glfw.SetWindowSizeCallback(_window, (wnd, newwidth, newheight) =>
            {
                GL.Viewport(0, 0, newwidth, newheight);
                _gui.Resize(new Size(newwidth, newheight));
            });

            Glfw.SetCursorPosCallback(_window, (wnd, x, y) => _gui.MouseMove(new Point((int)x, (int)y)));
            Glfw.SetWindowFocusCallback(_window, (wnd, focus) => _messageAggregator.Add(new FocusChangedMessage(this, focus)));
            Glfw.SetMouseButtonCallback(_window, OnCbfun);
            // Enable the OpenGL context for the current window
            Glfw.MakeContextCurrent(_window);

            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.VertexArray);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            //var back = new BackgroundRenderer(new GradientBackground(Color.YellowGreen, Color.Blue, Color.Plum, Color.Aquamarine));
            var back = new BackgroundRenderer(new SolidBackground(Color.FromArgb(35, 30, 32)));
            var gui  = new GUIRenderer();

            _modelRenderer = new ModelRenderer();
            _gui.Resize(size);

            while (!Glfw.WindowShouldClose(_window))
            {
                // Poll GLFW window events
                Glfw.PollEvents();

                // If you press escape the window will close
                if (Glfw.GetKey(_window, Key.Escape))
                {
                    Glfw.SetWindowShouldClose(_window, true);
                }

                _gui.Update();
                if (_gui.IsDirty)
                {
                    //Console.WriteLine("Dirty");
                    gui.Texture.Update(_gui);
                }
                // Set OpenGL clear colour to red
                GL.ClearColor(1.0f, 0.0f, 0.0f, 1.0f);

                // Clear the screen
                GL.Clear(ClearBufferMask.ColorBufferBit);
                back.Render();

                var model = ViewModel as IHasScenes;
                if (model != null)
                {
                    _modelRenderer.Render(model.CurrentScene);
                }

                //if (CurrentScene != null)
                //{
                //    _modelRenderer.Render(CurrentScene);
                //}

                gui.Render();

                // Swap the front and back buffer, displaying the scene
                Glfw.SwapBuffers(_window);
            }

            // Finally, clean up Glfw, and close the window
            Glfw.Terminate();
        }
コード例 #21
0
ファイル: Renderer.cs プロジェクト: impoetk/bepuphysics2
        public Renderer(RenderSurface surface)
        {
            looper  = new ParallelLooper();
            Surface = surface;
            using (var stream = new MemoryStream(Resources.DemoRendererShaders))
            {
                ShaderCache = ShaderCache.Load(stream);
            }
            Shapes         = new ShapesExtractor(looper);
            SphereRenderer = new SphereRenderer(surface.Device, ShaderCache);
            Lines          = new LineExtractor(looper);
            LineRenderer   = new LineRenderer(surface.Device, ShaderCache);
            Background     = new BackgroundRenderer(surface.Device, ShaderCache);
            CompressToSwap = new CompressToSwap(surface.Device, ShaderCache);

            GlyphRenderer  = new GlyphRenderer(surface.Device, surface.Context, ShaderCache);
            TextBatcher    = new TextBatcher();
            UILineRenderer = new UILineRenderer(surface.Device, ShaderCache);
            UILineBatcher  = new UILineBatcher();

            OnResize();
            var rasterizerStateDescription = RasterizerStateDescription.Default();

            rasterizerStateDescription.IsFrontCounterClockwise = true;
            rasterizerStateDescription.CullMode = CullMode.None;
            rasterizerState           = new RasterizerState(Surface.Device, rasterizerStateDescription);
            rasterizerState.DebugName = "Default Rasterizer State";

            var opaqueDepthStencilDescription = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                //Note depth reversal.
                DepthComparison  = Comparison.Greater,
                IsStencilEnabled = false
            };

            opaqueDepthState           = new DepthStencilState(Surface.Device, opaqueDepthStencilDescription);
            opaqueDepthState.DebugName = "Opaque Depth State";

            var opaqueBlendStateDescription = BlendStateDescription.Default();

            opaqueBlendState           = new BlendState(Surface.Device, opaqueBlendStateDescription);
            opaqueBlendState.DebugName = "Opaque Blend State";

            var uiDepthStateDescription = new DepthStencilStateDescription
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.Zero,
                //Note depth reversal.
                DepthComparison  = Comparison.Greater,
                IsStencilEnabled = false
            };

            uiDepthState           = new DepthStencilState(Surface.Device, uiDepthStateDescription);
            uiDepthState.DebugName = "UI Depth State";

            //The UI will use premultiplied alpha.
            var uiBlendStateDescription = BlendStateDescription.Default();

            uiBlendStateDescription.RenderTarget[0].IsBlendEnabled        = true;
            uiBlendStateDescription.RenderTarget[0].SourceBlend           = BlendOption.One;
            uiBlendStateDescription.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            uiBlendStateDescription.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            uiBlendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
            uiBlendStateDescription.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            uiBlendStateDescription.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            uiBlendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            uiBlendState           = new BlendState(Surface.Device, uiBlendStateDescription);
            uiBlendState.DebugName = "UI Blend State";
        }
コード例 #22
0
        public override void Draw(Squared.Render.Frame frame)
        {
            CreateRenderTargets();

            LightmapMaterials.ViewportScale    = new Vector2(1f / LightmapScale);
            LightmapMaterials.ProjectionMatrix = Matrix.CreateOrthographicOffCenter(
                0, BackgroundLightmap.Width,
                BackgroundLightmap.Height, 0,
                0, 1
                );

            using (var backgroundGroup = BatchGroup.ForRenderTarget(frame, 0, Background)) {
                ClearBatch.AddNew(backgroundGroup, 1, Game.ScreenMaterials.Clear, clearColor: Color.Transparent);

                using (var bb = BitmapBatch.New(backgroundGroup, 2, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    for (var i = 0; i < 1; i++)
                    {
                        var layer = Layers[i];
                        var dc    = new BitmapDrawCall(layer, Vector2.Zero);
                        dc.SortKey = i;
                        bb.Add(dc);
                    }
                }
            }

            using (var foregroundGroup = BatchGroup.ForRenderTarget(frame, 1, Foreground)) {
                ClearBatch.AddNew(foregroundGroup, 1, Game.ScreenMaterials.Clear, clearColor: Color.Transparent);

                using (var bb = BitmapBatch.New(foregroundGroup, 2, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    for (var i = 1; i < Layers.Length; i++)
                    {
                        var layer = Layers[i];
                        var dc    = new BitmapDrawCall(layer, Vector2.Zero);
                        dc.SortKey = i;
                        bb.Add(dc);
                    }
                }
            }

            using (var backgroundLightGroup = BatchGroup.ForRenderTarget(frame, 4, BackgroundLightmap)) {
                ClearBatch.AddNew(backgroundLightGroup, 1, LightmapMaterials.Clear, clearColor: new Color(32, 32, 32, 255), clearZ: 0, clearStencil: 0);
                BackgroundRenderer.RenderLighting(frame, backgroundLightGroup, 2);
            }

            using (var foregroundLightGroup = BatchGroup.ForRenderTarget(frame, 5, ForegroundLightmap)) {
                ClearBatch.AddNew(foregroundLightGroup, 1, LightmapMaterials.Clear, clearColor: new Color(96, 96, 96, 255), clearZ: 0, clearStencil: 0);
                ForegroundRenderer.RenderLighting(frame, foregroundLightGroup, 2);
            }

            SetRenderTargetBatch.AddNew(frame, 49, null);
            ClearBatch.AddNew(frame, 50, Game.ScreenMaterials.Clear, clearColor: Color.Black, clearZ: 0, clearStencil: 0);

            if (ShowLightmap)
            {
                using (var bb = BitmapBatch.New(frame, 55, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    var dc = new BitmapDrawCall(BackgroundLightmap, Vector2.Zero, LightmapScale);
                    bb.Add(dc);
                }

                ParticleRenderer.Draw(frame, 56);
            }
            else
            {
                var dc = new BitmapDrawCall(Background, Vector2.Zero);

                var material = LightmapMaterials.Get(LightmapMaterials.WorldSpaceLightmappedBitmap, blendState: BlendState.AlphaBlend);

                using (var bb = BitmapBatch.New(frame, 55, material)) {
                    dc.Textures = new TextureSet(Background, BackgroundLightmap);
                    dc.SortKey  = 0;

                    bb.Add(dc);
                }

                ParticleRenderer.Draw(frame, 56);

                using (var bb = BitmapBatch.New(frame, 57, material)) {
                    dc.Textures = new TextureSet(Foreground, ForegroundLightmap);
                    dc.SortKey  = 1;

                    bb.Add(dc);
                }
            }

            if (ShowOutlines || (Dragging != null))
            {
                BackgroundRenderer.RenderOutlines(frame, 59, true);
            }
        }
コード例 #23
0
        protected override void Initialize()
        {
            if (!IsDesignerHosted)
            {
                _spriteBatch = new SpriteBatch(GraphicsDevice);
                _backgroundRenderer = new BackgroundRenderer(_spriteBatch);

                System.Windows.Forms.Application.Idle += delegate { Invalidate(); };
                MouseMove += new System.Windows.Forms.MouseEventHandler(BackgroundDisplay_MouseMove);
                FindForm().KeyDown += new System.Windows.Forms.KeyEventHandler(Parent_KeyDown);
                FindForm().KeyUp += new System.Windows.Forms.KeyEventHandler(Parent_KeyUp);
            }
        }
コード例 #24
0
        protected override void LoadContent()
        {
            Logger.log("LoderGame.LoadContent method started.");

            Texture2D pixel = new Texture2D(GraphicsDevice, 1, 1);

            pixel.SetData <Color>(new[] { Color.White });

            _logo = Content.Load <Texture2D>("logo");

            // TODO: Be more selective about which resources to load?
            ResourceManager.initialize(GraphicsDevice);
            ResourceManager.loadAllCharacters(TitleContainer.OpenStream(ResourceManager.characterPath));
            ResourceManager.loadAllCircuits(TitleContainer.OpenStream(ResourceManager.circuitPath));
            ResourceManager.loadAllDialogue(TitleContainer.OpenStream(ResourceManager.dialoguePath));
            ResourceManager.loadAllItems(TitleContainer.OpenStream(ResourceManager.itemPath));
            ResourceManager.loadAllBlueprints(TitleContainer.OpenStream(ResourceManager.blueprintPath));
            ResourceManager.loadAllMaterials(TitleContainer.OpenStream(ResourceManager.materialPath));
            ResourceManager.loadAllBackgrounds(TitleContainer.OpenStream(ResourceManager.backgroundPath));
            ResourceManager.loadAllWorldMaps(TitleContainer.OpenStream(ResourceManager.worldMapPath));
            ResourceManager.loadAllRopeMaterials(TitleContainer.OpenStream(ResourceManager.ropeMaterialPath));
            ResourceManager.loadAllQuests(TitleContainer.OpenStream(ResourceManager.questPath));

            // Load user interface textures
            string[] interfaceTextures =
            {
                "blue_pane_top_left_corner",
                "blue_pane_top_right_corner",
                "blue_pane_bottom_right_corner",
                "blue_pane_bottom_left_corner",
                "blue_pane_left_side",
                "blue_pane_top_side",
                "blue_pane_right_side",
                "blue_pane_bottom_side",
                "blue_pane_background",
                "stone_pane_top_left_corner",
                "stone_pane_top_right_corner",
                "stone_pane_bottom_right_corner",
                "stone_pane_bottom_left_corner",
                "stone_pane_left_side",
                "stone_pane_top_side",
                "stone_pane_right_side",
                "stone_pane_bottom_side",
                "stone_pane_background",
                "cancel_button",
                "cancel_button_over",
                "okay_button",
                "okay_button_over",
                "line_indicator",
                "progress_bar_background",
                "progress_bar_fill",
                "progress_bar_border"
            };
            foreach (string texture in interfaceTextures)
            {
                if (File.Exists(ResourceManager.texturePath + "/" + texture + ".png") || File.Exists(ResourceManager.texturePath + "/" + texture + ".jpg"))
                {
                    ResourceManager.getTexture(texture);
                }
                else
                {
                    ResourceManager.setTexture(texture, Content.Load <Texture2D>("shared_ui/" + texture));
                }
            }
            ResourceManager.setTexture("pixel", pixel);

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _arial       = Content.Load <SpriteFont>("arial");

            _menuBackgroundRenderer = new BackgroundRenderer(_spriteBatch);

            // Scripts
            _scriptManager.addScript("home_village", new HomeVillageScript(_systemManager, _entityManager));
            _scriptManager.addScript("dagny_house", new DagnyHouseScript(_systemManager, _entityManager));
            _scriptManager.addScript("home_village_ravine", new HomeVillageRavineScript(_systemManager, _entityManager));

            Logger.log("LoderGame.LoadContent method finished.");
        }
コード例 #25
0
        public Renderer(RenderSurface surface)
        {
            looper  = new ParallelLooper();
            Surface = surface;
            using (var stream = GetType().Assembly.GetManifestResourceStream("DemoRenderer.DemoRenderer.shaderarchive"))
            {
                ShaderCache = ShaderCache.Load(stream);
            }
            pool             = new BufferPool();
            Shapes           = new ShapesExtractor(Surface.Device, looper, pool);
            SphereRenderer   = new RayTracedRenderer <SphereInstance>(surface.Device, ShaderCache, @"ShapeDrawing\RenderSpheres.hlsl");
            CapsuleRenderer  = new RayTracedRenderer <CapsuleInstance>(surface.Device, ShaderCache, @"ShapeDrawing\RenderCapsules.hlsl");
            BoxRenderer      = new BoxRenderer(surface.Device, ShaderCache);
            TriangleRenderer = new TriangleRenderer(surface.Device, ShaderCache);
            MeshRenderer     = new MeshRenderer(surface.Device, Shapes.MeshCache, ShaderCache);
            Lines            = new LineExtractor(pool, looper);
            LineRenderer     = new LineRenderer(surface.Device, ShaderCache);
            Background       = new BackgroundRenderer(surface.Device, ShaderCache);
            CompressToSwap   = new CompressToSwap(surface.Device, ShaderCache);

            GlyphRenderer  = new GlyphRenderer(surface.Device, surface.Context, ShaderCache);
            TextBatcher    = new TextBatcher();
            UILineRenderer = new UILineRenderer(surface.Device, ShaderCache);
            UILineBatcher  = new UILineBatcher();

            OnResize();
            var rasterizerStateDescription = RasterizerStateDescription.Default();

            rasterizerStateDescription.IsFrontCounterClockwise = true;
            rasterizerStateDescription.CullMode = CullMode.Back;
            rasterizerState           = new RasterizerState(Surface.Device, rasterizerStateDescription);
            rasterizerState.DebugName = "Default Rasterizer State";

            var opaqueDepthStencilDescription = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                //Note depth reversal.
                DepthComparison  = Comparison.Greater,
                IsStencilEnabled = false
            };

            opaqueDepthState           = new DepthStencilState(Surface.Device, opaqueDepthStencilDescription);
            opaqueDepthState.DebugName = "Opaque Depth State";

            var opaqueBlendStateDescription = BlendStateDescription.Default();

            opaqueBlendState           = new BlendState(Surface.Device, opaqueBlendStateDescription);
            opaqueBlendState.DebugName = "Opaque Blend State";

            var a2cBlendStateDescription = BlendStateDescription.Default();

            a2cBlendStateDescription.AlphaToCoverageEnable = true;
            a2cBlendState           = new BlendState(Surface.Device, a2cBlendStateDescription);
            a2cBlendState.DebugName = "A2C Blend State";

            var uiDepthStateDescription = new DepthStencilStateDescription
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.Zero,
                //Note depth reversal.
                DepthComparison  = Comparison.Greater,
                IsStencilEnabled = false
            };

            uiDepthState           = new DepthStencilState(Surface.Device, uiDepthStateDescription);
            uiDepthState.DebugName = "UI Depth State";

            //The UI will use premultiplied alpha.
            var uiBlendStateDescription = BlendStateDescription.Default();

            uiBlendStateDescription.RenderTarget[0].IsBlendEnabled        = true;
            uiBlendStateDescription.RenderTarget[0].SourceBlend           = BlendOption.One;
            uiBlendStateDescription.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            uiBlendStateDescription.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            uiBlendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
            uiBlendStateDescription.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            uiBlendStateDescription.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            uiBlendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            uiBlendState           = new BlendState(Surface.Device, uiBlendStateDescription);
            uiBlendState.DebugName = "UI Blend State";
        }
コード例 #26
0
ファイル: LoderGame.cs プロジェクト: klutch/StasisEngine
        protected override void LoadContent()
        {
            Logger.log("LoderGame.LoadContent method started.");

            Texture2D pixel = new Texture2D(GraphicsDevice, 1, 1);
            pixel.SetData<Color>(new[] { Color.White });

            _logo = Content.Load<Texture2D>("logo");

            // TODO: Be more selective about which resources to load?
            ResourceManager.initialize(GraphicsDevice);
            ResourceManager.loadAllCharacters(TitleContainer.OpenStream(ResourceManager.characterPath));
            ResourceManager.loadAllCircuits(TitleContainer.OpenStream(ResourceManager.circuitPath));
            ResourceManager.loadAllDialogue(TitleContainer.OpenStream(ResourceManager.dialoguePath));
            ResourceManager.loadAllItems(TitleContainer.OpenStream(ResourceManager.itemPath));
            ResourceManager.loadAllBlueprints(TitleContainer.OpenStream(ResourceManager.blueprintPath));
            ResourceManager.loadAllMaterials(TitleContainer.OpenStream(ResourceManager.materialPath));
            ResourceManager.loadAllBackgrounds(TitleContainer.OpenStream(ResourceManager.backgroundPath));
            ResourceManager.loadAllWorldMaps(TitleContainer.OpenStream(ResourceManager.worldMapPath));
            ResourceManager.loadAllRopeMaterials(TitleContainer.OpenStream(ResourceManager.ropeMaterialPath));
            ResourceManager.loadAllQuests(TitleContainer.OpenStream(ResourceManager.questPath));

            // Load user interface textures
            string[] interfaceTextures =
            {
                "blue_pane_top_left_corner",
                "blue_pane_top_right_corner",
                "blue_pane_bottom_right_corner",
                "blue_pane_bottom_left_corner",
                "blue_pane_left_side",
                "blue_pane_top_side",
                "blue_pane_right_side",
                "blue_pane_bottom_side",
                "blue_pane_background",
                "stone_pane_top_left_corner",
                "stone_pane_top_right_corner",
                "stone_pane_bottom_right_corner",
                "stone_pane_bottom_left_corner",
                "stone_pane_left_side",
                "stone_pane_top_side",
                "stone_pane_right_side",
                "stone_pane_bottom_side",
                "stone_pane_background",
                "cancel_button",
                "cancel_button_over",
                "okay_button",
                "okay_button_over",
                "line_indicator",
                "progress_bar_background",
                "progress_bar_fill",
                "progress_bar_border"
            };
            foreach (string texture in interfaceTextures)
            {
                if (File.Exists(ResourceManager.texturePath + "/" + texture + ".png") || File.Exists(ResourceManager.texturePath + "/" + texture + ".jpg"))
                {
                    ResourceManager.getTexture(texture);
                }
                else
                {
                    ResourceManager.setTexture(texture, Content.Load<Texture2D>("shared_ui/" + texture));
                }
            }
            ResourceManager.setTexture("pixel", pixel);

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _arial = Content.Load<SpriteFont>("arial");

            _menuBackgroundRenderer = new BackgroundRenderer(_spriteBatch);

            // Scripts
            _scriptManager.addScript("home_village", new HomeVillageScript(_systemManager, _entityManager));
            _scriptManager.addScript("dagny_house", new DagnyHouseScript(_systemManager, _entityManager));
            _scriptManager.addScript("home_village_ravine", new HomeVillageRavineScript(_systemManager, _entityManager));

            Logger.log("LoderGame.LoadContent method finished.");
        }
コード例 #27
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            if (plotter == null)
            {
                return;
            }

            BackgroundRenderer.SetRenderingState(this, RenderingState.DuringRendering);
            Debug.WriteLine("RenderingState = " + BackgroundRenderer.GetRenderingState(this));

            rendering         = true;
            invalidatePending = false;

            base.OnRender(drawingContext);

            var      transform = plotter.Viewport.Transform;
            Rect     output    = plotter.Viewport.Output;
            DataRect visible   = plotter.Viewport.Visible;

            visibleBounds = visible;

            var tileInfos = GetVisibleTiles();

            //Debug.WriteLine(String.Format("OnRender: {0}", DateTime.Now.TimeOfDay.ToString()));

            int notLoadedTilesCount = 0;

            var dc             = drawingContext;
            var lowerTilesList = GetLoadedLowerTiles(tileInfos);

            // displaying lower tiles
            if (showLowerTiles)
            {
                foreach (var tileInfo in lowerTilesList)
                {
                    var tile = tileInfo.Id;

                    if (server.IsLoaded(tile))
                    {
                        var      bmp          = server[tile];
                        DataRect visibleRect  = tileProvider.GetTileBounds(tile);
                        Rect     screenRect   = visibleRect.ViewportToScreen(transform);
                        Rect     enlargedRect = EnlargeRect(screenRect);

                        dc.PushClip(tileInfo.Clip);
                        dc.DrawImage(bmp, enlargedRect);
                        dc.Pop();

                        //if (!visibleRect.IntersectsWith(visible))
                        //{
                        //    dc.DrawRectangle(Brushes.Red, null, output);
                        //}

                        if (drawDebugBounds)
                        {
                            DrawDebugInfo(dc, enlargedRect, tile);
                        }
                    }
                    else
                    {
                        server.BeginLoadImage(tile);
                    }
                }
            }

            foreach (var tileInfo in tileInfos)
            {
                if (server.IsLoaded(tileInfo.Tile))
                {
                    var bmp = server[tileInfo.Tile];

                    Rect enlargedRect = EnlargeRect(tileInfo.ScreenBounds);
                    drawingContext.DrawImage(bmp, enlargedRect);

                    // drawing debug bounds
                    if (drawDebugBounds)
                    {
                        DrawDebugInfo(drawingContext, tileInfo.ScreenBounds, tileInfo.Tile);
                    }
                }
                else
                {
                    server.BeginLoadImage(tileInfo.Tile);
                    notLoadedTilesCount++;
                }
            }

            if (notLoadedTilesCount == 0 && (notLoadedTilesCount != prevNotLoadedTilesCount))
            {
                RaiseEvent(new RoutedEventArgs(BackgroundRenderer.RenderingFinished));
                BackgroundRenderer.SetRenderingState(this, RenderingState.RenderingFinished);

                Debug.WriteLine("Rendering finished");
            }

            prevNotLoadedTilesCount = notLoadedTilesCount;
            if (prevNotLoadedTilesCount == 0)
            {
                prevNotLoadedTilesCount = -1;
            }

            rendering = false;
        }
コード例 #28
0
ファイル: LevelView.cs プロジェクト: klutch/StasisEngine
        // Initialize
        protected override void Initialize()
        {
            // Resources
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _backgroundRenderer = new BackgroundRenderer(_spriteBatch);
            _contentManager = new ContentManager(Services, "Content");
            _pixel = new Texture2D(GraphicsDevice, 1, 1);
            _pixel.SetData<Color>(new[] { Color.White });
            _circle = _contentManager.Load<Texture2D>("circle");
            _playerSpawnIcon = _contentManager.Load<Texture2D>("actor_icons\\player_spawn");
            _itemIcon = _contentManager.Load<Texture2D>("actor_icons\\item");
            _circuitIcon = _contentManager.Load<Texture2D>("actor_icons\\circuit");
            _revoluteIcon = _contentManager.Load<Texture2D>("actor_icons\\revolute");
            _prismaticIcon = _contentManager.Load<Texture2D>("actor_icons\\prismatic");
            _decalIcon = _contentManager.Load<Texture2D>("actor_icons\\decal");
            _tooltipIcon = _contentManager.Load<Texture2D>("actor_icons/tooltip");
            _font = _contentManager.Load<SpriteFont>("arial");

            _coreContentManager = new ContentManager(Services, "Content");
            _primitivesEffect = _coreContentManager.Load<Effect>("effects\\primitives");

            // Draw loop
            Application.Idle += delegate { Invalidate(); };

            // Input
            MouseDown += new MouseEventHandler(LevelView_MouseDown);
            MouseEnter += new EventHandler(LevelView_MouseEnter);
            MouseLeave += new EventHandler(LevelView_MouseLeave);
            MouseWheel += new MouseEventHandler(LevelView_MouseWheel);
        }
コード例 #29
0
        public override void Draw(Squared.Render.Frame frame)
        {
            CreateRenderTargets();

            LightmapMaterials.ViewportScale    = new Vector2(1f / LightmapScale);
            LightmapMaterials.ProjectionMatrix = Matrix.CreateOrthographicOffCenter(
                0, BackgroundLightmap.Width,
                BackgroundLightmap.Height, 0,
                0, 1
                );

            using (var backgroundGroup = BatchGroup.ForRenderTarget(frame, 0, Background)) {
                ClearBatch.AddNew(backgroundGroup, 1, Game.ScreenMaterials.Clear, clearColor: Color.Transparent);

                using (var bb = BitmapBatch.New(backgroundGroup, 2, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    for (var i = 0; i < 1; i++)
                    {
                        var layer = Layers[i];
                        var dc    = new BitmapDrawCall(layer, Vector2.Zero);
                        dc.SortKey = i;
                        bb.Add(dc);
                    }
                }
            }

            using (var foregroundGroup = BatchGroup.ForRenderTarget(frame, 1, Foreground)) {
                ClearBatch.AddNew(foregroundGroup, 1, Game.ScreenMaterials.Clear, clearColor: Color.Transparent);

                using (var bb = BitmapBatch.New(foregroundGroup, 2, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    for (var i = 1; i < Layers.Length; i++)
                    {
                        var layer = Layers[i];
                        var dc    = new BitmapDrawCall(layer, Vector2.Zero);
                        dc.SortKey = i;
                        bb.Add(dc);
                    }
                }
            }

            if (ShowBrickSpecular)
            {
                using (var bricksLightGroup = BatchGroup.ForRenderTarget(frame, 2, ForegroundLightmap)) {
                    ClearBatch.AddNew(bricksLightGroup, 1, LightmapMaterials.Clear, clearColor: new Color(0, 0, 0, 255), clearZ: 0, clearStencil: 0);
                    ForegroundRenderer.RenderLighting(frame, bricksLightGroup, 2);
                }
            }

            if (ShowAOShadow)
            {
                using (var aoShadowFirstPassGroup = BatchGroup.ForRenderTarget(frame, 3, AOShadowScratch)) {
                    ClearBatch.AddNew(aoShadowFirstPassGroup, 1, LightmapMaterials.Clear, clearColor: Color.Transparent);

                    using (var bb = BitmapBatch.New(aoShadowFirstPassGroup, 2, Game.ScreenMaterials.ScreenSpaceHorizontalGaussianBlur5Tap)) {
                        bb.Add(new BitmapDrawCall(Foreground, Vector2.Zero, 1f / LightmapScale));
                    }
                }
            }

            using (var backgroundLightGroup = BatchGroup.ForRenderTarget(frame, 4, BackgroundLightmap)) {
                ClearBatch.AddNew(backgroundLightGroup, 1, LightmapMaterials.Clear, clearColor: new Color(40, 40, 40, 255), clearZ: 0, clearStencil: 0);

                BackgroundRenderer.RenderLighting(frame, backgroundLightGroup, 2);

                if (ShowBrickSpecular)
                {
                    using (var foregroundLightBatch = BitmapBatch.New(backgroundLightGroup, 3, MaskedForegroundMaterial)) {
                        var dc = new BitmapDrawCall(
                            ForegroundLightmap, Vector2.Zero
                            );
                        dc.Textures = new TextureSet(dc.Textures.Texture1, BricksLightMask);
                        foregroundLightBatch.Add(dc);
                    }
                }
                else
                {
                    ForegroundRenderer.RenderLighting(frame, backgroundLightGroup, 3);
                }

                if (ShowAOShadow)
                {
                    using (var aoShadowBatch = BitmapBatch.New(backgroundLightGroup, 4, AOShadowMaterial)) {
                        var dc = new BitmapDrawCall(
                            AOShadowScratch, new Vector2(0, 4)
                            );
                        dc.MultiplyColor = Color.Black;
                        dc.AddColor      = Color.White;

                        aoShadowBatch.Add(dc);
                    }
                }
            }

            using (var foregroundLightGroup = BatchGroup.ForRenderTarget(frame, 5, ForegroundLightmap)) {
                ClearBatch.AddNew(foregroundLightGroup, 1, LightmapMaterials.Clear, clearColor: new Color(127, 127, 127, 255), clearZ: 0, clearStencil: 0);
                ForegroundRenderer.RenderLighting(frame, foregroundLightGroup, 2);
            }

            SetRenderTargetBatch.AddNew(frame, 49, null);
            ClearBatch.AddNew(frame, 50, Game.ScreenMaterials.Clear, clearColor: Color.Black, clearZ: 0, clearStencil: 0);

            if (ShowLightmap)
            {
                using (var bb = BitmapBatch.New(frame, 55, Game.ScreenMaterials.WorldSpaceBitmap)) {
                    var dc = new BitmapDrawCall(BackgroundLightmap, Vector2.Zero, LightmapScale);
                    bb.Add(dc);
                }
            }
            else
            {
                var dc = new BitmapDrawCall(Background, Vector2.Zero);

                var material = LightmapMaterials.Get(LightmapMaterials.WorldSpaceLightmappedBitmap, blendState: BlendState.AlphaBlend);

                using (var bb = BitmapBatch.New(frame, 55, material)) {
                    dc.Textures = new TextureSet(Background, BackgroundLightmap);
                    dc.SortKey  = 0;

                    bb.Add(dc);
                }

                ParticleRenderer.Draw(frame, 56);

                using (var bb = BitmapBatch.New(frame, 57, material)) {
                    dc.Textures = new TextureSet(Foreground, ForegroundLightmap);
                    dc.SortKey  = 1;

                    bb.Add(dc);
                }
            }

            if (ShowOutlines || (Dragging != null))
            {
                BackgroundRenderer.RenderOutlines(frame, 59, true);
            }
        }