Ejemplo n.º 1
0
 internal void SetVertexAttributeArray(bool[] attrs)
 {
     for (int x = 0; x < attrs.Length; x++)
     {
         if (attrs[x] && !_enabledVertexAttributes.Contains(x))
         {
             _enabledVertexAttributes.Add(x);
             GL.EnableVertexAttribArray(x);
             GraphicsExtensions.CheckGLError();
         }
         else if (!attrs[x] && _enabledVertexAttributes.Contains(x))
         {
             _enabledVertexAttributes.Remove(x);
             GL.DisableVertexAttribArray(x);
             GraphicsExtensions.CheckGLError();
         }
     }
 }
Ejemplo n.º 2
0
 internal void SetVertexAttributeArray(bool[] attrs)
 {
     for (var x = 0; x < attrs.Length; x++)
     {
         if (attrs[x] && !_enabledVertexAttributes.ContainsKey(x))
         {
             _enabledVertexAttributes[x] = true;
             gl.enableVertexAttribArray(x);
             GraphicsExtensions.CheckGLError();
         }
         else if (!attrs[x] && _enabledVertexAttributes.ContainsKey(x))
         {
             _enabledVertexAttributes.Remove(x);
             gl.disableVertexAttribArray(x);
             GraphicsExtensions.CheckGLError();
         }
     }
 }
Ejemplo n.º 3
0
        private bool PlatformGetResult(out int pixelCount)
        {
            int resultReady = 0;

            GL.GetQueryObject(glQueryId, GetQueryObjectParam.QueryResultAvailable, out resultReady);
            GraphicsExtensions.CheckGLError();

            if (resultReady == 0)
            {
                pixelCount = 0;
                return(false);
            }

            GL.GetQueryObject(glQueryId, GetQueryObjectParam.QueryResult, out pixelCount);
            GraphicsExtensions.CheckGLError();

            return(true);
        }
Ejemplo n.º 4
0
        private void GetBufferData<T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) where T : struct
        {
            GL.BindBuffer (BufferTarget.ArrayBuffer, vbo);
            GraphicsExtensions.CheckGLError();
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            IntPtr ptr = GL.MapBuffer (BufferTarget.ArrayBuffer, BufferAccess.ReadOnly);
            GraphicsExtensions.CheckGLError();
            // Pointer to the start of data to read in the index buffer
            ptr = new IntPtr (ptr.ToInt64 () + offsetInBytes);
			if (typeof(T) == typeof(byte)) {
                byte[] buffer = data as byte[];
                // If data is already a byte[] we can skip the temporary buffer
                // Copy from the vertex buffer to the destination array
                Marshal.Copy (ptr, buffer, 0, buffer.Length);
            } else {
                // Temporary buffer to store the copied section of data
                byte[] buffer = new byte[elementCount * vertexStride - offsetInBytes];
                // Copy from the vertex buffer to the temporary buffer
                Marshal.Copy(ptr, buffer, 0, buffer.Length);
                
                var dataHandle = GCHandle.Alloc (data, GCHandleType.Pinned);
                var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject ().ToInt64 () + startIndex * elementSizeInByte);
                
                // Copy from the temporary buffer to the destination array
                
                int dataSize = Marshal.SizeOf(typeof(T));
                if (dataSize == vertexStride)
                    Marshal.Copy(buffer, 0, dataPtr, buffer.Length);
                else
                {
                    // If the user is asking for a specific element within the vertex buffer, copy them one by one...
                    for (int i = 0; i < elementCount; i++)
                    {
                        Marshal.Copy(buffer, i * vertexStride, dataPtr, dataSize);
                        dataPtr = (IntPtr)(dataPtr.ToInt64() + dataSize);
                    }
                }
                
                dataHandle.Free ();
                
                //Buffer.BlockCopy(buffer, 0, data, startIndex * elementSizeInByte, elementCount * elementSizeInByte);
            }
            GL.UnmapBuffer(BufferTarget.ArrayBuffer);
            }
