How do I create an OpenGL GrContext for SkiaSharp? - c#

I'm trying to render a SkiaSharp element in my WPF application using an OpenGL backend in the hopes of making it faster. I found this documentation explaining how to work with the resulting surface created, but it has this extremely unhelpful sentence in it:
Skia does not create a OpenGL context or Vulkan device for you. In OpenGL mode it also assumes that the correct OpenGL context has been made current to the current thread when Skia calls are made.
The documentation then proceeds to also assume that I know how to create said OpenGL or Vulkan device. After Googling this for an hour or so, I can tell you there are a few ways to do this (apparently), involving OpenTK, or creating the context manually, or using a WindowsFormsHost to host my drawing element, but I have been completely unable to find any specific information on what I need to do to make these things happen. If I have found this info in my Google searches, I lack the knowledge to recognize it as the answer.
To be 100% clear, what I'm asking is this: What do I need to do before the following lines of code will work?
var context = GRContext.CreateGl();
var gpuSurface = SKSurface.Create(context, true, new SKImageInfo(PageData.Instance.GetTotalWidth(), PageData.Instance.GetTotalHeight()));

Still looking for alternatives that don't require adding a 5 MB DLL just to use one object, but this is what I have for now.
I ended up going with this after installing OpenTK and OpenTK.GLControl from NuGet:
public SKSurface GetOpenGlSurface(int width, int height)
{
if (GPUContext == null)
{
GLControl control = new GLControl(new GraphicsMode(32, 24, 8, 4));
control.MakeCurrent();
GPUContext = GRContext.CreateGl();
}
var gpuSurface = SKSurface.Create(GPUContext, true, new SKImageInfo(width, height));
return gpuSurface;
}
It's worth noting that doing this and rendering various images using the GPU instead actually drastically cut performance, even with a decent video card. This is probably because I'm terrible at this, and I'm introducing bottlenecks. I suspect someone who knows what they're doing can avoid these pitfalls just fine.

Related

How to avoid touchpoints used by Tangibles in multitouch screen while using TangibleEngine in Unity3d?

I am building a touch user interface where Tangibles with different footprints will be placed on the screen. And I need to find the unassociated touchpoints.
Please refer the pseudo code below. I have tried with the method from the Tangible Engine library. As per the description it should return an array of unassociated touch points, but in my case its also registering associated touch points.
public Text Unassociated;
public void OnClick()
{
TangibleEngine tangibleEngineInstance = TangibleEngine.Instance;
var y = tangibleEngineInstance.UnassociatedTouchPoints[0].position;
Unassociated.text = y.ToString();
}
It might also be a bug in the library or might be due to some integration issue with UnityEngine. I dont have much expirence with this package and i did not find any other resource for my problem. Hope someone stackoverflow community has a solution for this.

Is it conceivable to make a game in system.drawing?

a while ago I started making simple game in c#, however after some time i started to add more and more objects on the screen and sadly i saw my framerate geting realy slow.
Bitmap bmp = new Bitmap(1200, 700);
Graphics FrameGraphics = Graphics.FromImage(bmp);
while (true)
{
FrameGraphics.Clear(Color.White);
foreach (GraphicalObject S in ObjectControll.ToList())
{
FrameGraphics.DrawImage(S.picture, (float)S.X, (float)S.Y);
}
DrawHandle.DrawImage(bmp, 0, 0);
frames++;
}
why most 3D games run faster than this loop with 20 objects in it? Do I need to use any software to make a game?
You could possibly create a game using System.Drawing, however it's not really what it's designed for and with a complex game and a lot of objects I imagine you will run into problems.
Your best bet is to use something that is the correct tool for the job and designed for games. Look into something like Unity, or personally I have found the XNA framework very easy to get into as a C# programmer, although it is unsupported and has been superseded by MonoGame.

Changing the individual pixels of a Gtk.Image

