コード例 #1
0
        /// <summary>
        /// Uploads the specified data block into this buffer, replacing all previous contents.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="buffer"></param>
        /// <param name="data">An array containing the data that will be uploaded.</param>
        /// <param name="index">The array starting index from which to start uploading data.</param>
        /// <param name="count">The number of elements from the array that should be uploaded.</param>
        public static void LoadData <T>(this INativeGraphicsBuffer buffer, T[] data, int index, int count) where T : struct
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index", "Index cannot be negative");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count", "Count cannot be negative");
            }
            if (index + count > data.Length)
            {
                throw new ArgumentOutOfRangeException("count", "Index + Count cannot exceed the specified arrays length.");
            }

            int itemSize = Marshal.SizeOf(typeof(T));

            using (PinnedArrayHandle pinned = new PinnedArrayHandle(data))
            {
                IntPtr dataAddress = IntPtr.Add(pinned.Address, index * itemSize);
                buffer.LoadData(
                    dataAddress,
                    count * itemSize);
            }
        }
コード例 #2
0
        public static void LoadData <T>(
            this INativeAudioBuffer buffer,
            int sampleRate,
            T[] data,
            int dataLength,
            AudioDataLayout dataLayout,
            AudioDataElementType dataElementType) where T : struct
        {
            if (dataLength < 0)
            {
                throw new ArgumentOutOfRangeException("dataLength", "Data length cannot be negative");
            }
            if (dataLength > data.Length)
            {
                throw new ArgumentOutOfRangeException("dataLength", "Data length cannot exceed the specified arrays length.");
            }

            int itemSize = Marshal.SizeOf(typeof(T));

            using (PinnedArrayHandle pinned = new PinnedArrayHandle(data))
            {
                buffer.LoadData(
                    sampleRate,
                    pinned.Address,
                    itemSize * dataLength,
                    dataLayout,
                    dataElementType);
            }
        }
コード例 #3
0
 /// <summary>
 /// Retrieves the textures pixel data from video memory in the Rgba8 format.
 /// As a storage array type, either byte or <see cref="ColorRgba"/> is recommended.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="texture"></param>
 /// <param name="target">The buffer to store pixel values into.</param>
 /// <param name="dataLayout">The desired color layout of the specified buffer.</param>
 /// <param name="dataElementType">The desired color element type of the specified buffer.</param>
 public static void GetData <T>(
     this INativeTexture texture,
     T[] target,
     ColorDataLayout dataLayout,
     ColorDataElementType dataElementType)
 {
     using (PinnedArrayHandle pinned = new PinnedArrayHandle(target))
     {
         texture.GetData(
             pinned.Address,
             dataLayout,
             dataElementType);
     }
 }