Ejemplo n.º 5
0
        internal void Apply(Shader shader, IntPtr offset)
        {
            VertexDeclarationAttributeInfo attrInfo;
            int shaderHash = shader.GetHashCode();

            if (!shaderAttributeInfo.TryGetValue(shaderHash, out attrInfo))
            {
                // Get the vertex attribute info and cache it
                attrInfo = new VertexDeclarationAttributeInfo(GraphicsDevice.MaxVertexAttributes);

                foreach (var ve in _elements)
                {
                    var attributeLocation = shader.GetAttribLocation(ve.VertexElementUsage, ve.UsageIndex);
                    // XNA appears to ignore usages it can't find a match for, so we will do the same
                    if (attributeLocation >= 0)
                    {
                        attrInfo.Elements.Add(new VertexDeclarationAttributeInfo.Element()
                        {
                            Offset                  = ve.Offset,
                            AttributeLocation       = attributeLocation,
                            NumberOfElements        = ve.VertexElementFormat.OpenGLNumberOfElements(),
                            VertexAttribPointerType = ve.VertexElementFormat.OpenGLVertexAttribPointerType(),
                            Normalized              = ve.OpenGLVertexAttribNormalized(),
                        });
                        attrInfo.EnabledAttributes[attributeLocation] = true;
                    }
                }

                shaderAttributeInfo.Add(shaderHash, attrInfo);
            }

            // Apply the vertex attribute info
            foreach (var element in attrInfo.Elements)
            {
                GL.VertexAttribPointer(element.AttributeLocation,
                                       element.NumberOfElements,
                                       element.VertexAttribPointerType,
                                       element.Normalized,
                                       this.VertexStride,
                                       (IntPtr)(offset.ToInt64() + element.Offset));
                GraphicsExtensions.CheckGLError();
            }
            GraphicsDevice.SetVertexAttributeArray(attrInfo.EnabledAttributes);
        }
Ejemplo n.º 6
0
        internal protected override void GraphicsDeviceResetting()
        {
#if OPENGL
            if (_shaderHandle != -1)
            {
                if (GL.IsShader(_shaderHandle))
                {
                    GL.DeleteShader(_shaderHandle);
                    GraphicsExtensions.CheckGLError();
                }
                _shaderHandle = -1;
            }
#endif

#if DIRECTX
            SharpDX.Utilities.Dispose(ref _vertexShader);
            SharpDX.Utilities.Dispose(ref _pixelShader);
#endif
        }
Ejemplo n.º 7
0
        /// <summary>
        /// If the IBO does not exist, create it.
        /// </summary>
        void GenerateIfRequired()
        {
            if (ibo == 0)
            {
                var sizeInBytes = IndexCount * (this.IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4);

#if IOS || ANDROID
                GL.GenBuffers(1, ref ibo);
#else
                GL.GenBuffers(1, out ibo);
#endif
                GraphicsExtensions.CheckGLError();
                GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
                GraphicsExtensions.CheckGLError();
                GL.BufferData(BufferTarget.ElementArrayBuffer,
                              (IntPtr)sizeInBytes, IntPtr.Zero, _isDynamic ? BufferUsageHint.StreamDraw : BufferUsageHint.StaticDraw);
                GraphicsExtensions.CheckGLError();
            }
        }
Ejemplo n.º 8
0
        private void PlatformSetData <T>(int level,
                                         int left, int top, int right, int bottom, int front, int back,
                                         T[] data, int startIndex, int elementCount, int width, int height, int depth)
        {
#if GLES
            throw new NotSupportedException("OpenGL ES 2.0 doesn't support 3D textures.");
#else
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataPtr           = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInByte);

            GL.BindTexture(glTarget, glTexture);
            GraphicsExtensions.CheckGLError();
            GL.TexSubImage3D(glTarget, level, left, top, front, width, height, depth, glFormat, glType, dataPtr);
            GraphicsExtensions.CheckGLError();

            dataHandle.Free();
