예제 #1
0
        private void CreateVertexVBO()
        {
            if (!Initialized)
            {
                return;
            }

            int length = VertexDataSize * sizeof(float);

            //unbind - just in case this is causing us the invalid exception problems
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            //create buffer
            GL.GenBuffers(1, out m_vertexVBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, m_vertexVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(length), IntPtr.Zero, BufferUsageHint.DynamicCopy);  // use data instead of IntPtr.Zero if needed
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            try
            {
                m_cudaVertexSource = new CudaOpenGLBufferInteropResource(m_vertexVBO, CUGraphicsRegisterFlags.None);
            }
            catch (CudaException e)
            {
                MyLog.DEBUG.WriteLine(
                    "{0}: CUDA-OpenGL interop error while itializing vertex data (using fallback): {1}",
                    GetType().Name, e.Message);

                m_cudaVertexVar = new CudaDeviceVariable <float>(VertexDataSize);
            }
        }
예제 #2
0
        // unregister this buffer object with CUDA and destroy buffer
        private void DeleteTextureVBO()
        {
            if ((m_cudaTextureSource == null) && (m_cudaTextureVar == null))
            {
                return;
            }

            if (m_cudaTextureSource != null)
            {
                m_cudaTextureSource.Dispose();
                m_cudaTextureSource = null;
            }
            else if (m_cudaTextureVar != null)
            {
                m_cudaTextureVar.Dispose();
                m_cudaTextureVar = null;
            }

            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0);
            GL.DeleteBuffers(1, ref m_textureVBO);

            GL.DeleteTextures(1, ref m_texture_id);
            m_textureVBO = 0;
            m_texture_id = 0;
        }
        void InitKernels()
        {
            var path = @"..\..\..\CudaParticleSimulation\kernel.ptx";

            if (!System.IO.File.Exists(path))
            {
                Debug.Error(path + " doesnt exists");
                return;
            }

            var cntxt = new CudaContext();

            uint deviceCount = 1;
            var  devices     = new CUdevice[50];

            OpenGLNativeMethods.CUDA3.cuGLGetDevices(ref deviceCount, devices, 50, CUGLDeviceList.All);

            var context = cntxt.Context;

            OpenGLNativeMethods.CUDA3.cuGLCtxCreate(ref context, CUCtxFlags.BlockingSync, devices[0]);

            Debug.Info("Found " + deviceCount + " OpenGL devices associated with current context");


            CUmodule cumodule = cntxt.LoadModule(path);

            updateParticles = new CudaKernel("updateParticles", cumodule, cntxt);
            updateParticles.BlockDimensions = new dim3(16 * 16, 1, 1);
            updateParticles.GridDimensions  = new dim3(16 * 16, 1, 1);


            generateParticles = new CudaKernel("generateParticles", cumodule, cntxt);
            generateParticles.BlockDimensions = updateParticles.BlockDimensions;
            generateParticles.GridDimensions  = updateParticles.GridDimensions;

            var random       = new Random();
            var randomFloats = new float[1000];

            for (int i = 0; i < randomFloats.Length; i++)
            {
                randomFloats[i] = (float)random.NextDouble();
            }

            generateParticles.SetConstantVariable("randomFloats", randomFloats);

            // CudaGraphicsInteropResourceCollection

            resources.Clear();
            foreach (var h in renderer.particleMesh.allBufferHandles)
            {
                var resoure = new CudaOpenGLBufferInteropResource(h, CUGraphicsRegisterFlags.None, CUGraphicsMapResourceFlags.None);
                resources.Add(resoure);
            }


            randomIndex_D = 0;
            randomIndex_D.CopyToDevice(0);
        }