コード例 #4
0
        [Test] public void Locking()
        {
            VertexBatch <VertexC1P3> typedBatch    = new VertexBatch <VertexC1P3>();
            IVertexBatch             abstractBatch = typedBatch;

            typedBatch.Vertices.Add(new VertexC1P3 {
                Color = new ColorRgba(0)
            });
            typedBatch.Vertices.Add(new VertexC1P3 {
                Color = new ColorRgba(1)
            });
            typedBatch.Vertices.Add(new VertexC1P3 {
                Color = new ColorRgba(2)
            });
            typedBatch.Vertices.Add(new VertexC1P3 {
                Color = new ColorRgba(3)
            });

            // Assert that we can retrieve all data via unmanaged pointer access
            VertexDeclaration layout = typedBatch.Declaration;
            int vertexSize           = layout.Size;
            int colorElementIndex    = layout.Elements.IndexOfFirst(item => item.FieldName == VertexDeclaration.ShaderFieldPrefix + "Color");
            int colorOffset          = (int)layout.Elements[colorElementIndex].Offset;

            using (PinnedArrayHandle locked = typedBatch.Lock())
            {
                Assert.AreEqual(new ColorRgba(0), ReadColor(locked.Address, vertexSize * 0 + colorOffset));
                Assert.AreEqual(new ColorRgba(1), ReadColor(locked.Address, vertexSize * 1 + colorOffset));
                Assert.AreEqual(new ColorRgba(2), ReadColor(locked.Address, vertexSize * 2 + colorOffset));
                Assert.AreEqual(new ColorRgba(3), ReadColor(locked.Address, vertexSize * 3 + colorOffset));
            }
            using (PinnedArrayHandle locked = abstractBatch.Lock())
            {
                Assert.AreEqual(new ColorRgba(0), ReadColor(locked.Address, vertexSize * 0 + colorOffset));
                Assert.AreEqual(new ColorRgba(1), ReadColor(locked.Address, vertexSize * 1 + colorOffset));
                Assert.AreEqual(new ColorRgba(2), ReadColor(locked.Address, vertexSize * 2 + colorOffset));
                Assert.AreEqual(new ColorRgba(3), ReadColor(locked.Address, vertexSize * 3 + colorOffset));
            }

            // Make sure that our locks released properly, i.e. allowing the array to be garbage collected
            WeakReference weakRefToLockedData = new WeakReference(typedBatch.Vertices.Data);

            Assert.IsTrue(weakRefToLockedData.IsAlive);
            typedBatch    = null;
            abstractBatch = null;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
            GC.WaitForPendingFinalizers();
            Assert.IsFalse(weakRefToLockedData.IsAlive);
        }
コード例 #5
0
        /// <summary>
        /// Uploads all dynamically gathered vertex data to the GPU using the internal <see cref="vertexBuffers"/> pool.
        /// </summary>
        private void UploadVertexData()
        {
            // Note that there is a 1:1 mapping between gathered vertex batches and vertex buffers.
            // We'll keep all buffers around until the drawdevice is disposed, in case we might need
            // them again later.
            this.vertexBuffers.Count = Math.Max(this.vertexBuffers.Count, this.drawVertices.TypeIndexCount);
            for (int typeIndex = 0; typeIndex < this.drawVertices.TypeIndexCount; typeIndex++)
            {
                // Filter out unused vertex types
                IReadOnlyList <IVertexBatch> batches = this.drawVertices.GetBatches(typeIndex);
                if (batches == null)
                {
                    continue;
                }
                if (batches.Count == 0)
                {
                    continue;
                }

                // Upload all vertex batches for this vertex type
                if (this.vertexBuffers[typeIndex] == null)
                {
                    this.vertexBuffers[typeIndex] = new RawList <VertexBuffer>();
                }
                this.vertexBuffers[typeIndex].Count = Math.Max(this.vertexBuffers[typeIndex].Count, batches.Count);
                for (int batchIndex = 0; batchIndex < batches.Count; batchIndex++)
                {
                    IVertexBatch vertexBatch = batches[batchIndex];

                    // Generate a VertexBuffer for this vertex type and batch index, if it didn't exist yet
                    if (this.vertexBuffers[typeIndex][batchIndex] == null)
                    {
                        this.vertexBuffers[typeIndex][batchIndex] = new VertexBuffer();
                    }

                    // Upload the vertex batch to
                    using (PinnedArrayHandle pinned = vertexBatch.Lock())
                    {
                        this.vertexBuffers[typeIndex][batchIndex].LoadVertexData(
                            vertexBatch.Declaration,
                            pinned.Address,
                            vertexBatch.Count);
                    }
                }
            }
        }
コード例 #6
0
 /// <summary>
 /// Uploads the specified pixel data in RGBA format to video memory. A call to <see cref="INativeTexture.SetupEmpty"/>
 /// is to be considered required for this.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="texture"></param>
 /// <param name="format">The textures internal format.</param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="data">The block of pixel data to transfer.</param>
 /// <param name="dataLayout">The color layout of the specified data block.</param>
 /// <param name="dataElementType">The color element type of the specified data block.</param>
 public static void LoadData <T>(
     this INativeTexture texture,
     TexturePixelFormat format,
     int width, int height,
     T[] data,
     ColorDataLayout dataLayout,
     ColorDataElementType dataElementType) where T : struct
 {
     using (PinnedArrayHandle pinned = new PinnedArrayHandle(data))
     {
         texture.LoadData(
             format,
             width,
             height,
             pinned.Address,
             dataLayout,
             dataElementType);
     }
 }
