protected override void Dispose(bool disposing) { if (disposing) { SeeingSharpUtil.DisposeObject(_stream); } }
/// <summary> /// Initializes a new instance of the <see cref="DeviceHandlerD3D11" /> class. /// </summary> internal DeviceHandlerD2D(GraphicsDeviceConfiguration deviceConfig, EngineFactory engineFactory, EngineDevice engineDevice) { try { // Simulate exception if requested if (deviceConfig.CoreConfiguration.ThrowD2DInitDeviceError) { throw new SeeingSharpGraphicsException("Simulation Direct2D device init exception"); } using (var dxgiDevice = engineDevice.DeviceD3D11_1.QueryInterface <IDXGIDevice>()) { _deviceD2D = engineFactory.FactoryD2D_2.CreateDevice(dxgiDevice); _deviceContextD2D = _deviceD2D .CreateDeviceContext(D2D.DeviceContextOptions.None); _renderTarget = _deviceContextD2D; } } catch (Exception) { SeeingSharpUtil.SafeDispose(ref _deviceContextD2D); SeeingSharpUtil.SafeDispose(ref _deviceD2D); SeeingSharpUtil.SafeDispose(ref _renderTarget); } }
/// <summary> /// Unloads the resource. /// </summary> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { SeeingSharpUtil.SafeDispose(ref _inputLayout); _vertexShader = null; _pixelShader = null; }
/// <summary> /// Loads a bitmap from the given texture. Be careful: The texture must have CPU read access and this only matches for staging textures. /// </summary> /// <param name="texture">The texture to be loaded into the bitmap.</param> public static GDI.Bitmap LoadBitmapFromMemoryMappedTexture(MemoryMappedTexture <int> texture) { texture.EnsureNotNullOrDisposed(nameof(texture)); var width = texture.Width; var height = texture.Height; // Create and lock bitmap so it can be accessed for texture loading var resultBitmap = new GDI.Bitmap(width, height); var bitmapData = resultBitmap.LockBits( new GDI.Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); try { SeeingSharpUtil.CopyMemory( texture.Pointer, bitmapData.Scan0, texture.SizeInBytes); } finally { resultBitmap.UnlockBits(bitmapData); } return(resultBitmap); }
/// <summary> /// Unloads the resource. /// </summary> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { _textureView = SeeingSharpUtil.DisposeObject(_textureView); _texture = SeeingSharpUtil.DisposeObject(_texture); _isCubeTexture = false; _isRenderTarget = false; }
public override void OnSampleClosed() { base.OnSampleClosed(); SeeingSharpUtil.SafeDispose(ref _solidBrush); SeeingSharpUtil.SafeDispose(ref _animatedRectBrush); SeeingSharpUtil.SafeDispose(ref _textFormat); }
/// <summary> /// Initializes a new instance of the <see cref="DeviceHandlerD3D9"/> class. /// </summary> /// <param name="dxgiAdapter">The target adapter.</param> /// <param name="isSoftwareAdapter">Are we in software mode?</param> internal DeviceHandlerD3D9(IDXGIAdapter1 dxgiAdapter, bool isSoftwareAdapter) { try { // Just needed when on true hardware if (!isSoftwareAdapter) { //Prepare device creation const D3D9.CreateFlags CREATE_FLAGS = D3D9.CreateFlags.HardwareVertexProcessing | D3D9.CreateFlags.PureDevice | D3D9.CreateFlags.FpuPreserve | D3D9.CreateFlags.Multithreaded; var presentparams = new D3D9.PresentParameters { Windowed = true, SwapEffect = D3D9.SwapEffect.Discard, DeviceWindowHandle = GetDesktopWindow(), PresentationInterval = D3D9.PresentInterval.Default, BackBufferCount = 1 }; //Create the device finally var result = Create9Ex(out _direct3DEx); result.CheckError(); // Try to find the Direct3D9 adapter that matches given DXGI adapter var adapterIndex = -1; for (var loop = 0; loop < _direct3DEx.AdapterCount; loop++) { var d3d9AdapterInfo = _direct3DEx.GetAdapterIdentifier(loop); if (d3d9AdapterInfo.DeviceId == dxgiAdapter.Description1.DeviceId) { adapterIndex = loop; break; } } // Direct3D 9 is only relevant on the primary device if (adapterIndex < 0) { return; } // Try to create the device _deviceEx = _direct3DEx.CreateDeviceEx( adapterIndex, D3D9.DeviceType.Hardware, IntPtr.Zero, CREATE_FLAGS, presentparams); } } catch (Exception) { // No direct3d 9 interface support SeeingSharpUtil.SafeDispose(ref _direct3DEx); SeeingSharpUtil.SafeDispose(ref _deviceEx); } }
/// <summary> /// Unloads the resource. /// </summary> protected internal override void UnloadShader() { foreach (var actInputLayout in _inputLayouts.Values) { SeeingSharpUtil.DisposeObject(actInputLayout); } _inputLayouts.Clear(); _vertexShader = SeeingSharpUtil.DisposeObject(_vertexShader); }
/// <summary> /// Unloads all resources. /// </summary> public void UnloadResources() { _immediateContext = SeeingSharpUtil.DisposeObject(_immediateContext); _immediateContext3 = SeeingSharpUtil.DisposeObject(_immediateContext3); _device1 = SeeingSharpUtil.DisposeObject(_device1); _device3 = SeeingSharpUtil.DisposeObject(_device3); _creationFlags = D3D11.DeviceCreationFlags.None; _featureLevel = D3D.FeatureLevel.Level_11_0; }
/// <summary> /// Creates a WIC BitmapSource object from the given source. /// </summary> /// <param name="resourceLink">The source of the resource.</param> public static async Task <WicBitmapSource> FromResourceSourceAsync(ResourceLink resourceLink) { WicBitmapSourceInternal?wicBitmapSource = null; using (var inStream = await resourceLink.OpenInputStreamAsync()) { wicBitmapSource = await SeeingSharpUtil.CallAsync(() => GraphicsHelper.Internals.LoadBitmapSource(inStream)); } return(new WicBitmapSource(wicBitmapSource)); }
/// <summary> /// Unloads all resources loaded on the given device. /// </summary> /// <param name="engineDevice">The device for which to unload the resource.</param> internal override void UnloadResources(EngineDevice engineDevice) { D2D.ID2D1Brush?brush = _loadedBrushes[engineDevice.DeviceIndex]; if (brush != null) { engineDevice.DeregisterDeviceResource(this); SeeingSharpUtil.DisposeObject(brush); _loadedBrushes[engineDevice.DeviceIndex] = null; } }
/// <summary> /// Unloads the resource. /// </summary> /// <param name="device">The device.</param> /// <param name="resources">Parent ResourceDictionary.</param> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { _defaultBlendState = SeeingSharpUtil.DisposeObjectLazy(_defaultBlendState); _depthStencilStateDefault = SeeingSharpUtil.DisposeObjectLazy(_depthStencilStateDefault); _depthStencilStateDisableZWrites = SeeingSharpUtil.DisposeObjectLazy(_depthStencilStateDisableZWrites); _rasterStateLines = SeeingSharpUtil.DisposeObjectLazy(_rasterStateLines); _rasterStateDefault = SeeingSharpUtil.DisposeObjectLazy(_rasterStateDefault); _samplerStateLow = SeeingSharpUtil.DisposeObjectLazy(_samplerStateLow); _samplerStateMedium = SeeingSharpUtil.DisposeObjectLazy(_samplerStateMedium); _samplerStateHigh = SeeingSharpUtil.DisposeObjectLazy(_samplerStateHigh); }
/// <summary> /// Unloads all resources loaded on the given device. /// </summary> /// <param name="engineDevice">The device for which to unload the resource.</param> internal override void UnloadResources(EngineDevice engineDevice) { var bitmap = _loadedBitmaps[engineDevice.DeviceIndex]; if (bitmap != null) { engineDevice.DeregisterDeviceResource(this); SeeingSharpUtil.DisposeObject(bitmap); _loadedBitmaps[engineDevice.DeviceIndex] = null; } }
/// <inheritdoc /> public void Dispose() { SeeingSharpUtil.SafeDispose(ref _uploaderColor); foreach (var actDumpResult in _dumpResults) { SeeingSharpUtil.DisposeObject(actDumpResult); } _dumpResults.Clear(); _isDisposed = true; }
/// <summary> /// Unloads all resources loaded on the given device. /// </summary> /// <param name="engineDevice">The device for which to unload the resource.</param> internal override void UnloadResources(EngineDevice engineDevice) { var actEffect = _loadedEffects[engineDevice.DeviceIndex]; if (actEffect != null) { engineDevice.DeregisterDeviceResource(this); SeeingSharpUtil.DisposeObject(actEffect); _loadedEffects[engineDevice.DeviceIndex] = null; } }
/// <summary> /// Disposes all resources of this object completely. /// </summary> public void Dispose() { // Dispose all created objects if (_renderTarget2D != null) { SeeingSharpUtil.SafeDispose(ref _renderTargetBitmap); _renderTarget2D = null; } else { SeeingSharpUtil.SafeDispose(ref _renderTarget2D); } }
/// <inheritdoc /> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { device.EnsureNotNull(nameof(device)); for (var loop = 0; loop < _chunkTemplates.Length; loop++) { SeeingSharpUtil.DisposeObject(_chunkTemplates[loop]); } _chunkTemplates = new RenderingChunkTemplate[0]; this.LoadedGeometryTriangleCount = 0; this.LoadedGeometryRenderingChunkCount = 0; }
/// <summary> /// Unloads all resources loaded on the given device. /// </summary> /// <param name="engineDevice">The device for which to unload the resource.</param> internal override void UnloadResources(EngineDevice engineDevice) { var loadedBrush = _loadedBrushes[engineDevice.DeviceIndex]; if (loadedBrush.Brush != null) { engineDevice.DeregisterDeviceResource(this); loadedBrush.Brush = SeeingSharpUtil.DisposeObject(loadedBrush.Brush); loadedBrush.GradientStops = SeeingSharpUtil.DisposeObject(loadedBrush.GradientStops); _loadedBrushes[engineDevice.DeviceIndex] = loadedBrush; } }
/// <summary> /// Creates a WIC bitmap from the given source. /// </summary> /// <param name="resourceLink">The source of the resource.</param> public static async Task <WicBitmap> FromResourceLinkAsync(ResourceLink resourceLink) { GraphicsCore.EnsureGraphicsSupportLoaded(); IWICBitmap?wicBitmap = null; using (var inStream = await resourceLink.OpenInputStreamAsync()) using (var bitmapSourceWrapper = await SeeingSharpUtil.CallAsync(() => GraphicsHelper.Internals.LoadBitmapSource(inStream))) { wicBitmap = GraphicsCore.Current.FactoryWIC !.CreateBitmapFromSource( bitmapSourceWrapper.Converter, BitmapCreateCacheOption.CacheOnLoad); } return(new WicBitmap(wicBitmap)); }
internal FactoryHandlerDXGI(GraphicsCoreConfiguration coreConfiguration) { _dxgiFactory = SeeingSharpUtil.TryExecute(() => CreateDXGIFactory2 <IDXGIFactory4>(coreConfiguration.DebugEnabled)); if (_dxgiFactory == null) { _dxgiFactory = SeeingSharpUtil.TryExecute(() => CreateDXGIFactory2 <IDXGIFactory2>(coreConfiguration.DebugEnabled)); } if (_dxgiFactory == null) { _dxgiFactory = SeeingSharpUtil.TryExecute(() => CreateDXGIFactory1 <IDXGIFactory1>()); } if (_dxgiFactory == null) { throw new SeeingSharpGraphicsException("Unable to create the DXGI Factory object!"); } }
/// <summary> /// Unloads all resources. /// </summary> /// <param name="device">The device on which the resources where loaded.</param> /// <param name="resources">The current ResourceDictionary.</param> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { if (device.Supports2D) { _graphics2D = null; SeeingSharpUtil.SafeDispose(ref _overlayRenderer); } else { _notLoadedDueToMissingSupport = false; return; } SeeingSharpUtil.SafeDispose(ref _renderTargetTextureView); SeeingSharpUtil.SafeDispose(ref _renderTargetTexture); }
/// <summary> /// Loads a bitmap from the given texture. Be careful: The texture must have CPU read access and this only matches for staging textures. /// </summary> /// <param name="device">The device on which the texture is created.</param> /// <param name="stagingTexture">The texture to be loaded into the bitmap.</param> /// <param name="targetBitmap">The target bitmap to write all contents to.</param> /// <param name="pixelWidth">With of the bitmap in pixels.</param> /// <param name="pixelHeight">Height of the bitmap in pixels.</param> /// <param name="lockTimeout">Timeout for locking the target bitmap.</param> internal static void LoadBitmapFromStagingTexture(EngineDevice device, D3D11.ID3D11Texture2D stagingTexture, WriteableBitmap targetBitmap, int pixelWidth, int pixelHeight, TimeSpan lockTimeout) { device.EnsureNotNull(nameof(device)); stagingTexture.EnsureNotNull(nameof(stagingTexture)); targetBitmap.EnsureNotNull(nameof(targetBitmap)); var textureDesc = stagingTexture.Description; pixelWidth.EnsureEqualComparable(textureDesc.Width, $"{nameof(textureDesc)}.{nameof(textureDesc.Width)}"); pixelHeight.EnsureEqualComparable(textureDesc.Height, $"{nameof(textureDesc)}.{nameof(textureDesc.Height)}"); // Prepare target bitmap var dataBox = device.Internals.DeviceImmediateContextD3D11.Map(stagingTexture, 0, D3D11.MapMode.Read, D3D11.MapFlags.None); try { if (!targetBitmap.TryLock(new Duration(lockTimeout))) { return; } try { // Copy data row by row // => Rows from data source may have more pixels because driver changes the size of textures var rowPitch = (uint)(pixelWidth * 4); for (var loopRow = 0; loopRow < pixelHeight; loopRow++) { var rowPitchSource = dataBox.RowPitch; var rowPitchDestination = pixelWidth * 4; SeeingSharpUtil.CopyMemory( dataBox.DataPointer + loopRow * rowPitchSource, targetBitmap.BackBuffer + loopRow * rowPitchDestination, rowPitch); } } finally { targetBitmap.AddDirtyRect(new Int32Rect(0, 0, pixelWidth, pixelHeight)); targetBitmap.Unlock(); } } finally { device.Internals.DeviceImmediateContextD3D11.Unmap(stagingTexture, 0); } }
private static byte[] GetShaderBytecode(EngineDevice device, ResourceLink resourceLink, ShaderResourceKind resourceKind, string shaderModel) { switch (resourceKind) { case ShaderResourceKind.Bytecode: using (var inStream = resourceLink.OpenInputStream()) { return(inStream.ReadAllBytes()); } case ShaderResourceKind.HlsFile: using (ReusableStringBuilders.Current.UseStringBuilder(out var singleShaderSourceBuilder, 10024)) { SingleShaderFileBuilder.ReadShaderFileAndResolveIncludes( resourceLink, singleShaderSourceBuilder); // device.DebugEnabled ? D3DCompiler.ShaderFlags.Debug : D3DCompiler.ShaderFlags.None var shaderSource = singleShaderSourceBuilder.ToString(); var compileResult = Compiler.Compile( shaderSource, Array.Empty <D3D.ShaderMacro>(), null !, "main", resourceLink.ToString() ?? "", shaderModel, device.DebugEnabled ? ShaderFlags.Debug : ShaderFlags.None, out var compBlob, out var compErrorBlob); try { if (compileResult.Failure) { throw new SeeingSharpGraphicsException($"Unable to compile shader from {resourceLink}: {compileResult.Code} - {compileResult.ToString()}"); } return(compBlob.GetBytes()); } finally { SeeingSharpUtil.SafeDispose(ref compBlob); SeeingSharpUtil.SafeDispose(ref compErrorBlob); } } default: throw new SeeingSharpException($"Unhandled {nameof(ShaderResourceKind)}: {resourceKind}"); } }
/// <summary> /// Loads a bitmap from the given texture. Be careful: The texture must have CPU read access and this only matches for staging textures. /// </summary> /// <param name="device">The device on which the texture is created.</param> /// <param name="stagingTexture">The texture to be loaded into the bitmap.</param> /// <param name="width">The width of the texture.</param> /// <param name="height">The height of the texture.</param> internal static GDI.Bitmap LoadBitmapFromStagingTexture(EngineDevice device, D3D11.ID3D11Texture2D stagingTexture, int width, int height) { device.EnsureNotNull(nameof(device)); stagingTexture.EnsureNotNull(nameof(stagingTexture)); width.EnsurePositiveOrZero(nameof(width)); height.EnsurePositiveOrZero(nameof(height)); //Prepare target bitmap var resultBitmap = new GDI.Bitmap(width, height); var dataBox = device.Internals.DeviceImmediateContextD3D11.Map(stagingTexture, 0, D3D11.MapMode.Read, D3D11.MapFlags.None); try { //Lock bitmap so it can be accessed for texture loading var bitmapData = resultBitmap.LockBits( new GDI.Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); try { //Copy data row by row // => Rows form data source may have more pixels because driver changes the size of textures var rowPitch = (uint)(width * 4); for (var loopRow = 0; loopRow < height; loopRow++) { // Copy bitmap data var rowPitchSource = dataBox.RowPitch; var rowPitchDestination = width * 4; SeeingSharpUtil.CopyMemory( dataBox.DataPointer + loopRow * rowPitchSource, bitmapData.Scan0 + loopRow * rowPitchDestination, rowPitch); } } finally { resultBitmap.UnlockBits(bitmapData); } } finally { device.Internals.DeviceImmediateContextD3D11.Unmap(stagingTexture, 0); } return(resultBitmap); }
/// <summary> /// Sets the content to all lines in the given polygon. /// </summary> /// <param name="center">The center of the ellipse.</param> /// <param name="radiusX">The radius in x direction.</param> /// <param name="radiusY">The radius in y direction.</param> public unsafe void SetContent(Vector2 center, float radiusX, float radiusY) { GraphicsCore.EnsureGraphicsSupportLoaded(); radiusX.EnsurePositiveOrZero(nameof(radiusX)); radiusY.EnsurePositiveOrZero(nameof(radiusY)); _center = center; _radiusX = radiusX; _radiusY = radiusY; SeeingSharpUtil.SafeDispose(ref _geometry); _geometry = GraphicsCore.Current.FactoryD2D !.CreateEllipseGeometry( new D2D.Ellipse( *(PointF *)¢er, radiusX, radiusY)); }
/// <summary> /// Subscribes the given object to the given render pass. /// </summary> internal RenderPassSubscription SubscribeForPass( RenderPassInfo passInfo, SceneObject sceneObject, Action <RenderState> renderMethod, int zOrder) { if (!_isSubscribeUnsubscribeAllowed) { throw new SeeingSharpException("Subscription is not allowed currently!"); } var subscriptionProperties = _objectsPerPassDict[passInfo]; // Append new subscription to subscription list var subscriptions = subscriptionProperties.Subscriptions; var subscriptionsCount = subscriptions.Count; var newSubscription = new RenderPassSubscription(this, passInfo, sceneObject, renderMethod, zOrder); if (!passInfo.IsSorted) { // No sort, so put the new subscription to the end of the collection newSubscription.SubscriptionIndex = subscriptionsCount; subscriptions.Add(newSubscription); } else { // Perform BinaryInsert to the correct position var newIndex = SeeingSharpUtil.BinaryInsert(subscriptions, newSubscription, SubscriptionZOrderComparer.Instance); // Increment all subscription indices after the inserted position subscriptionsCount++; for (var loop = newIndex; loop < subscriptionsCount; loop++) { var actSubscription = subscriptions[loop]; if (actSubscription.SubscriptionIndex != loop) { actSubscription.SubscriptionIndex = loop; subscriptions[loop] = actSubscription; actSubscription.SceneObject.UpdateSubscription(actSubscription, this); } } newSubscription = subscriptions[newIndex]; } return(newSubscription); }
/// <summary> /// Unloads all resources of this object. /// </summary> public override void UnloadResources() { base.UnloadResources(); // Dispose all locally created resources foreach (var actLocalResource in _localResources) { if (actLocalResource == null) { continue; } SeeingSharpUtil.SafeDispose(ref actLocalResource.IndexBuffer); SeeingSharpUtil.SafeDispose(ref actLocalResource.VertexBuffer); } // Clear local resource container _localResources.Clear(); }
/// <summary> /// Unloads the resource. /// </summary> /// <param name="device">The device.</param> /// <param name="resources">Parent ResourceDictionary.</param> protected override void UnloadResourceInternal(EngineDevice device, ResourceDictionary resources) { SeeingSharpUtil.SafeDispose(ref _depthBufferView); SeeingSharpUtil.SafeDispose(ref _colorBufferRenderTargetView); SeeingSharpUtil.SafeDispose(ref _colorBufferShaderResourceView); SeeingSharpUtil.SafeDispose(ref _depthBuffer); SeeingSharpUtil.SafeDispose(ref _colorBuffer); SeeingSharpUtil.SafeDispose(ref _normalDepthBufferRenderTargetView); SeeingSharpUtil.SafeDispose(ref _normalDepthBufferShaderResourceView); SeeingSharpUtil.SafeDispose(ref _normalDepthBuffer); // Unload shader resource if it was created explicitly if (_shaderResourceCreated) { SeeingSharpUtil.SafeDispose(ref _colorBufferShaderResource); SeeingSharpUtil.SafeDispose(ref _normalDepthBufferShaderResource); _shaderResourceCreated = false; } }
public static void EnsureMoreThanZeroElements <T>( this IEnumerable <T> collection, string checkedVariableName, [CallerMemberName] string callerMethod = "") { if (string.IsNullOrEmpty(callerMethod)) { callerMethod = "Unknown"; } // Get the collection count var hasAnyElement = SeeingSharpUtil.HasAnyElement(collection); // Check result if (!hasAnyElement) { throw new SeeingSharpCheckException( $"Collection {checkedVariableName} within method {callerMethod} musst have more than zero elements!"); } }
public static void EnsureCountEquals <T>( this IEnumerable <T> collection, int count, string checkedVariableName, [CallerMemberName] string callerMethod = "") { if (string.IsNullOrEmpty(callerMethod)) { callerMethod = "Unknown"; } // Get the collection count var collectionCount = -1; collectionCount = SeeingSharpUtil.GetCollectionCount(collection); // Check result if (collectionCount != count) { throw new SeeingSharpCheckException(string.Format( "Collection {0} within method {1} does not have the expected count of elements (expected {2})!", checkedVariableName, callerMethod, count, collectionCount)); } }