Example #1
0
        public unsafe void Run(Texture2d tex, Size InputSize, Size OutputSize, bool flip)
        {
            //ack! make sure to set the pipeline before setting
            Bind();

            Pipeline["InputSize"].Set(new Vector2(InputSize.Width,InputSize.Height));
            Pipeline["TextureSize"].Set(new Vector2(InputSize.Width, InputSize.Height));
            Pipeline["OutputSize"].Set(new Vector2(OutputSize.Width, OutputSize.Height));
            Pipeline["FrameCount"].Set(0); //todo
            Pipeline["FrameDirection"].Set(1); //todo

            var Projection = Owner.CreateGuiProjectionMatrix(OutputSize);
            var Modelview = Owner.CreateGuiViewMatrix(OutputSize);
            Pipeline["MVPMatrix"].Set(Modelview * Projection, false);

            Owner.SetTextureWrapMode(tex, true);

            Pipeline["Texture"].Set(tex);
            Owner.SetViewport(OutputSize);

            int w = OutputSize.Width;
            int h = OutputSize.Height;
            float v0,v1;
            if (flip) { v0 = 1; v1 = 0; }
            else { v0 = 0; v1 = 1; }
            float* pData = stackalloc float[10*4];
            int i=0;
            pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 1; //topleft vert
            pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //junk
            pData[i++] = 0; pData[i++] = v0; //texcoord
            pData[i++] = w; pData[i++] = 0; pData[i++] = 0; pData[i++] = 1; //topright vert
            pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //junk
            pData[i++] = 1; pData[i++] = v0; //texcoord
            pData[i++] = 0; pData[i++] = h; pData[i++] = 0; pData[i++] = 1; //bottomleft vert
            pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //junk
            pData[i++] = 0; pData[i++] = v1; //texcoord
            pData[i++] = w; pData[i++] = h; pData[i++] = 0; pData[i++] = 1; //bottomright vert
            pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; pData[i++] = 0; //junk
            pData[i++] = 1; pData[i++] = v1; //texcoord

            Owner.SetBlendState(Owner.BlendNoneCopy);
            Owner.BindArrayData(pData);
            Owner.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
        }
Example #2
0
		public void TestCreate()
		{
			Texture2d texture = null;

			// Create(uint, uint, PixelLayout)
			try {
				texture = new Texture2d();
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(16, 16, PixelLayout.RGB24);
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(_Context);
				Assert.IsTrue(texture.Exists(_Context));
			} finally {
				if (texture != null)
					texture.Dispose(_Context);
				texture = null;
			}

			// Create(GraphicsContext, uint, uint, PixelLayout)
			try {
				texture = new Texture2d();
				Assert.IsFalse(texture.Exists(_Context));

				texture.Create(_Context, 16, 32, PixelLayout.RGB24);
				Assert.IsTrue(texture.Exists(_Context));

				Assert.AreEqual(16, texture.Width);
				Assert.AreEqual(32, texture.Height);
				Assert.AreEqual(PixelLayout.RGB24, texture.PixelLayout);
			} finally {
				if (texture != null)
					texture.Dispose(_Context);
				texture = null;
			}
		}
Example #3
0
		/// <summary>
		/// Attach a 2D texture image to color buffer.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="Texture2d"/> which will be used for read/write operation on this RenderFrambuffer.
		/// </param>
		/// <param name="attachmentIndex">
		/// A <see cref="UInt32"/> that specify the framebuffer color attachment index.
		/// </param>
		public void AttachColor(Texture2d texture, uint attachmentIndex)
		{
			AttachColor(texture, attachmentIndex, 0);
		}
Example #4
0
 public void TexParameter2d(Texture2d tex, TextureParameterName pName, int param)
 {
     BindTexture2d(tex);
     GL.TexParameter(TextureTarget.Texture2D, pName, param);
 }
Example #5
0
 public sd.Bitmap BitmapForTexture(Texture2d tex)
 {
     return(TextureWrapperForTexture(tex).SDBitmap);
 }
Example #6
0
 public void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
 {
     bmp.ToSysdrawingBitmap(BitmapForTexture(tex));
 }
Example #7
0
		public void Draw(Texture2d tex, float x, float y) { DrawInternal(tex, x, y, tex.Width, tex.Height); }
Example #8
0
 public void FreeTexture(Texture2d tex)
 {
     GL.DeleteTexture((int)tex.Opaque);
 }