#endif
        }
Ejemplo n.º 9
0
        private void GetBufferData <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) where T : struct
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GraphicsExtensions.CheckGLError();

            // Pointer to the start of data in the vertex buffer
            var ptr = GL.MapBuffer(BufferTarget.ArrayBuffer, BufferAccess.ReadOnly);

            GraphicsExtensions.CheckGLError();

            ptr = (IntPtr)(ptr.ToInt64() + offsetInBytes);

            if (typeof(T) == typeof(byte) && vertexStride == 1)
            {
                // If data is already a byte[] and stride is 1 we can skip the temporary buffer
                var buffer = data as byte[];
                Marshal.Copy(ptr, buffer, startIndex * vertexStride, elementCount * vertexStride);
            }
            else
            {
                // Temporary buffer to store the copied section of data
                var tmp = new byte[elementCount * vertexStride];
                // Copy from the vertex buffer to the temporary buffer
                Marshal.Copy(ptr, tmp, 0, tmp.Length);

                // Copy from the temporary buffer to the destination array
                var tmpHandle = GCHandle.Alloc(tmp, GCHandleType.Pinned);
                var tmpPtr    = tmpHandle.AddrOfPinnedObject();
                try {
                    for (var i = 0; i < elementCount; i++)
                    {
                        data[startIndex + i] = (T)Marshal.PtrToStructure(tmpPtr, typeof(T));
                        tmpPtr = (IntPtr)(tmpPtr.ToInt64() + vertexStride);
                    }
                }
                finally {
                    tmpHandle.Free();
                }
            }

            GL.UnmapBuffer(BufferTarget.ArrayBuffer);
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 10
0
        internal void ApplyState(GraphicsDevice device)
        {
            var blendEnabled = !(this.ColorSourceBlend == Blend.One &&
                                 this.ColorDestinationBlend == Blend.Zero &&
                                 this.AlphaSourceBlend == Blend.One &&
                                 this.AlphaDestinationBlend == Blend.Zero);

            if (blendEnabled)
            {
                GL.Enable(EnableCap.Blend);
            }
            else
            {
                GL.Disable(EnableCap.Blend);
            }
            GraphicsExtensions.CheckGLError();

            GL.BlendColor(
                this.BlendFactor.R / 255.0f,
                this.BlendFactor.G / 255.0f,
                this.BlendFactor.B / 255.0f,
                this.BlendFactor.A / 255.0f);
            GraphicsExtensions.CheckGLError();

            GL.BlendEquationSeparate(
                this.ColorBlendFunction.GetBlendEquationMode(),
                this.AlphaBlendFunction.GetBlendEquationMode());
            GraphicsExtensions.CheckGLError();

            GL.BlendFuncSeparate(
                this.ColorSourceBlend.GetBlendFactorSrc(),
                this.ColorDestinationBlend.GetBlendFactorDest(),
                this.AlphaSourceBlend.GetBlendFactorSrc(),
                this.AlphaDestinationBlend.GetBlendFactorDest());
            GraphicsExtensions.CheckGLError();

            GL.ColorMask(
                (this.ColorWriteChannels & ColorWriteChannels.Red) != 0,
                (this.ColorWriteChannels & ColorWriteChannels.Green) != 0,
                (this.ColorWriteChannels & ColorWriteChannels.Blue) != 0,
                (this.ColorWriteChannels & ColorWriteChannels.Alpha) != 0);
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 11
0
        internal void Activate(TextureTarget target, bool useMipmaps = false)
        {
            switch (Filter)
            {
            case TextureFilter.Point:
                GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)(useMipmaps ? TextureMinFilter.NearestMipmapNearest : TextureMinFilter.Nearest));
                GraphicsExtensions.CheckGLError();
                GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                GraphicsExtensions.CheckGLError();
                break;

            case TextureFilter.Linear:
                GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)(useMipmaps ? TextureMinFilter.LinearMipmapLinear : TextureMinFilter.Linear));
                GraphicsExtensions.CheckGLError();
                GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GraphicsExtensions.CheckGLError();
                break;

            case TextureFilter.Anisotropic:
                // TODO: Requires EXT_texture_filter_anisotropic. Use linear filtering for now.
                GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)(useMipmaps ? TextureMinFilter.LinearMipmapLinear : TextureMinFilter.Linear));
                GraphicsExtensions.CheckGLError();
                GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GraphicsExtensions.CheckGLError();
                break;

            case TextureFilter.PointMipLinear:
                GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)(useMipmaps ? TextureMinFilter.LinearMipmapNearest : TextureMinFilter.Nearest));
                GraphicsExtensions.CheckGLError();
                GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
                GraphicsExtensions.CheckGLError();
                break;

            default:
                throw new NotImplementedException();
            }

            // Set up texture addressing.
            GL.TexParameter(target, TextureParameterName.TextureWrapS, (int)GetWrapMode(AddressU));
            GraphicsExtensions.CheckGLError();
            GL.TexParameter(target, TextureParameterName.TextureWrapT, (int)GetWrapMode(AddressV));
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 12
0
        internal void Apply(Shader shader, int offset, int programHash)
        {
            var attrInfo = GetAttributeInfo(shader, programHash);

            // Apply the vertex attribute info
            foreach (var element in attrInfo.Elements)
            {
                gl.vertexAttribPointer(element.AttributeLocation,
                                       element.NumberOfElements,
                                       element.VertexAttribPointerType,
                                       element.Normalized,
                                       VertexStride,
                                       offset + element.Offset);

                GraphicsExtensions.CheckGLError();
            }
            GraphicsDevice.SetVertexAttributeArray(attrInfo.EnabledAttributes);
            GraphicsDevice._attribsDirty = true;
        }
