How do I prevent receiving data from the network from dropping rendering frames in a multiplayer game? I'm building an HTML5 massively multiplayer online game. I've been working on this project for awhile, but am having some trouble sorting through a couple of performance issues. Since this is a multiplayer game, information is sent to and received from the network. When a client needs to know about new entities on the screen, the server must stream this data. Unfortunately, one big problem I'm having right now is that sometimes either a) a lot of data needs to be streamed or b) lots of small pieces of data are streamed in a short amount of time. Both scenarios currently cause the client to drop rendering frames as the client spends its time receiving packets and processing the data. What is the best way to prevent the networking data from causing frame rate problems? I am particularly interested in approaches to this kind of system that minimize frame drop issues, though suggestions tailored to my specific situation are welcome. Update To elaborate on the type of information sent in my particular case, my client does minimal interpolation and receives updates anytime the state of an entity changes on the server. The client also receives large packets with the entire state of an entity the first time the client needs to know about that entity.


Rendering tiles at a larger size for a detailed look I'm trying to make my 32 bit tiled map become more quot zoomed quot in. However, I experience an error that I can't resolve. Firstly, I followed this post on how to render the tiles larger. This is my code (close to identical to the code in the other post) class TiledMap def init (self, filename) tm pytmx.load pygame(filename, pixelalpha True) self.width tm.width tm.tilewidth self.height tm.height tm.tileheight self.tmxdata tm def render(self,surface) ti self.tmxdata.get tile image by gid for layer in self.tmxdata.visible layers if isinstance(layer,pytmx.TiledTileLayer) for x,y,gid in layer tile ti(gid) tile pg.transform.scale(tile,(64,64)) lt Line that gives Error if tile surface.blit(tile,(x 64, y 64)) def make map(self) temp surface pg.Surface((self.width, self.height)) self.render(temp surface) return temp surface The error that is produced is tile pg.transform.scale(tile,(64,64)) TypeError argument 1 must be pygame.Surface, not None I'm suspecting that some tile that its trying to render simply is empty. I've tried a separate smaller map but the issue persists. Is it the tileset? They've all been processed through the program Tiled where they were initially part of one png. If anyone knows a possible solutions I'll gladly try one. Or any other methods that could make it more zoomed in...


MonoGame rendering text with black boxes? I have a UI manager that renders a background image and some images and buttons using BlendState.AlphaBlend. This works as intended. However, when I try and draw some text on top of it with the same BlendState, each character is encased in a black box and it looks awful. I played around a bit and found that BlendState.Additive was the only one that didn't render the black boxes. However, the text is now slightly transparent, which looks weird. I then decided to mess around with custom BlendStates, but after around 10 minutes I found that there could be over 67 million different BlendStates. Hmm. My last thought is that it could be the font that is breaking it, because I tried rendering with the Arial font and AlphaBlend worked fine. Is there a way round this using BlendStates without finding a new font? tl dr I can only render text either with black boxes or half transparent. Text rendering code sb.Begin(samplerState SamplerState.PointClamp, blendState BlendState.AlphaBlend, transformMatrix Game.Camera.GetViewMatrix()) sb.DrawString(Game.Font, text, position, color) sb.End() SpriteFont File (using the free Minecraftia font) lt ?xml version "1.0" encoding "utf 8"? gt lt XnaContent xmlns Graphics "Microsoft.Xna.Framework.Content.Pipeline.Graphics" gt lt Asset Type "Graphics FontDescription" gt lt FontName gt Minecraftia lt FontName gt lt Size gt 6 lt Size gt lt Spacing gt 0 lt Spacing gt lt UseKerning gt true lt UseKerning gt lt Style gt Regular lt Style gt lt DefaultCharacter gt ? lt DefaultCharacter gt lt CharacterRegions gt lt CharacterRegion gt lt Start gt amp 32 lt Start gt lt End gt amp 126 lt End gt lt CharacterRegion gt lt CharacterRegions gt lt Asset gt lt XnaContent gt It's a pixelly game (so I need a blocky font to avoid weird antialiasing) and I think the font is a bitmap font. Just in case that makes a difference. Edit I found that setting the text size (in the SpriteFont file) to anything other than it's native size fixes the problem (but also renders with antialiasing, which I don't want). Also, this problem seems to happen with other bitmap fonts (tested 'Minecraftia' and '04b03').


How do I refer to the two types of loading screen? I'm troubleshooting some issues beyond the scope of this forum, and I'd like to be able to talk about certain parts of the gaming experience, specifically the two types of loading screen I see in Prey. Both are shown in this short video I made. The first type with the loading bar is what I usually think of as the quot loading screen quot , but what do I call the second quot loading screen quot that happens right after with the moving squares in the bottom right? To be clear, I'd like a term to be used with non game devs.


Ideas for extending tic tac toe game? I'm building a 3D tic tac toe game and this is what I've implemented so far 3D renderer with texture mapping Playing against the computer Playing online (multiplayer) Now I'm a little lost what I could add. Obviously, tic tac toe isn't that exciting or advanced, but I just miss something to salt it a little bit. Therefore, could anyone please suggest some ideas that would be worth implementing? Thanks!


Is there any reason to use a "canvas" based approach to GUI in isometric games? When designing game engine GUI systems, I know a lot of game engines (notably Unity and Unreal) use a sort of "canvas" system. However, in an isometric game where the camera is already orthographic, this seems like it might be overkill. Everything is already dictated in terms of pixels, as is the case in an isometric game I feel that there would be little need for such a "canvas", which seems to be the bridge between world space coordinates and screen space coordinates. With the orthographic view, world space is more seamlessly joined with screen space, so wouldn't it be simpler to get the position of the camera, define a set of points (i.e. top left, top right, center, etc.) on a plane that is directly in front of the camera and render controls directly in front of the camera? Would there be any downsides to this method, or am I missing the point entirely?


What's the use and difference between Forward, Deferred and Physically Based Rendering? Maybe I'm still confused about my own understanding, Forward Render render the lighting of an object according to the light source in the scene. (e.g Phong) Deferred Render render the scene to get geometric information, store it in a buffer, and then apply lighting. (e.g ?) PBR treats lights in the scene the way it behaves in the real world. (e.g Ray tracing, Photon Mapping) I don't see how Forward and Deferred render are going to give much difference to the scene. Why do we need to store the geometrical value in Deferred Render before applying lighting ? Why don't we just compute lighting right away like Forward Render ? Also for Physically Based Rendering, computing each light takes a lot of time, and almost impossible to be done in real time. But why this technique is always considered the best ?


Manual per glyph rendering with SDL TTF I'm trying to create a font atlas with SDL TTF. My idea was to create an SDL Surface for every character using TTF RenderGlyph Blended() and use TTF GlyphMetrics() to get glyph metrics so that I can position the surface relative to a baseline. I'm struggling with a correct positioning of a glyph. It looks like SDL TTF creates a surface with height which is at least the height of the font and width which is at least advance of a glyph, so the surface is bigger than just the glyph. How do I extract glyph's rectangle from the created surface? How do I position the glyph correctly relative to the base line on the screen? I thought y position of the glyph it should be baselineY maxy (where maxy is from TTF GlyphMetrics), but that places glyph too high above the base line.


Very slow motion smooth rendering cocos2d x I have a a white circle that I move on a black background very slowly. When I look very carefully, I see that the while moving the edge of the circle is jittering. In my opinion it is because the next row col of pixels becomes white from black where the circle should be rendered and as the pixel has some width I see some abrupt advance of the edge toward the direction. Ideally, this should not be visible if I would not have pixel discretization. But on the other hand a have a video sample with such a slow motion and my monitor renders it without any jumps on the edge. Hence, I think that it is because of not the fact that pixel have finite sizes but I render wrongly. How I can solve the problem? Any trick, flag? EDIT Here is the code I have used Sprite bg Sprite create("gfx letter background.png") addChild(bg, 100) bg gt runAction(MoveBy create(80, Vec2(500, 500))) wherer the .png I have used is a white circle attached below You don't see the image above as it is white )


How is the Unreal rendering pipeline implimented? I know this seems like a very broad question, but i am just interested in getting to know how the Unreal engine's rendering pipeline looks like, specially how it handles meterials, different types of lighting, and post processing. I know that Unreal4 uses differred shading, but how does it handle things like translucency, reflections, etc. I do not have access to the source code, that's why I asked this question here. You could even direct me to the source of the rendering part if available.


How can I create character graphics similar to Valkyrie Profile? I want to create a game with the character graphics similar to Valkyrie Profile. I don't know whether I should make my game character sprites pre rendered or hand drawn, or which technique would let me create a similar look. Are these created pixel by pixel, what sets me off is the ditter found in a lot of the images, kind of looks like the characters from treasure hunter G or harvest moon friends of mineral town. edit Added the screenshots from Treasure Hunter G and Harvest Moon. I know these are pre rendered sprites that are later incorporated into the game, just for comparison against the valkyrie profile ones. Also, the treasure hunter G is a SNES game, and the Valkyrie Profile is PSX one, so I expect an upgrade in graphics.


Input handling between game loops This may be obvious and trivial for you but as I am a newbie in programming I come with a specific question. I have three loops in my game engine which are input loop, update loop and render loop. Update loop is set to 10 ticks per second with a fixed timestep, render loop is capped at around 60 fps and the input loop runs as fast as possible. I am using one of the Javascript frameworks which provide such things but it doesn't really matter. Let's say I am rendering a tile map and the view of which elements are rendered depends on camera like movement variables which are modified during key pressing. This is only about camera viewport and rendering, no game physics involved here. And now, how can I handle input events among these loops to keep consistent engine reaction? Am I supposed to read the current variable modified with input and do some needed calculations in a update loop and share the result so it could be interpolated in a render loop? Or read the input effect directly inside the render loop and put needed calculations inside? I thought interpreting user input inside an update loop with a low tick rate would be inaccurate and kind of unresponsive while rendering with interpolation in the final view. How it is done properly in games overall?


How to use a mask texture with Kobold2D I am an iOS developer but I'm new to cocos2d. I'm working on new game, I use Kobold2D, have cocos2d installed too, and I want to make this effect I know how is done with Flash, but can't make it with Kobold2D. There's 2 images with the same size one is a low res image for the background and the second is a hi res over the first one. When the "reticle" mask moves, it reveals the second image inside the circle and the background is visible outside only. I googled with no success, saw some Ray Wenderlich projects they weren't helpful.