Example #9
0
        private void initialize()
        {
            textureId = GL.GenTexture();
            texture   = new Texture2d(textureId, width, height, "rendertarget");

            DrawState.BindPrimaryTexture(textureId);
            GL.TexImage2D(TextureTarget.Texture2D, 0, internalFormat, width, height, 0, pixelFormat, pixelType, IntPtr.Zero);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)textureMagFilter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)textureMinFilter);

            GL.GetInteger(GetPName.FramebufferBinding, out previousFrameBufferId);

            frameBufferId = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBufferId);
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, textureId, 0);
            DrawState.CheckError("creating fbo");

            if (renderBufferType != null)
            {
                renderBufferId = GL.GenRenderbuffer();
                GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, renderBufferId);
                GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, renderBufferType.Value, width, height);

                switch (renderBufferType.Value)
                {
                case RenderbufferStorage.DepthComponent:
                case RenderbufferStorage.DepthComponent16:
                case RenderbufferStorage.DepthComponent24:
                case RenderbufferStorage.DepthComponent32:
                case RenderbufferStorage.DepthComponent32f:
                    GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, RenderbufferTarget.Renderbuffer, renderBufferId);
                    break;

                case RenderbufferStorage.DepthStencil:
                case RenderbufferStorage.Depth24Stencil8:
                case RenderbufferStorage.Depth32fStencil8:
                    GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, RenderbufferTarget.Renderbuffer, renderBufferId);
                    break;

                case RenderbufferStorage.StencilIndex1:
                case RenderbufferStorage.StencilIndex4:
                case RenderbufferStorage.StencilIndex8:
                case RenderbufferStorage.StencilIndex16:
                    GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.StencilAttachment, RenderbufferTarget.Renderbuffer, renderBufferId);
                    break;

                default:
                    throw new NotSupportedException("renderBufferType " + renderBufferType.Value + " isn't supported.");
                }
            }

            var status = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);

            if (status != FramebufferErrorCode.FramebufferComplete)
            {
                throw new Exception("frame buffer couldn't be constructed: " + status);
            }

            DrawState.UnbindTexture(textureId);
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, previousFrameBufferId);

            Debug.Print(width + "x" + height + " render target created");
        }
Example #10
0
        void UpdateSourceDrawingWork(JobInfo job)
        {
            //begin rendering on this context
            //should this have been done earlier?
            //do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldnt be a problem)
            //GraphicsControl.Begin();

            GlobalWin.GL.BeginScene();

            //run filter chain
            Texture2d    texCurr       = null;
            RenderTarget rtCurr        = null;
            int          rtCounter     = 0;
            bool         inFinalTarget = false;

            foreach (var step in CurrentFilterProgram.Program)
            {
                switch (step.Type)
                {
                case FilterProgram.ProgramStepType.Run:
                {
                    int fi = (int)step.Args;
                    var f  = CurrentFilterProgram.Filters[fi];
                    f.SetInput(texCurr);
                    f.Run();
                    var orec = f.FindOutput();
                    if (orec != null)
                    {
                        if (orec.SurfaceDisposition == SurfaceDisposition.Texture)
                        {
                            texCurr = f.GetOutput();
                            rtCurr  = null;
                        }
                    }
                    break;
                }

                case FilterProgram.ProgramStepType.NewTarget:
                {
                    var size = (Size)step.Args;
                    rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size);
                    rtCurr.Bind();
                    CurrentFilterProgram.CurrRenderTarget = rtCurr;
                    break;
                }

                case FilterProgram.ProgramStepType.FinalTarget:
                {
                    var size = (Size)step.Args;
                    inFinalTarget = true;
                    rtCurr        = null;
                    CurrentFilterProgram.CurrRenderTarget = null;
                    GL.BindRenderTarget(null);
                    break;
                }
                }
            }

            GL.EndScene();

            if (job.offscreen)
            {
                job.offscreenBB = rtCurr.Texture2d.Resolve();
            }
            else
            {
                Debug.Assert(inFinalTarget);
                //apply the vsync setting (should probably try to avoid repeating this)
                bool vsync = Global.Config.VSyncThrottle || Global.Config.VSync;

                //ok, now this is a bit undesireable.
                //maybe the user wants vsync, but not vsync throttle.
                //this makes sense... but we dont have the infrastructure to support it now (we'd have to enable triple buffering or something like that)
                //so what we're gonna do is disable vsync no matter what if throttling is off, and maybe nobody will notice.
                if (Global.DisableSecondaryThrottling)
                {
                    vsync = false;
                }

                if (LastVsyncSetting != vsync || LastVsyncSettingGraphicsControl != presentationPanel.GraphicsControl)
                {
                    if (LastVsyncSetting == null && vsync)
                    {
                        // Workaround for vsync not taking effect at startup (Intel graphics related?)
                        presentationPanel.GraphicsControl.SetVsync(false);
                    }
                    presentationPanel.GraphicsControl.SetVsync(vsync);
                    LastVsyncSettingGraphicsControl = presentationPanel.GraphicsControl;
                    LastVsyncSetting = vsync;
                }

                //present and conclude drawing
                presentationPanel.GraphicsControl.SwapBuffers();

                //nope. dont do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything
                //presentationPanel.GraphicsControl.End();

                NeedsToPaint = false;                 //??
            }
        }