예제 #4
0
        private void CreateTextureVBO()
        {
            if (!Initialized)
            {
                return;
            }

            int length = TextureWidth * TextureHeight * sizeof(uint);

            if (length <= 0)
            {
                return;
            }

            //unbind - just in case this is causing us the invalid exception problems
            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0);
            //create buffer
            GL.GenBuffers(1, out m_textureVBO);
            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, m_textureVBO);
            GL.BufferData(BufferTarget.PixelUnpackBuffer, (IntPtr)(length), IntPtr.Zero, BufferUsageHint.DynamicCopy);  // use data instead of IntPtr.Zero if needed
            GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0);

            try
            {
                m_cudaTextureSource = new CudaOpenGLBufferInteropResource(m_textureVBO, CUGraphicsRegisterFlags.None); //.WriteDiscard);  // Write only by CUDA
            }
            catch (CudaException e)
            {
                MyLog.DEBUG.WriteLine(
                    "{0}: CUDA-OpenGL interop error while itializing texture (using fallback): {1}",
                    GetType().Name, e.Message);

                m_cudaTextureVar = new CudaDeviceVariable <uint>(TextureSize);
            }

            // Enable Texturing
            GL.Enable(EnableCap.Texture2D);
            // Generate a texture ID
            GL.GenTextures(1, out m_texture_id);
            // Make this the current texture (remember that GL is state-based)
            GL.BindTexture(TextureTarget.Texture2D, m_texture_id);
            // Allocate the texture memory. The last parameter is NULL since we only
            // want to allocate memory, not initialize it
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, TextureWidth, TextureHeight, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero);

            // Must set the filter mode, GL_LINEAR enables interpolation when scaling
            int filter = BilinearFiltering
                ? (int)OpenTK.Graphics.OpenGL.All.Linear
                : (int)OpenTK.Graphics.OpenGL.All.Nearest;

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, filter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, filter);
        }
예제 #5
0
            void InitGL()
            {
                m_window  = new NativeWindow();
                m_context = new GraphicsContext(GraphicsMode.Default, m_window.WindowInfo);
                m_context.MakeCurrent(m_window.WindowInfo);
                m_context.LoadAll();

                // Setup rendering texture
                m_renderTextureHandle = (uint)GL.GenTexture();
                GL.BindTexture(TextureTarget.Texture2D, m_renderTextureHandle);
                GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, Owner.VisualWidth, Owner.VisualHeight, 0, OpenTK.Graphics.OpenGL.PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero);

                // Setup FBO
                m_fboHandle = (uint)GL.GenFramebuffer();
                GL.BindFramebuffer(FramebufferTarget.Framebuffer, m_fboHandle);
                GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, m_renderTextureHandle, 0);

                // Setup Cuda <-> OpenGL interop
                int length = Owner.VisualHeight * Owner.VisualWidth * sizeof(uint);

                //unbind - just in case this is causing us the invalid exception problems
                GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);
                //create buffer
                GL.GenBuffers(1, out m_sharedBufferHandle);
                GL.BindBuffer(BufferTarget.PixelPackBuffer, m_sharedBufferHandle);
                GL.BufferData(BufferTarget.PixelPackBuffer, (IntPtr)(length), IntPtr.Zero, BufferUsageHint.StaticRead);  // use data instead of IntPtr.Zero if needed
                GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);
                try
                {
                    m_renderResource = new CudaOpenGLBufferInteropResource(m_renderTextureHandle, CUGraphicsRegisterFlags.ReadOnly); // Read only by CUDA
                }
                catch (CudaException e)
                {
                    MyLog.INFO.WriteLine(
                        "{0}: CUDA-OpenGL interop error while itializing texture (using fallback): {1}",
                        GetType().Name, e.Message);
                }

                // Clean up
                GL.BindTexture(TextureTarget.Texture2D, 0);
                FramebufferErrorCode err = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);

                GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            }
예제 #6
0
        private void CreateVertexVBO()
        {
            if (Initialized)
            {
                int length = VertexDataSize * sizeof(float);

                //unbind - just in case this is causing us the invalid exception problems
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                //create buffer
                GL.GenBuffers(1, out m_vertexVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, m_vertexVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(length), IntPtr.Zero, BufferUsageHint.DynamicCopy);  // use data instead of IntPtr.Zero if needed
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

                m_cudaVertexSource = new CudaOpenGLBufferInteropResource(m_vertexVBO, CUGraphicsRegisterFlags.None);
            }
        }