Partial mesh culling by checking against the AABB tree of objects vertices instead of only the AABB of the whole objects First thing this is more of a conceptual question than an implementation oriented one, but still tips about implementation will be very much welcome if you happen to have any (athough I have some experience programming different parts of games, graphics are certainly my weak spot as you will see). So, I have an application in which all high poly objects have their vertices grouped in an object specific AABB tree to speed up the narrow phase of collision detection. Now, it occurred to me the following. Since that structure is already in place, would it be possible to use it for culling parts of objects instead of the usual all or nothing approach of the frustum and occlusion culling techniques? The idea for that is simple in concept. Instead of testing for visibility only using the whole objects' AABB, I would do that first but in the positive cases I would proceed to visibility checks of the sub AABBs containing that object's vertices. Once identified the sub AABBs that are visible, only the triangles that are contained in these sub AABBs would be sent to the GPU for rendering. Therefore, in a more systematized way, my three related questions are 1) is such an approach even possible in what regards the way GPU gets and processes the mesh geometry information pulled from CPU? 2) given that in such scenario the CPU would have to break the meshes somehow and pass to the GPU only the vertices that were identified as being in the visible parts of the visible objects, wouldn't that pose additional load on the processing time such that the cost would overcome the gains? 3) most importantly, passing to the GPU only some triangles of a mesh could cause graphically distorted results when shader and texture are rendered for that partially only rendered object? I searched quite a bit for academic references on this subject but came almost empty. I would gladly welcome reading suggestions of any sort.


Rendering a selected part of the terrain with different shading I'm trying to understand how to modify the shading of the section of the terrain based on some user selection. In a game like Civ5, when a user selects a city or unit, that area is lit up more than the other parts of the terrain. I'm trying to implement this effect. In the civ 5 example the selected tile is has a circle outline and the selected city has a transparent overlay that follows the height of the terrain nicely. My current pipeline so far is at a primitive state. I render a quad and texture it with a grass texture. Then I draw a rectangular grid on top of this (a set of lines, with a slightly higher height value than the background grid). Upon selection (ie a mouse click inside the grid area), I calculate the approriate grid index by converting mouse to world coordinates and then to grid coordinates, and highlight the appropriate grid rectangle by changing the color of that particular rectangle. But, my approach gets outdated the moment I get a height map (as it assumes constant height), and looks pretty bad, hence this question. EDIT Added my pipeline description


How do 3D rendering pipelines render light effects? How does 3D software like Blender, Maya, Unity, or Houidini etc. render the effects of lights illuminating a 3D scene?


Drawing a line between 2 vectors I was trying to implement a simple mechanic by drawing a line between the sprite and the mouse, but it's not working that well extends KinematicBody2D onready var player CollisionShape2D var pos two var pos func physics process(delta) var vel Vector2() pos two player.get position() pos get global mouse position() look at(pos) if Input.is action pressed( quot movethere quot ) vel Vector2(400 , 0).rotated(rotation) vel move and slide(vel) func draw() draw line( pos two ,pos, Color(255 , 0 , 0))


Drawing thousands of isometric tiles per frame with a high FPS This question seems similar to other questions but no other topics I saw helped. I'm making a game in GML (GameMaker Language). Regardless of the language software, this should be a universal topic. Okay, so I currently barely exceed 60FPS on a game with no code in the tick (step? frame? iteration?) so it should most definitely not be a CPU issue. My computer is fantastic and I can run nearly all (if not, all) games at ultra and high settings. Anyway, my game is isometric and tiles are 32x16. The terrain data ds grid (like a 2D array, but can't be jagged) is never changed except when loading other maps. I need the game to be played in a max of 1080p, and higher resolutions won't be implicitly supported. So, I have a nested for loop, to loop through a calculated minx maxx and miny maxy, basically defining the rectangular area in the terrain data ds grid that I need to render. However, at the moment, in 1080p, after applying a variable called count to increment every iteration of the nested loop, I have nearly 8000 draw calls every frame, rendering every tile near the view. Remember, the tiles are both isometric and small, so there are a lot of things needed to be rendered. There are multiple grass tiles to reduce texture repeating. There is also a water tile, and I may add other terrain tiles. So basically, I need a method of rendering tons of tiles (that don't change) with a much higher (preferably at least 300) FPS. MORE INFO in GM, a ds grid is a data structure that is very similar to a 2D array, where the main differences are that it cannot be jagged (it's similar to a table) and any cell can hold any data type, so I could have strings and real numbers etc. all in the same ds grid. My ds grid contains enumeration values, such as tile.grass or tile.water. The terrain does not fit within the screen borders, and resolution directly affects view size.


16bit triangle lists vs 32bit triangle strips When drawing geometry we may use indexed drawing, where we pass index of the vertex we want to draw in array. In this case we need to pick a topology for our geometry and the type of indices. Popular topologies are triangle lists, where we have to specify 3 indices for each triangle, and triangle strips, where each new triangle shares its first 2 vertices with last 2 vertices of previous triangle. As for index types we have 16 bit indices, which allow for 65k vertices per model, and 32 bit indices, 4B vertices. My GPU (1050ti) fetches 32 bit indices at half the rate of 16 bit indices, where 16 bit indices triangle list topology gets it at its maximum throughput, but so do 32bit triangle strips. As my GPU isn't that old, I expect many GPUs to be quite alike in this manner. So, is the inconvinience of having to specify geometry in strips worse than having a limit to 65k vertices per model?


How can I render cloud patterns like in these examples? I have a quick question. I see in many games, usually in the menu, some moving "clouds" in the background, apparently additive blended into each other, which does a really nice job immersing the player, in my opinion. A couple of examples that jump to mind right now are the Far Cry 3 main menu background https www.youtube.com watch?v B5XcMx3GjPA and the Plague Inc main menu background https www.youtube.com watch?v RQv60ywrLxU (the first seconds show it) These cloudy patterns seem like some kind of noise to me, like Perlin or other. So, how would you proceed to achieve that kind of blurred cloud effect with vivid colors? More specifically, would you pre generate sets of clouds and include them in the game package? Or generate them on the fly? On the CPU as a regular texture or on draw in the GPU shader program? I am interested in mastering this kind of visual effect, and as such any help would be appreciated pointing me in the right way. Thanks.


How can I keep straight alpha during rendering particles? Rencently,I was trying to save textures of 3D particles so that I can reuse the in 2D rendering.Now I had some problem with alpha channel.Some artist told me I that my textures should have unpremultiplied alpha channel.When I try to get the rgb value back,I got strange result.Some area went lighter and even totally white.I mainly focus on additive and blend mode,that is ADDITIVE srcAlpha VS 1 BLEND srcAlpha VS 1 srcAlpha I tried a technique called premultiplied alpha.This technique just got you the right rgb value,its all you need on screen.As for alpha value,it worked well with BLEND mode,but not ADDITIVE mode.As you can see in parameters,BLEND mode always controlled its value within 1.While ADDITIVE mode cannot guarantee. I want proper alpha,but it just got too big or too small consider to rgb.Now what can I do?Any help will be great thankful. PS If you don't understand what I am trying to do,there is a commercial software called "Particle Illusion".You can create various particles and then save the scene to texture,where you can choose to remove background of particles. Now,I changed the title.For some software like maya or AE,what I want is called straight alpha .


How should I implement multi pass rendering in a game engine? I have done multi pass rendering, before, and understand how it works. I made a simple example, which rendered a basic scene with shadows. This was all part of one file. Now, I am trying to figure out is how to put it into my game engine. Currently, my game engine uses a single pass. It is in a hierarchical structure, and uses Direct3D 9. I have a graphics component, which will load and draw a 3D model. In my game loop, I update all of the entities in the world, then I call the draw function for each one. This draw function gets the vertex buffer, index buffer and texture or material, and draws the 3D model using a shader. This works fine. To do multi pass rendering, to allow for shadows, I will need to draw each model multiple times. It doesn't seem right, to me, that in each models draw function I should put the second pass code this will then be completed before the next models first pass. How should I implement multi pass rendering in a game engine?


How do I create a manual object with colors for each vertex? How do I create a shaded manual object with colours for each vertex? Eg if ogreObj is the Ogre ManualObject ogreObj gt begin("BaseWhiteNoLighting", Ogre RenderOperation OT TRIANGLE LIST) will allow me to select each vertex's colour with ogreObj gt colour(r, g, b) after each ogreObj gt position(x, y, z) and ogreObj gt normal(x, y, z) call. However, if I change the material to BaseWhite, color() instructions are ignored. I read that you must disable lighting int the .material script, but I need it active... Any advice? ANSWER This Ogre forum's thread has a simple .material script that works for this purpose material Voxel Default technique pass diffuse vertexcolour specular vertexcolour ambient vertexcolour lighting on


cocos2d mask rotation I've been experimenting with Ray Wenderlich's tutorial about masking sprite using shaders with cocos2D 2.0. It works pretty well but now I'd like to rotate the mask independently of the masked texture. Does anyone have any idea about how to achieve it ?


Using multiple shaders I'm currently studying opengl shaders but I can't figure out something how to apply different shaders to the objects, for example, a teapot rendered using toon shader and another one in the same scene using a very reflective surface and other distorted from a noise function, like in this video http www.youtube.com watch?v 1ogg4ZfdBqU Another one is applying a bloom shader in a scene and a motion blur shader afterwards. How to achieve those effects when you can only have one vertex shader and one fragment shader? Is there any trick such as using more than one shader program?


Vertex Shader Fundamental Workings I understand that water ripples (e.g. stone thrown into a pond) are often handled with vertex shaders. My first question is are the ripples nothing more than an algorithm that is the function of time? If yes, it means that the size and diameter of ripples is not "additive." It means water vertices do not statefully "remember" their previous "disturbance" positions and accumulate more translation info. Rather it means that, as a function of time, the position of "disturbed" water vertices are freshly computed each frame per unit time. If no, it means that indeed the vertices accumulate disturbance translation information the vertices are stateful. I hope the answer is "yes," because that actually makes sense to me. If the answer is no, the I feel it creates tremendous burden on the CPU GPU to keep track of all the state per vertice. If the answer is "neither," do tell. ) My second question is, assuming a "yes" above, how does such a "water disturbance shader algorithm" account for continuous interaction with irregular shapes? For example, please look at the video 40 second mark showing a car crashing through water. It is not so clear how the vertex shader knows how to make a rectangular disturbance shape (the shape of the car). Perhaps, over simplifying, the vertex shader takes both time and a vector to generate the ripples, where the vector is the speed direction of a car (and the shader code always makes a car shaped rectangle no matter what). Is this the right high level understanding of how this water trick works?


Cocos2d x Differences between applying shader to child node and entire scene? I'm beginning with shader. I wonder what if i apply shader for single node, what'll happen? The gl FragCoord (0.5,0.5) is the bottom left of the screen or the bottom left of the node? I get some wrong caculations while wanting to draw something in the center of the node (not the screen). Many shader tutorias with sample code to draw at center using gl FragCoord.xy resolution.xy, if it's 0.5, it's center. In this case, it might be wrong because i want to draw in center of the node. Finally, how's about texture2D i use texture2D instead of texture, are they the same? I've applied this code on the node and it prints out the whole screen with stretch version (resolution device resolution) vec2 xy gl FragCoord.xy resolution.xy vec4 texColor texture2D(CC Texture0,xy) gl FragColor texColor


