/// <summary> /// Find the display mode that most closely matches the requested display mode. /// </summary> /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param> /// <param name="mode">The mode.</param> /// <returns>Returns the closes display mode.</returns> /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged> /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order. ScanlineOrdering Scaling Format Resolution RefreshRate When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering, Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output. If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output. Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks> public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) { if (targetProfiles == null) throw new ArgumentNullException("targetProfiles"); ModeDescription closestDescription; SharpDX.Direct3D11.Device deviceTemp = null; try { var features = new SharpDX.Direct3D.FeatureLevel[targetProfiles.Length]; for (int i = 0; i < targetProfiles.Length; i++) { features[i] = (FeatureLevel)targetProfiles[i]; } deviceTemp = new SharpDX.Direct3D11.Device(adapter.NativeAdapter, SharpDX.Direct3D11.DeviceCreationFlags.None, features); } catch (Exception) { } var description = new SharpDX.DXGI.ModeDescription() { Width = mode.Width, Height = mode.Height, RefreshRate = mode.RefreshRate.ToSharpDX(), Format = (SharpDX.DXGI.Format)mode.Format, Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }; using (var device = deviceTemp) output.GetClosestMatchingMode(device, description, out closestDescription); return DisplayMode.FromDescription(closestDescription); }
public static void GetGLVersion(GraphicsProfile graphicsProfile, out int major, out int minor) { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: major = 3; minor = 3; return; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: major = 4; minor = 3; return; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: major = 4; minor = 4; return; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } }
internal GraphicsAdapter() { outputs = new [] { new GraphicsOutput() }; // set default values int versionMajor = 1; int versionMinor = 0; // get real values // using glGetIntegerv(GL_MAJOR_VERSION / GL_MINOR_VERSION) only works on opengl (es) > 3.0 var version = GL.GetString(StringName.Version); if (version != null) { var splitVersion = version.Split(new char[] { '.', ' ' }); // find first number occurence because: // - on OpenGL, "<major>.<minor>" // - on OpenGL ES, "OpenGL ES <profile> <major>.<minor>" for (var i = 0; i < splitVersion.Length - 1; ++i) { if (int.TryParse(splitVersion[i], out versionMajor)) { int.TryParse(splitVersion[i + 1], out versionMinor); break; } } } supportedGraphicsProfile = OpenGLUtils.GetFeatureLevel(versionMajor, versionMinor); }
protected override bool IsPreferredProfileAvailable(GraphicsProfile[] preferredProfiles, out GraphicsProfile availableProfile) { if(!base.IsPreferredProfileAvailable(preferredProfiles, out availableProfile)) { var minimumProfile = preferredProfiles.Min(); Assert.Ignore("This test requires the '{0}' graphic profile. It has been ignored", minimumProfile); } return true; }
/// <summary> /// Gets a reference to the singleton instance. /// </summary> public static GraphicsDeviceService AddRef(IntPtr windowHandle, int width, int height, GraphicsProfile profile) { // Increment the "how many controls sharing the device" reference count. if (Interlocked.Increment(ref mReferenceCount) == 1) { // If this is the first control to start using the // device, we must create the singleton instance. mSingletonInstance = new GraphicsDeviceService(windowHandle, width, height, profile); } return mSingletonInstance; }
public static byte[] GetEffectBytes(CompiledEffect effect, GraphicsProfile graphicsProfile) { switch (effect) { case CompiledEffect.CircleEffect: return graphicsProfile == GraphicsProfile.HiDef ? CircleEffect.HiDefWindows : CircleEffect.ReachWindows; default: throw new Exception("Effect not found"); } }
/// <summary> /// Constructor is private, because this is a singleton class: /// client controls should use the public AddRef method instead. /// </summary> GraphicsDeviceService(GraphicsProfile profile, IntPtr windowHandle, int width, int height) { parameters = new PresentationParameters(); parameters.BackBufferWidth = Math.Max(width, 1); parameters.BackBufferHeight = Math.Max(height, 1); parameters.BackBufferFormat = SurfaceFormat.Color; parameters.DepthStencilFormat = DepthFormat.Depth24Stencil8; parameters.DeviceWindowHandle = windowHandle; parameters.IsFullScreen = false; graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, profile, parameters); }
/// <summary> /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile. /// </summary> /// <param name="textureFormat">The desired type of format for the output texture</param> /// <param name="platform">The graphics platform</param> /// <param name="graphicsProfile">The graphics profile</param> /// <param name="textureSizeInput">The texture size input.</param> /// <param name="textureSizeRequested">The texture size requested.</param> /// <param name="generateMipmaps">Indicate if mipmaps should be generated for the output texture</param> /// <param name="logger">The logger.</param> /// <returns>true if the texture size is supported</returns> /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception> public static Size2 FindBestTextureSize(TextureFormat textureFormat, GraphicsPlatform platform, GraphicsProfile graphicsProfile, Size2 textureSizeInput, Size2 textureSizeRequested, bool generateMipmaps, ILogger logger) { var textureSize = textureSizeRequested; // compressed DDS files has to have a size multiple of 4. if (platform == GraphicsPlatform.Direct3D11 && textureFormat == TextureFormat.Compressed && ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0)) { textureSize.Width = unchecked((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3)); textureSize.Height = unchecked((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3)); } var maxTextureSize = 0; // determine if the desired size if valid depending on the graphics profile switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: if (generateMipmaps && (!IsPowerOfTwo(textureSize.Width) || !IsPowerOfTwo(textureSize.Height))) { // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD textureSize.Width = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024); textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024); logger.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize); } maxTextureSize = graphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048; break; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: maxTextureSize = 8192; break; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: maxTextureSize = 16384; break; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize) { logger.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " + "Please reduce texture size or upgrade your graphic profile.", graphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height); return new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize)); } return textureSize; }
/// <summary> /// Gets the level of feature ? /// </summary> /// <param name="profile"></param> /// <returns></returns> public static FeatureLevel GetFeatureLevel( GraphicsProfile profile ) { if (profile==GraphicsProfile.HiDef) { return FeatureLevel.Level_11_0; } if (profile==GraphicsProfile.Reach) { return FeatureLevel.Level_10_0; } if (profile==GraphicsProfile.Mobile) { return FeatureLevel.Level_9_3; } throw new ArgumentException("profile"); }
/// <summary> /// Gets the version of shader /// </summary> /// <param name="profile"></param> /// <returns></returns> public static string GetShaderVersion( GraphicsProfile profile ) { if (profile==GraphicsProfile.HiDef) { return "5_0"; } if (profile==GraphicsProfile.Reach) { return "4_0"; } if (profile==GraphicsProfile.Mobile) { return "2_0"; } throw new ArgumentException("profile"); }
internal GraphicsAdapter() { outputs = new [] { new GraphicsOutput() }; // set default values int detectedVersion = 100; var renderer = GL.GetString(StringName.Renderer); var vendor = GL.GetString(StringName.Vendor); // Stay close to D3D: Cut renderer after first / (ex: "GeForce 670/PCIe/SSE2") var rendererSlash = renderer.IndexOf('/'); if (rendererSlash != -1) renderer = renderer.Substring(0, rendererSlash); // Stay close to D3D: Remove "Corporation" from vendor vendor = vendor.Replace(" Corporation", string.Empty); // Generate adapter Description Description = $"{vendor} {renderer}"; // get real values // using glGetIntegerv(GL_MAJOR_VERSION / GL_MINOR_VERSION) only works on opengl (es) > 3.0 var version = GL.GetString(StringName.Version); if (version != null) { var splitVersion = version.Split(new char[] { '.', ' ' }); // find first number occurrence because: // - on OpenGL, "<major>.<minor>" // - on OpenGL ES, "OpenGL ES <profile> <major>.<minor>" for (var i = 0; i < splitVersion.Length - 1; ++i) { int versionMajor, versionMinor; if (int.TryParse(splitVersion[i], out versionMajor)) { // Note: minor version might have stuff concat, take only until not digits var versionMinorString = splitVersion[i + 1]; versionMinorString = new string(versionMinorString.TakeWhile(c => char.IsDigit(c)).ToArray()); int.TryParse(versionMinorString, out versionMinor); detectedVersion = versionMajor * 100 + versionMinor * 10; break; } } } supportedGraphicsProfile = OpenGLUtils.GetFeatureLevel(detectedVersion); }
/// <summary> /// Constructor is private, because this is a singleton class: /// client controls should use the public AddRef method instead. /// </summary> protected GraphicsDeviceService(IntPtr windowHandle, int width, int height, GraphicsProfile profile) { mParameters = new PresentationParameters { BackBufferWidth = Math.Max(width, 1), BackBufferHeight = Math.Max(height, 1), BackBufferFormat = SurfaceFormat.Color, DepthStencilFormat = DepthFormat.Depth24, DeviceWindowHandle = windowHandle, PresentationInterval = PresentInterval.Immediate, IsFullScreen = false }; GraphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, profile, mParameters) { BlendState = BlendState.Additive, DepthStencilState = DepthStencilState.Default }; }
public static IEnumerable<int> GetGLVersions(GraphicsProfile[] graphicsProfiles) { if (graphicsProfiles != null && graphicsProfiles.Length > 0) { foreach (var profile in graphicsProfiles) { if (profile >= GraphicsProfile.Level_10_0) yield return 3; else yield return 2; } } else { yield return 2; } }
public ImportParameters(TextureConvertParameters textureParameters) { var asset = textureParameters.Texture; IsSRgb = asset.SRgb; DesiredSize = new Size2((int)asset.Width, (int)asset.Height); IsSizeInPercentage = asset.IsSizeInPercentage; DesiredFormat = asset.Format; DesiredAlpha = asset.Alpha; TextureHint = asset.Hint; GenerateMipmaps = asset.GenerateMipmaps; PremultiplyAlpha = asset.PremultiplyAlpha; ColorKeyColor = asset.ColorKeyColor; ColorKeyEnabled = asset.ColorKeyEnabled; TextureQuality = textureParameters.TextureQuality; GraphicsPlatform = textureParameters.GraphicsPlatform; GraphicsProfile = textureParameters.GraphicsProfile; Platform = textureParameters.Platform; }
public static GLVersion GetGLVersion(GraphicsProfile graphicsProfile) { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: return GLVersion.ES2; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: return GLVersion.ES3; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: return GLVersion.ES31; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } }
public static void GetGLVersion(GraphicsProfile graphicsProfile, out int version) { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: version = 330; return; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: version = 410; return; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: version = 440; return; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } }
public ImportParameters(TextureConvertParameters textureParameters) { var asset = textureParameters.Texture; // Compute SRgb usage // If Texture is in auto mode, use the global settings, else use the settings overridden by the texture asset. IsSRgb = textureParameters.Texture.ColorSpace.ToColorSpace(textureParameters.ColorSpace, asset.Hint) == ColorSpace.Linear; DesiredSize = new Size2((int)asset.Width, (int)asset.Height); IsSizeInPercentage = asset.IsSizeInPercentage; DesiredFormat = asset.Format; DesiredAlpha = asset.Alpha; TextureHint = asset.Hint; GenerateMipmaps = asset.GenerateMipmaps; PremultiplyAlpha = asset.PremultiplyAlpha; ColorKeyColor = asset.ColorKeyColor; ColorKeyEnabled = asset.ColorKeyEnabled; TextureQuality = textureParameters.TextureQuality; GraphicsPlatform = textureParameters.GraphicsPlatform; GraphicsProfile = textureParameters.GraphicsProfile; Platform = textureParameters.Platform; }
public GameTest(string name, GraphicsProfile profile = GraphicsProfile.Level_9_3) { screenShots = 0; testName = name; xenkoDir = Environment.GetEnvironmentVariable("SiliconStudioXenkoDir"); assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; #if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP // SaveScreenshot is only defined for windows platformName = "Windows"; Directory.CreateDirectory(xenkoDir + "\\screenshots\\"); #endif AutoLoadDefaultSettings = true; // Note! This will override the preferred graphics profile so save it for later overrideGraphicsProfile = profile; IsFixedTimeStep = true; ForceOneUpdatePerDraw = true; IsDrawDesynchronized = false; // This still doesn't work IsDrawDesynchronized = false; // Double negation! TargetElapsedTime = TimeSpan.FromTicks(10000000 / 60); // target elapsed time is by default 60Hz }
/// <summary> /// Find the display mode that most closely matches the requested display mode. /// </summary> /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param> /// <param name="mode">The mode.</param> /// <returns>Returns the closes display mode.</returns> /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged> /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order. ScanlineOrdering Scaling Format Resolution RefreshRate When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering, Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output. If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output. Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks> public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) { if (targetProfiles == null) throw new ArgumentNullException("targetProfiles"); // TODO VULKAN //ModeDescription closestDescription; //SharpDX.Direct3D12.Device deviceTemp = null; //for (int i = 0; i < targetProfiles.Length; i++) //{ // // Create Device D3D12 with feature Level based on profile // try // { // deviceTemp = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, (FeatureLevel)targetProfiles[i]); // break; // } // catch (Exception) // { // } //} //if (deviceTemp == null) // throw new InvalidOperationException("Could not create D3D12 graphics device"); //var description = new SharpDX.DXGI.ModeDescription() //{ // Width = mode.Width, // Height = mode.Height, // RefreshRate = mode.RefreshRate.ToSharpDX(), // Format = (SharpDX.DXGI.Format)mode.Format, // Scaling = DisplayModeScaling.Unspecified, // ScanlineOrdering = DisplayModeScanlineOrder.Unspecified //}; //using (var device = deviceTemp) // output.GetClosestMatchingMode(device, description, out closestDescription); //return DisplayMode.FromDescription(closestDescription); return mode; }
public GraphicsDevice( GraphicsAdapter adapter, GraphicsProfile graphicsProfile, PresentationParameters presentationParameters) { Screen = Sdl.SDL_SetVideoMode(800, 600, 32, Sdl.SDL_SWSURFACE | Sdl.SDL_OPENGL | Sdl.SDL_GL_DOUBLEBUFFER | Sdl.SDL_ANYFORMAT); Sdl.SDL_GL_SetAttribute ( Sdl.SDL_GL_DOUBLEBUFFER, 1 ); Gl.glEnable( Gl.GL_TEXTURE ); Gl.glEnable( Gl.GL_TEXTURE_2D ); Gl.glShadeModel( Gl.GL_SMOOTH ); Gl.glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); Gl.glClearDepth( 1.0f ); Gl.glEnable( Gl.GL_DEPTH_TEST ); Gl.glDepthFunc( Gl.GL_LEQUAL ); Gl.glHint( Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST ); Resize(800, 600); }
public ContentBuilder(string contentProjectFile, GraphicsProfile graphicsProfile = GraphicsProfile.HiDef, TargetPlatform targetPlatform = TargetPlatform.Windows, bool compressContent = true, LoggerVerbosity loggerVerbosity = LoggerVerbosity.Normal, bool rebuildContent = false) { FileInfo fileInfo = new FileInfo(contentProjectFile); _contentProjectFile = Path.GetFullPath(fileInfo.FullName); if (fileInfo.Extension != ".contentproj") throw new NotSupportedException(string.Format("The file '{0}' is not a XNA content project.", _contentProjectFile)); if (!fileInfo.Exists) throw new FileNotFoundException(String.Format("The file '{0}' does not exist.", _contentProjectFile, _contentProjectFile)); GraphicsProfile = graphicsProfile; TargetPlatform = targetPlatform; CompressContent = compressContent; LoggerVerbosity = loggerVerbosity; RebuildContent = rebuildContent; if (!_globalProperties.ContainsKey("XnaProfile")) _globalProperties.Add("XnaProfile", GraphicsProfile.ToString()); if (!_globalProperties.ContainsKey("XNAContentPipelineTargetPlatform")) _globalProperties.Add("XNAContentPipelineTargetPlatform", TargetPlatform.ToString()); if (!_globalProperties.ContainsKey("XnaCompressContent")) _globalProperties.Add("XnaCompressContent", CompressContent.ToString()); if (!_globalProperties.ContainsKey("OutputhPath")) _globalProperties.Add("OutputPath", OutputPath); if (!_globalProperties.ContainsKey("ContentRootDirectory")) _globalProperties.Add("ContentRootDirectory", ContentRootDirectory); }
/// <summary> /// Find the display mode that most closely matches the requested display mode. /// </summary> /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param> /// <param name="mode">The mode.</param> /// <returns>Returns the closes display mode.</returns> /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged> /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order. ScanlineOrdering Scaling Format Resolution RefreshRate When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering, Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output. If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output. Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks> public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) { if (targetProfiles == null) throw new ArgumentNullException("targetProfiles"); ModeDescription closestDescription; SharpDX.Direct3D12.Device deviceTemp = null; for (int i = 0; i < targetProfiles.Length; i++) { // Create Device D3D12 with feature Level based on profile try { deviceTemp = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, (FeatureLevel)targetProfiles[i]); break; } catch (Exception) { } } if (deviceTemp == null) throw new InvalidOperationException("Could not create D3D12 graphics device"); var description = new SharpDX.DXGI.ModeDescription() { Width = mode.Width, Height = mode.Height, RefreshRate = mode.RefreshRate.ToSharpDX(), Format = (SharpDX.DXGI.Format)mode.Format, Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }; using (var device = deviceTemp) output.GetClosestMatchingMode(device, description, out closestDescription); return DisplayMode.FromDescription(closestDescription); }
private VisualTestSoftEdge(GraphicsProfile profile) : base("VisualTestSoftEdge", profile) { }
/// <summary> /// Creates a new instance of ContentWriter. /// </summary> /// <param name="compiler">The compiler object that created this writer.</param> /// <param name="output">The stream to write the XNB file to.</param> /// <param name="targetPlatform">The platform the XNB is intended for.</param> /// <param name="targetProfile">The graphics profile of the target.</param> /// <param name="compressContent">True if the content should be compressed.</param> /// <param name="rootDirectory">The root directory of the content.</param> /// <param name="referenceRelocationPath">The path of the XNB file, used to calculate relative paths for external references.</param> internal ContentWriter(ContentCompiler compiler, Stream output, TargetPlatform targetPlatform, GraphicsProfile targetProfile, bool compressContent, string rootDirectory, string referenceRelocationPath) : base(output) { this.compiler = compiler; this.targetPlatform = targetPlatform; this.targetProfile = targetProfile; this.compressContent = compressContent; this.rootDirectory = rootDirectory; // Normalize the directory format so PathHelper.GetRelativePath will compute external references correctly. this.referenceRelocationPath = PathHelper.NormalizeDirectory(referenceRelocationPath); outputStream = this.OutStream; bodyStream = new MemoryStream(); this.OutStream = bodyStream; }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.NativeAdapter.Description.Description; // Profiling is supported through pix markers IsProfilingSupported = true; // Command lists are thread-safe and execute deferred IsDeferred = true; bool isDebug = (deviceCreationFlags & DeviceCreationFlags.Debug) != 0; if (isDebug) { SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer(); } // Default fallback if (graphicsProfiles.Length == 0) { graphicsProfiles = new[] { GraphicsProfile.Level_11_0 } } ; // Create Device D3D12 with feature Level based on profile for (int index = 0; index < graphicsProfiles.Length; index++) { var graphicsProfile = graphicsProfiles[index]; try { // D3D12 supports only feature level 11+ var level = graphicsProfile.ToFeatureLevel(); if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) { level = SharpDX.Direct3D.FeatureLevel.Level_11_0; } nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level); RequestedProfile = graphicsProfile; CurrentFeatureLevel = level; break; } catch (Exception) { if (index == graphicsProfiles.Length - 1) { throw; } } } // Describe and create the command queue. var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct); NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); //queueDesc.Type = CommandListType.Copy; NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); TimestampFrequency = NativeCommandQueue.TimestampFrequency; SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler); if (isDebug) { var debugDevice = nativeDevice.QueryInterfaceOrNull <DebugDevice>(); if (debugDevice != null) { var infoQueue = debugDevice.QueryInterfaceOrNull <InfoQueue>(); if (infoQueue != null) { MessageId[] disabledMessages = { // This happens when render target or depth stencil clear value is diffrent // than provided during resource allocation. MessageId.CleardepthstencilviewMismatchingclearvalue, MessageId.ClearrendertargetviewMismatchingclearvalue, // This occurs when there are uninitialized descriptors in a descriptor table, // even when a shader does not access the missing descriptors. MessageId.InvalidDescriptorHandle, // These happen when capturing with VS diagnostics MessageId.MapInvalidNullRange, MessageId.UnmapInvalidNullRange, }; // Disable irrelevant debug layer warnings InfoQueueFilter filter = new InfoQueueFilter { DenyList = new InfoQueueFilterDescription { Ids = disabledMessages } }; infoQueue.AddStorageFilterEntries(filter); //infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true); //infoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true); infoQueue.Dispose(); } debugDevice.Dispose(); } } // Prepare pools CommandAllocators = new CommandAllocatorPool(this); SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler); // Prepare descriptor allocators SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler); ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView); RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView); // Prepare copy command list (start it closed, so that every new use start with a Reset) NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct); NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null); NativeCopyCommandList.Close(); // Fence for next frame and resource cleaning nativeFence = NativeDevice.CreateFence(0, FenceFlags.None); nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None); }
/// <summary> /// Initializes this instance. /// </summary> /// <param name="adapter">The graphics adapter.</param> /// <param name="profile">The graphics profile.</param> protected void Initialize(GraphicsAdapter adapter, GraphicsProfile profile, PresentationParameters presentationParameters, object windowHandle) { throw new NotImplementedException(); }
/// <summary> /// Determines if alpha channel should be separated from a given texture's attribute and graphics profile /// </summary> /// <param name="alphaFormat">Alpha format for a texture</param> /// <param name="textureFormat">Texture format</param> /// <param name="platform">Platform</param> /// <param name="graphicsProfile">Level of graphics</param> /// <returns></returns> public static bool ShouldSeparateAlpha(AlphaFormat alphaFormat, TextureFormat textureFormat, PlatformType platform, GraphicsProfile graphicsProfile) { if (alphaFormat != AlphaFormat.None && textureFormat == TextureFormat.Compressed && platform == PlatformType.Android) { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: // Android with OpenGLES < 3.0 require alpha splitting if the image is compressed since ETC1 compresses only RGB return(true); case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: // Since OpenGLES 3.0, ETC2 RGBA is used instead of ETC1 RGB so alpha is compressed along with RGB; therefore, no need to split alpha return(false); default: throw new ArgumentOutOfRangeException("graphicsProfile"); } } return(false); }
public bool QueryRenderTargetFormat(GraphicsProfile graphicsProfile, SurfaceFormat format, DepthFormat depthFormat, int multiSampleCount, out SurfaceFormat selectedFormat, out DepthFormat selectedDepthFormat, out int selectedMultiSampleCount) { throw new NotImplementedException(); }
/// <summary> /// Creates a new instance of ContentWriter. /// </summary> /// <param name="compiler">The compiler object that created this writer.</param> /// <param name="output">The stream to write the XNB file to.</param> /// <param name="targetPlatform">The platform the XNB is intended for.</param> /// <param name="targetProfile">The graphics profile of the target.</param> /// <param name="compressContent">True if the content should be compressed.</param> /// <param name="rootDirectory">The root directory of the content.</param> /// <param name="referenceRelocationPath">The path of the XNB file, used to calculate relative paths for external references.</param> internal ContentWriter(ContentCompiler compiler, Stream output, TargetPlatform targetPlatform, GraphicsProfile targetProfile, bool compressContent, string rootDirectory, string referenceRelocationPath) : base(output) { if (compressContent) { throw new NotSupportedException("Content compression is not supported at this time."); } this.compiler = compiler; this.targetPlatform = targetPlatform; this.targetProfile = targetProfile; this.compressContent = compressContent; this.rootDirectory = rootDirectory; this.referenceRelocationPath = referenceRelocationPath; outputStream = this.OutStream; headerStream = new MemoryStream(); bodyStream = new MemoryStream(); this.OutStream = bodyStream; }
public static GraphicsDeviceService AddRef(IntPtr windowHandle, int width, int height, GraphicsProfile graphicsProfile) { if (Interlocked.Increment(ref _referenceCount) == 1) { _singletonInstance = new GraphicsDeviceService(windowHandle, width, height, graphicsProfile); } return(_singletonInstance); }
/// <summary> /// Initializes a new instance of the <see cref="GraphicsDevice" /> class. /// </summary> /// <param name="adapter">The graphics adapter.</param> /// <param name="graphicsProfile">The graphics profile.</param> /// <param name="presentationParameters">The presentation options.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="presentationParameters"/> is <see langword="null"/>. /// </exception> public GraphicsDevice( GraphicsAdapter adapter, GraphicsProfile graphicsProfile, PresentationParameters presentationParameters ) { if (presentationParameters == null) { throw new ArgumentNullException("presentationParameters"); } // Set the properties from the constructor parameters. Adapter = adapter; PresentationParameters = presentationParameters; GraphicsProfile = graphicsProfile; PresentationParameters.MultiSampleCount = MathHelper.ClosestMSAAPower( PresentationParameters.MultiSampleCount ); // Set up the IGLDevice GLDevice = FNAPlatform.CreateGLDevice(PresentationParameters, adapter); // The mouse needs to know this for faux-backbuffer mouse scaling. Input.Mouse.INTERNAL_BackBufferWidth = PresentationParameters.BackBufferWidth; Input.Mouse.INTERNAL_BackBufferHeight = PresentationParameters.BackBufferHeight; // The Touch Panel needs this too, for the same reason. Input.Touch.TouchPanel.DisplayWidth = PresentationParameters.BackBufferWidth; Input.Touch.TouchPanel.DisplayHeight = PresentationParameters.BackBufferHeight; // Force set the default render states. BlendState = BlendState.Opaque; DepthStencilState = DepthStencilState.Default; RasterizerState = RasterizerState.CullCounterClockwise; // Initialize the Texture/Sampler state containers int maxTextures = Math.Min(GLDevice.MaxTextureSlots, MAX_TEXTURE_SAMPLERS); int maxVertexTextures = MathHelper.Clamp( GLDevice.MaxTextureSlots - MAX_TEXTURE_SAMPLERS, 0, MAX_VERTEXTEXTURE_SAMPLERS ); vertexSamplerStart = GLDevice.MaxTextureSlots - maxVertexTextures; Textures = new TextureCollection( maxTextures, modifiedSamplers ); SamplerStates = new SamplerStateCollection( maxTextures, modifiedSamplers ); VertexTextures = new TextureCollection( maxVertexTextures, modifiedVertexSamplers ); VertexSamplerStates = new SamplerStateCollection( maxVertexTextures, modifiedVertexSamplers ); // Set the default viewport and scissor rect. Viewport = new Viewport(PresentationParameters.Bounds); ScissorRectangle = Viewport.Bounds; // Set the initial swap interval GLDevice.SetPresentationInterval( PresentationParameters.PresentationInterval ); // Allocate the pipeline cache to be used by Effects PipelineCache = new PipelineCache(this); #if WIIU_GAMEPAD wiiuStream = DRC.drc_new_streamer(); if (wiiuStream == IntPtr.Zero) { FNALoggerEXT.LogError("Failed to alloc GamePad stream!"); return; } if (DRC.drc_start_streamer(wiiuStream) < 1) // ??? { FNALoggerEXT.LogError("Failed to start GamePad stream!"); DRC.drc_delete_streamer(wiiuStream); wiiuStream = IntPtr.Zero; return; } DRC.drc_enable_system_input_feeder(wiiuStream); wiiuPixelData = new byte[ PresentationParameters.BackBufferWidth * PresentationParameters.BackBufferHeight * 4 ]; #endif }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.NativeAdapter.Description.Description; // Profiling is supported through pix markers IsProfilingSupported = true; // Command lists are thread-safe and execute deferred IsDeferred = true; if ((deviceCreationFlags & DeviceCreationFlags.Debug) != 0) { SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer(); } // Default fallback if (graphicsProfiles.Length == 0) { graphicsProfiles = new[] { GraphicsProfile.Level_11_0 } } ; // Create Device D3D12 with feature Level based on profile for (int index = 0; index < graphicsProfiles.Length; index++) { var graphicsProfile = graphicsProfiles[index]; try { // D3D12 supports only feature level 11+ var level = graphicsProfile.ToFeatureLevel(); if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) { level = SharpDX.Direct3D.FeatureLevel.Level_11_0; } nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level); RequestedProfile = graphicsProfile; CurrentFeatureLevel = level; break; } catch (Exception) { if (index == graphicsProfiles.Length - 1) { throw; } } } // Describe and create the command queue. var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct); NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); //queueDesc.Type = CommandListType.Copy; NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler); // Prepare pools CommandAllocators = new CommandAllocatorPool(this); SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler); // Prepare descriptor allocators SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler); ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView); RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView); // Prepare copy command list (start it closed, so that every new use start with a Reset) NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct); NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null); NativeCopyCommandList.Close(); // Fence for next frame and resource cleaning nativeFence = NativeDevice.CreateFence(0, FenceFlags.None); nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None); }
/// <summary> /// Tests to see if the adapter supports the requested profile. /// </summary> /// <param name="graphicsProfile">The graphics profile.</param> /// <returns>true if the profile is supported</returns> public bool IsProfileSupported(GraphicsProfile graphicsProfile) { NullHelper.ToImplement(); return(false); }
protected override void UpgradeAsset(AssetMigrationContext context, PackageVersion currentVersion, PackageVersion targetVersion, dynamic asset, PackageLoadingAssetFile assetFile, OverrideUpgraderHint overrideHint) { int backBufferWidth = asset.BackBufferWidth ?? 1280; asset.RemoveChild("BackBufferWidth"); int backBufferHeight = asset.BackBufferHeight ?? 720; asset.RemoveChild("BackBufferHeight"); GraphicsProfile profile = asset.DefaultGraphicsProfile ?? GraphicsProfile.Level_9_1; asset.RemoveChild("DefaultGraphicsProfile"); ColorSpace colorSpace = asset.ColorSpace ?? ColorSpace.Linear; asset.RemoveChild("ColorSpace"); DisplayOrientation displayOrientation = asset.DisplayOrientation ?? DisplayOrientation.Default; asset.RemoveChild("DisplayOrientation"); TextureQuality textureQuality = asset.TextureQuality ?? TextureQuality.Fast; asset.RemoveChild("TextureQuality"); var renderingMode = RenderingMode.HDR; if (asset.RenderingMode != null) { if (asset.RenderingMode == "LDR") { renderingMode = RenderingMode.LDR; } } asset.RemoveChild("RenderingMode"); var configurations = new DynamicYamlArray(new YamlSequenceNode()); asset.Defaults = configurations; dynamic renderingSettings = new DynamicYamlMapping(new YamlMappingNode { Tag = "!SiliconStudio.Xenko.Graphics.RenderingSettings,SiliconStudio.Xenko.Graphics" }); renderingSettings.DefaultBackBufferWidth = backBufferWidth; renderingSettings.DefaultBackBufferHeight = backBufferHeight; renderingSettings.DefaultGraphicsProfile = profile; renderingSettings.ColorSpace = colorSpace; renderingSettings.DisplayOrientation = displayOrientation; asset.Defaults.Add(renderingSettings); dynamic editorSettings = new DynamicYamlMapping(new YamlMappingNode { Tag = "!SiliconStudio.Xenko.Assets.EditorSettings,SiliconStudio.Xenko.Assets" }); editorSettings.RenderingMode = renderingMode; asset.Defaults.Add(editorSettings); dynamic textSettings = new DynamicYamlMapping(new YamlMappingNode { Tag = "!SiliconStudio.Xenko.Assets.Textures.TextureSettings,SiliconStudio.Xenko.Assets" }); textSettings.TextureQuality = textureQuality; asset.Defaults.Add(textSettings); dynamic physicsSettings = new DynamicYamlMapping(new YamlMappingNode { Tag = "!SiliconStudio.Xenko.Physics.PhysicsSettings,SiliconStudio.Xenko.Physics" }); asset.Defaults.Add(physicsSettings); var defaultFilters = new DynamicYamlArray(new YamlSequenceNode()); asset.PlatformFilters = defaultFilters; asset.PlatformFilters.Add("PowerVR SGX 54[0-9]"); asset.PlatformFilters.Add("Adreno \\(TM\\) 2[0-9][0-9]"); asset.PlatformFilters.Add("Adreno (TM) 320"); asset.PlatformFilters.Add("Adreno (TM) 330"); asset.PlatformFilters.Add("Adreno \\(TM\\) 4[0-9][0-9]"); asset.PlatformFilters.Add("NVIDIA Tegra"); asset.PlatformFilters.Add("Intel(R) HD Graphics"); asset.PlatformFilters.Add("^Mali\\-4"); asset.PlatformFilters.Add("^Mali\\-T6"); asset.PlatformFilters.Add("^Mali\\-T7"); }
/// <summary> /// Creates a new hidden graphics device. /// </summary> public static GraphicsDevice CreateHiddenGraphicsDevice(GraphicsProfile profile) { return(CreateHiddenGraphicsDevice(1, 1, profile)); }
protected void PerformTest(Action<Game> testAction, GraphicsProfile? profileOverride = null, bool takeSnapshot = false) { // create the game instance var typeGame = GetType(); var game = (GameTestBase)Activator.CreateInstance(typeGame); if (profileOverride.HasValue) game.GraphicsDeviceManager.PreferredGraphicsProfile = new[] { profileOverride.Value }; // register the tests. game.FrameGameSystem.IsUnitTestFeeding = true; game.FrameGameSystem.Draw(() => testAction(game)); if (takeSnapshot) game.FrameGameSystem.TakeScreenshot(); RunGameTest(game); }
/// <summary> /// Write the content to a XNB file. /// </summary> /// <param name="stream">The stream to write the XNB file to.</param> /// <param name="content">The content to write to the XNB file.</param> /// <param name="targetPlatform">The platform the XNB is intended for.</param> /// <param name="targetProfile">The graphics profile of the target.</param> /// <param name="compress">True if the content should be compressed.</param> /// <param name="rootDirectory">The root directory of the content.</param> /// <param name="referenceRelocationPath">The path of the XNB file, used to calculate relative paths for external references.</param> public void Compile(Stream stream, object content, TargetPlatform targetPlatform, GraphicsProfile targetProfile, bool compressContent, string rootDirectory, string referenceRelocationPath) { using (var writer = new ContentWriter(this, stream, targetPlatform, targetProfile, compressContent, rootDirectory, referenceRelocationPath)) { writer.WriteObject(content); writer.Flush(); } }
/// <summary> /// Creates a new hidden graphics device. /// </summary> public static GraphicsDevice CreateHiddenGraphicsDevice(int width, int height, GraphicsProfile profile) { // Create graphics device System.Windows.Forms.Form dummy = new System.Windows.Forms.Form(); PresentationParameters parameters = new PresentationParameters(); parameters.BackBufferWidth = 1; parameters.BackBufferHeight = 1; parameters.DeviceWindowHandle = dummy.Handle; GraphicsAdapter.UseNullDevice = true; return(new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, parameters)); }
/// <summary> /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile. /// </summary> /// <param name="textureFormat">The desired type of format for the output texture</param> /// <param name="platform">The graphics platform</param> /// <param name="graphicsProfile">The graphics profile</param> /// <param name="textureSizeInput">The texture size input.</param> /// <param name="textureSizeRequested">The texture size requested.</param> /// <param name="generateMipmaps">Indicate if mipmaps should be generated for the output texture</param> /// <param name="logger">The logger.</param> /// <returns>true if the texture size is supported</returns> /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception> public static Size2 FindBestTextureSize(TextureFormat textureFormat, GraphicsPlatform platform, GraphicsProfile graphicsProfile, Size2 textureSizeInput, Size2 textureSizeRequested, bool generateMipmaps, ILogger logger) { var textureSize = textureSizeRequested; // compressed DDS files has to have a size multiple of 4. if (platform == GraphicsPlatform.Direct3D11 && textureFormat == TextureFormat.Compressed && ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0)) { textureSize.Width = unchecked ((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3)); textureSize.Height = unchecked ((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3)); } var maxTextureSize = 0; // determine if the desired size if valid depending on the graphics profile switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: if (generateMipmaps && (!IsPowerOfTwo(textureSize.Width) || !IsPowerOfTwo(textureSize.Height))) { // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD textureSize.Width = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024); textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024); logger.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize); } maxTextureSize = graphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048; break; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: maxTextureSize = 8192; break; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: maxTextureSize = 16384; break; } if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize) { logger.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " + "Please reduce texture size or upgrade your graphic profile.", graphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height); return(new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize))); } return(textureSize); }
public bool IsProfileSupported(GraphicsProfile profile) { return(true); }
/// <summary> /// Determine the output format of the texture depending on the platform and asset properties. /// </summary> /// <param name="parameters">The conversion request parameters</param> /// <param name="graphicsPlatform">The graphics platform</param> /// <param name="graphicsProfile">The graphics profile</param> /// <param name="imageSize">The texture output size</param> /// <param name="inputImageFormat">The pixel format of the input image</param> /// <param name="textureAsset">The texture asset</param> /// <returns>The pixel format to use as output</returns> public static PixelFormat DetermineOutputFormat(TextureAsset textureAsset, TextureConvertParameters parameters, Int2 imageSize, PixelFormat inputImageFormat, PlatformType platform, GraphicsPlatform graphicsPlatform, GraphicsProfile graphicsProfile) { if (textureAsset.SRgb && ((int)parameters.GraphicsProfile < (int)GraphicsProfile.Level_9_2 && parameters.GraphicsPlatform != GraphicsPlatform.Direct3D11)) { throw new NotSupportedException("sRGB is not supported on OpenGl profile level {0}".ToFormat(parameters.GraphicsProfile)); } var hint = textureAsset.Hint; // Default output format var outputFormat = PixelFormat.R8G8B8A8_UNorm; switch (textureAsset.Format) { case TextureFormat.Compressed: switch (parameters.Platform) { case PlatformType.Android: if (inputImageFormat.IsHDR()) { outputFormat = inputImageFormat; } else if (textureAsset.SRgb) { outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; } else { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: outputFormat = textureAsset.Alpha == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm; break; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android outputFormat = textureAsset.Alpha == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA; break; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } } break; case PlatformType.iOS: // PVRTC works only for square POT textures if (inputImageFormat.IsHDR()) { outputFormat = inputImageFormat; } else if (textureAsset.SRgb) { outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; } else if (SupportPVRTC(imageSize)) { switch (textureAsset.Alpha) { case AlphaFormat.None: // DXT1 handles 1-bit alpha channel outputFormat = PixelFormat.PVRTC_4bpp_RGB; break; case AlphaFormat.Mask: // DXT1 handles 1-bit alpha channel // TODO: Not sure about the equivalent here? outputFormat = PixelFormat.PVRTC_4bpp_RGBA; break; case AlphaFormat.Explicit: case AlphaFormat.Interpolated: // DXT3 is good at sharp alpha transitions // TODO: Not sure about the equivalent here? outputFormat = PixelFormat.PVRTC_4bpp_RGBA; break; default: throw new ArgumentOutOfRangeException(); } } else { outputFormat = PixelFormat.R8G8B8A8_UNorm; } break; case PlatformType.Windows: case PlatformType.WindowsPhone: case PlatformType.WindowsStore: switch (parameters.GraphicsPlatform) { case GraphicsPlatform.Direct3D11: // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx // http://www.reedbeta.com/blog/2012/02/12/understanding-bcn-texture-compression-formats/ // ---------------------------------------------- ---------------------------------------------------- --- --------------------------------- // Source data Minimum required data compression resolution Recommended format Minimum supported feature level // ---------------------------------------------- ---------------------------------------------------- --- --------------------------------- // Three-channel color with alpha channel Three color channels (5 bits:6 bits:5 bits), with 0 or 1 bit(s) of alpha BC1 Direct3D 9.1 (color maps, cutout color maps - 1 bit alpha, normal maps if memory is tight) // Three-channel color with alpha channel Three color channels (5 bits:6 bits:5 bits), with 4 bits of alpha BC2 Direct3D 9.1 (idem) // Three-channel color with alpha channel Three color channels (5 bits:6 bits:5 bits) with 8 bits of alpha BC3 Direct3D 9.1 (color maps with alpha, packing color and mono maps together) // One-channel color One color channel (8 bits) BC4 Direct3D 10 (Height maps, gloss maps, font atlases, any gray scales image) // Two-channel color Two color channels (8 bits:8 bits) BC5 Direct3D 10 (Tangent space normal maps) // Three-channel high dynamic range (HDR) color Three color channels (16 bits:16 bits:16 bits) in "half" floating point* BC6H Direct3D 11 (HDR images) // Three-channel color, alpha channel optional Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha BC7 Direct3D 11 (High quality color maps, Color maps with full alpha) switch (textureAsset.Alpha) { case AlphaFormat.None: case AlphaFormat.Mask: // DXT1 handles 1-bit alpha channel outputFormat = textureAsset.SRgb ? PixelFormat.BC1_UNorm_SRgb : PixelFormat.BC1_UNorm; break; case AlphaFormat.Explicit: // DXT3 is good at sharp alpha transitions outputFormat = textureAsset.SRgb ? PixelFormat.BC2_UNorm_SRgb : PixelFormat.BC2_UNorm; break; case AlphaFormat.Interpolated: // DXT5 is good at alpha gradients outputFormat = textureAsset.SRgb ? PixelFormat.BC3_UNorm_SRgb : PixelFormat.BC3_UNorm; break; default: throw new ArgumentOutOfRangeException(); } // Overrides the format when profile is >= 10.0 // Support some specific optimized formats based on the hint or input type if (parameters.GraphicsProfile >= GraphicsProfile.Level_10_0) { if (hint == TextureHint.NormalMap) { outputFormat = PixelFormat.BC5_SNorm; } else if (hint == TextureHint.Grayscale) { outputFormat = PixelFormat.BC4_UNorm; } else if (inputImageFormat.IsHDR()) { // BC6H is too slow to compile //outputFormat = parameters.GraphicsProfile >= GraphicsProfile.Level_11_0 && textureAsset.Alpha == AlphaFormat.None ? PixelFormat.BC6H_Uf16 : inputImageFormat; outputFormat = inputImageFormat; } // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now } break; case GraphicsPlatform.OpenGLES: // OpenGLES on Windows if (inputImageFormat.IsHDR()) { outputFormat = inputImageFormat; } else if (textureAsset.SRgb) { outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; } else { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: case GraphicsProfile.Level_9_2: case GraphicsProfile.Level_9_3: outputFormat = textureAsset.Alpha == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm; break; case GraphicsProfile.Level_10_0: case GraphicsProfile.Level_10_1: case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: case GraphicsProfile.Level_11_2: // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android outputFormat = textureAsset.Alpha == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA; break; default: throw new ArgumentOutOfRangeException("graphicsProfile"); } } break; default: // OpenGL on Windows // TODO: Need to handle OpenGL Desktop compression outputFormat = textureAsset.SRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm; break; } break; default: throw new NotSupportedException("Platform " + parameters.Platform + " is not supported by TextureTool"); } break; case TextureFormat.Color16Bits: if (textureAsset.SRgb) { outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; } else { if (textureAsset.Alpha == AlphaFormat.None) { outputFormat = PixelFormat.B5G6R5_UNorm; } else if (textureAsset.Alpha == AlphaFormat.Mask) { outputFormat = PixelFormat.B5G5R5A1_UNorm; } } break; case TextureFormat.Color32Bits: if (textureAsset.SRgb) { outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; } break; case TextureFormat.AsIs: outputFormat = inputImageFormat; break; default: throw new ArgumentOutOfRangeException(); } return(outputFormat); }
/// <summary> /// Creates a typical graphics compositor programatically. It can render meshes, sprites and backgrounds. /// </summary> public static GraphicsCompositor CreateDefault(bool enablePostEffects, string modelEffectName = "XenkoForwardShadingEffect", CameraComponent camera = null, Color4?clearColor = null, GraphicsProfile graphicsProfile = GraphicsProfile.Level_10_0) { var opaqueRenderStage = new RenderStage("Opaque", "Main") { SortMode = new StateChangeSortMode() }; var transparentRenderStage = new RenderStage("Transparent", "Main") { SortMode = new BackToFrontSortMode() }; var shadowCasterRenderStage = new RenderStage("ShadowMapCaster", "ShadowMapCaster") { SortMode = new FrontToBackSortMode() }; var shadowCasterCubeMapRenderStage = new RenderStage("ShadowMapCasterCubeMap", "ShadowMapCasterCubeMap") { SortMode = new FrontToBackSortMode() }; var shadowCasterParaboloidRenderStage = new RenderStage("ShadowMapCasterParaboloid", "ShadowMapCasterParaboloid") { SortMode = new FrontToBackSortMode() }; var postProcessingEffects = enablePostEffects ? new PostProcessingEffects { ColorTransforms = { Transforms = { new ToneMap() }, }, } : null; if (postProcessingEffects != null) { postProcessingEffects.DisableAll(); postProcessingEffects.ColorTransforms.Enabled = true; } var singleView = new ForwardRenderer { Clear = { Color = clearColor ?? Color.CornflowerBlue }, OpaqueRenderStage = opaqueRenderStage, TransparentRenderStage = transparentRenderStage, ShadowMapRenderStages = { shadowCasterRenderStage, shadowCasterParaboloidRenderStage, shadowCasterCubeMapRenderStage }, PostEffects = postProcessingEffects, }; var forwardLighting = graphicsProfile >= GraphicsProfile.Level_10_0 ? new ForwardLightingRenderFeature { LightRenderers = { new LightAmbientRenderer(), new LightSkyboxRenderer(), new LightDirectionalGroupRenderer(), new LightPointGroupRenderer(), new LightSpotGroupRenderer(), new LightClusteredPointSpotGroupRenderer(), }, ShadowMapRenderer = new ShadowMapRenderer { Renderers = { new LightDirectionalShadowMapRenderer { ShadowCasterRenderStage = shadowCasterRenderStage }, new LightSpotShadowMapRenderer { ShadowCasterRenderStage = shadowCasterRenderStage }, new LightPointShadowMapRendererParaboloid { ShadowCasterRenderStage = shadowCasterParaboloidRenderStage }, new LightPointShadowMapRendererCubeMap { ShadowCasterRenderStage = shadowCasterCubeMapRenderStage }, }, }, } : new ForwardLightingRenderFeature { LightRenderers = { new LightAmbientRenderer(), new LightDirectionalGroupRenderer(), new LightSkyboxRenderer(), new LightPointGroupRenderer(), new LightSpotGroupRenderer(), }, }; var cameraSlot = new SceneCameraSlot(); if (camera != null) { camera.Slot = cameraSlot.ToSlotId(); } return(new GraphicsCompositor { Cameras = { cameraSlot }, RenderStages = { opaqueRenderStage, transparentRenderStage, shadowCasterRenderStage, shadowCasterParaboloidRenderStage, shadowCasterCubeMapRenderStage, }, RenderFeatures = { new MeshRenderFeature { RenderFeatures = { new TransformRenderFeature(), new SkinningRenderFeature(), new MaterialRenderFeature(), new ShadowCasterRenderFeature(), forwardLighting, }, RenderStageSelectors = { new MeshTransparentRenderStageSelector { EffectName = modelEffectName, OpaqueRenderStage = opaqueRenderStage, TransparentRenderStage = transparentRenderStage, }, new ShadowMapRenderStageSelector { EffectName = modelEffectName + ".ShadowMapCaster", ShadowMapRenderStage = shadowCasterRenderStage, }, new ShadowMapRenderStageSelector { EffectName = modelEffectName + ".ShadowMapCasterParaboloid", ShadowMapRenderStage = shadowCasterParaboloidRenderStage, }, new ShadowMapRenderStageSelector { EffectName = modelEffectName + ".ShadowMapCasterCubeMap", ShadowMapRenderStage = shadowCasterCubeMapRenderStage, }, }, PipelineProcessors = { new MeshPipelineProcessor { TransparentRenderStage = transparentRenderStage }, new ShadowMeshPipelineProcessor { ShadowMapRenderStage = shadowCasterRenderStage }, new ShadowMeshPipelineProcessor { ShadowMapRenderStage = shadowCasterParaboloidRenderStage, DepthClipping = true }, new ShadowMeshPipelineProcessor { ShadowMapRenderStage = shadowCasterCubeMapRenderStage, DepthClipping = true }, } }, new SpriteRenderFeature { RenderStageSelectors = { new SpriteTransparentRenderStageSelector { EffectName = "Test", OpaqueRenderStage = opaqueRenderStage, TransparentRenderStage = transparentRenderStage, } }, }, new BackgroundRenderFeature { RenderStageSelectors = { new SimpleGroupToRenderStageSelector { RenderStage = opaqueRenderStage, EffectName = "Test", } }, }, }, Game = new SceneCameraRenderer() { Child = singleView, Camera = cameraSlot }, Editor = singleView, SingleView = singleView, }); }
private static string ShaderProfileFromGraphicsProfile(GraphicsProfile graphicsProfile) { switch (graphicsProfile) { case GraphicsProfile.Level_9_1: return "4_0_level_9_1"; case GraphicsProfile.Level_9_2: return "4_0_level_9_2"; case GraphicsProfile.Level_9_3: return "4_0_level_9_3"; case GraphicsProfile.Level_10_0: return "4_0"; case GraphicsProfile.Level_10_1: return "4_1"; case GraphicsProfile.Level_11_0: case GraphicsProfile.Level_11_1: return "5_0"; } throw new ArgumentException("graphicsProfile"); }
public bool IsProfileSupported(GraphicsProfile graphicsProfile) { throw new NotImplementedException(); }
//[return: MarshalAs(UnmanagedType.U1)] internal bool IsProfileSupported(Enum deviceType, GraphicsProfile graphicsProfile) { return(true); }
/// <summary> /// Write the content to a XNB file. /// </summary> /// <param name="stream">The stream to write the XNB file to.</param> /// <param name="content">The content to write to the XNB file.</param> /// <param name="targetPlatform">The platform the XNB is intended for.</param> /// <param name="targetProfile">The graphics profile of the target.</param> /// <param name="compress">True if the content should be compressed.</param> /// <param name="rootDirectory">The root directory of the content.</param> /// <param name="referenceRelocationPath">The path of the XNB file, used to calculate relative paths for external references.</param> public void Compile(Stream stream, object content, TargetPlatform targetPlatform, GraphicsProfile targetProfile, bool compressContent, string rootDirectory, string referenceRelocationPath) { using (var writer = new ContentWriter(this, stream, targetPlatform, targetProfile, compressContent, rootDirectory, referenceRelocationPath)) { writer.WriteObject(content); writer.Flush(); } }
public GraphicsDevice(GraphicsAdapter adapter, GraphicsProfile graphicsProfile, PresentationParameters presentationParameters) { }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.NativeAdapter.Description.Description; // Profiling is supported through pix markers IsProfilingSupported = true; // Map GraphicsProfile to D3D11 FeatureLevel creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags; // Create Device D3D11 with feature Level based on profile for (int index = 0; index < graphicsProfiles.Length; index++) { var graphicsProfile = graphicsProfiles[index]; try { // D3D12 supports only feature level 11+ var level = graphicsProfile.ToFeatureLevel(); // INTEL workaround: it seems Intel driver doesn't support properly feature level 9.x. Fallback to 10. if (Adapter.VendorId == 0x8086) { if (level < SharpDX.Direct3D.FeatureLevel.Level_10_0) { level = SharpDX.Direct3D.FeatureLevel.Level_10_0; } } #if STRIDE_PLATFORM_WINDOWS_DESKTOP // If RenderDoc is loaded, force level 11+ if (GetModuleHandle("renderdoc.dll") != IntPtr.Zero) { if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) { level = SharpDX.Direct3D.FeatureLevel.Level_11_0; } } #endif nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, level); // INTEL workaround: force ShaderProfile to be 10+ as well if (Adapter.VendorId == 0x8086) { if (graphicsProfile < GraphicsProfile.Level_10_0 && (!ShaderProfile.HasValue || ShaderProfile.Value < GraphicsProfile.Level_10_0)) { ShaderProfile = GraphicsProfile.Level_10_0; } } RequestedProfile = graphicsProfile; break; } catch (Exception) { if (index == graphicsProfiles.Length - 1) { throw; } } } nativeDeviceContext = nativeDevice.ImmediateContext; // We keep one reference so that it doesn't disappear with InternalMainCommandList ((IUnknown)nativeDeviceContext).AddReference(); if (IsDebugMode) { GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext"); } }
public bool IsProfileSupported(GraphicsProfile graphicsProfile) { // TODO: Check OpenGL version? // TODO: ES specific code? return(graphicsProfile <= supportedGraphicsProfile); }
public SpriteSheetParameters(SpriteSheetAsset sheetAsset, Dictionary <SpriteInfo, string> imageToTextureUrl, PlatformType platform, GraphicsPlatform graphicsPlatform, GraphicsProfile graphicsProfile, TextureQuality textureQuality, ColorSpace colorSpace) { ImageToTextureUrl = imageToTextureUrl; SheetAsset = sheetAsset; Platform = platform; GraphicsPlatform = graphicsPlatform; GraphicsProfile = graphicsProfile; TextureQuality = textureQuality; ColorSpace = colorSpace; }
public ImportParameters(SpriteSheetAssetCompiler.SpriteSheetParameters spriteSheetParameters) { var asset = spriteSheetParameters.SheetAsset; // Compute SRgb usage // If Texture is in auto mode, use the global settings, else use the settings overridden by the texture asset. IsSRgb = asset.ColorSpace.ToColorSpace(spriteSheetParameters.ColorSpace, TextureHint.Color) == ColorSpace.Linear; DesiredSize = new Size2(100, 100); IsSizeInPercentage = true; DesiredFormat = asset.Format; DesiredAlpha = asset.Alpha; TextureHint = TextureHint.Color; GenerateMipmaps = asset.GenerateMipmaps; PremultiplyAlpha = asset.PremultiplyAlpha; ColorKeyColor = asset.ColorKeyColor; ColorKeyEnabled = asset.ColorKeyEnabled; TextureQuality = spriteSheetParameters.TextureQuality; GraphicsPlatform = spriteSheetParameters.GraphicsPlatform; GraphicsProfile = spriteSheetParameters.GraphicsProfile; Platform = spriteSheetParameters.Platform; }
public bool IsProfileSupported(GraphicsProfile graphicsProfile) { // TODO: Check OpenGL version? // TODO: ES specific code? return graphicsProfile <= supportedGraphicsProfile; }
protected void PerformDrawTest(Action<Game, RenderDrawContext, RenderFrame> drawTestAction, GraphicsProfile? profileOverride = null, string subTestName = null, bool takeSnapshot = true) { // create the game instance var typeGame = GetType(); var game = (GameTestBase)Activator.CreateInstance(typeGame); if (profileOverride.HasValue) game.GraphicsDeviceManager.PreferredGraphicsProfile = new[] { profileOverride.Value }; // register the tests. game.FrameGameSystem.IsUnitTestFeeding = true; var testName = TestContext.CurrentContext.Test.FullName+subTestName; if (takeSnapshot) game.FrameGameSystem.TakeScreenshot(null, testName); // add the render callback var graphicsCompositor = new SceneGraphicsCompositorLayers { Master = { Renderers = { new ClearRenderFrameRenderer { Color = Color.Green, Name = "Clear frame" }, new SceneDelegateRenderer((context, frame) => drawTestAction(game, context, frame)), } } }; var scene = new Scene { Settings = { GraphicsCompositor = graphicsCompositor } }; game.SceneSystem.SceneInstance = new SceneInstance(Services, scene); RunGameTest(game); }
protected virtual bool IsPreferredProfileAvailable(GraphicsProfile[] preferredProfiles, out GraphicsProfile availableProfile) { availableProfile = GraphicsProfile.Level_9_1; var graphicsProfiles = Enum.GetValues(typeof(GraphicsProfile)); foreach (var graphicsAdapter in GraphicsAdapterFactory.Adapters) { foreach (var graphicsProfileValue in graphicsProfiles) { var graphicsProfile = (GraphicsProfile)graphicsProfileValue; if (graphicsProfile > availableProfile && graphicsAdapter.IsProfileSupported(graphicsProfile)) { availableProfile = graphicsProfile; } } } foreach (var preferredProfile in preferredProfiles) { if (availableProfile >= preferredProfile) { return(true); } } return(false); }
public override void Validate(GraphicsProfile? targetProf) { throw new NotImplementedException(); }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private unsafe void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != VkDevice.Null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.Description; vkGetPhysicalDeviceProperties(NativePhysicalDevice, out var physicalDeviceProperties); ConstantBufferDataPlacementAlignment = (int)physicalDeviceProperties.limits.minUniformBufferOffsetAlignment; TimestampFrequency = (long)(1.0e9 / physicalDeviceProperties.limits.timestampPeriod); // Resolution in nanoseconds RequestedProfile = graphicsProfiles.Last(); var queueProperties = vkGetPhysicalDeviceQueueFamilyProperties(NativePhysicalDevice); //IsProfilingSupported = queueProperties[0].TimestampValidBits > 0; // Command lists are thread-safe and execute deferred IsDeferred = true; // TODO VULKAN // Create Vulkan device based on profile float queuePriorities = 0; var queueCreateInfo = new VkDeviceQueueCreateInfo { sType = VkStructureType.DeviceQueueCreateInfo, queueFamilyIndex = 0, queueCount = 1, pQueuePriorities = &queuePriorities, }; var enabledFeature = new VkPhysicalDeviceFeatures { fillModeNonSolid = true, shaderClipDistance = true, shaderCullDistance = true, samplerAnisotropy = true, depthClamp = true, }; var extensionProperties = vkEnumerateDeviceExtensionProperties(NativePhysicalDevice); var availableExtensionNames = new List <string>(); var desiredExtensionNames = new List <string>(); for (int index = 0; index < extensionProperties.Length; index++) { fixed(VkExtensionProperties *extensionPropertiesPtr = extensionProperties) { var namePointer = new IntPtr(extensionPropertiesPtr[index].extensionName); var name = Marshal.PtrToStringAnsi(namePointer); availableExtensionNames.Add(name); } } desiredExtensionNames.Add(KHRSwapchainExtensionName); if (!availableExtensionNames.Contains(KHRSwapchainExtensionName)) { throw new InvalidOperationException(); } if (availableExtensionNames.Contains(EXTDebugMarkerExtensionName) && IsDebugMode) { desiredExtensionNames.Add(EXTDebugMarkerExtensionName); IsProfilingSupported = true; } var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray(); try { var deviceCreateInfo = new VkDeviceCreateInfo { sType = VkStructureType.DeviceCreateInfo, queueCreateInfoCount = 1, pQueueCreateInfos = &queueCreateInfo, enabledExtensionCount = (uint)enabledExtensionNames.Length, ppEnabledExtensionNames = enabledExtensionNames.Length > 0 ? (byte **)Core.Interop.Fixed(enabledExtensionNames) : null, pEnabledFeatures = &enabledFeature, }; vkCreateDevice(NativePhysicalDevice, &deviceCreateInfo, null, out nativeDevice); } finally { foreach (var enabledExtensionName in enabledExtensionNames) { Marshal.FreeHGlobal(enabledExtensionName); } } vkGetDeviceQueue(nativeDevice, 0, 0, out NativeCommandQueue); //// Prepare copy command list (start it closed, so that every new use start with a Reset) var commandPoolCreateInfo = new VkCommandPoolCreateInfo { sType = VkStructureType.CommandPoolCreateInfo, queueFamilyIndex = 0, //device.NativeCommandQueue.FamilyIndex flags = VkCommandPoolCreateFlags.ResetCommandBuffer }; vkCreateCommandPool(NativeDevice, &commandPoolCreateInfo, null, out NativeCopyCommandPool); var commandBufferAllocationInfo = new VkCommandBufferAllocateInfo { sType = VkStructureType.CommandBufferAllocateInfo, level = VkCommandBufferLevel.Primary, commandPool = NativeCopyCommandPool, commandBufferCount = 1 }; VkCommandBuffer nativeCommandBuffer; vkAllocateCommandBuffers(NativeDevice, &commandBufferAllocationInfo, &nativeCommandBuffer); NativeCopyCommandBuffer = nativeCommandBuffer; DescriptorPools = new HeapPool(this); nativeResourceCollector = new NativeResourceCollector(this); graphicsResourceLinkCollector = new GraphicsResourceLinkCollector(this); EmptyTexelBufferInt = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_UInt); EmptyTexelBufferFloat = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_Float); EmptyTexture = Texture.New2D(this, 1, 1, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.ShaderResource); }
/// <summary> /// Initializes the specified device. /// </summary> /// <param name="graphicsProfiles">The graphics profiles.</param> /// <param name="deviceCreationFlags">The device creation flags.</param> /// <param name="windowHandle">The window handle.</param> private unsafe void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) { if (nativeDevice != Device.Null) { // Destroy previous device ReleaseDevice(); } rendererName = Adapter.Description; SharpVulkan.ResultExtensions.SuppressValidationExceptions = (deviceCreationFlags & DeviceCreationFlags.NoValidationExceptions) != 0; PhysicalDeviceProperties physicalDeviceProperties; NativePhysicalDevice.GetProperties(out physicalDeviceProperties); ConstantBufferDataPlacementAlignment = (int)physicalDeviceProperties.Limits.MinUniformBufferOffsetAlignment; TimestampFrequency = (long)(1.0e9 / physicalDeviceProperties.Limits.TimestampPeriod); // Resolution in nanoseconds RequestedProfile = graphicsProfiles.Last(); var queueProperties = NativePhysicalDevice.QueueFamilyProperties; //IsProfilingSupported = queueProperties[0].TimestampValidBits > 0; // Command lists are thread-safe and execute deferred IsDeferred = true; // TODO VULKAN // Create Vulkan device based on profile uint queuePriorities = 0; var queueCreateInfo = new DeviceQueueCreateInfo { StructureType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = 0, QueueCount = 1, QueuePriorities = new IntPtr(&queuePriorities) }; var enabledFeature = new PhysicalDeviceFeatures { FillModeNonSolid = true, ShaderClipDistance = true, ShaderCullDistance = true, SamplerAnisotropy = true, DepthClamp = true, }; var extensionProperties = NativePhysicalDevice.GetDeviceExtensionProperties(); var availableExtensionNames = new List <string>(); var desiredExtensionNames = new List <string>(); for (int index = 0; index < extensionProperties.Length; index++) { var namePointer = new IntPtr(Interop.Fixed(ref extensionProperties[index].ExtensionName)); var name = Marshal.PtrToStringAnsi(namePointer); availableExtensionNames.Add(name); } desiredExtensionNames.Add("VK_KHR_swapchain"); if (!availableExtensionNames.Contains("VK_KHR_swapchain")) { throw new InvalidOperationException(); } if (availableExtensionNames.Contains("VK_EXT_debug_marker") && IsDebugMode) { desiredExtensionNames.Add("VK_EXT_debug_marker"); IsProfilingSupported = true; } var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray(); try { var deviceCreateInfo = new DeviceCreateInfo { StructureType = StructureType.DeviceCreateInfo, QueueCreateInfoCount = 1, QueueCreateInfos = new IntPtr(&queueCreateInfo), EnabledExtensionCount = (uint)enabledExtensionNames.Length, EnabledExtensionNames = enabledExtensionNames.Length > 0 ? new IntPtr(Interop.Fixed(enabledExtensionNames)) : IntPtr.Zero, EnabledFeatures = new IntPtr(&enabledFeature) }; nativeDevice = NativePhysicalDevice.CreateDevice(ref deviceCreateInfo); } finally { foreach (var enabledExtensionName in enabledExtensionNames) { Marshal.FreeHGlobal(enabledExtensionName); } } NativeCommandQueue = nativeDevice.GetQueue(0, 0); //// Prepare copy command list (start it closed, so that every new use start with a Reset) var commandPoolCreateInfo = new CommandPoolCreateInfo { StructureType = StructureType.CommandPoolCreateInfo, QueueFamilyIndex = 0, //device.NativeCommandQueue.FamilyIndex Flags = CommandPoolCreateFlags.ResetCommandBuffer }; NativeCopyCommandPool = NativeDevice.CreateCommandPool(ref commandPoolCreateInfo); var commandBufferAllocationInfo = new CommandBufferAllocateInfo { StructureType = StructureType.CommandBufferAllocateInfo, Level = CommandBufferLevel.Primary, CommandPool = NativeCopyCommandPool, CommandBufferCount = 1 }; CommandBuffer nativeCommandBuffer; NativeDevice.AllocateCommandBuffers(ref commandBufferAllocationInfo, &nativeCommandBuffer); NativeCopyCommandBuffer = nativeCommandBuffer; DescriptorPools = new HeapPool(this); nativeResourceCollector = new NativeResourceCollector(this); graphicsResourceLinkCollector = new GraphicsResourceLinkCollector(this); EmptyTexelBuffer = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_Float); dummyTexture = Texture.New2D(this, 1, 1, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource); }
protected override bool IsPreferredProfileAvailable(GraphicsProfile[] preferredProfiles, out GraphicsProfile availableProfile) { Assert.True(base.IsPreferredProfileAvailable(preferredProfiles, out availableProfile), $"This test requires the '{preferredProfiles.Min()}' graphic profile. It has been ignored"); return(true); }
/// <summary> /// Tests to see if the adapter supports the requested profile. /// </summary> /// <param name="graphicsProfile">The graphics profile.</param> /// <returns>true if the profile is supported</returns> public bool IsProfileSupported(GraphicsProfile graphicsProfile) { return SharpDX.Direct3D11.Device.IsSupportedFeatureLevel(this.NativeAdapter, (SharpDX.Direct3D.FeatureLevel)graphicsProfile); }
public VisualTestSoftEdge(GraphicsProfile profile) : base("VisualTestSoftEdge", profile) { }