Example #11
0
        FilterProgram UpdateSourceInternal(JobInfo job)
        {
            //no drawing actually happens. it's important not to begin drawing on a control
            if (!job.simulate)
            {
                GlobalWin.GLManager.Activate(CR_GraphicsControl);
            }

            IVideoProvider videoProvider = job.videoProvider;
            bool           simulate      = job.simulate;
            Size           chain_outsize = job.chain_outsize;

            //simulate = true;

            int vw = videoProvider.BufferWidth;
            int vh = videoProvider.BufferHeight;

            if (Global.Config.DispFixAspectRatio)
            {
                if (Global.Config.DispManagerAR == Config.EDispManagerAR.System)
                {
                    vw = videoProvider.VirtualWidth;
                    vh = videoProvider.VirtualHeight;
                }
                if (Global.Config.DispManagerAR == Config.EDispManagerAR.Custom)
                {
                    vw = Global.Config.DispCustomUserARWidth;
                    vh = Global.Config.DispCustomUserARHeight;
                }
            }

            var padding = CalculateCompleteContentPadding(true, false);

            vw += padding.Horizontal;
            vh += padding.Vertical;

            int[] videoBuffer = videoProvider.GetVideoBuffer();

            int  bufferWidth   = videoProvider.BufferWidth;
            int  bufferHeight  = videoProvider.BufferHeight;
            bool isGlTextureId = videoBuffer.Length == 1;

            BitmapBuffer bb           = null;
            Texture2d    videoTexture = null;

            if (!simulate)
            {
                if (isGlTextureId)
                {
                    //FYI: this is a million years from happening on n64, since it's all geriatric non-FBO code
                    //is it workable for saturn?
                    videoTexture = GL.WrapGLTexture2d(new IntPtr(videoBuffer[0]), bufferWidth, bufferHeight);
                }
                else
                {
                    //wrap the videoprovider data in a BitmapBuffer (no point to refactoring that many IVideoProviders)
                    bb = new BitmapBuffer(bufferWidth, bufferHeight, videoBuffer);
                    bb.DiscardAlpha();

                    //now, acquire the data sent from the videoProvider into a texture
                    videoTexture = VideoTextureFrugalizer.Get(bb);

                    //lets not use this. lets define BizwareGL to make clamp by default (TBD: check opengl)
                    //GL.SetTextureWrapMode(videoTexture, true);
                }
            }

            //record the size of what we received, since lua and stuff is gonna want to draw onto it
            currEmuWidth  = bufferWidth;
            currEmuHeight = bufferHeight;

            //build the default filter chain and set it up with services filters will need
            Size chain_insize = new Size(bufferWidth, bufferHeight);

            var filterProgram = BuildDefaultChain(chain_insize, chain_outsize, job.includeOSD);

            filterProgram.GuiRenderer = Renderer;
            filterProgram.GL          = GL;

            //setup the source image filter
            Filters.SourceImage fInput = filterProgram["input"] as Filters.SourceImage;
            fInput.Texture = videoTexture;

            //setup the final presentation filter
            Filters.FinalPresentation fPresent = filterProgram["presentation"] as Filters.FinalPresentation;
            fPresent.VirtualTextureSize     = new Size(vw, vh);
            fPresent.TextureSize            = new Size(bufferWidth, bufferHeight);
            fPresent.BackgroundColor        = videoProvider.BackgroundColor;
            fPresent.GuiRenderer            = Renderer;
            fPresent.Config_FixAspectRatio  = Global.Config.DispFixAspectRatio;
            fPresent.Config_FixScaleInteger = Global.Config.DispFixScaleInteger;

            fPresent.GL = GL;

            filterProgram.Compile("default", chain_insize, chain_outsize, !job.offscreen);

            if (simulate)
            {
            }
            else
            {
                CurrentFilterProgram = filterProgram;
                UpdateSourceDrawingWork(job);
            }

            //cleanup:
            if (bb != null)
            {
                bb.Dispose();
            }

            return(filterProgram);
        }
Example #12
0
        void UpdateSourceDrawingWork(JobInfo job)
        {
            bool alternateVsync = false;

            // only used by alternate vsync
            IGL_SlimDX9 dx9 = null;

            if (!job.Offscreen)
            {
                //apply the vsync setting (should probably try to avoid repeating this)
                var vsync = Global.Config.VSyncThrottle || Global.Config.VSync;

                //ok, now this is a bit undesirable.
                //maybe the user wants vsync, but not vsync throttle.
                //this makes sense... but we don't have the infrastructure to support it now (we'd have to enable triple buffering or something like that)
                //so what we're gonna do is disable vsync no matter what if throttling is off, and maybe nobody will notice.
                //update 26-mar-2016: this upsets me. When fast-forwarding and skipping frames, vsync should still work. But I'm not changing it yet
                if (Global.DisableSecondaryThrottling)
                {
                    vsync = false;
                }

                //for now, it's assumed that the presentation panel is the main window, but that may not always be true
                if (vsync && Global.Config.DispAlternateVsync && Global.Config.VSyncThrottle)
                {
                    dx9 = GL as IGL_SlimDX9;
                    if (dx9 != null)
                    {
                        alternateVsync = true;
                        //unset normal vsync if we've chosen the alternate vsync
                        vsync = false;
                    }
                }

                //TODO - whats so hard about triple buffering anyway? just enable it always, and change api to SetVsync(enable,throttle)
                //maybe even SetVsync(enable,throttlemethod) or just SetVsync(enable,throttle,advanced)

                if (LastVsyncSetting != vsync || LastVsyncSettingGraphicsControl != presentationPanel.GraphicsControl)
                {
                    if (LastVsyncSetting == null && vsync)
                    {
                        // Workaround for vsync not taking effect at startup (Intel graphics related?)
                        presentationPanel.GraphicsControl.SetVsync(false);
                    }
                    presentationPanel.GraphicsControl.SetVsync(vsync);
                    LastVsyncSettingGraphicsControl = presentationPanel.GraphicsControl;
                    LastVsyncSetting = vsync;
                }
            }

            // begin rendering on this context
            // should this have been done earlier?
            // do i need to check this on an intel video card to see if running excessively is a problem? (it used to be in the FinalTarget command below, shouldn't be a problem)
            //GraphicsControl.Begin(); // CRITICAL POINT for yabause+GL

            //TODO - auto-create and age these (and dispose when old)
            int rtCounter = 0;

            _currentFilterProgram.RenderTargetProvider = new DisplayManagerRenderTargetProvider(size => ShaderChainFrugalizers[rtCounter++].Get(size));

            GL.BeginScene();

            // run filter chain
            Texture2d    texCurr       = null;
            RenderTarget rtCurr        = null;
            bool         inFinalTarget = false;

            foreach (var step in _currentFilterProgram.Program)
            {
                switch (step.Type)
                {
                case FilterProgram.ProgramStepType.Run:
                {
                    int fi = (int)step.Args;
                    var f  = _currentFilterProgram.Filters[fi];
                    f.SetInput(texCurr);
                    f.Run();
                    var orec = f.FindOutput();
                    if (orec != null)
                    {
                        if (orec.SurfaceDisposition == SurfaceDisposition.Texture)
                        {
                            texCurr = f.GetOutput();
                            rtCurr  = null;
                        }
                    }
                    break;
                }

                case FilterProgram.ProgramStepType.NewTarget:
                {
                    var size = (Size)step.Args;
                    rtCurr = ShaderChainFrugalizers[rtCounter++].Get(size);
                    rtCurr.Bind();
                    _currentFilterProgram.CurrRenderTarget = rtCurr;
                    break;
                }

                case FilterProgram.ProgramStepType.FinalTarget:
                {
                    inFinalTarget = true;
                    rtCurr        = null;
                    _currentFilterProgram.CurrRenderTarget = null;
                    GL.BindRenderTarget(null);
                    break;
                }
                }
            }

            GL.EndScene();

            if (job.Offscreen)
            {
                job.OffscreenBb = rtCurr.Texture2d.Resolve();
                job.OffscreenBb.DiscardAlpha();
            }
            else
            {
                Debug.Assert(inFinalTarget);

                // wait for vsync to begin
                if (alternateVsync)
                {
                    dx9.AlternateVsyncPass(0);
                }

                // present and conclude drawing
                presentationPanel.GraphicsControl.SwapBuffers();

                // wait for vsync to end
                if (alternateVsync)
                {
                    dx9.AlternateVsyncPass(1);
                }

                // nope. don't do this. workaround for slow context switching on intel GPUs. just switch to another context when necessary before doing anything
                // presentationPanel.GraphicsControl.End();
            }
        }
