Multiple pipelined game loops I am considering using the following game engine design pattern, but I am unsure if it's a good idea or not Each major task (drawing, physics, logic, networking, disk I O) will have its own isolated thread or subprocess Each of these threads can be put to sleep if it is running too quickly, so as to not consume an excess of CPU resources Threads can only talk to each other through some well defined interface to avoid messy, buggy, thread unsafe conditions from occurring This approach enables parallelism and scalability, but causes a thread safety problem what if one thread is accessing data that another thread is currently processing? We could introduce fine grained locking, but it still can't be guaranteed that the collective states of all of a thread's data objects are coherent. To solve this, collections of objects are maintained inside state objects, and state objects are double buffered. The intent of this is to ensure that other threads only see a valid, coherent set of data. If one thread happens to be processing data that another thread wants to read, then the other thread reads from a buffered state, which is guaranteed not to be written to. However, buffering these states introduces a delay where one thread sees old data from the last cycle of the other thread. Another problem might occur when a reading thread has a slower "tick rate" than a writing thread the writing thread may have flipped the state buffer multiple times, while the reading thread is still processing one "tick" using the same state. However this can be solved using OO references. Pipelining should be achievable using this approach, because the draw thread could be drawing information that entered the pipeline 30 milliseconds ago, while more information is being processed Ultimately, what I'd like to see is completely decoupled processing for all of the tasks in a game, implemented in a way that helps leverage multi core environments, and maybe leaves some future expansion room for scaling the server side of things amongst multiple machines. I am aware that this is probably overkill for most purposes ) What are the criticisms or pitfalls of this approach? Is this the "right" way to do things? Am I thinking about this backwards?


Game Loop design that is speed hack proof I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter? I found this in stackoverflow I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it ref https stackoverflow.com questions 17512906 how does cheatengines speed hack work


Should I bother with SDL WaitEvent? When I wrote my first application in SDL, it looked like this while (!quit) SDL PollEvent( amp event) switch (event) ... But then one time I left my app running while I went to do something else, and when I came back my laptop was boiling hot. I checked the system monitor and one of my cores was maxed out by my program! So I did some research, and now my loop looks like this while (!quit) SDL WaitEvent( amp event) switch (event) ... Great, so now my program doesn't max the CPU. But now I need to introduce rendering, and the problem is, currently this loop runs one iteration per event. If input and other events don't occur, my program won't render the next frame, no matter where the rendering code goes in the loop. So that's no good. I could have threads, but that seems like a lot of extra complexity when I could just do while (!quit) SDL PollEvent( amp event) switch (event) ... SDL Delay(10) This won't melt the CPU, and I can render at about 100 frames per second. My questions are Which approach quot should quot I use? I don't see any reason to not just use (3). What's the point of SDL WaitEvent, if you can't use it the moment you want to do anything other than handle events in your game loop? I assume SDL WaitEvent does something like approach (3) under the hood, so even though ostensibly approach (3) should introduce more latency, in practice it won't. Is this correct? How low should the integer passed to SDL Delay be to get a responsive app?


Exchanging data between custom built hardware and games I have a built my own steering wheel and motion platform that I would like to connect to popular car racing games (e.g. iRacing, Dirt Rally). I need to read data such as the car's acceleration (to send to the motion platform) from these games and send information such as steering wheel's angle to the game. I have written an SDK in C to communicate with my steering will and motion platform. Now I need to interface different games with to that SDK. I searched quite a bit but could not find much information about how this is generally done. Do game developers provide some sort of extension which allows third party hardware developers to communicate with their game? Any guidance from the community is much appreciated. Kam


Should I send the elapsed time to the fixed step update function from my game loop? I am making a basic game loop based on this article. This is the nearly final version double previous getCurrentTime() double lag 0.0 while (true) double current getCurrentTime() double elapsed current previous previous current lag elapsed processInput() while (lag gt MS PER UPDATE) update() lag MS PER UPDATE render() But I think the update function should have elapsed time passed to it so that the game state is calculate based on that. So this should be the correct version double previous getCurrentTime() double lag 0.0 while (true) double current getCurrentTime() double elapsed current previous previous current lag elapsed processInput() while (lag gt MS PER UPDATE) update(elapsed) gt gt gt ?? lag MS PER UPDATE render() Am I right? Because I think a physics engine should always have a delta time to calculate state changes.


Design of a turn based game where actions have side effects I am writing a computer version of the game Dominion. It is a turn based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later. The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine in general, players pass through an "action phase", a "buy phase", and a "clean up phase" (in that order). Based on the answer to the question How to implement turn based game engine?, the state machine is a standard technique for this situation. My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn based Strategy Loop does not go into a level of detail that addresses designs to solve this problem. What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object class whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine.


Turn based Strategy Loop I'm working on a strategy game. It's turn based and card based (think Dominion style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop. What is the "best" way to implement a game loop in such a game? Should I use a simple "while gameActive" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when? Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question.


NodeJS setTimeOut How to run callback before delay time exceeded I'm developing a card game server. I want to do this While server process a turn for players, players have 20 seconds to do something. If players send a request to server within 20 secs, timer will stop and the callback will fire. I'm doing like this self.tables table.id .currentTimer setTimeout(function () callback() , 20 1000) How should I run the callback before delay time exceeded ?


Delta times and frame lag in the game loop Let's say we have a standard gameloop like this, in pseudocode while (true) dt GetDeltaTime() Update(dt) Render() Here Update(dt) either uses a true variable timestep, or it determines how many cycles of a fixed timestep physics loop to execute based on dt. Now say we have the common case where we have mostly constant framerate except for infrequent single frame hiccups, so let's say we have dt values like 1 60, 1 60, 1 60, 1 6, 1 60, 1 60, ... By the time our GetDeltaTime() detects the larger timestep in the fourth frame, we have already rendered and presented the fourth frame! So one frame will already have been rendered with a wrong (too small) timestep no matter what we do. So if we now use the larger dt 1 6 to render the fifth frame, my understanding is that we artificially create a second frame where a wrong timestep is used, this time a too large one. I wonder if this problem is acknowledged anywhere. Wouldn't it be better, say, to use the averaged dt over the previous few frames to combat this? Here are some pictures to illustrate what I mean. I use the example of an object moving along a fixed axis with a constant speed, and using a variable timestepping scheme. The problem is essentially the same with fixed timesteps, though. The plots have time on the x axis, and the object position on the y axis. Let's say the object moving at 1 unit s, and framerate is 1 Hz. This is the ideal situation. Now let's say we have a frame where the time interval is 2 instead of 1. With a classical dt based scheme, we get this So we have one frame where the velocity is perceived too low, and one where it is perceived too high and which corrects for the velocity in the previous frame. What if we instead, say, always use a constant (or very slowly changing) dt? We get this The perceived velocity seems smoother using this approach to me. Of course, the object position is now not the "true" one, but I think humans perceive abrupt changes in velocity more clearly than such small positional offsets. Thoughts? UPDATE At least Ogre can do this http ogre.sourcearchive.com documentation 1.6.4.dfsg1 1 classOgre 1 1Root 1f045bf046a75d65e6ddc71f4ebe0b2c.html So I guess I just got downvoted for people not understanding my question, which is rather frustrating.


What are "frame rate" and "fps?" Can someone give me a detailed explanation about frame rate and fps concepts?


Varying framerate (FPS) In my game loop, I am using fixed time step for physics and interpolation for rendering as suggested on Gaffer on Games Fix Your Timestep! However, when the framerate is varying between 30 60fps during the game, the game looks jumpy. For example, balls suddenly look accelerated when the frame rate increases from 35 to 45 suddenly. Is there a way to make the game look smooth while framerate is varying? Here is my game loop protected void update(float deltaTime) do some pre stuff deltaTimeAccumulator deltaTime deltaTimeAccumulator is a class member holding the accumulated frame time while(deltaTimeAccumulator gt FIXED TIME STEP) world.step(FIXED TIME STEP, 6, 2) perform physics simulation deltaTimeAccumulator FIXED TIME STEP world.step(deltaTime, 6, 2) destroyBodiesScheduledForRemoval() render(deltaTimeAccumulator FIXED TIME STEP) interpolate according to the remaining time Here is the part related to the interpolation (related inner works of render() method) this.prevPosition this.position get previously simulated position this.position body.getPosition() get currently simulated position interpolate Vector2 renderedPosition new Vector2() if (prevPosition ! null) amp amp !isFloatApproximatelyEquals(this.prevPosition.x, this.position.x) amp amp !isFloatApproximatelyEquals(this.prevPosition.y, this.position.y)) renderedPosition.x this.position.x interpolationAlpha this.prevPosition.x (1 interpolationAlpha) renderedPosition.y this.position.y interpolationAlpha this.prevPosition.y (1 interpolationAlpha) else renderedPosition position Draw the object at renderedPosition


LUA Keeping track of game state for a digital card trading game I am building a card game. Let's say it's similar to Magic the Gathering, Hearthstone, etc. The problem I am trying to figure out is how to architect "auras" and how much damage each card takes. Right now I have a deck and I store card data as follows. I've made up names for the types of cards that will exist. M.card Minion cards have health and damage M.card 1 .name "Minion" M.card 1 .hp 1 M.deck 1 .dmg 1 Super Minions have more health and damage M.card 2 .name "Super Minion" M.card 2 .hp 4 M.card 2 .dmg 4 Spell cards have no health and damage. Instead they affect the health and damage of other cards. M.card 3 .name "Heal" M.card 3 .details "This card heals any character for 2 health" M.card 3 .healthboost 2 M.card 4 .name "Damage Boost" M.card 4 .details "This card gives 1 damage to any other card for 1 turn" M.card 4 .dmgboost 1 Super damage boost gives more damage boost to other cards M.card 5 .name "Super Damage Boost" M.card 5 .details "This card gives 3 damage to any other card permanently" M.card 5 .dmgboost 3 So when one card attacks another card, I need to keep track of the damage taken by both cards. I don't want to change the base stats of each card so I need to keep track of adjustments. I could do something like this Super Minion takes 3 damage M.card 2 .newHp 1 or M.card 2 .adjHp 3 Not sure which is better. During the battle I need to keep track of which auras are played. So for example if the Damage boost card is played. I need to give another card 1 damage for just one turn. Let's say that I am keep track of each turn number starting from 1. Should I do something like this M.aura 1 4 ( aura 1 is card 4) M.aura 1 .target 2 (this aura is applied to card 2) M.aura 1 .expires 5 (this aura expires on turn 5) M.aura 2 3 ( second active aura is heal, card 3 ) M.aura 2 .target 2 M.aura 2 .expires 0 this is a one time aura. So I need to apply it to card 2 and then immediately expire it so it never activates again. Then on every new turn I loop through all the auras and make sure they are still active before a fight begins? Just wondering architecturally what is the best way to keep track of Damage that characters have taken and spells that are active that are giving characters special abilities.


