Beispiel #1
0
 public EglContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags)
 {
     if (mode == null)
     throw new ArgumentNullException("mode");
       if (window == null)
     throw new ArgumentNullException("window");
       EglContext eglContext = (EglContext) sharedContext;
       int major1;
       int minor1;
       if (!Egl.Initialize(window.Display, out major1, out minor1))
     throw new GraphicsContextException(string.Format("Failed to initialize EGL, error {0}.", (object) Egl.GetError()));
       this.WindowInfo = window;
       this.Mode = new EglGraphicsMode().SelectGraphicsMode(mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples, mode.AccumulatorFormat, mode.Buffers, mode.Stereo, major > 1 ? RenderableFlags.ES2 : RenderableFlags.ES);
       if (!this.Mode.Index.HasValue)
     throw new GraphicsModeException("Invalid or unsupported GraphicsMode.");
       IntPtr config = this.Mode.Index.Value;
       if (window.Surface == IntPtr.Zero)
     window.CreateWindowSurface(config);
       int[] attrib_list = new int[3]
       {
     12440,
     major,
     12344
       };
       this.HandleAsEGLContext = Egl.CreateContext(window.Display, config, eglContext != null ? eglContext.HandleAsEGLContext : IntPtr.Zero, attrib_list);
       this.MakeCurrent((IWindowInfo) window);
 }
		public SampleBrowser(Context context, IGraphicsContext graphicsContext, IWindowInfo windowInfo)
		{
			// TODO: Complete member initialization
			this.androidContext = context;
			this.GLGraphicsContext = graphicsContext;
			this.GlWindowInfo = windowInfo;
		}
 public RotateWidgetRenderableAsset(IGraphicsContext context)
 {
     _texture = context.LoadTexture2D("RotationWidget");
     _boundingBox = new AxisAlignedBoundingBox2D(0, 0, _texture.Height, _texture.Width);
     RenderingOffset = - _boundingBox.Center;
     Origin = _boundingBox.Center;
 }
Beispiel #4
0
        public AglContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext)
        {
            Debug.Print("Context Type: {0}", shareContext);
            Debug.Print("Window info: {0}", window);

            this.graphics_mode = mode;
            this.carbonWindow = (CarbonWindowInfo)window;

            if (shareContext is AglContext)
                shareContextRef = ((AglContext)shareContext).Handle.Handle;
			if (shareContext is GraphicsContext)
			{
				ContextHandle shareHandle = shareContext != null ?
					(shareContext as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

				shareContextRef = shareHandle.Handle;
			}

			if (shareContextRef == IntPtr.Zero)
			{
				Debug.Print("No context sharing will take place.");
			}

            CreateContext(mode, carbonWindow, shareContextRef, true);
        }
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     X11WindowInfo x11_win = (X11WindowInfo)window;
     //EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(x11_win.WindowHandle, Egl.GetDisplay(x11_win.Display));
     EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(x11_win.WindowHandle, Egl.GetDisplay(new IntPtr(0)));
     return new EglContext(handle, egl_win, shareContext, major, minor, flags);
 }
Beispiel #6
0
        /// <summary>
        /// 現在のコンテキストが持つテクスチャをすべて削除します。
        /// </summary>
        /// <remarks>
        /// OpenGLの終了時に呼ばれます。
        /// </remarks>
        public static void DeleteAll(IGraphicsContext context)
        {
            //var context = context;
            lock (textureListSync)
            {
                for (int index = 0; index < textureList.Count; )
                {
                    var texture = textureList[index].Target as Texture;
                    if (texture == null)
                    {
                        // 要素を削除したため、indexの更新は行いません。
                        textureList.RemoveAt(index);
                        continue;
                    }

                    if (texture.Context == context)
                    {
                        // テクスチャを削除
                        texture.Destroy();

                        // 要素を削除したため、indexの更新は行いません。
                        textureList.RemoveAt(index);
                        continue;
                    }

                    index += 1;
                }
            }
        }
Beispiel #7
0
        bool vsync = true;   // Default vsync value is defined as 1 (true) in EGL.

        #endregion

        #region Constructors

        public EglContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext,
            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
                throw new ArgumentNullException("mode");
            if (window == null)
                throw new ArgumentNullException("window");

            EglContext shared = (EglContext)sharedContext;

            int dummy_major, dummy_minor;
            if (!Egl.Initialize(window.Display, out dummy_major, out dummy_minor))
                throw new GraphicsContextException(String.Format("Failed to initialize EGL, error {0}.", Egl.GetError()));

            WindowInfo = window;

            Mode = new EglGraphicsMode().SelectGraphicsMode(mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples, mode.AccumulatorFormat, mode.Buffers, mode.Stereo);
            if (!Mode.Index.HasValue)
                throw new GraphicsModeException("Invalid or unsupported GraphicsMode.");
            IntPtr config = Mode.Index.Value;

            if (window.Surface == IntPtr.Zero)
                window.CreateWindowSurface(config);

            int[] attrib_list = new int[] { Egl.CONTEXT_CLIENT_VERSION, major, Egl.NONE };
            HandleAsEGLContext = Egl.CreateContext(window.Display, config, shared != null ? shared.HandleAsEGLContext : IntPtr.Zero, attrib_list);

            MakeCurrent(window);
        }
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     WinWindowInfo win_win = (WinWindowInfo)window;
     IntPtr egl_display = GetDisplay(win_win.DeviceContext);
     EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(win_win.WindowHandle, egl_display);
     return new EglContext(handle, egl_win, shareContext, major, minor, flags);
 }
 public override OpenTK.Graphics.IGraphicsContext CreateGLContext(
     GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering,
     int major, int minor, GraphicsContextFlags flags)
 {
     flags |= GraphicsContextFlags.Embedded;
     return base.CreateGLContext(mode, window, shareContext, directRendering, major, minor, flags);
 }
        internal iPhoneOSGraphicsContext(ContextHandle handle, IWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags)
        {
            // ignore mode, window

            iPhoneOSGraphicsContext shared = sharedContext as iPhoneOSGraphicsContext;

            EAGLRenderingAPI version = 0;
            if (major == 1 && minor == 1)
                version = EAGLRenderingAPI.OpenGLES1;
            else if (major == 2 && minor == 0)
                version = EAGLRenderingAPI.OpenGLES2;
            else if (major == 3 && minor == 0)
                version = EAGLRenderingAPI.OpenGLES3;
            else
                throw new ArgumentException (string.Format("Unsupported GLES version {0}.{1}.", major, minor));

            if (handle.Handle == IntPtr.Zero) {
                EAGLContext = shared != null && shared.EAGLContext != null
                    ? new EAGLContext(version, shared.EAGLContext.ShareGroup)
                    : new EAGLContext(version);
                contextHandle = new ContextHandle(EAGLContext.Handle);
            } else {
                EAGLContext = (EAGLContext) Runtime.GetNSObject (handle.Handle);
                contextHandle = handle;
            }
        }
        public SceneViewerControl()
        {
            Tabs = new ObservableCollection<SceneTabViewModel>();

            RemoveTab = new RelayCommand((obj) =>
            {
                Tabs.Remove(obj as SceneTabViewModel);
                //MessageBox.Show("New Folder!");
            });

            InitializeComponent();
            AssignPanelEventHandling(xna);

            ScenesControl.ItemsSource = Tabs;

            if (DesignerProperties.GetIsInDesignMode(this))
                return;

            _game = new MyGame(xna.Handle);
            _game.GameWorld.UpdateWorld = false;
            _context = _game.GraphicsContext;

            var gameWorldArg =
                new ConstructorArgument(
                    ApplicationProperties.ISceneViewerGameWorldArgName,
                    _game.GameWorld);
            _controller = DependencyInjectorHelper
                            .MainWindowKernel
                            .Get<ISceneViewerController>(gameWorldArg);
            _controller.Control = this;
        }
Beispiel #12
0
 public void CreateContext(bool direct, IGraphicsContext source)
 {
     if (!(this.Handle == ContextHandle.Zero))
     return;
       ++DummyGLContext.handle_count;
       this.Handle = new ContextHandle((IntPtr) DummyGLContext.handle_count);
 }
