Exemplo n.º 1
0
 public static FrameBuffer GetInstance()
 {
     if(instance==null){
         instance=new FrameBuffer();
     }
     return instance;
 }
Exemplo n.º 2
0
 public FrameBuffer Regist( string key, FrameBuffer frameBuffer )
 {
     if( Find( key ) != null ){
     return null;
     }
     frameBufferTable[ key ] = frameBuffer;
     return frameBuffer;
 }
Exemplo n.º 3
0
        private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap,
            SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared)
        {
            _frameBuffer = new FrameBuffer();     
            _frameBuffer.SetColorTarget(_texture2D,0);

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

            throw new NotImplementedException();
        }
Exemplo n.º 4
0
 public void blur_Gauss(
     fx_Quad quad,
     int blur_amount,
     Texture texture_to_blur, FrameBuffer texture_frame_buffer, DrawBuffersEnum attachement,
     float destination_scale = 1)
 {
     blur_Gauss(
         quad,
         blur_amount,
         new Vector2(1.0f, 0.0f), new Vector2(0.0f, 1.0f),
         texture_to_blur, texture_frame_buffer, attachement,
         destination_scale);
 }
Exemplo n.º 5
0
        /// <summary>
        /// If available, returns the next frame from the video. If not, returns null
        /// </summary>
        /// <returns></returns>
        public Frame PlayNextFrame()
        {
            if (FramesInBuffer)
            {
                var result = FrameBuffer.First;

                FrameBuffer.RemoveFirst();

                return(result);
            }

            return(null);
        }
Exemplo n.º 6
0
        public UIExtension(FrameBuffer buffer)
        {
            _buffer = buffer;

            _uiBuffer = new FrameBuffer(_buffer.Width, _buffer.Height);
            _buffer.GetFramebufferCopy(_uiBuffer.RawFrameBuffer);

            buffer.FrameDrawn += Buffer_FrameDrawn;

            _uiGraphics = new FrameBufferGraphics(_uiBuffer);

            BasePanel = new Panel();
        }
 protected override void PreDrawMask(FrameBuffer clippingMask)
 {
     clippingMask.Bind();
     GLWrapper.PushViewport(new RectangleI(0, 0, clippingMask.Texture.Width, clippingMask.Texture.Height));
     GLWrapper.Clear(new ClearInfo(Colour4.White));
     GLWrapper.SetBlend(new BlendingParameters
     {
         Source           = BlendingType.Zero,
         Destination      = BlendingType.OneMinusSrcColor,
         SourceAlpha      = BlendingType.Zero,
         DestinationAlpha = BlendingType.OneMinusSrcAlpha,
     });
 }
Exemplo n.º 8
0
        /// <summary>
        /// Ensures that there is no active <see cref="Buffers.FrameBuffer"/> object bound to the RenderContext.
        /// </summary>
        public void UnbindFrameBuffer()
        {
            if (_frameBufferHandle == GLHandle.Zero)
            {
                return;
            }

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, GLHandle.Zero);

            _frameBufferHandle        = GLHandle.Zero;
            _frameBuffer.BoundContext = null;
            _frameBuffer = null;
        }
Exemplo n.º 9
0
        public Engine(string contentDirectory = "Content", Vector2?screenSize = null, bool fullscreen = true, bool exclusiveFullscreen = true,
                      string firstSceneName   = null, params Scene [] scenes)
        {
            if (SharedEngine != null)
            {
                throw new InvalidOperationException();
            }

            graphics = new GraphicsDeviceManager(this)
            {
                IsFullScreen       = fullscreen,
                HardwareModeSwitch = exclusiveFullscreen
            };

            Window.AllowUserResizing  = true;
            Window.ClientSizeChanged += (sender, e) =>
            {
                if (graphics == null || GraphicsDevice == null)
                {
                    return;
                }
                graphics.PreferredBackBufferWidth  = Window.ClientBounds.Width;
                graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
                graphics.ApplyChanges();

                if (!isCustomSize)
                {
                    frameBuffer.Size = new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
                }

                CalculateBackBufferArea();
            };

            frameBuffer              = new FrameBuffer(screenSize ?? new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight));
            frameBuffer.SizeChanged += (sender, e) => CalculateBackBufferArea();
            isCustomSize             = screenSize != null;

            Content.RootDirectory = contentDirectory;

            Services.AddService(new EntityManager());
            Services.AddService(new SystemManager());
            Services.AddService(new ProcessorManager());
            Services.AddService(new SceneManager(firstSceneName, scenes));
            Services.AddService(new Coroutine());
            Services.AddService(new Logger());
            Services.AddService(new InputService());

            ProcessorManager.SharedManager.RegisterProcessor(new FrameRateCalculateProcessor());

            SharedEngine = this;
        }
        public RenderPass(FrameBuffer myFrameBuffer, SubPass[] mySubpasses = null)
        {
            List <AttachmentDescription> GBufferSupportedTypes     = new List <AttachmentDescription>();
            List <AttachmentReference>   attachmentColorReferences = new List <AttachmentReference>();
            AttachmentReference          myDepthBuffer;
            SubpassDescription           GeometryBufferSubpassDescription = new SubpassDescription()
            {
                PipelineBindPoint = PipelineBindPoint.Graphics
            };

            foreach (var Attachment in myFrameBuffer.GetAttachments())
            {
                GBufferSupportedTypes.Add(Attachment.AttachmentDescription);
                if (Attachment.AttachmentReference.Layout != ImageLayout.DepthStencilAttachmentOptimal)
                {
                    attachmentColorReferences.Add(Attachment.AttachmentReference);
                }
                else
                {
                    GeometryBufferSubpassDescription.DepthStencilAttachment = Attachment.AttachmentReference;
                }
            }
            GeometryBufferSubpassDescription.ColorAttachments = attachmentColorReferences.ToArray();


            //Above is for the Geometry Buffer to intialize.
            uint starting = 1;
            uint ending   = 2;
            List <SubpassDependency>  myIncomingDependencies = new List <SubpassDependency>();
            List <SubpassDescription> mySubpassDescriptions  = new List <SubpassDescription>();

            if (mySubpasses != null)
            {
                for (int i = 0; i < mySubpasses.Length; i++)
                {
                    myIncomingDependencies.AddRange(mySubpasses[i].GetSubpassDependencies());
                    mySubpassDescriptions.Add(mySubpasses[i].GetSubpassDescription());
                }
                ;
            }

            var aRenderPassCreateInfo = new RenderPassCreateInfo
            {
                Attachments  = GBufferSupportedTypes.ToArray(),
                Subpasses    = mySubpassDescriptions.ToArray(),
                Dependencies = myIncomingDependencies.ToArray()
            };

            myFrameBuffer.SetRenderPass(this);
            CreateRenderPass(aRenderPassCreateInfo);
        }
        ///<summary>
        ///    Compile this Composition chain into a series of RenderTarget operations.
        ///</summary>
        protected void Compile()
        {
            ClearCompiledState();

            bool compositorsEnabled = false;

            /// Set previous CompositorInstance for each compositor in the list
            CompositorInstance lastComposition = originalScene;

            originalScene.PreviousInstance = null;
            CompositionPass pass = originalScene.Technique.OutputTarget.GetPass(0);

            pass.ClearBuffers = viewport.ClearBuffers;
            pass.ClearColor   = viewport.BackgroundColor;
            foreach (CompositorInstance instance in instances)
            {
                if (instance.Enabled)
                {
                    compositorsEnabled        = true;
                    instance.PreviousInstance = lastComposition;
                    lastComposition           = instance;
                }
            }

            /// Compile misc targets
            lastComposition.CompileTargetOperations(compiledState);

            /// Final target viewport (0)
            outputOperation.RenderSystemOperations.Clear();
            lastComposition.CompileOutputOperation(outputOperation);

            // Deal with viewport settings
            if (compositorsEnabled != anyCompositorsEnabled)
            {
                anyCompositorsEnabled = compositorsEnabled;
                if (anyCompositorsEnabled)
                {
                    // Save old viewport clearing options
                    oldClearEveryFrameBuffers = viewport.ClearBuffers;
                    // Don't clear anything every frame since we have our own clear ops
                    viewport.SetClearEveryFrame(false);
                }
                else
                {
                    // Reset clearing options
                    viewport.SetClearEveryFrame(oldClearEveryFrameBuffers > 0,
                                                oldClearEveryFrameBuffers);
                }
            }
            dirty = false;
        }
