Esempio n. 1
0
 protected GraphicsDeviceCreationTests(
     GraphicsBackend backend,
     bool validation = false)
     : base(backend, validation)
 {
 }
Esempio n. 2
0
        public static void Main()
        {
            bool            onWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            var             window    = new Sdl2Window("Veldrid Render Demo", 100, 100, 960, 540, SDL_WindowFlags.Resizable | SDL_WindowFlags.OpenGL, RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
            RenderContext   rc;
            GraphicsBackend preferredBackend = Preferences.Instance.PreferredBackend;

            if (preferredBackend == GraphicsBackend.Vulkan)
            {
                rc = CreateVulkanRenderContext(window);
            }
            else if (preferredBackend == GraphicsBackend.Direct3D11 && onWindows)
            {
                rc = CreateDefaultD3dRenderContext(window);
            }
            else if (preferredBackend == GraphicsBackend.OpenGLES && onWindows)
            {
                rc = CreateDefaultOpenGLESRenderContext(window);
            }
            else
            {
                rc = CreateDefaultOpenGLRenderContext(window);
            }

            var options        = new List <RenderDemo.RendererOption>();
            var openGLOption   = new RenderDemo.RendererOption("OpenGL", () => CreateDefaultOpenGLRenderContext(window));
            var openGLESOption = new RenderDemo.RendererOption("OpenGL ES", () => CreateDefaultOpenGLESRenderContext(window));
            var d3dOption      = new RenderDemo.RendererOption("Direct3D", () => CreateDefaultD3dRenderContext(window));
            var vulkanOption   = new RenderDemo.RendererOption("Vulkan", () => CreateVulkanRenderContext(window));

            if (onWindows)
            {
                if (rc is OpenGLRenderContext)
                {
                    options.Add(openGLOption);
                    options.Add(d3dOption);
                    options.Add(openGLESOption);
                    options.Add(vulkanOption);
                }
                else if (rc is OpenGLESRenderContext)
                {
                    options.Add(openGLESOption);
                    options.Add(openGLOption);
                    options.Add(d3dOption);
                    options.Add(vulkanOption);
                }
                else if (rc is VkRenderContext)
                {
                    options.Add(vulkanOption);
                    options.Add(d3dOption);
                    options.Add(openGLOption);
                    options.Add(openGLESOption);
                }
                else
                {
                    Debug.Assert(rc is D3DRenderContext);
                    options.Add(d3dOption);
                    options.Add(vulkanOption);
                    options.Add(openGLOption);
                    options.Add(openGLESOption);
                }
            }
            else
            {
                if (rc is VkRenderContext)
                {
                    options.Add(vulkanOption);
                    options.Add(openGLOption);
                }
                else
                {
                    options.Add(openGLOption);
                    options.Add(vulkanOption);
                }
            }

            RenderDemo.RunDemo(rc, window, options.ToArray());
        }
Esempio n. 3
0
 public VeldridSurfaceView(Context context, GraphicsBackend backend)
     : this(context, backend, new GraphicsDeviceOptions())
 {
 }
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ToolChain" /> class.  For now tool chains are single tools, but this
        /// could be easily extended to support multiple steps.
        /// </summary>
        /// <param name="graphicsBackend">The graphics backend.</param>
        /// <param name="backendType">Type of the backend.</param>
        /// <param name="createBackend">The function to create the backend.</param>
        /// <param name="compileFunction">The compile function.</param>
        /// <param name="createHeadless">The function to create a headless graphics device.</param>
        /// <param name="createWindowed">The create windowed.</param>
        /// <exception cref="ArgumentOutOfRangeException">backendType</exception>
        private ToolChain(GraphicsBackend graphicsBackend,
                          Type backendType,
                          Func <Compilation, LanguageBackend> createBackend,
                          CompileDelegate compileFunction,
                          Func <GraphicsDevice> createHeadless,
                          Func <GraphicsDevice> createWindowed)
        {
            if (!backendType.IsSubclassOf(typeof(LanguageBackend)))
            {
                throw new ArgumentOutOfRangeException(nameof(backendType),
                                                      $"{backendType.Name} is not a descendent of {nameof(LanguageBackend)}.");
            }

            BackendType = backendType;

            // Calculate name (strip 'Backend' if present).
            Name = backendType.Name;
            if (Name.EndsWith("Backend", StringComparison.InvariantCultureIgnoreCase))
            {
                Name = Name.Substring(0, Name.Length - 7);
            }

            GraphicsBackend = graphicsBackend;

            ToolFeatures features = ToolFeatures.None;

            if (createBackend != null)
            {
                _createBackend = createBackend;
                features      |= ToolFeatures.Transpilation;
            }

            if (compileFunction != null)
            {
                _compileFunction = compileFunction;

                features |= ToolFeatures.Compilation;
            }

            // Don't allow creation of graphics devices on CI Servers.
            bool onCiServer = Environment.GetEnvironmentVariable("CI")?.ToLowerInvariant() == "true";

            if (!onCiServer &&
                createHeadless != null &&
                GraphicsDevice.IsBackendSupported(graphicsBackend))
            {
                try
                {
                    // Try to create a headless graphics device
                    using (createHeadless()) { }
                    _createHeadless = createHeadless;
                    features       |= ToolFeatures.HeadlessGraphicsDevice;
                }
                catch
                {
                }
            }

            // TODO For future expansion, will need to review signature of function.
            if (!onCiServer &&
                createWindowed != null &&
                GraphicsDevice.IsBackendSupported(graphicsBackend))
            {
                try
                {
                    // Try to create a headless graphics device
                    using (createWindowed()) { }
                    _createWindowed = createWindowed;
                    features       |= ToolFeatures.WindowedGraphicsDevice;
                }
                catch
                {
                }
            }

            Features = features;

            // Add to lookup dictionaries.
            _toolChainsByGraphicsBackend.Add(graphicsBackend, this);
            _toolChainsByBackendType.Add(backendType, this);
        }
Esempio n. 5
0
        internal static bool IsFormatSupported(OpenGLExtensions extensions, PixelFormat format, GraphicsBackend backend)
        {
            switch (format)
            {
            case PixelFormat.ETC2_R8_G8_B8_UNorm:
            case PixelFormat.ETC2_R8_G8_B8_A1_UNorm:
            case PixelFormat.ETC2_R8_G8_B8_A8_UNorm:
                return(extensions.GLESVersion(3, 0) || extensions.GLVersion(4, 3));

            case PixelFormat.BC1_Rgb_UNorm:
            case PixelFormat.BC1_Rgb_UNorm_SRgb:
            case PixelFormat.BC1_Rgba_UNorm:
            case PixelFormat.BC1_Rgba_UNorm_SRgb:
            case PixelFormat.BC2_UNorm:
            case PixelFormat.BC2_UNorm_SRgb:
            case PixelFormat.BC3_UNorm:
            case PixelFormat.BC3_UNorm_SRgb:
                return(extensions.IsExtensionSupported("GL_EXT_texture_compression_s3tc"));

            case PixelFormat.BC4_UNorm:
            case PixelFormat.BC4_SNorm:
            case PixelFormat.BC5_UNorm:
            case PixelFormat.BC5_SNorm:
                return(extensions.GLVersion(3, 0) || extensions.IsExtensionSupported("GL_ARB_texture_compression_rgtc"));

            case PixelFormat.BC7_UNorm:
            case PixelFormat.BC7_UNorm_SRgb:
                return(extensions.GLVersion(4, 2) || extensions.IsExtensionSupported("GL_ARB_texture_compression_bptc") ||
                       extensions.IsExtensionSupported("GL_EXT_texture_compression_bptc"));

            case PixelFormat.B8_G8_R8_A8_UNorm:
            case PixelFormat.B8_G8_R8_A8_UNorm_SRgb:
            case PixelFormat.R10_G10_B10_A2_UInt:
            case PixelFormat.R10_G10_B10_A2_UNorm:
                return(backend == GraphicsBackend.OpenGL);

            default:
                return(true);
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Gets the <see cref="ToolChain" /> for the specified <see cref="GraphicsBackend"/>.
 /// </summary>
 /// <param name="graphicsBackend">The graphics backend.</param>
 /// <returns>
 /// A <see cref="ToolChain" /> if available; otherwise <see langword="null" />.
 /// </returns>
 public static ToolChain Get(GraphicsBackend graphicsBackend) =>
 _toolChainsByGraphicsBackend.TryGetValue(graphicsBackend, out ToolChain toolChain)
         ? toolChain
         : null;
Esempio n. 7
0
 /// <summary>
 /// Gets the graphicsBackends, ensuring it has the required features.
 /// </summary>
 /// <param name="requiredFeatures">The required features.</param>
 /// <param name="graphicsBackend">The graphics backend.</param>
 /// <returns></returns>
 /// <exception cref="ShaderGen.Tests.Tools.RequiredToolFeatureMissingException"></exception>
 public static ToolChain Require(
     ToolFeatures requiredFeatures,
     GraphicsBackend graphicsBackend) =>
 Requires(requiredFeatures, true, graphicsBackend).SingleOrDefault();
Esempio n. 8
0
 public void UpdateBackend(GraphicsDevice gd)
 {
     _backend         = gd.BackendType;
     _useReverseDepth = gd.IsDepthRangeZeroToOne;
     UpdatePerspectiveMatrix();
 }
Esempio n. 9
0
        /// <summary>
        ///     Loads the native library `sokol_gfx` and sets up the function pointers given a specified
        ///     <see cref="GraphicsBackend" />.
        /// </summary>
        /// <param name="backend">The <see cref="GraphicsBackend" /> to load.</param>
        /// <remarks>
        ///     <para>
        ///         <see cref="LoadApi(GraphicsBackend)" /> will attempt to find the library path for `sokol_gfx` given
        ///         <paramref name="backend" /> by calling <see cref="LoadApi(string)" />.
        ///     </para>
        /// </remarks>
        public static void LoadApi(GraphicsBackend backend)
        {
            var libraryPath = GraphicsHelper.GetLibraryPath(backend, "sokol_gfx");

            LoadApi(libraryPath);
        }
Esempio n. 10
0
 public VeldridSurface(GraphicsBackend backend)
 {
     Backend = backend;
 }
Esempio n. 11
0
 public VeldridSurface(GraphicsBackend backend, GraphicsDeviceOptions gdOptions)
 {
     Backend = backend;
     GraphicsDeviceOptions = gdOptions;
 }
Esempio n. 12
0
        public static Alimer.Graphics.ShaderBytecode Compile(
            GraphicsBackend backend,
            string source,
            ShaderStages stage,
            string entryPoint = "",
            string fileName   = "")
        {
            if (string.IsNullOrEmpty(entryPoint))
            {
                entryPoint = GetDefaultEntryPoint(stage);
            }

            // We use legacy compiler for D3D11.
            bool isDxil = backend != GraphicsBackend.Direct3D11;

            if (isDxil)
            {
                var dxcShaderStage = GetDxcShaderStage(stage);
                var options        = new DxcCompilerOptions
                {
                };

                var result = DxcCompiler.Compile(dxcShaderStage, source, entryPoint, fileName, options);

                if (result.GetStatus() == 0)
                {
                    var blob     = result.GetResult();
                    var bytecode = GetBytesFromBlob(blob);

                    var containReflection = CreateDxcContainerReflection();
                    containReflection.Load(blob);
                    int hr = containReflection.FindFirstPartKind(DFCC_DXIL, out uint dxilPartIndex);
                    if (hr < 0)
                    {
                        //MessageBox.Show("Debug information not found in container.");
                        //return;
                    }

                    /*var f = containReflection.GetPartReflection(dxilPartIndex, typeof(ID3D12ShaderReflection).GUID, out var nativePtr);
                     * using (var shaderReflection = new ID3D12ShaderReflection(nativePtr))
                     * {
                     *  var shaderReflectionDesc = shaderReflection.Description;
                     *
                     *  foreach (var parameterDescription in shaderReflection.InputParameters)
                     *  {
                     *  }
                     *
                     *  foreach (var resource in shaderReflection.Resources)
                     *  {
                     *  }
                     * }*/

                    unsafe
                    {
                        var   part = containReflection.GetPartContent(dxilPartIndex);
                        uint *p    = (uint *)part.GetBufferPointer();
                        var   v    = DescribeProgramVersion(*p);
                    }

                    // Disassemble
                    //var disassembleBlob = compiler.Disassemble(blob);
                    //string disassemblyText = Dxc.GetStringFromBlob(disassembleBlob);

                    return(new Alimer.Graphics.ShaderBytecode(stage, bytecode));
                }
                else
                {
                    //var resultText = GetStringFromBlob(DxcCompiler, result.GetErrors());
                }
            }
            else
            {
                var shaderProfile = $"{GetShaderProfile(stage)}_5_0";
                var result        = Compiler.Compile(source,
                                                     entryPoint,
                                                     fileName,
                                                     shaderProfile,
                                                     out var blob,
                                                     out var errorMsgs);

                if (result.Failure)
                {
                    if (errorMsgs != null)
                    {
                        var errorText = errorMsgs.ConvertToString();
                    }
                }
                else
                {
                    var bytecode = blob.GetBytes();
                    return(new Alimer.Graphics.ShaderBytecode(stage, bytecode));
                }
            }

            return(default);
Esempio n. 13
0
 private void ChangeBackend(GraphicsBackend backend) => ChangeBackend(backend, false);
 public WindowBuilder SetBackend(GraphicsBackend backend)
 {
     preferredBackend = backend;
     return(this);
 }
Esempio n. 15
0
        public static unsafe void SetSDLGLContextAttributes(GraphicsDeviceOptions options, GraphicsBackend backend)
        {
            if (backend != GraphicsBackend.OpenGL && backend != GraphicsBackend.OpenGLES)
            {
                throw new VeldridException(
                          $"{nameof(backend)} must be {nameof(GraphicsBackend.OpenGL)} or {nameof(GraphicsBackend.OpenGLES)}.");
            }

            SDL_GLContextFlag contextFlags = options.Debug
                ? SDL_GLContextFlag.Debug | SDL_GLContextFlag.ForwardCompatible
                : SDL_GLContextFlag.ForwardCompatible;

            Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextFlags, (int)contextFlags);

            (int major, int minor) = GetMaxGLVersion(backend == GraphicsBackend.OpenGLES);

            if (backend == GraphicsBackend.OpenGL)
            {
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextProfileMask, (int)SDL_GLProfile.Core);
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMajorVersion, major);
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMinorVersion, minor);
            }
            else
            {
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextProfileMask, (int)SDL_GLProfile.ES);
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMajorVersion, major);
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMinorVersion, minor);
            }

            int depthBits   = 0;
            int stencilBits = 0;

            if (options.SwapchainDepthFormat.HasValue)
            {
                switch (options.SwapchainDepthFormat)
                {
                case PixelFormat.R16_UNorm:
                    depthBits = 16;
                    break;

                case PixelFormat.D24_UNorm_S8_UInt:
                    depthBits   = 24;
                    stencilBits = 8;
                    break;

                case PixelFormat.R32_Float:
                    depthBits = 32;
                    break;

                case PixelFormat.D32_Float_S8_UInt:
                    depthBits   = 32;
                    stencilBits = 8;
                    break;

                default:
                    throw new VeldridException("Invalid depth format: " + options.SwapchainDepthFormat.Value);
                }
            }

            int result = Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.DepthSize, depthBits);

            result = Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.StencilSize, stencilBits);

            if (options.SwapchainSrgbFormat)
            {
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.FramebufferSrgbCapable, 1);
            }
            else
            {
                Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.FramebufferSrgbCapable, 0);
            }
        }