Beispiel #13
0
        public void Initialize()
        {
            // <Rant>
            // OpenTK has a great fuckup in its design here. It's absolutly nohm it possible to create
            // a render context for offscreen rendering without creating an OpenTK window.
            // before.
            // Passing Utilities.CreateDummyWindowInfo() or anything else will cause an invalid cast exception
            // Using Utilities.CreateWindowsWindowInfo(IntPtr.Zero) binds the code to windows only
            // Really great, why do i need to have a window in order to render to memory? -_-
            //</Rant>

            _window = new NativeWindow { Visible = false };
            _context = new GraphicsContext(GraphicsMode.Default, _window.WindowInfo, 2, 0, GraphicsContextFlags.Default);
            _context.MakeCurrent(_window.WindowInfo);
            _context.LoadAll();

            // create offscreen rendertarget with high precision
            _rtt = new RenderToTexture(1, 1, false, 4, typeof(float));

            int precision;
            int range;
            GL.GetShaderPrecisionFormat(OpenTK.Graphics.OpenGL.ShaderType.FragmentShader, ShaderPrecisionType.HighFloat, out range, out precision);
            Debug.WriteLine("Precision: {0}, Range {1}", precision, range);

            // init SL#
            Bindings.OpenTK.SLSharp.Init();
        }
Beispiel #14
0
 public override IGraphicsContext CreateGLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     WinWindowInfo win_win = (WinWindowInfo)window;
     EGLDisplay egl_display = Egl.GetDisplay(EGLNativeDisplayType.Default);  // Egl.GetDisplay(new EGLNativeDisplayType(win_win.DeviceContext));
     EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(win_win.WindowHandle, egl_display);
     return new EglContext(mode, egl_win, shareContext, major, minor, flags);
 }
        public static ShaderProgram CreateProgram(IGraphicsContext context, string vertexSource, string fragmentSource)
        {
            int vertID = context.CreateShader(ShaderType.VertexShader);
            int fragID = context.CreateShader(ShaderType.FragmentShader);

            context.ShaderSource(vertID, vertexSource);
            context.ShaderSource(fragID, fragmentSource);

            context.CompileShader(vertID);
            context.CompileShader(fragID);

            Debug.LogInfo(context.GetShaderInfoLog(vertID));
            Debug.LogInfo(context.GetShaderInfoLog(fragID));

            int programID = context.CreateProgram();

            context.AttachShader(programID, vertID);
            context.AttachShader(programID, fragID);

            context.LinkProgram(programID);

            Debug.LogInfo(context.GetProgramInfoLog(programID));

            return new ShaderProgram(context, vertID, fragID, programID);
        }
Beispiel #16
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     WinWindowInfo winWindowInfo = (WinWindowInfo) window;
       IntPtr display = this.GetDisplay(winWindowInfo.DeviceContext);
       EglWindowInfo window1 = new EglWindowInfo(winWindowInfo.WindowHandle, display);
       return (IGraphicsContext) new EglContext(handle, window1, shareContext, major, minor, flags);
 }
Beispiel #17
0
 public GraphicsObject()
 {
     context = GraphicsContext.CurrentContext;
     if (context == null)
         throw new InvalidOperationException("No OpenGL context found " +
             "for thread " + Thread.CurrentThread.ManagedThreadId);
 }
Beispiel #18
0
        public AglContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext,
            GetInt xoffset, GetInt yoffset)
        {
            Debug.Print("Share context: {0}", shareContext);
            Debug.Print("Window info: {0}", window);
            IntPtr shareContextRef = IntPtr.Zero;

            XOffset = xoffset;
            YOffset = yoffset;

            carbonWindow = window;

            if (shareContext is AglContext)
            {
                shareContextRef = ((AglContext)shareContext).Handle.Handle;
            }
            else if (shareContext is GraphicsContext)
            {
                ContextHandle shareHandle = shareContext != null ? (shareContext as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;
                shareContextRef = shareHandle.Handle;
            }

            if (shareContextRef == IntPtr.Zero)
            {
                Debug.Print("No context sharing will take place.");
            }

            CreateContext(mode, carbonWindow, shareContextRef, true);
        }
Beispiel #19
0
        int swap_interval = 1; // Default interval is defined as 1 in EGL.

        #endregion

        #region Constructors

        public EglContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext,
            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
                throw new ArgumentNullException("mode");
            if (window == null)
                throw new ArgumentNullException("window");

            EglContext shared = (EglContext)sharedContext;

            int dummy_major, dummy_minor;
            if (!Egl.Initialize(window.Display, out dummy_major, out dummy_minor))
                throw new GraphicsContextException(String.Format("Failed to initialize EGL, error {0}.", Egl.GetError()));

            WindowInfo = window;

            // Select an EGLConfig that matches the desired mode. We cannot use the 'mode'
            // parameter directly, since it may have originated on a different system (e.g. GLX)
            // and it may not support the desired renderer.
            Mode = new EglGraphicsMode().SelectGraphicsMode(mode.ColorFormat,
                mode.Depth, mode.Stencil, mode.Samples, mode.AccumulatorFormat,
                mode.Buffers, mode.Stereo,
                major > 1 ? RenderableFlags.ES2 : RenderableFlags.ES);
            if (!Mode.Index.HasValue)
                throw new GraphicsModeException("Invalid or unsupported GraphicsMode.");
            IntPtr config = Mode.Index.Value;

            if (window.Surface == IntPtr.Zero)
                window.CreateWindowSurface(config);

            int[] attrib_list = new int[] { Egl.CONTEXT_CLIENT_VERSION, major, Egl.NONE };
            HandleAsEGLContext = Egl.CreateContext(window.Display, config, shared != null ? shared.HandleAsEGLContext : IntPtr.Zero, attrib_list);

            MakeCurrent(window);
        }
Beispiel #20
0
 public GameWorld(IGraphicsContext graphicsContext)
 {
     _scenes = new List<Scene>();
     _activeSceneIndex = NO_ACTIVE_SCENE;
     _graphicsContext = graphicsContext;
     UpdateWorld = true;
 }
        public VertexBuffer(IGraphicsContext context, BufferUsageHint hint)
        {
            this.GraphicsContext = context;
            this.hint = hint;

            this.GraphicsContext.GenBuffers(1, out Handle);
        }
Beispiel #22
0
        public override void QueueRenderCommands(GameTime gameTime, Renderer renderer, IGraphicsContext context)
        {
            List<TerrainNode> nodesToRender = new List<TerrainNode>();

            renderer.EnqueueLight(dlight);

            // todo: maybe can parallelize
            for (int i = 0; i < rootNodes.Length; i++)
            {
                if (rootNodes[i] != null)
                {
                    List<TerrainNode> nodesFromThisCubeFace = new List<TerrainNode>();
                    findNodesToRender(nodesFromThisCubeFace, rootNodes[i], context.CurrentCamera);
                    nodesToRender.AddRange(nodesFromThisCubeFace);
                }
            }

            int nodeCount = nodesToRender.Count;
            NodeCount = nodeCount;
            if (nodeCount > 0)
            {
                TerrainVertex[] vertices = nodesToRender.SelectMany(node => node.Geometry).ToArray();

                var command = GenerateRenderCommand();
                (command as RenderDeferredCommand<TerrainVertex>).NumVertices = vertices.Length;
                vertexBuffer.SetData(vertices);

                renderer.EnqueueDeferred(command as IRenderDeferredCommand);
            }
        }
 public FreeMovementRenderableAsset(IGraphicsContext context)
 {
     _texture = context.LoadTexture2D("freeMovementWidget");
     _boundingBox = new AxisAlignedBoundingBox2D(0, 0, _texture.Height, _texture.Width);
     RenderingOffset = -AABoundingBox.Center;
     Origin = AABoundingBox.Center;
 }
 protected RenderManager(IGraphicsContext graphics)
 {
     _graphics = graphics;
     // todo: subscribe to changes to asset libraries and build a dirty list for each library which will be processed on the next call to UpdateAssets. also observe changes to group dormancy.
     // 1. if a mesh has been removed, check the asset group and if it's empty, destroy the buffer. ignore removed meshes; we'll leave them in place for performance reasons.
     // 2. if a mesh has been added or updated, rebuild the buffer for now. later we may be able to optimise to do in-place buffer updates if it's an issue, but it probably won't be.
 }
        public override void Draw(IGraphicsContext gc)
        {
            int depth = CountParentDepth ();
            Color color = _Colors [depth]; // CountParentDepth is expensive - so don't call ComponentColor here...
            Color contactColor = color;
            if (IsNotEmptyString (TypeName) == false)
            {
                color = Color.Crimson;
            }
            if (IsNotEmptyString (Name) == false)
            {
                color = Color.Red;
            }

            gc.Color = color;
            DrawComponent (gc, _Bounds.Left, _Bounds.Top, _Bounds.Width, _Bounds.Height, 20, 2+depth, color);
            gc.Color = contactColor;
            gc.Thickness = 2 + depth;
            if (Selected)
            {
                foreach (IGlyph contact in ContactPoints)
                {
                    contact.Draw (gc);
                }
            }
        }
 // Necessary to allow creation of dummy GraphicsContexts (see CreateDummyContext static method).
 GraphicsContext(ContextHandle handle)
 {
     implementation = new OpenTK.Platform.Dummy.DummyGLContext(handle);
     lock (SyncRoot)
     {
         available_contexts.Add((implementation as IGraphicsContextInternal).Context, new WeakReference(this));
     }
 }