Example #13
0
 public void TexParameter2d(Texture2d tex, TextureParameterName pname, int param)
 {
     BindTexture2d(tex);
     GL.TexParameter(TextureTarget.Texture2D, (global::OpenTK.Graphics.OpenGL.TextureParameterName)pname, param);
 }
Example #14
0
		private FilterProgram UpdateSourceInternal(JobInfo job)
		{
			//no drawing actually happens. it's important not to begin drawing on a control
			if (!job.Simulate && !job.Offscreen)
			{
				GLManager.Activate(CR_GraphicsControl);

				if (job.ChainOutsize.Width == 0 || job.ChainOutsize.Height == 0)
				{
					// this has to be a NOP, because lots of stuff will malfunction on a 0-sized viewport
					if (_currentFilterProgram != null)
					{
						UpdateSourceDrawingWork(job); //but we still need to do this, because of vsync
					}

					return null;
				}
			}

			IVideoProvider videoProvider = job.VideoProvider;
			bool simulate = job.Simulate;
			Size chainOutsize = job.ChainOutsize;

			//simulate = true;

			int[] videoBuffer = videoProvider.GetVideoBuffer();
			int bufferWidth = videoProvider.BufferWidth;
			int bufferHeight = videoProvider.BufferHeight;
			int presenterTextureWidth = bufferWidth;
			int presenterTextureHeight = bufferHeight;
			bool isGlTextureId = videoBuffer.Length == 1;

			int vw = videoProvider.VirtualWidth;
			int vh = videoProvider.VirtualHeight;

			//TODO: it is bad that this is happening outside the filter chain
			//the filter chain has the ability to add padding...
			//for now, we have to have some hacks. this could be improved by refactoring the filter setup hacks to be in one place only though
			//could the PADDING be done as filters too? that would be nice.
			var fCoreScreenControl = CreateCoreScreenControl();
			if(fCoreScreenControl != null)
			{
				var sz = fCoreScreenControl.PresizeInput("default", new Size(bufferWidth, bufferHeight));
				presenterTextureWidth = vw = sz.Width;
				presenterTextureHeight = vh = sz.Height;
			}

			if (Global.Config.DispFixAspectRatio)
			{
				if (Global.Config.DispManagerAR == EDispManagerAR.System)
				{
					//Already set
				}
				if (Global.Config.DispManagerAR == EDispManagerAR.Custom)
				{
					//not clear what any of these other options mean for "screen controlled" systems
					vw = Global.Config.DispCustomUserARWidth;
					vh = Global.Config.DispCustomUserARHeight;
				}
				if (Global.Config.DispManagerAR == EDispManagerAR.CustomRatio)
				{
					//not clear what any of these other options mean for "screen controlled" systems
					FixRatio(Global.Config.DispCustomUserArx, Global.Config.DispCustomUserAry, videoProvider.BufferWidth, videoProvider.BufferHeight, out vw, out vh);
				}
			}

			var padding = CalculateCompleteContentPadding(true,false);
			vw += padding.Horizontal;
			vh += padding.Vertical;

			BitmapBuffer bb = null;
			Texture2d videoTexture = null;
			if (!simulate)
			{
				if (isGlTextureId)
				{
					//FYI: this is a million years from happening on n64, since it's all geriatric non-FBO code
					//is it workable for saturn?
					videoTexture = GL.WrapGLTexture2d(new IntPtr(videoBuffer[0]), bufferWidth, bufferHeight);
				}
				else
				{
					//wrap the VideoProvider data in a BitmapBuffer (no point to refactoring that many IVideoProviders)
					bb = new BitmapBuffer(bufferWidth, bufferHeight, videoBuffer);
					bb.DiscardAlpha();

					//now, acquire the data sent from the videoProvider into a texture
					videoTexture = VideoTextureFrugalizer.Get(bb);

					// lets not use this. lets define BizwareGL to make clamp by default (TBD: check opengl)
					//GL.SetTextureWrapMode(videoTexture, true);
				}
			}

			// record the size of what we received, since lua and stuff is gonna want to draw onto it
			currEmuWidth = bufferWidth;
			currEmuHeight = bufferHeight;

			//build the default filter chain and set it up with services filters will need
			Size chainInsize = new Size(bufferWidth, bufferHeight);

			var filterProgram = BuildDefaultChain(chainInsize, chainOutsize, job.IncludeOSD, job.IncludeUserFilters);
			filterProgram.GuiRenderer = Renderer;
			filterProgram.GL = GL;

			//setup the source image filter
			Filters.SourceImage fInput = filterProgram["input"] as Filters.SourceImage;
			fInput.Texture = videoTexture;

			//setup the final presentation filter
			Filters.FinalPresentation fPresent = filterProgram["presentation"] as Filters.FinalPresentation;
			if (fPresent != null)
			{
				fPresent.VirtualTextureSize = new Size(vw, vh);
				fPresent.TextureSize = new Size(presenterTextureWidth, presenterTextureHeight);
				fPresent.BackgroundColor = videoProvider.BackgroundColor;
				fPresent.GuiRenderer = Renderer;
				fPresent.Flip = isGlTextureId;
				fPresent.Config_FixAspectRatio = Global.Config.DispFixAspectRatio;
				fPresent.Config_FixScaleInteger = Global.Config.DispFixScaleInteger;
				fPresent.Padding = ClientExtraPadding;
				fPresent.AutoPrescale = Global.Config.DispAutoPrescale;

				fPresent.GL = GL;
			}

			//POOPY. why are we delivering the GL context this way? such bad
			Filters.ScreenControlNDS fNDS = filterProgram["CoreScreenControl"] as Filters.ScreenControlNDS;
			if (fNDS != null)
			{
				fNDS.GuiRenderer = Renderer;
				fNDS.GL = GL;
			}

			filterProgram.Compile("default", chainInsize, chainOutsize, !job.Offscreen);

			if (simulate)
			{
			}
			else
			{
				_currentFilterProgram = filterProgram;
				UpdateSourceDrawingWork(job);
			}

			// cleanup:
			bb?.Dispose();

			return filterProgram;
		}