예제 #7
0
        private void DeleteTextureVBO()
        {
            // unregister this buffer object with CUDA and destroy buffer

            if (m_cudaTextureSource != null)
            {
                m_cudaTextureSource.Dispose();
                GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0);
                GL.DeleteBuffers(1, ref m_textureVBO);

                GL.DeleteTextures(1, ref m_texture_id);
                m_textureVBO = 0;
                m_texture_id = 0;

                m_cudaTextureSource = null;
            }
        }
예제 #8
0
        // unregister this buffer object with CUDA and destroy buffer
        private void DeleteVertexVBO()
        {
            if ((m_cudaVertexSource == null) && (m_cudaVertexVar == null))
            {
                return;
            }

            if (m_cudaVertexSource != null)
            {
                m_cudaVertexSource.Dispose();
                m_cudaVertexSource = null;
            }
            else if (m_cudaVertexVar != null)
            {
                m_cudaVertexVar.Dispose();
                m_cudaVertexVar = null;
            }

            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
            GL.DeleteBuffers(1, ref m_vertexVBO);

            m_vertexVBO = 0;
        }
예제 #9
0
            internal void Dispose()
            {
                if (m_window == null)
                {
                    return;
                }

                try
                {
                    if (!m_context.IsDisposed && !m_context.IsCurrent && !m_window.Exists)
                    {
                        return;
                    }

                    m_context.MakeCurrent(m_window.WindowInfo);

                    ErrorCode err = GL.GetError();
                    if (err != ErrorCode.NoError)
                    {
                        MyLog.WARNING.WriteLine(Owner.Name + ": OpenGL error detected when disposing stuff, code: " + err);
                    }

                    // delete textures
                    if (m_textureHandles != null)
                    {
                        foreach (int handle in m_textureHandles.Values)
                        {
                            int h = handle;
                            GL.DeleteTextures(1, ref h);
                        }

                        m_textureHandles.Clear();
                    }

                    if (m_renderTextureHandle != 0)
                    {
                        GL.DeleteTextures(1, ref m_renderTextureHandle);
                        m_renderTextureHandle = 0;
                    }
                    if (m_scoreTextHandle != 0)
                    {
                        GL.DeleteTextures(1, ref m_scoreTextHandle);
                        m_scoreTextHandle = 0;
                    }

                    // delete FBO
                    if (m_fboHandle != 0)
                    {
                        GL.DeleteFramebuffers(1, ref m_fboHandle);
                        m_fboHandle = 0;
                    }

                    // delete PBO
                    if (m_sharedBufferHandle != 0)
                    {
                        GL.DeleteBuffers(1, ref m_sharedBufferHandle);
                        m_sharedBufferHandle = 0;
                    }

                    // delete CUDA <-> GL interop
                    if (m_renderResource != null)
                    {
                        m_renderResource.Dispose();
                        m_renderResource = null;
                    }

                    if (m_context != null)
                    {
                        m_context.Dispose();
                        m_context = null;
                    }
                    if (m_window != null)
                    {
                        m_window.Dispose();
                        m_window = null;
                    }
                }
                catch (AccessViolationException e)
                {
                    MyLog.WARNING.WriteLine(Owner.Name + ": Failed when disposing OpenGL stuff. Cautious progress advised. Error: " + e.Message);
                }
                catch (Exception e)
                {
                    MyLog.WARNING.WriteLine(Owner.Name + ": Failed when disposing OpenGL. Error: " + e.Message);
                }
            }