Ejemplo n.º 13
0
        private void PlatformSetData <T>(CubeMapFace face, int level, IntPtr dataPtr, int xOffset, int yOffset, int width, int height)
        {
            Threading.BlockOnUIThread(() =>
            {
                GL.BindTexture(TextureTarget.TextureCubeMap, this.glTexture);
                GraphicsExtensions.CheckGLError();

                TextureTarget target = GetGLCubeFace(face);
                if (glFormat == (PixelFormat)All.CompressedTextureFormats)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    GL.TexSubImage2D(target, level, xOffset, yOffset, width, height, glFormat, glType, dataPtr);
                    GraphicsExtensions.CheckGLError();
                }
            });
        }
Ejemplo n.º 14
0
        private void PlatformSetViewport(ref Viewport value)
        {
            if (IsRenderTargetBound)
            {
                gl.viewport(value.X, value.Y, value.Width, value.Height);
            }
            else
            {
                gl.viewport(value.X, PresentationParameters.BackBufferHeight - value.Y - value.Height, value.Width, value.Height);
            }
            GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.Viewport");

            gl.depthRange(value.MinDepth, value.MaxDepth);
            GraphicsExtensions.LogGLError("GraphicsDevice.Viewport_set() GL.DepthRange");

            // In OpenGL we have to re-apply the special "posFixup"
            // vertex shader uniform if the viewport changes.
            _vertexShaderDirty = true;
        }