How can I replicate the color limitations of the NES with an HLSL pixel shader? So since 256 color mode is depreciated and no longer supported under Direct3D mode, I got the idea to use a pixel shader instead to simulate the NES palette of all possible colors so that fading objects and whatnot don't have smooth fade outs with alpha channels. (I know objects couldn't really fade out on the NES, but I have all objects that do fade in and out on a solid black background, which would be possible with palette swapping. Also, the screen fades in and out when you pause which I know also was possible with palette swapping as it was done in a few Mega Man games.) Problem is, I know next to nothing about HLSL shaders. How do I do it?


Monogame fails to load Effect I'm currently porting an old XNA game over to MonoGame and everything (including custom shaders) build fine. However when i try to load the xnb file using content.Load lt Effect gt ("BaseDraw") I receive the following error An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll Additional information HRESULT 0x80070057 , Module General , ApiCode E INVALIDARG Invalid Arguments , Message The parameter is incorrect. I even tried building the shaders with 2MGFX.exe and loading it manually but that throws the same error. I have no idea what to so any help would be appreciated!


bug in webgl phong shader lighting rotates with object I'm working on a simple phong shader in webgl, and I think I'm getting close but something is still wrong. Dead give away if I have a billboard and have it roll (so it spins like a wheel), the part of the billboard that is lit up spins with it (. This confuses me, because it seems like a problem with the model matrix, but the transform makes all the positions amp rotations correct, and lighting math is done entirely in world coordinates , just the lighting wrong. Ditto with the view matrix, I can move around and look freely and everything is located in its proper place, just lit wrong. Here are my shaders (minus the definitions for space, and with the lighting in the model matrix moved into GPU for clarity) if you prefer reading in github https github.com nickgeorge quantum blob master index.html L41 lt script id "fragment shader" type "x shader x fragment" gt void main(void) vec3 lightWeighting if (!uUseLighting) lightWeighting vec3(1.0, 1.0, 1.0) else vec3 lightDirection normalize(vLightPosition.xyz vPosition.xyz) float directionalLightWeighting max(0.0, dot( normalize(vTransformedNormal), lightDirection)) lightWeighting uAmbientColor uPointLightingColor directionalLightWeighting vec4 fragmentColor if (uUseTexture) fragmentColor texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) else fragmentColor uColor gl FragColor vec4(fragmentColor.rgb lightWeighting, fragmentColor.a) lt script gt lt script id "vertex shader" type "x shader x vertex" gt void main(void) vPosition uModelMatrix vec4(aVertexPosition, 1.0) TODO Move back to CPU vLightPosition uModelMatrix vec4(uPointLightingLocation, 1.0) gl Position uPerspectiveMatrix uViewMatrix vPosition vTextureCoord aTextureCoord vTransformedNormal normalize(uNormalMatrix aVertexNormal) lt script gt Thanks a lot, and let me know if there's anything else useful to add.


Algorithm for a rain effect (Shaders) I'm trying to implement a rain effect using shader, I use godot 3 alpha, which uses a simplified GLSL 3.0 language. But I'm just finding very complex examples for me, I understand little about shaders, I wanted to achieve something very basic even to be able to walk. I thought of doing the following, moving the texture with just a few painted pixels. Yet I still do not know where to start. I found this code, I really wanted to understand what is done in it http www.glslsandbox.com e 36547.0 I managed to translate the code for godot 3, but it does not work very well, I believe this line is to blame p 0.5 0.35 sin(11.0 fract(sin((s p scale) mat2(vec2(7,3),vec2(6,5))) 5.0)) f What really is done that line? I can not understand what he does. I did so shader type canvas item uniform float direction uniform float velocity 1.0 uniform float intensity float snow(vec2 uv, float scale, float time) float w smoothstep(1.0,0.0, uv.y (scale 10.0)) if(w lt 0.1) return 0.0 uv time scale uv.y time velocity scale VELOCITY uv.x sin(uv.y time 0.5) scale uv scale vec2 s floor(uv) vec2 f fract(uv) vec2 p float k 3.0 float d vec2 t (s p vec2(scale)) mat2(vec2(7.0, 3.0), vec2(6.0,5.0)) p.y (0.5 0.35 sin(11.0 fract(sin((s.y p.y scale) t.y) 5.0)) f.y) p.x f.x d length(p) k min(d,k) k smoothstep(0.0,k,sin(f.x f.y) 0.01) return k w void fragment() vec2 uv (COLOR.xy 2.0 SCREEN UV.xy) min(SCREEN UV.x,SCREEN UV.y) float c smoothstep(1.0,0.3,clamp(uv.y 0.3 0.8,0.0,0.75)) c snow(uv, 30.0, TIME) 0.3 c snow(uv, 20.0, TIME) 0.5 c snow(uv, 15.0, TIME) 0.8 c snow(uv, 10.0, TIME) c snow(uv, 8.0, TIME) c snow(uv, 6.0, TIME) c snow(uv, 5.0, TIME) c snow(uv, 2.0, TIME) COLOR vec4(vec3(c),0.5) and this happens I have discovered that by decreasing the value I am passing to the scale, it increases the "particles", I mean how octaves in a noise, the smaller the number last, the greater the peaos generated. But my screen seems to be divided in two, cut by a diagonal line, I do not understand much because. I realize that here is the problem vec2 uv (COLOR.xy 2.0 SCREEN UV.xy) min(SCREEN UV.x,SCREEN UV.y) Up 1 I managed to improve with this vec2 uv UV now it's like this but what he wanted was to be able to pass three uniforms, direction, velocity and intensity, and to be able to control the direction (right equer), the speed with which they fall, the intensity (higher or lower particles, more or less drops). But I still do not understand how well it is done to do that. Even more that what I will do is rain, I have to understand what is done with the colors to get the idea of rain and not snow. Up 2 I was stirring here and the velocity, intensity and direction I was able to configure passing a uniform. But I can not change the color of the drops, it always comes out black and white. How would you put a blue color for example? I try to change the color to red for example using the mix() function vec3 col2 vec3(1.0, 0.0, 0.0) vec3 resultColor mix(vec3(c), col2, 0.7) COLOR vec4(vec3(resultColor),0.3) and I get this I wanted to change only the color of the drops? R I got it like this COLOR vec4(vec3(0.3, 0.3, c),0.5) but I'm not very fond of the result, it's very bright, and my breasts are too big, I'll fix it.


HLSL How to flip geometry horizontally I want to flip my asymmetric 3d model horizontally in the vertex shader alongside an arbitrary plane parallel to the YZ plane. This should switch everything for the model from the left hand side to the right hand side (like flipping it in Photoshop). Doing it in pixel shader would be a huge computational cost (extra RT, more fullscreen samples...), so it must be done in the vertex shader. Once more this is NOT reflection, i need to flip THE WHOLE MODEL. I thought I could simply do the following Turn off culling. Run the following code in the vertex shader input.Position mul(input.Position, World) World 3 0 holds x value of the model's pivot in the World. if (input.Position.x lt World 3 0 ) input.Position.x World 3 0 input.Position.x else input.Position.x input.Position.x World 3 0 ... The model is never drawn. Where am I wrong? I presume that messes up the index buffer. Can something be done about it? P.S. it's INSANELY HARD to format code here. Thanks to Panda I found my problem. SOLUTION Do thins before anything else in the vertex shader. Position.x 1 To invert alongside the object's YZ plane.


What are the pros and cons of HLSL vs GLSL vs cg? What are the pros cons of the three?


Fragment shader for lighting in isometric perspective What I'm trying to do is to achieve basic lighting in 2D from an isometric perspective. Here I have 2 textures that are used as tiles for the ground Color Normal map I have a fragment shader that was adjusted a bit to my needs, but mostly made from this tutorial https github.com mattdesl lwjgl basics wiki ShaderLesson6 Here is my fragment shader uniform sampler2D texture uniform sampler2D normal texture values used for shading algorithm... uniform vec2 Resolution resolution of screen uniform vec4 AmbientColor ambient RGBA alpha is intensity uniform vec3 LightPos 3 light position, normalized uniform vec4 LightColor 3 light RGBA alpha is intensity uniform vec3 Falloff 3 attenuation coefficients void main() vec4 DiffuseColor texture2D(texture, gl TexCoord 0 .xy) vec3 NormalMap texture2D(normal texture, gl TexCoord 0 .xy) vec3 Sum vec3(0.0) for (int i 0 i lt 3 i ) The delta position of light vec3 LightDir vec3(LightPos i .xy (gl FragCoord.xy Resolution.xy), LightPos i .z) Correct for aspect ratio LightDir.x Resolution.x Resolution.y Determine distance (used for attenuation) BEFORE we normalize our LightDir float D length(LightDir) normalize our vectors vec3 N normalize(NormalMap 2.0 1.0) vec3 L normalize(LightDir) Pre multiply light color with intensity Then perform "N dot L" to determine our diffuse term vec3 Diffuse (LightColor i .rgb LightColor i .a) max(dot(N, L), 0.0) pre multiply ambient color with intensity vec3 Ambient AmbientColor.rgb AmbientColor.a calculate attenuation float Attenuation 1.0 (Falloff i .x (Falloff i .y D) (Falloff i .z D D)) the calculation which brings it all together vec3 Intensity Ambient Diffuse Attenuation vec3 FinalColor DiffuseColor.rgb Intensity Sum FinalColor gl FragColor gl Color vec4(Sum, DiffuseColor.a) This shader WORKS with traditional 2D perspective. That's because in traditional perspective the ground tiles normal map would have a color scheme closer to something like this, just wouldn't be tilted to fit an isometric perspective of course. The issue How do I go about adjusting the math in my fragment shader to fit an isometric perspective and work with the "greenish" ground normal maps. Here's what I'm currently getting with this shader. Light should be equally going in all directions, but it's as if it's going down a slope.