Beispiel #27
0
 public EglContext(ContextHandle handle, EglWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags)
 {
     if (handle == ContextHandle.Zero)
     throw new ArgumentException("handle");
       if (window == null)
     throw new ArgumentNullException("window");
       this.Handle = handle;
 }
 public void CreateContext(bool direct, IGraphicsContext source)
 {
     if (Handle == ContextHandle.Zero)
     {
         ++handle_count;
         Handle = new ContextHandle((IntPtr)handle_count);
     }
 }
		public AndroidGraphicsContext (GraphicsMode mode, IWindowInfo window, IGraphicsContext sharedContext,
										int major, int minor, GraphicsContextFlags flags)
		{
			if (major < 1 || major > 3)
				throw new ArgumentException (string.Format("Unsupported GLES version {0}.{1}.", major, minor));

			Init (mode, window, sharedContext, major, minor, flags);
		}
 public override void Draw(IGraphicsContext GC)
 {
     base.Draw (GC);
     string s = _PortName;
     using (Brush brush = new System.Drawing.SolidBrush (Color.Black))
     {
         GC.DrawString (s, brush, 10, new Point (Bounds.Right + 10, Bounds.Top), false);
     }
 }
Beispiel #31
0
        public void Render(GameTime gameTime, IGraphicsContext context)
        {
            var device        = context.Device;
            var renderContext = context.RenderContext;

            // clear render queues
            normalQueue.Clear();
            deferredQueue.Clear();
            postProcessQueue.Clear();
            lightQueue.Clear();

            // HACK: update current camera... camera probably needs to be a GameObject
            context.CurrentCamera.Update(gameTime);

            // Depth First Traversal of Scene Graph to queue render commands
            Engine.SceneGraph.QueueRenderCommands(gameTime, this, context);

            PrepareForNewFrame(device);

            // render deferred queue to gbuffer 1st
            gbuffer.SetAsRenderTarget();
            gbuffer.Clear();

            while (deferredQueue.Count > 0)
            {
                var command = deferredQueue.Dequeue();
                ProcessRenderCommand(command, context);
            }

            // switch to scene target
            device.Clear(sceneTarget, Color.Black);
            device.SetRenderTargets(sceneTarget);

            // render all the lights to shade deferred objects
            while (lightQueue.Count > 0)
            {
                var light = lightQueue.Dequeue();
                gbuffer.RenderDirectionalLight(light);
            }

            // render normal queue to scene target
            // note that we're carrying over depth info from the deferred queue
            // since we haven't changed depth buffers
            while (normalQueue.Count > 0)
            {
                var command = normalQueue.Dequeue();
                ProcessRenderCommand(command, context);
            }

            // apply post processes that need to run on the MSAA render target
            // before it is resolved into the backbuffer
            while (postProcessQueue.Count > 0)
            {
                var command = postProcessQueue.Dequeue();
                ProcessRenderCommand(command, context);
            }

            // resolve MSAA scene target to back buffer
            device.Copy((GraphicsResource)sceneTarget, 0, (GraphicsResource)device.BackBuffer, 0, SharpDX.DXGI.Format.R8G8B8A8_UNorm);

            device.SetRenderTargets(device.BackBuffer);
            RenderDiagnostics(context);

            // Present
            device.Present();

            // commit the changes to the image source
            if (context.ImageSourcePresenter != null)
            {
                var renderTarget = ((GraphicsDeviceService)context.GraphicsService).BackBuffer;
                context.ImageSourcePresenter.Commit(renderTarget);
            }
        }
Beispiel #32
0
        /// <summary>
        /// Initializes the <see cref="GLWidget"/> with its given values and creates a <see cref="GraphicsContext"/>.
        /// </summary>
        private void Initialize()
        {
            _Initialized = true;

            // If this looks uninitialized...  initialize.
            if (ColorBPP == 0)
            {
                ColorBPP = 32;

                if (DepthBPP == 0)
                {
                    DepthBPP = 16;
                }
            }

            ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

            ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

            int buffers = 2;

            if (SingleBuffer)
            {
                buffers--;
            }

            GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

            if (Configuration.RunningOnWindows)
            {
                Console.WriteLine("OpenTK running on windows");
            }
            else if (Configuration.RunningOnMacOS)
            {
                Console.WriteLine("OpenTK running on OSX");
            }
            else
            {
                Console.WriteLine("OpenTK running on X11");
            }

#if GTK3
            IntPtr widgetWindowHandle = this.Window.Handle;
#else
            IntPtr widgetWindowHandle = this.GdkWindow.Handle;
#endif

            // IWindowInfo
            if (Configuration.RunningOnWindows)
            {
                _WindowInfo = WinWindowsInfoInitializer.Initialize(widgetWindowHandle);
            }
            else if (Configuration.RunningOnMacOS)
            {
                _WindowInfo = OSXWindowInfoInitializer.Initialize(widgetWindowHandle);
            }
            else
            {
                _WindowInfo = XWindowInfoInitializer.Initialize(graphicsMode, this.Display.Handle, this.Screen.Number, widgetWindowHandle, this.Screen.RootWindow.Handle);
            }

            // GraphicsContext
            _GraphicsContext = new GraphicsContext(graphicsMode, _WindowInfo, GlVersionMajor, GlVersionMinor, GraphicsContextFlags);
            _GraphicsContext.MakeCurrent(_WindowInfo);

            if (GraphicsContext.ShareContexts)
            {
                Interlocked.Increment(ref _GraphicsContextCount);

                if (!_SharedContextInitialized)
                {
                    _SharedContextInitialized = true;
                    ((IGraphicsContextInternal)_GraphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }
            }
            else
            {
                ((IGraphicsContextInternal)_GraphicsContext).LoadAll();
                OnGraphicsContextInitialized();
            }

            OnInitialized();
        }
 public MeshBufferManager(IGraphicsContext graphicsContext)
 {
     _vertexBufferManager = graphicsContext.VertexBufferManagerFactory.Create <T>();
     _indexBufferManager  = graphicsContext.IndexBufferManagerFactory.Create();
     Disposed            += OnDisposed;
 }
Beispiel #34
0
 public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                     int major, int minor, GraphicsContextFlags flags)
     : base(DesktopBackend.OpenGL)
 {
     LongInit(mode, window, shared, direct, major, minor, flags);
 }
        public void CreateWindow(int width, int height, GraphicsMode mode, int major, int minor, GraphicsContextFlags flags, out IGraphicsContext context)
        {
            Rect r = new Rect(0, 0, (short)width, (short)height);

            CreateNativeWindow(mWindowClass, mWindowAttrib, r);

            Show();

            this.context = new GraphicsContext(mode, window, major, minor, flags);
            this.context.MakeCurrent(window);

            context = this.context;
        }