Ejemplo n.º 15
0
        private void PlatformDrawUserIndexedPrimitives <T>(PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int numVertices, short[] indexData, int indexOffset, int primitiveCount, VertexDeclaration vertexDeclaration) where T : struct
        {
            ApplyState(true);

            var count = GetElementCountArray(primitiveType, primitiveCount);

            var vertexArrayBuffer = ConvertVertices(vertexData, vertexOffset, numVertices, vertexDeclaration);
            var uintIndexData     = new Uint16Array(count.As <uint>());//indexData.As<Uint16Array>();

            for (uint i = 0; i < uintIndexData.length; i++)
            {
                uintIndexData[i] = indexData[indexOffset + i].As <ushort>();
            }

            var vertexBuffer = gl.createBuffer();
            var indexBuffer  = gl.createBuffer();

            gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
            GraphicsExtensions.CheckGLError();
            gl.bufferData(gl.ARRAY_BUFFER, vertexArrayBuffer, gl.STATIC_DRAW);
            GraphicsExtensions.CheckGLError();
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
            GraphicsExtensions.CheckGLError();
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, uintIndexData, gl.STATIC_DRAW);
            GraphicsExtensions.CheckGLError();

            _vertexBuffersDirty = true;
            _indexBufferDirty   = true;

            var mode = (uint)GraphicsExtensions.GetPrimitiveTypeGL(primitiveType);

            vertexDeclaration.GraphicsDevice = this;
            vertexDeclaration.Apply(_vertexShader, vertexOffset, ShaderProgramHash);

            GraphicsExtensions.CheckGLError();
            gl.drawElements(mode, count, gl.UNSIGNED_SHORT, 0);
            GraphicsExtensions.CheckGLError();

            gl.bindBuffer(gl.ARRAY_BUFFER, null);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
            gl.deleteBuffer(vertexBuffer);
            gl.deleteBuffer(indexBuffer);
        }
Ejemplo n.º 16
0
        private ShaderProgram Link(Shader vertexShader, Shader pixelShader)
        {
            // NOTE: No need to worry about background threads here
            // as this is only called at draw time when we're in the
            // main drawing thread.
            var program = GL.CreateProgram();

            GraphicsExtensions.CheckGLError();

            GL.AttachShader(program, vertexShader.GetShaderHandle());
            GraphicsExtensions.CheckGLError();

            GL.AttachShader(program, pixelShader.GetShaderHandle());
            GraphicsExtensions.CheckGLError();

            //vertexShader.BindVertexAttributes(program);

            GL.LinkProgram(program);
            GraphicsExtensions.CheckGLError();

            GL.UseProgram(program);
            GraphicsExtensions.CheckGLError();

            vertexShader.GetVertexAttributeLocations(program);

            pixelShader.ApplySamplerTextureUnits(program);

            var linked = 0;

            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out linked);
            GraphicsExtensions.LogGLError("VertexShaderCache.Link(), GL.GetProgram");
            if (linked == (int)Bool.False)
            {
                var log = GL.GetProgramInfoLog(program);
                Console.WriteLine(log);
                GL.DetachShader(program, vertexShader.GetShaderHandle());
                GL.DetachShader(program, pixelShader.GetShaderHandle());
                _graphicsDevice.DisposeProgram(program);
                throw new InvalidOperationException("Unable to link effect program");
            }

            return(new ShaderProgram(program));
        }
        private ShaderProgram Link(Shader vertexShader, Shader pixelShader)
        {
            // NOTE: No need to worry about background threads here
            // as this is only called at draw time when we're in the
            // main drawing thread.
            var program = (WebGLProgram)gl.createProgram();

            GraphicsExtensions.CheckGLError();

            gl.attachShader(program, vertexShader.GetShaderHandle());
            GraphicsExtensions.CheckGLError();

            gl.attachShader(program, pixelShader.GetShaderHandle());
            GraphicsExtensions.CheckGLError();

            //vertexShader.BindVertexAttributes(program);

            gl.linkProgram(program);
            GraphicsExtensions.CheckGLError();

            gl.useProgram(program);
            GraphicsExtensions.CheckGLError();

            vertexShader.GetVertexAttributeLocations(program);

            pixelShader.ApplySamplerTextureUnits(program);

            var linked = (bool)gl.getProgramParameter(program, gl.LINK_STATUS);

            GraphicsExtensions.LogGLError("VertexShaderCache.Link(), GL.GetProgram");

            if (!linked)
            {
                var log = gl.getProgramInfoLog(program);
                gl.detachShader(program, vertexShader.GetShaderHandle());
                gl.detachShader(program, pixelShader.GetShaderHandle());
                _graphicsDevice.DisposeProgram(program);
                throw new InvalidOperationException("Unable to link effect program");
            }

            return(new ShaderProgram(program));
        }
