protected void Blit(D3D9.Device d3d9Device, HardwarePixelBuffer rsrc, BasicBox srcBox, BasicBox dstBox, BufferResources srcBufferResources, BufferResources dstBufferResources) { if (dstBufferResources.Surface != null && srcBufferResources.Surface != null) { // Surface-to-surface var dsrcRect = ToD3DRectangle(srcBox); var ddestRect = ToD3DRectangle(dstBox); var srcDesc = srcBufferResources.Surface.Description; // If we're blitting from a RTT, try GetRenderTargetData // if we're going to try to use GetRenderTargetData, need to use system mem pool // romeoxbm: not used even in Ogre //var tryGetRenderTargetData = false; if ((srcDesc.Usage & D3D9.Usage.RenderTarget) != 0 && srcDesc.MultiSampleType == D3D9.MultisampleType.None) { // Temp texture var tmptex = new D3D9.Texture(d3d9Device, srcDesc.Width, srcDesc.Height, 1, // 1 mip level ie topmost, generate no mipmaps 0, srcDesc.Format, D3D9.Pool.SystemMemory); var tmpsurface = tmptex.GetSurfaceLevel(0); d3d9Device.GetRenderTargetData(srcBufferResources.Surface, tmpsurface); D3D9.Surface.FromSurface(dstBufferResources.Surface, tmpsurface, D3D9.Filter.Default, 0, dsrcRect, ddestRect); tmpsurface.SafeDispose(); tmptex.SafeDispose(); return; } // Otherwise, try the normal method D3D9.Surface.FromSurface(dstBufferResources.Surface, srcBufferResources.Surface, D3D9.Filter.Default, 0, dsrcRect, ddestRect); } else if (dstBufferResources.Volume != null && srcBufferResources.Volume != null) { // Volume-to-volume var dsrcBox = ToD3DBox(srcBox); var ddestBox = ToD3DBox(dstBox); D3D9.Volume.FromVolume(dstBufferResources.Volume, srcBufferResources.Volume, D3D9.Filter.Default, 0, dsrcBox, ddestBox); } else { // Software fallback base.Blit(rsrc, srcBox, dstBox); } }
protected void LoadFromSource(D3D9.Device d3D9Device) { //Entering critical section this.LockDeviceAccess(); D3D9.ShaderBytecode microcode = null; // Create the shader // Assemble source into microcode try { microcode = D3D9.ShaderBytecode.Assemble(Source, null, // no #define support null, // no #include support 0); // standard compile options } catch (DX.CompilationException e) { throw new AxiomException("Cannot assemble D3D9 shader {0} Errors:\n{1}", e, Name, e.Message); } LoadFromMicrocode(d3D9Device, microcode); microcode.SafeDispose(); //Leaving critical section this.UnlockDeviceAccess(); }
public Menu(Device device, Point location, Orientation orientation, params MenuItem[] items) { Log.Trace("Menu()"); this.Device = device; Items = new List <MenuItem>(items); Location = location; Orientation = orientation; ForeColor = Color.White; SelectedForeColor = Color.Red; Font = new Font ("Arial", 12, FontStyle.Bold); ItemPadding = 15; DrawingFont = new SharpDX.Direct3D9.Font (device, Font); IncrementMenuKey = new Key (Keys.OemCloseBrackets); DecrementMenuKey = new Key (Keys.OemOpenBrackets); IncrementValueKey = new Key (Keys.PageUp); DecrementValueKey = new Key (Keys.PageDown); ResetToZeroKey = new Key (Keys.End); IncrementMenuKey.OnJustPressed += (sender, args) => { SelectedIndex = (SelectedIndex + 1).Clamp(SelectedIndex, Items.Count - 1); }; DecrementMenuKey.OnJustPressed += (sender, args) => { SelectedIndex = (SelectedIndex - 1).Clamp(0, SelectedIndex); }; IncrementValueKey.OnHold += (sender, args) => Items[SelectedIndex].IncrementValue(2); DecrementValueKey.OnHold += (sender, args) => Items[SelectedIndex].DecrementValue(2); ResetToZeroKey.OnJustPressed += (sender, args) => { Items[SelectedIndex].Value = 0; }; }
/// <summary> /// Initializes a new instance of the <see cref="DeviceContext9"/> class. /// </summary> /// <param name="handle">The window handle to associate with the device.</param> /// <param name="settings">The settings used to configure the device.</param> internal DeviceContext9(IntPtr handle, DeviceSettings9 settings) { if (handle == IntPtr.Zero) throw new ArgumentException("Value must be a valid window handle.", "handle"); if (settings == null) throw new ArgumentNullException("settings"); this.settings = settings; PresentParameters = new PresentParameters { BackBufferFormat = Format.X8R8G8B8, BackBufferCount = 1, BackBufferWidth = settings.Width, BackBufferHeight = settings.Height, MultiSampleType = MultisampleType.None, SwapEffect = SwapEffect.Discard, EnableAutoDepthStencil = true, AutoDepthStencilFormat = Format.D16, PresentFlags = PresentFlags.DiscardDepthStencil, PresentationInterval = PresentInterval.Default, Windowed = true, DeviceWindowHandle = handle }; direct3D = new Direct3D(); Device = new Device(direct3D, settings.AdapterOrdinal, DeviceType.Hardware, handle, settings.CreationFlags, PresentParameters); }
public void CreateBuffer(D3D9.Device d3d9Device, D3D9.Pool ePool) { // Find the vertex buffer of this device. BufferResources bufferResources; if (this._mapDeviceToBufferResources.TryGetValue(d3d9Device, out bufferResources)) { bufferResources.VertexBuffer.SafeDispose(); } else { bufferResources = new BufferResources(); this._mapDeviceToBufferResources.Add(d3d9Device, bufferResources); } bufferResources.VertexBuffer = null; bufferResources.IsOutOfDate = true; bufferResources.LockOffset = 0; bufferResources.LockLength = sizeInBytes; bufferResources.LockOptions = BufferLocking.Normal; bufferResources.LastUsedFrame = Root.Instance.NextFrameNumber; // Create the vertex buffer try { bufferResources.VertexBuffer = new D3D9.VertexBuffer(d3d9Device, sizeInBytes, D3D9Helper.ConvertEnum(usage), 0, ePool); } catch (Exception ex) { throw new AxiomException("Cannot restore D3D9 vertex buffer", ex); } this._bufferDesc = bufferResources.VertexBuffer.Description; }
public void Render(Device device, float w, float h, float scale) { if (_handle != IntPtr.Zero) { AnimatedModel_Render(_handle, device.NativePointer, w, h, scale); } }
public BlurComponent(Device graphics, int size) { _graphics = graphics; Dims = size; Format = Format.A8R8G8B8; _sampleOffsetsHoriz = new Vector4D[SampleCount]; _sampleOffsetsVert = new Vector4D[SampleCount]; _sampleWeightsHoriz = new float[SampleCount]; _sampleWeightsVert = new float[SampleCount]; int width = Dims - 5; int height = Dims - 5; SetBlurEffectParameters(1.0f / width, 0, ref _sampleOffsetsHoriz, ref _sampleWeightsHoriz); SetBlurEffectParameters(0, 1.0f / height, ref _sampleOffsetsVert, ref _sampleWeightsVert); _effect = new GaussianBlurEffect(_graphics); OutputTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default); _intermediateTexture = new Texture(_graphics, Dims, Dims, 1, Usage.RenderTarget, Format, Pool.Default); _sprite = new Sprite(_graphics); }
public void Render(Device device, float w, float h, float xTrans, float yTrans, float scale) { ParticleSystem_SetObjPos(ScreenPosition.X, ScreenPosition.Y); ParticleSystem_SetPos(_handle, ScreenPosition.X, ScreenPosition.Y); ParticleSystem_Render(device.NativePointer, _handle, w, h, xTrans, yTrans, scale); }
public bool RenderVideo(Device device, Color background, string fileName) { ParticleSystem_SetObjPos(ScreenPosition.X, ScreenPosition.Y); ParticleSystem_SetPos(_handle, ScreenPosition.X, ScreenPosition.Y); return ParticleSystem_RenderVideo(device.NativePointer, _handle, background.ToArgb(), fileName, 60); }
internal ModelMesh(Mesh sourceMesh, Device device, VertexBuffer vertexBuffer, int numVertices, IndexBuffer indexBuffer, int primitiveCount, Matrix3D world, Material material) { SourceMesh = sourceMesh; _device = device; _vertexBuffer = vertexBuffer; _numVertices = numVertices; _indexBuffer = indexBuffer; _primitiveCount = primitiveCount; _effect = new SimpleEffect(device) { World = world, AmbientLightColor = new ColorRgbF(0.1f, 0.1f, 0.1f), DiffuseColor = material.DiffuseColor, SpecularColor = material.SpecularColor, SpecularPower = material.Shininess, Alpha = material.Transparency }; if (!string.IsNullOrEmpty(material.DiffuseTextureName)) _effect.DiffuseTexture = Texture.FromFile(device, material.DiffuseTextureName, Usage.None, Pool.Default); _effect.CurrentTechnique = "RenderScene"; Opaque = (material.Transparency == 1.0f); }
/// <summary> /// Creates the VertexBuffer for the quad /// </summary> /// <param name="graphicsDevice">The GraphicsDevice to use</param> public void CreateFullScreenQuad(Device graphicsDevice) { // Create a vertex buffer for the quad, and fill it in m_vertexBuffer = new VertexBuffer(graphicsDevice, MyVertexFormatFullScreenQuad.Stride * 4, Usage.WriteOnly, VertexFormat.None, Pool.Default); m_vertexBuffer.DebugName = "FullScreenQuad"; MyVertexFormatFullScreenQuad[] vbData = new MyVertexFormatFullScreenQuad[4]; // Upper right vbData[0].Position = new Vector3(1, 1, 1); vbData[0].TexCoordAndCornerIndex = new Vector3(1, 0, 1); // Lower right vbData[1].Position = new Vector3(1, -1, 1); vbData[1].TexCoordAndCornerIndex = new Vector3(1, 1, 2); // Upper left vbData[2].Position = new Vector3(-1, 1, 1); vbData[2].TexCoordAndCornerIndex = new Vector3(0, 0, 0); // Lower left vbData[3].Position = new Vector3(-1, -1, 1); vbData[3].TexCoordAndCornerIndex = new Vector3(0, 1, 3); m_vertexBuffer.SetData(vbData); }
public Poll(Device device, float height) { _height = height; Texture = Texture ?? Texture.FromFile(device, "Assets/Textures/poll.png"); TextureTop = TextureTop ?? Texture.FromFile(device, "Assets/Textures/poll_top.png"); _topFlagLocation = new Vector3(-0.5f, 0.25f + (height / 2 - 1.5f), 0); _flag = Add(new Sprite(device, "flag", 1)); _flag.Translate(_topFlagLocation); Add(new GameObject { new MeshRenderer { Mesh = new TexturedCube(device, 0.5f, 0.5f, 0.5f, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV), Material = new TextureMaterial(TextureTop, false) } }).Translate(0, 0.25f + (height / 2 - 0.5f), 0); Add(new GameObject { new MeshRenderer { Mesh = new TexturedCube(device, 0.2f, height - 0.5f, 0.2f, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV, DefaultUV), Material = new TextureMaterial(Texture, false) } }).Translate(0, -0.25f, 0); Add(new Trigger(SlideDown, 0.5f, height, 0.5f, Vector3.Zero)); }
unsafe static Tuple<CUDADevice, IntPtr> Generate(D3D9Device d3d9Device) { var cuContext = IntPtr.Zero; var cuDevice = -1; CUDAInterop.cuSafeCall(CUDAInterop.cuD3D9CtxCreate(&cuContext, &cuDevice, 0u, d3d9Device.NativePointer)); return (new Tuple<CUDADevice, IntPtr>(CUDADevice.DeviceDict[cuDevice], cuContext)); }
protected GraphicsResource(Device graphicsDevice, string name) : base(name) { if (graphicsDevice == null) throw new ArgumentNullException("graphicsDevice"); GraphicsDevice = graphicsDevice; }
private void InitGrabber() { try { this.pixelFormat = PixelFormat.Format32bppRgb; boundsRect = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT); var format = SharpDX.Direct3D9.Format.A8R8G8B8; SharpDX.Direct3D9.PresentParameters present_params = new SharpDX.Direct3D9.PresentParameters(); present_params.Windowed = true; present_params.BackBufferFormat = format; present_params.SwapEffect = SharpDX.Direct3D9.SwapEffect.Discard; present_params.BackBufferWidth = WIDTH; present_params.BackBufferHeight = HEIGHT; dx9Device = new SharpDX.Direct3D9.Device(new SharpDX.Direct3D9.Direct3D(), 0, SharpDX.Direct3D9.DeviceType.Hardware, IntPtr.Zero, SharpDX.Direct3D9.CreateFlags.HardwareVertexProcessing, present_params); dx9Device.SetRenderState(RenderState.CullMode, Cull.None); dx9Device.SetRenderState(RenderState.Lighting, false); dx9Device.SetRenderState(RenderState.AntialiasedLineEnable, false); } catch (SharpDX.SharpDXException dxe) { LdpLog.Error("SharpDX InitializeDX9\n" + dxe.Message); } catch (Exception ex) { LdpLog.Error("InitializeDX9\n" + ex.Message); } }
public virtual SharpDX.Direct3D9.Device CreateDevice(GraphicsDeviceInformation deviceInformation) { //var device = //GraphicsDevice.New(deviceInformation.Adapter, deviceInformation.DeviceCreationFlags); // Create Device //SharpDX.Direct3D9.Direct3D direct3D = new SharpDX.Direct3D9.Direct3D(); PresentParameters p = deviceInformation.PresentationParameters; p.DeviceWindowHandle = MainWindow.NativeWindow.Handle; deviceInformation.PresentationParameters = p; SharpDX.Direct3D9.Device device = null; //try { device = new SharpDX.Direct3D9.Device(GraphicsAdapter.D3D, deviceInformation.Adapter.AdapterOrdinal, DeviceType.Hardware, p.DeviceWindowHandle, CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded, deviceInformation.PresentationParameters); } /*catch * { * } */ //device.Presenter = new SwapChainGraphicsPresenter(device, deviceInformation.PresentationParameters); return(device); }
internal void RecursiveSetViewportImage(ViewportImage viewportImage) { if (viewportImage == null) { this.DisposeDisposables(); this.viewportImage = null; this.graphicsDevice = null; this.layer2D = null; Children.viewportImage = null; } else { this.graphicsDevice = viewportImage.GraphicsDevice; this.layer2D = viewportImage.Layer2D; OnViewportImageChanged(viewportImage); BindToViewportImage(); Children.viewportImage = viewportImage; this.RecreateDisposables(); } foreach (Model3D model in this.Children) { model.RecursiveSetViewportImage(viewportImage); } // TODO Set target on all children, checking for maximum depth or // circular dependencies }
private void Form1_Load(object sender, EventArgs e) { direct3dInterface = new Direct3D(); PresentParameters[] paramters = new PresentParameters[1]; paramters[0].Windowed = true; paramters[0].SwapEffect = SwapEffect.Discard; paramters[0].DeviceWindowHandle = this.Handle; direct3dDevice = new Device(direct3dInterface, 0, DeviceType.Hardware, this.Handle, CreateFlags.SoftwareVertexProcessing, paramters); if (direct3dDevice == null) { MessageBox.Show("Error: Can not initialize Direct3D Device", Name, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Vertex[] vertices = new Vertex[] { new Vertex(0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f), new Vertex(0.5f, -.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f), new Vertex(-.5f, -.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f), }; int bufferSize = 3 * Marshal.SizeOf<CustomVertex>(); vertexBuffer = new VertexBuffer(direct3dDevice, bufferSize, Usage.None, vertexFormat, Pool.Managed); tmrUpdate.Start(); }
/// <summary> /// Copies Crosire's D3D8To9 and hooks the DX9 device creation. /// </summary> /// <param name="dllDirectory">Directory containing Crosire's d3d8to9.</param> public void HookDevice(string dllDirectory) { // Copy crosire's d3d8to9 to game directory and then load it. (Game should use D3D9 now). if (!File.Exists("d3d8.dll")) { File.Copy(dllDirectory + $"\\d3d8.dll", "d3d8.dll", true); } // Load Crosire's D3D8To9 (which in turn loads D3D9 internally) LoadLibraryW("d3d8.dll"); // Get our D3D Interface VTable using (Direct3D direct3D = new Direct3D()) using (Form renderForm = new Form()) using (SharpDX.Direct3D9.Device device = new SharpDX.Direct3D9.Device(direct3D, 0, DeviceType.NullReference, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = 1, BackBufferHeight = 1, DeviceWindowHandle = renderForm.Handle })) { _direct3DVirtualFunctionTable = new VirtualFunctionTable(direct3D.NativePointer, Enum.GetNames(typeof(Interfaces.IDirect3D9)).Length); _direct3DDeviceVirtualFunctionTable = new VirtualFunctionTable(device.NativePointer, Enum.GetNames(typeof(Interfaces.IDirect3DDevice9)).Length); } // Hook D3D9 device creation. _createDeviceHook = _direct3DVirtualFunctionTable.TableEntries[(int)Interfaces.IDirect3D9.CreateDevice].CreateFunctionHook86 <CreateDevice>(CreateDeviceImpl).Activate(); //_resetDeviceHook = _direct3DDeviceVirtualFunctionTable.TableEntries[(int)Interfaces.IDirect3DDevice9.Reset].CreateFunctionHook86<Direct3D9DeviceResetDelegate>(ResetDeviceImpl).Activate(); }
public SpriteBatch(Device d, ContentManager c) { Device = d; cubeVert = new VertexBuffer(Device, 4 * 28, Usage.WriteOnly, VertexFormat.None, Pool.Managed); cubeVert.Lock(0, 0, LockFlags.None).WriteRange(new[] { new VertexPositionTextureColor() { Color = Color.White.ToArgb(), Position = new Vector4f(0, 0, 0.0f, 1.0f), TexCoord = new Vector2f(0.0f, 1.0f) }, new VertexPositionTextureColor() { Color = Color.White.ToArgb(), Position = new Vector4f(0, 1, 0.0f, 1.0f), TexCoord = new Vector2f(0.0f, 0.0f) }, new VertexPositionTextureColor() { Color = Color.White.ToArgb(), Position = new Vector4f(1, 0, 0.0f, 1.0f), TexCoord = new Vector2f(1.0f, 1.0f) }, new VertexPositionTextureColor() { Color = Color.White.ToArgb(), Position = new Vector4f(1, 1, 0.0f, 1.0f), TexCoord = new Vector2f(1.0f, 0.0f) } }); cubeVert.Unlock(); var cubeElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 16, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), new VertexElement(0, 24, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; cubeDecl = new VertexDeclaration(Device, cubeElems); renderEffect = c.LoadString<Content.Effect>("float4 c;Texture b;sampler s=sampler_state{texture=<b>;magfilter=LINEAR;minfilter=LINEAR;mipfilter=LINEAR;AddressU=wrap;AddressV=wrap;};float4 f(float2 t:TEXCOORD0):COLOR{return tex2D(s, t) * c;}technique t{pass p{PixelShader = compile ps_2_0 f();}}"); }
public static Model FromScene(Scene scene, Device device) { VertexDeclaration vertexDeclaration = new VertexDeclaration(device, VertexPositionNormalTexture.VertexElements); Model result = new Model(scene, device, vertexDeclaration); foreach (Mesh mesh in scene.Meshes.Where(x => x.Positions.Any())) { VertexBuffer vertexBuffer = new VertexBuffer(device, mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes, Usage.WriteOnly, VertexFormat.None, Pool.Default); DataStream vertexDataStream = vertexBuffer.Lock(0, mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes, LockFlags.None); VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[mesh.Positions.Count]; for (int i = 0; i < vertices.Length; ++i) vertices[i] = new VertexPositionNormalTexture(mesh.Positions[i], (mesh.Normals.Count > i) ? mesh.Normals[i] : Vector3D.Zero, (mesh.TextureCoordinates.Count > i) ? mesh.TextureCoordinates[i].Xy : Point2D.Zero); vertexDataStream.WriteRange(vertices); vertexBuffer.Unlock(); IndexBuffer indexBuffer = new IndexBuffer(device, mesh.Indices.Count * sizeof(int), Usage.WriteOnly, Pool.Default, false); DataStream indexDataStream = indexBuffer.Lock(0, mesh.Indices.Count * sizeof(int), LockFlags.None); indexDataStream.WriteRange(mesh.Indices.ToArray()); indexBuffer.Unlock(); ModelMesh modelMesh = new ModelMesh(mesh, device, vertexBuffer, mesh.Positions.Count, indexBuffer, mesh.PrimitiveCount, Matrix3D.Identity, mesh.Material); result.Meshes.Add(modelMesh); } return result; }
public GBuffer(IKernel kernel) { IDeviceProvider provider = kernel.Get<IDeviceProvider>(); _device = provider.Device; _form = provider.RenderForm; }
public PointSpriteRenderer(Device device, int size) { if (device == null) throw new ArgumentNullException("device"); _device = device; _size = size; _vertexBuffer = new VertexBuffer(_device, _size * Particle.SizeInBytes, Usage.Dynamic | Usage.Points | Usage.WriteOnly, VertexFormat.None, Pool.Default); var vertexElements = new[] { new VertexElement(0, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Color, 0), // Age new VertexElement(1, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Position, 0), // X new VertexElement(2, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Position, 1), // Y new VertexElement(3, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Color, 1), // R new VertexElement(4, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Color, 2), // G new VertexElement(5, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.Color, 3), // B new VertexElement(6, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.PointSize, 0), // Size new VertexElement(7, 0, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), // Rotation VertexElement.VertexDeclarationEnd }; _effect = Effect.FromString(device, Resources.PointSpriteShader, ShaderFlags.PartialPrecision); _vertexDeclaration = new VertexDeclaration(device, vertexElements); }
static void Main(string[] args) { RenderForm form = new RenderForm("Underground - POO version"); form.Size = new Size(1280, 700); Direct3D direct3D = new Direct3D(); PresentParameters parameters = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height); Device device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, parameters); ResManager.Initialize(ref device, ref form); IngameClass ingame = new IngameClass(ref device, ref form); Stopwatch clock = new Stopwatch(); clock.Start(); RenderLoop.Run(form, () => { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); ingame.Draw(ref device, ref form, ref clock); device.EndScene(); device.Present(); }); ResManager.Dispose(); device.Dispose(); direct3D.Dispose(); }
public bool Initialise(Device device) { Debug.Assert(!_initialised); if (_initialising) return false; _initialising = true; try { _device = device; _sprite = ToDispose(new Sprite(_device)); // Initialise any resources required for overlay elements IntialiseElementResources(); _initialised = true; return true; } finally { _initialising = false; } }
unsafe int PresentHook(IntPtr devicePtr, SharpDX.Rectangle *pSourceRect, SharpDX.Rectangle *pDestRect, IntPtr hDestWindowOverride, IntPtr pDirtyRegion) { // Example of using delegate to original function pointer to call original method //var original = (Direct3D9Device_PresentDelegate)(Object)Marshal.GetDelegateForFunctionPointer(id3dDeviceFunctionAddresses[(int)Direct3DDevice9FunctionOrdinals.Present], typeof(Direct3D9Device_PresentDelegate)); //try //{ // unsafe // { // return original(devicePtr, ref pSourceRect, ref pDestRect, hDestWindowOverride, pDirtyRegion); // } //} //catch { } _isUsingPresent = true; Device device = (Device)devicePtr; DoCaptureRenderTarget(device, "PresentHook"); if (pSourceRect == null || *pSourceRect == SharpDX.Rectangle.Empty) { device.Present(); } else { if (hDestWindowOverride != IntPtr.Zero) { device.Present(*pSourceRect, *pDestRect, hDestWindowOverride); } else { device.Present(*pSourceRect, *pDestRect); } } return(SharpDX.Result.Ok.Code); }
/// <summary> /// Reset the _renderTarget so that we are sure it will have the correct presentation parameters (required to support working across changes to windowed/fullscreen or resolution changes) /// </summary> /// <param name="devicePtr"></param> /// <param name="presentParameters"></param> /// <returns></returns> int ResetHook(IntPtr devicePtr, ref PresentParameters presentParameters) { Device device = (Device)devicePtr; try { lock (_lockRenderTarget) { if (_renderTarget != null) { _renderTarget.Dispose(); _renderTarget = null; } } // EasyHook has already repatched the original Reset so calling it here will not cause an endless recursion to this function device.Reset(presentParameters); return(SharpDX.Result.Ok.Code); } catch (SharpDX.SharpDXException sde) { return(sde.ResultCode.Code); } catch (Exception e) { DebugMessage(e.ToString()); return(SharpDX.Result.Ok.Code); } }
private Device GetOrCreateDevice(IntPtr devicePointer) { if (this.Device == null) this.Device = Device.FromPointer<Device>(devicePointer); return this.Device; }
protected override void LoadFromMicrocode(D3D9.Device d3D9Device, D3D9.ShaderBytecode microcode) { D3D9.PixelShader pixelShader; var shaderWasFound = this._mapDeviceToPixelShader.TryGetValue(d3D9Device, out pixelShader); if (shaderWasFound) { pixelShader.SafeDispose(); } if (IsSupported) { // Create the shader pixelShader = new D3D9.PixelShader(d3D9Device, microcode); } else { LogManager.Instance.Write("Unsupported D3D9 pixel shader '{0}' was not loaded.", _name); pixelShader = null; } if (shaderWasFound) { this._mapDeviceToPixelShader[d3D9Device] = pixelShader; } else { this._mapDeviceToPixelShader.Add(d3D9Device, pixelShader); } }
public static SharpDX.Direct3D9.VertexDeclaration GetDeclaration(Device device) { return _declaration ?? (_declaration = new VertexDeclaration(device, new[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd })); }
/// <summary> /// Initializes a new instance of the <see cref="CubeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="edgeLength">Length of the edge.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="sharedHandle">The shared handle.</param> public CubeTexture(Device device, int edgeLength, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { fixed (void* pSharedHandle = &sharedHandle) device.CreateCubeTexture(edgeLength, levelCount, (int)usage, format, pool, this, (IntPtr)pSharedHandle); } }
public static bool RenderVideo(Device device, string dataPath, PartSysSpec spec, string filename) { var specStr = spec.ToSpec(); var activeSys = ParticleSystem.FromSpec(device, dataPath, specStr); return activeSys.RenderVideo(device, Color.FromArgb(255, 32, 32, 32), filename); }
static void DrawLine(SharpDX.Direct3D9.Device device, SharpDX.Vector2[] vLine, ColorBGRA col, int width) { Line line = null; line = new Line(device); line.Width = width; line.Draw(vLine, col); }
unsafe static Tuple <CUDADevice, IntPtr> Generate(D3D9Device d3d9Device) { var cuContext = IntPtr.Zero; var cuDevice = -1; CUDAInterop.cuSafeCall(CUDAInterop.cuD3D9CtxCreate(&cuContext, &cuDevice, 0u, d3d9Device.NativePointer)); return(new Tuple <CUDADevice, IntPtr>(CUDADevice.DeviceDict[cuDevice], cuContext)); }
/// <summary> /// Initializes a new instance of the <see cref="VolumeTexture"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <param name="levelCount">The level count.</param> /// <param name="usage">The usage.</param> /// <param name="format">The format.</param> /// <param name="pool">The pool.</param> /// <param name="sharedHandle">The shared handle.</param> /// <unmanaged>HRESULT IDirect3DDevice9::CreateVolumeTexture([In] unsigned int Width,[In] unsigned int Height,[In] unsigned int Levels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DVolumeTexture9** ppVolumeTexture,[In] void** pSharedHandle)</unmanaged> public VolumeTexture(Device device, int width, int height, int depth, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { fixed (void* pSharedHandle = &sharedHandle) device.CreateVolumeTexture(width, height, depth, levelCount, (int)usage, format, pool, this, new IntPtr(pSharedHandle)); } }
public Texture2D(Device d, int width, int height, Usage u) { handle = new Texture(d, width, height, 1, u, Format.A8R8G8B8, Pool.Default); usage = u; Width = width; Height = height; device = d; managed = false; }
private void _releaseQuery(D3D9.Device d3d9Device) { if (this._mapDeviceToQuery.ContainsKey(d3d9Device)) { // Remove from query resource map. this._mapDeviceToQuery[d3d9Device].SafeDispose(); this._mapDeviceToQuery.Remove(d3d9Device); } }
public Texture2D(Device d, int width, int height) { handle = new Texture(d, width, height, 1, Usage.None, Format.A8R8G8B8, Pool.Managed); Width = width; Height = height; device = d; managed = true; usage = Usage.None; }
public static VertexDeclaration GetDeclaration(Device device) { return vdecl ?? (vdecl = new VertexDeclaration(device, new VertexElement[]{ new VertexElement(0,0,DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0,sizeof(float)*3, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0), new VertexElement(0,sizeof(float)*6, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), VertexElement.VertexDeclarationEnd })); }
/// <summary> /// Initializes a new instance of the <see cref="IndexBuffer"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="sizeInBytes">The size in bytes.</param> /// <param name="usage">The usage.</param> /// <param name="pool">The pool.</param> /// <param name="sixteenBit">if set to <c>true</c> use 16bit index buffer, otherwise, use 32bit index buffer.</param> /// <param name="sharedHandle">The shared handle.</param> /// <msdn-id>bb174357</msdn-id> /// <unmanaged>HRESULT IDirect3DDevice9::CreateIndexBuffer([In] unsigned int Length,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[Out, Fast] IDirect3DIndexBuffer9** ppIndexBuffer,[In] void** pSharedHandle)</unmanaged> /// <unmanaged-short>IDirect3DDevice9::CreateIndexBuffer</unmanaged-short> public IndexBuffer(Device device, int sizeInBytes, Usage usage, Pool pool, bool sixteenBit, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { fixed (void* pSharedHandle = &sharedHandle) device.CreateIndexBuffer(sizeInBytes, (int)usage, sixteenBit ? Format.Index16 : Format.Index32, pool, this, (IntPtr)pSharedHandle); } }
protected BufferResources GetBufferResources(D3D9.Device d3d9Device) { if (this.mapDeviceToBufferResources.ContainsKey(d3d9Device)) { return(this.mapDeviceToBufferResources[d3d9Device]); } return(null); }
public void initialize(int videoWidth, int videoHeight) { try { this.videoHeight = videoHeight; this.videoWidth = videoWidth; if (direct3D == null) { SharpDX.Result resultCode; direct3D = new D3D.Direct3D(); if (direct3D.CheckDeviceFormatConversion( 0, D3D.DeviceType.Hardware, makeFourCC('Y', 'V', '1', '2'), D3D.Format.X8R8G8B8, out resultCode) == false) { throw new SharpDX.SharpDXException("Video Hardware does not support YV12 format conversion"); } D3D.PresentParameters[] presentParams = createPresentParams(windowed, owner); device = new D3D.Device(direct3D, 0, D3D.DeviceType.Hardware, owner.Handle, D3D.CreateFlags.SoftwareVertexProcessing, presentParams); releaseResources(); aquireResources(); } else { releaseResources(); D3D.PresentParameters[] presentParams = createPresentParams(windowed, owner); device.Reset(presentParams); aquireResources(); } int sizeBytes = videoWidth * (videoHeight + videoHeight / 2); offscreenBuffer = new Byte[sizeBytes]; //log.Info("Direct3D Initialized"); } catch (SharpDX.SharpDXException e) { throw new VideoPlayerException("Direct3D Initialization error: " + e.Message, e); } }
public void NotifyOnDeviceReset(D3D9.Device d3D9Device) { lock ( _resourcesMutex ) { foreach (var it in this.Resources) { it.NotifyOnDeviceReset(d3D9Device); } } }
/// <summary> /// Initializes a new instance of the <see cref="SharpDX.Direct3D9.VertexBuffer" /> class. /// </summary> /// <param name="device">The device that will be used to create the buffer.</param> /// <param name="sizeInBytes">Size of the buffer, in bytes.</param> /// <param name="usage">The requested usage of the buffer.</param> /// <param name="format">The vertex format of the vertices in the buffer. If set to <see cref="SharpDX.Direct3D9.VertexFormat" />.None, the buffer will be a non-FVF buffer.</param> /// <param name="pool">The memory class into which the resource will be placed.</param> /// <param name="sharedHandle">The variable that will receive the shared handle for this resource.</param> /// <remarks>This method is only available in Direct3D9 Ex.</remarks> /// <msdn-id>bb174364</msdn-id> /// <unmanaged>HRESULT IDirect3DDevice9::CreateVertexBuffer([In] unsigned int Length,[In] D3DUSAGE Usage,[In] D3DFVF FVF,[In] D3DPOOL Pool,[Out, Fast] IDirect3DVertexBuffer9** ppVertexBuffer,[In] void** pSharedHandle)</unmanaged> /// <unmanaged-short>IDirect3DDevice9::CreateVertexBuffer</unmanaged-short> public VertexBuffer(Device device, int sizeInBytes, Usage usage, VertexFormat format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero) { unsafe { sharedHandle = IntPtr.Zero; fixed (void* pSharedHandle = &sharedHandle) device.CreateVertexBuffer(sizeInBytes, usage, format, pool, this, new IntPtr(pSharedHandle)); } }
public void Bind(D3D9.Device dev, D3D9.Volume volume, D3D9.BaseTexture mipTex) { //Entering critical section LockDeviceAccess(); var bufferResources = GetBufferResources(dev); var isNewBuffer = false; if (bufferResources == null) { bufferResources = new BufferResources(); this.mapDeviceToBufferResources.Add(dev, bufferResources); isNewBuffer = true; } bufferResources.MipTex = mipTex; bufferResources.Volume = volume; var desc = volume.Description; width = desc.Width; height = desc.Height; depth = desc.Depth; format = D3D9Helper.ConvertEnum(desc.Format); // Default rowPitch = Width; slicePitch = Height * Width; sizeInBytes = PixelUtil.GetMemorySize(Width, Height, Depth, Format); if (isNewBuffer && this.ownerTexture.IsManuallyLoaded) { foreach (var it in this.mapDeviceToBufferResources) { if (it.Value != bufferResources && it.Value.Volume != null && it.Key.TestCooperativeLevel().Success&& dev.TestCooperativeLevel().Success) { var fullBufferBox = new BasicBox(0, 0, 0, Width, Height, Depth); var dstBox = new PixelBox(fullBufferBox, Format); var data = new byte[sizeInBytes]; using (var d = BufferBase.Wrap(data)) { dstBox.Data = d; BlitToMemory(fullBufferBox, dstBox, it.Value, it.Key); BlitFromMemory(dstBox, fullBufferBox, bufferResources); Array.Clear(data, 0, sizeInBytes); } break; } } } //Leaving critical section UnlockDeviceAccess(); }
public D3D9.Surface GetFSAASurface(D3D9.Device d3d9Device) { var bufferResources = GetBufferResources(d3d9Device); if (bufferResources != null) { this.ownerTexture.CreateTextureResources(d3d9Device); bufferResources = GetBufferResources(d3d9Device); } return(bufferResources.FsaaSurface); }
private void _createQuery(D3D9.Device d3d9Device) { // Check if query supported. try { // create the occlusion query. this._mapDeviceToQuery[d3d9Device] = new D3D9.Query(d3d9Device, D3D9.QueryType.Occlusion); } catch { this._mapDeviceToQuery[d3d9Device] = null; } }
public void ReleaseSurfaces(D3D9.Device d3d9Device) { var bufferResources = GetBufferResources(d3d9Device); if (bufferResources != null) { bufferResources.Surface.SafeDispose(); bufferResources.Surface = null; bufferResources.Volume.SafeDispose(); bufferResources.Volume = null; } }
/// <summary> /// Hook for IDirect3DDevice9.EndScene /// </summary> /// <param name="devicePtr">Pointer to the IDirect3DDevice9 instance. Note: object member functions always pass "this" as the first parameter.</param> /// <returns>The HRESULT of the original EndScene</returns> /// <remarks>Remember that this is called many times a second by the Direct3D application - be mindful of memory and performance!</remarks> int EndSceneHook(IntPtr devicePtr) { Device device = (Device)devicePtr; if (!_isUsingPresent) { DoCaptureRenderTarget(device, "EndSceneHook"); } device.EndScene(); return(SharpDX.Result.Ok.Code); }
public void NotifyOnDeviceReset(D3D9.Device d3d9Device) { //Entering critical section this.LockDeviceAccess(); if (D3D9RenderSystem.ResourceManager.CreationPolicy == D3D9ResourceManager.ResourceCreationPolicy.CreateOnAllDevices) { CreateBuffer(d3d9Device, this._bufferDesc.Pool); } //Leaving critical section this.UnlockDeviceAccess(); }
public DX(D3D9.Direct3D direct3D, D3D9.Device device) { Direct3D = direct3D; Device = device; GlobalLock = new object(); if (Device.Capabilities.PixelShaderVersion < new Version(2, 0) || Device.Capabilities.VertexShaderVersion < new Version(2, 0)) { MessageBox.Show("This computer doesn't support Vertex and Pixel Shader version 2. Get with the times."); Application.Exit(); } }
internal Direct3D9IndexBuffer(SharpDX.Direct3D9.Device device, uint[] data) { _length = data.Length; _buffer = new SharpDX.Direct3D9.IndexBuffer(device, data.Length * sizeof(uint), Usage.WriteOnly, Pool.Managed, false); SharpDX.DataStream ds = _buffer.Lock(0, _length * sizeof(uint), LockFlags.None); for (int i = 0; i < data.Length; i++) { ds.Write(data[i]); } _buffer.Unlock(); }
public void NotifyOnDeviceDestroy(D3D9.Device d3d9Device) { //Entering critical section this.LockDeviceAccess(); if (this._mapDeviceToDeclaration.ContainsKey(d3d9Device)) { this._mapDeviceToDeclaration[d3d9Device].SafeDispose(); this._mapDeviceToDeclaration.Remove(d3d9Device); } //Leaving critical section this.UnlockDeviceAccess(); }
public void DestroyBufferResources(D3D9.Device d3d9Device) { //Entering critical section LockDeviceAccess(); if (this.mapDeviceToBufferResources.ContainsKey(d3d9Device)) { this.mapDeviceToBufferResources[d3d9Device].SafeDispose(); this.mapDeviceToBufferResources.Remove(d3d9Device); } //Leaving critical section UnlockDeviceAccess(); }
public void NotifyOnDeviceDestroy(D3D9.Device d3d9Device) { //Entering critical section this.LockDeviceAccess(); if (this._mapDeviceToBufferResources.ContainsKey(d3d9Device)) { this._mapDeviceToBufferResources[d3d9Device].IndexBuffer.SafeDispose(); this._mapDeviceToBufferResources[d3d9Device].SafeDispose(); this._mapDeviceToBufferResources.Remove(d3d9Device); } //Leaving critical section this.UnlockDeviceAccess(); }
public void NotifyOnDeviceLost(D3D9.Device d3d9Device) { //Entering critical section this.LockDeviceAccess(); if (this._bufferDesc.Pool == D3D9.Pool.Default) { if (this._mapDeviceToBufferResources.ContainsKey(d3d9Device)) { this._mapDeviceToBufferResources[d3d9Device].IndexBuffer.SafeDispose(); } } //Leaving critical section this.UnlockDeviceAccess(); }
/* Sets the different device parameters on each reset. */ private void SetDeviceParameters(IntPtr device) { SharpDX.Direct3D9.Device localDevice = new SharpDX.Direct3D9.Device(device); if (_dx9Settings.EnableMSAA) { localDevice.SetRenderState(RenderState.MultisampleAntialias, true); } if (_dx9Settings.EnableAF) { localDevice.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Anisotropic); localDevice.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Anisotropic); localDevice.SetSamplerState(0, SamplerState.MaxAnisotropy, _dx9Settings.AFLevel); } }
public static void Initiate() { var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample"); // Creates the Device var direct3D = new Direct3D(); var device = new SharpDX.Direct3D9.Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height)); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); string Game = "WOT"; switch (Game) { case "WOT": _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_enter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_6473.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 100, 0))); _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-addenter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-add.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 400, 0))); break; } //choose game RenderLoop.Run(form, () => { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); foreach (DrawTextureAndCatchIt dr in _list) { dr.CheckCursorPosition(); dr.DrawTexture(device); } device.EndScene(); device.Present(); }); device.Dispose(); direct3D.Dispose(); }
void DestructDevice() { if (this.device != null) { this.device.Dispose(); this.device = null; } if (this.render != null) { this.render.Dispose(); this.render = null; } if (this.device9 != null) { this.device9.Dispose(); this.device9 = null; } }
static void Main() { var form = new RenderForm("SlimDX2 - MiniTri Direct3D9 Sample"); var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width,form.ClientSize.Height)); var vertices = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); vertices.Lock(0, 0, LockFlags.None).WriteRange(new[] { new Vertex() { Color = Color.Red, Position = new Vector4(400.0f, 100.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Blue, Position = new Vector4(650.0f, 500.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Green, Position = new Vector4(150.0f, 500.0f, 0.5f, 1.0f) } }); vertices.Unlock(); var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(device, vertexElems); RenderLoop.Run(form, () => { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); device.SetStreamSource(0, vertices, 0, 20); device.VertexDeclaration = vertexDecl; device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); device.EndScene(); device.Present(); }); }