Do game programming just let all the objects in the program to interact with themselves and what about preventing infinite loop? Does game programming use the method of 1) using time as the main controller to let objects interact with each other, so each step, let 1 object send messages to N objects, and the second object to any number of objects, and 3rd, 4th, until all objects done, and that's it, and display the results on screen (or think of it as just a loop that always repeat, with each iteration considered "a tick in time") (so object 1 call object 2's method, and object 2 cannot call other object's method immediately? otherwise, there can be infinite loop like (2) below. but how do you implement "cannot call other objects until next time?" ) Or, 2) let the objects freely call other objects' methods (send messages to them), with no "Time" concept like the above Are they both feasible solutions? But what if in (2), you have stones in a circular tube, and stone 1 pushes stone 2, and 2 pushes 3, and so forth, until stone N pushes stone 1 again, then the program will go into infinite loop and not able to do anything else (say if the program is a single process, single thread)


Pro's Con's of separating game logic and render threads Originally, I have thought that it is good practice to separate my game logic (updating) from my rendering thread. In this threading model, the rendering thread has no limitation on frame rate and simply draws whatever information is currently made available by the updating thread. On the other hand, the updating thread is monitored, and has a capped frame rate. I'm led to believe this is BAD and will lead to many coding struggles down the road... So, I'm wondering what are the POTENTIAL benefits for separating updating from rendering? Likewise, what are the POTENTIAL benefits gained when keeping the updating and rendering in the same thread? What are the losses for each method?


Tilemap Collision Generation Tracing Polygons with Slopes I've been using Godot for my game, but it has a unfortunate quirks with tilemap collision where physics objects can bounce weirdly near tile seams and kinematic bodies can often get stuck in seams as well. For early alpha work, I've been able to get around this by not using tilemap collision and then tracing the contours by hand... Well this isn't going to scale well to 200 rooms (or whatever I end up having) and could easily lead to mismatched collision data, so I've decided that this process needs to be automated. Tilemaps have a few different tile types fully solid, diagonal slopes, and 2 1 slopes. My first attempt matched each of these types to a half tile size, marking each vertex as solid or not solid, and then combining all the vertices (with their overlap) into a single grid of vertices. I could then use all of these together by marching along the perimeter and probing ahead to detect corners. Turns out this works well for convex corners but has serious issues in concave corners, plus there isn't enough data to detect slopes properly, so it often resulted in extra slopey parts or cutting into slopes just slightly. From there I decided to add some extra information on the vertex grid, such as whether a vertex is a slope edge and doing clever things surrounding the properties of how it overlaps, but it's quickly blowing up into a lot of specific cases. I spent much of today thinking about adding vertex normals to each tile definition, but I realized it wasn't going to work without adding a bunch of different tile solidity types. Are there better approaches than what I'm thinking that don't involve brittle lossy intermediate representations or ridiculous amounts of special cases?


How to calculate the magnitude of the drag in Corona sdk? I'm making a game on Corona that launches a ball. The force is based on the magnitude of the drag the larger is the drag the higher is the force. I'm having some trouble to do this, because I can't calculate the magnitude of the drag. I tried a simple (finalX initialX) but that's not a good idea. local function onTouch(event) if "began" event.phase then end if "ended" event.phase then local finalX event.x local finalY event.y forceX event.x event.xStart forceY event.y event.yStart print(forceX, forceY) end end local function gameComponents() local crate display.newImageRect( "images sonic.png", 90, 90 ) crate.x, crate.y 60, 360 crate.rotation 0 physics.addBody( crate, "static", friction 0.3 ) Runtime addEventListener( "touch", onTouch ) return crate end local Game Game.new gameComponents return Game