Esempio n. 16
0
        public static WindowBase CreateMainWindow(Type windowType, WindowProps props = null, GraphicsBackend backend = GraphicsBackend.Direct3D11)
        {
#if DEBUG
            using Profiler fullProfiler = new Profiler(typeof(WindowBase));
#endif
            if (windowType == typeof(WindowsWindow))
            {
                return(new WindowsWindow(props ?? new WindowProps(), backend));
            }
            return(null);
        }
Esempio n. 17
0
 public static bool IsSupported(GraphicsBackend backend)
 {
     return(true); // TODO
 }
Esempio n. 18
0
 public static GraphicsDevice CreateGraphicsDevice(
     Sdl2Window window,
     GraphicsDeviceOptions options,
     GraphicsBackend preferredBackend) => CreateGraphicsDevice(window, options, preferredBackend, false);
Esempio n. 19
0
 /// <summary>
 /// Gets the graphicsBackends, ensuring it has the required features.
 /// </summary>
 /// <param name="graphicsBackend">The graphics backend.</param>
 /// <returns></returns>
 /// <exception cref="ShaderGen.Tests.Tools.RequiredToolFeatureMissingException"></exception>
 public static ToolChain Require(
     GraphicsBackend graphicsBackend) =>
 Requires(ToolFeatures.All, true, graphicsBackend).SingleOrDefault();
