Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Danbo Daxter! posted:

I am not interested in 3D games at all really, 2D is more my sort of thing. Are there any decent tutorials out there for using DirectX (or hell, OpenGL or some other graphics API) in a 2D context? Most of the ones I find seem to focus on 3D, and that seems like a gigantic branch of games development that I'ld rather not go near if I can help it.

Part of the reason you'll see so few tutorials is because 2d projects, at least in Direct3d (I'm not terribly familiar with OpenGL), are relatively straightforward. Books like this spend about one chapter covering the D3DXSprite and D3DXFont interfaces because they really are that simple. Anything you need to know about their usage can be gleaned fairly easily from the actual DirectX SDK documentation once you're past all the normal DirectX boilerplate code. If you're going to go beyond D3DXFont/D3DXSprite* you'll need to know at least the basics of working with Direct3d "normally" so any tutorial or book will do.

Other than that, I agree that using SDL or Clanlib is a good idea, but learning to use Direct3d or OpenGL "raw" at some point wouldn't hurt either.

*In my experience D3DXSprite should pretty much be sufficient for anything. The only good reason I can imagine to roll your own sprite class/library would be if the D3DXSprite interface was missing some feature you needed. D3DXFont, on the other hand, is still abysmally slow for text-heavy projects.

Adbot
ADBOT LOVES YOU

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

SnakeByte posted:

http://www.amazon.com/Introduction-Game-Programming-Direct-9-0c/dp/1598220160/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198303208&sr=8-1

Just bought this book from Barnes & Noble. You can get it for $30 on Amazon. So far it's been an incredible read. The first three chapters went from vectors, to rays, to matrices, and it never lost me! I'm about to get into Part II (Nerdy DX Goodness.)

Yeah, I've recommended this book here before and I still say it's the only C++/DirectX book that's actually worth buying. Most online tutorials are terrible, so if you can't get what you need from the SDK documentation it's probably the best way to learn the API. The math coverage is a little light, though, so I think picking up something to supplement that (assuming you don't already know everything you need) isn't a bad idea.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
Your delta value should be the time differential between frames. Here's an example of some boilerplate code to handle something like this in a fairly simple way:

code:
LARGE_INTEGER ticksPerSec = 0;
QueryPerformanceFrequency(&ticksPerSec);
float secsPerTick = 1.f / static_cast<float>(ticksPerSec);

LARGE_INTEGER prevTime = 0;
QueryPerformanceCounter(&prevTime);