コード例 #7
0
 /// <summary>
 /// Retrieves the main rendering buffer's pixel data from video memory in the Rgba8 format.
 /// As a storage array type, either byte or <see cref="ColorRgba"/> is recommended.
 /// </summary>
 /// <param name="target">The target buffer to store transferred pixel data in.</param>
 /// <param name="dataLayout">The desired color layout of the specified buffer.</param>
 /// <param name="dataElementType">The desired color element type of the specified buffer.</param>
 /// <param name="x">The x position of the rectangular area to read.</param>
 /// <param name="y">The y position of the rectangular area to read.</param>
 /// <param name="width">The width of the rectangular area to read. Defaults to the rendering targets width.</param>
 /// <param name="height">The height of the rectangular area to read. Defaults to the rendering targets height.</param>
 public static void GetOutputPixelData <T>(
     this IGraphicsBackend backend,
     T[] target,
     ColorDataLayout dataLayout,
     ColorDataElementType dataElementType,
     int x, int y,
     int width, int height) where T : struct
 {
     using (PinnedArrayHandle pinned = new PinnedArrayHandle(target))
     {
         backend.GetOutputPixelData(
             pinned.Address,
             dataLayout,
             dataElementType,
             x, y,
             width,
             height);
     }
 }
コード例 #8
0
 /// <summary>
 /// Retrieves the rendering targets pixel data from video memory in the Rgba8 format.
 /// As a storage array type, either byte or <see cref="ColorRgba"/> is recommended.
 /// </summary>
 /// <param name="renderTarget"></param>
 /// <param name="buffer">The target buffer to store transferred pixel data in.</param>
 /// <param name="dataLayout">The desired color layout of the specified buffer.</param>
 /// <param name="dataElementType">The desired color element type of the specified buffer.</param>
 /// <param name="targetIndex">The target texture lists index to read from.</param>
 /// <param name="x">The x position of the rectangular area to read.</param>
 /// <param name="y">The y position of the rectangular area to read.</param>
 /// <param name="width">The width of the rectangular area to read. Defaults to the rendering targets width.</param>
 /// <param name="height">The height of the rectangular area to read. Defaults to the rendering targets height.</param>
 public static void GetData <T>(
     this INativeRenderTarget renderTarget,
     T[] buffer,
     ColorDataLayout dataLayout,
     ColorDataElementType dataElementType,
     int targetIndex,
     int x, int y,
     int width, int height) where T : struct
 {
     using (PinnedArrayHandle pinned = new PinnedArrayHandle(buffer))
     {
         renderTarget.GetData(
             pinned.Address,
             dataLayout,
             dataElementType,
             targetIndex,
             x, y,
             width,
             height);
     }
 }