Exemplo n.º 12
0
        public void Render(
            GraphicsContext graphics,
            Camera camera,
            LightModel light,
            Model model,
            BgModel bg
            )
        {
            // offscreen rendering
            FrameBuffer oldBuffer = graphics.GetFrameBuffer();

            // render the scene
            graphics.SetFrameBuffer(sceneBuffer);
            graphics.SetViewport(0, 0, sceneBuffer.Width, sceneBuffer.Height);
            graphics.SetClearColor(0.0f, 0.5f, 1.0f, 1.0f);

            renderSimpleScene(graphics, camera, light, model, bg);

            // apply gaussian along X axis
            graphics.SetFrameBuffer(gaussianXBuffer);
            graphics.SetViewport(0, 0, gaussianXBuffer.Width, gaussianXBuffer.Height);

            renderGaussianX(graphics);

            // apply gaussian along Y axis
            graphics.SetFrameBuffer(gaussianXYBuffer);
            graphics.SetViewport(0, 0, gaussianXYBuffer.Width, gaussianXYBuffer.Height);

            renderGaussianY(graphics);

            // final draw
            {
                // restore frame buffer
                graphics.SetFrameBuffer(oldBuffer);
                graphics.SetViewport(0, 0, oldBuffer.Width, oldBuffer.Height);
                graphics.SetClearColor(0.0f, 0.5f, 1.0f, 1.0f);

                graphics.Clear();

                int width  = sceneBuffer.Width / 4;
                int height = sceneBuffer.Height / 4;

                texRenderer.Begin();
                texRenderer.Render(texGaussianXY, 0, 0, 0, 0, sceneBuffer.Width, sceneBuffer.Height);

                texRenderer.Render(texScene, 0, height * 0, 0, 0, width, height);
                texRenderer.Render(texGaussianX, 0, height * 1, 0, 0, width, height);
                texRenderer.Render(texGaussianXY, 0, height * 2, 0, 0, width, height);
                texRenderer.End();
            }
        }
Exemplo n.º 13
0
        protected override void OnRenderTargetChange(FrameBuffer oldRenderTarget)
        {
            if (mInFrame)
            {
                throw new AgateException(
                          "Cannot change the current render target inside BeginFrame..EndFrame block!");
            }

            System.Diagnostics.Debug.Assert(mGraphics == null);

            mRenderTarget = RenderTarget.Impl as Drawing_FrameBuffer;

            OnRenderTargetResize();
        }
Exemplo n.º 14
0
        public override void OnProcessing(Frame current)
        {
            if (buffer == null || !current.SameSizeAs(buffer.First))
            {
                buffer = new FrameBuffer(framesNeeded, current.Width, current.Height);
            }

            var result = new MotionProcessorResult();

            //Check for duplicate frames, and assume previous result for them
            if (buffer.Count > 0 && !current.IsDifferentFrom(buffer.First))
            {
                current.ProcessorResult  = (MotionProcessorResult)buffer.First.ProcessorResult;
                current.IsReadyForRender = true;
                return;
            }

            if (buffer.Count == framesNeeded)
            {
                buffer.RemoveFirst();
            }

            buffer.Enqueue(current);

            if (buffer.Count == framesNeeded)
            {
                var prev = buffer.First;

                var roi = new System.Windows.Rect
                          (
                    new Point(current.Width * LeftBoundPCT, current.Height * TopBoundPCT),
                    new Point(current.Width * RightBoundPCT, current.Height * BottomBoundPCT)
                          );

                var changedPixels = current.ChangeExtentPoints(prev, Threshold, roi);

                result.Threshold = Threshold;

                result.ChangedPixels      = changedPixels;
                result.ChangedPixelsCount = changedPixels.Count;

                result.Frame      = current;
                result.FrameIndex = current.FrameIndex;
                result.FrameTime  = current.FrameTime;
            }

            current.ProcessorResult = result;

            current.IsReadyForRender = true;
        }
Exemplo n.º 15
0
        private void PlatformConstruct(GraphicsDevice graphicsDevice, int width, int height, bool mipMap,
                                       SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared)
        {
            _frameBuffer = new FrameBuffer();
            _frameBuffer.SetColorTarget(_texture2D, 0);

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
            {
                return;
            }

            throw new NotImplementedException();
        }
Exemplo n.º 16
0
        public void Initialize()
        {
            m_CoroutineManager   = new CoroutineManager();
            m_ResourceLoader     = new ResourceLoader();
            m_FrameBuffer        = new FrameBuffer();
            m_FrameDataCollector = new FrameDataCollector();
            m_InputManager       = new InputManager();
            m_GameLogicManager   = new GameLogicManager();
            m_LevelManager       = new LevelManager();
            m_CameraManager      = new CameraManager();

            Utils.Random.seed = 1;
            m_LevelManager.Start();
        }
        /// <summary>
        /// Makes sure the first frame buffer is always the one we want to draw from.
        /// This saves us the need to sync the draw indices across draw node trees
        /// since the Shared.FrameBuffers array is already shared.
        /// </summary>
        private void finalizeFrameBuffer()
        {
            if (currentFrameBufferIndex != 0)
            {
                Trace.Assert(currentFrameBufferIndex == 1,
                             $"Only the first two framebuffers should be the last to be written to at the end of {nameof(Draw)}.");

                FrameBuffer temp = Shared.FrameBuffers[0];
                Shared.FrameBuffers[0] = Shared.FrameBuffers[1];
                Shared.FrameBuffers[1] = temp;

                currentFrameBufferIndex = 0;
            }
        }
Exemplo n.º 18
0
        private ImageAsset getOffscreenImage(Scene scene, Texture2D texture)
        {
            FrameBuffer offScreenFramebufferCache = UISystem.offScreenFramebufferCache;

            offScreenFramebufferCache.SetColorTarget(texture, 0);
            scene.Update(0f);
            Matrix4 identity = Matrix4.Identity;

            scene.RootWidget.RenderToFrameBuffer(offScreenFramebufferCache, ref identity, false);
            return(new ImageAsset(texture)
            {
                AdjustScaledSize = true
            });
        }