Esempio n. 20
0
 public static unsafe GraphicsDevice CreateDefaultOpenGLGraphicsDevice(
     GraphicsDeviceOptions options,
     Sdl2Window window,
     GraphicsBackend backend) => CreateDefaultOpenGLGraphicsDevice(options, window, backend, false);
Esempio n. 21
0
 /// <summary>
 /// Gets the graphicsBackends, ensuring it has the required features.
 /// </summary>
 /// <param name="requiredFeatures">The required features.</param>
 /// <param name="throwOnFail">if set to <c>true</c> throws an error if any of the <paramref name="graphicsBackends" />
 /// do not have the <paramref name="requiredFeatures">required features</paramref>.</param>
 /// <param name="graphicsBackend">The graphics backend.</param>
 /// <returns></returns>
 /// <exception cref="ShaderGen.Tests.Tools.RequiredToolFeatureMissingException"></exception>
 public static ToolChain Require(
     ToolFeatures requiredFeatures,
     bool throwOnFail,
     GraphicsBackend graphicsBackend) =>
 Requires(requiredFeatures, throwOnFail, graphicsBackend).SingleOrDefault();
Esempio n. 22
0
 public abstract void createScene(GraphicsBackend graphicsBackend, Sdl2Window contextWindow = null);
Esempio n. 23
0
        public static GraphicsDevice CreateGraphicsDevice(ILogger logger, Window window, GraphicsDeviceOptions options, GraphicsBackend backend)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            switch (backend)
            {
            case GraphicsBackend.OpenGL:
                return(CreateOpenGLGraphicsDevice(logger, window, options));

            case GraphicsBackend.Vulkan:
                return(CreateVulkanGraphicsDevice(window, options));

            default: throw new NotSupportedException($"Graphics backend {backend} not supported");
            }
        }
Esempio n. 24
0
 public RuntimeContext(GraphicsBackend backend)
 {
     this.backend = backend;
     Initialize();
 }
Esempio n. 25
0
        static void Main(string[] args)
        {
            //TransformTests();
            _startupOnly  = args.Contains("--startuponly");
            _useRenderDoc = args.Contains("--renderdoc") || args.Contains("-rd");
            if (args.Contains("-gl") || args.Contains("--opengl"))
            {
                _backend = GraphicsBackend.OpenGL;
            }
            if (args.Contains("-gles") || args.Contains("--opengles"))
            {
                _backend = GraphicsBackend.OpenGLES;
            }
            if (args.Contains("-vk") || args.Contains("--vulkan"))
            {
                _backend = GraphicsBackend.Vulkan;
            }
            if (args.Contains("-metal") || args.Contains("--metal"))
            {
                _backend = GraphicsBackend.Metal;
            }
            if (args.Contains("-d3d") || args.Contains("--direct3d"))
            {
                _backend = GraphicsBackend.Direct3D11;
            }
            if (args.Contains("-h") || args.Contains("--help") || args.Contains("/?") || args.Contains("help"))
            {
                DisplayUsage();
                return;
            }

            PerfTracker.StartupEvent("Entered main");
            //GraphTests();
            //return;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Required for code page 850 support in .NET Core
            PerfTracker.StartupEvent("Registered encodings");

            /*
             * Console.WriteLine("Entry point reached. Press enter to continue");
             * Console.ReadLine(); //*/

            var baseDir = FormatUtil.FindBasePath();

            if (baseDir == null)
            {
                throw new InvalidOperationException("No base directory could be found.");
            }

            PerfTracker.StartupEvent($"Found base directory {baseDir}");

            var logger   = new ConsoleLogger();
            var settings = new Settings {
                BasePath = baseDir
            };

            PerfTracker.StartupEvent("Registering asset manager");
            using var assets = new AssetManager();
            using var global = new EventExchange("Global", logger);
            Global           = global;

            Global
            // Need to register settings first, as the AssetConfigLocator relies on it.
            .Register <ISettings>(settings)
            .Register <IEngineSettings>(settings)
            .Register <IAssetManager>(assets)
            .Register <ITextureLoader>(assets)
            ;
            PerfTracker.StartupEvent("Registered asset manager");

            // Dump.CoreSprites(assets, baseDir);
            // Dump.CharacterSheets(assets);
            // Dump.Chests(assets);
            // Dump.ItemData(assets, baseDir);
            // Dump.MapEvents(assets, baseDir, MapDataId.Toronto2DGesamtkarteSpielbeginn);
            //return;

            RunGame(Global, baseDir);
        }