예제 #10
0
            private T InitRR <T>(T rr, MyMemoryBlock <float> targetMemBlock, MyMemoryBlock <float> targetDepthMemBlock, Action <T> initializer = null)
                where T : class, IRenderRequestBase
            {
                if (initializer != null)
                {
                    initializer.Invoke(rr);
                }

                rr.FlipYAxis = true;


                targetMemBlock.ExternalPointer = 0; // first reset ExternalPointer

                // Setup image copying from RR through Cpu
                if (Owner.CopyDataThroughCPU)
                {
                    ImageSettings imageSettings = new ImageSettings(RenderRequestImageCopyingMode.Cpu)
                    {
                        CopyDepth = Owner.CopyDepthData && targetDepthMemBlock != null,
                    };

                    imageSettings.OnSceneBufferPrepared += (request, data, depthData) =>
                    {
                        int width  = rr.Resolution.Width;
                        int stride = width * sizeof(uint);
                        int lines  = data.Length / width;

                        for (int i = 0; i < lines; ++i)
                        {
                            Buffer.BlockCopy(data, i * stride, targetMemBlock.Host, i * width * sizeof(uint), stride);
                        }

                        if (imageSettings.CopyDepth)
                        {
                            for (int i = 0; i < lines; ++i)
                            {
                                Buffer.BlockCopy(depthData, i * stride, targetDepthMemBlock.Host, i * width * sizeof(float), stride);
                            }
                        }

                        // targetMemBlock.SafeCopyToDevice(); this needs to be called on the BrainSim thread
                        // targetDepthMemBlock.SafeCopyToDevice(); this needs to be called on the BrainSim thread
                    };

                    rr.Image = imageSettings;
                    return(rr);
                }


                // Setup image copying from RR through Pbo
                ImageSettings image = new ImageSettings(RenderRequestImageCopyingMode.OpenglPbo)
                {
                    CopyDepth = Owner.CopyDepthData && targetDepthMemBlock != null,
                };

                // Setup data copying to our unmanaged memblocks
                uint renderTextureHandle      = 0;
                uint depthRenderTextureHandle = 0;
                CudaOpenGLBufferInteropResource renderResource      = null;
                CudaOpenGLBufferInteropResource depthRenderResource = null;

                image.OnPreRenderingEvent += (sender, vbo, depthVbo) =>
                {
                    if (renderResource != null && renderResource.IsMapped)
                    {
                        renderResource.UnMap();
                    }

                    if (image.CopyDepth)
                    {
                        if (depthRenderResource != null && depthRenderResource.IsMapped)
                        {
                            depthRenderResource.UnMap();
                        }
                    }
                };

                image.OnPostRenderingEvent += (sender, vbo, depthVbo) =>
                {
                    // Vbo can be allocated during drawing, create the resource after that (post-rendering)
                    MyKernelFactory.Instance.GetContextByGPU(Owner.GPU).SetCurrent();

                    // Fill color memblock
                    if (renderResource == null || vbo != renderTextureHandle)
                    {
                        if (renderResource != null)
                        {
                            renderResource.Dispose();
                        }

                        renderTextureHandle = vbo;
                        try
                        {
                            renderResource = new CudaOpenGLBufferInteropResource(renderTextureHandle,
                                                                                 image.CopyDepth ? CUGraphicsRegisterFlags.None : CUGraphicsRegisterFlags.ReadOnly); // Read only by CUDA
                        }
                        catch (Exception e)
                        {
                            MyLog.ERROR.WriteLine("calling CudaOpenGLBufferInteropResource returns " + e +
                                                  ". Go to World properties and in Runtime section set Copy data through CPU to True");
                            throw e;
                        }
                    }

                    renderResource.Map();
                    targetMemBlock.ExternalPointer = renderResource.GetMappedPointer <uint>().DevicePointer.Pointer;
                    targetMemBlock.FreeDevice();
                    targetMemBlock.AllocateDevice();

                    // Fill depth memblock
                    if (image.CopyDepth)
                    {
                        if (depthRenderResource == null || depthVbo != depthRenderTextureHandle)
                        {
                            if (depthRenderResource != null)
                            {
                                depthRenderResource.Dispose();
                            }

                            depthRenderTextureHandle = depthVbo;
                            depthRenderResource      = new CudaOpenGLBufferInteropResource(
                                depthRenderTextureHandle,
                                CUGraphicsRegisterFlags.ReadOnly); // Read only by CUDA
                        }

                        depthRenderResource.Map();
                        targetDepthMemBlock.ExternalPointer = depthRenderResource.GetMappedPointer <float>().DevicePointer.Pointer;
                        targetDepthMemBlock.FreeDevice();
                        targetDepthMemBlock.AllocateDevice();
                    }
                };

                rr.Image = image;


                // Initialize the target memory block
                // Use a dummy number that will get replaced on first Execute call to suppress MemBlock error during init
                targetMemBlock.ExternalPointer = 1;

                if (targetDepthMemBlock != null)
                {
                    targetDepthMemBlock.ExternalPointer = 1;
                }

                return(rr);
            }