Exemplo n.º 19
0
        /// <summary>
        /// adrr contains the save address of the generated image,
        /// and must have the extension .pgm;
        /// Example /home/user/image.pgm
        /// </summary>
        public void ExportMapPGM(string adrr, int baseColor, int lineColor)
        {
            FrameBuffer frame = new FrameBuffer((int)this.size.X + 1,
                                                (int)this.size.Y + 1, baseColor);

            foreach (intTuple item in this.edge)
            {
                Vector2 a = this.vertex[item.A];
                Vector2 b = this.vertex[item.B];

                LineGeneration.plotLine(a, b, frame, lineColor);
            }
            frame.Export(adrr);
        }
 public CompositorChain(Viewport vp)
 {
     this.viewport             = vp;
     originalScene             = null;
     instances                 = new List <CompositorInstance>();
     dirty                     = true;
     anyCompositorsEnabled     = false;
     compiledState             = new List <CompositorTargetOperation>();
     outputOperation           = null;
     oldClearEveryFrameBuffers = viewport.ClearBuffers;
     renderSystemOperations    = new List <CompositorRenderSystemOperation>();
     listener                  = new RQListener();
     Debug.Assert(viewport != null);
 }
Exemplo n.º 21
0
        public CXPCapabilityMessageSender(PresenterModel model, PresenterCapability capability)
        {
            this.m_Model          = model;
            this.m_LocalId        = m_Model.Participant.Guid;
            this.m_Classroom      = new ClassroomModel(null, "CXP Capability Classroom", ClassroomModelType.CXPCapability);
            this.m_Capability     = capability;
            this.m_Participants   = new Dictionary <string, ParticipantModel>();
            this.m_SsrcToSenderId = new Dictionary <uint, Guid>();
            this.m_Receivers      = new Dictionary <string, CXPCapabilityMessageReceiver>();

            m_Capability.OnStreamAdded   += new PresenterCapability.OnStreamAddedHandler(OnStreamAdded);
            m_Capability.OnStreamRemoved += new PresenterCapability.OnStreamRemovedHandler(OnStreamRemoved);
            using (Synchronizer.Lock(this)) {
                // Initialize the message chunking utilities.
                this.m_Encoder = new Chunk.ChunkEncoder();
                // TODO: Make the buffer size dynamic, ie., grow if we send a single very large message.
                // Make the buffer store up to 5MB worth of data.
                this.m_FrameBuffer = new FrameBuffer(5 * 1024 * 1024 / this.m_Encoder.MaximumChunkSize);

                // Create the NackManager which is responsible for sending NACKs on behalf of
                // our set of RTPMessageReceivers.
                this.m_NackManager = new RTPNackManager(this, this.m_Classroom);
            }

            // Create network services outside of the "lock(this)" so they can lock their own objects
            // without worrying about locking order.

            // Create the PresenterNetworkService which will watch for changes to the model and send messages.
            this.m_PresenterNetworkService = new PresenterNetworkService(this, this.m_Model);

            // Create the StudentSubmissionsNetworkService which will watch for requests to submit and send messages.
            this.m_StudentSubmissionNetworkService = new StudentSubmissionNetworkService(this, this.m_Model);

            // Create the SynchronizationNetworkService which will watch for all synchronization messages.
            this.m_SynchronizationNetworkService = new SynchronizationNetworkService(this, this.m_Model);

            // Create the ScriptingNetworkService which will watch for all scripting messages.
            this.m_ScriptingNetworkService = new ScriptingNetworkService(this, this.m_Model);

            // Create the BeaconService which will broadcast periodic information about the presentation.
            this.m_BeaconService = new Beacons.DefaultBeaconService(this, this.m_Model);

            // Report Network status to the UI
            m_CapabilityNetworkStatus = new CapabilityNetworkStatus(this.m_Model);
            m_CapabilityNetworkStatus.Register();

            // Send an initial message to announce our node to others in the venue.
            SendObject(new CapabilityMessageWrapper(null, m_LocalId, Guid.Empty, m_Capability.IsSender));
        }
Exemplo n.º 22
0
        public void WindowMovedOrResized(Vector2I size)          // bool fullScreen )//, Vec2I windowSize )
        {
            if (Disposed)
            {
                return;
            }

            EngineThreading.CheckMainThread();

            //unsafe
            //{
            //!!!!было
            //MyOgreSceneManager.destroyShadowTextures( SceneManager.realObject );

            //!!!!как теперь? текстуры композитинга удалять? где еще?
            //MyOgreSceneManager.destroyAdditionalMRTs( SceneManager.realObject );
            //}

            //foreach( Viewport viewport in viewports )
            //{
            //   foreach( CompositorInstance instance in viewport.CompositorInstances )
            //      instance.DoRealEnabledUpdate( false );
            //}

            this.size = size;

            //!!!!по идее не во всех графических API надо пересоздавать
            if (thisIsApplicationWindow)
            {
                Bgfx.Reset(size.X, size.Y, RenderingSystem.GetApplicationWindowResetFlags());
            }
            else
            {
                frameBuffer.Dispose();
                frameBuffer = new FrameBuffer(windowHandle, size.X, size.Y);
            }

            //unsafe
            //{
            //	OgreRenderWindow.windowMovedOrResized( realObjectRenderWindow, fullScreen );//, windowSize.X, windowSize.Y );
            //}
            //GetSizeFromNative();

            //update aspect ratio
            foreach (Viewport viewport in viewports)
            {
                viewport.UpdateAspectRatio();
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            FrameBuffer buffer = new FrameBuffer(Console.WindowWidth, Console.WindowHeight)
            {
                FrameLimit = 60
            };

            FrameBufferGraphics graphics = new FrameBufferGraphics(buffer);

            buffer.Run();

            UIExtension ext      = new UIExtension(buffer);
            ImageBox    imageBox = new ImageBox()
            {
                Image  = Image.Load <Rgb24>(@"C:\Users\wamwo\Downloads\congaparrot.gif"),
                Width  = 32,
                Height = 32
            };

            ext.Controls.Add(imageBox);
            ImageBox imageBox2 = new ImageBox()
            {
                Image  = Image.Load <Rgb24>(@"C:\Users\wamwo\Downloads\congaparrot.gif"),
                Width  = 32,
                Height = 32,
                X      = 32
            };

            ext.Controls.Add(imageBox2);
            ImageBox imageBox3 = new ImageBox()
            {
                Image  = Image.Load <Rgb24>(@"C:\Users\wamwo\Downloads\congaparrot.gif"),
                Width  = 32,
                Height = 32,
                X      = 64
            };

            ext.Controls.Add(imageBox3);
            ImageBox imageBox4 = new ImageBox()
            {
                Image  = Image.Load <Rgb24>(@"C:\Users\wamwo\Downloads\congaparrot.gif"),
                Width  = 32,
                Height = 32,
                X      = 96
            };

            ext.Controls.Add(imageBox4);
            buffer.AddDrawExtension(ext);
        }
Exemplo n.º 24
0
        public void render(fx_Quad quad, fx_Special special, Texture depth_texture, FrameBuffer scene_fbo, Texture scene_texture)
        {
            autoFocus(depth_texture);

            //printFocusDistance();
            genCOC(quad, special, depth_texture);

            resetBokeh();
            extractBokeh(quad, depth_texture, scene_texture);
            //printBokehCount();
            genBokeh(depth_texture);

            genDOF(quad, depth_texture);
            blendDOF(quad, special, scene_fbo, scene_texture);
        }
Exemplo n.º 25
0
		public void init() {
			//Model.getDefaultShaderProgram();	//Initializes the default shader
			
			this.graphicsContext.Enable(EnableMode.DepthTest, true);
			//this.graphicsContext.Enable(EnableMode.CullFace, true);
			this.graphicsContext.Enable(EnableMode.Blend, true);
			//this.graphicsContext.Enable(EnableMode.ScissorTest, true);
			//his.graphicsContext.Enable(EnableMode.Dither, true);
			//this.graphicsContext.Enable(EnableMode.StencilTest, true);
			
        	this.graphicsContext.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha);
			this.graphicsContext.SetCullFace(CullFaceMode.Back, CullFaceDirection.Ccw);
			
			this.mainFrameBuffer = this.graphicsContext.GetFrameBuffer();
		}