Ejemplo n.º 18
0
        private void SetBufferData <T>(int bufferSize, int elementSizeInBytes, int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride, SetDataOptions options) where T : struct
        {
            GenerateIfRequired();

            var sizeInBytes = elementSizeInBytes * elementCount;

            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GraphicsExtensions.CheckGLError();

            if (options == SetDataOptions.Discard)
            {
                // By assigning NULL data to the buffer this gives a hint
                // to the device to discard the previous content.
                GL.BufferData(BufferTarget.ArrayBuffer,
                              (IntPtr)bufferSize,
                              IntPtr.Zero,
                              _isDynamic ? BufferUsageHint.StreamDraw : BufferUsageHint.StaticDraw);
                GraphicsExtensions.CheckGLError();
            }

            var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataPtr    = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInBytes);

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

            if (dataSize == vertexStride)
            {
                GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)offsetInBytes, (IntPtr)sizeInBytes, dataPtr);
                GraphicsExtensions.CheckGLError();
            }
            else
            {
                for (int i = 0; i < elementCount; i++)
                {
                    GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)offsetInBytes + i * vertexStride, (IntPtr)dataSize, dataPtr);
                    GraphicsExtensions.CheckGLError();
                    dataPtr = (IntPtr)(dataPtr.ToInt64() + dataSize);
                }
            }

            dataHandle.Free();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// If the VBO does not exist, create it.
        /// </summary>
        void GenerateIfRequired()
        {
            if (vbo == 0)
            {
                //GLExt.Oes.GenVertexArrays(1, out this.vao);
                //GLExt.Oes.BindVertexArray(this.vao);
#if IOS || ANDROID
                GL.GenBuffers(1, ref this.vbo);
#else
                GL.GenBuffers(1, out this.vbo);
#endif
                GraphicsExtensions.CheckGLError();
                GL.BindBuffer(BufferTarget.ArrayBuffer, this.vbo);
                GraphicsExtensions.CheckGLError();
                GL.BufferData(BufferTarget.ArrayBuffer,
                              new IntPtr(VertexDeclaration.VertexStride * VertexCount), IntPtr.Zero,
                              _isDynamic ? BufferUsageHint.StreamDraw : BufferUsageHint.StaticDraw);
                GraphicsExtensions.CheckGLError();
            }
        }
Ejemplo n.º 20
0
        public override void Dispose()
        {
#if DIRECTX
            if (_resourceView != null)
            {
                _resourceView.Dispose();
                _resourceView = null;
            }

            if (_texture != null)
            {
                _texture.Dispose();
                _texture = null;
            }
#elif OPENGL
            GL.DeleteTextures(1, ref glTexture);
            GraphicsExtensions.CheckGLError();
#endif
            base.Dispose();
        }
Ejemplo n.º 21
0
        private void PlatformSetData <T>(CubeMapFace face, int level, Rectangle rect, T[] data, int startIndex, int elementCount)
        {
            var subarr = new Uint8Array(data.As <ArrayBuffer>(), startIndex.As <uint>(), elementCount.As <uint>());

            gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.glTexture);
            GraphicsExtensions.CheckGLError();

            var target = GetGLCubeFace(face);

            if (glFormat == gl.COMPRESSED_TEXTURE_FORMATS)
            {
                gl.compressedTexSubImage2D(target, level, rect.X, rect.Y, rect.Width, rect.Height, glInternalFormat, subarr);
                GraphicsExtensions.CheckGLError();
            }
            else
            {
                gl.texSubImage2D(target, level, rect.X, rect.Y, rect.Width, rect.Height, glFormat, glType, subarr.As <ArrayBufferView>());
                GraphicsExtensions.CheckGLError();
            }
        }
