Saturday, October 31, 2015

c++ - When several classes need to access the same data, where should the data be declared?



I have a basic 2D tower defense game in C++.


Each map is a separate class which inherits from GameState. The map delegates the logic and drawing code to each object in the game and sets data such as the map path. In pseudo-code the logic section might look something like this:


update():
for each creep in creeps:
creep.update()
for each tower in towers:
tower.update()
for each missile in missiles:
missile.update()


The objects (creeps, towers and missiles) are stored in vector-of-pointers. The towers must have access to the vector-of-creeps and the vector-of-missiles to create new missiles and identify targets.


The question is: where do I declare the vectors? Should they be members of the Map class, and passed as arguments to the tower.update() function? Or declared globally? Or are there other solutions I'm missing entirely?


When several classes need to access the same data, where should the data be declared?



Answer



When you need a single instance of a class throughout your program, we call that class a service. There are several standard methods of implementing services in programs:



  • Global variables. These are the easiest to implement, but the worst design. If you use too many global variables, you will quickly find yourself writing modules that rely on each other too much (strong-coupling), making the flow of logic very difficult to follow. Global variables are not multithreading-friendly. Global variables make tracking the lifetime of objects more difficult, and clutter the namespace. They are, however, the most performant option, so there are times when they can and should be used, but use them spareingly.


  • Singletons. About 10-15 years ago, singletons were the big design-pattern to know about. However, nowadays they are looked down upon. They are much easier to multi-thread, but you must limit their use to one thread at a time, which is not always what you want. Tracking lifetimes is just as difficult as with global variables.
    A typical singleton class will look something like this:



    class MyClass
    {
    private:
    static MyClass* _instance;
    MyClass() {} //private constructor

    public:
    static MyClass* getInstance();
    void method();
    };


    ...

    MyClass* MyClass::_instance = NULL;
    MyClass* MyClass::getInstance()
    {
    if(_instance == NULL)
    _instance = new MyClass(); //Not thread-safe version
    return _instance;


    //Note that _instance is *never* deleted -
    //it exists for the entire lifetime of the program!
    }


  • Dependency Injection (DI). This just means passing the service in as a constructor parameter. A service must already exist in order to pass it into a class, so there's no way for two services to rely on each other; in 98% of the cases, this is what you want (and for the other 2%, you can always create a setWhatever() method and pass in the service later). Because of this, DI doesn't have the same coupling problems as the other options. It can be used with multithreading, because each thread can simply have its own instance of every service (and share only those it absolutely needs to). It also makes code unit-testable, if you care about that.


    The problem with dependency injection is that it takes up more memory; now every instance of a class needs references to every service it will use. Also, it gets annoying to use when you have too many services; there are frameworks that mitigate this problem in other languages, but because of C++'s lack of reflection, DI frameworks in C++ tend to be even more work than just doing it manually.


    //Example of dependency injection
    class Tower
    {

    private:
    MissileCreationService* _missileCreator;
    CreepLocatorService* _creepLocator;
    public:
    Tower(MissileCreationService*, CreepLocatorService*);
    }

    //In order to create a tower, the creating-class must also have instances of
    // MissileCreationService and CreepLocatorService; thus, if we want to
    // add a new service to the Tower constructor, we must add it to the

    // constructor of every class which creates a Tower as well!
    //This is not a problem in languages like C# and Java, where you can use
    // a framework to create an instance and inject automatically.

    See this page (from the documentation for Ninject, a C# DI framework) for another example.


    Dependency injection is the usual solution for this problem, and is the answer you will see most highly upvoted to questions like this on StackOverflow.com. DI is a type of Inversion of Control (IoC).




  • Service Locator. Basically, just a class that holds an instance of every service. You can do it using reflection, or you can just add a new instance to it every time you want to create a new service. You still have the same problem as before - How do classes access this locator? - which can be solved in any of the above ways, but now you only need to do it for your ServiceLocator class, rather than for dozens of services. This method is also unit-testable, if you care about that sort of thing.


    Service Locators are another form of Inversion of Control (IoC). Usually, frameworks that do automatic dependency injection will also have a service locator.



    XNA (Microsoft's C# game programming framework) includes a service locator; to learn more about it, see this answer.






By the way, IMHO the towers should not know about the creeps. Unless you are planning on simply looping over the list of creeps for every tower, you'll probably want to implement some nontrivial space partitioning; and that sort of logic doesn't belong in the towers class.


Friday, October 30, 2015

Implementing a build queue in a browser based game


I need to be able to execute certain events at a given time in my game, for example, say the player "Builds a building" this building should take 15mins to process. Implementing this seems straightforward enough, simply enter the event into the database and execute the event when the time comes for it to be completed.


However, it is my understanding that i would need a script that is running permanently on the server and continually checks the event database for delayed events to execute and process them as needed. My question is, is this the right approach or should i be tackling the "event que" differently?



Some of the events that will be processed can effect many different players so they would need to happen in real time, as opposed to be lazy loaded.


You can see similar such event queues in browser games such as travian, grepolis etc.


Update - If i was to implement a purely lazy load method, are there any flaws in the following pseudo code?


    ## upon player_x pages load

## start a loop that will only exit once all needed events have been processed

## check for any events initiated by player_x that are overdue

## get event and lock it for processing


## does this event involve another players object?

## if it does, then lets check if said object also has any events that should happen before this event

## if it has, then lets process one of those events instead, and loop again once processed

## if it doesnt have any previous events, then we're free to process this event, do it

## loop till all overdue events for player_x's object are done



collocations - Can I say 'I swam at the beach'?


I have come across the following sentence in New Round-Up 3 Pearson Education Limited 2010:



I swam at the beach last weekend.




I would have understood if it were 'at the seaside', but 'at the beach' strikes me as unusual.



Answer



At least to this American, "the seaside" seems too general for the specific action of "I swam". I generally think of "seaside" as referring to a coastal area in general, though perhaps this because (at least Merriam-Websters EL definition of seaside seems to think this) in AmE seaside is most often used as an adjective (e.g. the seaside town, a seaside hotel) rather than referring to the actual coast/strip of sand where one might swim. Additionally, the word seaside to me could be connoting any portion of the coast, whereas one primarily swims at specific sandy places: the beach.


c# - A simple map, four biomes, and how to distribute them


Here's the basic idea: I've got a Rogue-ish, perhaps Dwarf Fortress-ish game, with a randomly generated overworld and several dungeon entrances scattered around it. I already have the dungeons basically covered, but I'm stuck on an aspect of the overworld.


Said overworld, considered as a 2D map of screens, should have a perhaps blob-like distribution of four different themes or biomes -- grasslands, desert, snow and swamp, each with their own total amount of screens. Let's say the map is 8x8, which gives 64 unique screens. Half of those could be grasslands, a quarter desert, and swamp and snow get a quarter each:


mockup of a possible world map with towns and starting location, but no dungeon entrances


It seems palette reduction has made snow the same color as swamp. Originally, there were eight snow screens in the bottom corner, and a slightly staggered eight-screen swamp area in the middle. Sorry 'bout that, and please ignore the location markers.


The best I could get was some snaking shapes, and often enough with nonsensical combinations like desert snaking through snow (or vice versa). I can't for the life of me figure out how to get it nice and blobby, let alone having it make climatical (?) sense. So how do I generate a biome map like in the mockup?


Okay, by request: the world really isn't much bigger than that example, and what I need is just a way to spread some blobs that determine thematic appearances, with the extra limitation that snow can't touch desert. Screens don't scroll, and if a screen is set to "desert", there'll be no grass anywhere on it.




Answer



There are many ways to skin this cat, however one of the more interesting is using cellular automata. Begin with your empty grid and add a few seed starting cells in random locations. These should be of some basic non-mixed types of biomes. Say: Grass, Desert, Snow, Ocean.


Based on growth rules of your own design, which could feature some randomness (I don't care that it technically breaks the idea of CA, do you?) have them grown each step into the map. Additional rules can be such that if you are ocean and are next to grass or swamp, you might turn into swamp. If you are next to snow, you may become ice, if you are near desert, you may dry up and become desert too.


The same might be true for other mixes, and in theory even sub-mixes like frozen swamp, or tundra, or jungle sprouting from large expanses of forests that grew from large expanses of grassland.


The possibilities are endless, and can also be continual. As these rules are all simple, you can implement environments that shift over time. Combined with height information, and rules that take it into account, you can grow lakes and rivers, block the growth of forests over mountains and other fancy things.


That height map can be the result of perlin noise, or diamond square, or even whole other CA models. In fact, you could modify that map as time goes on as well by modelling plate tectonics, pushing up mountains, sinking in trenches, and even let rivers lower the landscape creating canyons.


This rabbit hole extends forever.


Unity: Unable to rearrange "Sorting Layer" for 2D game


Since yesterday I got a bit into game development with Unity (i've never done game development before), and I am currently making a small 2D game. I am attempting to rearrange the various layers in the "Sorting Layers" list. According to Unity's own official tutorial, you can simply drag & drop the layers around to rearrange them. However, when I click on one of the layers, I can not drag it anywhere.


Can someone help me out?



Answer



The elements that can be dragged to new positions will have a = sign next to it in the inspector. The other ones below cannot be dragged but can be set up however you like.



Here is a pic the highlighted Layer in sorting layers is draggable


enter image description here


Note: you must select edit layers button located in the Layers Dropdown Tab shown at the top middle in the pic to get the Tags & Layers Inspector Window.


Design Document Contents



What is the minimum content that a game design document should have?



Answer




I come from a different stream of life (TV Production), but it's basically the same. You need a production bible. But, to put it more simply - you need what you need and nothing more.



  • Character list

  • Levels list with each level set list (areas that need/deserve special attention)

  • Prop list


Each list contains layout sheets (or character layouts for characters - front, side, 3/4), notes, mechanics notes for animation, etc. Whatever you need or might need.


Story/Game production sheet.



  • Screenplay and X-Sheets for animators if you have a story and dialog/VO


  • Run through screenplay which describes game as though linearly progressed (if game is intricate enough to need it and is, of course, linear in nature)

  • Game mechanics per game/level/mini game with set goals, obstacles, rewards - you can do this per level list and only a big idea in run through screenplay


In short, whatever works for you and size/scope of your team.


How ofted do you use Future Perfect nowadays


How often do you use Future Perfect in the US and UK? How does it sound to you?



I will have visited Asia by the time I am 30 years old.


The mankind will have colonized Mars by 2030.




For example:



a) We use it (regularly, seldom).


b) We don't use it but it sounds nice.


c) We don't use it and it sounds awkward.




Answer



We use it when we need it, and don't really notice.


But it is not clearly needed in either of your examples. Simple predictions are ordinarily expressed with a will + infinitive future:




I will visit Asia by the time I am 30.
Mankind will colonize Mars by 2030. (Incidentally: no article with mankind)



But if your context establishes that such an event acts as 'background' for some other predicted event, a future perfect construction is called for. For instance:



I will have visited Asia and be ready to start writing my book about it by the time I am 30.


The only hope for the survival of the species is that mankind will have colonized Mars by the time our oil reserves run out in 2030.



You only use the future perfect if your story includes some future event—not just a date—to which the fp event is necessarily anterior.



prepositions - where do people say ON the weekend (geographically speaking)?


I've always been taught to say AT the weekend, not ON the weekend, but recently I've come across the following sentence: Clifton's very crowded ON the weekend.



It makes me wonder where native speakers in the UK or the USA use this preposition in this expression/phrase.



Answer



Because I've mentioned a post on Language Log, A weekend is not a surface, I think I should write about it a little, boiling it down to a short, useful post.


Though this question is only about on or at (the weekend), the post on Language Log summarizes it nicely:



An attempt ensued to achieve descriptive accuracy. It was agreed that times within the day generally take at (at 9:30, at noon, at dawn, at dinner, at night), except for those that take in with the definite article (in the morning, in the evening); that days generally take on (on Monday, on her birthday, on Valentine's Day), except maybe for at Christmas; that months and seasons and years and centuries generally take in (in December, in winter, in 1893, in the 15th century). And never mind the (generally relative) time-references that don't take any preposition at all, like tomorrow, next week, three days ago.



That's really useful, not just because it covers all the most common prepositions used with time expressions (at, on, in); it also hints at how we can conceptualize these expressions so we can use them appropriately.


The next paragraph also gives a big clue to the difference between dialects:




This all hints at a coherent metaphor: hours and other short periods of time are places; days are surfaces; months and longer time periods are containers. But it seems that only North Americans apply this logic to weekends.



So, it's rather clear that only North American speakers will normally use on with weekends. On (not at or in) the other side of the pond, it seems like at is the choice.


That's as far as I can go. Beyond that, you have to rely on yourself (the mentioned Martin Haspelmath, "From Space to Time: Temporal Adverbials in the World’s Languages", 1997, seems like a great read). I also hope more native speakers will chime in soon.


Thursday, October 29, 2015

unity - Top-Down Octree Generation of Procedural Terrain


I'm trying to implement a voxel-based terrain generation system in Unity3d (C#). I have successfully implemented a uniform 3d grid system, and have extracted the isosurface out using Marching Cubes and Surface Nets algorithms.


I quickly bumped up against the inherent issues in representing all space with a 3d grid. Much of this space was either above or below the surface, and I turned to space partitioning with octrees, as it didn't seem too difficult. One of the great things about octrees is that octree nodes that that don't have edges intersected by the surface don't need to be split again.


I researched, and found a couple resources to construct my code. One is Volume GFX, and another is the original Dual Contouring paper by Ju et al. My edge-checking is done by the Marching Cube's checking from Paul Bourke's code. If the "cubeindex" is either 0 or 255, then no edge is intersected, and the octree node does not need to be split.


My Octree generation code works for something like a quarter-sphere, where the surface features are extremely normal: Octree Node visualization and corresponding Dual Contouring Surface



As seen in the picture, only octree nodes containing the surface are subdivided. Working great.


Now, however, when we move to something more complex, like Unity3d's PerlinNoise function: Perlin Noise using Octree GASP! What's that hole doing in the mesh at the lower-right corner? Upon closer inspection, we see the octree didn't subdivide properly (red lines highlighting the offending node's dimensions): enter image description here This turns out to be the same issue Jules Bloomenthal highlights in her paper on polygonization, page 10, Figure 10. Traditional methods at generating top-down octrees ("Adaptive Subdivision"), are sensitive to fine surface features relative to the size of the octree node.


The gist:


X-------X
| |
| | <- Node
X--/\---X X's - tested values, all outside of the surface!
/ \ <- surface

The surface breaks the surface, but comes back down before it goes over a vertex. Because we calculate edge intersections by looking at the signs at the two vertices, this does not flag the edge as crossed.



Is there any method to determine if these anomalies exist? Preferably, the solution would work for more than just the Unity3d noise function, but for any 3d noise function (for cliffs/overhangs/floating islands, etc).


UPDATE


Thanks to Jason's awesome answer, I was able to answer my own questions I asked (in the comments under his answer). The issue I had was that I didn't understand how I could create a bounding function for trigonometric functions (sine,cosine,etc) due to their periodic nature.


For these guys, the periodicity is the key to bounds functions. We know that sin/cos reach their extrema values at a set interval, specifically every π/2. So, if the interval we are checking contains any multiple (cos) or half-multiple (sin) than 1/-1 is the certain extrema. If it doesnt contain a multiple (i.e. the interval [0.1,0.2]), then the range is simply the values of the function evaluated at its endpoints.


UPDATE 2:


If the above doesn't make sense, check Jason's answer to my comments.



Answer



I will assume that you have a function f such that the surface is defined by f(x,y,z)==0. Right now, all you have is the function f itself, and so with no further information, it is impossible to know when to subdivide. It is always possible for the surface to do what you describe, i.e. the function f can have arbitrarily thin "fins" which can require you do go arbitrarily deep in the octree.


The only solution that allows top down generation is to have additional information on f. Right now you have a point query: you can determine what the value of f is at any particular point, but you have no guarantees about what the value will be at any other point, even ones right next to it. Instead, you need a bounds query: given a AABB, it determines what the maximum and minimum value of f is over that range.


Now it is simple: for each octree node, perform a bounds query. If the minimum is greater than zero or the maximum is less than zero, do not subdivide. Otherwise, subdivide unless you are at the smallest size, in which case you can use the point query on the corners as usual to construct the surface.



It is easy to write the point query for interesting functions, but it is not clear how to write the corresponding bounds function. However, our job is made easier by the fact that we don't need to be precise: calculating the exact min/max is not going to be particularly useful anyway, because we are just going to compare them to zero. So really we just need to calculate and interval [a,b] which completely contains [true_min, true_max] over the given AABB bounds. If we are close to the true range, we will subdivide mostly things which actually contain the surface, and if we are loose and give much bigger ranges we will end up dividing more nodes than is necessary. However, as long as we make sure to contain the true range we will never miss part of the surface.


As an example, we can construct the bounds function for the sphere function. (To see why your technique doesn't work even in this case, start with a sphere which is entirely contained in the starting cube. The algorithm will terminate immediately!). The point function is f(x,y,z) = dist(, center) - radius. We see that this function depends only on the distance from the point center, so is really at its core a 1D function. First, we determine which range of radiuses our AABB covers. A simple but slow way to do this is to determine the distances for the 8 corners and take the minimum and maximum distances. The only special case is that if the center is contained in the AABB, then the minimum is zero. Now we have a range of radiuses, and by plugging in the function f(r) = r - radius will give the desired range for values of f.


Of course, that was a simple example; you probably want something more complicated than spheres. The nice thing about this approach is that you can combine such bounds functions. For example, if you add two functions together, say f + g, the bounds function for the sum can be easily constructed in a conservative manner as: the min and max are just the sum of the mins and maxes respectively of the two functions. To see this is conservative, consider the functions sin(x) and -sin(x) in 1D. Clearly over any range greater than 2pi these each have a range [-1,1], and so the calculated range is [-2,2], but the real range is the interval [0,0] containing just 0! All hope is not lost, however: if we zoom in on a small range for x, then the interval gets smaller (closer to [0,0]) as well.


This means if you can bound one octave of Perlin noise, then you can bound a full fractal noise, which is just a sum of many individual octaves. Actually, if we can bound individual functions, we can use the rules of interval arithmetic to construct more interesting functions. In particular for procedural synthesis, summation, minimum/maximum, domain distortions, and scaling by constants can all be handled by interval arithmetic, which let us add surface texture, place objects, and distort & scale without needing to write complicated bounds functions. So we can write f(x) + min(g(x), h(x)) * 4 + h(2*x) for the point query, and automatically (but imprecisely) construct the corresponding bounds function, assuming we have the bounds functions for f, g, and h.


Finally, some functions are not easily expressed as a simple combination of others. In that case, you can often bound the derivative and use that to bound the value of the function. This is somewhat more math intensive though, so I won't cover it here.


Implementation note


It is probably easiest to represent a function f by a pair of functions:



  1. a point query f_point which is a function taking a point to a float.

  2. a bounds query f_bounds which takes a AABB to an interval [min,max].



Then you can write combinators like Sum, Scale, etc. which take these pairs and return new ones which are the combination given. You can represent these as tuples, objects, etc. depending on the language.


game design - The Thin Red Line. What to present to get interest without showing too much?


I am Dalilean and I am a gamer. There I have said it. Damn, feels like a weight is lifted from my shoulders… They say the first step is to admit the problem. Now the second step is doing something about it.


So….


As more than a few of you know, I decided to design a game.


Right now I feel like I am at a critical point in development. I am looking at the aspects of the game, from a game play point of view. This means I am past the story, the conceptualization, and now I am dealing with issues of “What specifics do each character have”, “What options and results do the actions of the player have in the game.”



I got to wondering, How much do I show possible investors or developers without showing too much?


I worry that I give them a copy of the Game Design Document; they will just say thank you and nothing else. Then, several years later, I will see my concepts seeping into games. I have learned from previous experiences that not everyone is honest and that a healthy level of paranoia goes a long way in this world.




What are the advantages and disadvantages to using a game engine?



How do I know whether or not to use a game engine? I want to make a relatively complex 2D game for Android. What factors should I weigh to decide whether to find, install and learn a game engine or just do everything manually?



Answer




Advantages:




  • Most if not all of the coding is done for you, so all you have to worry about is content, level layout, etc.




  • Along those lines, memory management, asset loading, lighting (in complex engines), etc has all been designed and tested thoroughly (hopefully).




  • As mentioned below, if the engine is cross platform you will have to do little to no work to port your game.





Disadvantages:



  • If you are modifying anything, you now need to become familiar with a new codebase.

  • If there is a bug in the engine, unless it is open source you can't fix it.

  • The engine was not designed specifically for your game, so it may be less efficient than code you write specifically for your game.

  • Game engines generally are not free.

  • If a game is small, the overhead of using an engine may not be worth the time invested to write code yourself.

  • If your game engine also has any editors or tools, you will have to build and test those as well before turning them over to artists or relying on them yourself.



Don't let the fact that the list of disadvantages is longer: when the time spent coding and testing all the systems you need is too long for your production cycle, or if you have more skill with art than code, using a game engine is definitely a good idea.


A comparison of game engines is in the works in this question: Pro's and Con's of Various 3D Game Engines


preposition omission before "this time of day"



I love going out at this time of the day.


I love going out this time of the day.




Are both the sentences grammatically correct? Or does the omitting the preposition render the sentence ungrammatical?



Answer



Both are correct. In English certain nouns and standard noun phrases that refer to a specific time can function as adverbs without needing to be introduced by a preposition. They indicate when the action or state named by the verb occurred. With some of these phrases, a preposition is not even allowed. These constructions are all fine even in formal English. Some more examples:



I'll call you Tuesday.


I'll call you on Tuesday.


We vacationed in Hawaii last year.


Let's have lunch next week.


This time, I'm going to remember to set the parking brake.



Next time you go to Poppy's Restaurant, order the linguine.


I missed breakfast this morning.


I'll see you tomorrow evening.


Prague is beautiful this time of year.


Prague is beautiful at this time of year.


Next year, we should meet in Jerusalem.



There is no rule for this, though. These are ungrammatical:



We vacationed in Hawaii 2018.



Call me 9:00.



You have to say:



We vacationed in Hawaii in 2018.


Call me at 9:00.



Wednesday, October 28, 2015

grammar - What's the right form of verb in this sentence?


I found this sentence in the delivery note.



Above mentioned Goods received in good condition.
We are not responsible for the Goods after the delivery.
Receiver's signature.



My question why do we use the verb "received" and not "were received" or "have been received"?





adjectives - "It is not well" or "it is not good"?


Watching an old Dr. Who episode, one character said to another,




"Highness, it is not well to think of the past, there is still the future to make."
("The Ribos Operation", 1978)



To my ear, this sounds wrong and should have been,



"Highness, it is not good to think of the past, there is still the future to make."



Unfortunately, other than the way it sounds, I cannot determine the applicable grammar rules to know if I am correct.




achievements - Ready to use leaderboard service. Is any?




I'm looking for ready to use thirdparty leaderboard service where player's achivementes and scores can be placed. I'd intagrate it into my game to allow players push scores and locate themselves in the tables of tops. It would be nice whether anybody experienced share some points with me.



Answer



I've had good luck with ScoreLoop. They may just be mobile, but worth checking out.


http://www.scoreloop.com/developers/social/


opengl - How to do perspective projection “parallax” but without changing the scale or offset of objects?


Hello everyone I have this problem that I have tried everything I could think of. The problem: I am making a 2D game with parallax effect but I am using 3d space so am not simulating the parallax but letting the perspective projection take care of it for me. now the problem i have my own game editor where I design the levels, in this editor I use just images and I set a Z value for each layer. however I want the layers to show in the game engine exactly as I set them in the game editor, in short I want perspective projection to do parallax but without changing their scale or offset/position.


obvious solution is to scale them up and offset them but the problem how to calculate their offset? with scaling I tried object->Scale(object.Z/view.Z) and seems to return them to their real size but their positions are still wrong. I tried object->setPositionX(object->getPosition().x*(object.Z/view.Z)) and seems to be aligned except they all seems shifted.


I have tried unprojecting and tried to convert from world matrix to screen matrix and find some ratios and so on.


If anyone have any idea or anyway how this could be done in an elegant/mathematical way , I will be most grateful.


Thank you all in advance.




phrase usage - What defines a native English Speaker?


I think this particular phrase creates a lot of concern in English learners. From general conversation to posts here, we see native speaker a common usage when talking about a person who speaks English by birth. So according to this definition, inhabitants of all the countries considered as English speaking countries should be considered as native speakers. But herein lies my confusion. Would we conclude a random inhabitant of these countries to be a native speaker (as there is a chance of them to be a English speaking person)?


Also, I think Native speaker can also be one whose mother tongue is not English but uses English a lot in day-to-day life. For example, I don't speak English by birth, but as India is a country full of diversities, I have to use English daily for at least 5 hours a day in my normal life. So can I consider myself as native because I use it frequently?


UPDATE 1 - From Googling, I could not find any dictionary sites explaining this phrase. The results only include different forum answers. So I thought of asking the question here and perhaps wise users here can help me out with the actual meaning.


UPDATE 2 - Later I thought it is worth adding that Anglo Indian families (and some purely Indian families too) who are born and raised here in India, speak English from birth and their first language is English and English is their primary means of communication although I cannot admit they fully abide by or understand all English cultural values like a British or an American. So what can I call them? Are they native?



Answer



I think we need to clarify a couple of definitions:





  • Native English speaker – A person whose first language is English (they learned English from birth or as a very young child), and for whom English is the primary means of communication.




  • Fluent English speaker – A person who learned English later in life (i.e. as an older child, teenager, or adult), and who is very proficient in both spoken and written English.




There is nothing wrong with not being a native English speaker, and many non-native speakers have far better English skills than myriads of native speakers.


graphics programming - What techniques could I use to give players the ability to control certain features, e.g. fatness?


I'm working on a tool for character customization (e.g. starting from a base model, a player can control his fatness), so I'm looking for ideas, techniques or other regarding this topic.


After some research I thought to this technique: starting from two models (one standard human and one fat human, both with the same data, like vertices and triangles), then creating a new model by storing data about the two original mesh (e.g. store vertex data of the second mesh as color data), and controlling their interpolation with a shader.


What do you think about this idea? Suggestions?



Answer



You might want to have a look at Elder Scrolls: Oblivion, in particular the character creation screen. They do a lot with modifiable anatomies there. Each race has its own anthropometric norms and ranges. Anthropometrics is the study of the particular measurements / proportions of individual physical characteristics (phenotypes) of individual human beings, comparatively speaking. It's a good place to start doing some research into exactly what varies between individuals.


Your idea sounds good, although I think simply interpolating between just two meshes may not give you enough variation.


game design - Authoritative Server Movement and Collision


I am attempting to write a proof of concept in preparation to do my first networked game. I have decided to do an authoritative server with client side prediction.


I am trying to implement my architecture like this diagram from an excellent article on the subject


Client Server Architecture example


In the article, the data that is synchronized is the player's position. This works great for turn based games, but what about real time games?



In my game, each entity has a position and a velocity vector. It is the server's job to detect collisions. I have attempted to send the server velocity changes, but I am having an issue where the server's position and the client's position begins to diverge because their clocks are not perfectly synchronized.


So my question is, is it standard practice to send positions as the synchronized state between a client and server instead of a velocity vector? Will changing to synchronizing positions instead of velocities open my game up to cheating? Is there a better way to synchronize the players' states with the server?


Also, if I use positions, doesn't that mean that the other players are going to be seen in a past state? Will that mean that the server might send a player killed message before the collision is visible to the player in the present?



Answer



Making good multiplayer games isn't a trivial thing, we know. There are many aspects to care about: network architecture, machines synchronization, network delays, cheating... But, let's start one step per time.


In turn-based games, as you said, you are limited to send objects positions, because that is the only important information you'll need. In real-time, fast-paced video games (such as FPS, racing games...), good timing is the key to make the game enjoyable, and mostly playable.


When playing an FPS there are many objects to sync: players, bullets, weapons, vehicles, and then scores, chat messages... The more the objects, the more the packets to send over the network, and with few to no delays independently of your connection. That means you need a proper network protocol to connect different players to play together. That means you can't rely on TCP, because you are focusing on real-time simulation and fast updates, not packets integrity and reliability. UDP is better for this task. Well, not UDP as is, but a custom net protocol built on top of it.


The image you posted shows a basic client-server interaction, where the server is authoritative over the client. That means the client always applies the information received from the server, whatever it is, because it is the server and it is always right. And it is right because it is the only one running the game logic, whilst clients are only replicating it on different machines. Also, clients should replicate exactly the server simulation: this is called deterministic lockstep. A system is said deterministic if we can know every single action to perform to get to a state B from a given starting state A.
A video game is a deterministic system: if I hold the 'move forward' key for a certain amount of time, I can foresee the position I'm going to be at (thanks, high school physics).
Deterministic lockstep - together with floating point determinism, the property of several machines to compute same results if given the same starting numbers and operations to perform - is the reason a client can simulate for a small amount of time what is happening on the server when some packets are suddendly lost, if given the right state information such as position and velocity instead of one only of them.

On the other hand, deterministic lockstep and client-server synchronization is only possible if both the client and server are running the same code, and assuming that there are no game logic delays because of internal application integrating/rendering time.


In the FPS scenario, a server must send clients many updates per second, so that they are always running the most recent simulation possible (for example 20 updates per seconds). This rate should be nor low enough to cause lag because of many server-side corrections, neither too high for the client machine to handle (we don't want to congestionate one's connection).


Syncing your game isn't just telling clients objects coordinates and velocities vectors, and updating; you must make sure clients are able to sync single entities as well as whole game session (e.g. when a player wants to join a game in progress). Or, your game should be able to compensate network latency so that shooting to a player is actually shooting to a player on the server: clients are running a simulation in the past because of networking, and there are efficient ways to prevent players from feeling frustrated for playing a "bad" game.


Now, answering your question: what info does one need to send to sync clients? The Quake source code shows how they dealt with client synchronization: the server receives from clients every players' input, and then sends every player avatar's position, speed and direction, this way - using the same physics code - both clients and server will compute the same frames after small amounts of time. Eventually the server will perform corrections over the clients, and there is some data to update instantly and other one should interpolate smoothly, but the game will maintain its logical integrity most of the time. And let's not forget client-side prediction!


You can read more about networked physics, server authority, client-side prediction and server-side compensation here. Also, the Valve Developer Community is a place full of interesting guides to understand better how their engine (and, generally speaking, any possible engine) works.


Tuesday, October 27, 2015

word choice - What are the differences between "to talk" and "to speak"?


Both verbs "to talk" and "to speak" refer to the same action.


Is their meaning exactly the same?
When is more appropriate to use one, or the other verb?



Answer




Using speak, tell, say, and talk is a very common problem for ELL.


@Siddhartha and @Em1 gave great answers, so let me quickly list only those aspects not mentioned by them.


So, I have some meaning to convey. How do I know which word to use?



  • Ability — if it's about ability, "talk" is preferred: "cats can't talk", "when I'm drunk I lose my ability to talk". Note that "speak" is allowed but is less popular;

  • Languages — use "speak": "I speak English";

  • Action — covered in answers above; both words can be used; "speak" is mostly about single-direction, while "talk" usually refers a conversation (and is less formal);

  • Express information — use "say" or "tell": "I told her that I love her". Here, "I love her" is the information being expressed. "Say" can also be used, but it connotates a single-time action. Compare: "I said that the discussion is over and hung up the phone."


Consider this sentence:




I can see they are talking, but I don't know what they are saying.



Here, you see an action, but you don't know or don't understand the meaning of the information others are exchanging.



  • Wide topic, narrow topic:

    • use "say" or "tell" if the topic is narrow or it's about a small piece of information: "I told her there is a party tonight";

    • use "talk about" or "speak about" when the topic is wide: "We are speaking about history". There's also an idiomatic construct, "talk politics" that omits "about".




  • Conversing during an extended period of time: use "talk about" or "speak about", as above;

  • Imperative usually follows the rules above, but due to an extended popularity, here's a brief:

    • Extended time or dialogue"Talk to me."

    • Long monologue"Tell me about your problem."

    • Short monologue"Say something!"

    • Requesting a certain attribute of speaking process"Speak slowly please."





unity - How do I merge colliders in a tile-based game?


I'm doing a tiled based platformer in unity, and I was having some issues with collisions and I figured the problem was the way my colliders were arranged.



So right now, my collision look like this:


example 1


You see each tile has its own collider, outlined in black. Polygon colliders in unity are formed by lists of points in space, and I can manipulate them freely. What I would ultimately want, is to have all this colliders in the example image to merge into just two colliders ( or maybe one, depending on how the edges of those squares touching would be handled ):


example 2


How could I achieve that? Is there any known algorithm?



Answer



Ok, so I solved this problem using the Clipper library: http://www.angusj.com/delphi/clipper.php


The library has an all in one .cs file, so the easiest way to use it in unity, is to just paste this file in your Assets folder.


Here is what the collision looks like in my scene view, before and after:


enter image description here enter image description here



It's not 100% perfect, but I think I'll do in most cases.


Here is the commented code:


using UnityEngine;
using System.Collections.Generic;
using System;

using ClipperLib;
using Path = System.Collections.Generic.List;
using Paths = System.Collections.Generic.List>;


//this function takes a list of polygons as a parameter, this list of polygons represent all the polygons that constitute collision in your level.
public List> UniteCollisionPolygons(List> polygons)
{
//this is going to be the result of the method
List> unitedPolygons = new List>();
Clipper clipper = new Clipper();

//clipper only works with ints, so if we're working with floats, we need to multiply all our floats by
//a scaling factor, and when we're done, divide by the same scaling factor again
int scalingFactor = 10000;


//this loop will convert our List> to what Clipper works with, which is "Path" and "IntPoint"
//and then add all the Paths to the clipper object so we can process them
for (int i = 0; i < polygons.Count; i++)
{
Path allPolygonsPath = new Path(polygons[i].Count);

for (int j = 0; j < polygons[i].Count; j++)
{
allPolygonsPath.Add(new IntPoint(Mathf.Floor(polygons[i][j].x * scalingFactor), Mathf.Floor(polygons[i][j].y * scalingFactor)));

}
clipper.AddPath(allPolygonsPath, PolyType.ptSubject, true);

}

//this will be the result
Paths solution = new Paths();

//having added all the Paths added to the clipper object, we tell clipper to execute an union
clipper.Execute(ClipType.ctUnion, solution);


//the union may not end perfectly, so we're gonna do an offset in our polygons, that is, expand them outside a little bit
ClipperOffset offset = new ClipperOffset();
offset.AddPaths(solution, JoinType.jtMiter, EndType.etClosedPolygon);
//5 is the ammount of offset
offset.Execute(ref solution, 5f);

//now we just need to conver it into a List> while removing the scaling
foreach (Path path in solution)
{

List unitedPolygon = new List();
foreach (IntPoint point in path)
{
unitedPolygon.Add(new Vector2(point.X / (float)scalingFactor, point.Y / (float)scalingFactor));
}
unitedPolygons.Add(unitedPolygon);
}

//this removes some redundant vertices in the polygons when they are too close from each other
//may be useful to clean things up a little if your initial collisions don't match perfectly from tile to tile

unitedPolygons = RemoveClosePointsInPolygons(unitedPolygons);

//everything done
return unitedPolygons;
}

//create the collider in unity from the list of polygons
public void CreateLevelCollider(List> polygons)
{
GameObject colliderObj = new GameObject("LevelCollision");

colliderObj.layer = GR.inst.GetLayerID(Layer.PLATFORM);
colliderObj.transform.SetParent(level.levelObj.transform);

PolygonCollider2D collider = colliderObj.AddComponent();

collider.pathCount = polygons.Count;

for (int i = 0; i < polygons.Count; i++)
{
Vector2[] points = polygons[i].ToArray();


collider.SetPath(i, points);
}
}

public List> RemoveClosePointsInPolygons(List> polygons)
{
float proximityLimit = 0.1f;

List> resultPolygons = new List>();


foreach(List polygon in polygons)
{
List pointsToTest = polygon;
List pointsToRemove = new List();

foreach (Vector2 pointToTest in pointsToTest)
{
foreach (Vector2 point in polygon)
{

if (point == pointToTest || pointsToRemove.Contains(point)) continue;

bool closeInX = Math.Abs(point.x - pointToTest.x) < proximityLimit;
bool closeInY = Math.Abs(point.y - pointToTest.y) < proximityLimit;

if (closeInX && closeInY)
{
pointsToRemove.Add(pointToTest);
break;
}

}
}
polygon.RemoveAll(x => pointsToRemove.Contains(x));

if(polygon.Count > 0)
{
resultPolygons.Add(polygon);
}
}


return resultPolygons;
}

Monday, October 26, 2015

isometric - Picking a tile in an Iso Engine


I have developed an iso engine for a farm game. In general it works fine, but the problem is that it is not always accurate when pressing the tiles, so the tile I wanted to select is not the one picked. Anybody has some ideas how to improve this?




costs - Why is it so expensive to develop an MMO?



I want to develop an MMO, like World of Warcraft, but some basic research says that it is going to take a lot of time and money. I'd like to know why.


Why is it so expensive to develop an MMO?



Answer




The first problem is that the software itself is very complicated, particularly for a new or inexperienced game developer. You have to maintain (at the very least) a client and server application while providing more content than you would expect for a "regular" multiplayer or single-player game.


Even on their own as a single player game, an RPG with the complexity of a World of Warcraft would take professional teams years to develop to the same level of polish: an enormous content investment, lots of work up front and afterward with balancing and playtesting, and some of the most complicated interactions of any game genre. These are commercial-level games, and while yours might be smaller, it will still require a lot of effort just to be a good game before you pour in the extra work to make it become a good multiplayer game.


Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise.


Building it shouldn't be your sole concern for manpower and money, either; also consider the costs of running it after it's developed. Even a small massively multiplayer online game will need constant improvements to its hardware/software to keep up with demand and staff to manage the game and provide support for your players.


Think about the following:



  • Hosting - Where are you going to host the servers? How will you pay for the bandwidth? How will you load balance players between servers and keep a minority of players from monopolizing the resources of the game? You'll need people to keep an eye on the condition of your hardware and software hosting the game in order to make sure that it will continue to work well.

  • Technical support - Not just getting the game to run, but dealing with problems between players and handling player feedback in a way that will keep them loyal. If you're charging money (say, for a subscription), the billing system will be even more complicated (and most likely require legal assistance and possibly international representation and banking/processing fees). People who deal with these things need salaries.

  • Security - Not just of their game accounts, but you have to consider cheat prevention and doing frequent repairs and community maintenance effort whenever a new exploit is discovered by players.



Sunday, October 25, 2015

idioms - Does this sentence need "if" or "when"?



I came across this sentence:



"There isn't an entomologist in the whole world who wouldn't give all he has to be in my shoes today."



This was said when a person caught a rare insect.


If "if" or "when" is placed before "he has to be in my shoes today", I think it makes sense but this sentence doesn't have them. Is my understanding wrong?



Answer



I think your confusion might just come from not understanding the idioms in the sentence, so I'll start by paraphrasing it.



There isn't an entomologist in the whole world who wouldn't give all he has to be in my shoes today




Since there is a double negative, we'll go ahead and reverse it. Hopefully this makes the sentence less confusing already.



Any entomologist would give all he has to be in my shoes today.



2 of the phrases left are give all he has and to be in my shoes.


You seem to be trying to split it into would give all and [if/when] he has to be in my shoes, and you are reading "has to" as "must". This is incorrect in context.


To give all he has is to sacrifice anything he owns. To be in my shoes means to be experiencing what the author is experiencing (catching the rare insect)


So the whole sentence simplified is:




Any entomologist would love to be in my situation



It should be clear there is no room for if or when in that sentence.


mathematics - RPG Logarithmic leveling formula?


I'm working on a RPG game, however, I am not the amazing person at math that I wish I was, although someone suggested a logarithmic equation would work well. My current idea is for this:


You start off getting levels relatively quickly (lower xp amounts), then once you get higher up like 20-30 maybe it starts to take longer and longer to level, ending somewhere around 10-15 million experience for level 100. Can anyone offer me an equation or suggestions on how to do this? Thanks :)



Answer



If you want a logarithmic levelling formula that would simply be:


Level = Math.max( Math.floor( constA * Math.log( XP + constC ) + constB ), 1 )


For ~10 million XP at level 100 you should choose something like constA = 8.7, constB = -40 and constC = 111.


If the level gap rises too fast for your taste increase constA, decrease constB if you want the inital level gap to be higher, and finally set constC ~= exp((1-constB)/constA), in order to properly start at level 1.


Note that the appropriateness of any levelling formula depend completely on how fast players can gain XP at any given level.


See also: Algorithm for dynamically calculating a level based on experience points?


c# - In Unity, how do I make the camera follow a character?


When my character moves, I want the camera to follow them, such that the character always stays in the middle of the view. How do I do that in Unity?




Here's my code right now:


using UnityEngine;
using System.Collections;

public class CharacterControll : MonoBehaviour {


public float speed = 3f;

private Animator animator;
private Vector2 screenSW;
private Vector2 screenNE;
private float wrapPadding = 1f;
public GameObject gameObject;

// Use this for initialization
void Start () {

animator = this.GetComponent ();

screenSW = Camera.main.ScreenToWorldPoint (new Vector2(0, 0));
screenNE = Camera.main.ScreenToWorldPoint (new Vector2(Screen.width, Screen.height));
}

// Update is called once per frame
void Update () {
float horizontalInput = Input.GetAxis ("Horizontal");
float verticalInput = Input.GetAxis ("Vertical");


if (horizontalInput == 0) {
animator.speed = 0;
animator.SetInteger("Direction", 0);
}

else if (horizontalInput < 0) {
animator.speed = 3;
animator.SetInteger("Direction", 1);
}


transform.Translate (Vector2.right * horizontalInput * Time.deltaTime * speed);
transform.Translate (Vector2.up * verticalInput * Time.deltaTime * speed);

if (transform.localPosition.x < screenSW.x - wrapPadding) {
transform.localPosition = new Vector2(screenNE.x, transform.localPosition.y);
}

else if (transform.localPosition.x > screenNE.x + wrapPadding) {
transform.localPosition = new Vector2(screenSW.x, transform.localPosition.y);

}

}

void OnTriggerEnter2d(Collider2D other){



}
}


Answer



Just make the main camera a child of the player object in the hierarchy, then move it to where you want it in the scene view with the translate/rotate tools. Don't make it overly complicated with code.


Or apply the same control scripts and colliders to the camera as to the player object.


Saturday, October 24, 2015

security - How should multiplayer games handle authentication?


I've been lurking around to understand how an authentication system would work in games, but after many searches, it seems that working with ssl/certificates could be a little complicated for just a multiplayer game with a lot less capacity than an MMO.


I know that successful multiplayer games need this, but I'd like to check if other multiplayer games commonly take this precautions.


EDIT: I'll describe what I have in mind. The server not only handles game logic, but also authentication. So, in order to play on a specific server (that everyone could start), you first need to register an account on the server, and each time you want to play there, login as usual (password/name user).


My question is, would not providing a secure channel for logging in/registering an account be forgivable/understandable in this context? Also I'm interested to know how games with a similar architecture would handle this matter.




Answer



Specifically regarding the last bit of your question: No, it is never forgivable to have an insecure authentication system. Users are rarely enlightened when it comes to computer security. Users use the same password for your little game as they do for their Google account, Facebook account, bank account, and so on. Even if you can claim that it's their fault for using poor Internet security habits, you're the one who will be held responsible if your game is used as an attack vector to steal users' login credentials. As a developer who knows better, the only ethical options are to properly secure your authentication process or to not have one at all.


As some unsolicited but related advice, users don't want to be required to sign up for your game anyway. They might do so if they want to play your game badly enough, but having Yet Another Freaking Login to sign up for is going to just drive away many potential players. Users are sick to death of making a new account for every single site, service, and game out there, especially if they require any kind of email validation or the like. If you can, either avoid having a login at all, or use an existing third-party authentication service that users likely already have an account with. You will have more players that way. This goes triple if you plan on having any kind of in-app purchases.


Web Games


A popular option -- particularly for Web games, though it also works for traditional games -- is to use a Web-based third-party authentication service. Facebook and Google both have well-documented APIs (both based on standardized APIs, iirc) for authentication. They do require the ability to open a browser window and direct the user towards their services, but this is pretty easy to do on most non-console platforms, and of course trivial for Web games.


Those services take care of all the messy details of encrypting login traffic over the wire, securely storing login credentials, and validating user logins. Your game server then needs only implement the portion of the protocol that receives a cookie from the user and asks the authentication service if the cookie is valid or not, which can be done with a simple HTTP in most cases.


I won't claim most traditional multiplayer games do this, because they don't, but I will claim that most online casual Web games do this.


For traditional (non-Web) games, facilitating this login procedure is possible by either embedding a browser (Awesomium, Chromium Embedded Framework, or straight up Webkit being popular choices) or by calling out to an external browser (this takes some more fanagling to get the auth cookie out of though, and isn't really any easier than embedding one of the aforementioned libraries).


A typical example of this approach is any Facebook game.


Traditional Games using HTTPS



Having a simple HTTPS service for login is increasingly normal. Many games use custom protocols, but most of these are incomplete (they have secure login, but no secure way to create/update an account, so they need the HTTPS service anyway) or are simply horrifically insecure.


You don't even need to go about getting a custom SSL cert. There are online app hosting providers that give you a subdomain and use a wildcard SSL cert. You can put your authentication service at mygame.someservice.com, which is covered by the *.someservice.com wildcard cert that Some Service maintains, and you're good to go.


The idea here is that the user logs in to your service, which generates a unique session cookie, which the user can then pass into your main game server. The server then asks the login system if the cookie is valid for the requested user. There's usually a very short timeout on the cookie, on the order of seconds (15-30, for example), and it's generally invalidated once used, making replay attacks impossible.


Note that HTTPS is my most recommended option if you plan on sending payment information over the wire from inside the client itself. However, it's significantly better to use a third-party for this. If you think securing something as simple as a password is too much work, you don't even want to even think about trying to meet the minimum (and honestly quite inadequate) PCI compliance rules for storing and processing credit card numbers. You'll have better sales uptake anyway if you have users use trusted third-party payment services that they're already on file with.


One strong advantage of separating your login service from the main game server is that it allows external functionality to be tied to user accounts independent of the game. You might have some account features (viewing avatars or such) on your website, or perhaps you allow linking Facebook accounts into your accounts, or perhaps you have multiple games sharing a single underlying account platform (e.g., the Galaxy at War features of Mass Effect 3).


A popular example game using HTTPS for authentication is Minecraft.


Third-Party Web Authentication with Native Client Games


It is possible to use third-party services like Facebook Connect or Google with a native client. Facebook for example has a native SDK for iOS and Android, as does Google. Some services likewise have native SDKs for traditional PC clients.


If the target service does not having a native SDK and requires the use of a Web browser, you could just embed a browser in your game. However, some users may be distrustful of using an embedded browser to enter login information.


You can also use an external browser. There are a few ways to pull this off. Some require a little bit more OS-integration than others. Some require you to have an external Web service running alongside (or at least reachable by) your main game server. Note that since Facebook and Google generally require a URL that is authenticated, you will need a public website landing page to use these protocols in (almost) all cases.



The most fool-proof and reliable, if not quite the easiest, is to bounce your login request from your client through your main website. Your client connects to the main game server as an authenticated guest user and receives a unique session token. The game server does not allow the client to actually do much while in this state; the game doesn't know who the player is, so the player cannot yet chat, start a match, or so on.


The client then launches the external browser pointing at the login URL of your game's domain, passing this session token as a parameter in the URL. The site then goes through the usual login handshake for Facebook/Google.


At this point, your webserver knows that the user has logged in, and can associate that with the session token it received from the client. This verification can then communicated to the game server, elevating the client's unauthenticated guest connection into an authenticated user session. This can be done by having the webserver directly communicate with the game server, if possible. Or the game server can periodically poll the webserver for authentication status of pending guest connections. Or the client can periodically poll the webserver to see if login is complete and, when it is, signal the game server to request verification from the webserver.


All of these require that your game server and webserver be able to communicate, but any third party authentication service will require your game server to be able to communicate with the outside world, so this shouldn't be a surprise.


This authentication method is found in some small-to-mid-sized MMOs.


Note that this all also works for making payment requests through an external service, like PayPal, Amazon Payments, Google Wallet, etc.


Direct TLS Connection


It is not too difficult to start a TLS session over a custom stream protocol. Libraries like OpenSSL, GnuTLS, NSS, and various OS-specific libraries provide a stream wrapper API that layers over a low-level transport/protocol. You generally just need to feed bytes through the wrapper API and it deals with the handshake and encryption.


The tricky parts here are ensuring your use of TLS is safe. Some of the common libraries for example will by default require a valid signed certificate from a trusted authority. Some of the common libraries require that, but by default don't trust any authorities. Some of them do not require that the cert be valid at all.


It is recommended that you always require a valid cert. Allowing invalid certs will not allow an attacker who is merely eavesdropping to steal a password, but it will still allow man-in-the-middle attacks.



This approach requires the absolute least in terms of external dependencies while still allowing maximum security.


Examples of games using this now include most big traditional MMOs.


Secure(ish) Traditional Games


Games that don't use a separate service and don't use TLS typically have to implement some kind of nonce-based login protocol in their main game protocol. With this method, the server generates a random number (a nonce) and sends that to the client. The client then hashes that nonce with the user's password (and username, possibly some other data) and sends that response to the server. The server then compares this hashed value with the credentials it has on file. This keeps the user's password secrete over the wire and ensures that you can't use a simple replay attack on the hashed password, like many other weak hash-based login schemes.


A problem is that the user has no way to submit a new password to the service over this protocol securely. Typical implementations also store the user's password in plaintext on the server, which is a horrible practice (if your server gets hacked, your user probably just had his email/facebook/bank password stolen, because he was using the same password for your game as everywhere else, because users tend to do that).


There are enhanced versions of that basic login scheme. The most basic -- though still not ideally secure -- is for the server to send the password hash salt with the nonce value during login. This allows the server to stored a hashed (and salted) password securely while allowing the client to generate the same hash during login. This does allow an attacker to get the salt for a particular user's password, but this is not particularly useful without also getting the original hashed password (which is not sent over the wire during login). During creation/updating of the password, the client sends the whole hashed password (with salt), which the attacker can sniff. If the hash function used is strong enough (say, sha-2/512) then pure brute forcing is not feasible, though the attacker can still easily brute-force weak passwords (which is why enforcing some minimum password length, minimum distribution of letters/numbers/symbols, and comparing to a dictionary of known/obvious/weak passwords is important). The fact that the attacker can still get the hashed password is why it still more secure to do the entire password exchange over a secured, encrypted channel.


A number of popular game networking libraries implement some optional form of this protocol. I believe SmartFox is one such example, though I haven't looked at it in depth (I generally ignore any such library auth system and use the HTTPS method, since it's dead simple to implement and significantly stronger). A number of early non-Web Internet games also used this approach, particularly before Steam, XBL, and so on came around.


Unsecure Traditional Games


A lot of games unfortunately just send a username/password in plaintext. Maybe they hash the password, which vaguely kind-of protects the users actual password (not nearly well enough) but a replay attack makes logging into the game service trivial.


Don't do this. It's irresponsible and lazy. The Internet naiveté of the 1990's that popularized these login methods is no longer a viable excuse.



Many early pre-Facebook Flash and web games took this approach. I don't know of any specific examples off the top of my head; I'd like to believe they're all long dead, but the world just isn't that lucky.


No Authentication


Most games just don't do authentication. The player connects, sends over some handle to uniquely identify himself, and a match starts. There is no global server that tries to validate that only one real human is ever allowed to claim to be "CaptainMisterDude". The local server just ensures that only one currently connected player has any particular handle, and that's the end of it. Local servers use name-based and IP-based blacklisting for trouble makers. This is common for FPS deathmatch style games even today.


If you don't need any permanent state for accounts, this is by far the easiest solution, and quite "secure" since there's nothing there to actually hack or steal. Obviously this doesn't work too well if you do need to store account information between game sessions.


Quake is an example of a game using this method of "authenticating" users.


grammar - It is threads versus they are threads



I don't understand why the author used "It is" rather than They are in the following sentence.



It is threads, not processes, that are the units scheduled by the system for execution on the processor.



Why don't we say the following?



They are threads, not processes, that are the units scheduled by the system for execution on the processor.




Answer



This is a cleft sentence: "It is noun phrase that clause." In this construct, the pronoun is always "it"; it doesn't agree with the number (or gender) of anything. So it doesn't matter that threads or are are plural.



grammar - “of my heart” vs “in my heart” and how to use prepositions correctly


I'm not a native speaker, and the uses of prepositions are driving me crazy.


I saw a post with the phrase "you are the champion of my heart" on it. I thought it should be "the champion in my heart", "of my heart" sounds like you have several hearts, and one of them is your champion... Then I googled it, found out this "of my hearts" usage got more results than "in". The same question goes for "Secret of my heart" and "secret in my heart".


I read some grammar books, there were a lot of examples for prepositions, but still cannot cover all of the situations. Are there any rules about how to use prepositions correctly or I just have to remember every case I've met?


Thank you.




Answer



First, "of my heart" simply means that something is associated with your emotions:



You are the love of my heart.



Also, when we use words like "heart" or "head" metaphorically, prepositions may not mean what you think they mean. Consider:



You really got in my head for a minute there.



That simply means, "You affected my thoughts," and (thankfully) has nothing to do with you shrinking and climbing into my skull.



As for "of my heart" vs. "in my heart", here's one way I might characterize the two:



  • of my heart can be used with the definite article, to indicate preeminent personal feelings

  • in my heart can be used with the indefinite article, to project a role


For example:



You are a diva in my heart. (means: in my heart, I regard you as a diva)
You are the diva of my heart. (means: in my heart, I regard you as the diva)




So, back to what you said:



"of my heart" sounds like you have several hearts, and one of them is your champion...



Instead:



the champion of my heart



means something more like:




there may be several people who could be my champion, but, in my heart, you are my true champion





Disclaimer: I wouldn't regard this as a hard-and-fast rule with zero exceptions. As was mentioned, prepositions are very tricky. Macmillan lists more than 20 possible usages of the word of, and when you combine those with metaphorical words such as head, heart or skin, some preposition-noun combinations will indeed be idiomatic, and need to be learned one-by-one (such as, "She really gets under my skin.")


opengl - Combining rotation,scaling around a pivot with translation into a matrix



In short: I need to combine rotation (in the form of a quaternion), scaling around a pivot point along with translation into a transformation matrix.


The long: I am trying to implement a proprietary model format. This format includes animations. Part of that animation involves generating a matrix which combines rotation (in the form of a quaternion) and scaling around a pivot point, with translation into a transformation matrix. I am using OpenGL and the OpenGL math library (GLM)


Someone else has already implemented parts of the proprietary model format using DirectX. The part in question was implemented in directX like this:


D3DXMatrixTransformation(&BaseMatrix, &ModelBaseData->PivotPoint, NULL, &ScalingVector, &ModelBaseData->PivotPoint, reinterpret_cast(&RotationVector), &TranslationVector);

I found the WINE implementation of this function and attempted to duplicate it like this:


mat4 m1, m2, m3, m4, m5, m6, m7, p1, p2, p3, p4, p5;

m5 = glm::translate(0,0,0);
m7 = glm::translate(pivot+translationVector);

m1 = glm::translate(-pivot);
m3 = glm::scale(scalingVector);
m6 = glm::mat4_cast(rotationQuaternion); //Convert quaternion to a matrix

//m2 & m4 are identity
p1 = m1;// * m2
p2 = p1 * m3; //Apply scaling first
p3 = p2;// * m4;
p4 = p3 * m5;
p5 = p4;

p5 = p4 * m6;
mat4 result = p5 * m7;

(I realize glm::translate(0,0,0) is the identity matrix) Unfortunately neither the scaling nor the rotation seems to work correctly like this. So I took another approach based off of this ordering of translation, rotation and scaling.


mat4 result = glm::scale(scalingVector) * glm::translate(pivot) * glm::mat4_cast(rotationQuaternion) * glm::translate(translationVector);

However the scaling does not appear to be around the pivot point and I'm not entirely sure about the rotation. Does anyone have any tips on how to accomplish this?



Answer



Rotation/scaling is around the origin. To both scale/rotate around a pivot, you apply a negative translation to move the pivot point to the origin, apply your scale and rotate, and then move your pivot point back.


mat4 result = glm::translate(-pivot) *

glm::scale(..) *
glm::rotate(..) *
glm::translate(pivot) *
glm::translate(..);

OpenGL 3.0+ framebuffer to texture/images



I need a way to capture what is rendered on screen, i have read about glReadPixels but it looks really slow.


Can you suggest a more efficient or just an alternative way for just copying what is rendered by OpenGL 3.0+ to the local RAM and in general to output this in a image or in a data stream?


How i can achieve the same goal with OpenGL ES 2.0 ?


EDIT:


i just forgot: with this OpenGL functions how i can be sure that



  • I'm actually reading a complete frame, meaning that there is no overlapping between 2 frames or any nasty side effect

  • I'm actually reading the frame that comes right next to the previous one so i do not lose frames




physics - How do I configure a joint for a sliding door in Unity?


I have this sliding door where i want to use a joint to limit its motion:


Screenshot of a sliding door, partially open


...but I am confused about how to configure a joint to provide this sliding motion.


I've found the Hinge Joint component, but the comments below say this is for rotating motion. What kind of joint do I use to create a sliding motion?



Answer




As pointed out in the comments above, the Hinge Joint is not the right type of constraint to use for a sliding door. It handles rotational movement, like a door that swings.


For a sliding door, we'd instead use what's called a "Prismatic Joint"


Unfortunately, Unity doesn't have a built-in 3D Prismatic Joint component the way it does for springs and hinges. But we can create one using the Configurable Joint.


True to its name, this has a pile of configurable parameters, but we only need a few for this situation...




  • Connected Body: you can leave this as "None" if you want your door to slide with respect to a fixed track in the world. Optionally, you could create a track object and connect the door to that.




  • Anchor: this is the position in your door's local coordinates that should act as the attachment point - like where it hooks into your track. It looks here like your pivot is in the bottom-left corner of the door, and that's a sensible place, so let's use (0, 0, 0) here.





  • Axis: this is the direction of movement, in your object's local coordinate space. In my tests, my door slid along its local X axis (1, 0, 0). If you're using Z, interchange X&Z below.




  • Auto-Configure Connected Anchor: uncheck this. If checked, the joint will treat the door's placed position as the center of its movement range, allowing it to slide both left & right. I expect though you want to place your door in either the open or closed position, so we'll want to manually control this.




  • Connected Anchor: this is the position of the center of your track. If you specified a Connected Body, then it's in that body's local coordinates. Otherwise, it's in worldspace. To find the right value to use, slide your door until it's half-open, copy the worldspace position of its pivot, and use this value.





  • X/Y/Z Motion: X should be set to "Limited", and the others should be set to "Locked." This gets us the sliding motion we want.




  • Linear Limit: This is how far the door should be able to slide from the center point of its track we defined earlier. It's measured in worldspace, and should probably be about half the width of your door, or a little less.




  • Finally, select the Rigidbody component on your door and activate all three rotation constraints, to keep the door from twisting. The joint handles the position constraints just fine, so you don't need to fiddle with those.





That should do it. You can also play with the drive settings if you want the door to close itself, or adjust its Rigidbody's drag to help it slide to a stop.


Friday, October 23, 2015

actionscript 3 - Level editor event system, how to translate event to game action



I've been busy trying to create a level editor for a tile based game i'm working on. It's all going pretty fine, the only thing i'm having trouble with is creating a simple event system.


Let's say the player steps on a particulair tile that had the action "teleport" assigned to it in the editor. The teleport string is saved in the tile object as a variable. When creating the tilegrid an actionmanager class scans the action variable and assigns actions to the variable.


    public static class ActionManager
{

public static function ParseTileAction(tile:Tile) {

switch(tile.action) {

case "TELEPORT":


//assign action here

break;
}

}


}


Now this is an collision event, so I guess I should also provide an object to colide with the tile. But what if it would have to count for collision with all objects in the world? Also, checking for collisions in the actionmanager class doesn't seem very efficient.


Am I even on the right track here? I'm new to game design so I could be completly off track. Any tips on how handeling and creating events using an editor is usually done would be great. The main problem i'm having is and efficient way to read out and react to the given actions in the editor.


Thanks in advance.




opengl - GLSL to Cg fragment shader


I have found very useful resource on the Swiftless website on OpenGL.



Unfortunately, I cannot manage to adapt a GLSL fragment shader to my project, which uses Cg. Here it is:


uniform sampler2D color_texture;  
uniform sampler2D normal_texture;

void main() {

// Extract the normal from the normal map
vec3 normal = normalize(texture2D(normal_texture, gl_TexCoord[0].st).rgb * 2.0 - 1.0);

// Determine where the light is positioned (this can be set however you like)

vec3 light_pos = normalize(vec3(1.0, 1.0, 1.5));

// Calculate the lighting diffuse value
float diffuse = max(dot(normal, light_pos), 0.0);

vec3 color = diffuse * texture2D(color_texture, gl_TexCoord[0].st).rgb;

// Set the output color of our current pixel
gl_FragColor = vec4(color, 1.0);
}


I have tried something:


struct fsOutput {
vec4 color : COLOR;
};

uniform sampler2D detailTexture : TEXUNIT0;
uniform sampler2D bumpTexture : TEXUNIT1;

fsOutput FS_Main(float2 detailCoords : TEXCOORD0,

float2 bumpCoords: TEXCOORD1)
{

fsOutput fragm;

float4 anorm = tex2D(bumpTexture, bumpCoords);
vec3 normal = normalize(anorm.rgb * 2.0f - 1.0f);
vec3 light_pos = normalize(vec3(1.0f, 1.0f, 1.5f));
float diffuse = max(dot(normal, light_pos), 0.0);
vec3 color = diffuse * texture2D(detailTexture, detailCoords).rgb;

fragm.color = vec4(color, 1.0f);
return fragm;
}

But it doesn't work. To debug, I have a function that catches Cg errors, and my program breaks at this point. I have identified the two texture IDs in the main program. Can you suggest any improvement for this Cg shader?



Answer



I tried compiling it from the command-line as follows:


cgc -profile glslf -entry FS_Main test.cg

This gave the following error output:



test.cg
test.cg(18) : error C1066: invalid type in type constructor
test.cg(18) : error C1010: expression left of ."rgb" is not a struct

This immediately highlights the fact that you used texture2D on line 18 instead of the correct Cg function tex2D. Fixing this error makes it compile correctly.


In the future, you should probably use the cgGetLastListing function when cgGetError returns CG_COMPILER_ERROR. This will allow you to print out the error listing in your application, which makes your shaders easier to debug.


On another note, you use vec3 and vec4 on various occasions. While the Cg compiler seems to accept this, the correct types are float3 and float4, I believe.


Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...