Exemplo n.º 26
0
        public void blur_Gauss(
            fx_Quad quad,
            int blur_amount, float blur_angle,
            Texture texture_to_blur, FrameBuffer texture_frame_buffer, DrawBuffersEnum attachement,
            float destination_scale = 1)
        {
            Vector2 angle_mod = EngineHelper.createRotationVector(blur_angle);

            blur_Gauss(
                quad,
                blur_amount,
                angle_mod, angle_mod,
                texture_to_blur, texture_frame_buffer, attachement,
                destination_scale);
        }
Exemplo n.º 27
0
        protected override void load_Buffers()
        {
            _tFinalScene = new Texture(TextureTarget.Texture2D,
                                       _resolution.W, _resolution.H,
                                       0, false, false,
                                       PixelInternalFormat.Rgba16f, PixelFormat.Rgba, PixelType.Float,
                                       TextureMinFilter.Linear, TextureMagFilter.Linear, TextureWrapMode.Clamp);
            _tFinalScene.load();

            _fFinalScene = new FrameBuffer("Final Scene");
            _fFinalScene.load(new Dictionary <FramebufferAttachment, Texture>()
            {
                { FramebufferAttachment.ColorAttachment0, _tFinalScene }
            });
        }
Exemplo n.º 28
0
    void Start()
    {
        frameBuffer = GetComponent<FrameBuffer>();
        renderTexture = frameBuffer.GetCurrentTexture();

        rect = new Rect(0f, 0f, Game.width, Game.height);
        texture2D = new Texture2D((int)Game.width, (int)Game.height);
        colorArray = new Color[(int)Game.width * (int)Game.height];

        if (collectibleList == null) {
            collectibleList = new List<Collectible>();
        }

        position = Vector2.zero;
    }
Exemplo n.º 29
0
 public int Push(ref FrameBuffer f)
 {
     m.WaitOne();
     if (data_frame.Count < 3)
     {
         data_frame.Enqueue(f);
         m.ReleaseMutex();
         return(1);
     }
     else
     {
         m.ReleaseMutex();
         return(0);
     }
 }
Exemplo n.º 30
0
        void recordDraw(PrimaryCommandBuffer cmd, FrameBuffer fb)
        {
            pipeline.RenderPass.Begin(cmd, fb);

            cmd.SetViewport(fb.Width, fb.Height);
            cmd.SetScissor(fb.Width, fb.Height);
            cmd.BindDescriptorSet(pipeline.Layout, descriptorSet);

            pipeline.Bind(cmd);

            cmd.BindVertexBuffer(vbo, 0);
            cmd.Draw(36);

            pipeline.RenderPass.End(cmd);
        }
Exemplo n.º 31
0
        public void RenderToTexture(Texture2D texture, Matrix4 transform)
        {
            if (texture == null)
            {
                throw new ArgumentNullException("texture");
            }
            if (!texture.IsRenderable)
            {
                throw new ArgumentException("Texture is not renderable.", "texture");
            }
            FrameBuffer offScreenFramebufferCache = UISystem.offScreenFramebufferCache;

            offScreenFramebufferCache.SetColorTarget(texture, 0);
            this.RenderToFrameBuffer(offScreenFramebufferCache, ref transform, true);
        }
Exemplo n.º 32
0
        /// <summary>
        /// Creates a new <see cref="BufferedDrawNodeSharedData"/> with a specific amount of effect buffers.
        /// </summary>
        /// <param name="effectBufferCount">The number of effect buffers.</param>
        /// <exception cref="ArgumentOutOfRangeException">If <paramref name="effectBufferCount"/> is less than 0.</exception>
        public BufferedDrawNodeSharedData(int effectBufferCount)
        {
            if (effectBufferCount < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(effectBufferCount), "Must be positive.");
            }

            MainBuffer    = new FrameBuffer();
            effectBuffers = new FrameBuffer[effectBufferCount];

            for (int i = 0; i < effectBufferCount; i++)
            {
                effectBuffers[i] = new FrameBuffer();
            }
        }
Exemplo n.º 33
0
        void buildCommandBuffers()
        {
            cmdPool.Reset();

            for (int i = 0; i < swapChain.ImageCount; ++i)
            {
                FrameBuffer fb = frameBuffers[i];
                cmds[i].Start();

                renderPass.Begin(cmds[i], fb);
                renderPass.End(cmds[i]);

                cmds[i].End();
            }
        }
Exemplo n.º 34
0
        public void Run(string[] args)
        {
            using (new DisplayWindowBuilder(args)
                   .BackbufferSize(800, 600)
                   .QuitOnClose()
                   .Build())
            {
                Surface someSurface = new Surface("Images/wallpaper.png");
                bool    capturing   = false;

                FrameBuffer capture = new FrameBuffer(1600, 1200);

                while (AgateApp.IsAlive)
                {
                    if (Input.Unhandled.Keys[KeyCode.C])
                    {
                        capturing = true;
                        Input.Unhandled.Keys.Release(KeyCode.C);
                    }
                    if (capturing)
                    {
                        Display.RenderTarget = capture;
                        someSurface.SetScale(2, 2);
                    }

                    Display.BeginFrame();

                    Display.Clear(Color.White);

                    someSurface.Draw();
                    Display.Primitives.FillRect(Color.Gray, new Rectangle(10, 10, 10, 10));

                    Display.EndFrame();

                    if (capturing)
                    {
                        capture.RenderTarget.SaveTo("CapturedImage.png", ImageFileFormat.Png);
                        Display.RenderTarget = Display.CurrentWindow.FrameBuffer;
                        someSurface.SetScale(1, 1);
                        capturing = false;

                        Debug.WriteLine("Captured image to CapturedImage.png");
                    }

                    AgateApp.KeepAlive();
                }
            }
        }