Basic equation for pure metallic reflectance I'm working on a live wallpaper that shows a pure metallic object. Since it's a live wallpaper, I can make a ton of approximations...this isn't a full blown scene in a game world. My shader only has to support this one material. People won't expect extreme detail, etc. So, for example, I don't even bother with diffuse since a pure conductive material barely has any. So I'm trying to implement a reflective conductive surface that pulls the reflection from a cubemap representing the lighting environment. On a very basic level it looks like this vec3 fresnelSchlick (vec3 f0, float cosTheta) return mix(f0, vec3(1.0), pow(1.0 cosTheta, 5.0)) ... float NdV dot(normal, viewDir) vec2 brdf texture2D(u brdf, vec2(u roughness, NdV)).rg from a LUT vec3 reflection textureCube(u cubemap, reflect(viewDir, normal)) gl FragColor reflection (fresnelSchlick(materialColor, NdV) brdf.x brdf.y) The problem with my simple math here is that the range of possible final pixel colors does not produce a proper looking range of hues. Suppose my material color is 0050ff and the environment is monochrome white. Then all of the possible colors that could be seen are This doesn't allow for bright looking reflections at the light sources in the envmap. I found this example material render for comparison. The cubemap in the example here is close to monochrome white. But at the bright areas of the reflection, there is a lot of red component in the color. With my limited range of colors, my object looks dull and lifeless. Can anyone point out what I'm missing in my equation?