I am trying to set individual pixels on a Gtk.Image widget. The documentation states that the ImageProp property of a Gtk.Image returns a Gdk.Image which seems to let you edit the individual pixels, but whenever I use this it only returns null.
My solution so far is to load the image from disk as a System.Drawing.Bitmap, edit it, save it to a temporary file, then load it back into a Gtk.Image, but this is obviously not ideal.
For
Gtk.Image image = new Gtk.Image("images/test.png");
Gdk.Image gdkImage = image.ImageProp;
Why is gdkImage always null?
The image itself loads and displays correctly.
Although I have no prior experience with GTK# or C#, based on whatever little I know about Gtk & what I could look up online, I will make an attempt to provide some inputs.
You can get Gdk.Image for a Gtk.Image only if you have created the Gtk.Image from a Gdk.Image using the mentioned property, otherwise you will get null as in your case where you are creating it from a file or as suggested by creating it from Gdk.Pixbuf. In current case, you could try to get Gdk.Image from Gdk.Drawable using Gdk.Drawable.GetImage method or use Gdk.Image.Get method. You can make use of GdkWindow associated with Gtk.Image as Gdk.Drawable in the mentioned cases. For Gdk.Window to be valid the widget should have been shown or realized. But it is quite likely that you may end with null in both the cases.
Side Note: GdkImage APIs are deprecated in the newer versions of Gtk, please note it may not be so in the case of GTK# as yet.
Thus it might be a good idea to use Gdk.Pixbuf instead. It is possible to get pixels for GdkPixbuf and modify the same in GTK. But unfortunately it appears that in case of GTK# that particular property (Pixels) of Gdk.Pixbuf is made as read only. One option maybe to use Gdk.Pixdata from Gdk.Pixbuf which is created from the image, modify the pixels using methods in Gdk.Pixdata, create a Gdk.Pixbuf out of it & copy that back to the original Gdk.Pixbuf. Unfortunately I cannot be sure about this, you can give it a shot though.
Alternatively you can consider drawing onto Gdk.Drawable. There are examples available wherein the Gdk.Drawable assocaited with Gtk.Widget (usually Gtk.DrawingArea) is updated in the Expose Event callback.
I hope that the information provided can provide you with some pointer to proceed.
Use Pixbuf first:
Gdk.Pixbuf pixbufImage = new Gdk.Pixbuf(#"images/test.png");
Gtk.Image gtkImage = new Gtk.Image(pixbufImage);
Gdk.Image gdkImage = gtkImage.ImageProp;

How to properly draw a GeometryDrawing on a Canvas in WPF (performance-wise)

A few days ago I asked the following question:
How to draw graphics as efficiently as possible in WPF
The consensus was that using a Canvas as host-object in combination with GeometryDrawing classes I had nothing to fear performance-wise.
Though, after implementing a simple test, I came to the conclusion the application chokes on only 3000 of those objects on-screen.
During the implementation, I noticed I had to encapsulate a GeometryDrawing object in 2 different objects (DrawingImage and Image) before I could make the Canvas render it, I think this is where the chokepoint is. Below is an example code on how I do this currently:
//Node
GeometryDrawing geoNode = new GeometryDrawing(
new SolidColorBrush(Utils.IntToColor(graphNode.Color)),
new Pen(Brushes.Black, graphNode.Thickness),
new EllipseGeometry(new Point(graphNode.Position.X, graphNode.Position.Y), 16, 16)
);
Image imageNode = new Image
{
Source = new DrawingImage(geoNode),
};
SetLeft(imageNode, graphNode.Position.X);
SetTop(imageNode, graphNode.Position.Y);
Children.Add(imageNode);
My questions are:
Is encapsulating the GeometryDrawing objects the proper method to get them rendered?
Is there a faster way to display my GeometryDrawing objects without having to encapsulate them (eg. something else than Canvas)?
Am I expecting too much if I want good performance with 3000 on-screen objects using WPF? It doesn't seem like a high-number to me, as a proper 2D engine can render 10000 objects and still run smoothly. Besides, it has been pointed out that "under the hood" WPF uses DirectX.
Thanks!
I ended up using WPF for the interface and used SlimDX/XNA for the actual rendering. The library that came out of it this will be available some time later.

Why this code throws System.ExecutionEngineException

Background:
I am using DirectX 9.0 Managed Libraries to transform arrays of 3d points to 2d screen coordinates. For speed I use the UnsafeNativeMethods to do all the transformations.
The Problem:
If my custom line clipping function is used my application dies without throwing any exceptions, it took me a while to figure out that it was throwing an uncatchable System.ExecutionEngineException. I have narrowed it down to happening because of the last two lines of my clipping function.
List<Vector3> verticesAfterClipping = new List<Vector3>;
public unsafe void ClipLine(Line lineToClip)
{
this.verticesAfterClipping.Clear();
// Clipping algorithm happens here... (this is psuedo-code of what it does)
foreach(Vertex in lineToClip.Vertices)
{
bool thisIsClipped = // Set to whether this vertex is clipped
bool lastWasClipped = // Set to whether last vertex was clipped
if(thisIsClipped == false && lastWasClipped == true)
{
verticesAfterClipping.Add( /* intersection on clipping plane */ );
verticesAfterClipping.Add( /* thisVertex */ );
}
else if (thisIsClipped == false && lastWasClipped == false)
{
verticesAfterClipping.Add( /* thisVertex */ );
}
else if (thisIsClipped == true && lastWasClipped == false)
{
verticesAfterClipping.Add(/* intersection on clipping plane */);
}
}
// THIS IS WHERE BAD THINGS HAPPEN
lineToClip.Vertices = new Vertex[verticesAfterClipping.Count];
verticesAfterClipping.CopyTo(lineToClip.Vertices, 0);
}
When the verticesAfterClipping list is copied to the lineToClip vertices the lineToClip object is then passed to an UnsafeNativeMethod which transforms these vertices to 2d vertices. From everything I can see when I step through it in Debug mode it is working completely fine, until it just dies.
I simply cannot figure out what is wrong. Any help would be much appreciated.
The problem may not actually be occurring in the line that throws an exception. This may just be a symptom of something that happened earlier.
The System.ExecutionEngineException exception is thrown when the CLR detects that something has gone horribly wrong. This can happen some considerable time after the problem occurred. This is because the exception is usually a result of corruption of internal data structures - the CLR discovers that something has got into a state that makes no sense. It throws an uncatchable exception because it's not safe to proceed.
So you might have some code in some completely unrelated part of the system that corrupts something, but this only becomes apparent when this particular piece of code runs. The code you've shown might be just fine. (It also might not be...I don't see anything obvious wrong, but then I don't know the DX 9 managed libraries well. I can't see which feature of this method requires the unsafe keyword, for example.)
Unfortunately, this means you need to start casting the net a bit wider. Pretty much anything that uses either unsafe code, or COM interop is potentially suspect. This will be a long and tedious process, sadly. One way you might approach it is to try gradually simplifying the program: what's the smallest piece of code that can illustrate the problem? (E.g., if you put the code you've shown there into an application that contains nothing else except the simplest possible call to that method, does it still fail?)
I have the same problem with different libraries. In my case all started long before because I had to run a 32 bit .net app in a 64 bit environment. Well this cause me a lot of trouble, the compatibility between architectures, or between the CLR of your .NET framework may be your problem too.
PS: Now I know what my trouble is but have no idea where is it.
I have two classes that deal with a particular table in my database
StorageManager - a class that has methods that handle the direct interactions with the database
Controller - a class that has methods to handle the api calls
When a new entry in the table is about to be created, I check child tables for certain values that might already exist.
I wrote these methods to check for pre-existing/duplicates in the wrong class, which ended up causing the executingengineexception to get thrown for me.
Moving the methods so that they lived with the correct database context seemed to fix it for me.

Categories

Resources