コード例 #9
0
ファイル: GraphicsBackend.cs プロジェクト: razluta/jazz2
        void IGraphicsBackend.BeginRendering(IDrawDevice device, VertexBatchStore vertexData, RenderOptions options, RenderStats stats)
        {
            DebugCheckOpenGLErrors();

            // ToDo: AA is disabled for now
            //this.CheckContextCaps();

            this.currentDevice = device;
            this.renderOptions = options;
            this.renderStats   = stats;

            // Upload all vertex data that we'll need during rendering
            if (vertexData != null)
            {
                this.perVertexTypeVBO.Count = Math.Max(this.perVertexTypeVBO.Count, vertexData.Batches.Count);
                for (int typeIndex = 0; typeIndex < vertexData.Batches.Count; typeIndex++)
                {
                    // Filter out unused vertex types
                    IVertexBatch vertexBatch = vertexData.Batches[typeIndex];
                    if (vertexBatch == null)
                    {
                        continue;
                    }
                    if (vertexBatch.Count == 0)
                    {
                        continue;
                    }

                    // Generate a VBO for this vertex type if it didn't exist yet
                    if (this.perVertexTypeVBO[typeIndex] == 0)
                    {
                        GL.GenBuffers(1, out this.perVertexTypeVBO.Data[typeIndex]);
                    }
                    GL.BindBuffer(BufferTarget.ArrayBuffer, this.perVertexTypeVBO[typeIndex]);

                    // Upload all data of this vertex type as a single block
                    int vertexDataLength = vertexBatch.Declaration.Size * vertexBatch.Count;
                    using (PinnedArrayHandle pinned = vertexBatch.Lock()) {
                        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, IntPtr.Zero, BufferUsage.StreamDraw);
                        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, pinned.Address, BufferUsage.StreamDraw);
                    }
                }
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            // Prepare the target surface for rendering
            NativeRenderTarget.Bind(options.Target as NativeRenderTarget);

            // Determine the available size on the active rendering surface
            //Point2 availableSize;
            //if (NativeRenderTarget.BoundRT != null) {
            //    availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height);
            //} else {
            //    availableSize = this.externalBackbufferSize;
            //}

            Rect openGLViewport = options.Viewport;

            // Setup viewport and scissor rects
            GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H));
            GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H));

            // Clear buffers
            ClearBufferMask glClearMask = 0;
            ColorRgba       clearColor  = options.ClearColor;

            if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None)
            {
                glClearMask |= ClearBufferMask.ColorBufferBit;
            }
            if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None)
            {
                glClearMask |= ClearBufferMask.DepthBufferBit;
            }
            GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f);
            GL.ClearDepth(options.ClearDepth);
            GL.Clear(glClearMask);

            // Configure Rendering params
            if (options.RenderMode == RenderMatrix.ScreenSpace)
            {
                GL.Enable(EnableCap.ScissorTest);
                GL.Enable(EnableCap.DepthTest);
                GL.DepthFunc(DepthFunction.Always);
            }
            else
            {
                GL.Enable(EnableCap.ScissorTest);
                GL.Enable(EnableCap.DepthTest);
                GL.DepthFunc(DepthFunction.Lequal);
            }

            Matrix4 modelView  = options.ModelViewMatrix;
            Matrix4 projection = options.ProjectionMatrix;

            if (NativeRenderTarget.BoundRT != null)
            {
                modelView = Matrix4.CreateScale(new Vector3(1f, -1f, 1f)) * modelView;
                if (options.RenderMode == RenderMatrix.ScreenSpace)
                {
                    modelView = Matrix4.CreateTranslation(new Vector3(0f, -device.TargetSize.Y, 0f)) * modelView;
                }
            }

            // Convert matrices to float arrays
            GetArrayMatrix(ref modelView, ref modelViewData);
            GetArrayMatrix(ref projection, ref projectionData);

            // All EBOs can be used again
            lastUsedEBO = 0;
        }