while (// !quit condition goes here)
{
    if ( //peekmessage conditional)
    {
        // windows message handling
    }
    else
    {
        // game code up in here

        LARGE_INTEGER currTime = 0;
        QueryPerformanceCounter(&currTime);
        float delta = (currTime - prevTime) * secsPerTick;

        update(delta);
        render(delta);

        prevTime = currTime;
    }
}
MSDN has information on QueryPerformanceCounter and QueryPerformanceFrequency.

QueryPerformanceCounter() provides a much higher resolution timer than what you'd get with GetTickCount(). It gives you a value in "counts." The actual length of a single count is static as long as the system is running, but it might vary from system to system. To determine the actual length of a count you use QueryPerformanceFrequency(), which provides you with the number of counts per second. You can use this (1 / frequency) to determine the length of a single count. Multiply this value by the count difference between frames and you've got your frametime in seconds.

If your animations are timed in seconds it's trivial to use your frametime to keep them framerate independent. Let's say you wanted a sprite to move ten pixels to the right every second:

code:
void updateSprite(float delta)
{
     float displacement = 10 * delta;
     x += displacement;
}
Your sprite will always move ten pixels right for every second that passes, regardless of the time spent rendering and updating each frame. Faster systems will provide smoother, not faster, animation. Hope this helps. :)

Edit- Just realized that I completely missed part of your question. Your delta is your frametime, which is the inverse of your framerate. Taking your average framerate is easy and something you can do trivially in your update function:

code:
static const float interval = 1.f;
static float numFrames = 0.f;
static float timeElapsed = 0.f;

numFrames += 1.f; // each time through your update function one frame has been rendered
timeElapsed += delta; // and delta time has passed

if (timeElapsed >= interval)
{
    // the number of frames rendered since the last time interval passed by is your average framerate
    // over 1 second, in this case
    fps = numFrames;
    timeElapsed = 0.f;
    numFrames = 0.f;
}

Paradoxish fucked around with this message at 07:16 on May 25, 2008

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Gary the Llama posted:

Edit: This fixed it but I'm not sure if it's correct. (Although Microsoft's documentation seems to think it's correct. Thoughts?)

Yep, that's right. That was my fault there. Like ehnus suggested, you should use __int64s and just do a cast for the counter calls. I was writing that code off the top of my head and I just used LARGE_INTEGERs to reduce the number of casts and make it less confusing. The fact that LARGE_INTEGER is actually a union totally slipped my mind, so I guess I just ended up making it more confusing. :v:

edit- For what it's worth, the QuadPart of a LARGE_INTEGER is just a typedef'd __int64 anyway, so it's really just a matter of semantics either way.

quote:

Edit 2x: Also, in my Update method, do I need to keep doing this? I assume the answer is no and I can just go ahead and move my stuff like you said.

Right, as long as you can somehow time your movement in pixels (or units or whatever) per second you can just multiply by the frame delta and there's no problem.

ehnus posted:

Something to be aware of in regards to QueryPerformanceCounter is that it's very expensive, on the order of 3000-4000 cycles per call. You might want to beware if you're using it in many places in your code

For most game applications you shouldn't need more than one call per frame. Not that one call per frame should have any impact at all on performance, but is there a faster alternative I'm not aware of?

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Gary the Llama posted:

My delta is always higher than interval.

Delta is usually something like 1.6761907e-006, so it's never even entering the inside of the if statement. Any thoughts on what I'm doing wrong?

Ack, I've been kind of busy for the last week so I totally forgot about this thread. If you're still having problems would you mind posting the full code you're using? You're multiplying the time delta from querying the performance counter by the frequency of the counter, right? Otherwise you'll just end up with the difference in ticks, which is going to be significantly larger than the difference in seconds.

This is the exact code I'm using for my game dev competition entry in games. I didn't want to copy this directly before because there's extra crap in there that gets in the way of the timing code, but I figured it might be useful if you're having issues:

code:

        __int64 ticksPerSec = 0;
	QueryPerformanceFrequency((LARGE_INTEGER*)&ticksPerSec);
	float ticksPerCnt = 1.0f / (float)ticksPerSec;

	__int64 prevTimeStamp = 0;
	QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);

	// Pump any received messages and transfer control over to the game logic and
	// rendering code when there aren't any
	while(msg.message != WM_QUIT)
	{
		if (PeekMessage ( &msg, 0, 0, 0, PM_REMOVE ))
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{
			if ( isPaused() )
			{
				Sleep(20);
				continue;
			}

			if ( !deviceLost() && !mAppClosed )
			{
				__int64 currTimeStamp = 0;
				QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
				float dt = (currTimeStamp - prevTimeStamp) * ticksPerCnt;
				
				updateScene(dt);

				if (!mAppClosed)
				{
					renderScene();
				}

				prevTimeStamp = currTimeStamp;
			}
		}
	}

Paradoxish fucked around with this message at 16:24 on Jun 3, 2008

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

StickGuy posted:

I'm not sure how scalable this approach is when you have, for example, many different types of objects that require special rendering techniques. It would get a bit messy to have all of that in one place.

In a general sense you could keep that information in the actual Sprite (or RenderableObject or whatever the hell) structure. That would allow you to sort your sprites by rendering technique and still basically localize things in the way TSDK is suggesting. It'd actually be pretty trivial to do something like this if you're using programmable shaders.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
Here's a simple rule of thumb that isn't beaten into the head of hobbyist game developers often enough: if you end up with a complete, functional game then it doesn't matter if the code it's built on sucks. This is actually a corollary to the idea that you should build games and not engines, but it deserves specific mention because it's so important. If you've never worked on a project like this before then it's difficult to plan your code on paper before you've even started. Improving small, working chunks of code later on is much easier and refactoring is an important skill to develop anyway.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Unormal posted:

Might use a variation of Voronoi something or other, like this:

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/
e: http://en.wikipedia.org/wiki/Voronoi_diagram