Shader authoring editing tools for GLSL ES Since Render Monkey has been discontinued (perhaps due to the complexity of today's shading languages), there are few successors that can match its functionality. Is there any useful tool for material editing aimed at developers and artists alike, but concentrated (or with substantial support for) on embedded GLSL shaders? Render Monkey itself wasn't that flexible (I'm not aware if it allowed the usage of several textures, each with its own set of texture coordinates plus, it didn't seem to be that intuitive either). Apart from complete engines, is there such a stand alone tool that can be used together with a stand alone engine (able to interface with a custom application)?


Rendering terrain only with GPU This is not about generating plane geometry and then applying a shader on it. Instead, I want a big single flat plane, then apply a shader on it. The vertex shader has a uniform vec3 realPlanePosition and calls a height calculation function Vertex shader code uniform vec3 realPlanePosition varying vPosition float heightCalculation(vec2 verticePosition) Just for pseudo code (more black magic append here). return magicNoise2D(verticePosition.x, verticePosition.y) void main(void) vec3 vPosition position vec2 verticePosition vec2(vPosition.x realPlanePosition.x, vPosition.y realPlanePosition.z) vPosition.z heightCalculation(verticePosition) gl Position projectionMatrix modelViewMatrix vec4(vPosition, 1.0) In my plane update code, I just change realPlanePosition with player position, for example. The plane moves on (x, z) (X rotation PI 2.0). The only thing the vertex shader updates is the z (due to plane rotation) value of gl Position. Is this good practice? Also, how do I detect collisions with it? And finally, how can I control other terrain objects' generation (rocks, trees, ...)


Can't import shaders textures to Godot from Blender 2.8 I'm using this shader for my models and then i import them like this This is the original model in blender the result in godot I think i might have missed some step but not sure of which one, i followed the tutorial video on how to import and other similar guides but the results is the same. Any ideas of what i'm doing wrong? Looks like my model not importing shader and textures cor


Bump mapping Problem GLSL I am having a slight problem with my Bump Mapping project. Although everything works OK (at least from what I know) there is a slight mistake somewhere and I get incorrect shading on the brick wall when the light goes to the one side or the other as seen in the picture below The light is on the right side so the shading on the wall should be the other way. I have provided the shaders to help find the issue (I do not have much experience with shaders). Shaders varying vec3 viewVec varying vec3 position varying vec3 lightvec attribute vec3 tangent attribute vec3 binormal uniform vec3 lightpos uniform mat4 cameraMat void main() gl TexCoord 0 gl MultiTexCoord0 gl Position ftransform() position vec3(gl ModelViewMatrix gl Vertex) lightvec vec3(cameraMat vec4(lightpos,1.0)) position vec3 eyeVec vec3(gl ModelViewMatrix gl Vertex) viewVec normalize( eyeVec) uniform sampler2D colormap uniform sampler2D normalmap varying vec3 viewVec varying vec3 position varying vec3 lightvec vec3 vv uniform float diffuset uniform float specularterm uniform float ambientterm void main() vv viewVec vec3 normals normalize(texture2D(normalmap,gl TexCoord 0 .st).rgb 2.0 1.0) normals.y normals.y normals (normals gl NormalMatrix).xyz vec3 distance lightvec float dist number length(distance) float final dist number 2.0 pow(dist number,diffuset) vec3 light dir normalize(lightvec) vec3 Halfvector normalize(light dir vv) float angle max(dot(Halfvector,normals),0.0) angle pow(angle,specularterm) vec3 specular vec3(angle,angle,angle) float diffuseterm max(dot(light dir,normals),0.0) vec3 diffuse diffuseterm texture2D(colormap,gl TexCoord 0 .st).rgb vec3 ambient ambientterm texture2D(colormap,gl TexCoord 0 .st).rgb vec3 diffusefinal diffuse final dist number vec3 finalcolor diffusefinal specular ambient gl FragColor vec4(finalcolor, 1.0)


Disney BRDF where is metallic factor input into BRDF? Burley states about metallic parameter "This is a linear blend between two different models. ..." What are the two models? I can't see this described in the Frostbite or the Unreal papers either. Is it simply a blend between the diffuse and specular terms or a scaling factor on the specular term? Disney Paper


Alpha is not working in diffuse light shader I am following this tutorials series on rastertek.com and I got a bit stuck on the Diffuse Lighting Tutorial. Particulary, the part that does not work for me is alpha channel of the light color. Here are the I think they are relevant code parts Light Shader cbuffer MatrixBuffer matrix worldMatrix matrix viewMatrix matrix projectionMatrix Texture2D shaderTexture SamplerState SampleType cbuffer LightBuffer float4 ambientColor float4 diffuseColor float3 lightDirection float padding struct PixelInputType float4 position SV POSITION float2 tex TEXCOORD0 float3 normal NORMAL float4 LightPixelShader(PixelInputType input) SV TARGET float4 textureColor float3 lightDir float lightIntensity float4 color textureColor shaderTexture.Sample(SampleType, input.tex) lightDir lightDirection lightIntensity saturate(dot(input.normal, lightDir)) color saturate(diffuseColor lightIntensity) color color textureColor return color PixelInputType LightVertexShader(VertexInputType input) PixelInputType output input.position.w 1.0f output.position mul(input.position, worldMatrix) output.position mul(output.position, viewMatrix) output.position mul(output.position, projectionMatrix) output.tex input.tex output.normal mul(input.normal, (float3x3)worldMatrix) output.normal normalize(output.normal) return output The problem here is the shader completely ignores the alpha channel of the light. If I set the diffuse color to red, then the texture will be reddish no matter what alpha is supplied. The only way I could make the alpha work is changing the line color color textureColor to color color color.w textureColor in the pixel shader. This however gives overall wrong result. Might it be the DirectX setup issue, here are some parts of the device initialization Set regular 32 bit surface for the back buffer. swapChainDesc.BufferDesc.Format DXGI FORMAT R8G8B8A8 UNORM ... Set up the description of the depth buffer. depthBufferDesc.Width screenWidth depthBufferDesc.Height screenHeight depthBufferDesc.MipLevels 1 depthBufferDesc.ArraySize 1 depthBufferDesc.Format DXGI FORMAT D24 UNORM S8 UINT depthBufferDesc.SampleDesc.Count 1 depthBufferDesc.SampleDesc.Quality swapChainDesc.SampleDesc.Quality depthBufferDesc.Usage D3D11 USAGE DEFAULT depthBufferDesc.BindFlags D3D11 BIND DEPTH STENCIL depthBufferDesc.CPUAccessFlags 0 depthBufferDesc.MiscFlags 0 ... Setup the raster description which will determine how and what polygons will be drawn. rasterDesc.AntialiasedLineEnable false rasterDesc.CullMode D3D11 CULL BACK rasterDesc.DepthBias 0 rasterDesc.DepthBiasClamp 0.0f rasterDesc.DepthClipEnable true rasterDesc.FillMode D3D11 FILL SOLID rasterDesc.FrontCounterClockwise false rasterDesc.MultisampleEnable false rasterDesc.ScissorEnable false rasterDesc.SlopeScaledDepthBias 0.0f What's wrong with this shader? I'm not sure what other code might be relevant, I will gladly add any at your request.


Using Jump Flooding Alghorithm for pathfinding? I am creating a distance to river texture. I am using the Jump Flood Alghorithm in a compute shader to do this using simple distance() and it works well. See code below. I want to augment this by adding blockers walls so raw distance to seed might be blocked by pixels inbetween. I need to adapt it to a more pathfinding alghorithm. Is this possible to do with JFA? Or do I need some other solution? cbuffer JFAConstants register( CBUFFER REGISTER EXTRA ) int2 gSampleOffset RWTexture2D lt uint2 gt gJumpFloodRiverMap register( UAV REGISTER 0 ) void UpdateClosest( inout int2 currentValue, int2 currentTexcoord, int2 jumpTexcoord ) int2 jumpValue gJumpFloodRiverMap jumpTexcoord if ( IsZero( jumpValue ) ) return float jumpDistance distance( (float2)currentTexcoord, (float2)jumpValue ) if ( IsZero( currentValue ) ) gJumpFloodRiverMap currentTexcoord jumpValue currentValue jumpValue return float currentDistance distance( (float2)currentTexcoord, (float2)currentValue ) if ( jumpDistance lt currentDistance ) gJumpFloodRiverMap currentTexcoord jumpValue currentValue jumpValue numthreads(TERRAIN NORMAL THREADS AXIS, TERRAIN NORMAL THREADS AXIS, 1) void cs main(uint3 groupID SV GroupID, uint3 dispatchTID SV DispatchThreadID, uint3 groupTID SV GroupThreadID, uint groupIndex SV GroupIndex) int2 texCoord dispatchTID.xy int2 currentValue gJumpFloodRiverMap texCoord int2 texCoordT texCoord int2( 0, gSampleOffset.y ) int2 texCoordTR texCoord gSampleOffset int2 texCoordR texCoord int2( gSampleOffset.x, 0 ) int2 texCoordBR texCoord int2( gSampleOffset.x, gSampleOffset.y ) int2 texCoordB texCoord int2( 0, gSampleOffset.y ) int2 texCoordBL texCoord gSampleOffset int2 texCoordL texCoord int2( gSampleOffset.x, 0 ) int2 texCoordTL texCoord int2( gSampleOffset.x, gSampleOffset.y ) UpdateClosest( currentValue, texCoord, texCoordT ) UpdateClosest( currentValue, texCoord, texCoordTR ) UpdateClosest( currentValue, texCoord, texCoordR ) UpdateClosest( currentValue, texCoord, texCoordBR ) UpdateClosest( currentValue, texCoord, texCoordB ) UpdateClosest( currentValue, texCoord, texCoordBL ) UpdateClosest( currentValue, texCoord, texCoordL ) UpdateClosest( currentValue, texCoord, texCoordTL )


What is an efficient way to manage uniforms in a game? Most engines on the market have their drawbacks and it's difficult to find a simple light weight one that's open source and doesn't have to put you through a rather complex learning process. Writing one is a difficult task on its own, but it might not be a bad idea if what you want that engine to do is to support a specific kind of games (e.g. 2.5 D games on mobile devices). So, in search for a good game engine architecture, I've found a few logistical issues. Consider this scenario Objects Each object is comprised of two principle structures of render information a model (geometry mainly) and a material (that tells the object what textures and what shaders to use). Of course, it is natural to allow an object to switch its material definition on the fly. But a material encapsulates the shaders, so these drag along with them some slots for uniforms and vertex attributes. Since an uniform, for example, can be object specific (color, specular exponent, etc.) global superglobal (lights, weather conditions fog wind,etc.) or specific to a group of objects (they all have, let's say, a reflectivity factor) then it means that it's wrong to put them in either the object's property region or in the material's property region. It's clear that both uniforms and attributes are always declared in the shader sections of a material, but where their values come from is an enigma in the frames of a pretty general rendering engine. You have to allow for the existence of numerous types (by semnatics!) of uniforms position, colour, bone matrices, indices, lighting parameters, etc. The big question now how would you suggest to organize and manage uniforms? (especially the information flow they're declared by shaders, but their values are supplied by apparently different type of entities some renderable, some more abstract, being themselves controllers or managers).


One Giant Shader VS Many Small Shaders I am building forward rendering engine combined with atlas shadow map technique. My goal is to build an engine that is capable of rendering similar scenes from games such as.. Doom Overwatch So I wonder, do I need to write one giant shader that does all? or do I have many different shaders for each different materials?


Use of the xyY color space? What's the use of the xyY colorspace in games? I'm not sure what's the advantage of using it in shader programming or elsewhere.


What will happen if the argument of mix() or clamp() is above 1 or below 0? There's two magnificent intrisincs mix() in GLSL and clamp() in HLSL, which are used to implement linear interpolation. Let's say we have a variable float v ? where ? can be FLOAT MAX, FLOAT MAX and then we do gl FragColor mix(value1, value2, v) So, the question is does it works the correct way under GL or DirectX? Should I EXPLICITLY normalize the value of v like this gl FragColor mix(value1, value2, clamp(v, 0.0, 1.0))


Make part of albedo transparent I have a shader which creates a circle inside of a plane mesh. I would like to get get rid of the parts around the circle, which are the r and b parts of the ALBEDO but I can't seem to figure out how to do it. The only thing I've managed to find is ALPHA but that changes the transparency of the entire shader and not just parts of it. shader type spatial float circle(vec2 position, float radius, float feather) return smoothstep(radius, radius feather, length(position vec2(0.5))) void fragment() ALBEDO vec3(0, circle(UV vec2(0), 0.5, 0.005), 0) Which currently looks like


Failed to pass uniform in Metal shader modifier I'm trying to write a simple shader able to pass the color to be used for drawing in the fragment shader, through a uniform. I load the shader modifier and pass the uniform let fragmentShaderPath bundle.pathForResource("Cube", ofType "fragment")! let fragmentShader try String(contentsOfFile fragmentShaderPath) let shaderModifiers String String SCNShaderModifierEntryPointFragment fragmentShader cube.geometry?.shaderModifiers shaderModifiers SCNTransaction.begin() cube.geometry?.setValue(NSValue(SCNVector4 SCNVector4Make(0.0,1.0,0.0,1.0)), forKey "myColor") SCNTransaction.commit() And this is my fragment shader modifier code include lt metal stdlib gt using namespace metal float4 myColor output.color myColor But nothing happens the object is drawn as black. If I try declaring myColor as a uniform, I get an error


How would one construct a realistic "infrared vision" effect? How would you go about constructing a realistic infrared vision effect with shaders? By realistic I mean one that looks realistic, like this example. I have an idea about making a texture to determine how much heat a material emits and then determine by using the dot product of normal and view vector how much of that heat reaches the viewer but I'm not even sure that this is how thermal vision even works so I wanted to check if there's a better approach before starting to implement something that might be entirely wrong.


Strange result, when changing variable name I have no idea, what is going on. The mat4 xxx is the cause. Renaming it to "bones" "bone transfromations" etc. won't work it gives me an error. Renaming it to "test" works perfectly fine... This is my GLSL code version 400 core data from VBO in vec3 position in vec2 texture coordinates in vec3 normal bone data in int bone pointer in float bone intensity vertex color output out vec4 color texture coordinates out vec2 pass texcoords out vec2 texCoord0 normal out vec3 surface normal vector pointing towards the light out vec3 to light vector position, rotation, scale uniform mat4 transformationMatrix perspective projection uniform mat4 projectionMatrix TODO material color uniform vec3 in color camera viewmatrix uniform mat4 viewMatrix lights uniform vec3 lightPosition uniform vec3 lightColor skeleton data uniform mat4 xxx void main() mat4 total transform xxx transformationMatrix vec4 worldPosition worldPosition total transform (vec4(position, 1)) vec4 pos projectionMatrix viewMatrix worldPosition gl Position pos Texture pass texcoords texture coordinates light surface normal (total transform vec4(normal, 0)).xyz to light vector lightPosition worldPosition.xyz textures texCoord0 texture coordinates


Specular intensity of non metals(plastics) in metalness pbs workflow The specular color in metalness roughness workflow is usually defined as following float3 specColor lerp(0.03f, albedoColor, metallic) The Cook Torrance BRDF is given with the following formula The final color will be Ci (diffColor (n.l) Ks specColor cook) My question is won't specular be too dim for non metals? Cook Torrance term will be multiplied by 0.03 in case of dielectrics this will make the specular component virtually non existent. This doesn't seem realistic to me, because smooth plastic reflects a lot of light, almost as much as metals What am I missing?


Recreating this flat shaded look I'll keep it short. How does one achieve the effect depicted in the image below? Is it feasible to do in realtime? It looks deceptively simple, but it probably isn't. Are there any keywords I can search for to get more information about programming the shaders to achieve this look? Thanks.


How to determine vertex index using Shader Model 3 or lower? I need something like SV VertexId (added in Shader Model 4) in HLSL shader to determine which vertex is currently handled. Unfortunatelly, I can compile only vs 3 0 or lower. The objective is to change position of one specific vertex using HLSL. I can't edit the mesh and can't pass any data from game engine, my capabilities are limited by HLSL shader. Shader is writing only for one mesh (humain face), I need to change it's shape a bit (for example, close an eye or make it smiling). I already tried to locate vertex by TEXCOORD, but had no idea how to separate it from other triangles verticles connected to it (placed at the same point where many triangles are met). if ( VS.TC 0 gt 0.8828125 amp amp VS.TC 1 gt 0.6328125 amp amp VS.TC 1 lt 0.671875 ) Upper lip center VS.Position VS.Normal uUpLip Could you, please, give me any advice how to identify move only one specific verticle in HLSL? I need something like moving verticle in Blender's Edit Mode (wytn neighbour triangles are still connected in one point), but my attempt with TEXTCOORD makes them moving in different directions Thanks


GLSL Editor and Debugger for MacOSX with ES2 support is there a GLSL editor for the mac? I need it for iOS OpenGLES2 shader. How do you best debug shader? Regards


Low level GPU code and Shader Compilation Bear with me, because I will raise several questions at once. I still feel, though, that overall this can be treated as one question that may be answered succinctly. I recently dove into solidifying my understanding of the assembly language, low level memory operations, CPU structure, and program optimizations. This also sparked my interest in how higher level shading languages, GLSL and HLSL in particular, are compiled and optimized, as well as what formats they are reduced to before machine code is generated (assuming they are not converted directly into machine code). After a bit of research into this, the best resource I've found is this presentation from ATI about the compilation of and optimizations for HLSL. I also found sample ARB assembly code. This sort of addressed my original curiosity, but it raised several other questions. The assembler code in the ATI presentation seems like it contains instructions specifically targeted for the GPU, but is this merely a hypothetical example created for the purpose of conceptual understanding, or is this code really generated during shader compilation? If so, is it possible to inspect it, or even write it in place of the higher level syntax? My initial searches for an answer to the last question tell me that this may be disallowed, but I have not dug too deep yet. Also, along the same lines, are GLSL shader programs compiled into ARB assembly code before machine code is generated, and is it possible to write direct ARB assembly? Lastly, and perhaps what I am most interested in finding out are there comprehensive resources on shader compilation and low level GPU code? I have been unable to find any thus far. I ask simply because I am curious )


Special relativity shader in GLSL I'm trying to implement a GLSL shader which helps understanding special relativity Lorentz Transformation. Let's take two axis aligned inertial observer O and O' . The observer O' is in motion w.r.t observer O with velocity v (v x,0,0). When described in terms of O' coordinates, an event P' (x',y',z',ct') has transformed coordinates (x,y,z,ct) L (x',y',z',ct') where L is a 4x4 matrix called Lorentz transformation which helps us writing the coordinates of event P' in O coordinates. (for details look http en.wikipedia.org wiki Lorentz transformation Boost in the x direction) I've wrote down a first preliminary vertex shader that apply the Lorentz transformation given the velocity to every vertex, but I can't get the transformation to work correctly. vec3 beta vec3(0.5,0.0,0.0) float b2 (beta.x beta.x beta.y beta.y beta.z beta.z ) 1E 12 float g 1.0 (sqrt(abs(1.0 b2)) 1E 12) Lorentz factor (boost) float q (g 1.0) b2 http en.wikipedia.org wiki Lorentz transformation Matrix forms vec3 tmpVertex (gl ModelViewMatrix gl Vertex).xyz float w gl Vertex.w mat4 lorentzTransformation mat4( 1.0 beta.x beta.x q , beta.x beta.y q , beta.x beta.z q , beta.x g , beta.y beta.x q , 1.0 beta.y beta.y q , beta.y beta.z q , beta.y g , beta.z beta.x q , beta.z beta.y q , 1.0 beta.z beta.z q , beta.z g , beta.x g , beta.y g , beta.z g , g ) vec4 vertex2 (lorentzTransformation) vec4(tmpVertex,1.0) gl Position gl ProjectionMatrix (vec4(vertex2.xyz,1.0) ) This shader should apply to every vertex and perform the non linear Lorentz transformation, but the transformation it performs is clearly different from what I'd expect (in this case a length contraction on x axis). Has somebody already worked on special relativity shader for 3D videogame?


How does the GPU know how to form triangles for a given mesh? I have just begun learning shader programing. What I learned is that the rasteriser groups three vertices to form a triangle for doing further operations. If that's true how does the rasteriser determines appropriate vertices which form a triangle in the mesh geometry? Is it the 3D software which saves geometry in the proper order in model file like .3ds or .obj, .x or is it the GPU which internally triangulates the geometry irrespective of the order the vertices are passed?


How to draw a Bezier line with shaders? I found a shader code to draw a filled Quadratic Bezier in https developer.nvidia.com gpugems GPUGems3 gpugems3 ch25.html How can I use something similar to draw a Bezier line that follows the same path?


Is there a way to make the boundary between materials wavy? I have a sea trading game that I'm working on developing. Right now, my world looks like this There are 4 different "biomes", with more to be added. Internally, this is a large mesh which has 4 different types of materials added to it, to make it work. Each region has a material associated with it. The problem that I'm trying to overcome is to make it look less squary, I believe the process is known as bitmasking. The traditional way to do so I believe is to use images to show the boundary between each one, having one for each possible curve. That doesn't work with my current mesh architecture so far as I can tell. What I'm wondering is if there is a way to make the edges of the mesh to be curvy instead of straight lines. I assume it would have to be a shader of some kind, but my mind isn't quite figuring out the specifics of how to make it work. Any tips? Thanks!


ShaderBytecode Compiler one technique multiple passes I have an effect code with a basic structure like technique TechniqueName pass FirstPass Profile fx 4 0 VertexShader RenderFirstVS GeometryShader null PixelShader RenderFirstPS pass SecondPass Profile fx 4 0 VetrexShader RenderSecondVS GeometryShader null PixelShader RenderSecondPS pass ThirdPass Profile fx 4 0 VertexShader RenderThirdVS GeometryShader null PixelShader RenderThirdPS Now I tried to compile this with using (BinaryReader reader new BinaryReader(stream)) CompilationResult result ShaderBytecode.Compile(reader.ReadBytes((int)stream.Length), "fx 4 0") if (result.HasErrors) throw new Exception(result.Message, new Exception(result.ResultCode.ToString())) Data result.Bytecode.Data stream is new MemoryStream(Encoding.Default.GetBytes(effectContent)). The Data Property (byte ) is about 1 KiB large but if I try to load it via context.InputAssembler.InputLayout new InputLayout(device, effect.Data, someElements) it crashes with following exception D3D11 ERROR ID3D11Device CreateInputLayout Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. STATE CREATION ERROR 161 CREATEINPUTLAYOUT UNPARSEABLEINPUTSIGNATURE Any idea how I can fix this or why the error is thrown? I do not want to use multiple shaders because I reuse many parameters I do not want to reassign in a deferred shading setup.


Drawing a deferred decal when the camera clips its bounding geometry I have a building grid effect that I decal onto my terrain using a cube that moves to follow the cursor. You can see if the camera gets too close to the cube, it gets clipped by the camera's near plane See the clipping just starting here I'd like to find a solution to this as the camera may be this low to the ground or lower upwards of 50 of the time during gameplay. (the rest of the time you would use the view from above, as illustrated by the clip I provided). Is there any way to solve this problem? I'd like to correctly render the cube's shader despite while clipping with the camera. is this possible and how? . . . EDIT amp UPDATE I'm implementing camera to cubemesh clipping detection and already having issues public class Grid MonoBehaviour region Header( quot First point to Camera Controller quot ) SerializeField public CameraController CameraController MeshRenderer constructionGrid private Camera cam private void Start() cam GameObject.FindGameObjectWithTag( quot MainCamera quot ).GetComponent lt UnityEngine.Camera gt () constructionGrid GameObject.FindGameObjectWithTag( quot GridViewer quot ).GetComponent lt MeshRenderer gt () void Update() Plane frustumPlanes GeometryUtility.CalculateFrustumPlanes(cam) if (GeometryUtility.TestPlanesAABB(frustumPlanes, constructionGrid.bounds)) Debug.Log( quot Clipping quot ) else Debug.Log( quot Not quot ) This always logs quot Cliping quot whether clipping or not. If I add a meshCollider to the shadercube the same happens but the shadercube jitters all over the place. I can't figure out clipping detection.


What is the math behind the light effect in krakatoa? I'd like to know the math behind the light effect in krakatoa (click here for an example). Light source is traveling with particles, but how is shading done? Is it something simple, like Phong shading? Is it possible to implement such effect in real time on GPU?


DirectX11 how to use textures and samplers in slots in shaders I have a system to render many objects, but I don t know how to render more tan one object with same shader, let me explain I have a sphere and a cylinder, but both objects can be rendered by different shaders, example Shader1 Shader to render object using 1 texture Shader2 Shader to render object using 2 textures Both objects need to coexist in space, so if I want to render sphere with shader 1 and I use shader1 resources context gt PSSetShaderResources(0, 1, amp texture) context gt PSSetSamplers(0, 1, amp sampler) shader2 resources context gt PSSetShaderResources(1, 1, amp texture) context gt PSSetSamplers(1, 1, amp sampler) context gt PSSetShaderResources(2, 1, amp texture) context gt PSSetSamplers(2, 1, amp sampler) in Shader1 the resources are references like this Texture2D colorTexture register(t0) SamplerState sampler register(s0) And in Shader2 the resources are references like this Texture2D colorTexture register(t1) SamplerState sampler register(s1) Texture2D colorTexture register(t2) SamplerState sampler register(s2) But what if I need to use shader1 resource s in shader2???? How to manage those resources or do I need to replicate shader2 with shader1 registers?? this is the simplest example, this is part of a very much complex system with many many shaders and many textures, but I don t know in what slot will be setted the resources, this can be absolutely generic, example, slot 5 will be used for texture 1 of shader2 It is possible to render many objects with minimal change of shaders, but the resources could be updated at any time.. I m using directX11.


How many active shaders at one frame in the game should I typically use? 5 or more like 100? How many shaders are usually active, at the same time in one scene, in modern games? I know that multiple shaders are being used, with the games switching between them in each frame, and it's common to draw objects via the shader Draw all objects with shader one Change from shader one to shader two Draw all objects with shader two Still, I know it's not as simple, especially with effects like a glow effect for whole scene, render to texture, etc., but I guess we can assume it works that way most of the time, right? The "group by shader" approach is good, because switching shaders is an expensive operation. From one side, you cannot have too many shaders, because you want to render the scene fast. On the other hand, you need many different shaders (or uber shader with branches quite similar) for skin, metal, water etc. How many (and which) different shaders would the theoretical, modern, third person, 3D detective game for PC (DirectX 11, if it matters) use? It would be 5, 20 or more like 100 active shaders, counting only active, at some "frame X"? I know it's not one number, but I wonder what scale and factors are important, in consideration for a PC game. In my sample game, I would use about 9 11 per frame (count it as different, small shaders or one uber shader doesn't matter now) Skin shader Eye shader (not too much? but they are different) Metal shader Ground shader Snow rain shader (if required) Water shader (if the water exists in scene) Glow shader (only when some special effects are involved) Light emiter shader (street lamps etc.) Standard shader (for all other, just standard shading) Standard shader with normal maps 2D shader (for GUI etc.) Is it "much" or "not many"? Did I forget about some important shaders that I would need?