Calculating angle a segment forms with a ray I am given a point C and a ray r starting there. I know the coordinates (xc, yc) of the point C and the angle theta the ray r forms with the horizontal, theta in ( pi, pi . I am also given another point P of which I know the coordinates (xp, yp) how do I calculate the angle alpha that the segment CP forms with the ray r, alpha in ( pi, pi ? Some examples follow I can use the the atan2 function.


Getting the bounding box of a sphere I have a sphere with values center,radius and I need to convert the sphere to a bounding box with values min,max. How do I convert a sphere into a bounding box?


Find projecting triangle for UV mapping in RuneScape model format I am using an old Runescape model format, also used by Thief and Quake. In this format, instead of specifying UV coordinates for each vertex ABC, we specify a second trio of vertices PMN. Those vertices are then used to project UV texture coordinates onto ABC. Some previous Q amp A explains this projection algorithm and how to reverse it. I have a mesh with UVs that I want to save in this format. To do that, I want to find a trio of vertices PMN for each triangle ABC that reproduce the correct UVs. These PMN vertices are chosen from the collection of vertices already in my mesh. I could search every possible ordered triangle in my mesh, but that scales as O(n 3) and would be impractical for meshes with high vertex counts. How can I more efficiently find a PMN triangle that produces my desired UV coordinates on each triangle ABC?


How can I determine the first visible tile in an isometric perspective? I am trying to render the visible portion of a diamond shaped isometric map. The "world" coordinate system is a 2D Cartesian system, with the coordinates increasing diagonally (in terms of the view coordinate system) along the axes. The "view" coordinates are simply mouse offsets relative to the upper left corner of the view. My rendering algorithm works by drawing diagonal spans, starting from the upper right corner of the view and moving diagonally to the right and down, advancing to the next row when it reaches the right view edge. When the rendering loop reaches the lower left corner, it stops. There are functions to convert a point from view coordinates to world coordinates and then to map coordinates. Everything works when rendering from tile 0,0, but as the view scrolls around the rendering needs to start from a different tile. I can't figure out how to determine which tile is closest to the upper right corner. At the moment I am simply converting the coordinates of the upper right corner to map coordinates. This works as long as the view origin (upper right corner) is inside the world, but when approaching the edges of the map the starting tile coordinate obviously become invalid. I guess this boils down to asking "how can I find the intersection between the world X axis and the view X axis?"


How can I tell whether an object is moving CW or CCW around a connected path? Lets say we have a jagged shape And two creatures moving along it's outline. Then we smooth the shape completely by pulling the corners out. We get this It is easy to see now that Orange is moving CW and green CCW. How can I tell in which direction they are moving without smoothing out the shape? New image


Finding the normals of an oriented bounding box? Here is my problem. I'm working on the physics for my 2D game. All objects are oriented bounding boxes (OBB) based on the separate axis theorem. In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating. To do this I need to find the normal of the face(s) that the other OBB is touching. Example The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there. Here are my questions How do I determine which edges the car is penetrating. I know how to determine the normal of an edge, but how do I know if I need ( dy, dx) or (dy, dx)? In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out? Answers or help with any or all of these is greatly appreciated. Thank you


which quarter of a triangle the point is in I've got a world made out of squares. The square are devided in four triangles like this The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates? EDIT My algorithm bool h1 false, h2 false if(posZ lt posX posZ) something weird going on here h1 true if(posX lt posZ posX) and here h2 true if(h1 amp amp h2) triangle 0 if(h1 amp amp !h2) triangle 1 if(!h1 amp amp !h2) triangle 2 if(!h1 amp amp h2) triangle 3 This algorithm tries to find in which triangle you are. There is something wrong in that math.


How do I make a low pass filter (average of readings over time) for compass? I'm making a prototype for android that pulls compass data from the phone. I want to stabilize it so it is less jerky, by taking the average of the last couple of readings. I have done this for accelerometer readings with great success, but adding every measurement to a queue and then collapsing it and dividing it by the queue size ( calculating the average) but for angles this is different. If my measurements are for example 350, 359, 360 I could calculate the average as 356.3 But if my measurements are 350 359, 1 Then my average is 236 which is a radically different angle. Is there any way you guys can think of I could deal with this?


Intersect of vector and triangle side I'm trying to create a triangular touch surface for iOS where the user can drag around a point inside this triangle. Using information from this page, it is easy to figure out if the dragged point is inside or outside the triangle. However, I want to clip the point to the triangle edges if the user drags outside the triangle. This is easy for side AB and side AC, because I just have to set vectors u or v to zero respectively if the user's finger drags outside of these edges. However, I'm not sure how to find point p, on side BC. I need to find this point of intersection if the user drags their finger outside of edge BC.


How can I find the reflection of a point in a perpendicular line? From the image below I know the positions A and B. How can I find positions C and D and the reflection (Er) of an object E in the line CD? I saw the solution in How can I reflect a point about a line in Unity? but I don't understand it enough to apply it in my case. Please note that I'm trying to achieve this in 2D.


How to know if two surface are in the same direction? In my code I creat a Mesh that are composed by multiple tile. those tile can have edge that are shared, and I need to know if the normal of the tile that have shared edge have the same direction, because I calculat the normal of the edge to smooth the light. before I used the Vector.Dot() , but I've sometimes two tile that have a curve that make impossible to use this function as you can see in the 4th image. and the only information that i have in the calcul is the 2 normal of the tile. img 1 diferent direction img 2 diferent direction img 3 same direction img 4 same direction img 5 same direction


Segment Cylinder intersection What is the complete code (C , pseudo, does not matter) for calculating the resulting segment (or its absence) for the intersection of asegment and a cylinder? The segment is defined by Vector3(x,y,z) as Start andVector3(x,y,z) as End. The cylinder is defined by the same parameters plus a value for Radius.


Circles within circle (PUBG safe zone) I'm attempting to do something that resembles the safe zone in PUBG (PLAYERUNKNOWN'S BATTLEGROUNDS), a circular area on the map that shrinks over time. On map screen draw circle at rand X Y, 300 pixels wide After say 5 minutes, I want to edit the X, Y and WIDTH of the circle so the new, smaller circle sits at a random position inside the old one.


Calculating the center of a turning circle I'm trying to understand how to calculate the midpoint of a turning circle. In the attached picture, my unit is at location U. I want to compute the trajectory of the unit as it turns toward the starred location. I understand that to achieve this I need to know the location of point P, whose coordinates are (a,b). I also understand that I can do this using some simple trig a x cos(theta) r b y sin(theta) r My problem is that I do not know the value of the angle Theta which sits between the sides of the right triangle named "R" and "X A". All I know is The radius of the turning circle. The orientation of the unit. How can I solve this problem and others like it more generally?


Calculating approximations of contact between two meshes I'm looking for ways to calculate the degree of contact between two objects in a scene. I was thinking that calculating the hausdorff distance would be a useful approximation if it is then normalized somehow using the surface area volume of the objects. Does anyone have any experience calculating this in Unity? Or have any suggestions for other ways to approximate this? Edit For some context, I'm working on a project which involves looking at the relationship between geometric properties and relations of objects, and what language words people use to describe objects and I am using scenes in unity to test this. The notion of 'contact' appears to be an important one and it would be useful to be able to quantify the amount of contact between two objects in a scene


How to access Maya Bonus Tools 2012 in Maya 2014 I have been trying to use the paint geometry tool for Maya 2014 but it isnt showing up. I downloaded Bonus Tools 2012 and installed it. Where can I find this tool in Maya 2014?


Move object forward according to rotation How do I make an object (like a bullet) go forward according to its rotation in vanilla nodejs (my game server language)? For example, if an object's rotation is 0 degrees, then it goes straight up.


Moving and shrinking circle to a circle inside of it (PUBG like zone) I am trying to create a battle royale circle gamemode within Arma3 that would work like in PUBG. For anyone who doesn't know how it looks like Red circle should smoothly shrink into the blue one (that means sides that close to each other should move very slowly by adjusting speed of the red circle center) Global variables Center (getMarkerPos quot marker start quot ) eg. 1000, 1000 ClosingSpeed 0.5 CurrentRadius 1000 EndingRadius 250 Offset 1 Code for generating new circle Determines maximum radius of a new circle private maxRadius CurrentRadius 0.7 Generates radius of the new circle private randomRadius maxRadius 0.6, maxRadius call BIS fnc randomNum Generates new circle center private randomCenter CurrentRadius 0.1, (CurrentRadius randomRadius) call BIS fnc randomNum Randomizes position of the new circle within the old one FinalCenter Center getPos randomCenter, random 360 EndingRadius randomRadius ClosingSpeed ClosingSpeed 2 This number should be somehow calculated to make the closing circle animation work properly Offset 0.75 Shrinking code, executed every 100 ms Decreases radius CurrentRadius CurrentRadius ClosingSpeed Gets the angle between two center points in degrees private angle ((FinalCenter select 1) (Center select 1)) atan2 ((FinalCenter select 0) (Center select 0)) if (CurrentRadius gt EndingRadius) then This sets new position of the circle Center set 0, (Center select 0) ((Offset ClosingSpeed) cos ( angle)) Center set 1, (Center select 1) ((Offset ClosingSpeed) sin ( angle)) Without the correct Offset it shrinks like this center points (red circle center was moving at a wrong velocity)


Easy way to project point onto triangle (or plane) I have a mesh of triangles (navigation mesh), and a point in 3d space. This point should be "over" one of the triangles all the times. I'm trying to determine which triangle is the one the point is "over", but I can't quite figure it out. I have found a way to tell if the point is in the triangle using one of the techniques described here, but I can't quite figure out how to project the point on the triangle (or the plane the triangle is in, for that matter). I've been looking online but I can't find anything helpful. Does anyone know how to project a point onto a triangle (or plane)? Also, if someone knows of a better way to test which triangle is the one the point is over, it would be appreciated.


Tilemap Collision Generation Tracing Polygons with Slopes I've been using Godot for my game, but it has a unfortunate quirks with tilemap collision where physics objects can bounce weirdly near tile seams and kinematic bodies can often get stuck in seams as well. For early alpha work, I've been able to get around this by not using tilemap collision and then tracing the contours by hand... Well this isn't going to scale well to 200 rooms (or whatever I end up having) and could easily lead to mismatched collision data, so I've decided that this process needs to be automated. Tilemaps have a few different tile types fully solid, diagonal slopes, and 2 1 slopes. My first attempt matched each of these types to a half tile size, marking each vertex as solid or not solid, and then combining all the vertices (with their overlap) into a single grid of vertices. I could then use all of these together by marching along the perimeter and probing ahead to detect corners. Turns out this works well for convex corners but has serious issues in concave corners, plus there isn't enough data to detect slopes properly, so it often resulted in extra slopey parts or cutting into slopes just slightly. From there I decided to add some extra information on the vertex grid, such as whether a vertex is a slope edge and doing clever things surrounding the properties of how it overlaps, but it's quickly blowing up into a lot of specific cases. I spent much of today thinking about adding vertex normals to each tile definition, but I realized it wasn't going to work without adding a bunch of different tile solidity types. Are there better approaches than what I'm thinking that don't involve brittle lossy intermediate representations or ridiculous amounts of special cases?


Calculating surface normal numerically Say I have a 2D surface defined with the use of bitmap. I want to use this bitmap for collision detection (white color is where object can move freely, with black I mark the walls). How can I numerically calculate the surface normal vector at given point? For example, in the attached picture, how can I calculate the surface normal vector for the red point?


Rasterizing euclidean planes I'd like to visualize a BSP tree. To do this, I need to project an arbitrary euclidean plane onto a projection plane. I was thinking about calculating the intersections of the plane with the viewing frustum (in world space), then triangulating the resulting quadrangle and projecting the 2 triangles. Is there a better way? For example, I thought about transforming the plane into the viewing space first, creating an ONB (from the transformed plane normal). Then I would simply stretch the quadrangle, until it is outside of the frustum and transform the quadrangle back into world space and send it into the rendering queue. How should I got about shading the plane approximation (quadrangle)?


Get triangles after subdivision I was able to do subdivision on a triangle mesh with midpoints but then I get polygons with too many faces. How do I convert to triangles after? Similar to this picture


How to avoid destroying information when scaling I'm in the progress of making a simple 3D editor, just for developing skills on 3d graphics. After implementing some basic tools, I realize that scaling isn't working as I expected. For example, when you scale down a model to a flat plane along some axis, how is it possible to restore that model when you scale up again on that axis? Every vertex has been crunched to the same position, so they will all be scaling in the same way, so the model's vertex layout will be lost. I assume that I need some metadata or quot shadow copy quot of the model, but I'm not sure. How can I solve this problem in my editor?


ray polygon intersection I am looking for an elegant way to do ray and polygon intersections in 2d. I don't care about languages. Now what I'm doing is taking a line that lies on the ray (with a screen length) and testing line to line intersections between this derived ray and all lines formed by each consecutive vertices in the polygon. This, for now, is good even if I don't know which parts of the ray are inside or outside the polygon (in cases it is concave one). But for now I don't need this information, even if a general approach could maybe give it. I don't care about self intersection polygons. Any advice? Maybe triangulating the polygons could be an idea?


Procedural Geometry Generation I have recently been looking into SceneKit for OS X and noticed that there are several factory methods to create geometric shapes such as Box, Capsule, Cone, Cylinder, Plane, Pyramid, Sphere, Torus and Tube. I am interested in adding such primitive shapes to my renderer but am struggling to find any reasonable source from which I can gather an understanding of procedural generation. There are several resources which detail the theory, but lack the appropriate source code to back it up. SceneKit provides factory methods which allow for dynamically setting the attributes of such shapes. In the case of the Box, you can provide integer values for the number of width, height and depth segments which each face should be divided into. I understand the theory but lack the knowledge to begin subdividing geometry faces to achieve the desired effect. The vertices for each shape are most likely quite easy to generate in simple loops. What stumps me is knowing how to create the faces, or rather the appropriate texture coordinates for each face. Normals can be calculated per face so I'm fairly confident I could achieve what I want, it's just knowing where to start. Can anyone provide any details on procedural geometry? What I really need is some source code to glean some information from. I have searched high and low for tutorials but have so far come up with only a few reasonable sites or blogs. Any good books, tutorials, blogs or research papers would be appreciated. Edit based on comments I should have clarified that I know how to create vertices for basic shapes, most of these can probably be achieved by simple loops. What I don't comprehend is how to create faces from the generated array of vertices. How do I create a triangle strip, or triangles, from a seemingly unordered array of vertices? I assume that once I get past this point, I can create the normals from each face. Whilst I haven't delved into this yet, I have seen a lot of references to this and am sure it will be easy enough to implement. Ideally, i'd like to be able to generate geometry from a given set of properties such as the way that SceneKit provides. Given SceneKit has done it, and you can do similar things in Blender and Maya etc, I assume i'm not trying to implement the impossible. The final aspect would be applying textures. Again, this isn't something I have implemented but have read up on and am aware of the requirements. The main problem here is that I know what I want to achieve but am struggling to decipher how to implement for the aforementioned primitives. I was hopeful that I would be able to find some semblance of knowledge by way of source code but I really haven't come across anything suitable so far.


Finding the position of a point inside a triangle, based on the position of a point in another triangle (barycentric coordinates in Godot) I'm trying to translate a UV coordinate into a world coordinate. (this is not in a shader, it's in GDScript in Godot, to bake out a texture based on some raycasts). So I find out which triangle in the UV map the coordinate is in and then I find the corresponding triangle in the mesh and get it's world position, that's all good. But then I can't figure out how to translate the points relative position inside the UV triangle to the mesh triangle. I've been trying to use the distance from the point to each of the triangle points as weights to how much of each of the mesh points I should use to find the point I'm looking for, but having no luck. Any help would be much appreciated. Not sure how best to illustrate this. But imagine you had a triangle where you knew the corner points a, b, and c, and a position inside it p. And you had another triangle where you knew the corner points A, B and C, how would you find a point that was relative in the same as p is to abc in triangle ABC. EDIT I added an answer based on the comments from DMGregory


which quarter of a triangle the point is in I've got a world made out of squares. The square are devided in four triangles like this The corners have their heights stored in a 2D array and the center height is the average of the corners. To calculate the players Y coordinate I have to know in which triangle he is standing on. How can you calculate in which quarter the player is by the X and Y coordinates? EDIT My algorithm bool h1 false, h2 false if(posZ lt posX posZ) something weird going on here h1 true if(posX lt posZ posX) and here h2 true if(h1 amp amp h2) triangle 0 if(h1 amp amp !h2) triangle 1 if(!h1 amp amp !h2) triangle 2 if(!h1 amp amp h2) triangle 3 This algorithm tries to find in which triangle you are. There is something wrong in that math.


How can you tell if you are a large player on a large map or a small player on a small map? If everything is scaled by a constant factor, can you tell that the world is smaller or larger? I think you could look down at the ground and see that it's "closer". But how do you know what should be the correct distance? What visual clues give it away? Edit The player controller has an FPS camera!


Is there a 3D equivalent of hex tile maps? Probably the biggest advantage of a hex based versus square based map tiling is that the center of each hex has the same distance to all its neighboring hexes. Is there a similar shape that tiles this way in 3D, and an engine that supports such a model?


What shapes interlock solidly like cubes? What basic geometric shapes, besides cubes, interlock "minecraft" style like cubes? A small edit to make question more suited to Game Dev I am experimenting with game dynamics to create geometric solids interlock seamlessly on their faces much the way the cubes do in minecraft. The objective is to create an interlock system that is also memory efficient consistent enough to maintain interlock over the course of many connections without deviating from the main grid.