Coincidentally, I've been working on a world generation project in C# inspired pretty heavily by your first link. I ended up taking a weekend long detour to implement my own Fortune's algorithm library in C++ because I'm a masochist and I hate myself and my life, but I'm pretty happy with my results (of just the diagram generation since I've barely started on the actual world gen stuff) so far. If you're working in C# and not a silly person like me, this is a reasonable ready-to-use solution. I've been using that to confirm the results of my own library.

And just because I think Voronoi diagrams are really, really pretty, here are a couple of sample outputs from my project so far:



With a little bit of noise added to the polygon edges, Voronoi diagrams really would be great for maps divided up into provinces or regions.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
Another relatively simple idea might be to predefine the number of territories you want and then place that many seed hexes on the map (possibly in a way that prevents any two seeds from starting too close together). Then you could grow each territory from its seed point by randomly determining if the seed "spreads" to each of its neighbors, reducing the chance of spread for every hex you move outward from the first. Once you're done, you can fill in any gaps by connecting them to neighboring territories, leaving them neutral, or whatever. You'd end up with more solid territories and fewer snaky, meandering ones. Depends on what you're going for, ultimately.

I might play around with this idea a little bit when I get home and see what kind of results it produces. If your map has things like resources or hex values you could even weight the "growth" of territories so they naturally expand to encompass nearby valuable spaces.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
So I decided to try out the method I described in my last post for randomly generated territories on a hex grid. It, uh, well:



I actually think it kind of, sort of works okay, aside from its unfortunate tendency to produce giant hex tile penises when a territory only has a narrow gap to grow down. On the other hand, it's relatively simple compared to using Voronoi diagrams with a hex grid. If I can get it to work a little better I'll put the code up, but it's basically what I laid out in my last post with a few tweaks:
  • Any territory below a minimum size (5 hexes in this case) gets culled and its hexes go back into the pool of open hexes.
  • Once all the territories are generated a good portion of the map is still open, so iterate over all the open tiles and assign them to the neighboring territory (if there is one) with the fewest hexes of its own. Keep doing that until all the hexes are used up.
Right now the chance that a territory grows from a hex it already owns is based entirely on how far that hex is from the territory's original seed hex. I think the penis problem could probably be solved pretty easily by also taking into account the number of "friendly" hexes that are nearby.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
I seem to be posting an awful lot on this page. Sorry. :(

I ended up getting this to work a little bit better, so I figured I'd share since I'm reasonably happy with the results for an hour or so of work:



Source code here in case anyone actually has a use for it: http://pastebin.com/i6RViEYL. In general it would probably work pretty well if you were generating this as an overlay on a terrain map where the growth function could be influenced by natural borders like forests, rivers, etc.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Dr. Dos posted:



One small suggestion: you might want to consider increasing the padding around each building so your district boxes don't cut off their rooftops and sides.

Also, have you considered only drawing lines around the edge of a district rather than around every building in it? Your tint would make more sense in that case and you'd reduce the amount of visual noise quite a bit. That might help since it sounds like your gameplay depends on the color of the buildings.

Other than that I'm loving your Windows 3.1 style. :)

Paradoxish fucked around with this message at 20:11 on May 6, 2012

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

MarsMattel posted:

Accelerated C++ is the book I most often see recommended. Thinking in C++ is (or used to be) a free online book that you can probably dip in and out of. There's also the C++ FAQ Lite (not to be confused with the C++ FQA).

Accelerated C++ is probably the best C++ book around if you're looking to pick up a practical understanding of the language as quickly as possible. I think I first read it about nine years ago and I still haven't come across anything that I'd feel more comfortable recommending to people who are looking for a solid introduction to C++ without an excessive amount of hand holding. Thinking in C++ also happens to be really good, although it's much longer. The second volume in particular is great if you're looking to get a deeper understanding of intermediate topics.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?

Orzo posted:

My (C#) game engine uses Lua scripts for all game logic. I am considering switching to C# scripting for a number of reasons. Does anyone have any good (preferably highly technical) articles on how Unity does this? I have an idea on how to go about accomplishing what I need (aggregate all scripts and use CSharpCodeCompiler to dynamically generate an assembly) but I want to see if there's any gotchas or concepts that I haven't considered yet.

I don't suppose you've turned up any resources on this? I'm actually in the process of doing something similar (my game's "events" are scripted in C#), and I've been trying to find best practices or at least good examples of using C# as an embedded scripting language inside a C# program. I sort of just charged ahead and did my own thing, but I'd definitely feel a lot more comfortable if I could see how other people approached this. What I have right now looks more like a plugin system than an actual scripting engine.

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
Can anyone point me at some good resources for working with Unity's new UI system primarily through code? I'm fairly new to Unity and I feel like Unity's documentation is telling me very little, and I keep running into strange problems that I can't figure out. In particular, I'm having a ton of trouble with positioning elements properly. Should I always be using rectTransform to set an element's position? What should I be setting - localPosition? When does a ContentSizeFitter component actually update an object's rectTransform? Are the values being given in pixels or Unity units or what?

Sorry if these seem like idiotic questions, but I feel like I'm really missing something with how these UI components are supposed to be used in scripts. For a more concrete example: let's say I have a prefab text label and I want to instantiate some number of them at runtime and display them one on top of the other, starting at the top of the screen and working down. What's the proper way to accomplish something like that via a C# script?

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
I'm having a problem in Unity that's got me on the verge of ripping my hair out. I'm trying to get Unity to play nicely with pixel art at various resolutions and scaling modes. I'm going to do a real bad job explaining this, so I apologize in advance:

I'm using two cameras. There's an offscreen camera that outputs to a render texture. The offscreen camera's orthographic size is set based on a set pixels per unit and target render resolution. If the game is supposed to render at 800x600 with 32 PPU sprites, then the orthographic size ends up being 600 / 32 / 2 = 9.375 regardless of screen resolution. The target resolution can be set based on the screen resolution, but it doesn't really matter - the point is that the offscreen texture always ends up containing a pixel perfect version of the scene with no scaling. Sprites are all intended to use Unity's sprite shader with pixel snap on or another shader that prevents sprites from rendering off pixel boundaries.

The second camera does nothing except render a single quad textured using the output from the offscreen camera. The quad is scaled up to whatever amount of scaling you want. So if you want your pixel art to render at 2x, the quad is twice the size of the backing texture. Right now this camera's orthographic size is always set so that 1 screen pixel = 1 world unit, but it doesn't (or shouldn't, as far as I know?) really matter.

Here's the problem: everything works perfectly if the output resolution's height is even. If the output resolution's height is odd, the texture on the output quad ends up being off by 1 pixel. So, for example, setting a weird resolution like 534x398 works perfectly, whereas 534x397 doesn't. This is the case even if the scaled quad is much, much smaller than the actual resolution. It's hard to explain exactly what's wrong, so I'll try to use some pictures:


This is the offscreen texture if the target resolution is 100x50.


Here's the same image scaled up by 4x just so you can see it more clearly. It's hard to tell, but everything should be perfect. All the checker squares should be exactly 4x4 pixels.


And here it is as it's actually output in Unity with an editor resolution of 534x397. This is also scaled up by 4x. Ignore the yellow border, that's just because the scene resolution is larger than the quad being rendered. If you look super closely, you'll see that the top row is 5 pixels high, the bottom row is 3 pixels high, and every other row is 4 pixels high as it should be.

I'm at a complete loss for why this is happening, and why it only happens with odd screen resolutions. It obviously has to have something to do with the orthographic size of the output camera since that's the only thing actually affected by screen resolution, but I don't know why it should affect anything. The quad is exactly 200 pixels high as it should be, but for some reason the texture is being applied unevenly at the top and bottom.

Help me. I'm at my wit's end here. :(

Edit- I should add that the error amount is always 1 pixel. There's always exactly 1 extra pixel at the top and 1 missing pixel at the bottom, regardless of how much the output is scaled by or how large the output screen resolution is.

Double Edit- And I'm a loving idiot. After typing up this absurdly long post, I'm pretty sure I solved my problem. With odd screen heights, the orthographic size of the camera was causing (0, 0) to sit in the center of a row of pixels. Moving the output quad up by half a unit with odd screen resolutions fixed everything. :downs:

Paradoxish fucked around with this message at 20:38 on Mar 16, 2016

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
That was my original solution, but it irked me a little bit that it wasn't behaving properly at any resolution. Honestly it's not like this really matters since there's no particular reason to support odd screen resolutions, I just hate it when things don't work consistently.

Adbot
ADBOT LOVES YOU

Paradoxish
Dec 19, 2003

Will you stop going crazy in there?
Anyone have some experience with working with textures in Unity editor scripts? I'm making what I thought was a pretty simple editor tool, but I'm beating my head against what feels like a wildly inconsistent problem.

I need to be able to read data from a Texture2D in the editor, but I don't want to actually alter the texture or its import settings. I figured this would be a pretty straightforward matter of setting the isReadable flag with the TextureImporter, doing the work that I need to do, and then setting it back. This isn't working for me, though, at least not consistently. Nine out of ten times Unity will complain that the texture isn't readable when I try to use any of the GetPixels methods, but sometimes it works fine? Here's my code:

code:
var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(textureFile)) as TextureImporter;
importer.isReadable = true;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

// Work gets done here, in theory

importer.isReadable = false;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
I'm sure it's something simple going on here, but I'm at a complete loss. Halp.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply