• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Muzzy A

Most Optimized way to draw a circle DirectX

15 posts in this topic

Hello, I've made a 2D scale model of the solar system, it shows the orbits, which is a circle i draw. There is a circle being drawn for each planet, as I'm adding more features the program is getting extremely laggy sometimes due to all of the circles. I'm looking for a more optimized way to draw circles.

The way I'm doing it now is HIGHLY unoptimized I'm pretty sure, I'm using D3DXLine the circle gets drawn with however many lines i tell it. For planets that are farther away i have to give it a whopping 100 sides (D3DXlines) to draw separately for the circle to not show straight edges.

I KNOW there's a better way to do it than the way I am

[code]
void DrawCircle( const Vector2 &Center,float Radius,Color color,unsigned short Sides /*= 30*/ )
{
float Angle = ToRadian(360.0f/Sides);

float Cos = cos(Angle);
float Sin = sin(Angle);

Vector2 vec(Radius,0);

for(unsigned short i = 0;i < Sides;++i)
{
Vector2 rot( Cos*vec.x - Sin*vec.y , Sin*vec.x + Cos*vec.y );
rot += Center;
vec += Center;
DrawLine(vec,rot,color);
vec = rot - Center;
}
}
void DrawLine( const Vector2 &Point1,const Vector2 &Point2,Color &color,unsigned short BorderWidth /*= 1*/ )
{
Vector2 points[2] = { Point1,Point2 };

d3dLine->Begin();

d3dLine->Draw(points,2,color);

d3dLine->End();
}

// Anyone have a better way to draw a circle in Direct X, a 2D simulation of the Solar System should'nt lag like mine does
// As soon as I stop drawing the circles, the program is runs smoothly no lag at all
[/code] Edited by Muzzy A
0

Share this post


Link to post
Share on other sites
I'm always astonished that the latest platforms on the latest computers still offer opportunities for 286-like performance. ;)

I'm not a D3D expert, but this thread might help:
[url="http://www.gamedev.net/topic/259860-drawing-circle-in-directx/"]http://www.gamedev.net/topic/259860-drawing-circle-in-directx/[/url]

I'm guessing the speed problem is because you're doing many drawcalls in separate batches, e.g. each line drawn starts with d3dLine->Begin() and ends with d3dLine->End(). The sample code in that forum post uses a D3DPT_LINESTRIP, which is probably a more optimal way to draw a series of lines.
1

Share this post


Link to post
Share on other sites
Thanks all look into that when i get home tomorrow, but for now bed. night, thanks!
0

Share this post


Link to post
Share on other sites
Yeah, 100 lines is nothing, batch them up!

Drawing a circle as a bunch of lines is actually nothing strange and standard practice for drawing curves on graphics hardware.

You probably will see a big improvement by just moving the "Begin" and "End" to outside of the loop.
You could even put the Begin and End outside of the loop drawing all your circles.

Next step is building the vertex buffer from all the points in the circle and, as jeffery suggests, send them all in with a single Draw-call.
1

Share this post


Link to post
Share on other sites
[quote name='___' timestamp='1338372759' post='4944616']
vertex arrays
[/quote]
ah you reminded me of something

ID3DLine::Draw(); takes a list of vectors, and the 2nd parameter is how many vectors there are in the list. I can make alot of use out of that. Thanks.

[quote name='Olof Hedman' timestamp='1338365865' post='4944597']
Yeah, 100 lines is nothing, batch them up!

Drawing a circle as a bunch of lines is actually nothing strange and standard practice for drawing curves on graphics hardware.
[/quote]
I actually assumed that the way I was doing it was not really a good way to go, Good to know I was in the right direction with it =D. I don't know why I couldn't notice that doing a 'begin()' and 'end()' over and over to draw a circle wasn't good. It's like having a word on the tip of your tongue and you just can't get it lol.

Thanks for the support guys - Muzzy A
0

Share this post


Link to post
Share on other sites
One thing you can do to greatly optimize this little piece of code is to create the vertices for a circle beforehand.

make the circle have a radius of 1 with the center at (0,0), then use matrix transformations to move and scale the circle.


[CODE]
#define CircleResolution 100

static Vector2 gCircleData[CircleResolution];

void InitCircle()
{
for (int i = 0; i < CircleResolution; ++i)
{
gCircleData[i].x = cos(2 * PI * i / CircleResolution);
gCircleData[i].y = sin(2 * PI * i / CircleResolution);
}
}

// then to draw your cirlce
void DrawCircle( const Vector2 &Center,float Radius,Color color)
{
// save word matrix transformation
// set worldtransform = TranslateMatrix(Center) * ScaleMatrix(Radius) * currentWordTransform

d3dLine->Begin();

d3dLine->Draw(gCircleData, CircleResolution,color);

d3dLine->End();

// restore previous world transform

}
[/CODE]

By doing it this way you avoid calculating sin/cos all the time which can be expensive. If you want to use lower resolution circles for smaller circles I would have a few premade circles at different resolutions and you choose from those few. Anyway, those are my two cents.


By doing it this way you
1

Share this post


Link to post
Share on other sites
I haven't used D3D in many years, but last time I used it, I recall that the UP (user pointer to CPU memory... which would often mean a copy from CPU to GPU RAM every time you call DrawPrimitiveUP) functions were inherently not as fast as using a vertex buffer and non-UP functions. I assume that this ID3DXLine::Draw function that takes a user pointer to CPU memory would suffer from the same "problem".