How do I mask a height based fog? I've been trying to implement a 3D (with the Y axis being utilized) fog of war system similar to what XCOM uses. There is only one hint that really seems to nail it, but I can't read the actual function that was in place. http etiennecarrier.com zombie tycoon 2 fog of war shader The key difference here is that I'm also trying to apply this to a multi leveled building. So the question is... How do you go about implementing a height based fog shader, with a masking texture to prevent it from drawing in certain world spaces.


Normal Matrix in plain English I'm into shader language with Webgl and GLSL. I've seen some tutorial about normal matrix and I don't really understand it. I mean, I think I'm ok with the math such as modelViewMatrix mat4.multiply(camera.view, modelMatrix) inverseModelViewMatrix mat4.invert(this.modelViewMatrix) normalMatrix mat3.fromMat4(inverseModelViewMatrix) normalMatrix mat3.transpose(this.normalMatrix) But why do I need it? Where can I find a case where I can see the difference between using it and not using it? Ot when do I don't need it?


What do shaders encompass? I'm researching shaders as I'm thinking about doing them for my final year project at Uni. I've looked at a lot of examples online and I think I get it. It's something that you apply to an object or scene in order to create a desired effect without changing the original object scene, I think. I know that there are different types of shaders but that's the basic goal right? Furthermore, what do shaders encompass? Are weather systems in games shaders? Particle effects? Landslides? I don't know where the line is drawn between animations cinematics and shaders. Also I guess shaders which effect something in the game world, for example, a tower blowing up in BF4. The explosion itself would be shaders but the way the tower effects the world around it would be physics and collisions. Am I right?


What is a Fragment Pipe? I remember someone saying "24 fragment pipes on nVidia 7800" in a presentation. Am I correct in saying that a fragment is the data that can generate a pixel in the frame buffer? Or are fragments the same thing as pixels? I'm getting confused here. What is a fragment pipe?


Making a crosshatching effect in Unity Shader Graphs I'm learning Shader Graph and am trying to experiment with toon shading effects. One thing I'd love to do is make a traditional art styled crosshatching effect either inside shadows or at the edge of shadows. However, I'm lost as to how to do that. I have a sample crosshatch texture I can use as a texture2D but I'm unsure how to use this as an input in shadows and to which nodes to hook it up to. I'm very new to dabbling in shaders so I'd appreciate any tips.


PBR texture conversion Is it possible to convert from specular glossiness to metallic roughness textures for UE4?


How to implement in app Billing in libgdx? I'm trying to implement in app Billing in libgdx game. Does someone have a working example? There is some explanation on developer.android but it's not helpful for libgdx.


Label not properly centered in TextButton I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code m resumeButton new TextButton("resume", skin) m resumeButton.addListener(new ChangeListener() public void changed(ChangeEvent event, Actor actor) m state GameState.RUNNING getGame().getWorld().pauseWorld(false) ) The default TextButtonStyle is defined as "com.badlogic.gdx.scenes.scene2d.ui.TextButton TextButtonStyle" "default" "up" "menu button", "down" "menu button down", "checked" "menu button down", "disabled" "menu button disabled", "font" "font24", "fontColor" "white" The menu button images are simple 240x48 bitmaps saved as 9 patch images. An image can be found here to illustrate the problem https www.dropbox.com s cwuhu5xb9ro5w6m screenshot001.jpg Am I doing something wrong? Or is there a problem with the button images I'm using?


Scene2D set table cell size in percentage of tables s size Is it somehow possible to set Scene2D table cell s size in percentage of the table? I would like to have orientation independent menu, with buttons filling let s say 75 percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using Value table.add(button).width(Value.percentWidth(.75F)) but when value.get(actor) is called inside cell, it is supplied with inner button actor not its container (table). I have also tried to set it in fixed fashion table.add(button).width(Value.percentWidth(.75F).get(table)) This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing. Is there any way to achieve this?


Using the same font with different sizes in libgdx I am using BitmapFonts, LabelStyles and Labels for my texts. I want to resize some labels, so i use this. fontType.scale( .6f) LabelStyle style new LabelStyle(fontType, Color.WHITE) titleLabel new Label("Points", style) titleLabel.setColor(Color.RED) titleLabel.x 260 titleLabel.y 310 but when i want to resize another label, all the labels containing that font resize (I create a new LabelStyle). So i resize the label instead of the font, but that doesnt solve the problem, because it doesnt resize the label, any idea?


LibGDX Camera and viewport initialization in show()? I'm reading the book LibGDX game development by example and the author tends to follow a pattern like public class MyGame extends Game Override public void create() setScreen(new GameScreen(this)) ... public class GameScreen extends ScreenAdapter private Viewport viewport private Camera camera private final MyGame myGame code omitted for brevity public GameScreen(MyGame myGame) this.myGame myGame Override public void show() camera new OrthographicCamera() camera.position.set(WORLD WIDTH 2, WORLD HEIGHT 2, 0) camera.update() viewport new FitViewport(WORLD WIDTH, WORLD HEIGHT, camera) ... It seems to me that creating a new camera and viewport in the show() method is not correct, as it would create new objects every time the screen becomes active (eg when the game has multiple screen and the user can switch between them). So my questions Am I correct in my reasoning? Should the camera and the viewport be created in the GameScreen class constructor? Would it be possible advisable to have just a single camera and viewport shared by all screens?


Box2D rotate and set position to a static body with another origin I try to rotate a static body of a PolygonShape, from another origin, and set the position regarding this new origin. Why ? Because I create bodies from TiledMapEditor object. And origins of objects in this editor are in the left upper corner. Regarding the documentation, I can set origin using the setAsBox method. But then when I set the position, the body is not where it is supposed to be. (an offset is apply between the current position and the expected position) I assume that the origin is used for the rotation, but not the position. How can I set the position from another origin, and rotating from this same origin ? (the upper left corner and not the center of the shape) My attempt val rotation 45f rotation angle (in degree) val shape PolygonShape() shape.setAsBox(rectangle.width 0.5f, half width rectangle.height 0.5f, half height Vector2(0f, rectangle.height), new origin rotation MathUtils.degreesToRadians) angle to radians val bodyDef BodyDef() bodyDef.type BodyDef.BodyType.StaticBody bodyDef.position.set(rectangle.x, rectangle.y) set the position Regards


Box2D meters and pixels I am confused about pixels and meters in Box2D. I know that Box2D work only in mters so I need SCALING FACTOR. How big I need it? For example I want that from my mouse coordinates position X and Y for example(1527, 30) throw an Box2D object how I need to do that? if my scaling factor is private final static float PPM 1 100f so my x 152,7, y 3meters Here is my code private void setBox2DFigures() world new World(new Vector2(0, 9.81f), true) rend new Box2DDebugRenderer() cam new OrthographicCamera() Camera body new BodyDef() bodyPhysics new FixtureDef() CircleShape c new CircleShape() body.type BodyType.DynamicBody c new CircleShape() c.setRadius(20 PPM) c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) bodyPhysics.shape c world.createBody(body).createFixture(bodyPhysics) and here in a draw method I want to coin position set to my mouse position public void draw() c.setPosition(new Vector2(Gdx.input.getX() PPM, Gdx.input.getY() PPM)) mouse coordinates PPM rend.render(world, cam.combined) But I don't see anything in my screen. Whats wrong? How I need to choose My scaling factor(PPM)? here's my main public class DesktopLauncher public static void main (String arg) LwjglApplicationConfiguration cfg new LwjglApplicationConfiguration() cfg.title "Catch Me!" cfg.width 1800 1800 cfg.height 900 900 new LwjglApplication(new Game(), cfg)


Which is the best method implementing a background scrolling for game in libgdx? My question is very simple I am new to libgdx development, which is the best approach implementing a background that is to make the background move in y direction 1)My First approach is drawing the background image 10 times towards positive y direction using camera.translate(x,y) function to move camera from bottom to top 2)second approach is to make the camera still while making the background scroll ie drawing the background frame by frame updating the position each time Can you please suggest which is the best approach?


How can I make my button do something when clicked? I'm trying to create a game with libGDX in Android Studio, and I am struggling with my code to add a command to the program to do something when I press the button. I have added an ImageButton, but now I struggle to get it to do something when I click on it. Here's my code bplay.addListener( new ClickListener() public void clicked(InputEvent event, float x, float y) batch.begin() batch.draw( splash, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ) batch.end() )


Hand cards auto arrangement I'm making a card game with libgdx scene2d and what I'm trying to achieve is auto arrange the cards in a way the all fit the screen. This is what it looks now when the hand is full I have done that using a horizontalGroup and puting a 1 3 cardWidth space between the cards. I want the cards to spread evenly when some are removed. I think I have to change the space between the cards whenever a card is removed or added but I don't know how much. This is my code CardActor cards new CardActor 14 HorizontalGroup hand new HorizontalGroup() int width Gdx.graphics.getWidth() 10 int height width 2 hand.setBounds(width 2, height 4, stage.getWidth() width, height) hand.space(width 3f) hand.align(Align.bottom Align.center) for (int i 0 i lt cards.length i ) cards i new CardActor(new Card(MathUtils.random(3), MathUtils.random(3, 10))) hand.addActor(cards i ) stage.addActor(hand) And this is the CardActor public class CardActor extends ImageButton public CardActor(Card card) super(new TextureRegionDrawable(CardTextures .getTexture(card.getType(), card.getRank()))) int width Gdx.graphics.getWidth() 10 int height width 2 getImageCell().prefSize(width, height) setBounds(getX(), getY(), getWidth(), getHeight()) addListener(new ChangeListener() Override public void changed(ChangeEvent event, Actor actor) onSelected() )


Deploying GWT application LibGDX and TextureAtlas problem I encountered with a little problem. After GWT (and LibGDX) deployment I got an error GwtApplication exception Couldn't load image ' images objects.png', file does not exist Couldn't load image ' images objects.png', file does not exist This error throws when TextureAtlas tries to load the image from settings.text file images objects.png format RGBA8888 filter Nearest,Nearest repeat none hills rotate false xy 0, 0 size 1024, 146 orig 1024, 146 offset 0, 0 index 1 I tried to use any type of path " assets images object.png" " clutchkick assets images object.png" " public html clutchkick assets images object.png" and so on.. Any suggestions? By the way there are no any problems on android or desktop deployment. EDIT The same problem occurs when trying to load a Tmx map.


How do I find the shape of Tiled's circles or ellipses in libGDX? I created a level in the 'Tiled Map Editor' and loaded it into my libGDX game. I can easily transform almost all objects into Box2D objects (although this problem is not Box2D specific), but I have trouble with ellipses. Tiled seems to only create ellipse objects, without a special case for circles. I'd be happy with just circles if they existed in Tiled. However, even the EllipseMapObject I load in libGDX only has an x,y position. I don't see any information about area or vertices. Did I miss something? How can I create circle or ellipse objects in Tiled and load them into libGDX with right dimensions? Tiled version 0.10.1, libGDX version 1.4.1


Act on Right Mouse Button click on Button I want to be able to listen for a right mouse click onto a TextButton. Is this possible without removing the default ClickListener of the TextButton? If yes, how? Or should I use a different listener?


When should one use LibGDX's FrameBuffer and when SpriteCache? In my game I have some graphics that I want to draw once and only redraw whenever something is changed by the player. Now, I'm wondering, whether I should use the FrameBuffer or the SpriteCache class. I know that a framebuffer is much more general concept and also works for 3D, while a SpriteCache is only for 2D. However it seems to me that they would both make sense in my use case, so I'm wondering.. What are the differences, drawbacks and advantages of using one over the other?