コード例 #10
0
ファイル: GraphicsBackend.cs プロジェクト: razluta/jazz2
        void IGraphicsBackend.BeginRendering(IDrawDevice device, VertexBatchStore vertexData, RenderOptions options, RenderStats stats)
        {
            DebugCheckOpenGLErrors();
            this.CheckContextCaps();

            this.currentDevice = device;
            this.renderOptions = options;
            this.renderStats   = stats;

            // Upload all vertex data that we'll need during rendering
            if (vertexData != null)
            {
                this.perVertexTypeVBO.Count = Math.Max(this.perVertexTypeVBO.Count, vertexData.Batches.Count);
                for (int typeIndex = 0; typeIndex < vertexData.Batches.Count; typeIndex++)
                {
                    // Filter out unused vertex types
                    IVertexBatch vertexBatch = vertexData.Batches[typeIndex];
                    if (vertexBatch == null)
                    {
                        continue;
                    }
                    if (vertexBatch.Count == 0)
                    {
                        continue;
                    }

                    // Generate a VBO for this vertex type if it didn't exist yet
                    if (this.perVertexTypeVBO[typeIndex] == 0)
                    {
                        GL.GenBuffers(1, out this.perVertexTypeVBO.Data[typeIndex]);
                    }
                    GL.BindBuffer(BufferTarget.ArrayBuffer, this.perVertexTypeVBO[typeIndex]);

                    // Upload all data of this vertex type as a single block
                    int vertexDataLength = vertexBatch.Declaration.Size * vertexBatch.Count;
                    using (PinnedArrayHandle pinned = vertexBatch.Lock())
                    {
                        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, IntPtr.Zero, BufferUsageHint.StreamDraw);
                        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, pinned.Address, BufferUsageHint.StreamDraw);
                    }
                }
            }
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            // Prepare the target surface for rendering
            NativeRenderTarget.Bind(options.Target as NativeRenderTarget);

            // Determine whether masked blending should use alpha-to-coverage mode
            if (this.msaaIsDriverDisabled)
            {
                this.useAlphaToCoverageBlend = false;
            }
            else if (NativeRenderTarget.BoundRT != null)
            {
                this.useAlphaToCoverageBlend = NativeRenderTarget.BoundRT.Samples > 0;
            }
            else if (this.activeWindow != null)
            {
                this.useAlphaToCoverageBlend = this.activeWindow.IsMultisampled;
            }
            else
            {
                this.useAlphaToCoverageBlend = this.defaultGraphicsMode.Samples > 0;
            }

            // Determine the available size on the active rendering surface
            Point2 availableSize;

            if (NativeRenderTarget.BoundRT != null)
            {
                availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height);
            }
            else if (this.activeWindow != null)
            {
                availableSize = new Point2(this.activeWindow.Width, this.activeWindow.Height);
            }
            else
            {
                availableSize = this.externalBackbufferSize;
            }

            // Translate viewport coordinates to OpenGL screen coordinates (bottom-left, rising), unless rendering
            // to a texture, which is laid out Duality-like (top-left, descending)
            Rect openGLViewport = options.Viewport;

            if (NativeRenderTarget.BoundRT == null)
            {
                openGLViewport.Y = (availableSize.Y - openGLViewport.H) - openGLViewport.Y;
            }

            // Setup viewport and scissor rects
            GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H));
            GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H));

            // Clear buffers
            ClearBufferMask glClearMask = 0;
            ColorRgba       clearColor  = options.ClearColor;

            if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None)
            {
                glClearMask |= ClearBufferMask.ColorBufferBit;
            }
            if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None)
            {
                glClearMask |= ClearBufferMask.DepthBufferBit;
            }
            GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f);
            GL.ClearDepth((double)options.ClearDepth);             // The "float version" is from OpenGL 4.1..
            GL.Clear(glClearMask);

            // Configure Rendering params
            if (options.RenderMode == RenderMatrix.ScreenSpace)
            {
                GL.Enable(EnableCap.ScissorTest);
                GL.Enable(EnableCap.DepthTest);
                GL.DepthFunc(DepthFunction.Always);
            }
            else
            {
                GL.Enable(EnableCap.ScissorTest);
                GL.Enable(EnableCap.DepthTest);
                GL.DepthFunc(DepthFunction.Lequal);
            }

            OpenTK.Matrix4 openTkModelView;
            Matrix4        modelView = options.ModelViewMatrix;

            GetOpenTKMatrix(ref modelView, out openTkModelView);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadMatrix(ref openTkModelView);

            OpenTK.Matrix4 openTkProjection;
            Matrix4        projection = options.ProjectionMatrix;

            GetOpenTKMatrix(ref projection, out openTkProjection);

            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref openTkProjection);

            if (NativeRenderTarget.BoundRT != null)
            {
                GL.Scale(1.0f, -1.0f, 1.0f);
                if (options.RenderMode == RenderMatrix.ScreenSpace)
                {
                    GL.Translate(0.0f, -device.TargetSize.Y, 0.0f);
                }
            }
        }