Example #15
0
		public void AttachDepth(Texture2d texture)
		{
			AttachDepth(texture, 0);
		}
Example #16
0
        static unsafe void Main(string[] args)
        {
            BizHawk.Bizware.BizwareGL.IGL igl = new BizHawk.Bizware.BizwareGL.Drivers.OpenTK.IGL_TK();

            List <Art> testArts = new List <Art>();
            ArtManager am       = new ArtManager(igl);

            foreach (var name in typeof(Program).Assembly.GetManifestResourceNames())
            {
                if (name.Contains("flame"))
                {
                    testArts.Add(am.LoadArt(typeof(Program).Assembly.GetManifestResourceStream(name)));
                }
            }
            var smile = am.LoadArt(typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.smile.png"));

            am.Close(true);
            StringRenderer sr;

            using (var xml = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.courier16px.fnt"))
                using (var tex = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.courier16px_0.png"))
                    sr = new StringRenderer(igl, xml, tex);

            GuiRenderer gr = new GuiRenderer(igl);

            TestForm tf = new TestForm();
            RetainedGraphicsControl c = new RetainedGraphicsControl(igl);

            tf.Controls.Add(c);
            c.Dock          = System.Windows.Forms.DockStyle.Fill;
            tf.FormClosing += (object sender, System.Windows.Forms.FormClosingEventArgs e) =>
            {
                tf.Controls.Remove(c);
                c.Dispose();
                c = null;
            };
            tf.Show();

            //tf.Paint += (object sender, PaintEventArgs e) => c.Refresh();

            c.SetVsync(false);

            //create a render target
            RenderTarget rt = igl.CreateRenderTarget(60, 60);

            rt.Bind();
            igl.SetClearColor(Color.Blue);
            igl.Clear(ClearBufferMask.ColorBufferBit);
            gr.Begin(60, 60, true);
            gr.Draw(smile);
            gr.End();
            rt.Unbind();

            Texture2d rttex2d = igl.LoadTexture(rt.Texture2d.Resolve());

            //test retroarch shader
            RenderTarget rt2 = igl.CreateRenderTarget(240, 240);

            rt2.Bind();
            igl.SetClearColor(Color.CornflowerBlue);
            igl.Clear(ClearBufferMask.ColorBufferBit);
            RetroShader shader;

            using (var stream = typeof(Program).Assembly.GetManifestResourceStream("BizHawk.Bizware.Test.TestImages.4xSoft.glsl"))
                shader = new RetroShader(igl, new System.IO.StreamReader(stream).ReadToEnd());
            igl.SetBlendState(igl.BlendNone);
            shader.Run(rttex2d, new Size(60, 60), new Size(240, 240), true);


            bool running = true;

            c.MouseClick += (object sender, MouseEventArgs e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    running ^= true;
                }
                if (e.Button == MouseButtons.Right)
                {
                    c.Retain ^= true;
                }
            };

            DateTime start  = DateTime.Now;
            int      wobble = 0;

            for (; ;)
            {
                if (c == null)
                {
                    break;
                }

                if (running)
                {
                    c.Begin();

                    igl.SetClearColor(Color.Red);
                    igl.Clear(ClearBufferMask.ColorBufferBit);

                    int frame = (int)((DateTime.Now - start).TotalSeconds) % testArts.Count;

                    gr.Begin(c.ClientSize.Width, c.ClientSize.Height);
                    gr.SetBlendState(igl.BlendNormal);

                    gr.SetModulateColor(Color.Green);
                    gr.RectFill(250, 0, 16, 16);

                    gr.SetBlendState(igl.BlendNone);
                    gr.Draw(rttex2d, 0, 20);
                    gr.SetBlendState(igl.BlendNormal);

                    sr.RenderString(gr, 0, 0, "?? fps");
                    gr.SetModulateColor(Color.FromArgb(255, 255, 255, 255));
                    gr.SetCornerColor(0, OpenTK.Graphics.Color4.Red);
                    gr.Draw(rt2.Texture2d, 0, 0);
                    gr.SetCornerColor(0, OpenTK.Graphics.Color4.White);
                    gr.SetModulateColorWhite();
                    gr.Modelview.Translate((float)Math.Sin(wobble / 360.0f) * 50, 0);
                    gr.Modelview.Translate(100, 100);
                    gr.Modelview.Push();
                    gr.Modelview.Translate(testArts[frame].Width, 0);
                    gr.Modelview.Scale(-1, 1);
                    wobble++;
                    gr.SetModulateColor(Color.Yellow);
                    gr.DrawFlipped(testArts[frame], true, false);
                    gr.SetModulateColorWhite();
                    gr.Modelview.Pop();
                    gr.SetBlendState(igl.BlendNormal);
                    gr.Draw(smile);

                    gr.End();


                    c.SwapBuffers();
                    c.End();
                }

                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(0);
            }
        }
Example #17
0
        public void SetTextureWrapMode(Texture2d tex, bool clamp)
        {
            var tw = tex.Opaque as TextureWrapper;

            tw.WrapClamp = clamp ? TextureAddress.Clamp : TextureAddress.Wrap;
        }
Example #18
0
		public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
		{
			var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
			var g = Gdi.GetCurrentGraphics();
			PrepDraw(g, tex);
			SetupMatrix(g);

			float x0 = u0 * tex.Width;
			float y0 = v0 * tex.Height;
			float x1 = u1 * tex.Width;
			float y1 = v1 * tex.Height;

			sd.PointF[] destPoints = new sd.PointF[] {
				new sd.PointF(x,y),
				new sd.PointF(x+w,y),
				new sd.PointF(x,y+h),
			};

			g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(x0, y0, x1 - x0, y1 - y0), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
			g.Transform = new sd.Drawing2D.Matrix(); //.Reset() doesnt work ? ?
		}
 public void SetPipelineUniformSampler(PipelineUniform uniform, Texture2d tex)
 {
 }
Example #20
0
		void PrepDraw(sd.Graphics g, Texture2d tex)
		{
			var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
			//TODO - we can support bicubic for the final presentation..
			if ((int)tw.MagFilter != (int)tw.MinFilter)
				throw new InvalidOperationException("tw.MagFilter != tw.MinFilter");
			if (tw.MagFilter == TextureMagFilter.Linear)
				g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
			if (tw.MagFilter == TextureMagFilter.Nearest)
				g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;


			//---------

			if (CurrentBlendState == Gdi.BlendNormal)
			{
				g.CompositingMode = sd.Drawing2D.CompositingMode.SourceOver;
				g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default; //?

				//CurrentImageAttributes.ClearColorMatrix(ColorAdjustType.Bitmap);
			}
			else
			//if(CurrentBlendState == Gdi.BlendNoneCopy)
			//if(CurrentBlendState == Gdi.BlendNoneOpaque)
			{
				g.CompositingMode = sd.Drawing2D.CompositingMode.SourceCopy;
				g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;

				//WARNING : DO NOT USE COLOR MATRIX TO WIPE THE ALPHA
				//ITS SOOOOOOOOOOOOOOOOOOOOOOOOOOOO SLOW
				//instead, we added kind of hacky support for 24bpp images
			}

		}
        public void LoadTextureData(Texture2d tex, BitmapBuffer bmp)
        {
            var tw = tex.Opaque as GDIPTextureWrapper;

            bmp.ToSysdrawingBitmap(tw.SDBitmap);
        }
Example #22
0
        unsafe void DrawInternal(Texture2d tex, float x, float y, float w, float h)
        {
            var tw = Gdi.TextureWrapperForTexture(tex);
            var g = Gdi.GetCurrentGraphics();
            PrepDraw(g, tw);

            //a little bit of a fastpath.. I think it's safe
            //if (w == tex.Width && h == tex.Height && x == (int)x && y == (int)y)
            //  g.DrawImageUnscaled(tw.SDBitmap, (int)x, (int)y);
            //else
            {
                sd.PointF[] destPoints = new sd.PointF[] {
                    new sd.PointF(x,y),
                    new sd.PointF(x+w,y),
                    new sd.PointF(x,y+h),
                };
                //g.DrawImage(tw.SDBitmap, x, y, w, h); //original
                g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(0, 0, tex.Width, tex.Height), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
            }
        }
        public void FreeTexture(Texture2d tex)
        {
            var tw = tex.Opaque as GDIPTextureWrapper;

            tw.Dispose();
        }
Example #24
0
 public unsafe BitmapBuffer ResolveTexture2d(Texture2d tex)
 {
     //todo
     return(null);
 }
 public void SetTextureWrapMode(Texture2d tex, bool clamp)
 {
 }
Example #26
0
 public TextureWrapper TextureWrapperForTexture(Texture2d tex)
 {
     return(ResourceIDs.Lookup[tex.Id.ToInt32()] as TextureWrapper);
 }
Example #27
0
 public void SetInput(Texture2d tex)
 {
     InputTexture = tex;
 }
Example #28
0
		/// <summary>
		/// Attach a 2D texture image to color buffer.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="Texture2d"/> which will be used for read/write operation on this RenderFrambuffer.
		/// </param>
		public void AttachColor(Texture2d texture)
		{
			AttachColor(texture, 0, 0);
		}
Example #29
0
 // filter actions
 protected void YieldOutput(Texture2d tex)
 {
     _outputTexture = tex;
 }
Example #30
0
		/// <summary>
		/// Attach a 2D texture image to color buffer.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="Texture"/> which will be used for read/write operation on this RenderFrambuffer.
		/// </param>
		/// <param name="level">
		/// A <see cref="UInt32"/> that specify the texture level to bind.
		/// </param>
		/// <param name="attachmentIndex">
		/// A <see cref="UInt32"/> that specify the framebuffer color attachment index.
		/// </param>
		public void AttachColor(Texture2d texture, uint attachmentIndex, uint level)
		{
			if ((level != 0) && (level > (uint)Math.Log(level, 2.0)))
				throw new ArgumentException("level greater than maximum allowed");

			AttachColor(new RenderTextureAttachment(texture, level), attachmentIndex);
		}
Example #31
0
        private void VisionControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
        {
            // Create GL context abstraction
            _GraphicsContext = new GraphicsContext(e.DeviceContext, e.RenderContext);

            // Create texture
            _FramebufferTexture = new Texture2d(1024, 1024, PixelLayout.RGB24);
            _FramebufferTexture.SamplerParams.MagFilter = TextureMagFilter.Linear;
            _FramebufferTexture.SamplerParams.MinFilter = TextureMinFilter.Linear;
            _FramebufferTexture.Create(_GraphicsContext);

            // Create framebuffer
            _Framebuffer = new Framebuffer();
            _Framebuffer.AttachColor(0, _FramebufferTexture);
            _Framebuffer.Create(_GraphicsContext);

            // Create shader (standard)
            _ProgramStd = _GraphicsContext.CreateProgram("OpenGL.Standard");
            _ProgramStd.Create(_GraphicsContext);

            // Create program (standard + texture)
            _ProgramStdTex = _GraphicsContext.CreateProgram("OpenGL.Standard+Texture");
            _ProgramStdTex.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> quadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            quadBuffer.Create(new Vertex2f[] {
                new Vertex2f(-0.5f, +0.5f),
                new Vertex2f(-0.5f, -0.5f),
                new Vertex2f(+0.5f, +0.5f),
                new Vertex2f(+0.5f, -0.5f),
            });

            _ArraysQuad = new VertexArrays();
            _ArraysQuad.SetArray(quadBuffer, VertexArraySemantic.Position);
            _ArraysQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysQuad.Create(_GraphicsContext);

            // Create vertex arrays (square)
            ArrayBuffer <Vertex2f> postquadBuffer = new ArrayBuffer <Vertex2f>(BufferUsage.StaticDraw);

            postquadBuffer.Create(new Vertex2f[] {
                new Vertex2f(0.0f, 1.0f),
                new Vertex2f(0.0f, 0.0f),
                new Vertex2f(1.0f, 1.0f),
                new Vertex2f(1.0f, 0.0f),
            });

            _ArraysPostQuad = new VertexArrays();
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.Position);
            _ArraysPostQuad.SetArray(postquadBuffer, VertexArraySemantic.TexCoord);
            _ArraysPostQuad.SetElementArray(PrimitiveType.TriangleStrip);
            _ArraysPostQuad.Create(_GraphicsContext);

            // Create vertex arrays (optical markers)
            _BufferOpticalMarkers = new ArrayBuffer <Vertex2f>(BufferUsage.DynamicDraw);
            _BufferOpticalMarkers.Create(10000 * 2);

            _ArraysOpticalMarkers = new VertexArrays();
            _ArraysOpticalMarkers.SetArray(_BufferOpticalMarkers, VertexArraySemantic.Position);
            _ArraysOpticalMarkers.SetElementArray(PrimitiveType.Lines);
            _ArraysOpticalMarkers.Create(_GraphicsContext);
        }
Example #32
0
		public void AttachDepth(Texture2d texture, uint level)
		{
			AttachDepth(new RenderTextureAttachment(texture, level));
		}
Example #33
0
        private void SetSphereMaterial(SceneObjectGeometry sphere, string material)
        {
            MaterialState sphereMaterial = new MaterialState();

            sphereMaterial.FrontMaterial           = new MaterialState.Material(ColorRGBAF.ColorWhite);
            sphereMaterial.FrontMaterial.Ambient   = ColorRGBAF.ColorWhite * 0.2f;
            sphereMaterial.FrontMaterial.Diffuse   = ColorRGBAF.ColorWhite * 0.8f;
            sphereMaterial.FrontMaterial.Specular  = ColorRGBAF.ColorWhite * 1.0f;
            sphereMaterial.FrontMaterial.Shininess = 32.0f;

            sphere.ObjectState.DefineState(sphereMaterial);

            if (material == null)
            {
                return;
            }

            string basePath = Path.Combine("Data", "PhotosculptTextures");
            string textureFilename, texturePath;

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "diffuse");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialDiffuseTexture  = texture;
                    sphereMaterial.FrontMaterialDiffuseTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "normal");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialNormalTexture  = texture;
                    sphereMaterial.FrontMaterialNormalTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "specular");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialSpecularTexture  = texture;
                    sphereMaterial.FrontMaterialSpecularTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "ambientocclusion");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    texture.RequestMipmapsCreation();
                    texture.WrapCoordR = Texture.Wrap.MirroredRepeat;
                    texture.WrapCoordS = Texture.Wrap.MirroredRepeat;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialAmbientTexture  = texture;
                    sphereMaterial.FrontMaterialAmbientTexCoord = 0;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }

            textureFilename = String.Format("photosculpt-{0}-{1}.jpg", material, "displace");
            texturePath     = Path.Combine(basePath, textureFilename);
            if (File.Exists(texturePath))
            {
                try {
                    Image     textureImage = ImageCodec.Instance.Load(texturePath);
                    Texture2d texture      = new Texture2d();

                    // texture.RequestMipmapsCreation();
                    texture.WrapCoordR     = Texture.Wrap.Repeat;
                    texture.WrapCoordS     = Texture.Wrap.Repeat;
                    texture.MinFilter      = Texture.Filter.Nearest;
                    texture.MagFilter      = Texture.Filter.Nearest;
                    texture.MipmapMaxLevel = 0;
                    texture.Create(textureImage);

                    sphereMaterial.FrontMaterialDisplacementTexture = texture;
                    // sphereMaterial.FrontMaterialDisplacementTexCoord = 0;
                    sphereMaterial.FrontMaterialDisplacementFactor = 0.2f;
                } catch (Exception exception) {
                    throw new InvalidOperationException(String.Format("unable to load texture {0}", texturePath), exception);
                }
            }
        }