Exemplo n.º 35
0
        public Depth()
        {
            if(depth == null)
            {
                depth = new ShaderProgram(VFS.GetFileBytes("vfs1:/shaders/Depth.cgx"));
                depth.SetAttributeBinding(0, "a_Position");
                depth.SetUniformBinding(0, "WorldViewProj");
            }

            RenderPassTarget = new Texture2D((int)RootNode.graphicsContext.GetDisplay().Width,
                                             (int)RootNode.graphicsContext.GetDisplay().Height
                                             , false, PixelFormat.Rgba, PixelBufferOption.Renderable);
            RenderPassBuf = new FrameBuffer();
            RenderPassBuf.SetColorTarget(RenderPassTarget,0);

            DepthBuffer temp = new DepthBuffer(RenderPassTarget.Width, RenderPassTarget.Height, PixelFormat.Depth24Stencil8);
            RenderPassBuf.SetDepthTarget(temp);
        }
Exemplo n.º 36
0
        public DynamicTexture(Context context, Format format, Vector4i size)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (format == null)
                throw new ArgumentNullException("format");
            this.format = format;
            this.frameBuffer = new FrameBuffer();
            this.mainProgram = new Program();
            this.dimensions = size;

            var builder = ShaderBuilder.CreateFromAssemblyResource("Glare.Graphics.Shaders.DynamicTexture.glsl");
            mainProgram.Shaders.AddRange(
                builder.VertexShader("Common", "Vertex"),
                builder.FragmentShader("Common", "Fragment"));
            mainProgram.MustLink();
            mainProgramAction = mainProgram.FragmentStage.Uniforms["Act"];
            mainProgram.Attributes["Position"].BindArray(new Vector2f[] {
                new Vector2f(-1, 1), new Vector2f(-1, -1),
                new Vector2f(1, 1), new Vector2f(1, -1) });
        }
Exemplo n.º 37
0
 public override void ComputeNextFrame(FrameBuffer frameBuffer)
 {
     base.ComputeNextFrame(frameBuffer);
     TIA.StartFrame();
     CPU.RunClocks = (FrameBuffer.Scanlines + 3) * 76;
     while (CPU.RunClocks > 0 && !CPU.Jammed)
     {
         if (TIA.WSYNCDelayClocks > 0)
         {
             CPU.Clock += (ulong)TIA.WSYNCDelayClocks / 3;
             CPU.RunClocks -= TIA.WSYNCDelayClocks / 3;
             TIA.WSYNCDelayClocks = 0;
         }
         if (TIA.EndOfFrame)
         {
             break;
         }
         CPU.Execute();
     }
     TIA.EndFrame();
 }
Exemplo n.º 38
0
        public Video(DisposableI parent, ApplicationI application, DepthStencilFormats depthStencilFormats, bool vSync)
            : base(parent)
        {
            try
            {
                this.application = application;
                FileTag = "Vita_";
                currentPixelTextures = new Texture2D[4];
                currentSamplerStates = new SamplerState[4];

                PixelFormat format = PixelFormat.None;
                switch (depthStencilFormats)
                {
                    case DepthStencilFormats.None: format = PixelFormat.None; break;
                    case DepthStencilFormats.Defualt: format = PixelFormat.Depth16; break;
                    case DepthStencilFormats.Depth24Stencil8: format = PixelFormat.Depth24Stencil8; break;
                    case DepthStencilFormats.Depth16: format = PixelFormat.Depth16; break;
                    case DepthStencilFormats.Depth24: format = PixelFormat.Depth24; break;

                    default:
                        Debug.ThrowError("Video", "Unsuported DepthStencilFormat type");
                        break;
                }

                context = new GraphicsContext(0, 0, PixelFormat.Rgba, format, MultiSampleMode.None);
                currentFrameBuffer = context.Screen;
                BackBufferSize = new Size2(currentFrameBuffer.Width, currentFrameBuffer.Height);
                ((VitaApplication)application).Vita_SetFrameSize(currentFrameBuffer.Width, currentFrameBuffer.Height);

                currentEnableMode = EnableMode.None;
                context.Enable(currentEnableMode);
            }
            catch (Exception e)
            {
                Dispose();
                throw e;
            }
        }
Exemplo n.º 39
0
 public abstract void CopyContentsToMemory(PixelBox pb, FrameBuffer buffer);
 public void ClearFrameBuffer(FrameBuffer buffers, ColorEx color)
 {
     ClearFrameBuffer(buffers, color, 1.0f, 0);
 }
 public void ClearFrameBuffer(FrameBuffer buffers)
 {
     ClearFrameBuffer(buffers, ColorEx.Black, 1.0f, 0);
 }
Exemplo n.º 42
0
		/// <summary>
		/// Error throwing implementation, it's not possible to copy a MultiRenderTarget.
		/// </summary>
		/// <param name="pb"></param>	
		/// <param name="buffer"></param>
		public override void CopyContentsToMemory( PixelBox pb, FrameBuffer buffer )
		{
			throw new NotSupportedException( "It's not possible to copy a MultiRenderTarget." );
		}
 public void ClearFrameBuffer(FrameBuffer buffers, ColorEx color, float depth)
 {
     ClearFrameBuffer(buffers, color, depth, 0);
 }
Exemplo n.º 44
0
        /// <summary></summary>
        public TransitionFadeBase( Scene next_scene )
            : base(next_scene)
        {
            Vector2i size = new Vector2i( Director.Instance.GL.Context.GetViewport().Width,
                                         Director.Instance.GL.Context.GetViewport().Height );

            if ( !m_graphics_resources_init )
            {
                m_previous_scene_render = new TextureInfo( new Texture2D( size.X, size.Y, false, PixelFormat.Rgba, PixelBufferOption.Renderable ) );
                m_next_scene_render = new TextureInfo( new Texture2D( size.X, size.Y, false, PixelFormat.Rgba, PixelBufferOption.Renderable ) );

                m_fbuf1 = new FrameBuffer();
                m_fbuf2 = new FrameBuffer();

                m_fbuf1.SetColorTarget( m_previous_scene_render.Texture, 0 );
                m_fbuf2.SetColorTarget( m_next_scene_render.Texture, 0 );

                m_graphics_resources_init = true;
            }
            else
            {
                Common.Assert( m_previous_scene_render.TextureSizei == size );
                Common.Assert( m_next_scene_render.TextureSizei == size );
            }
        }
Exemplo n.º 45
0
    /**
    * Assign the review state to sync gui/input states to
    */
    private void SetReviewState(ReviewState state)
    {
        switch(state)
        {
            case ReviewState.None:
                m_recordButton.setControlIsEnabled(true);
                m_pauseButton.setControlIsEnabled(false);
                if(m_group.Buffer != null && m_group.Buffer.CurrentTime > 0)
                {
                    m_playButton.setControlIsEnabled(true);
                }
                else
                    m_playButton.setControlIsEnabled(false);

                m_group.UpdateAction = UpdateAction.None;
            break;

            case ReviewState.Recording:
                m_recordButton.setControlIsEnabled(true);
                m_playButton.setControlIsEnabled(false);
                m_pauseButton.setControlIsEnabled(false);

                if(m_reviewState == ReviewState.ReplayPaused)
                {
                    // regenerate
                    FrameBuffer regenBuffer = new FrameBuffer();
                    m_group.Buffer.CopyFramesTo(regenBuffer);
                    m_group.Buffer = regenBuffer;

                    // make sure the replay timeline is cleared
                    m_replayTimeline.setProgressValue(0);
                }
                else
                {
                    // create a new buffer
                    m_group.Buffer = new FrameBuffer();
                }

                m_group.UpdateAction = UpdateAction.Record;
            break;

            case ReviewState.Replaying:
                m_recordButton.setControlIsEnabled(false);
                m_playButton.setControlIsEnabled(false);
                m_pauseButton.setControlIsEnabled(true);

                // reset the read/write position in the frame buffer if we're initiating a replay
                if(m_reviewState == ReviewState.None)
                    //m_group.Buffer.Seek(0);

                m_group.UpdateAction = UpdateAction.Replay;
            break;

            case ReviewState.ReplayPaused:
                m_recordButton.setControlIsEnabled(true);
                m_playButton.setControlIsEnabled(true);
                m_pauseButton.setControlIsEnabled(false);

                m_group.UpdateAction = UpdateAction.None;
            break;
        }

        m_reviewState = state;
    }