Beispiel #36
0
        public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            // Do not move this lower, as almost everything requires the Display
            // property to be correctly set.
            Display = ((X11WindowInfo)window).Display;

            // Check that GLX is supported. We cannot proceed to create
            // an OpenGL context without the GLX extension.
            int error_base;
            int event_base;
            int glx_major;
            int glx_minor;

            using (new XLock(Display))
            {
                bool supported = Glx.QueryExtension(Display, out error_base, out event_base);
                supported &= Glx.QueryVersion(Display, out glx_major, out glx_minor);
                if (supported)
                {
                    Debug.Print("[X11] GLX supported. Version is {0}.{1}", glx_major, glx_minor);
                }
                else
                {
                    throw new NotSupportedException("[X11] GLX extension is not supported.");
                }
            }

            IntPtr visual   = IntPtr.Zero;
            IntPtr fbconfig = IntPtr.Zero;

            // Once a window has a visual, we cannot use a different
            // visual on the OpenGL context, or glXMakeCurrent might fail.
            // Note: we should only check X11WindowInfo.Visual, as that
            // is the only property that can be set by Utilities.CreateX11WindowInfo.
            currentWindow = (X11WindowInfo)window;
            if (currentWindow.Visual != IntPtr.Zero)
            {
                visual   = currentWindow.Visual;
                fbconfig = currentWindow.FBConfig;
                Mode     = currentWindow.GraphicsMode;
            }

            if (Mode == null || !Mode.Index.HasValue)
            {
                Mode = ModeSelector.SelectGraphicsMode(mode, out visual, out fbconfig);
            }

            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other madness.
            // Use legacy context creation if the user doesn't request a 3.0+ context.
            if (fbconfig != IntPtr.Zero && (major * 10 + minor >= 30) && SupportsCreateContextAttribs(Display, currentWindow))
            {
                Handle = CreateContextAttribs(Display, currentWindow.Screen,
                                              fbconfig, direct, major, minor, flags, shareHandle);
            }

            if (Handle == ContextHandle.Zero)
            {
                Handle = CreateContextLegacy(Display, visual, direct, shareHandle);
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }

            using (new XLock(Display))
            {
                if (!Glx.IsDirect(Display, Handle.Handle))
                {
                    Debug.Print("Warning: Context is not direct.");
                }
            }
        }
Beispiel #37
0
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     throw new PlatformNotSupportedException(error_string);
 }
Beispiel #38
0
 public IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return(Default.CreateGLContext(handle, window, shareContext, directRendering, major, minor, flags));
 }
        public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
        {
            X11WindowInfo x11WindowInfo = (X11WindowInfo)window;
            EglWindowInfo window1       = new EglWindowInfo(x11WindowInfo.WindowHandle, Egl.GetDisplay(x11WindowInfo.Display));

            return((IGraphicsContext) new EglContext(handle, window1, shareContext, major, minor, flags));
        }
Beispiel #40
0
        public X11GLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                            int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            Mode = ModeSelector.SelectGraphicsMode(
                mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples,
                mode.AccumulatorFormat, mode.Buffers, mode.Stereo);

            // Do not move this lower, as almost everything requires the Display
            // property to be correctly set.
            Display = ((X11WindowInfo)window).Display;

            currentWindow            = (X11WindowInfo)window;
            currentWindow.VisualInfo = SelectVisual(Mode, currentWindow);

            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other madness.
            // Use legacy context creation if the user doesn't request a 3.0+ context.
            if ((major * 10 + minor >= 30) && SupportsCreateContextAttribs(Display, currentWindow))
            {
                Debug.Write("Using GLX_ARB_create_context... ");

                unsafe
                {
                    // We need the FB config for the current GraphicsMode.
                    int     count;
                    IntPtr *fbconfigs = Glx.ChooseFBConfig(Display, currentWindow.Screen,
                                                           new int[] {
                        (int)GLXAttribute.VISUAL_ID,
                        (int)Mode.Index,
                        0
                    }, out count);

                    if (count > 0)
                    {
                        List <int> attributes = new List <int>();
                        attributes.Add((int)ArbCreateContext.MajorVersion);
                        attributes.Add(major);
                        attributes.Add((int)ArbCreateContext.MinorVersion);
                        attributes.Add(minor);
                        if (flags != 0)
                        {
                            attributes.Add((int)ArbCreateContext.Flags);
                            attributes.Add((int)GetARBContextFlags(flags));
                            attributes.Add((int)ArbCreateContext.ProfileMask);
                            attributes.Add((int)GetARBProfileFlags(flags));
                        }
                        // According to the docs, " <attribList> specifies a list of attributes for the context.
                        // The list consists of a sequence of <name,value> pairs terminated by the
                        // value 0. [...]"
                        // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
                        attributes.Add(0);
                        attributes.Add(0);

                        using (new XLock(Display))
                        {
                            Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                    shareHandle.Handle, direct, attributes.ToArray()));

                            if (Handle == ContextHandle.Zero)
                            {
                                Debug.Write(String.Format("failed. Trying direct: {0}... ", !direct));
                                Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                        shareHandle.Handle, !direct, attributes.ToArray()));
                            }
                        }

                        if (Handle == ContextHandle.Zero)
                        {
                            Debug.WriteLine("failed.");
                        }
                        else
                        {
                            Debug.WriteLine("success!");
                        }

                        using (new XLock(Display))
                        {
                            Functions.XFree((IntPtr)fbconfigs);
                        }
                    }
                }
            }

            if (Handle == ContextHandle.Zero)
            {
                Debug.Write("Using legacy context creation... ");

                XVisualInfo info = currentWindow.VisualInfo;
                using (new XLock(Display))
                {
                    // Cannot pass a Property by reference.
                    Handle = new ContextHandle(Glx.CreateContext(Display, ref info, shareHandle.Handle, direct));

                    if (Handle == ContextHandle.Zero)
                    {
                        Debug.WriteLine(String.Format("failed. Trying direct: {0}... ", !direct));
                        Handle = new ContextHandle(Glx.CreateContext(Display, ref info, IntPtr.Zero, !direct));
                    }
                }
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }

            using (new XLock(Display))
            {
                if (!Glx.IsDirect(Display, Handle.Handle))
                {
                    Debug.Print("Warning: Context is not direct.");
                }
            }
        }
Beispiel #41
0
 public EglWinContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext,
                      int major, int minor, GraphicsContextFlags flags)
     : base(mode, window, sharedContext, major, minor, flags | GraphicsContextFlags.Embedded | GraphicsContextFlags.Angle)
 {
 }
Beispiel #42
0
        public void _Render(GameTime gameTime, IGraphicsContext context)
        {
            if (isFirst)
            {
                skybox  = new Skybox(context.Device);
                isFirst = false;
                fpsClock.Start();
            }

            var device = context.Device;

            device.SetRenderTargets(device.DepthStencilBuffer, device.BackBuffer);
            device.SetViewports(new ViewportF(0, 0, device.BackBuffer.Width, device.BackBuffer.Height));

            device.Clear(device.DepthStencilBuffer, SharpDX.Direct3D11.DepthStencilClearFlags.Depth, 1, 0);
            device.Clear(device.BackBuffer, Color.Black);

            device.SetBlendState(device.BlendStates.Default);
            device.SetDepthStencilState(device.DepthStencilStates.None);
            device.SetRasterizerState(device.RasterizerStates.CullBack);

            //gbuffer.SetAsRenderTarget();
            //gbuffer.Clear();

            // update current camera
            context.CurrentCamera.Update(gameTime);

            device.SetDepthStencilState(device.DepthStencilStates.Default);

            // Render SceneGraph to GBuffer
            //Engine.SceneGraph.Render(gameTime, context);

            // switch to scene target
            //device.Clear(sceneTarget, Color.Black);
            //device.SetRenderTargets(sceneTarget);

            skybox.QueueRenderCommands(gameTime, this, context);

            Engine.SceneGraph.QueueRenderCommands(gameTime, this, context);
            //worldEngine.Skybox.Render(gameTime, context);

            // Render Custom Visualization Systems

            device.SetDepthStencilState(device.DepthStencilStates.None);
            device.SetBlendState(device.BlendStates.Default);

            // Render Lights
            //context.GBuffer.RenderDirectionalLight(new Graphics.DirectionalLight());

            // Render atmosphere as post-process
            //worldEngine.Atmosphere.Render(gameTime, context);

            // copy scene target to back buffer
            //device.SetRenderTargets(device.BackBuffer);
            //texToTargetEffect.Parameters["CopyTexture"].SetResource(sceneTarget);
            //texToTargetEffect.Parameters["CopyTextureSamp"].SetResource(device.SamplerStates.LinearClamp);
            //device.DrawQuad(texToTargetEffect);

            frameCount++;
            if (fpsClock.ElapsedMilliseconds > 1000.0f)
            {
                fpsText    = string.Format("{0:F2} FPS", (float)frameCount * 1000 / fpsClock.ElapsedMilliseconds);
                frameCount = 0;
                fpsClock.Restart();
            }

            context.SpriteBatch.Begin();
            context.SpriteBatch.DrawString(font, fpsText, Vector2.Zero, Color.White);
            context.SpriteBatch.DrawString(font, string.Format("camera X: {0}", context.CurrentCamera.Position.X), new Vector2(0, 15), Color.White);
            context.SpriteBatch.DrawString(font, string.Format("camera Y: {0}", context.CurrentCamera.Position.Y), new Vector2(0, 30), Color.White);
            context.SpriteBatch.DrawString(font, string.Format("camera Z: {0}", context.CurrentCamera.Position.Z), new Vector2(0, 45), Color.White);
            context.SpriteBatch.DrawString(font, string.Format("Camera Height: {0}", context.CurrentCamera.Position.Length()), new Vector2(0, 60), Color.White);
            context.SpriteBatch.End();

            // Present
            device.Present();

            // reset all state
            device.ClearState();

            // commit the changes to the image source
            if (context.ImageSourcePresenter != null)
            {
                var renderTarget = ((GraphicsDeviceService)context.GraphicsService).BackBuffer;
                context.ImageSourcePresenter.Commit(renderTarget);
            }
        }
