• What Do You Need Help With? V8
    1,074 replies, posted
Sorry for the delay, had to transcribe the code from the PDF file. Code #1: [C#] using System; using System; using System.Collections.Gene.. Code #2: [C#] using System; using System; using System.Collections.Gene..
A lot of this is C# specific. To better understand how a lot of this works, I'd highly recommend that you write a very basic console app that tries to call these functions, or just run the code yourself. Then you can set breakpoints and see what each line actually does. If you're not sure how to do things like setting a break point in Visual Studio, then checkout the beginner guide here. To get you started, I'll help you with the first example: The code starts by declaring a delegate. Delegates are like function pointers if you know what that is. It allows you to pass a method as a parameter to another method so that it can use it to do stuff like callbacks. F1: This function uses reflection to list the methods of the string type. F2: You should understand this one F3: This creates an instance of a "CSharpStudy.Utils" class. It then finds the "F4" method and calls that method with some arguments F4: this is basic string formatting. Using "{0}" in a string means that the first parameter will be used there: Console.WriteLine("My name is {0}. I like {1}", person.Name, person.FavFood); > "My name is Jeff. I like pizza" The rest is just basic OOP using the classic car example.
Been slapping my face into the keyboard a bit over this problem. I'm working on creating bindings for SDL for an engine for my own personal projects in C#. One of the goals of my SDL bindings is to get it working on all platforms through a single DLL (not including the native libraries). I believe in order to do this I need to dynamically load the native libraries in Runtime. I decided to make an extremely basic version of this until it is officially implemented. Learning from Mellinoe's NativeLibraryLoader I put something together that works great on Windows but miraculously fails on Android, which Mellinoe's NativeLibraryLoader also does. To get the SDL Bindings working for Android on C# I wrapped the SDL Android Project up into a jar and generated bindings to that JAR from Android, then when building the native libraries for android I also hook in my own tiny bit of code which implements SDL_main and has it call another function that we set using C#. void SetMain(Main main) {     CurrentMain = main; } int SDL_main(int argc, char* argv[]) {     CurrentMain();     return 0; } This all worked fine and dandy when using DllImport to call the SetMain function. But as soon as I switched over to the NativeLibrary method it (and many other SDL functions) failed to load properly on Android. My Unix Library Loader currently looks like this: public class UnixLibraryLoader : IPlatformLibraryLoader {     internal const string NativeLibrary = "libdl";     [DllImport(NativeLibrary)]     internal static extern IntPtr dlopen(string filename, int flags);     [DllImport(NativeLibrary)]     internal static extern IntPtr dlsym(IntPtr handle, string name);     [DllImport(NativeLibrary)]     internal static extern int dlclose(IntPtr handle);     [DllImport(NativeLibrary)]     internal static extern string dlerror();     public IntPtr LoadLibrary(string name)     {         const int rtldLazy = 0x00001;         const int rtldNow = 0x00002;         const int rtldNoLoad = 0x00004;         const int rtldGlobal = 0x00100;         var library = dlopen(name, rtldNoLoad | rtldGlobal);         if (library == IntPtr.Zero)             library = dlopen(name, rtldNow | rtldGlobal);         return library;     }     public IntPtr LoadFunction(IntPtr handle, string name) => dlsym(handle, name);     public void UnloadLibrary(IntPtr handle) => dlclose(handle); } It used to be smaller but got messier after trying everything I could to get this working properly. Right now when opening a library, as far as I know, it should be attempting to find an existing implementation of SDL2 and if it doesn't just open it ourselves. My current problem goes back to that wrapper code in C. For some reason when I use SetMain it doesn't stick, somewhere along the line the pointer to the function gets lost and is no longer assigned to CurrentMain. I had tests in each of those functions making sure that things were assigned, the SetMain would immediately check the CurrentMain variable after setting it, and the function would be there. But when I check CurrentMain before calling it in the SDL_main function, its gone, there is no longer a pointer to a function there. As far as I know this type of problem only showed up for me after I started using the NativeLibrary method, so I assume it has something to do with the dlopen or dlsym functions. But unfortunately I am not at all familiar with Unix or the dlx functions, so I have no clue what I'm doing or what's going wrong in my code. I've even tried spitting dlerror() messages out all over the place and still haven't figured anything out. And even if I use DllImport just for the SetMain portion, the rest of the SDL bindings also fail, so it's a greater issue than just with that specific function, there's something going on with the dll loading in general on Android and probably Linux. Any help would be appreciated
You should always use P/Invoke to load native libraries and not the platform specific way of LoadLibrary/dlopen unless you have a REALLY GOOD reason to do so. [DllImport("LibraryName", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] LibraryName should not contain any extension as it will be automatically added for each platform, there's also some config files where you can map library names onto something else. If you have native code which returns a delegate, keep in mind delegates also can have a calling convention and you are looking for the UnmanagedFunctionPointer attribute.
Unroll all your loops, you'll hit 5000 lines no problem ;)
Any OpenGL wizards know why glGetUniformLocation returns -1 even though the uniform is defined in the shader, but not being used? Is it a compiler optimisation or something? If so I'm gonna have to be extra careful with my shader combos later on :s
Yeah if you don't use a uniform it gets optimized out by the shader compiler.
Try explicitly stating the uniform location in the shader, and then in your code use that location instead of fetching it. IIRC those fetching commands really add up in the long run, so hopefully you don't use them in your rendering loop unless you absolutely have to. I circumvent this as much as possible by explicitly setting the uniform location in the shaders. This helps two fold as it also allows some sort of standardization between my certain types of shaders.
Long post, sorry if I'm annoying. It's for the C# class. I did as Foda (thanks again, I'm slowly getting somewhere with this) said but got stuck with this. I cannot figure out how this writes out what it writes out in the console. There's some comments I wrote in the code as well. It's mainly the use of EventArgs and onEvent that throws me off and reading the documentation about them wasn't too helpful. The WhatIsUp delegate         public delegate void WhatIsUp(object source, EventArgs e); //EventArgs? Has to do with event data but I don't get what role it has in this code. Where does the input for object and EventArgs come from? Method F4 in Utils class         public static void F4 (object o, EventArgs e) //from where does this get the inputs object o and EventArgs e in order to do the Console.WriteLine here?         {             Console.WriteLine("My name is: {0} not {1}", o, o.ToString());         } Observer class     public class Observer     {         private string name;         public Observer (ARegister a, string name)         { //             this.name = name;             a.onEvent += new Utils.WhatIsUp(What); //I know what += operator works. x += y is like x = x + y.             a.onEvent += new Utils.WhatIsUp(Utils.F4); // does it fetch input (object and EventArgs) for method F4 here somehow with the += operator? Also, what does onEvent do here?         }         private void What (object source, EventArgs e) //why is EventArgs and object used here as inputs ?         { //does it fetch input for both via += operator?             Console.WriteLine("My name is {0}", name);         }     } "A" class     public class A //I know how this class works.     {         public static string name;         private string address = "An address";         static A()         {             name = "A name";         }         public string Address         {             set { address = value; }             get { return address; }         }         public string Name         {             set { name = value; }             get { return name; }         }         public void print (object person)         {             Person p = person as Person;             Console.WriteLine((p.Address.Substring(0, 3)).CompareTo(p.Address));         }     } ARegister class     public class ARegister : List<A> //inheritance from class A? I know the ":" is inheritance but inhertiance from List<A>, I don't understand.     {         public Utils.WhatIsUp onEvent; //what does onevent do in this case?         public new void Hit (A a) //I know that new is used to create object, invoke constructors etc, but what role does it play here? Is it actually needed here?         {             if (onEvent != null)                 onEvent(this, EventArgs.Empty); //where does "this" point to in this case?         }     } Running the code:         static void Ab()         {             ARegister aR = new ARegister();             Observer obs = new Observer(aR, "E.T");             aR.Hit(new A());         }         static void Main (string [] args)         { Ab(); } //Console output My name is E.T My name is: ConsoleApp2.ARegister not ConsoleApp2.ARegister Thanks to whoever answers again.
I should have posted an example with that, even if you already know how (in case someone googles this and lands here) layout (binding = 0) uniform sampler2D ImageSampler; // makes this sampler look into GL_TEXTURE0 layout (location = 0) uniform float superImportantVariable; // can set variable by glUniform1fv at this location (0)
Do you have Discord by any chance? I can write you many examples there if you have the time, my username is (counts for anybody who wants help with C# or P/Invoke) Carpmanium#5094 For your WhatIsUp delegate the input comes from when you actually invoke the event handler, in your case the onEvent(this, EventArgs.Empty); in the ARegister class, think of onEvent as a list of functions. When you invoke it, it invokes every single function inside it with the this and EventArgs.Empty arguments. this in this case is the instance of ARegister class, for example: ARegister Potato = new ARegister(); Potato.Hit(new A()); this would be equal to Potato in this case. The "new" in "public new void Hit" is not required but it removes the warning when you define a function which exists in the base class, it is used to explicitly tell the compiler you want to shadow the old definition https://files.facepunch.com/forum/upload/108652/e6a9bb2d-01b5-493b-8f40-b01f692fc769/KLdXOA.png
Thanks a lot, you're a lifesaver lol. I just created a Discord account: Stjartgossen#6962
Oh cool, once I finish the tutorial series I'm gonna be rehashing a few things, so I guess I'll add "make automatic uniform system" to that list.. thinking along the lines of appending the uniform declarations into the shader files from code, I'll already be doing combos like that anyway.
It's also good to get in the habit of outright stating the locations since DX12 (iirc) and Vulkan (this I know for sure) require explicitly stating which locations the attributes and uniforms are bound to. Instead of querying the location at runtime, I found it easiest to just query all the locations when compiling/linking a shader. Then just store the attribute names and locations in some kind of map, and you'll be good to go. You can get more advanced by using generative shaders to always insert a certain fragment of attributes/uniforms into the header of your shader, which is what I'm working on - and on that topic, anyone have any resources on doing stuff like this? I'm just curious and sort of prodding around, it's not that complex but it'd be nice to see how other people have done it if nothing else.
I don't have any resources no, I was gonna just wing it seen as generating the uniform strings / defines is pretty easy really. It's gonna be a lot of fun once I figure out how to write shaders to disk as compiled files and load them at runtime instead of compiling every single time.
Do you mean like "including" another portion of shader code, like a package/header? I thought I read somewhere that opengl had that functionality sort of, but was heavily advised against using. I actually wanted to look into that again anyways, as a means of standardizing my lighting shaders because they have a LOT of redundant pbr related functions.
I am taking a graphics course as we speak, was gonna investigate doing that too. Will report back with results. I have a pretty good idea on how to accomplish it, just will have to see.
The GLSL includes are a nvidia extension that is sort of a pain to work with. Your best bet is to preprocess the shaders yourself, as in literally writing a micro C preprocessor to insert the files you "include". I did it a while ago when I was still using OpenGL, it's really not too bad. It gets easier if you can use something like <filesystem> in C++, since it makes finding files a whole lot easier. This sounds like using SPIR-V in OpenGL - this is a really good thing to do usually, as the OpenGL driver implementation (per card and per vendor) is required to otherwise implement it's own compiler for GLSL -> shader bytecode. SPIR-V is an intemediary bytecode format and is much easier (and often more performant) for the graphics card to process, since it's damn near the same as the driver's final bytecode anyways. There's a page here on using that: https://www.khronos.org/opengl/wiki/SPIR-V If you have more questions about SPIR-V, feel free to ask. It's the only format used with Vulkan, and parsing SPIR-V is how you have to perform reflection in Vulkan - there's nothing like "glGetUniformLocation" with Vulkan. It also has some different requirements and works like separable shader programs, compared to what you're probably used to thus far.
Is the spir-v data cross-platform, or is it required to be built on the end-machine that is running it, like current glsl shaders?
So I didn't realize this until now but SPIR-V is only supported by OpenGL 4.6 it looks like (for explicit support, I think?). There's an ARB extension back to 3.3 though: https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_gl_spirv.txt. I've otherwise used my SPIR-V binaries I've compiled once on windows on Mac, Linux, and Windows with no issues to speak of. Some of the time it was on integrated chips, sometimes it was dedicated gpus, and it was also varying driver versions. SPIR-V is pretty heckin' robust. Here's an example of compiling and linking a shader to SPIR-V in OpenGL: Example/SPIRV Full Compile Linking (and full wiki page: https://www.khronos.org/opengl/wiki/SPIR-V). The entry point can just be usually manually set to "main", which is what I've always done. Sascha is the go-to for most examples of using Vulkan, and it so happens that he also has a fuller example of SPIR-V in OpenGL: openglcpp/main.cpp at master · SaschaWillems/openglcpp · GitHub Note that the shader specialization call also opens up some really powerful possibilities and potential optimization points - Lets say you have a switch statement in your shader: switch(object_type) case 0: // object_type_skybox // skybox lighting stuff case 1: // object_type_geometry // conventional lighting stuff // and so on } By declaring a specialization constant where you declare other uniforms, like so: layout(constant_index = 0) const int object_type = 0; // spec. constants can be any scalar type Then in your call to glSpecializeShader, you can do the following: const GLuint constant_idx = 0; const int constant_value = 1; glSpecializeShader(SHADER_HANDLE, "main", 1, &constant_idx, &constant_value); These values are constant for the lifetime of the shader and are set at the link stage so the driver can (when consuming the SPIR-V) choose to just get completely get rid of the branching, discard the unused branches, and only traverse the single case you provided. I'd give this a shot and see what happens: I just realized the potential of using spec. constants like that last night after seeing of Sascha's Vulkan examples. It can also be useful for array indices and bounds, since it could potentially affect decisions about loop unrolling and such. Another important note is that you'll almost certainly (if I understand correctly) have to add these two lines to your shaders: #extension GL_ARB_separate_shader_objects : enable #extension GL_ARB_shading_language_420pack : enable You'll also need the interface block, as is you were using separable shaders conventionally: out gl_PerVertex { vec4 gl_Position; }; It's a bit of work and quite a change, but SPIR-V binaries have been one of my favorite parts of OpenGL thus far. Skipping the potential quality issues and unique bugs present in an IHVs GLSL compiler for a given architecture is nice, but it also makes passing shaders around easier and gives you neat things like specialization constants. It might be worth a try in your case.
Has anyone encountered an error where the winsock func accept() returns bad data even though all the parameters are fine and valid?
As this is a homework assignment, I'll hint you along. What function is used to print output? And where would you put it to get output in the loop?
public class DenseArray<T> : IEnumerable<T> { private readonly T[] _dataarray; public IEnumerator<T> GetEnumerator() { return (IEnumerator<T>) _dataarray.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _dataarray.GetEnumerator(); } So I have this data structure, here's a stubbed version, it uses an internal array to store everything. but when I try to use it in a foreach loop I find out there's something wrong with the IEnumerable implementation, it won't cast the data array enumerator to IEnumerator<T> Is the reason obvious? Why is it an invalid cast? Utility/DenseArray.cs at master · EReeves/Utility · GitHub
I felt like golfing that second one, but just posting the end result wouldn't be very helpful. Instead, I wrote down the process in an IPython notebook in the hopes it might be educational in some way. If not, well, I enjoyed writing it. https://gist.github.com/BackwardSpy/f98041f31f44a4875f36f3729beef245
Are there any design patterns that deal with storing/aggregating classes that all implement a common interface? Several times over I've run across this issue, and I've only figured out a janky solution. Currently, I'm working on an animation system, and thought I'd make an animator interface for things such as model related components to implement. However, I would like a way to be able to quickly grab all instances of classes that implement said interface. What I've done before was to make the interface an abstract class, give its constructor/destructor calls to the target system to register/deregister a reference to itself to store in a single list. But that feels wrong.
Any foreigners here that have gotten a developer job in the US? What company? Was it easy? How is the pay?
All my coworkers are Indian and got jobs here. starting salary is a little less than $60,000, but the cost of living is much lower in my area Companies look for talent outside of the United States all the time; you need an H-1B visa in order to work in the United States long term. Big companies hire H-1Bs all the time and will sponsor them if you're a good enough candidate. There is, however, political talk about severely limiting the number of H-1B visas in the United States (republicans are generally anti-immigrant), but I think H-1B is too valuable to huge companies for their lobbyists to allow that to happen. From what I hear, many big companies will use your H-1B status as an excuse to pay you less, so make sure to negotiate well and apply to more than one company
This is a question for anyone using Monogame/XNA, or just those who understand IDisposable well, since I definitely don't. I'm creating a RenderTarget2D to draw images and then get a Texture2D from that. RenderTarget2D uses IDisposable, but whenever I dispose of it, any texture I get back is empty (but with the original height and width). I can get past this by not disposing of it, but then I'm worried about memory leaks, since these function will need to be called multiple times for a lot of the images used in this project (sometimes up to 30 times per sprite), and a new RenderTarget2D needs to be created each time for the proper image size. This is the code I'm using. When I change the "use" to "let", which causes IDisposable not to be called, the image returns as expected. let draw graphicsDevice (rect: Rectangle) fn = use rt = new RenderTarget2D(graphicsDevice, rect.Width, rect.Height) graphicsDevice.SetRenderTarget rt graphicsDevice.Clear Color.Transparent use sb = new SpriteBatch(graphicsDevice) sb.Begin() fn sb sb.End() graphicsDevice.SetRenderTarget null rt :> Texture2D Which should be equivalent to this C# code public static Texture2D draw(GraphicsDevice graphicsDevice, Rectangle rect, Delegate<SpriteBatch> fn) { using (RenderTarget2D rt = new RenderTarget2D(graphicsDevice, rect.Width, rect.Height)) { graphicsDevice.SetRenderTarget(rt); graphicsDevice.Clear(Color.Transparent); using (SpriteBatch sb = new SpriteBatch(graphicsDevice)) { sb.Begin(); fn(sb); sb.End(); graphicsDevice.SetRenderTarget(null); return (Texture2D)rt; } } } Is this not as big of a problem as I'm thinking, or some way around this?
The whole point of IDisposable and using(){} is to dispose of any resources that have been used, what you are doing is returning the object after it has been disposed. Don't do this. Either create a set of them and cache them somewhere, or just manually dispose of them after you don't need them anymore. Also creating a render target and disposing it 30 times a frame sound really wasteful.
Oh, don't know how I didn't realize that I was just returning the same RenderTarget2D, rather than a copy. I'm an idiot. The function is only called for when the sprite is first loaded, so I don't have to worry about doing that every frame. Just was worried about memory building up after leaving the program running for a while, but it looks like that won't be the case anyways. Thanks.
Sorry, you need to Log In to post a reply to this thread.