Example #34
0
        public void FreeTexture(Texture2d tex)
        {
            var tw = (TextureWrapper)tex.Opaque;

            tw.Texture.Dispose();
        }
Example #35
0
 public void SetTexture(Texture2d tex)
 {
     Texture = tex;
 }
Example #36
0
 private void BindTexture2d(Texture2d tex)
 {
     GL.BindTexture(TextureTarget.Texture2D, (int)tex.Opaque);
 }
Example #37
0
 public void Draw(Texture2d tex)
 {
     DrawInternal(tex, 0, 0, tex.Width, tex.Height);
 }
Example #38
0
		public void Draw(Texture2d tex) { DrawInternal(tex, 0, 0, tex.Width, tex.Height); }
Example #39
0
 public void Draw(Texture2d tex, float x, float y)
 {
     DrawInternal(tex, x, y, tex.Width, tex.Height);
 }
Example #40
0
		public void Draw(Texture2d art, float x, float y, float width, float height)
		{
			DrawInternal(art, x, y, width, height);
		}
Example #41
0
 public void Draw(Texture2d art, float x, float y, float width, float height)
 {
     DrawInternal(art, x, y, width, height);
 }
Example #42
0
		unsafe void DrawInternal(Texture2d tex, float x, float y, float w, float h)
		{
			var g = Gdi.GetCurrentGraphics();
			PrepDraw(g, tex);

			SetupMatrix(g);

			sd.PointF[] destPoints = new sd.PointF[] {
				new sd.PointF(x,y),
				new sd.PointF(x+w,y),
				new sd.PointF(x,y+h),
			};

			var tw = tex.Opaque as IGL_GdiPlus.TextureWrapper;
			g.PixelOffsetMode = sd.Drawing2D.PixelOffsetMode.Half;
			g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(0, 0, tex.Width, tex.Height), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
			g.Transform = new sd.Drawing2D.Matrix(); //.Reset() doesnt work ? ?
		}
Example #43
0
 public void FreeTexture(Texture2d tex)
 {
     ResourceIDs.Free(tex.Id);
 }
Example #44
0
 public void BindTexture2d(Texture2d tex)
 {
     CurrentBoundTexture = tex;
 }
Example #45
0
        public void DrawSubrect(Texture2d tex, float x, float y, float w, float h, float u0, float v0, float u1, float v1)
        {
            var tw = Gdi.TextureWrapperForTexture(tex);
            var g = Gdi.GetCurrentGraphics();
            PrepDraw(g, tw);
            float x0 = u0 * tex.Width;
            float y0 = v0 * tex.Height;
            float x1 = u1 * tex.Width;
            float y1 = v1 * tex.Height;
            sd.PointF[] destPoints = new sd.PointF[] {
                new sd.PointF(x,y),
                new sd.PointF(x+w,y),
                new sd.PointF(x,y+h),
            };

            g.DrawImage(tw.SDBitmap, destPoints, new sd.RectangleF(x0, y0, x1 - x0, y1 - y0), sd.GraphicsUnit.Pixel, CurrentImageAttributes);
            //g.DrawImage(tw.SDBitmap, 0, 0); //test
        }