Exemplo n.º 46
0
 /// <summary>
 ///		Determines whether to clear the viewport before rendering.
 /// </summary>
 ///<remarks>
 ///    You can use this method to set which buffers are cleared
 ///    (if any) before rendering every frame.
 ///</remarks>
 ///<param name="clear">Whether or not to clear any buffers</param>
 ///<param name="buffers">One or more values from FrameBuffer denoting
 ///    which buffers to clear, if clear is set to true. Note you should
 ///    not clear the stencil buffer here unless you know what you're doing.
 ///</param>
 public void SetClearEveryFrame(bool clear, FrameBuffer buffers)
 {
     clearEveryFrame = clear;
     clearBuffers = buffers;
 }
        ///<summary>
        ///    Compile this Composition chain into a series of RenderTarget operations.
        ///</summary>
        protected void Compile()
        {
            ClearCompiledState();

            bool compositorsEnabled = false;

            /// Set previous CompositorInstance for each compositor in the list
            CompositorInstance lastComposition = originalScene;
            originalScene.PreviousInstance = null;
            CompositionPass pass = originalScene.Technique.OutputTarget.GetPass(0);
            pass.ClearBuffers = viewport.ClearBuffers;
            pass.ClearColor = viewport.BackgroundColor;
            foreach (CompositorInstance instance in instances) {
                if (instance.Enabled) {
                    compositorsEnabled = true;
                    instance.PreviousInstance = lastComposition;
                    lastComposition = instance;
                }
            }

            /// Compile misc targets
            lastComposition.CompileTargetOperations(compiledState);

            /// Final target viewport (0)
            outputOperation.RenderSystemOperations.Clear();
            lastComposition.CompileOutputOperation(outputOperation);

            // Deal with viewport settings
            if (compositorsEnabled != anyCompositorsEnabled) {
                anyCompositorsEnabled = compositorsEnabled;
                if (anyCompositorsEnabled) {
                    // Save old viewport clearing options
                    oldClearEveryFrameBuffers = viewport.ClearBuffers;
                    // Don't clear anything every frame since we have our own clear ops
                    viewport.SetClearEveryFrame(false);
                } else {
                    // Reset clearing options
                    viewport.SetClearEveryFrame(oldClearEveryFrameBuffers > 0,
                                                oldClearEveryFrameBuffers);
                }
            }
            dirty = false;
        }
 public RSClearOperation(FrameBuffer buffers, ColorEx color, float depth, int stencil)
 {
     this.buffers = buffers;
     this.color = color;
     this.depth = depth;
     this.stencil = stencil;
 }
Exemplo n.º 49
0
		public override void CopyContentsToMemory( PixelBox dst, FrameBuffer buffer )
		{
			if ( ( dst.Left < 0 ) || ( dst.Right > Width ) ||
				( dst.Top < 0 ) || ( dst.Bottom > Height ) ||
				( dst.Front != 0 ) || ( dst.Back != 1 ) )
			{
				throw new Exception( "Invalid box." );
			}

			XFG.GraphicsDevice device = Driver.XnaDevice;
            //in 3.1, this was XFG.ResolveTexture2D, an actual RenderTarget provides the exact same
            //functionality, especially seeing as RenderTarget2D is a texture now.
            //the difference is surface is actually set on the device -DoubleA
			XFG.RenderTarget2D surface;
			byte[] data = new byte[ dst.ConsecutiveSize ];
			int pitch = 0;

			if ( buffer == RenderTarget.FrameBuffer.Auto )
			{
				buffer = RenderTarget.FrameBuffer.Front;
			}

			XFG.DisplayMode mode = device.DisplayMode;
            surface = new XFG.RenderTarget2D(device, mode.Width, mode.Height, false, XFG.SurfaceFormat.Rgba64, XFG.DepthFormat.Depth24Stencil8); //XFG.ResolveTexture2D( device, mode.Width, mode.Height, 0, XFG.SurfaceFormat.Rgba32 );

			if ( buffer == RenderTarget.FrameBuffer.Front )
			{
				// get the entire front buffer.  This is SLOW!!
                device.SetRenderTarget(surface); 

				if ( IsFullScreen )
				{
					if ( ( dst.Left == 0 ) && ( dst.Right == Width ) && ( dst.Top == 0 ) && ( dst.Bottom == Height ) )
					{
						surface.GetData<byte>( data );
					}
					else
					{
						Rectangle rect = new Rectangle();
						rect.Left = dst.Left;
						rect.Right = dst.Right;
						rect.Top = dst.Top;
						rect.Bottom = dst.Bottom;

						surface.GetData<byte>( 0, XnaHelper.ToRectangle( rect ), data, 0, 255 );
					}
				}
#if !( XBOX || XBOX360 )
				else
				{
					Rectangle srcRect = new Rectangle();
					srcRect.Left = dst.Left;
					srcRect.Right = dst.Right;
					srcRect.Top = dst.Top;
					srcRect.Bottom = dst.Bottom;
					// Adjust Rectangle for Window Menu and Chrome
					System.Drawing.Point point = new System.Drawing.Point();
					point.X = (int)srcRect.Left;
					point.Y = (int)srcRect.Top;
					SWF.Control control = SWF.Control.FromHandle( _windowHandle );
					point = control.PointToScreen( point );
					srcRect.Top = point.Y;
					srcRect.Left = point.X;
					srcRect.Bottom += point.Y;
					srcRect.Right += point.X;

					surface.GetData<byte>( 0, XnaHelper.ToRectangle( srcRect ), data, 0, 255 );
				}
#endif
			}
			else
			{
				device.SetRenderTarget( surface );

				if ( ( dst.Left == 0 ) && ( dst.Right == Width ) && ( dst.Top == 0 ) && ( dst.Bottom == Height ) )
				{
					surface.GetData<byte>( data );
				}
				else
				{
					Rectangle rect = new Rectangle();
					rect.Left = dst.Left;
					rect.Right = dst.Right;
					rect.Top = dst.Top;
					rect.Bottom = dst.Bottom;

					surface.GetData<byte>( 0, XnaHelper.ToRectangle( rect ), data, 0, 255 );
				}
			}

			PixelFormat format = XnaHelper.Convert( surface.Format );

			if ( format == PixelFormat.Unknown )
			{
				throw new Exception( "Unsupported format" );
			}

			IntPtr dataPtr = Memory.PinObject( data );
			PixelBox src = new PixelBox( dst.Width, dst.Height, 1, format, dataPtr );
			src.RowPitch = pitch / PixelUtil.GetNumElemBytes( format );
			src.SlicePitch = surface.Height * src.RowPitch;

			PixelConverter.BulkPixelConversion( src, dst );

			Memory.UnpinObject( data );
			surface.Dispose();
		}