How can I convert my list of vertices and indices to a list of triangles? I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles. First I tried to group every three vertices from the vertex list into a triangle, so vertices 0 2 were triangle 0, vertices 3 5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh. Then I remembered the indices list, but I didn't know how to use them. So I came here to ask how can I use the indices list to make my list of triangles?


Puzzle game clipping of non convex polygons on the figures I have an original figure in the SVG file. I need to break it randomly on parts, an example of which is specified below I have an idea, to use for partitioning Voronoi diagram (Fortune's algorithm). Can I then change the line of intersection of figures to give them a curvature? Can be obtained to identify each shape as a path? To create a game I'll be using cocos2d x.


Finding the normals of an oriented bounding box? Here is my problem. I'm working on the physics for my 2D game. All objects are oriented bounding boxes (OBB) based on the separate axis theorem. In order to do collision resolution, I need to be able to get an object out out of the object it is penetrating. To do this I need to find the normal of the face(s) that the other OBB is touching. Example The small red OBB is a car lets say, and the big OBB is a static building. I need to determine the unit vector that is the normal of the building edge(s) the car is penetrating to get the car out of there. Here are my questions How do I determine which edges the car is penetrating. I know how to determine the normal of an edge, but how do I know if I need ( dy, dx) or (dy, dx)? In the case I'm demonstrating the car is penetrating 2 edges, which edge(s) do I use to get it out? Answers or help with any or all of these is greatly appreciated. Thank you


Circles within circle (PUBG safe zone) I'm attempting to do something that resembles the safe zone in PUBG (PLAYERUNKNOWN'S BATTLEGROUNDS), a circular area on the map that shrinks over time. On map screen draw circle at rand X Y, 300 pixels wide After say 5 minutes, I want to edit the X, Y and WIDTH of the circle so the new, smaller circle sits at a random position inside the old one.


Why is the depth test not done on geometry before rasterization? It seems the only time depth is used to discard data is during rasterization, i.e. at the fragment level. In the geometry stage, I've only see culling and clipping of vertices. Is it not possible to determine whether if a triangle is behind another triangle using just vertex data (depth?) and discard if so? Wouldn't this save all the work later in scan conversion?


Calculating angle a segment forms with a ray I am given a point C and a ray r starting there. I know the coordinates (xc, yc) of the point C and the angle theta the ray r forms with the horizontal, theta in ( pi, pi . I am also given another point P of which I know the coordinates (xp, yp) how do I calculate the angle alpha that the segment CP forms with the ray r, alpha in ( pi, pi ? Some examples follow I can use the the atan2 function.


How can I randomly pick points on a triangle? Please can help me for a geometry query, I am working out fast mesh to voxel algorithm without using rays and complex maths... What are the maths to sample N points on a triangle randomly? If you can sample randomly i think it means you know the same equation that can distribute points on a triangle at same spacing. I found some info here but it's too difficult to understand https math.stackexchange.com questions 18686 uniform random point in triangle http mathworld.wolfram.com TrianglePointPicking.html The reason is to sample N points on every triangle and round each into a voxel space and send the rounded position of every sample as a true value to a boolean spacial voxel array of X,Y,Z true false values to represent voxels. Thanks for any info's you may provide!


Push cube outside triangle face I'm creating a 3D game, and I need to know how to push a player (axis aligned box cube) outside a triangle. How can I get get the push direction?


Intersection points of plane set forming convex hull Mostly looking for a nudge in the right direction here. Given a set of planes (defined as a normal and distance from origin) that form a convex hull, I would like to find the intersection points that form the corners of that hull. More directly, I'm looking for a way to generate a point cloud appropriate to provide to Bullet. Bonus points if someone knows of a way I could give bullet the plane list directly, since I somewhat suspect that's what it's building on the backend anyway.


Testing whether two cubes are touching in space Does anyone have any clean ideas on testing whether two cubes in 3D space touch? By touch I mean, touch at corners or on a face or on an edge. Say that the cubes are axis aligned and there is no nesting of the cubes. So either the cubes touch or they don't. There is no overlap of the cubes at all (except of course possibly an edge or corner point). Everything I have thought of ends up needing a ton of cases. Also numerical stability is a factor. I don't want to just test on all the edges points. I guess I could utilize some sort of epsilon instead of testing whether something 0. The main thing however is minimizing the number of cases to test.


Implementing a Deferred Renderer (Basic Understanding) I am trying to implement a Deferred Renderer in Direct3D11. I am fairly new to this. I already bought a book Practical Rendering amp Computation with Direct3D 11. However, this book doesnt answer many of my questions. The Book just says "Call one of the Draw Commands to execute the Pipeline" In the context of a deferred Renderer I would like to know How I can actually render the different GBuffers, merge them and put actual Lighting to my scene. Let's say my GBuffers should represent Diffuse, Specular and Normals. I understand that Vertex Shaders have Constant Buffers that represent my Camera through Matrices. Vertices get Transformed in shaders into ViewSpace. How Do I get my Diffuse Specular Normal information out of that? Do I have to execute the Rendering Pipeline for every GBuffer? Technically do I just need to transform my vertices once in a VS and just execute my different GBuffer PS? The Context Object offers functions like "OMSetRenderTarget". The OutputMerger however is the last stage of the Pipeline, not the first... The Book itself just calls "Present(0,0)" exactly once and doesnt explain how you actually put things together. Sorry, quite a lot of different questions (


Independent blending with DXGI FORMAT R16G16 SINT I'm implementing direct volume rendering engine with volume bricking, but I'm stuck with this problem For each volume brick I render to color render target CRT (for visualization) and to data render target DRT (used for isosurface object picking). DRT is of the DXGI FORMAT R16G16 SINT format. All works fine and smooth except wrong handling of blending DRTs of multiple volume bricks together. Closer brick always occludes further brick DRT. Here are the pictures to illustrate my point (if the object has proper DRT data it's outlined as you can se in the highlighted area, there are objects parts with no data) Could somebody please give me a tip, how to handle this? Of course I could always render every brick to separate DRT and write own shader to merge them properly, but isn't there a way of only properly setting blending modes? (now I'm rendering with blending disabled for DRTs) Thanks


How to blend multiple normal maps? I want to achieve a distortion effect which distorts the full screen. For that I spawn a couple of images with normal maps. I render their normal map part on some camera facing quads onto a rendertarget which is cleared with the color (127,127,255,255). This color means that there is no distortion whatsoever. Then I want to render some images like this one onto it If I draw one somewhere on the screen, then it looks correct because it blends in seamlessly with the background (which is the same color that appears on the edges of this image). If I draw another one on top of it then it will no longer be a seamless transition. For this I created a blendstate in directX 11 that keeps the maximum of two colors, so it is now a seamless transition, but this way, the colors lower than 127 (0.5f normalized) will not contribute. I am not making a simulation and the effect looks quite convincing and nice for a game, but in my spare time I am thinking how I could achieve a nicer or a more correct effect with a blend state, maybe averaging the colors somehow? I I did it with a shader, I would add the colors and then I would normalize them, but I need to combine arbitrary number of images onto a rendertarget. This is my blend state now which blends them seamlessly but not correctly D3D11 BLEND DESC bd bd.RenderTarget 0 .BlendEnable true bd.RenderTarget 0 .SrcBlend D3D11 BLEND SRC ALPHA bd.RenderTarget 0 .DestBlend D3D11 BLEND INV SRC ALPHA bd.RenderTarget 0 .BlendOp D3D11 BLEND OP MAX bd.RenderTarget 0 .SrcBlendAlpha D3D11 BLEND ONE bd.RenderTarget 0 .DestBlendAlpha D3D11 BLEND ZERO bd.RenderTarget 0 .BlendOpAlpha D3D11 BLEND OP MAX bd.RenderTarget 0 .RenderTargetWriteMask 0x0f Is there any way of improving upon this? (PS. I considered rendering each one with a separate shader incementally on top of each other but that would consume a lot of render targets which is unacceptable)


How can I prevent other applications from interrupting my game's exclusive fullscreen mode? I am developing a game using D3D 11. When I got a pop up message from a chat client (HipChat), my game's full screen mode is disabled because IDXGISwapChain Present returns DXGI STATUS OCCLUDED. How can I avoid or prevent this? I don't want my game's exclusive full screen access interrupted.


Direct3D11 Depth buffer problem Encountered a strange error when using Direct3D11, feature level 10.0. If the depth buffer texture is created with the format DXGI FORMAT R24G8 TYPELESS, bind flag D3D11 BIND DEPTH STENCIL D3D11 BIND SHADER RESOURCE and the depth stencil view format DXGI FORMAT D24 UNORM S8 UINT, everything is correct. Also, there are no problems when the depth buffer texture format is DXGI FORMAT R32G8X24 TYPELESS and the depth stencil view format is DXGI FORMAT D32 FLOAT S8X24 UINT. However, when the depth buffer format is DXGI FORMAT R32 TYPELESS, and the depth stencil view format is DXGI FORMAT D32 FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation destruction of resources). I do not use the stencil functionality at all, and it is disabled. I use a Windows 7 virtual machine as a developer machine and using DXGI FORMAT R32 TYPELESS and DXGI FORMAT D32 FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine. Is it possible to have a bug somewhere else in my code? Is there a limitation when using DXGI FORMAT D32 FLOAT and sometimes it may not be possible to use DXGI FORMAT D32 FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)? Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus Intel HD 4000 GeForce GTX 650M)?


IsoSurface Normals Texture Coords Problems(DX11 SharpDX) Hi and thanks for your time! So over the past few days I have been playing with isosurface construction from volume textures, I have it running on the cpu and all is well from a "just got it working" stand point eg. surface reconstruction works and I have my really cool voxel mesh drawing. I have based my code(converted to VB.net) on Paul Bourke's work here Polygonising a scalar field and like I said it works well apart from the fact that my normals are wrong and I have these strange fully black on both sides triangles, I think I'm doing my normals wrong but the way they are now is the beast I can get, I tried a few ways to build the normals and this one is the only way I could get smooth normals. Here you can see how my normals are wrong, green should be up, gray dark should be unlit and the hay'ish colour is the lit side. I have tried to flip and invert them but as you can see they are not wrong all the same way. HLSL Normals 1st try float3x3 cotangent frame(float3 N, float3 p, float2 uv) get edge vectors of the pixel triangle float3 dp1 ddx(p) float3 dp2 ddy(p) float2 duv1 ddx(uv) float2 duv2 ddy(uv) solve the linear system float3 dp2perp cross(dp2, N) float3 dp1perp cross(N, dp1) float3 T dp2perp duv1.x dp1perp duv2.x float3 B dp2perp duv1.y dp1perp duv2.y construct a scale invariant frame float invmax sqrt(max(dot(T, T), dot(B, B))) return float3x3(T invmax, B invmax, N) HLSL Normals 2nd try NormalData CalcWS Normal(float2 WS TexCoord, float3 WS Pos) NormalData dout float3 dp1 ddx(WS Pos) float3 dp2 ddy(WS Pos) float2 duv1 ddx(WS TexCoord) float2 duv2 ddy(WS TexCoord) float3x3 M float3x3(dp1, dp2, cross(dp1, dp2)) float2x3 inverseM float2x3(cross(M 1 , M 2 ), cross(M 2 , M 0 )) float3 t mul(float2(duv1.x, duv2.x), inverseM) float3 b mul(float2(duv1.y, duv2.y), inverseM) float3 normal normalize(cross(normalize(b), normalize(t))) dout.Normal normal dout.Tang t dout.BiTang b return dout Heres is how I'm doing it now, takes a vertex and then samples the volume texture VB.net Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Single) As Vector3 Dim rfNormal As Vector3 rfNormal.X fSample1(fX fScale, fY, fZ) fSample1(fX fScale, fY, fZ) rfNormal.Y fSample1(fX, fY fScale, fZ) fSample1(fX, fY fScale, fZ) rfNormal.Z fSample1(fX, fY, fZ fScale) fSample1(fX, fY, fZ fScale) Return Vector3.Normalize(rfNormal) End Function Private Function vGetNormal(fX As Single, fY As Single, fZ As Single, fScale As Vector3) As Vector3 Dim rfNormal As Vector3 rfNormal.X fSample1(fX fScale.X, fY, fZ) fSample1(fX fScale.X, fY, fZ) rfNormal.Y fSample1(fX, fY fScale.Y, fZ) fSample1(fX, fY fScale.Y, fZ) rfNormal.Z fSample1(fX, fY, fZ fScale.Z) fSample1(fX, fY, fZ fScale.Z) Return Vector3.Normalize(rfNormal) End Function Volume sampling code VB.net Public Function GetVolumeData( pos As Vector3) As Half Dim x2 As Single Math.Abs(( pos.X CellsPerPatch 32) Mod mWidth) Dim y2 As Single Math.Abs(( pos.Y CellsPerPatch 8) Mod mDepth) Dim z2 As Single Math.Abs(( pos.Z CellsPerPatch 32) Mod mHeight) Return mScalars(CInt(Math.Truncate(x2)) (CInt(Math.Truncate(z2)) mWidth) (CInt(Math.Truncate(y2) mWidth mWidth))) End Function The rest of the isosurface construction code is just a copy convert paste of Paul Bourke's c code. Just to makes sure everyone knows what I'm asking Can anyone tell me what I'm doing wrong? Is it a problem with my normals or the isosurface stuffs or both? All of the above is just so u have some context, I'm happy to post more code if ppl need to see it EDIT Black squares come from having no depth info at that point so my deferred render hates those spots, this is leading back to maybe a problem with the surface reconstruction? But why its only happening in those spots, one would think that it would happen everywhere?