Esempio n. 26
0
        public static (Container, IsometricBuilder) SetupEngine(
            EventExchange exchange,
            int tileWidth, int tileHeight,
            int baseHeight, int tilesPerRow,
            GraphicsBackend backend, bool useRenderDoc, Rectangle?windowRect)
        {
            if (exchange == null)
            {
                throw new ArgumentNullException(nameof(exchange));
            }
            var framebuffer = new SimpleFramebuffer((uint)(tileWidth * tilesPerRow), (uint)tileHeight, "FB_Offscreen");
            var builder     = new IsometricBuilder(framebuffer, tileWidth, tileHeight, baseHeight, tilesPerRow);

#pragma warning disable CA2000 // Dispose objects before losing scopes
            var config        = exchange.Resolve <IGeneralConfig>();
            var shaderCache   = new ShaderCache(config.ResolvePath("$(CACHE)/ShaderCache"));
            var sceneRenderer = new SceneRenderer("MainPipeline", framebuffer)
                                .AddRenderer(new SpriteRenderer(framebuffer), typeof(VeldridSpriteBatch))
                                .AddRenderer(new EtmRenderer(framebuffer), typeof(EtmWindow))
            ;

            foreach (var shaderPath in exchange.Resolve <IModApplier>().ShaderPaths)
            {
                shaderCache.AddShaderPath(shaderPath);
            }

            var engine = new Engine(
                backend, useRenderDoc, false, windowRect != null, sceneRenderer, windowRect)
            ;

            var renderableSources = new IRenderableSource[]
            {
                new EtmManager(),
                new SpriteManager(),
            };

            var services = new Container("IsometricLayoutServices");
            services
            .Add(shaderCache)
            .Add(framebuffer)
            .Add(sceneRenderer)
            .Add(engine)
            .Add(new SpriteSamplerSource())
            .Add(new TextureSource())
            .Add(new ResourceLayoutSource())
            .Add(new VeldridCoreFactory())
            .Add(new SceneStack())
            .Add(new SceneManager()
                 .AddScene(new EmptyScene())
                 .AddScene((IScene) new IsometricBakeScene()
                           .Add(new PaletteManager())
                           .Add(builder)))
            ;

            foreach (var source in renderableSources)
            {
                if (source is IComponent component)
                {
                    services.Add(component);
                }
                sceneRenderer.AddSource(source);
            }

            return(services, builder);
        }
Esempio n. 27
0
 public SetBackendEvent(GraphicsBackend value)
 {
     Value = value;
 }
Esempio n. 28
0
        static void Main(string[] args)
        {
            _useOculus = true;
            if (!VRContext.IsOculusSupported())
            {
                _useOculus = false;
                if (!VRContext.IsOpenVRSupported())
                {
                    Console.WriteLine("This sample requires an Oculus or OpenVR-capable headset.");
                    return;
                }
            }

            Sdl2Window window = VeldridStartup.CreateWindow(
                new WindowCreateInfo(
                    Sdl2Native.SDL_WINDOWPOS_CENTERED, Sdl2Native.SDL_WINDOWPOS_CENTERED,
                    1280, 720,
                    WindowState.Normal,
                    "Veldrid.VirtualReality Sample"));

            VRContextOptions options = new VRContextOptions
            {
                EyeFramebufferSampleCount = TextureSampleCount.Count4
            };
            VRContext vrContext = _useOculus ? VRContext.CreateOculus(options) : VRContext.CreateOpenVR(options);

            GraphicsBackend backend = GraphicsBackend.Direct3D11;

            bool debug = false;

#if DEBUG
            debug = true;
#endif

            GraphicsDeviceOptions gdo = new GraphicsDeviceOptions(debug, null, false, ResourceBindingModel.Improved, true, true, true);

            if (backend == GraphicsBackend.Vulkan)
            {
                // Oculus runtime causes validation errors.
                gdo.Debug = false;
            }

            (GraphicsDevice gd, Swapchain sc) = CreateDeviceAndSwapchain(window, vrContext, backend, gdo);
            window.Resized += () => sc.Resize((uint)window.Width, (uint)window.Height);

            vrContext.Initialize(gd);

            ImGuiRenderer igr = new ImGuiRenderer(gd, sc.Framebuffer.OutputDescription, window.Width, window.Height, ColorSpaceHandling.Linear);
            window.Resized += () => igr.WindowResized(window.Width, window.Height);

            AssimpMesh mesh = new AssimpMesh(
                gd,
                vrContext.LeftEyeFramebuffer.OutputDescription,
                Path.Combine(AppContext.BaseDirectory, "cat", "cat.obj"),
                Path.Combine(AppContext.BaseDirectory, "cat", "cat_diff.png"));

            Skybox skybox = new Skybox(
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_ft.png")),
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_bk.png")),
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_lf.png")),
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_rt.png")),
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_up.png")),
                Image.Load(Path.Combine(AppContext.BaseDirectory, "skybox", "miramar_dn.png")));
            skybox.CreateDeviceObjects(gd, vrContext.LeftEyeFramebuffer.OutputDescription);

            CommandList windowCL = gd.ResourceFactory.CreateCommandList();
            CommandList eyesCL   = gd.ResourceFactory.CreateCommandList();

            MirrorTextureEyeSource eyeSource = MirrorTextureEyeSource.BothEyes;

            Stopwatch sw            = Stopwatch.StartNew();
            double    lastFrameTime = sw.Elapsed.TotalSeconds;

            while (window.Exists)
            {
                double newFrameTime = sw.Elapsed.TotalSeconds;
                double deltaSeconds = newFrameTime - lastFrameTime;
                lastFrameTime = newFrameTime;

                InputSnapshot snapshot = window.PumpEvents();
                if (!window.Exists)
                {
                    break;
                }
                InputTracker.UpdateFrameInput(snapshot);
                HandleInputs(deltaSeconds);

                igr.Update(1f / 60f, snapshot);

                if (ImGui.BeginMainMenuBar())
                {
                    if (ImGui.BeginMenu("Settings"))
                    {
                        if (ImGui.BeginMenu("Mirror Texture"))
                        {
                            if (ImGui.MenuItem("Both Eyes", null, eyeSource == MirrorTextureEyeSource.BothEyes))
                            {
                                eyeSource = MirrorTextureEyeSource.BothEyes;
                            }
                            if (ImGui.MenuItem("Left Eye", null, eyeSource == MirrorTextureEyeSource.LeftEye))
                            {
                                eyeSource = MirrorTextureEyeSource.LeftEye;
                            }
                            if (ImGui.MenuItem("Right Eye", null, eyeSource == MirrorTextureEyeSource.RightEye))
                            {
                                eyeSource = MirrorTextureEyeSource.RightEye;
                            }

                            ImGui.EndMenu();
                        }

                        if (ImGui.BeginMenu("VR API"))
                        {
                            if (ImGui.MenuItem("Oculus", null, _useOculus) && !_useOculus)
                            {
                                _useOculus       = true;
                                _switchVRContext = true;
                            }
                            if (ImGui.MenuItem("OpenVR", null, !_useOculus) && _useOculus)
                            {
                                _useOculus       = false;
                                _switchVRContext = true;
                            }

                            ImGui.EndMenu();
                        }

                        ImGui.EndMenu();
                    }

                    ImGui.EndMainMenuBar();
                }

                windowCL.Begin();
                windowCL.SetFramebuffer(sc.Framebuffer);
                windowCL.ClearColorTarget(0, new RgbaFloat(0f, 0f, 0.2f, 1f));
                vrContext.RenderMirrorTexture(windowCL, sc.Framebuffer, eyeSource);
                igr.Render(gd, windowCL);
                windowCL.End();
                gd.SubmitCommands(windowCL);
                gd.SwapBuffers(sc);

                HmdPoseState poses = vrContext.WaitForPoses();

                // Render Eyes
                eyesCL.Begin();

                eyesCL.PushDebugGroup("Left Eye");
                Matrix4x4 leftView = poses.CreateView(VREye.Left, _userPosition, -Vector3.UnitZ, Vector3.UnitY);
                RenderEye(eyesCL, vrContext.LeftEyeFramebuffer, mesh, skybox, poses.LeftEyeProjection, leftView);
                eyesCL.PopDebugGroup();

                eyesCL.PushDebugGroup("Right Eye");
                Matrix4x4 rightView = poses.CreateView(VREye.Right, _userPosition, -Vector3.UnitZ, Vector3.UnitY);
                RenderEye(eyesCL, vrContext.RightEyeFramebuffer, mesh, skybox, poses.RightEyeProjection, rightView);
                eyesCL.PopDebugGroup();

                eyesCL.End();
                gd.SubmitCommands(eyesCL);

                vrContext.SubmitFrame();

                if (_switchVRContext)
                {
                    _switchVRContext = false;
                    vrContext.Dispose();
                    vrContext = _useOculus ? VRContext.CreateOculus() : VRContext.CreateOpenVR();
                    vrContext.Initialize(gd);
                }
            }

            vrContext.Dispose();
            gd.Dispose();
        }
Esempio n. 29
0
 /// <summary>
 /// Creates a graphics device from an existing window.
 /// </summary>
 /// <param name="window">The window to create a graphics device from.</param>
 /// <param name="preferredBackend">The preferred graphics backend for the graphics device.</param>
 /// <returns>The new graphics device.</returns>
 public static GraphicsDevice CreateGraphicsDevice(IWindow window, GraphicsBackend preferredBackend)
 => CreateGraphicsDevice(window, new GraphicsDeviceOptions(), preferredBackend);
Esempio n. 30
0
 /// <summary>
 /// Creates a graphics device from an existing window.
 /// </summary>
 /// <param name="window">The window to create a graphics device from.</param>
 /// <param name="options">The graphics device options.</param>
 /// <param name="preferredBackend">The preferred graphics backend for the graphics device.</param>
 /// <returns>The new graphics device.</returns>
 public static GraphicsDevice CreateGraphicsDevice(
     IWindow window,
     GraphicsDeviceOptions options,
     GraphicsBackend preferredBackend) =>
 preferredBackend switch
 {