libgdx game not disposing My game does not exit entirely even after calling dispose() method. It loads a black screen when I launch it for the second time and works well if I kill the game manually and restart it. I get an error that says buffer not allocated with newUnsafeByteBuffer or already disposed when I try to dispose off the SpriteBatch object. This is were I suspect the problem to be. But not able to fix it entirely. Please help! Here is how I have built it (I have put the sample code here just to show you guys that there are no visible loop backs in dispose function, please correct me if I'm wrong) In game screen, public void dispose() AssetLoader.dispose() render.dispose() Gdx.app.exit() Under class AssetLoader public void dispose() Texture.dispose() sound.dispose() Under game render class public void dispose() spritebatch.dispose() throws an error when I GameScreen.dispose is called font.dispose() shaperender.dispose() I believe that my spritebatch isn't disposing which is causing the black screen but I cannot find a way to dispose it off successfully. Any help would be greatly appreciated.


LibGDX , Scale button with animation when it is pressed I am developing game using LibGDX . I want to create beautiful menu and to scale buttons when they are pressed but not in this way , when it is pressed scale it 1.5f , I want to scale it with animation . I am using imagebuttons .


LibGDX On the "slowness" of loading assets Many tutorials I've seen put the loading of assets via AssetManager in a dedicated screen which displays some progress bar or image while the loading happens in background. Each "real" screen then gets the resources it needs from the asset manager, typically in the constructor, eg public class GameScreen extends ScreenAdapter private MyGame game private Texture t1 private Sound s1 public GameScreen(MyGame game) this.game game AssetManager am game.getAssetManager() t1 am.get("....", Texture.class) s1 am.get("....", Sound.class) use t1 and s1 Now another source I've seen takes this concept a bit further and also does the actual get()s in the asset loading class, so screens don't have to do them themselves, eg in the Loader class public AssetManager am new AssetManager() public Texture t1 public Sound s1 ... am.load(...) am.load(...) am.load(...) finishLoading() or update().... ... t1 am.get(...) s1 am.get(...) ... in the screen class t1 game.am.t1 s1 game.am.s1 ... use t1 and s1 Now my question is is this good practice? What's the expensive part of loading assets, the AssetManager's .load()s or also the .get()s? (I thought it was only the .load()s.) Is removing the get()s from the screens really a performance gain?


Deleting Cleaning Screen Objects with all child objects in libGDX For my game, Im using libGDX Ashley (ECS) Box2D Ive got a lot of screens but for simplification MainMenuScreen and InGameScreen. In InGameScreen Im init the ECS (Ashley) and create a lot of entities. Some have PhysicsComponent. The PhysicsSystem will catch them and call Box2D to spawn some objects based on the parameters within the PhysicsComponents. So far so good. Now, when the player dyes, I run setScreen(new MainMenuScreen()) from my "Main" Class (MyGame.java). the game starts and MyGame loading at first the MainMenuScreen than the InGameScreen will get loaded (when player presses a key) than the player dyes MyGame recognized it and loading again (throu calling setScreen(...)) the MainMenuScreen When Player press key MyGame loading another round (setScreen(new InGameScreen)) I guess I have to do something like a complete clean up between switching screens. But how should I implement this? Just "deleting" the old InGameScreen Object shouldent be enought, right? Do I have to use the dispose() Method? Is it enough to instantiate everything new (in the init from InGameScreen) since it will instantiate all child object new for its own like Box2DWorld world new World()


How do I scale and rotate around different points in Libgdx? I'm using a SpriteBatcher to rotate and scale a TextureRegion in libGDX. I'd like to rotate the texture around an origin outside of the region, but have the texture scaled around the region's center. As far as I'm aware, this has to be performed in one action in the SpriteBatcher.draw() method. The region is scaled to the correct size, but scaled away from the origin. I could compensate by adjusting the origin location, but is there a better method?


Google Play Services Message Handling with Libgdx I'm looking for some idea of how to handle Reliable Messages in Google Play Services with libGDX. So far I've been using it like this I was waiting for message with OnRealTimeMessageReceivedListener, setting an outside byte array to the message received, changing a flag that suggests that new message arrived to true, getting that message in my libGDX class using methods from interface, setting newMessage flag again to false, handling message, and so again waiting for new one private OnRealTimeMessageReceivedListener mMessageRecievedHandler new OnRealTimeMessageReceivedListener() Override public void onRealTimeMessageReceived( NonNull RealTimeMessage realTimeMessage) Handle received message here byte message realTimeMessage.getMessageData() byte tbye message ByteBuffer bb ByteBuffer.wrap(tbye) if(bb.getFloat() 1884) Log.d("MESSAGETEST", "Message received in anL " debugIntL) debugIntL byteArray message newMessageFlag true Override public boolean getNewMessageFlag() return newMessageFlag Override public byte getMessage() newMessageFlag false return byteArray Libgdx class Override public void render (float delta) ... checkForNewMessage() ... private void checkForNewMessage() if(game.customHandler.getNewMessageFlag()) handleMessage() handling message here private void handleMessage() byte message game.customHandler.getMessage() ByteBuffer bb ByteBuffer.wrap(message) float typeOfMessage bb.getFloat() if(typeOfMessage NEW UNIT MESSAGE) Gdx.app.log("MESSAGETEST", "Message received in gdx " debugInt) debugInt ... But the result is, when uncommenting the code in OnRealTimeMessageReceivedListener and adding similar log to my handleMessage() that some messages are skipped between receiving it in listener and checking for new in my libGDX class, I don't know why, maybe because some render calls take longer to do everything inside and it skips through one check call when there's significant number of those in small amount of time On the image you can see that first log is from OnRealTimeMessageReceivedListener, which receives every message, but the second one is from handleMessage, and at 251 there it wasn't called, so handleMessage just skipped this message and went to the next one. So here's my question, what's good way to handle those messages so that I won't skip any?


TiledMap blocks makes Animation invisible Got it fixed. Thanks to anyone who tried to help me. New Code mapManager.render() spriteBatchForeground.setProjectionMatrix(Main.getGraphicsManager().getAdvCamera().getCamera().combined) spriteBatchForeground.begin() worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() I just implemented my animations but now I discovered a problem with my TiledMap. Here some Screenshots Code for 1 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Code for 2 spriteBatchForeground.begin() mapManager.render() spriteBatchForeground.setProjectionMatrix( Main.getGraphicsManager().getAdvCamera().getCamera().combined ) worldManager.render(delta, spriteBatchForeground) animationManager.render(spriteBatchForeground) particleEffectManager.render(delta, spriteBatchForeground) spriteBatchForeground.end() Issue The animation isn't drawing when I enable the drawing for the tiledmap. I have no idea why this happens...


Conditionally use java or android classes I'm using bezier curves in my libgdx project. I was testing the desktop version using java.awt.geom with GeneralPath but when I went to test on android, it raised an error saying that I can't import java.awt. Android have corresponding classes for GeneralPath, Point2D etc so my question is how can I use those classes in their respectives environments?


Using Delta for a stopwatch, delta too fast than real time seconds I search for methods to create a stopwatch on libgdx and came across with this public void trigger(float delta) playTime delta playTimeRounded ((double)Math.round(playTime 100) 100) Gdx.app.log("deltaTime", delta "") But its not accurate and its much faster. How can i create an accurate stopwatch?


Statemachine to behaviour tree? Background I was able to convert simple statemachines like this... Into a BT looking like this (Notation describtion)... root sequence After another playAnimation name idle sequence walks? Breaks current sequence if false playAnimation name walk sequence runs? playAnimation name run Goal But how do we convert more complex multi layered animation states into a behaviour tree ? How would such a BT look like ? The difficult parts here are transistions between the different states, something i couldnt solve in an BT. Question Is it possible to convert every statemachine into a behaviour tree ? What does the theory says and how does it look like in practice ?


Correct way of texture mapping a 2D mesh in libgdx this is a question regarding the libGDX framework. I have managed to UV map a texture to vertices (in 2D) but have come across a few problems that I think might be caused by incorrect order of vertices. In the first two pictures, you can see a rendering produced by the code bits below (without blending enabled). It seems fine at first, but you can clearly notice that the lower triangle seems to have a rough transition. Is there an easy way to prevent this (without writing too much low level stuff) or is this an expected limitation of this approach? The second problem occurs with the same code but with blending turned on. In the fragment shader, you can see that I adjust the alpha level of each pixel in the region, but with this mesh, it produces a rather weird and distorted image in the right triangle area. Here's the code Shaders Vertex shader attribute vec4 a position attribute vec4 a color attribute vec2 a texCoord0 uniform mat4 u projTrans varying vec4 v color varying vec2 v texCoords void main() v color vec4(1, 1, 1, 1) v texCoords a texCoord0 gl Position u projTrans a position Fragment shader ifdef GL ES precision mediump float endif varying vec4 v color varying vec2 v texCoords uniform sampler2D u texture void main() gl FragColor v color texture2D(u texture, v texCoords) vec4(0, 0, 0, 0.50) Mesh Mesh m new Mesh(true, 5, 0, new VertexAttribute(Usage.Position, 2, "a position"), x,y new VertexAttribute(Usage.TextureCoordinates,2,"a texCoord" 0)) u,v m.setVertices(new float 20f, 360f, 0f,0f, upper left 60f, 20f, 0f, 1f, lower left 180f,20f,1f,1f, lower right 220f, 360f, 1f, 0f, upper right 20f, 360f, 0f, 0f ) upper left (closure) Render Gdx.gl.glEnable(GL20.GL BLEND) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) shaderProgram mesh.begin() shaderProgram mesh.setUniformMatrix("u projTrans", camera.combined) texture.bind() m.render(shaderProgram mesh, GL20.GL TRIANGLE STRIP, 0, 5) shaderProgram mesh.end()


LibGDX ImageButton resizeing How can I resize ImageButton ? It show very big on screen . How I know it is an Actor and it is not resizing automatically . I can t find the method for resizing it. Any ideas?


LibGdx How to check if VSync is enabled I am just about finished my options screen, the only thing I need is some way of detecting if Vsync is enabled or not. I'm using LibGdx 1.5. I have tried to find an access to wglSwapIntervals, but haven't found one. Libgdxs API only allows a setVsync options that accepts a Boolean. If anyone could shed some light on this, it would be greatly appreciated!


Label not properly centered in TextButton I'm using LibGDX v1.1.0 and I see that the label of a TextButton is not properly centered. I have the following code m resumeButton new TextButton("resume", skin) m resumeButton.addListener(new ChangeListener() public void changed(ChangeEvent event, Actor actor) m state GameState.RUNNING getGame().getWorld().pauseWorld(false) ) The default TextButtonStyle is defined as "com.badlogic.gdx.scenes.scene2d.ui.TextButton TextButtonStyle" "default" "up" "menu button", "down" "menu button down", "checked" "menu button down", "disabled" "menu button disabled", "font" "font24", "fontColor" "white" The menu button images are simple 240x48 bitmaps saved as 9 patch images. An image can be found here to illustrate the problem https www.dropbox.com s cwuhu5xb9ro5w6m screenshot001.jpg Am I doing something wrong? Or is there a problem with the button images I'm using?


neon effect to textures libgdx I am working on a live wallpaper with Libgdx . I am wondering if I can give neon glow to my textures , at runtime . Is this possible? If yes can anybody give me any pointers?


How to achieve sprite reflection effect in libgdx I am currently working on an open world game similar to Pokemon using libgdx. I am currently stuck on this effect that I really want to be done before moving to other features of my game. How can I achieve the following water reflection effect? I also want it to shimmer like in this video "Pok mon Sapphire Reflections in the water Episode 4" 3 38


How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer how to properly link an OrthographicCamera to a OrthogonalTiledMapRenderer How do I properly link an OrthographicCamera to a OrthogonalTiledMapRenderer? I have tiled map i'd like render and two stages that have actors on them.. I call render.render() in my screens render method as well as stages.draw() but every i put render.setView(camera) the screen displayed flashes or does other weird things. How do I properly attach a moveable camera to a tiled map renderer? I render the map first, do game logic and then call draw on the stages. when I call translate on the camera the tiled map zooms way out for some reason? here is my render method public void render(float delta) Gdx.gl.glClearColor(1, 0, 0, 1) Gdx.gl.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) camera.update() renderer.render() gameLogic() backStage.act() acts are called but do nothing frontStage.act() frontStage.draw() backStage.draw() here is where the camera and renderer get created public void addMap(GameMap map) this.map map maps.add(map) renderer new OrthogonalTiledMapRenderer(map.getTiledMap(), 1 20f) camera new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) float aspect Gdx.graphics.getWidth() Gdx.graphics.getHeight() camera.setToOrtho(false, 20 aspect, 20 aspect) renderer.setView(camera) frontStage new Stage() backStage new Stage() xSize map.getXSize() ySize map.getYSize() Gdx.input.setInputProcessor(this)


LibGDX camera position shifted on movement I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom x) the camera is shifted when the player moves (the camera follows the player) Shifted View Normal View That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves. Here's some of my code Render Loop (excerpt) Override public void render(float delta) set the camera position to player's position cam.position.set(player body.getWorldCenter().x, player body.getWorldCenter().y, 0) cam.update() world.step(Gdx.graphics.getDeltaTime(), 6, 2) world.clearForces() handleInput() Gdx.gl.glClearColor(.05f, .05f, .05f, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) debugRenderer.render(world, cam.combined) Make the player move if (Gdx.input.isKeyPressed(Keys.W)) player body.setLinearVelocity(transX, transY) player.setMoving(true)