Exemplo n.º 50
0
        public override void ComputeNextFrame(FrameBuffer frameBuffer)
        {
            base.ComputeNextFrame(frameBuffer);

            AssertDebug(CPU.Jammed || CPU.RunClocks <= 0 && (CPU.RunClocks % CPU.RunClocksMultiple) == 0);
            AssertDebug(CPU.Jammed || ((CPU.Clock + (ulong)(CPU.RunClocks / CPU.RunClocksMultiple)) % (114 * (ulong)FrameBuffer.Scanlines)) == 0);

            ulong startOfScanlineCpuClock = 0;

            Maria.StartFrame();
            Cart.StartFrame();
            for (var i = 0; i < FrameBuffer.Scanlines && !CPU.Jammed; i++)
            {
                AssertDebug(CPU.RunClocks <= 0 && (CPU.RunClocks % CPU.RunClocksMultiple) == 0);
                var newStartOfScanlineCpuClock = CPU.Clock + (ulong)(CPU.RunClocks / CPU.RunClocksMultiple);

                AssertDebug(startOfScanlineCpuClock == 0 || newStartOfScanlineCpuClock == startOfScanlineCpuClock + 114);
                startOfScanlineCpuClock = newStartOfScanlineCpuClock;

                CPU.RunClocks += (7 * CPU.RunClocksMultiple);
                var remainingRunClocks = (114 - 7) * CPU.RunClocksMultiple;

                CPU.Execute();
                if (CPU.Jammed)
                    break;
                if (CPU.EmulatorPreemptRequest)
                {
                    Maria.DoDMAProcessing();
                    var remainingCpuClocks = 114 - (CPU.Clock - startOfScanlineCpuClock);
                    CPU.Clock += remainingCpuClocks;
                    CPU.RunClocks = 0;
                    continue;
                }

                var dmaClocks = Maria.DoDMAProcessing();

                // CHEAT: Ace of Aces: Title screen has a single scanline flicker without this. Maria DMA clock counting probably not 100% accurate.
                if (i == 203 && FrameBuffer.Scanlines == 262 /*NTSC*/ || i == 228 && FrameBuffer.Scanlines == 312 /*PAL*/)
                    if (dmaClocks == 152 && remainingRunClocks == 428 && (CPU.RunClocks == -4 || CPU.RunClocks == -8))
                        dmaClocks -= 4;

                // Unsure exactly what to do if Maria DMA processing extends past the current scanline.
                // For now, throw away half remaining until we are within the current scanline.
                // KLAX initialization starts DMA without initializing the DLL data structure.
                // Maria processing then runs away causing an invalid CPU opcode to be executed that jams the machine.
                // So Maria must give up at some point, but not clear exactly how.
                // Anyway, this makes KLAX work without causing breakage elsewhere.
                while ((CPU.RunClocks + remainingRunClocks) < dmaClocks)
                {
                    dmaClocks >>= 1;
                }

                // Assume the CPU waits until the next div4 boundary to proceed after DMA processing.
                if ((dmaClocks & 3) != 0)
                {
                    dmaClocks += 4;
                    dmaClocks -= (dmaClocks & 3);
                }

                CPU.Clock += (ulong)(dmaClocks / CPU.RunClocksMultiple);
                CPU.RunClocks -= dmaClocks;

                CPU.RunClocks += remainingRunClocks;

                CPU.Execute();
                if (CPU.Jammed)
                    break;
                if (CPU.EmulatorPreemptRequest)
                {
                    var remainingCpuClocks = 114 - (CPU.Clock - startOfScanlineCpuClock);
                    CPU.Clock += remainingCpuClocks;
                    CPU.RunClocks = 0;
                }
            }
            Cart.EndFrame();
            Maria.EndFrame();
        }
 public CompositionPass(CompositionTargetPass parent)
 {
     this.parent = parent;
     type = CompositorPassType.RenderQuad;
     identifier = 0;
     firstRenderQueue = RenderQueueGroupID.SkiesEarly;
     lastRenderQueue = RenderQueueGroupID.SkiesLate;
     clearBuffers = FrameBuffer.Color | FrameBuffer.Depth;
     clearColor = new ColorEx(0f, 0f, 0f, 0f);
     clearDepth = 1.0f;
     clearStencil = 0;
     stencilCheck = false;
     stencilFunc = CompareFunction.AlwaysPass;
     stencilRefValue = 0;
     stencilMask = (int)0x7FFFFFFF;
     stencilFailOp = StencilOperation.Keep;
     stencilDepthFailOp = StencilOperation.Keep;
     stencilPassOp = StencilOperation.Keep;
     stencilTwoSidedOperation = false;
 }
Exemplo n.º 52
0
 public void EnableRenderTarget()
 {
     currentFrameBuffer = context.Screen;
     context.SetFrameBuffer(currentFrameBuffer);
 }
Exemplo n.º 53
0
        public RenderTarget2D (GraphicsDevice graphicsDevice, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared)
			:base (graphicsDevice, width, height, mipMap, preferredFormat, SurfaceType.RenderTarget, shared)
		{
			DepthStencilFormat = preferredDepthFormat;
			MultiSampleCount = preferredMultiSampleCount;
			RenderTargetUsage = usage;

#if DIRECTX
            // Create a view interface on the rendertarget to use on bind.
            _renderTargetView = new RenderTargetView(graphicsDevice._d3dDevice, _texture);
#elif PSM
            _frameBuffer = new FrameBuffer();     
            _frameBuffer.SetColorTarget(_texture2D,0);
#endif

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

#if DIRECTX

            // Setup the multisampling description.
            var multisampleDesc = new SharpDX.DXGI.SampleDescription(1, 0);
            if ( preferredMultiSampleCount > 1 )
            {
                multisampleDesc.Count = preferredMultiSampleCount;
                multisampleDesc.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, new Texture2DDescription
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = width,
                Height = height,
                SampleDescription = multisampleDesc,
                BindFlags = BindFlags.DepthStencil,
            }))
            {
            // Create the view for binding to the device.
                _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer,
                    new DepthStencilViewDescription()
                { 
                    Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                        Dimension = DepthStencilViewDimension.Texture2D
                });
            }
#elif PSM
            throw new NotImplementedException();
#elif OPENGL

#if GLES
			GL.GenRenderbuffers(1, ref glDepthStencilBuffer);
#else
			GL.GenRenderbuffers(1, out glDepthStencilBuffer);
#endif
            GraphicsExtensions.CheckGLError();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, this.glDepthStencilBuffer);
            GraphicsExtensions.CheckGLError();
            var glDepthStencilFormat = GLDepthComponent16;
			switch (preferredDepthFormat)
			{
			case DepthFormat.Depth16: glDepthStencilFormat = GLDepthComponent16; break;
			case DepthFormat.Depth24: glDepthStencilFormat = GLDepthComponent24; break;
			case DepthFormat.Depth24Stencil8: glDepthStencilFormat = GLDepth24Stencil8; break;
			}
			GL.RenderbufferStorage(GLRenderbuffer, glDepthStencilFormat, this.width, this.height);
            GraphicsExtensions.CheckGLError();