Beispiel #43
0
 /// <summary>Constructs a new GameWindow with the specified attributes.</summary>
 /// <param name="width">The width of the GameWindow in pixels.</param>
 /// <param name="height">The height of the GameWindow in pixels.</param>
 /// <param name="mode">The OpenTK.Graphics.GraphicsMode of the GameWindow.</param>
 /// <param name="title">The title of the GameWindow.</param>
 /// <param name="options">GameWindow options regarding window appearance and behavior.</param>
 /// <param name="device">The OpenTK.Graphics.DisplayDevice to construct the GameWindow in.</param>
 /// <param name="major">The major version for the OpenGL GraphicsContext.</param>
 /// <param name="minor">The minor version for the OpenGL GraphicsContext.</param>
 /// <param name="flags">The GraphicsContextFlags version for the OpenGL GraphicsContext.</param>
 /// <param name="sharedContext">An IGraphicsContext to share resources with.</param>
 public GameWindow(int width, int height, GraphicsMode mode, string title, GameWindowFlags options, DisplayDevice device,
                   int major, int minor, GraphicsContextFlags flags, IGraphicsContext sharedContext)
     : this(width, height, mode, title, options, device, major, minor, flags, sharedContext, true)
 {
 }
Beispiel #44
0
 internal void MakeContextCurrent(IGraphicsContext context, global::OpenTK.Platform.IWindowInfo windowInfo)
 {
     context.MakeCurrent(windowInfo);
     PurgeStateCache();
 }
 public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window,
                                                  IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return(new CocoaContext(handle, window, shareContext, major, minor));
 }
Beispiel #46
0
        public override void QueueRenderCommands(GameTime gameTime, Renderer renderer, IGraphicsContext context)
        {
            var command = GenerateRenderCommand();

            if (command is IRenderDeferredCommand)
            {
                Engine.Renderer.EnqueueDeferred(command as IRenderDeferredCommand);
            }
            else
            {
                Engine.Renderer.EnqueueNormal(command);
            }
        }
Beispiel #47
0
        void LongInit(GraphicsMode mode, IWindowInfo window, IGraphicsContext shared, bool direct,
                      int major, int minor, GraphicsContextFlags flags)
        {
            //fixed PEVerify error
            //move long code from ctor to here

            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }
            Mode = mode;
            // Do not move this lower, as almost everything requires the Display
            // property to be correctly set.
            Display                  = ((X11WindowInfo)window).Display;
            currentWindow            = (X11WindowInfo)window;
            currentWindow.VisualInfo = SelectVisual(mode, currentWindow);
            ContextHandle shareHandle = shared != null ?
                                        (shared as IGraphicsContextInternal).Context : (ContextHandle)IntPtr.Zero;

            Debug.Write("Creating X11GLContext context: ");
            Debug.Write(direct ? "direct, " : "indirect, ");
            Debug.WriteLine(shareHandle.Handle == IntPtr.Zero ? "not shared... " :
                            String.Format("shared with ({0})... ", shareHandle));
            if (!glx_loaded)
            {
                Debug.WriteLine("Creating temporary context to load GLX extensions.");
                // Create a temporary context to obtain the necessary function pointers.
                XVisualInfo visual = currentWindow.VisualInfo;
                IntPtr      ctx    = IntPtr.Zero;
                using (new XLock(Display))
                {
                    ctx = Glx.CreateContext(Display, ref visual, IntPtr.Zero, true);
                    if (ctx == IntPtr.Zero)
                    {
                        ctx = Glx.CreateContext(Display, ref visual, IntPtr.Zero, false);
                    }
                }

                if (ctx != IntPtr.Zero)
                {
                    new Glx().LoadEntryPoints();
                    using (new XLock(Display))
                    {
                        Glx.MakeCurrent(Display, IntPtr.Zero, IntPtr.Zero);
                        //Glx.DestroyContext(Display, ctx);
                    }
                    glx_loaded = true;
                }
            }

            // Try using the new context creation method. If it fails, fall back to the old one.
            // For each of these methods, we try two times to create a context:
            // one with the "direct" flag intact, the other with the flag inversed.
            // HACK: It seems that Catalyst 9.1 - 9.4 on Linux have problems with contexts created through
            // GLX_ARB_create_context, including hideous input lag, no vsync and other. Use legacy context
            // creation if the user doesn't request a 3.0+ context.
            if ((major * 10 + minor >= 30) && Glx.Delegates.glXCreateContextAttribsARB != null)
            {
                Debug.Write("Using GLX_ARB_create_context... ");
                unsafe
                {
                    // We need the FB config for the current GraphicsMode.
                    int     count;
                    IntPtr *fbconfigs = Glx.ChooseFBConfig(Display, currentWindow.Screen,
                                                           new int[] {
                        (int)GLXAttribute.VISUAL_ID,
                        (int)mode.Index,
                        0
                    }, out count);
                    if (count > 0)
                    {
                        List <int> attributes = new List <int>();
                        attributes.Add((int)ArbCreateContext.MajorVersion);
                        attributes.Add(major);
                        attributes.Add((int)ArbCreateContext.MinorVersion);
                        attributes.Add(minor);
                        if (flags != 0)
                        {
#warning "This is not entirely correct: Embedded is not a valid flag! We need to add a GetARBContextFlags(GraphicsContextFlags) method."
                            attributes.Add((int)ArbCreateContext.Flags);
                            attributes.Add((int)flags);
                        }
                        // According to the docs, " <attribList> specifies a list of attributes for the context.
                        // The list consists of a sequence of <name,value> pairs terminated by the
                        // value 0. [...]"
                        // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
                        attributes.Add(0);
                        attributes.Add(0);
                        using (new XLock(Display))
                        {
                            Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                    shareHandle.Handle, direct, attributes.ToArray()));
                            if (Handle == ContextHandle.Zero)
                            {
                                Debug.Write(String.Format("failed. Trying direct: {0}... ", !direct));
                                Handle = new ContextHandle(Glx.Arb.CreateContextAttribs(Display, *fbconfigs,
                                                                                        shareHandle.Handle, !direct, attributes.ToArray()));
                            }
                        }

                        if (Handle == ContextHandle.Zero)
                        {
                            Debug.WriteLine("failed.");
                        }
                        else
                        {
                            Debug.WriteLine("success!");
                        }
                        using (new XLock(Display))
                        {
                            Functions.XFree((IntPtr)fbconfigs);
                        }
                    }
                }
            }

            if (Handle == ContextHandle.Zero)
            {
                Debug.Write("Using legacy context creation... ");
                XVisualInfo info = currentWindow.VisualInfo;
                using (new XLock(Display))
                {
                    // Cannot pass a Property by reference.
                    Handle = new ContextHandle(Glx.CreateContext(Display, ref info, shareHandle.Handle, direct));
                    if (Handle == ContextHandle.Zero)
                    {
                        Debug.WriteLine(String.Format("failed. Trying direct: {0}... ", !direct));
                        Handle = new ContextHandle(Glx.CreateContext(Display, ref info, IntPtr.Zero, !direct));
                    }
                }
            }

            if (Handle != ContextHandle.Zero)
            {
                Debug.Print("Context created (id: {0}).", Handle);
            }
            else
            {
                throw new GraphicsContextException("Failed to create OpenGL context. Glx.CreateContext call returned 0.");
            }
            using (new XLock(Display))
            {
                if (!Glx.IsDirect(Display, Handle.Handle))
                {
                    Debug.Print("Warning: Context is not direct.");
                }
            }
        }