The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0 ... I don't understand this error. The full output being The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0, but the sampler bound at this slot is configured for comparison filtering. Here is how I create the sampler state. Skybox sampler description D3D11 SAMPLER DESC skyboxSamplerDesc ZeroMemory( amp skyboxSamplerDesc, sizeof(D3D11 SAMPLER DESC)) skyboxSamplerDesc.Filter D3D11 FILTER COMPARISON MIN MAG LINEAR MIP POINT skyboxSamplerDesc.AddressU D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.AddressV D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.AddressW D3D11 TEXTURE ADDRESS CLAMP skyboxSamplerDesc.MipLODBias 0.0f skyboxSamplerDesc.MaxAnisotropy 16 skyboxSamplerDesc.ComparisonFunc D3D11 COMPARISON EQUAL skyboxSamplerDesc.MinLOD 0 skyboxSamplerDesc.MaxLOD D3D11 FLOAT32 MAX Create the skybox texture sampler state hr g d3dDevice gt CreateSamplerState( amp skyboxSamplerDesc, amp g SkyboxSamplerState) if (FAILED(hr)) return false The bindings. ID3D11SamplerState samplerStates 2 samplerStates 0 g SkyboxSamplerState samplerStates 1 g PixelDepthSamplerState g d3dDeviceContext gt PSSetSamplers(0, 2, samplerStates) HLSL side. SamplerState sbSamplerState register (s0) Filter MIN MAG LINEAR MIP POINT AddressU CLAMP AddressV CLAMP AddressW CLAMP ComparisonFunc EQUAL


How to make use of resizable BAR? From what I understand, resizable BAR (aka. Smart Access Memory) makes it possible to access the whole GPU memory from CPU code. But how can a programmer make use of that? Is there an example or code snippet somewhere, that makes use of that feature? Or is that just an automatic that improves the performance of staging resources? I'd also be happy if you can recommend further search terms that I can look up.