#endif
        }
Exemplo n.º 54
0
 public void EnableRenderTarget(DepthStencilI depthStencil)
 {
     currentFrameBuffer = context.Screen;
     ((DepthStencil)depthStencil).enable();
     context.SetFrameBuffer(currentFrameBuffer);
 }
Exemplo n.º 55
0
        /// <summary>
        ///		The constructor. Dimensions of the viewport are expressed as a pecentage between
        ///		0 and 100. This allows the dimensions to apply irrespective of
        ///		changes in the target's size: e.g. to fill the whole area,
        ///		values of 0,0,100,100 are appropriate.
        /// </summary>
        /// <param name="camera">Reference to the camera to be the source for the image.</param>
        /// <param name="target">Reference to the render target to be the destination for the rendering.</param>
        /// <param name="left">Left</param>
        /// <param name="top">Top</param>
        /// <param name="width">Width</param>
        /// <param name="height">Height</param>
        /// <param name="zOrder">Relative Z-order on the target. Lower = further to the front.</param>
        public Viewport(Camera camera, RenderTarget target, float left, float top, float width, float height, int zOrder)
        {
            Debug.Assert(camera != null, "Cannot use a null Camera to create a viewport.");
            Debug.Assert(target != null, "Cannor use a null RenderTarget to create a viewport.");

            LogManager.Instance.Write("Creating viewport rendering from camera '{0}', relative dimensions L:{1},T:{2},W:{3},H:{4}, Z-Order:{5}",
                camera.Name, left, top, width, height, zOrder);

            this.camera = camera;
            this.target = target;
            this.zOrder = zOrder;

            relativeLeft = left;
            relativeTop = top;
            relativeWidth = width;
            relativeHeight = height;

            backColor = ColorEx.Black;
            clearEveryFrame = true;
            clearBuffers = FrameBuffer.Color | FrameBuffer.Depth;

            // Calculate actual dimensions
            UpdateDimensions();

            isUpdated = true;
            showOverlays = true;
            showSkies = true;
            showShadows = true;

            materialSchemeName = MaterialManager.DefaultSchemeName;

            // notify camera
            camera.NotifyViewport(this);
        }
Exemplo n.º 56
0
		public override void CopyContentsToMemory( PixelBox dst, FrameBuffer buffer )
		{
			this._device.CopyContentsToMemory( this, dst, buffer );
		}
Exemplo n.º 57
0
 public void SetClearEveryFrame(bool clear)
 {
     clearEveryFrame = clear;
     clearBuffers = FrameBuffer.Color | FrameBuffer.Depth;
 }
Exemplo n.º 58
0
 public Terrain()
 {
     this.frameBuffer = new FrameBuffer();
 }
Exemplo n.º 59
0
        public RenderTarget2D (GraphicsDevice graphicsDevice, int width, int height, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage, bool shared)
			:base (graphicsDevice, width, height, mipMap, preferredFormat, SurfaceType.RenderTarget, shared)
		{
			DepthStencilFormat = preferredDepthFormat;
			MultiSampleCount = preferredMultiSampleCount;
			RenderTargetUsage = usage;

#if DIRECTX

            GenerateIfRequired();

#elif PSM
            _frameBuffer = new FrameBuffer();     
            _frameBuffer.SetColorTarget(_texture2D,0);
#endif

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

#if DIRECTX
#elif PSM
            throw new NotImplementedException();
#elif OPENGL
      
      
			var glDepthFormat = GLDepthComponent16;
			var glStencilFormat = GLStencilIndex8;
			switch (preferredDepthFormat)
			{
				case DepthFormat.Depth16: 
					glDepthFormat = GLDepthComponent16; 
				break;
#if GLES
				case DepthFormat.Depth24: 
					glDepthFormat = GraphicsCapabilities.SupportsDepth24 ? GLDepthComponent24 : GraphicsCapabilities.SupportsDepthNonLinear ? GLDepthComponent16NonLinear : GLDepthComponent16; 
				break;
				case DepthFormat.Depth24Stencil8:
					glDepthFormat = GraphicsCapabilities.SupportsDepth24 ? GLDepthComponent24 : GraphicsCapabilities.SupportsDepthNonLinear ? GLDepthComponent16NonLinear : GLDepthComponent16;
					glStencilFormat = GLStencilIndex8; 
				break;
#else
				case DepthFormat.Depth24: 
				  	glDepthFormat = GLDepthComponent24;
				break;
				case DepthFormat.Depth24Stencil8:
					glDepthFormat = GLDepthComponent24;
					glStencilFormat = GLStencilIndex8; 
				break;
#endif
			}

            Threading.BlockOnUIThread(() =>
            {

#if GLES
			GL.GenRenderbuffers(1, ref glDepthBuffer);
#else
			GL.GenRenderbuffers(1, out glDepthBuffer);
#endif
			GraphicsExtensions.CheckGLError();
			if (preferredDepthFormat == DepthFormat.Depth24Stencil8)
			{
				if (GraphicsCapabilities.SupportsPackedDepthStencil)
				{
					  this.glStencilBuffer = this.glDepthBuffer;
					  GL.BindRenderbuffer(GLRenderbuffer, this.glDepthBuffer);
					  GraphicsExtensions.CheckGLError();
					  GL.RenderbufferStorage(GLRenderbuffer, GLDepth24Stencil8, this.width, this.height);
					  GraphicsExtensions.CheckGLError();
				}
				else
				{
					GL.BindRenderbuffer(GLRenderbuffer, this.glDepthBuffer);
					GraphicsExtensions.CheckGLError();
					GL.RenderbufferStorage(GLRenderbuffer, glDepthFormat, this.width, this.height);
					GraphicsExtensions.CheckGLError();
#if GLES
					GL.GenRenderbuffers(1, ref glStencilBuffer);
#else
					GL.GenRenderbuffers(1, out glStencilBuffer);
#endif
					GraphicsExtensions.CheckGLError();
					GL.BindRenderbuffer(GLRenderbuffer, this.glStencilBuffer);
					GraphicsExtensions.CheckGLError();
					GL.RenderbufferStorage(GLRenderbuffer, glStencilFormat, this.width, this.height);
					GraphicsExtensions.CheckGLError();
				}
			}
			else
			{
				GL.BindRenderbuffer(GLRenderbuffer, this.glDepthBuffer);
				GraphicsExtensions.CheckGLError();
				GL.RenderbufferStorage(GLRenderbuffer, glDepthFormat, this.width, this.height);
				GraphicsExtensions.CheckGLError();
			}

            });
#endif

        }
 public CompositorChain(Viewport vp)
 {
     this.viewport = vp;
     originalScene = null;
     instances = new List<CompositorInstance>();
     dirty = true;
     anyCompositorsEnabled = false;
     compiledState = new List<CompositorTargetOperation>();
     outputOperation = null;
     oldClearEveryFrameBuffers = viewport.ClearBuffers;
     renderSystemOperations = new List<CompositorRenderSystemOperation>();
     listener = new RQListener();
     Debug.Assert(viewport != null);
 }