Beispiel #48
0
        public Sdl2PlatformWindow(Size requestWindowSize, WindowMode windowMode, int batchSize)
        {
            // Lock the Window/Surface properties until initialization is complete
            lock (syncObject)
            {
                windowSize = requestWindowSize;

                // Disable legacy scaling on Windows
                if (Platform.CurrentPlatform == PlatformType.Windows && !Game.Settings.Graphics.DisableWindowsDPIScaling)
                {
                    SetProcessDPIAware();
                }

                SDL.SDL_Init(SDL.SDL_INIT_NOPARACHUTE | SDL.SDL_INIT_VIDEO);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 0);

                // Decide between OpenGL and OpenGL ES rendering
                // Test whether we can use the preferred renderer and fall back to the other if that fails
                // If neither works we will throw a graphics error later when trying to create the real window
                bool useGLES;
                if (Game.Settings.Graphics.PreferGLES)
                {
                    useGLES = CanCreateGLWindow(3, 0, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_ES);
                }
                else
                {
                    useGLES = !CanCreateGLWindow(3, 2, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE);
                }

                var glMajor   = 3;
                var glMinor   = useGLES ? 0 : 2;
                var glProfile = useGLES ? SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_ES : SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE;

                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MAJOR_VERSION, glMajor);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MINOR_VERSION, glMinor);
                SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, (int)glProfile);

                Console.WriteLine("Using SDL 2 with OpenGL{0} renderer", useGLES ? " ES" : "");

                SDL.SDL_DisplayMode display;
                SDL.SDL_GetCurrentDisplayMode(0, out display);

                Console.WriteLine("Desktop resolution: {0}x{1}", display.w, display.h);
                if (windowSize.Width == 0 && windowSize.Height == 0)
                {
                    Console.WriteLine("No custom resolution provided, using desktop resolution");
                    windowSize = new Size(display.w, display.h);
                }

                Console.WriteLine("Using resolution: {0}x{1}", windowSize.Width, windowSize.Height);

                var windowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI;

                // HiDPI doesn't work properly on OSX with (legacy) fullscreen mode
                if (Platform.CurrentPlatform == PlatformType.OSX && windowMode == WindowMode.Fullscreen)
                {
                    SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_HIGHDPI_DISABLED, "1");
                }

                window = SDL.SDL_CreateWindow("OpenRA", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
                                              windowSize.Width, windowSize.Height, windowFlags);

                // Work around an issue in macOS's GL backend where the window remains permanently black
                // (if dark mode is enabled) unless we drain the event queue before initializing GL
                if (Platform.CurrentPlatform == PlatformType.OSX)
                {
                    SDL.SDL_Event e;
                    while (SDL.SDL_PollEvent(out e) != 0)
                    {
                        // We can safely ignore all mouse/keyboard events and window size changes
                        // (these will be caught in the window setup below), but do need to process focus
                        if (e.type == SDL.SDL_EventType.SDL_WINDOWEVENT)
                        {
                            switch (e.window.windowEvent)
                            {
                            case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_LOST:
                                Game.HasInputFocus = false;
                                break;

                            case SDL.SDL_WindowEventID.SDL_WINDOWEVENT_FOCUS_GAINED:
                                Game.HasInputFocus = true;
                                break;
                            }
                        }
                    }
                }

                surfaceSize = windowSize;
                windowScale = 1;

                // Enable high resolution rendering for Retina displays
                if (Platform.CurrentPlatform == PlatformType.OSX)
                {
                    // OSX defines the window size in "points", with a device-dependent number of pixels per point.
                    // The window scale is simply the ratio of GL pixels / window points.
                    int width, height;

                    SDL.SDL_GL_GetDrawableSize(Window, out width, out height);
                    surfaceSize = new Size(width, height);
                    windowScale = width * 1f / windowSize.Width;
                }
                else if (Platform.CurrentPlatform == PlatformType.Windows)
                {
                    float ddpi, hdpi, vdpi;
                    if (!Game.Settings.Graphics.DisableWindowsDPIScaling && SDL.SDL_GetDisplayDPI(0, out ddpi, out hdpi, out vdpi) == 0)
                    {
                        windowScale = ddpi / 96;
                        windowSize  = new Size((int)(surfaceSize.Width / windowScale), (int)(surfaceSize.Height / windowScale));
                    }
                }
                else
                {
                    float scale         = 1;
                    var   scaleVariable = Environment.GetEnvironmentVariable("OPENRA_DISPLAY_SCALE");
                    if (scaleVariable != null && float.TryParse(scaleVariable, out scale))
                    {
                        windowScale = scale;
                        windowSize  = new Size((int)(surfaceSize.Width / windowScale), (int)(surfaceSize.Height / windowScale));
                    }
                }

                Console.WriteLine("Using window scale {0:F2}", windowScale);

                if (Game.Settings.Game.LockMouseWindow)
                {
                    GrabWindowMouseFocus();
                }
                else
                {
                    ReleaseWindowMouseFocus();
                }

                if (windowMode == WindowMode.Fullscreen)
                {
                    SDL.SDL_SetWindowFullscreen(Window, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN);

                    // Fullscreen mode on OSX will ignore the configured display resolution
                    // and instead always picks an arbitrary scaled resolution choice that may
                    // not match the window size, leading to graphical and input issues.
                    // We work around this by force disabling HiDPI and resetting the window and
                    // surface sizes to match the size that is forced by SDL.
                    // This is usually not what the player wants, but is the best we can consistently do.
                    if (Platform.CurrentPlatform == PlatformType.OSX)
                    {
                        int width, height;
                        SDL.SDL_GetWindowSize(Window, out width, out height);
                        windowSize  = surfaceSize = new Size(width, height);
                        windowScale = 1;
                    }
                }
                else if (windowMode == WindowMode.PseudoFullscreen)
                {
                    // Work around a visual glitch in OSX: the window is offset
                    // partially offscreen if the dock is at the left of the screen
                    if (Platform.CurrentPlatform == PlatformType.OSX)
                    {
                        SDL.SDL_SetWindowPosition(Window, 0, 0);
                    }

                    SDL.SDL_SetWindowFullscreen(Window, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
                    SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
                }
            }

            // Run graphics rendering on a dedicated thread.
            // The calling thread will then have more time to process other tasks, since rendering happens in parallel.
            // If the calling thread is the main game thread, this means it can run more logic and render ticks.
            // This is disabled on Windows because it breaks the ability to minimize/restore the window from the taskbar for reasons that we dont understand.
            var threadedRenderer = Platform.CurrentPlatform != PlatformType.Windows || !Game.Settings.Graphics.DisableWindowsRenderThread;

            if (!threadedRenderer)
            {
                var ctx = new Sdl2GraphicsContext(this);
                ctx.InitializeOpenGL();
                context = ctx;
            }
            else
            {
                context = new ThreadedGraphicsContext(new Sdl2GraphicsContext(this), batchSize);
            }

            SDL.SDL_SetModState(SDL.SDL_Keymod.KMOD_NONE);
            input = new Sdl2Input();
        }