Ejemplo n.º 22
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                GraphicsDevice.AddDisposeAction(() =>
                {
                    if (_shaderHandle != -1)
                    {
                        if (GL.IsShader(_shaderHandle))
                        {
                            GL.DeleteShader(_shaderHandle);
                            GraphicsExtensions.CheckGLError();
                        }
                        _shaderHandle = -1;
                    }
                });
            }

            base.Dispose(disposing);
        }
Ejemplo n.º 23
0
        public void PlatformPresent()
        {
#if WINDOWS || LINUX || ANGLE
            Context.SwapBuffers();
#endif
            GraphicsExtensions.CheckGLError();

            // Dispose of any GL resources that were disposed in another thread
            lock (disposeActionsLock)
            {
                if (disposeActions.Count > 0)
                {
                    foreach (var action in disposeActions)
                    {
                        action();
                    }
                    disposeActions.Clear();
                }
            }
        }
Ejemplo n.º 24
0
 public Texture3D(GraphicsDevice graphicsDevice, int width, int height, int depth, bool mipMap, SurfaceFormat format)
 {
     if (graphicsDevice == null)
     {
         throw new ArgumentNullException("graphicsDevice");
     }
     this.GraphicsDevice = graphicsDevice;
     this.width          = width;
     this.height         = height;
     this.depth          = depth;
     this.levelCount     = 1;
     this.glTarget       = TextureTarget.Texture3D;
     GL.GenTextures(1, out this.glTexture);
     GL.BindTexture(this.glTarget, this.glTexture);
     GraphicsExtensions.GetGLFormat(format, out this.glInternalFormat, out this.glFormat, out this.glType);
     GL.TexImage3D(this.glTarget, 0, this.glInternalFormat, width, height, depth, 0, this.glFormat, this.glType, IntPtr.Zero);
     if (mipMap)
     {
         throw new NotImplementedException("Texture3D does not yet support mipmaps.");
     }
 }
Ejemplo n.º 25
0
 protected virtual void Dispose(bool disposing)
 {
     if (this._isDisposed)
     {
         return;
     }
     if (disposing)
     {
         GraphicsResource.DisposeAll();
         this._programCache.Dispose();
         GraphicsDevice.AddDisposeAction((Action)(() =>
         {
             if (this.glRenderTargetFrameBuffer <= 0U)
             {
                 return;
             }
             GraphicsExtensions.DeleteFramebuffers(1, ref this.glRenderTargetFrameBuffer);
         }));
     }
     this._isDisposed = true;
 }
Ejemplo n.º 26
0
        private void PlatformDrawIndexedPrimitives(PrimitiveType primitiveType, int baseVertex, int startIndex, int primitiveCount)
        {
            ApplyState(true);

            var shortIndices = _indexBuffer.IndexElementSize == IndexElementSize.SixteenBits;

            var indexElementType   = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
            var indexElementSize   = shortIndices ? 2 : 4;
            var indexOffsetInBytes = (IntPtr)(startIndex * indexElementSize);
            var indexElementCount  = GetElementCountArray(primitiveType, primitiveCount);
            var target             = PrimitiveTypeGL(primitiveType);
            var vertexOffset       = (IntPtr)(_vertexBuffer.VertexDeclaration.VertexStride * baseVertex);

            _vertexBuffer.VertexDeclaration.Apply(_vertexShader, vertexOffset);

            GL.DrawElements(target,
                            indexElementCount,
                            indexElementType,
                            indexOffsetInBytes);
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 27
0
        internal void ApplyState(GraphicsDevice device)
        {
            GL.Enable(EnableCap.Blend);
            GraphicsExtensions.CheckGLError();

            // Set blending mode
            var blendMode = ColorBlendFunction.GetBlendEquationMode();

            GL.BlendEquation(blendMode);
            GraphicsExtensions.CheckGLError();

            // Set blending function
            var bfs = ColorSourceBlend.GetBlendFactorSrc();
            var bfd = ColorDestinationBlend.GetBlendFactorDest();

#if IPHONE
            GL.BlendFunc((All)bfs, (All)bfd);
#else
            GL.BlendFunc(bfs, bfd);
#endif
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 28
0
        private void BufferData <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, SetDataOptions options) where T : struct
        {
            GenerateIfRequired();

            var elementSizeInByte = (IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4);
            var bufferSize        = IndexCount * elementSizeInByte;

            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
            GraphicsExtensions.CheckGLError();

            if (options == SetDataOptions.Discard)
            {
                // By assigning NULL data to the buffer this gives a hint
                // to the device to discard the previous content.
                gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Int16Array(0), _isDynamic ? gl.STREAM_DRAW : gl.STATIC_DRAW);
                GraphicsExtensions.CheckGLError();
            }

            if (elementSizeInByte == 2)
            {
                var arr = new Uint16Array((uint)elementCount);
                for (uint i = 0; i < elementCount; i++)
                {
                    arr[i] = data[i + startIndex].As <ushort>();
                }
                gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, offsetInBytes, arr);
            }
            else
            {
                var arr = new Uint32Array((uint)elementCount);
                for (uint i = 0; i < elementCount; i++)
                {
                    arr[i] = data[i + startIndex].As <uint>();
                }
                gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, offsetInBytes, arr);
            }
            GraphicsExtensions.CheckGLError();
        }