Update DXGI swapchain sample count without recreating swapchain in full screen mode I'm implementing the ability to tweak graphics settings in my application at runtime (resolution, refresh rate, v sync, multisampling). It is possible to update the resolution, format and refresh rate using IDXGISwapChain ResizeTarget and IDXGISwapChain ResizeBuffers. However, I cannot find any way to update the swapchain's sampling(count and quality) in the same way. The only option I have is to go to windowed mode using IDXGISwapChain SetFullscreenState, then release the swapchain, recreate the swapchain with a new DXGI SWAP CHAIN DESC, and then go back to fullscreen again. (Didn't mention releasing and recreating back buffer and depth stencil since it is a must do).I am willing to stay at full screen mode before and after the settings are applied.


Game only runs at 60fps in windowed mode with a 120hz monitor? In fullscreen the game will run at 120fps fine, the correct refresh rate for the monitor, but in windowed mode it only runs at 60fps. If I disable VSync then it runs at thounsands of fps so it's not a case of a lack of performance. I've correctly set the refresh rate in the ModeDescription.


Fbx SDK Importer issue (texture uv related) I am using the latest autodesk FBX Importer SDK, but whatever I do, I am unable to get the uvs right. Some parts are textured properly while others are not. I am using Direct3D9 and Direct3D11 (same result in both). Image 360 image https i.gyazo.com 5a2e5f6e127521915508c9c300eb03e5.mp4 The model uses a single texture and a single material shared among 4 meshes. Is there someone who sees immediately what the problem could be? Or is there someone who can replicate the issue for me and figure out what I am missing? FBX Test File http www.4shared.com rar o WG0Crpce Peach64FBX.html My UV reading method int vertexCounter 0 for (int j 0 j lt nbPolygons j ) for (int k 0 k lt 3 k ) int vertexIndex pFbxMesh gt GetPolygonVertex(j, k) Vector2 uv readUV(pFbxMesh, vertexIndex, pFbxMesh gt GetTextureUVIndex(j, k), uv) pVertices vertexIndex .uv.x uv.x pVertices vertexIndex .uv.y 1.0 uv.y vertexCounter void readUV(fbxsdk FbxMesh pFbxMesh, int vertexIndex, int uvIndex, Vector2 amp uv) fbxsdk FbxLayerElementUV pFbxLayerElementUV pFbxMesh gt GetLayer(0) gt GetUVs() if (pFbxLayerElementUV nullptr) return switch (pFbxLayerElementUV gt GetMappingMode()) case FbxLayerElementUV eByControlPoint switch (pFbxLayerElementUV gt GetReferenceMode()) case FbxLayerElementUV eDirect fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(vertexIndex) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break case FbxLayerElementUV eIndexToDirect int id pFbxLayerElementUV gt GetIndexArray().GetAt(vertexIndex) fbxsdk FbxVector2 fbxUv pFbxLayerElementUV gt GetDirectArray().GetAt(id) uv.x fbxUv.mData 0 uv.y fbxUv.mData 1 break break case FbxLayerElementUV eByPolygonVertex switch (pFbxLayerElementUV gt GetReferenceMode()) Always enters this part for the example model case FbxLayerElementUV eDirect case FbxLayerElementUV eIndexToDirect uv.x pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 0 uv.y pFbxLayerElementUV gt GetDirectArray().GetAt(uvIndex).mData 1 break break I am doing V 1.0 uv.y because I am using Direct3D11. NOTE the MappingMode is always eByPolygonVertex and ReferenceMode is always eIndexToDirect Rendering Info Rendered as a Triangle List Uv wrapping mode Wrap (Repeat) Culling None


Can state setting warnings be ignored? If I am running DirectX 11 in debug mode (D3D11 CREATE DEVICE DEBUG), I am constantly getting these warnings D3D11 WARNING ID3D11DeviceContext OMSetRenderTargets Resource being set to OM DepthStencil is still bound on input! STATE SETTING WARNING 9 DEVICE OMSETRENDERTARGETS HAZARD D3D11 WARNING ID3D11DeviceContext OMSetRenderTargets AndUnorderedAccessViews Forcing PS shader resource slot 6 to NULL. STATE SETTING WARNING 7 DEVICE PSSETSHADERRESOURCES HAZARD It is because I am setting a resource as a render target while it is currently bound to the PS. However, my rendering flow is set up such as it relies on the api to force the resource slot to null, and it works. Is there any reason I should be bothered with these warnings or I can rely on the api to enforce this every time? I only tested on 2 GPU s Intel HD 3000 and Nvidia GT525m.


How can I render a 2D image to my screen using Direct X 11? I am trying to render an image to my window using Direct X but I don't really want a "3D" world as such, and I don't really want to set up all the vertex index buffers as I won't need them. I am performing all of my calculations and operations using compute shaders which returns me an image. As the file io is quite a bottleneck, I am looking to just render the image directly to the screen to increase performance. My question is, how would I go about this using Direct X 11? I have looked at some examples already such as rastertek and other questions on SO but they are either over complicating the matter, or they want a solution to font drawing etc. At the moment I am able to produce a blank screen using the following code and the screen size is the size of the image retrieved from the GPU. I am looking to draw this entire image to my back buffer or some render target, and then display it. void Application Draw() float ClearColor 4 0.5f, 0.125f, 0.3f, 1.0f context gt ClearRenderTargetView( pRenderTargetView, ClearColor) compute shader operations, retrieve image data from gpu draw image to back buffer render target then present swapChain gt Present(0, 0) From Why can 39 t I write to my render targets?, I have tried the solution using ID3D11Resource backBufferResource pRenderTargetView gt GetResource( amp backBufferResource) backbuffer render target context gt CopyResource(backBufferResource, gpuResource) This doesn't seem to throw any errors, but it doesn't change the output on the screen. It is mentioned that the back buffer must be the exact same format as the image we're trying to copy to it so this may be the issue. My swap chain desc is as follows DXGI SWAP CHAIN DESC sd ZeroMemory( amp sd, sizeof(sd)) sd.BufferCount 1 sd.BufferDesc.Width WindowWidth sd.BufferDesc.Height WindowHeight sd.BufferDesc.Format DXGI FORMAT R8G8B8A8 UNORM FORMAT DIFFERENT sd.BufferDesc.RefreshRate.Numerator 60 sd.BufferDesc.RefreshRate.Denominator 1 sd.BufferUsage DXGI USAGE RENDER TARGET OUTPUT sd.OutputWindow hWnd sd.SampleDesc.Count 1 sd.SampleDesc.Quality 0 sd.Windowed TRUE and my image format is DXGI FORMAT R32G32B32A32 FLOAT If I try to change the swap chain format it throws a memory access violation.


How do I use com ptr t with RenderTargetView and DepthStencilView? I have successfully used com ptr t with the ID3D11Device and IDXGISwapChain but when applying the same reasoning to the RenderTargetView and DepthStencilView, the function m spD3DImmediateContext gt OMSetRenderTargets(...) sets the m spRenderTargetView smart COM pointer to null! Then, subsequent draw calls fail on ClearRenderTargetView and ClearDepthStencilView. Is it because I am passing the smart pointer incorrectly? HR(m spD3DDevice gt CreateRenderTargetView(pBackBuffer, 0, amp m spRenderTargetView)) ... HR(m spD3DDevice gt CreateTexture2D( amp stDepthStencilDesc, 0, amp m spDepthStencilBuffer)) ... m spD3DImmediateContext gt OMSetRenderTargets(1, amp m spRenderTargetView, m spDepthStencilView) assert(m spRenderTargetView) lt FAIL I think the smart pointer overloads the operator amp so that it returns an Interface (see Extractors in com ptr t class).


What are the tessellation factors Direct3D11? I don't quite understand the documentation but if I was to tessellate a mesh using 3 control points in Direct3D11 with the "tri" domain am I right in thinking that SV TessFactor is how many times to split up each edge and SV InsideTessFactor is how many points inside the triangle to create?


Can't get Direct3D11 depth buffer to work I can't get the depth buffer to work correctly. I am rendering 2 cubes in a single Draw function, and from one angle it looks great But swing the camera around to view the opposite sides, and I discover it's just Painter's Algorithm. This is my code to setup the depth stencil buffer void Graphics CreateDepthStencilBuffer(ID3D11Texture2D backBuffer) D3D11 TEXTURE2D DESC dsTextureDesc backBuffer gt GetDesc( amp dsTextureDesc) dsTextureDesc.Format DXGI FORMAT D24 UNORM S8 UINT dsTextureDesc.Usage D3D11 USAGE DEFAULT dsTextureDesc.BindFlags D3D11 BIND DEPTH STENCIL dsTextureDesc.MipLevels 1 dsTextureDesc.ArraySize 1 dsTextureDesc.CPUAccessFlags 0 dsTextureDesc.MiscFlags 0 Microsoft WRL ComPtr lt ID3D11Texture2D gt dsBuffer ASSERT SUCCEEDED(g Device gt CreateTexture2D( amp dsTextureDesc, NULL, dsBuffer.ReleaseAndGetAddressOf())) D3D11 DEPTH STENCIL DESC dsDesc dsDesc.DepthEnable true dsDesc.DepthWriteMask D3D11 DEPTH WRITE MASK ALL dsDesc.DepthFunc D3D11 COMPARISON LESS ... snipped stencil properties ... ASSERT SUCCEEDED(g Device gt CreateDepthStencilState( amp dsDesc, g DepthStencilState.GetAddressOf())) g pDevCon gt OMSetDepthStencilState(g DepthStencilState.Get(), 1) D3D11 DEPTH STENCIL VIEW DESC depthStencilViewDesc depthStencilViewDesc.Format dsTextureDesc.Format depthStencilViewDesc.ViewDimension D3D11 DSV DIMENSION TEXTURE2D depthStencilViewDesc.Texture2D.MipSlice 0 ASSERT SUCCEEDED(g Device gt CreateDepthStencilView(dsBuffer.Get(), amp depthStencilViewDesc, g depthStencilView.GetAddressOf())) And I'm calling g pDevCon gt OMSetRenderTargets(1, g renderTargetView.GetAddressOf(), g depthStencilView.Get()) after every Present call. I've been scratching my head for ages wondering what the problem is. Any clues will be much appreciated! Edit I used the graphics debugger, and apparently the output merger is doing its job, as seen in the screenshot below, but that isn't what I am seeing on screen. At the top of the pic is the state of the depth buffer, but I can't make sense of it to determine if it's correct or not.


Create Render Target View 138 140 need to Bind the back buffer to the render target view DirectX 11 This is the error D3D11 ERROR ID3D11Device CreateRenderTargetView A RenderTargetView cannot be created of a Resource that did not specify the RENDER TARGET BindFlag. STATE CREATION ERROR 138 CREATERENDERTARGETVIEW INVALIDRESOURCE D3D11 ERROR ID3D11Device CreateRenderTargetView Returning E INVALIDARG, meaning invalid parameters were passed. STATE CREATION ERROR 140 CREATERENDERTARGETVIEW INVALIDARG RETURN So as i see here i need to set the BindFlag of the backBuffer to D3D11 BIND RENDER TARGET, but in all the tutorial i saw nobody is doing it, they all create the render target view by using this code hr m swapChain gt GetBuffer(0, uuidof(ID3D11Texture2D), reinterpret cast lt void gt ( amp m backBuffer)) if (FAILED(hr)) MessageBox(0, L"Failed get buffer", 0, 0) hr m device gt CreateRenderTargetView(m backBuffer, NULL, amp m renderTargetView) if (FAILED(hr)) MessageBox(0, L"Failed to create rendertargetview", 0, 0) And nobody, nowhere is doing as the msdn site says, that the render target view must be created with this specific flag D3D11 BIND RENDER TARGET So I tried doing it by myself. I created a texture2d desc like this for the back buffer D3D11 TEXTURE2D DESC backBufferDescription backBufferDescription.BindFlags D3D11 BIND RENDER TARGET backBufferDescription.ArraySize 1 backBufferDescription.CPUAccessFlags 0 backBufferDescription.Format DXGI FORMAT R8G8B8A8 UNORM backBufferDescription.Height 600 backBufferDescription.Width 800 backBufferDescription.MipLevels 1 backBufferDescription.MiscFlags 0 backBufferDescription.SampleDesc.Quality 0 backBufferDescription.SampleDesc.Count 1 backBufferDescription.Usage D3D11 USAGE DEFAULT m device gt CreateTexture2D( amp backBufferDescription, NULL, amp m backBuffer) if (FAILED(hr)) MessageBox(0, L"Fallito back buffer desc", 0, 0) And it doesn't work the same. Help please


Why isn't my cbuffer updating? I am really frustrated because my cbufer isn't updating. This is my VS cbuffer MatrixBuffer register(b0) float4x4 worldViewProj struct VertexIn float4 Pos POSITION float4 Color COLOR struct PixelIn float4 PosH SV POSITION float4 Color COLOR PixelIn VS (VertexIn vin) PixelIn vout vin.Pos.w 1.0f vout.PosH mul(vin.Pos, worldViewProj) vout.Color vin.Color return vout PixelIn VS1(VertexIn vin) PixelIn vout vin.Pos.w 1.0f vout.PosH vin.Pos vout.Color vin.Color return vout When using VS1 it draws correctly, but when using VS it doesn't draw anything? Here is my CBUFFER update code bool Game UpdateShaders() HRESULT result D3D11 MAPPED SUBRESOURCE mappedResource MatrixBufferType dataPtr worldViewProjM worldM viewM projM worldViewProjM XMMatrixTranspose(worldViewProjM) result md3dDeviceContext gt Map(mMatrixBuffer, 0, D3D11 MAP WRITE DISCARD, 0, amp mappedResource) if (FAILED(result)) MessageBoxW(mMainWnd, L"FAOE ", 0, 0) return false dataPtr (MatrixBufferType )mappedResource.pData dataPtr gt worldViewProj worldViewProjM md3dDeviceContext gt Unmap(mMatrixBuffer, 0) int NBuffers 0 md3dDeviceContext gt VSSetConstantBuffers(0, 1, amp mMatrixBuffer) md3dDeviceContext gt PSSetConstantBuffers(0, 1, amp mMatrixBuffer) return true Here is my MATRIXBUFFERTYPE struct struct MatrixBufferType XMMATRIX worldViewProj This is called after I clear my depth stencil view and render target view. Does somebody know why my CBUFFER isn't updating? Thanks in advance.


DX11 Handle Device removed I get the DXGI ERROR DEVICE REMOVED error on some machines. According to this (https msdn.microsoft.com en us windows uwp gaming handling device lost scenarios) MSDN article this can happen and it should be handled by your application. I've managed to recreate the device but I'm unsure how to handle all content. It seems I have to create all vertex buffers and textures again, which essentially means I have to reload almost the entire scene. Is this really the correct way?


Send empty vertex buffer data but keep Vertex Shader Input Structure? lets say i have the following structure defined in a header (for reusage) struct VertexShaderInput float3 Position POSITION float3 Normal NORMAL float2 UV TEXCOORD float4 Color COLOR however, some meshes dont have normals or colors and some passes (such as Depth PrePass) doesn't need Normal or Color. Is there a way to keep the struct definition above in my shaders and simply sending "zero" bytes for Normals and Colors?


How do I specify ARGB format textures in my input declaration? const D3D11 INPUT ELEMENT DESC InputLayoutDesc Basic32 3 "POSITION", 0, DXGI FORMAT R32G32B32 FLOAT, 0, 0, D3D11 INPUT PER VERTEX DATA, 0 , "NORMAL", 0, DXGI FORMAT R32G32B32 FLOAT, 0, 12, D3D11 INPUT PER VERTEX DATA, 0 , "TEXCOORD", 0, DXGI FORMAT R32G32B32A32 FLOAT, 0, 24, D3D11 INPUT PER VERTEX DATA, 0 The TEXCOORD, There is no support for a image that is ARGB. Only DXGI FORMAT R32G32B32A32 FLOAT How can I load ARBG? Or can I convert a ARGB TO A RGBA IMAGE?


Adding mesh's objects to procedural isosurface terrain Thanks again for reading! So following on from my last question, I have my fully working isosurface terrain and now its time to add my trees and grass and whatever to the world. The old way I was doing it was to cast rays in a grid faceing down over the terrain, I would then read the normal from the ray hit and place things if the normal was lt as value. I would do this at different grid resolutions for each plant tree grass time and offset there x, z and scale by some random value then adding the object to my 2d BV tree because I was only working with height map terrain so I only had one row of bounding volumes for the tree. I can still use the above method but as you know it will only place objects on parts of the terrain that can see the sky. Part of building my new terrain system involved making a real octree so I no that I will use that to store my objects but what is the best way to generate my object positons. From what I have read around I should somehow use the voxels I build but I'm not really sure how I would go about it.


Full screen quad in the HLSL Directx 11 I want to create a full screen Triangle Quad so I can blur the box that is the quad I made. I want to do this in the vertex buffer. I tried this code struct VSQuadOut float4 position SV POSITION float2 uv TEXCOORD outputs a full screen triangle with screen space coordinates input three empty vertices VSQuadOut VSQuad( uint vertexID SV VertexID ) VSQuadOut result result.uv float2((vertexID lt lt 1) amp 2, vertexID amp 2) result.position float4(result.uv float2(2.0f, 2.0f) float2( 1.0f, 1.0f), 0.0f, 1.0f) return result I want something like this Any ideas?


What is the AlphaToCoverage blend state useful for? Alright, just finished most of my early UI stuff and I wanted the windows to have some transparency. So I expanded my application to initialize and bind blend states so that my UI shader could implement alpha blending. I was initially having no luck but I got the blend state configured to achieve my purpose, however the way it is configured doesn't make sense to me so I must be missing something. Here is how I initialize my blend state. bool BlendState StartUp() D11DeviceManager pDeviceManager D11DeviceManager GetSingleton() D3D11 BLEND DESC desc desc.AlphaToCoverageEnable false desc.IndependentBlendEnable false desc.RenderTarget 0 .BlendEnable true desc.RenderTarget 0 .SrcBlend D3D11 BLEND SRC COLOR desc.RenderTarget 0 .DestBlend D3D11 BLEND DEST COLOR desc.RenderTarget 0 .BlendOp D3D11 BLEND OP ADD desc.RenderTarget 0 .SrcBlendAlpha D3D11 BLEND SRC ALPHA desc.RenderTarget 0 .DestBlendAlpha D3D11 BLEND DEST ALPHA desc.RenderTarget 0 .BlendOpAlpha D3D11 BLEND OP ADD desc.RenderTarget 0 .RenderTargetWriteMask 7 return !FAILED( pDeviceManager gt GetDevice() gt CreateBlendState( amp desc, amp pBlendState)) Right now my alpha blending only works when the AlphaToCoverage bool is set to false... I thought this was just a bool enabling the pixel fragment blending (which upon retrospection would be redundant considering the BlendEnable flags...) but looking at the MSDN documentation is appears to do this... You can use the AlphaToCoverageEnable member of D3D11 BLEND DESC1 or D3D11 BLEND DESC to toggle whether the runtime converts the .a component (alpha) of output register SV Target0 from the pixel shader to an n step coverage mask (given an n sample RenderTarget). The runtime performs an AND operation of this mask with the typical sample coverage for the pixel in the primitive (in addition to the sample mask) to determine which samples to update in all the active RenderTargets. Could someone explain this to me and how it differs from when the AlphaToCoverageEnable bool is false? I see that it adds a new mask to the fragment but I don't quite follow what the mask exactly is.


Sharpdx DirectX11 MapSubresource is failing trying to map a staging texture I'm trying to render to a texture and then pull the image data out. I've created one texture as a render target and another as a staging texture. After rendering to the render target, I use CopyResource to copy from the render target texture to the staging texture. So far, so good. However, when I use DeviceContext.MapSubresource to get the data from the staging texture, I get E INVALIDARGS exception, and I can't figure out why. Here is how I create the staging texture textureDesc new Texture2DDescription() ArraySize 1, BindFlags BindFlags.None, CpuAccessFlags CpuAccessFlags.Read, Format Format.B8G8R8A8 UNorm, Height 256, MipLevels 1, SampleDescription new SampleDescription(1, 0), Usage ResourceUsage.Staging, Width 256 renderStaging new Texture2D( dev, textureDesc) Here is how I populate the staging texture and then try to map it DataStream stream con.CopyResource( renderTarget, renderStaging) The following is the line that fails box con.MapSubresource( renderStaging, 0, MapMode.Read, MapFlags.None, out stream) I have the same code working in C , so I know I have the general idea right. This is the working C code textureDesc.Width 256 textureDesc.Height 256 textureDesc.MipLevels 1 textureDesc.ArraySize 1 textureDesc.Format DXGI FORMAT B8G8R8A8 UNORM textureDesc.SampleDesc.Count 1 textureDesc.MiscFlags 0 textureDesc.Usage D3D11 USAGE STAGING textureDesc.BindFlags 0 textureDesc.CPUAccessFlags D3D10 CPU ACCESS READ hr dev gt CreateTexture2D( amp textureDesc, NULL, amp renderStagingTexture) devcon gt CopyResource(renderStagingTexture, renderTargetTextureMap) D3D11 MAPPED SUBRESOURCE mappedResource devcon gt Map(renderStagingTexture, 0, D3D11 MAP READ, 0, amp mappedResource)


How can I check the shader model capabilities of an adapter? I'm writing an application that targets Direct3D11 (through SlimDX) and shader model 5. When I'm running it on a system that doesn't have SM5 capable hardware, I will get a NullReferenceException when trying to access the techniques in the compiled effect instance. How can I check if the adapter is capable of this before I even attempt to use any of these features?


What is the format of DXGI FORMAT D24 UNORM S8 UINT? I'm trying to read the values in a depth texture of type DXGI FORMAT D24 UNORM S8 UINT. I know this means "24 bits for depth, 8 bits for stencil" "A 32 bit z buffer format that supports 24 bits for depth and 8 bits for stencil.", but how do you interpret those 24 bits? It's clearly not going to be a 32 bit int, and it's not going to be a 32 bit float. If it is an integer value, how "far away" is a value of "1" in the depth texture?


Is object space the same as local space? I was in directx 11 and was wondering is local space the same as object space and if not, what is object space?


Using a DirectX Vertex Shader to Modify the Vertex Data in VRAM? I'm working on a GPU side particle system in DirectX 11 where the vertex shader uses a vector field encoded into the color channels of a texture to modify the positions of the vertices before drawing them to the screen. I'm trying to keep the computations on the GPU rather than calculating the updated particle positions on the CPU and send the new vertex data to the GPU every frame, so I've been investigating the possibility of having the vertex shader overwrite the vertex buffer in VRAM with the updated vertex positions each frame. So far, I haven't managed to find anything on the topic. Would this be possible, and if so, how would I accomplish it?


Geometry shader Dynamic output? I'm currently using a geometry shader to generate grass blades out of single root points that are layed out in a grid. For each root point, I generate a grass blade with, right now, a constant number of vertices. However, for level of detail, I would like to generate a number of vertices depending on the distance to the camera. Now, since there are no dynamic arrays, I tried to declare multiple techniques which call the geometry shader with the number of vertices. I would then be able to divide my grass into patches smaller grids, calculate the distance to the camera for this patch and then call the technique with the appropriate number of vertices. The HLSL part looks something like this maxvertexcount(24) void GS LOD1(point GEO IN points 1 , inout TriangleStream lt GEO OUT gt output) GS Shader(points, 8, output) maxvertexcount(24) void GS LOD2(point GEO IN points 1 , inout TriangleStream lt GEO OUT gt output) GS Shader(points, 16, output) technique LevelOfDetail1 pass Pass1 VertexShader compile vs 4 0 VS Shader() GeometryShader compile gs 4 0 GS LOD1() PixelShader compile ps 4 0 PS Shader() technique LevelOfDetail2 pass Pass1 VertexShader compile vs 4 0 VS Shader() GeometryShader compile gs 4 0 GS LOD2() PixelShader compile ps 4 0 PS Shader() And the definition of the GS function void GS Shader(point GEO IN points 1 , in const int realVertexCount, inout TriangleStream lt GEO OUT gt output) ... GEO OUT v realVertexCount However, even this way the compiler complains array dimensions must be literal scalar expressions Is this possible in any way? I guess what would is just writing several geometry shaders that basically do the same thing but with a already defined number of vertices this sounds a bit messy though. Thanks!


Resizing D3D Buffers within a frame I have a particle system. So far it worked like this I have a dynamic vertex buffer for a system, which is created with a size that can hold for example 100 000 particles. I map unmap this and write the new data into it every frame. But what if the particle count gets bigger than the buffer can hold? I thought of recreating the vertex buffer with the double of its previous capacity (then map unmap into it). Is this the right direction for this or should I solve it in a different way? A short example ID3D11VertexBuffer buffer ID3D11Device graphicsDevice ... D3D11 BUFFER DESC desc buffer gt GetDesc( amp desc) if(dataSize gt (int)desc.ByteWidth) data can't fit, so destroy and recreate buffer gt Release() desc.ByteWidth 2 graphicsDevice gt CreateBuffer( amp desc, nullptr, amp buffer ) returns S OK Update I want to use it for other things, not just particles but for example instanced meshes. If I spawn a couple of instances, I'd only like to resize a buffer, without creating an other one.


Why does my game not update unless I'm moving the mouse? I'm pretty confused by what's happening. Now that I've finally put something moving on my screen, I notice it doesn't update unless I move the mouse, or press a key, or trigger other events. Using PIX, the "Frame " counter only goes up when I fire these events. This is all that happens in my game loop while(GetMessage( amp msg, NULL, 0, 0) gt 0 amp amp m isRunning) TranslateMessage( amp msg) DispatchMessage( amp msg) m gameGraphics gt BeginRender() m gameGraphics gt EndRender() BeginRender clears the screen, and EndRender presents to the swap chain. I thought maybe it was a problem with WndProc, but comparing it to other DirectX 11 game WndProcs, I don't see any major differences. I'm pretty confused, never seen this problem before, and I have no idea what causes it. I'm just hoping maybe someone will have some insight on why this might be happening.


FormatMessage not working for HRESULTs returned by Direct3D 11 I am using Windows 7 x64 and Visual Studio 17 (v15.9.7). Say I try to create a swap chain using IDXGIFactory2 CreateSwapChainForHwnd and pass in DXGI SCALING NONE. I will get the following message in debug output (if I have enabled Direct3D debugging) DXGI ERROR IDXGIFactory CreateSwapChain DXGI SCALING NONE is only supported on Win8 and beyond. DXGI SWAP CHAIN DESC SwapChainType ... HWND, BufferDesc DXGI MODE DESC1 Width 816, Height 488, RefreshRate DXGI RATIONAL Numerator 0, Denominator 1 , Format B8G8R8A8 UNORM, ScanlineOrdering ... UNSPECIFIED, Scaling ... UNSPECIFIED, Stereo FALSE , SampleDesc DXGI SAMPLE DESC Count 1, Quality 0 , BufferUsage 0x20, BufferCount 2, OutputWindow 0x0000000000290738, Scaling ... NONE, Windowed TRUE, SwapEffect ... FLIP SEQUENTIAL, AlphaMode ... UNSPECIFIED, Flags 0x0 MISCELLANEOUS ERROR 175 The function returns 0x887a0001 in form of a HRESULT. If I put err,hr in the watch window, I get a nice error message there ERROR MOD NOT FOUND The specified module could not be found. However, if I pass this HRESULT to FormatMessage, it just puts NULL in the output and returns 0. err,hr helpfully informs me that the new error is ERROR MR MID NOT FOUND The system cannot find message text for message number 0x 1 in the message file for 2. My questions are Why is FormatMessage not giving me right error string (the one starting with ERROR MOD NOT FOUND...)? Where is Visual Studio getting these pretty error strings from? Can I get them too? Who do I pay? PS. I am using the Windows 10 SDK version of DX11, not the older DirectX SDK version. Thus, I can't really link to dxerr.lib either. This is the code that is used to print the error message LPTSTR error text NULL FormatMessage(FORMAT MESSAGE FROM SYSTEM FORMAT MESSAGE ALLOCATE BUFFER FORMAT MESSAGE IGNORE INSERTS, NULL, hr, MAKELANGID(LANG NEUTRAL, SUBLANG DEFAULT), (LPTSTR) amp error text, 0, NULL)


Direct3D11 Depth buffer problem Encountered a strange error when using Direct3D11, feature level 10.0. If the depth buffer texture is created with the format DXGI FORMAT R24G8 TYPELESS, bind flag D3D11 BIND DEPTH STENCIL D3D11 BIND SHADER RESOURCE and the depth stencil view format DXGI FORMAT D24 UNORM S8 UINT, everything is correct. Also, there are no problems when the depth buffer texture format is DXGI FORMAT R32G8X24 TYPELESS and the depth stencil view format is DXGI FORMAT D32 FLOAT S8X24 UINT. However, when the depth buffer format is DXGI FORMAT R32 TYPELESS, and the depth stencil view format is DXGI FORMAT D32 FLOAT, the whole geometry is not rendered at all, only the clear color is visible. I used Visual Studio 2015's Graphics Debugger to check if the geometry is rendered as desired, but during the Output Merger stage the whole geometry is discarded because it failed the depth test. Every Direct3D function call returns no error and the Direct3D debugging output reports no error (only INFO messages about creation destruction of resources). I do not use the stencil functionality at all, and it is disabled. I use a Windows 7 virtual machine as a developer machine and using DXGI FORMAT R32 TYPELESS and DXGI FORMAT D32 FLOAT worked flawlessly before I switched from a Windows 7 host to an Arch Linux host, because the old hard drive started to fail and the operating system was unable to read its own files during boot. After I switched the host operating system, this problem started to occur inside the virtual machine. Is it possible to have a bug somewhere else in my code? Is there a limitation when using DXGI FORMAT D32 FLOAT and sometimes it may not be possible to use DXGI FORMAT D32 FLOAT or the other depth formats on every machine (considering D3D11 feature level 10.0 is available)? Or is this a bug somewhere else, possibly in VMware player or Linux or Bumblebee (Optimus Intel HD 4000 GeForce GTX 650M)?


DXGI Frame rate drops from 8000 FPS to 1500 FPS when switching to full screen mode I've created a simple app with a DirectX11 device and swap chain (IDXGISwapChain). All it does is clear the screen with a color and call Present(0, 0) on the swap chain. The app handles full screen windowed mode transition by itself (I passed DXGI MWA NO WINDOW CHANGES) to the IDXGIFactory object. After switching from windowed mode to full screen, the VS graphics profiler shows a drop in the frame rate, from 8000 FPS (window mode) to 1500 FPS (full screen mode). I think I'm resizing my buffers properly (in response to WM SIZE), I'm not getting any warnings about presentation inefficiencies in the debug window. The mode used to create the swap chain is obtained by enumerating the supported modes of the output device and selecting the proper resolution info. Isn't full screen mode supposed to be more efficient (as I understand, it can simply do a flip instead of a bit blit). The code is here in case you want to take a look.


Frustum culling instancing I've implemented instancing in my app and right now I have an instance buffer holding position data for all instances. But I'd like to also implement frustum culling which would cull some of the instances depending on the camera view. Now, how can I render only some of the instances in the buffer but not all? Do I have to rebuild the buffer every frame (so that it only holds visible instances) or is there a way in DirectX 11 to "tell" API which instances from the buffer I want drawn?


Figure out why vertices are clipped I am trying to figure out why, at sharp cutoffs in geometry, some vertices seems to be culled for some reason. I have a heightmap for demonstrating it like this And this is the result I get See the red rectangles where the geometry is just cut and the skybox is shown behind. I am not quite sure where to start looking where the problem might be. I know for a fact it's not colliding with the z near value. Any non steep geometry is fine. Any pointers? EDIT at certain angles, re orienting the camera ever so slightly changes things, like this


D3D11 Can only Pixel Shader and Compute Shader stages write to buffers? I am reading Practical Rendering and Computation with Direct3D 11. In the book the D3D11 pipeline is often described with this image In the Chapter about resources, Paragraph about buffers, I understood that the only stages that can write to buffers are the Pixel Shader and the Compute Shader, using Unordered Access Views. Is it correct? If so, why? Is it because of the inherent architecture of GPUs? Then, what would be the typical method to output data from a different stage? For example, how could one get the result of a computation done in the vertex shader, without needing to pass through the other stages?


Fix Pixel Shader "Stage did not run. No output" I'm trying to set up a minimal D3D11 renderer but fail to get the pixel shader stage to run. The available answers here or the ones I found through Google couldn't help me, unfortunately. Using Visual Studio's Graphics Debugger I could verify that my vertices are set correctly and the vertex shader also runs as expected. The debug layer doesn't report any issues either. As a test I disabled depth testing, stencil testing and backface culling as shown below with no changes. I made sure that the viewport is set correctly as well as this seems to be a common source of this problem. At this moment I can't think of any other cause for this issue and would be happy about any advice of what else to look out for. Disable depth stencil test D3D11 DEPTH STENCIL DESC dsstate desc dsstate desc.DepthEnable false dsstate desc.StencilEnable false dsstate desc.DepthFunc D3D11 COMPARISON ALWAYS dsstate desc.DepthWriteMask D3D11 DEPTH WRITE MASK ALL dsstate desc.BackFace.StencilFailOp D3D11 STENCIL OP KEEP dsstate desc.BackFace.StencilPassOp D3D11 STENCIL OP KEEP dsstate desc.BackFace.StencilFunc D3D11 COMPARISON ALWAYS dsstate desc.FrontFace.StencilFailOp D3D11 STENCIL OP KEEP dsstate desc.FrontFace.StencilPassOp D3D11 STENCIL OP KEEP dsstate desc.FrontFace.StencilFunc D3D11 COMPARISON ALWAYS d3d11device gt CreateDepthStencilState( amp ds state, amp this gt ds state) d3d11context gt OMSetDepthStencilState(this gt ds state, 0) Disable backface culling D3D11 RASTERIZER DESC rasterizer desc rasterizer desc.AntialiasedLineEnable false rasterizer desc.CullMode D3D11 CULL NONE rasterizer desc.DepthBias 0 rasterizer desc.DepthBiasClamp 0.0f rasterizer desc.DepthClipEnable false rasterizer desc.FillMode D3D11 FILL SOLID rasterizer desc.FrontCounterClockwise true rasterizer desc.MultisampleEnable false rasterizer desc.ScissorEnable false rasterizer desc.SlopeScaledDepthBias 0.0f d3d11device gt CreateRasterizerState( amp rasterizer desc, amp this gt rasterizer state) d3d11context gt RSSetState(this gt rasterizer state) Pipeline view in debugger Vertex shader transformation Vertex shader struct VertexIn float3 position POSITION float3 normal NORMAL float4 color COLOR struct VertexOut float4 color COLOR float4 position SV POSITION VertexOut main(VertexIn i) VertexOut o o.position float4(i.position, 1.0f) o.color i.color return o Pixel shader struct FragmentIn float4 color COLOR float4 pos SV POSITION float4 main(FragmentIn i) SV TARGET return float4(1.0f, 0.0f, 0.0f, 1.0f)


Using DirectWrite to write text on a IDirect3DTexture9 I'm trying to write text using the DirectWrite API on a IDirect3DTexture9. I've heard that people were capable of doing this but I do not see directly how I can glue these two APIs together. It seems I need a IDXGISurface to create a valid ID2D1RenderTarget (with which I can draw the text). I can get this by creating a surface for the Window. But I think the idea is that I use the IDirect3DTexture9 as a surface for the render target so that I can use whatever is drawn on it in my application. I can get the underlying IDirect3DSurface9 from the IDrect3DTexture9 but then I have to convert it somehow to a IDXGISurface and this is where I'm stuck. Does anybody have a clue?


Frame timer does not show time I am currently using DirectX11 and MFC. The top of the window should tell me how long it takes to render the cube (in seconds). At the moment the cube is rendered but when I try to work out how many seconds it took to render the cube I keep getting 0 on the top of the window. This cannot be right. Help please? This is my Ondraw function void CLearningVisualCView OnDraw(CDC pDC) I want the OnDraw function to create the cube.. CString TimerReports TODO add draw code for native data here CLearningVisualCDoc pDoc GetDocument() ASSERT VALID(pDoc) if (!pDoc) return Timer.GetStartTime() Render() This renders the cube Timer.GetEndTime() The counts stopwatch ends. Timer.DeltaCountDifference(Timer.StartTime, Timer.EndTime) Timer.GetSecondsPerCount() Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount) TimerReports.Format( T(" .100I64d"), Timer.Time) TimerReports.Format( T(" .5I64d"), Timer.FrameTime(Timer.DeltaCounts, Timer.SecondsPerCount)) This converts the DeltaCountDifference into a CString. It has 5 d.p. AfxGetMainWnd() gt SetWindowText(TimerReports) This displays my count difference to the top of the window. This is my Timer class include "stdafx.h" include "GameTimer.h" GameTimer GameTimer() QueryPerformanceFrequency((LARGE INTEGER ) amp countsPerSec) SecondsPerCount 1.0 (double)countsPerSec GameTimer GameTimer() int64 GameTimer GetStartTime() QueryPerformanceCounter((LARGE INTEGER ) amp StartTime) return StartTime int64 GameTimer GetEndTime() QueryPerformanceCounter((LARGE INTEGER ) amp EndTime) return EndTime The int64 amp are references. We will link them to the StartTime and the EndTime in the CLearningVisualCView OnDraw(). This is done by adding them as arguments. int64 GameTimer DeltaCountDifference( int64 amp TimeA, int64 amp TimeB) int64 DeltaCounts TimeB TimeA return DeltaCounts float GameTimer GetSecondsPerCount() QueryPerformanceFrequency((LARGE INTEGER ) amp CountsPerSecond) SecondsPerCount 1 CountsPerSecond return SecondsPerCount int64 GameTimer FrameTime( int64 amp TheDeltaCounts, float amp SecsPerCount) Time TheDeltaCounts SecsPerCount return Time