Beispiel #49
0
        // Called when the widget needs to be (fully or partially) redrawn.
        protected override bool OnExposeEvent(Gdk.EventExpose eventExpose)
        {
            if (!initialized)
            {
                initialized = true;

                // If this looks uninitialized...  initialize.
                if (ColorBPP == 0)
                {
                    ColorBPP = 32;

                    if (DepthBPP == 0)
                    {
                        DepthBPP = 16;
                    }
                }

                ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

                ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

                int buffers = 2;
                if (SingleBuffer)
                {
                    buffers--;
                }

                GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

                // IWindowInfo
                if (Configuration.RunningOnWindows)
                {
                    IntPtr windowHandle = gdk_win32_drawable_get_handle(GdkWindow.Handle);
                    windowInfo = OpenTK.Platform.Utilities.CreateWindowsWindowInfo(windowHandle);
                }
                else if (Configuration.RunningOnMacOS)
                {
                    IntPtr windowHandle = gdk_quartz_window_get_nswindow(GdkWindow.Handle);
                    IntPtr contentView  = gdk_quartz_window_get_nsview(GdkWindow.Handle);

                    // Problem: gdk_window_ensure_native() crashes when used more than once.
                    // For now, just create a NSView in place and use that instead.
                    // Needs some care updating when resizing, hiding, etc, but seems to work.
                    // (I'd guess this is pretty much what gdk_window_ensure_native() does internally.)

                    var customView = Class.AllocateClass("CustomNSView" + uniqueId++, "NSView");
                    //Class.RegisterMethod(windowClass, new WindowKeyDownDelegate(WindowKeyDown), "keyDown:", "v@:@");
                    //Class.RegisterMethod(customView, new OnHitTestDelegate(OnHitTest), "hitTest:", "@@:{NSPoint=ff}");
                    Class.RegisterMethod(customView, new OnMouseDownDelegate(OnMouseDown), "mouseDown:", "v@:@");
                    Class.RegisterMethod(customView, new OnMouseDraggedDelegate(OnMouseDragged), "mouseDragged:", "v@:@");
                    Class.RegisterMethod(customView, new OnMouseUpDelegate(OnMouseUp), "mouseUp:", "v@:@");

                    Class.RegisterClass(customView);

                    nsView = SendIntPtr(SendIntPtr(customView, sel_registerName("alloc")), sel_registerName("initWithFrame:"), new RectangleF(0, 0, 100, 100));
                    SendVoid(contentView, sel_registerName("addSubview:"), nsView);


//					bool native = gdk_window_ensure_native(GdkWindow.Handle);
//					if (!native)
//					{
//						throw new PlatformNotSupportedException("Could not create native view.");
//					}
//
//					nsView = gdk_quartz_window_get_nsview(GdkWindow.Handle);

                    windowInfo = OpenTK.Platform.Utilities.CreateMacOSWindowInfo(windowHandle, nsView);
                    UpdateNSView();
                }
                else if (Configuration.RunningOnX11)
                {
                    IntPtr display      = gdk_x11_display_get_xdisplay(Display.Handle);
                    int    screen       = Screen.Number;
                    IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                    IntPtr rootWindow   = gdk_x11_drawable_get_xid(RootWindow.Handle);

                    IntPtr visualInfo;
                    if (graphicsMode.Index.HasValue)
                    {
                        XVisualInfo info = new XVisualInfo();
                        info.VisualID = graphicsMode.Index.Value;
                        int dummy;
                        visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy);
                    }
                    else
                    {
                        visualInfo = GetVisualInfo(display);
                    }

                    windowInfo = OpenTK.Platform.Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo);
                    XFree(visualInfo);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }

                // GraphicsContext
                graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
                graphicsContext.MakeCurrent(windowInfo);

                if (GraphicsContext.ShareContexts)
                {
                    Interlocked.Increment(ref graphicsContextCount);

                    if (!sharedContextInitialized)
                    {
                        sharedContextInitialized = true;
                        ((IGraphicsContextInternal)graphicsContext).LoadAll();
                        OnGraphicsContextInitialized();
                    }
                }
                else
                {
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }

                OnInitialized();
            }
            else
            {
                try                 // Hack: Fix crash when returning from sleep mode on windows, using nvidia drivers. See: http://www.opentk.com/node/2634
                {
                    graphicsContext.MakeCurrent(windowInfo);
                }
                catch
                {
                }
            }

            bool result = base.OnExposeEvent(eventExpose);

            OnRenderFrame();
            eventExpose.Window.Display.Sync();             // Add Sync call to fix resize rendering problem (Jay L. T. Cornwall) - How does this affect VSync?
            graphicsContext.SwapBuffers();
            return(result);
        }
Beispiel #50
0
 public abstract IGraphicsContext CreateGLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags);
        public override IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
        {
            X11WindowInfo x11_win = (X11WindowInfo)window;
            EglWindowInfo egl_win = new OpenTK.Platform.Egl.EglWindowInfo(x11_win.WindowHandle, Egl.GetDisplay(x11_win.Display));

            return(new EglContext(handle, egl_win, shareContext, major, minor, flags));
        }
Beispiel #52
0
 public virtual IGraphicsContext CreateGLContext(ContextHandle handle, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     throw new NotImplementedException();
 }
Beispiel #53
0
        private int swap_interval = 1; // Default interval is defined as 1 in EGL.

        public EglContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext,
                          int major, int minor, GraphicsContextFlags flags)
        {
            if (mode == null)
            {
                throw new ArgumentNullException("mode");
            }
            if (window == null)
            {
                throw new ArgumentNullException("window");
            }

            EglContext shared = GetSharedEglContext(sharedContext);

            WindowInfo = window;

            // Select an EGLConfig that matches the desired mode. We cannot use the 'mode'
            // parameter directly, since it may have originated on a different system (e.g. GLX)
            // and it may not support the desired renderer.

            Renderable = RenderableFlags.GL;
            if ((flags & GraphicsContextFlags.Embedded) != 0)
            {
                switch (major)
                {
                case 3:
                    Renderable = RenderableFlags.ES3;
                    break;

                case 2:
                    Renderable = RenderableFlags.ES2;
                    break;

                default:
                    Renderable = RenderableFlags.ES;
                    break;
                }
            }

            RenderApi api = (Renderable & RenderableFlags.GL) != 0 ? RenderApi.GL : RenderApi.ES;

            Debug.Print("[EGL] Binding {0} rendering API.", api);
            if (!Egl.BindAPI(api))
            {
                Debug.Print("[EGL] Failed to bind rendering API. Error: {0}", Egl.GetError());
            }

            bool offscreen = (flags & GraphicsContextFlags.Offscreen) != 0;

            SurfaceType surfaceType = offscreen
                ? SurfaceType.PBUFFER_BIT
                : SurfaceType.WINDOW_BIT;

            Mode = new EglGraphicsMode().SelectGraphicsMode(surfaceType,
                                                            window.Display, mode.ColorFormat, mode.Depth, mode.Stencil,
                                                            mode.Samples, mode.AccumulatorFormat, mode.Buffers, mode.Stereo,
                                                            Renderable);

            if (!Mode.Index.HasValue)
            {
                throw new GraphicsModeException("Invalid or unsupported GraphicsMode.");
            }
            IntPtr config = Mode.Index.Value;

            if (window.Surface == IntPtr.Zero)
            {
                if (!offscreen)
                {
                    window.CreateWindowSurface(config);
                }
                else
                {
                    window.CreatePbufferSurface(config);
                }
            }

            int[] attribList   = { Egl.CONTEXT_CLIENT_VERSION, major, Egl.NONE };
            var   shareContext = shared?.HandleAsEGLContext ?? IntPtr.Zero;

            HandleAsEGLContext = Egl.CreateContext(window.Display, config, shareContext, attribList);

            GraphicsContextFlags = flags;
        }
 public EglUnixContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext,
                       int major, int minor, GraphicsContextFlags flags)
     : base(mode, window, sharedContext, major, minor, flags)
 {
 }