You asked for the most optimal... like ____ hints at, if your circles are static from frame to frame, then stuff them all into a vertex buffer / index buffer pair and go to town (yes, an index buffer does make a difference in performance). This way you only transfer the data across the bus once (and well, once again whenever the device is lost and regained, but you get the idea). That would likely be the most optimal, if you want to get nitpicky. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] This is all assuming that the latest D3D still has vertex / index buffers. Edited by taby
0

Share this post


Link to post
Share on other sites
[quote]This is all assuming that the latest D3D still has vertex / index buffers.[/quote]
It does, and furthermore starting from D3D10, devices can no longer be lost (they can, however, be removed, such as when a laptop switches between two graphics cards or your graphics driver fails, but recovery is easier as you pretty much just go through the whole graphics initialization code again instead of picking specific objects to recreate).

Note that for D3D9 which is being used here, I'm pretty sure a vertex/index buffer solution would be good enough. But it depends on what you use the circles for - perhaps it is, in fact, more efficient to simply render a quad and draw a texture of a circle over it (especially if you are already drawing a texture on top of the circle). Edited by Bacterius
2

Share this post


Link to post
Share on other sites
[quote name='Bacterius' timestamp='1338560290' post='4945310']
Note that for D3D9 which is being used here, I'm pretty sure a vertex/index buffer solution would be good enough. But it depends on what you use the circles for - perhaps it is, in fact, more efficient to simply render a quad and draw a texture of a circle over it (especially if you are already drawing a texture on top of the circle).
[/quote]

Ya know, that's actually pretty brilliant!
0

Share this post


Link to post
Share on other sites
If you can use shaders you could draw fullscreen quad and specify circle position/radius. With little maths inside shader you could have different colors, position, line width, etc.
1

Share this post


Link to post
Share on other sites
Why are you using a fullscreen quad (using a constant buffer for the circle positions and orientations?) instead of drawing a quad for each circle (using a geometry shader or point sprites to create it from a single point for example)? What method would you use to render the circles with different line widths? The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math*.

* Well, I would try to solve a [s]quadratic[/s] quartic equation, is there any better method? Edited by apatriarca
0

Share this post


Link to post
Share on other sites
[quote]Why are you using a fullscreen quad (using a constant buffer for the circle positions and orientations?) instead of drawing a quad for each circle (using a geometry shader or point sprites to create it from a single point for example)?[/quote]
I believe the OP is using D3D9, making geometry shaders a no-go. That said, I was merely referring to the possibility of drawing the circle using a texture overlay instead of actual vertices, the cost could then be negated by the circle already being textured anyway later on. Vertices aren't always the be all end all of rendering geometry.

[quote]The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math*. * Well, I would try to solve a quadratic equation, is there any better method?[/quote]
Off-topic, but ray-tracing a torus is in fact solving a quartic equation (which gets really messy very quickly). You most definitely don't want to use the [url="http://planetmath.org/encyclopedia/quarticformula.html"]analytic solution[/url], but there are numerical solutions which are satisfying (if convoluted). A quadratic equation is for a sphere.
0

Share this post


Link to post
Share on other sites
[quote name='Bacterius' timestamp='1338649733' post='4945594']
Off-topic, but ray-tracing a torus is in fact solving a quartic equation (which gets really messy very quickly). You most definitely don't want to use the analytic solution, but there are numerical solutions which are satisfying (if convoluted). A quadratic equation is for a sphere.
[/quote]
Yes, sure. It was a typo. A quadratic equation is actually very simple math.. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] For a quartic equation you surely use numerical methods (Ferrari's method is not really well suited for GPUs). I was just curious whether there is a better solution to render a circle with different line widths in a shader...

[quote name='Bacterius' timestamp='1338649733' post='4945594']
I believe the OP is using D3D9, making geometry shaders a no-go. That said, I was merely referring to the possibility of drawing the circle using a texture overlay instead of actual vertices, the cost could then be negated by the circle already being textured anyway later on. Vertices aren't always the be all end all of rendering geometry.
[/quote]
I was actually replying to Ripiz. The only problem I see in your method is that it may give "wrong" results at some angles, i.e. when the circle axis is perpendicular to the eye vector. But I would probably use your solution anyway. Edited by apatriarca
1

Share this post


Link to post
Share on other sites
[quote name='apatriarca' timestamp='1338648247' post='4945587']
What method would you use to render the circles with different line widths? The only one I have in mind is to ray-trace a torus and I wouldn't consider it simple math
[/quote]

Lets say vertexes in fullscreen quad contain 2D positions as texture coordinate (4 vertices = 4 different values). In the pixel shader they'll get interpolated giving 2D position at any given pixel. Then in pixel shader you can calculate whatever is needed.

[CODE]
float4 CirclePS(coord : TEXCOORD0) : COLOR0 {
float2 circleCenter = g_Center; // comes from constant buffer
float circleRadius = g_Radius; // comes from constant buffer
float lineWidth = g_Width; // comes from constant buffer
float2 currentPos = coord; // comes from interpolator

float distance = length(currentPos - currentPos); // distance from center to current position in space (2D plane)

if(distance >= circleRadius) // we're not too close
if(distance <= circleRadius + lineWidth) // and not too far
return float4(1, 0, 0, 1); // it's a line!

return float4(0, 0, 0, 0);
}
[/CODE] Edited by Ripiz
0

Share this post


Link to post
Share on other sites
[img]http://public.gamedev.net//public/style_emoticons/default/ohmy.png[/img] We are working in 2D!! It looks like I completely misunderstood the problem.. I was thinking about the rendering of circles in 3D and it was the reason I considered ray-tracing a torus. If we are in 2D, it is surely possible to draw circles with any line width in a shader and there is no problem with the texture solution.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0