Ejemplo n.º 29
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
#if DIRECTX
                if (disposing)
                {
                    SharpDX.Utilities.Dispose(ref _resourceView);
                    SharpDX.Utilities.Dispose(ref _texture);
                }
#elif OPENGL
                GraphicsDevice.AddDisposeAction(() =>
                {
                    GL.DeleteTextures(1, ref glTexture);
                    GraphicsExtensions.CheckGLError();
                    glTexture = -1;
                });

                glLastSamplerState = null;
#endif
            }
            base.Dispose(disposing);
        }
Ejemplo n.º 30
0
        public void SetData <T> (int level,
                                 int left, int top, int right, int bottom, int front, int back,
                                 T[] data, int startIndex, int elementCount) where T : struct
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
#if !PORTABLE
            var elementSizeInByte = Marshal.SizeOf(typeof(T));
            var dataHandle        = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataPtr           = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startIndex * elementSizeInByte);
            int width             = right - left;
            int height            = bottom - top;
            int depth             = back - front;

#if OPENGL
            GL.BindTexture(glTarget, glTexture);
            GraphicsExtensions.CheckGLError();
            GL.TexSubImage3D(glTarget, level, left, top, front, width, height, depth, glFormat, glType, dataPtr);
            GraphicsExtensions.CheckGLError();
#elif DIRECTX
            int rowPitch   = GetPitch(width);
            int slicePitch = rowPitch * height; // For 3D texture: Size of 2D image.
            var box        = new DataBox(dataPtr, rowPitch, slicePitch);

            int subresourceIndex = level;

            var region = new ResourceRegion(left, top, front, right, bottom, back);

            var d3dContext = GraphicsDevice._d3dContext;
            lock (d3dContext)
                d3dContext.UpdateSubresource(box, GetTexture(), subresourceIndex, region);
#endif
            dataHandle.Free();
#endif
        }
Ejemplo n.º 31
0
 public static void LogToFile(GraphicsExtensions.LogSeverity severity, string message)
 {
   try
   {
     using (FileStream fileStream = File.Open(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\FEZ\\Debug Log.txt", FileMode.Append))
     {
       using (StreamWriter streamWriter = new StreamWriter((Stream) fileStream))
         streamWriter.WriteLine("({0}) [{1}] {2} : {3}", (object) DateTime.Now.ToString("HH:mm:ss.fff"), (object) "MonoGame", (object) ((object) severity).ToString().ToUpper(CultureInfo.InvariantCulture), (object) message);
     }
   }
   catch (Exception ex)
   {
   }
 }