Beispiel #55
0
        private static void SetGLAttributes(GraphicsMode mode,
            IGraphicsContext shareContext,
            int major, int minor,
            GraphicsContextFlags flags)
        {
            ContextProfileFlags cpflags = 0;
            ClearGLAttributes();

            if (mode.AccumulatorFormat.BitsPerPixel > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.ACCUM_ALPHA_SIZE, mode.AccumulatorFormat.Alpha);
                SDL.GL.SetAttribute(ContextAttribute.ACCUM_RED_SIZE, mode.AccumulatorFormat.Red);
                SDL.GL.SetAttribute(ContextAttribute.ACCUM_GREEN_SIZE, mode.AccumulatorFormat.Green);
                SDL.GL.SetAttribute(ContextAttribute.ACCUM_BLUE_SIZE, mode.AccumulatorFormat.Blue);
            }

            if (mode.Buffers > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.DOUBLEBUFFER, mode.Buffers > 1 ? 1 : 0);
            }

            if (mode.ColorFormat > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.ALPHA_SIZE, mode.ColorFormat.Alpha);
                SDL.GL.SetAttribute(ContextAttribute.RED_SIZE, mode.ColorFormat.Red);
                SDL.GL.SetAttribute(ContextAttribute.GREEN_SIZE, mode.ColorFormat.Green);
                SDL.GL.SetAttribute(ContextAttribute.BLUE_SIZE, mode.ColorFormat.Blue);
            }

            if (mode.Depth > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.DEPTH_SIZE, mode.Depth);
            }

            if (mode.Samples > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.MULTISAMPLEBUFFERS, 1);
                SDL.GL.SetAttribute(ContextAttribute.MULTISAMPLESAMPLES, mode.Samples);
            }

            if (mode.Stencil > 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.STENCIL_SIZE, 1);
            }

            if (mode.Stereo)
            {
                SDL.GL.SetAttribute(ContextAttribute.STEREO, 1);
            }

            if (major > 0)
            {
                // Workaround for https://github.com/opentk/opentk/issues/44
                // Mac OS X desktop OpenGL 3.x/4.x contexts require require
                // ContextProfileFlags.Core, otherwise they will fail to construct.
                if (Configuration.RunningOnMacOS && major >= 3 &&
                    (flags & GraphicsContextFlags.Embedded) == 0)
                {
                    cpflags |= ContextProfileFlags.CORE;

                    // According to https://developer.apple.com/graphicsimaging/opengl/capabilities/GLInfo_1075_Core.html
                    // Mac OS X supports 3.2+. Indeed, requesting 3.0 or 3.1 results in failure.
                    if (major == 3 && minor < 2)
                    {
                        minor = 2;
                    }
                }

                SDL.GL.SetAttribute(ContextAttribute.CONTEXT_MAJOR_VERSION, major);
                SDL.GL.SetAttribute(ContextAttribute.CONTEXT_MINOR_VERSION, minor);
            }

            if ((flags & GraphicsContextFlags.Debug) != 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.CONTEXT_FLAGS, ContextFlags.DEBUG);
            }

            /*
            if ((flags & GraphicsContextFlags.Robust) != 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.CONTEXT_FLAGS, ContextFlags.ROBUST_ACCESS_FLAG);
            }

            if ((flags & GraphicsContextFlags.ResetIsolation) != 0)
            {
                SDL.GL.SetAttribute(ContextAttribute.CONTEXT_FLAGS, ContextFlags.RESET_ISOLATION_FLAG);
            }
            */

            {
                if ((flags & GraphicsContextFlags.Embedded) != 0)
                {
                    cpflags |= ContextProfileFlags.ES;
                    SDL.GL.SetAttribute(ContextAttribute.CONTEXT_EGL, 1);
                }

                if ((flags & GraphicsContextFlags.ForwardCompatible) != 0)
                {
                    cpflags |= ContextProfileFlags.CORE;
                }

                if (cpflags != 0)
                {
                    SDL.GL.SetAttribute(ContextAttribute.CONTEXT_PROFILE_MASK, cpflags);
                }
            }

            if (shareContext != null)
            {
                if (shareContext.IsCurrent)
                {
                    SDL.GL.SetAttribute(ContextAttribute.SHARE_WITH_CURRENT_CONTEXT, 1);
                }
                else
                {
                    Trace.WriteLine("Warning: SDL2 requires a shared context to be current before sharing. Sharing failed.");
                }
            }
        }
Beispiel #56
0
 public virtual IGraphicsContext CreateGLContext(GraphicsMode mode, IWindowInfo window, IGraphicsContext shareContext, bool directRendering, int major, int minor, GraphicsContextFlags flags)
 {
     return((IGraphicsContext) new X11GLContext(mode, window, shareContext, directRendering, major, minor, flags));
 }
Beispiel #57
0
 public void RenderDeferred(GameTime gameTime, IGraphicsContext context)
 {
     throw new NotImplementedException();
 }
Beispiel #58
0
        private void SetupShaderProgram(ref Matrix4 projection, ShaderProgram program)
        {
            IGraphicsContext context = program.GraphicsContext;

            context.UseShaderProgram(program);

            program.SetUniform(PROJ_MAT, ref projection);
            program.SetUniform(FORCES, ref this.settings.Forces);

            program.SetUniform(START_COLOR, settings.StartColor);
            program.SetUniform(END_COLOR, settings.EndColor);
            program.SetUniform(START_SIZE, settings.StartSize);
            program.SetUniform(END_SIZE, settings.EndSize);
            program.SetUniform(START_ANGULAR_VELOCITY, settings.StartAngularVelocity);
            program.SetUniform(END_ANGULAR_VELOCITY, settings.EndAngularVelocity);
            program.SetUniform(COLOR_VARIANCE, settings.ColorVariance);
            program.SetUniform(SIZE_VARIANCE, settings.SizeVariance);

            Vector3 g = new Vector3(500, 500, -0);

            program.SetUniform("gravity_well_1", ref g);
            g = new Vector3(1550, 500, 0);
            program.SetUniform("gravity_well_2", ref g);


            program.SetUniform(START_ALPHA, 1.5f);
            program.SetUniform(END_ALPHA, 0f);

            program.SetUniform(LIFE_TIME, settings.LifeTime);
            program.SetUniform(CURRENT_TIME, this.currentTime);

            program.SetUniform(TEXTURE, 0);


            GL.BindVertexArray(this.vba);

            int posIndex    = program.GetAttributeLocation(IN_POS);
            int veloIndex   = program.GetAttributeLocation(IN_VEL);
            int randomIndex = program.GetAttributeLocation(IN_RANDOM);
            int offsetIndex = program.GetAttributeLocation(IN_OFFSET);
            int coordIndex  = program.GetAttributeLocation(IN_COORDS);
            int timeIndex   = program.GetAttributeLocation(IN_TIME);



            context.BindVertexBuffer(this.vertexBuffer);

            context.EnableVertexAttribArray(posIndex);
            context.EnableVertexAttribArray(veloIndex);
            context.EnableVertexAttribArray(randomIndex);
            context.EnableVertexAttribArray(offsetIndex);
            context.EnableVertexAttribArray(coordIndex);
            context.EnableVertexAttribArray(timeIndex);

            context.VertexAttribPointer(posIndex, 2, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, 0);

            context.VertexAttribPointer(veloIndex, 2, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, Vector2.SizeInBytes);

            context.VertexAttribPointer(randomIndex, 2, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, Vector2.SizeInBytes * 2);


            context.VertexAttribPointer(offsetIndex, 2, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, Vector2.SizeInBytes * 3);


            context.VertexAttribPointer(coordIndex, 2, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, Vector2.SizeInBytes * 4);


            context.VertexAttribPointer(timeIndex, 1, VertexAttribPointerType.Float,
                                        false, this.queue[0].SizeInBytes, Vector2.SizeInBytes * 5);


            GL.BindVertexArray(0);
        }
Beispiel #59
0
 public EglWinContext(ContextHandle handle, EglWindowInfo window, IGraphicsContext sharedContext,
                      int major, int minor, GraphicsContextFlags flags)
     : base(handle, window, sharedContext, major, minor, flags)
 {
 }
Beispiel #60
0
        void InitializeContext()
        {
            Toolkit.Init();

            // If this looks uninitialized...  initialize.
            if (ColorBPP == 0)
            {
                ColorBPP = 24;

                if (DepthBPP == 0)
                {
                    DepthBPP = 16;
                }
            }

            ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP);

            ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP);

            int buffers = 2;

            if (SingleBuffer)
            {
                buffers--;
            }

            var graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo);

            // IWindowInfo
            if (Configuration.RunningOnWindows)
            {
                IntPtr windowHandle = gdk_win32_drawable_get_handle(GdkWindow.Handle);
                windowInfo = Utilities.CreateWindowsWindowInfo(windowHandle);
            }
            else if (Configuration.RunningOnMacOS)
            {
                IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                bool   ownHandle    = true;
                bool   isControl    = true;
                windowInfo = Utilities.CreateMacOSCarbonWindowInfo(windowHandle, ownHandle, isControl);
            }
            else if (Configuration.RunningOnX11)
            {
                IntPtr display      = gdk_x11_display_get_xdisplay(Display.Handle);
                int    screen       = Screen.Number;
                IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle);
                IntPtr rootWindow   = gdk_x11_drawable_get_xid(RootWindow.Handle);

                IntPtr visualInfo;
                if (graphicsMode.Index.HasValue)
                {
                    XVisualInfo info = new XVisualInfo();
                    info.VisualID = graphicsMode.Index.Value;
                    int dummy;
                    visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy);
                }
                else
                {
                    visualInfo = GetVisualInfo(display);
                }

                windowInfo = Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo);
                XFree(visualInfo);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }

            // GraphicsContext
            graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags);
            graphicsContext.MakeCurrent(windowInfo);

            if (GraphicsContext.ShareContexts)
            {
                Interlocked.Increment(ref graphicsContextCount);

                if (!sharedContextInitialized)
                {
                    sharedContextInitialized = true;
                    ((IGraphicsContextInternal)graphicsContext).LoadAll();
                    OnGraphicsContextInitialized();
                }
            }
            else
            {
                ((IGraphicsContextInternal)graphicsContext).LoadAll();
                OnGraphicsContextInitialized();
            }

            initialized = true;
            OnInitialized();
            //QueueDraw();
        }