Tuesday, February 28, 2017

idioms - "BE to VERB" construction in "you are to blame"





  1. The plane is to take off at 9pm

  2. You are to blame



1 refer to what will happen in the future as the "be + to +verb" construction is normally used for. In 2, "you" is like the object of "blame". Could you explain this usage to me?



Answer



The idiom BE to VERB has three distinct meanings:





  1. active sense = ‘Be appointed, expected, supposed, obliged to VERB at some point in the future’



    I am to go to London tomorrow. ... I am supposed to go to London tomorrow.


    I was to see the Minister yesterday, but he was called away. ... I had an appointment to see the Minister, but ....


    The plane is to take off at 9pm. ... The plane is expected to take off at 9pm.





  2. passive sense = ‘Be worthy of being or ‘expected to be VERBed’. This 'passival' infinitive also appears without BE as a postposited modifier. The phrase may also be expressed with an explicit passive, BE to be VERBed, or with for VERBing.




    This room is to let. ... This room is to be let (=rented).


    These doughnuts are to share. ... These doughnuts are for sharing.
    I got us doughnuts to share. ... I got doughnuts for us to share.


    You are to blame. ... You deserve to be blamed.



    Compare HAVE to VERB, where to VERB has the same passive sense: ‘We have several treatments to show you’.




  3. conditional sense = ‘If [subject] VERBed’. The past form were, without inflection for 3rd person singular, may express a tentative or hypothetical condition; this may be introduced with if, or were may invert with the subject.




    If he were to win the lottery he might retire. OR
    Were he to win the lottery he might retire. ... If he won the lottery he might retire.





optimization - How to optimize two-pass operations on an array with Unity Coroutines


I am working on simulating vacuum decompression in a 2D top down environment. I have 2 2-dimensional arrays: one that stores the pressure at a location, and one that stores the vector of fluid flow.


The algorithm looks likes this:


private void Flow()
{
Diffuse();
Vectorize();
}


private void Vectorize()
{
for(int x=0;x {
for(int y=0;y {
float myPressure= pressure[x,y];
[...]
Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op

[...]
vector[x,y]=flowVector;
}
}
}

private void Diffuse()
{
for(int x=0;x {

for(int y=0;y {
float myPressure= pressure[x,y];
[...]
float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
[...]
pressure[x,y]=newPressure;
}
}
}


The problem is that as the area of the simulation space increases, the performance continues to drop off as the iteration steps block the update loop.


I want to convert these to Coroutines in such a way that both yield but more or less maintain a lockstep appearance. Since flow is dependent on pressure differential, and pressure differential is partially dependent on flow, if an order has to be enforced, then Diffuse should take precedence.


My initial attempt followed the following form:


IEnumerable Flow()
{
StartCoroutine(Diffuse());
yield return null;
StartCoroutine(Vectorize());
}


IEnumerable Vectorize()
{
for(int x=0;x {
for(int y=0;y {
float myPressure= pressure[x,y];
[...]
Vector2 flowVector=calculate_the_resultant_vector_from_the_pressure_differentials //O(1) op

[...]
vector[x,y]=flowVector;
yield return null;
}
}
}

IEnumerable Diffuse()
{
for(int x=0;x
{
for(int y=0;y {
float myPressure= pressure[x,y];
[...]
float newPressure=calculate_the_new_pressure_from_the_pressure_differentials //O(1) op
[...]
pressure[x,y]=newPressure;
yield return null;
}

}
}

This tended to cause a jittery simulation. Even on a small 20x20 simulation field, there was noticeable difference between the first and second solutions.


Are there any tricks to coroutines that will allow a more lockstep simulation that scales well? Any suggestions on optimization is welcomed as well.



Answer



You seem to be aware of this but I just want to make it clear, the best solution for these kinds of problems is usually to spread calculations over multiple frames. This is especially true when frame perfect data representation is not necessary.




Now to answer your actual problem:


Coroutines are still executed sequentially, so you don't need to worry about lock step as long they both yield after the same number of iterations.



Whenever you call yield return null, you're telling your function to wait until the next frame to resume. This can cause things to slow down, since you're waiting a frame for every iteration in your double for.


When I've tackled similar problems, I usually follow a pattern like so


IEnumerator Control(){
while(flag){
yield return SpinLock(method);
}
}

IEnumerator SpinLock(){
StartCoroutine(method);

StartCoroutine(method2);
while(running1 && running2){yield return null}
}

This control block executes a coroutine, and doesn't launch another until the current completes. The launched runs its two Coroutines and waits for both two complete. They're both operating on the same chunks of data, but since they sleep at the same count, one doesn't get ahead of the other.


As for the other methods, I'd do something like this:


int perFrame; 
IEnumerator doWork(){
int counter = 0;
runningX = true;


for(int x = 0; x < stuff; x++){
for(int y = 0; y < stuff2; y++){
doStuff()

//yields for next frame.
//you can make this a fraction of the total, or a magic number, both have their uses.
if(counter > perFrame) {counter = 0; yield return null;}
counter++;
}

}

runningX = false;
}

This tells the function to do up to perFrame calculations, then rests. Since the function that calls it isn't waiting, both functions should do the same amount of calculations (in sequence), wait for end of frame, then resume on the next frame.


You can choose to work with the mixed dirty/clean data, or you can update your utilized matrix every iteration




If those 2D arrays are just data, you may be able to use actual threads in your Vectorize and Diffuse methods to take advantage of parallelism. The implementation should mostly be the same.


c++ - D3D9 Effects- variable parameters



I've created some simple Phong shading code from a sample. The issue is that the sample only handles one light. If I wanted a variable number of lights set at the start of each frame, how could I specify in the effect file that I need to pass a variable number of e.g. light positions and etc to render from?



Answer



For each light do one render pass and use Additive blending. It is called forward rendering.


Question is: Why to do it this way and not just send all of the light positions and params in few arrays? Answer is that this is much easier to handle once you start making some more complex effects. And there is one plus more. You can use your current shader.


Edit: To prove my point, i added two renders, because this technique sometimes sounds weird. One is rendered with gpu renderer which using described technique. And second is same scene rendered with Maya. Scene is lighted with 3 lights. One emits red, one blue and one green color. Common shadow mapping is used.


Realtime renderer:
furryball


Rendered with maya


maya


libgdx - Why can't I read .ttf file when running Android configuration?


When running or debugging my game on Android device, I get this error in the logcat:



com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/fonts/myFont.ttf (Internal)



Which is created by this code line:


FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);

where fontFile is defined like this:


FileHandle fontFile = Gdx.files.internal("data/fonts/myFont.ttf");


This doesn't happen when I run the desktop configuration.


I know that for desktop configuration you have to define the working directory of your project, but I don't see such option in android configuration and it also makes no sense, so I don't think it's a "working directory"-related problem.


Obviously, the file is in the correct path.


Also note that everything worked fine in my previous project. I created this new project by creating a new blank prj using libgdx-setup and then copying all the classes and packages from the older project. So maybe it's a problem related to some Gradle file?




Monday, February 27, 2017

progressive aspect - past continuous or past simple


At the dentist's:



I was on time for my dentist's appointment, but the dentist was still busy with another patient, so I sat in the waiting room and read some of the old magazines lying there. All the while I was wondering whether to leave and come back another day .



Why past simple here and not past continuous? To me both actions are in progress they are not completed


http://teachermuriel.eu/hotpot/5_gram_mixed_tenses_gaptext_dentist.htm





prepositions - "He plays games in/at/using his laptop"


Which one is correct?



He plays games in his laptop.


He plays games at his laptop.


He plays games using his laptop.




Answer



The form I have encountered is:- He plays games on his laptop. I don't particularly know why - it just seems idiomatic.



Of the three versions you have suggested, the first sounds wrong, as it suggests he is inside his computer. I would argue that the second and third are both correct, though the third has a subtle difference in meaning.


word usage - Present/past perfect when the object is a dead person


I remember (vaguely) reading somewhere that it is wrong to use the present perfect when the subject of a sentence is someone who is long dead:




*Einstein has visited the Philippines.



My question is, What if the dead person is not the subject but an object:



Leo is the best president our country has/had ever had. (The ones who succeeded him were inferior, even our current president.)



Which tense is proper here



Answer



The perfect construction HAVE + past participle imputes a state to the subject.


Consequently you cannot say "Einstein has visited the Phillipines" because (being dead) Einstein is incapable of sustaining the state of having visited the Philippines.



But you can say "Leo is the best president our country has ever had", because your country still exists (I assume) and can sustain the state of having had Leo as president.


However, you are not required to use the present perfect; you may also use the simple past, "Leo is the best president our country ever had".


Furthermore, you may also say "Leo was the best president our country (has) ever had." That really depends on how "present" Leo is to your memory.


What you may not say is "Leo is the best president our country had ever had". The past perfect must be related to a point in the past, but your main clause here is in the present. If you use the past perfect in the relative clause, your main clause must be in the past: "Leo was the best president our country had ever had", meaning he was better than any of his predecessors". But this does not compare Leo to his successors. He may or may not have been better than them.


Sunday, February 26, 2017

algorithm - Path finding in grid for objects that occupy more than one tile


In a grid-based game I am working on, I want to add objects that occupy more than one tile of the grid. Are there any algorithms or techniques to find paths for this kind of objects?



Answer



In general you'll be adapting existing pathfinding algorithms to be width-sensitive. Primarily that means adapting A*, though since your game is grid-based you may find the algorithm for solving fat mazes helpful.


For A*, the most basic solution is to simply add an assertion for width to your calculations, according to your movement rules. However, this will make a mess of your pathfinding code and slows down pathfinding for any regular-sized entities.


Alternatively, you can consider your grid to be a node-based pathfinding network, and for your larger entities you could create a secondary network which accounts for their size, and use that for movement and pathfinding. This has the benefit of allowing you to tailor your pathfinding for larger entities so that it behaves as expected, but means creating multiple maps for each scene and holding them in memory, which may impact games on mobile platforms.


If neither of those methods suits your purposes, you could look for inspiration in navigation mesh pathfinding algorithms, which are inherently width-aware.



Saturday, February 25, 2017

c# - Euler (right-handed) to Quaternion (left-handed) conversion in Unity


I'm having trouble figuring out the proper conversions from Euler angles to Quaternions. The Eulers come from BVH files, which use a right-handed coordinate system (Y is up, Z is forward) and can have any rotation order specified. The Quaternions are in Unity, which is left-handed (Y is up, Z is back).



I'm composing the Quaternions from three AngleAxis rotations, but messing up the order somewhere. So far I can't find understandable and generalized information for doing these types of conversions.


public enum AxisOrder
{
XYZ, XZY, YXZ, YZX, ZXY, ZYX, None
}

public Quaternion EulerToQuat(Vector3 eulerAngles, AxisOrder rotationOrder)
{
// I've tried various combinations of axis angles here, but would
// like to understand what's wrong rather than brute-force

// every combination
var xRot = Quaternion.AngleAxis(eulerAngles.x, Vector3.left);
var yRot = Quaternion.AngleAxis(eulerAngles.y, Vector3.down);
var zRot = Quaternion.AngleAxis(eulerAngles.z, Vector3.back);

switch (rotationOrder)
{
case AxisOrder.XYZ: return (xRot * yRot) * zRot;
case AxisOrder.XZY: return (xRot * zRot) * yRot;
case AxisOrder.YXZ: return (yRot * xRot) * zRot;

case AxisOrder.YZX: return (yRot * zRot) * xRot;
case AxisOrder.ZXY: return (zRot * xRot) * yRot;
case AxisOrder.ZYX: return (zRot * yRot) * xRot;
}

return Quaternion.identity;
}

...and converting translation data like so (I believe this is working):


public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos)

{
return new Vector3(xPos, yPos, -zPos);
}

If anyone can help me better understand how to conceptualize coordinate system conversions, and where I'm going wrong, I'd greatly appreciate it.



Answer



Three points we need to consider:




  1. Matrices and quaternions in Unity multiply from right to left, if we think of each subsequent rotation being applied with regard to the world axes:



    output space or vector = <-- transformation * <--- input space or vector

    As discussed below, if BVH's "XYZ" order means "rotate about the world X axis, then the world Y axis, then the world Z axis" you'd stack your rotations in Unity right-to-left: Z * Y * X


    But, it sounds like BVH's XYZ means "rotate about the local X axis, then the local Y axis, then the local Z axis" which means in Unity we'd match the order left-to-right: X * Y * Z




  2. When switching the handedness of the coordinate system, all rotation angles are negated (if we keep the axis of rotation consistent)




  3. The axes map up like so, based on the conversation above:



    direction    Unity       BVH
    ----------------------------
    right x+ x-
    up y+ y+
    forward z+ z+


So we should be able to get correct conversion between the two spaces with a few small changes:


public Quaternion BvhToUnityRotation(Vector3 eulerAngles, AxisOrder rotationOrder)
{

// BVH's x+ axis is Unity's left (x-)
var xRot = Quaternion.AngleAxis(-eulerAngles.x, Vector3.left);
// Unity & BVH agree on the y & z axes
var yRot = Quaternion.AngleAxis(-eulerAngles.y, Vector3.up);
var zRot = Quaternion.AngleAxis(-eulerAngles.z, Vector3.forward);

switch (rotationOrder)
{
// Reproduce rotation order (no need for parentheses - it's associative)
case AxisOrder.XYZ: return xRot * yRot * zRot;

case AxisOrder.XZY: return xRot * zRot * yRot;
case AxisOrder.YXZ: return yRot * xRot * zRot;
case AxisOrder.YZX: return yRot * zRot * xRot;
case AxisOrder.ZXY: return zRot * xRot * yRot;
case AxisOrder.ZYX: return zRot * yRot * xRot;
}

return Quaternion.identity;
}


And:


public static Vector3 BvhToUnityTranslation(float xPos, float yPos, float zPos)
{
// Flipping x axis instead.
return new Vector3(-xPos, yPos, zPos);
}

terminology - What is the difference between an alpha and a beta release?


What is the difference between an alpha and a beta release? I'm surprised this question hasn't been asked here before.



Answer



In traditional software engineering, Alpha releases will still be introducing new features, while Beta releases will see no new features, but rather polishing up the existing stuff.


However the current development environment in game dev is that both of these are simply "not complete yet", and alpha is generally just "less complete" than beta.


Beta releases will still see new features, while sometimes I'll see alphas that simply try and flesh out existing stuff. And even a few things that stay in alpha or beta forever.



camera - How to avoid gimbal lock


I am trying to write code with rotates an object.


I implemented it as:


Rotation about X-axis is given by the amount of change in y coordinates of a mouse and Rotation about Y-axis is given by the amount of change in x coordinates of a mouse.


This method is simple and work fine until on the the axis coincides with Z-axis, in short a gimble lock occurs.


How can I utilize the rotation arount Z-axis to avoid gimbal lock.




Answer



The simple solution is not to store the orientation of the object as angles around axes (X-, Y-, Z-axis), as for instance in euler angles.


Store the orientation of the object as a matrix or a quaternion.


This can cause gimbal lock, using euler angles:


class Object
{
float m_angleAxisX;
float m_angleAxisY;
float m_angleAxisZ;
};


No gimbal lock:


class Object
{
matrix m_orientation;
};

No gimbal lock either:


class Object
{

quaternion m_orientation;
};

Now whenever the mouse is changed, multiply m_orientation with the orientation change coming from the mouse movement each frame.


Friday, February 24, 2017

grammar - In A Job, At A Job


I have a question about "in a job" here:




Mr. Feliciano remains employed by the department, working in a desk job after two domestic violence offenses and a violation of a court order to stay away from his wife.



How is "in a job" different from "at a job"?




word usage - When are 'if' and 'when' interchangeable?


While translating some technical documentation, I came across this dilemma. Which is better in the below examples?



The value is true if electrical and mechanical damage are covered
The value is true when electrical and mechanical damage are covered




I've read some similar questions about the usage of the word 'if', but it felt like the answers posted there don't apply here.



Answer




When should be used while referring to something that one is certain will happen.



E.g: I will be able to see you in the evening when I get off work.


Meaning: The speaker is sure that she/he will get free from work in the evening.



If should be used while referring to something that might or might not happen.




E.g: I will be able to see you in the evening if I get off work


Meaning: The speaker is not sure that she/he will get free from work in the evening.


If is a possibility, when is a certainty.


In your example if you are not certain whether electrical and mechanical damage will be covered, then you can use 'If'.


unity - Display image a couple seconds after an enemy spawns?


So right now I have enemies that spawn behind objects with a delay.


What I need is to display an image on the screen 5 seconds after each enemy spawns (it's to show the player it has been "attacked") and that image has to disappear after like 2 seconds so.



I know I have to use WaitForSeconds but I don't know how because everything I've tried isn't working.


Here's my code:


 public class TimedSpawn : MonoBehaviour {

public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;

// Use this for initialization

void Start () {
InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}

public void SpawnObject (){
Instantiate (spawnee, transform.position, transform.rotation);

if (stopSpawning) {
CancelInvoke ("SpawnObject");
}

}
}


algorithm - Is there a way to increase the collision check efficiency of a system of n objects?


I'm making a game that consists of many onscreen objects, one of which is the player. I need to know which objects are colliding every iteration.


I made something like this:


for (o in objects)
{
o.stuff();
for (other in objects)

if (collision(o, other))
doStuff();

bla.draw();
}

This has O(n^2), which I'm told is bad. How do I do this more efficiently, is it even possible? I'm doing this in Javascript, and n will usually be lower than 30, will it be a problem if this stays the same?



Answer



With only 30 objects max, you shouldn't need much optimization at all other than to not check the same two pairs against each other more than once per frame. Which the code sample below will cover. But if you're interesting in different optimizations that a physics engine would use then continue reading through the rest of this post.


What you will need is a spatial partitioning implementation, such as an Octree (for 3D games) or Quadtree (for 2D games). These partition the world into sub-sections, and then each sub-section is partitioned further in the same manor, until they have subdivided to a minimum size. This allows you to very quickly check which other objects are in the same region of the world as another, which limits the amount of collisions you must check against.



In addition to spatial partitioning I would recommend creating an AABB (Axis-aligned bounding box) for each of your physics objects. This allows you to check the AABB of one object against another, which is much faster than a detailed per-poly check between objects.


This can be taken another step further for complicated or large physics objects, where you can sub-divide the physics mesh itself, giving each sub-shape its own AABB that you can check against only if two object's AABBs are overlapping.


Most physics engines will deactivate active physics simulation on physics bodies once they come to a rest. When a physics body is deactivated, it need only check for collision against its AABB each frame, and if anything collides with the AABB then it then it will reactivate and do a more granular collision check. This keeps simulation times down.


Also, many physics engines use 'simulation islands', which is where a group of physics bodies that are close together are grouped together. If everything in the simulation island is at rest then the simulation island itself deactives. The benefit of the simulation island is that all of the bodies inside of it can stop checking for collisions once the island is inactive, and the only check each frame is to see if something entered the AABB of the island. Only once something enters the AABB of the island will each of the bodies within the island need to check for collisions. The simulation island also reactivates if any body inside of it starts to move again on its own. If a body moves far enough from the center of the group, it is removed from the island.


In the end you're left with something like this (in pseudo-code):


// Go through each leaf node in the octree. This could be more efficient
// by keeping a list of leaf nodes with objects in it.
for ( node in octreeLeafNodes )
{
// We only need to check for collision if more than one object

// or island is in the bounds of this octree node.
if ( node.numAABBsInBounds > 1)
{
for ( int i = 0; i < AABBNodes.size(); ++i )
{
// Using i+1 here allows us to skip duplicate checks between AABBS
// e.g (If there are 5 bodies, and i = 0, we only check i against
// indexes 1,2,3,4. Once i = 1, we only check i against indexes
// 2,3,4)
for ( int j = i + 1; j < AABBNodes.size(); ++j )

{
if ( AABBOverlaps( AABBNodes[i], AABBNodes[j] ) )
{
// If the AABB we checked against was a simulation island
// then we now check against the nodes in the simulation island

// Once you find overlaps between two actual object AABBs
// you can now check sub-nodes with each object, if you went
// that far in optimizing physics meshes.
{

}
}
}
}

I would also recommend not having so many loops within loops like this, the above sample was just so you got the idea, I would break it up into multiple functions that give you the same functionality as something like what is shown above.


Also, make sure not to alter the AABBNodes container while looping through it, as that could mean missed collision checks. This may sound like common sense, but you would be surprised how easy it is to have things reacting to collisions cause changes you wouldn't anticipate. For example if a collision caused one of the colliding objects to change position enough to remove them from the AABB of the Octree node you were checking then it could alter that container. To solve this I recommend keeping a list of all collision events that occur during the checks, and then after all checks are complete run through the list and send out any collision events.


Thursday, February 23, 2017

word usage - Using the verb 'have' instead of the verb 'eat'



I used to think that the verb have can only be used when we talk about meals, which means an occasion when people sit down to eat food, especially breakfast, lunch, or dinner. But I see native speakers say:



I eat breakfast.



I mean they use the verb eat for a meal like breakfast or dinner. So my questions are:



  1. Is this common to say "I am eating breakfast, lunch or dinner" for a meal time?

  2. Can we use the word have with the word eat interchangeably?


For example when somebody phoned us while we are eating something (at anytime) and asks




What are you doing?



Can we also say:



I having some pizza now. I'll call you back.




Answer



When talking about a particular food or meal, eat and have can function interchangeably most of the time. Of the two, have is the more versatile and generic word:


Let's start with your last example:




I'm eating pizza now. Let me call you back – I don't want my pizza getting cold.
I'm having pizza now. Let me call you back – I don't want my pizza getting cold.



I see no real difference in those two statements. I think I'd be more likely to use the first, but the second wouldn't jar my native ear.


Then your breakfast example:



I eat breakfast every day at 8 o'clock.
I have breakfast every day at 8 o'clock.




Once again, either one of those is okay, although the second sounds a little bit more formal for some reason. In its seventh definition for have, Macmillan mentions:



have (verb) [TRANSITIVE] [NEVER PASSIVE] to eat or drink something. This word is often used in polite offers and requests



  • Can I have another piece of that delicious cake?

  • Let me buy you a drink. What’ll you have?

  • Why don’t you stay and have lunch with us?


I’ll have (=used for requesting food or drink in a restaurant): I’ll have the roast beef, please.




There are a few places where the two words aren't interchangeable. The end of that definition gives one example; if I was ordering at a restaurant, I wouldn't say, "I'll eat the roast beef, please." That might be true, if that's what I'm ordering – but it's simply not idiomatic to say it that way.


Another clue is that have is always transitive. So, it's perfectly fine to say:



I'm starving – let's eat!



but you wouldn't be able to say:



I'm starving – let's have!



Here's one more odd case:




I'm hungry; let's have at that hamburger place.
I'm hungry; let's eat at that hamburger place.



In this case, we can't use have to mean eat, because we're not using the word transitively. We can fix that by saying:



I'm hungry; let's have hamburgers at that place.



However, the first is not necessarily grammatically incorrect, because we could be using the phrasal verb have at. NOTE: This would be a very informal usage of have at, but I give it a mention because it shows how complex and flexible English can be, especially when dealing with informal expressions and eating food. When I was in college, one of my roommates might have said:




I'm hungry; I think I hear hamburgers calling my name!



pronouns - Can 'it' be used to refer to a person?


I read a dialogue. It went like this:


A: Is this your family?
B: Yes, it is.
A: What a big family! Is this your sister?
B: Yes, it is. Her name is Linda. (I think this should be "Yes, she is")
A: Are these your grandparents?
B: Yes, they are. My mum's parents are on the left.


I was confused here by "Yes, it is". I believe it should be "Yes, she is", because "it" generally is referring to person instead of object. But is there any exception, for instance, this dialogue?


Also, 'it' generally is referring to a thing, animal and baby instead of an adult. Isn't it?





lighting - Can I achieve a torchlight effect (lighter area around a light source) in a 2D game?


I am thinking of writing myself a simple 2D game. It will not shine with perfect graphics or gameplay at first, but I'd consider it my first step in PC game development. So, imagine such simple sprite-based 2D game (like Heroes IV or Startcraft BroodWar).



I want the gameplay to support day/night with the according lighting changes and at the same time it will be madness to have to create sprites for every lighting nuance. So, I decided adding a semi-transparent layer on top of other objects will be enough.


The issue with this solution is if I have a light source object in the game (like the hero wearing a torch, or a burning building), there must be a lighter area around it, right? Since I am putting my semi-transparent layer over everything, how would you suggest to achive the torchligt visual effect I want? Maybe redraw that layer adding 'gaps' or differently colored areas based on the lighting effect?



Answer



I don't know what you're programming in, but this is how I handled it in XNA:



  1. On the draw call, a List object is created/cleared.

  2. During the tile draw loop, each tile is checked to see if it has any Lights associated with it. If it does, the Light objects are appended to the List.

  3. The tiles are drawn onto their own RenderTarget2D.

  4. After the tile loop, the list of Lights is iterated through and drawn on their own RenderTarget2D using a texture I made that looks like this:
    Light Texture (Note: I used the R, G and B values here but you should probably use the alpha channel in your actual texture.)


  5. Using a custom shader, I render the tile surface to the screen and pass in the lighting surface as a parameter which gets sampled for the "darkness" value at each pixel.




Now, there's a few things to note:

Regarding Point 4:


I actually have two custom shaders, one to draw the lights to the lighting render target (step 4) and another to draw the tile render target to the screen using the lighting render target (step 5).
The shader used at point 4 allows me to add (what I call) a "luminosity" value. This value is a float that gets multiplied against each pixel in the texture before it's added to the render target so that I can essentially make lights brighter or darker.
At this point, I also take into account the light's "scale" value which means that I can have large or small lights using only one texture.


Regarding Point 5:


Think of the lighting render target as essentially having a value for each pixel from 0 (black) to 1 (white). The shader essentially multiplies that value against the RGB values for a pixel in the tile render target to make the final drawn image.



I also have some more code here where I pass in (to the shader) a value to be used as the day/night overlay colour. This is also multiplied into the RGB values and included in the lighting render target calculations.




Now, this won't allow you to do things like block light from going around objects and whatnot but, at least for my purposes, it's simple and works well.

I've written more detailed blog posts here and here which may help you. I don't have time right now, but if you want I can go into more detail here on gamedev.


Oh, and here's a look at it in my map editor:enter image description here


Why has the industry switched from C to C++?



First of all i would like to have a real answer, i'm always trying to get more from various sources and articles, and when I read things like C++ is slow because it has virtual functions and because of this C is better, i really don't know what to say and think as an human being with a brain. So please avoid to reach this level in your answer/s.


My question is about a massive switch to C++ that was completed, more or less, with Doom 3.


The interesting thing for me is that before this milestone, most of the game engines and the games itself were written in C, just like it was since the Quake era. It's also interesting to note that the ID software decide to completely rewrite the codebase for the IdTech 4 in C++, a massive amount of work that honestly i can't understand without a really good list of reasons.


I'm focusing on Doom 3 because I am mainly interested in the OpenGL world and in my journey i try to stay focused on this topic, so i read a lot about this, but i think that a question like that can be render-API-agnostic without too much problems.


Why at a certain point in time the industry switched massively to C++ ? What are the reasons for the choice that ID made ?



The last thing that i would like to say is that the C language is much more simple to implement and provides a less number of features, because of this has much less chance to be "fragmented" in pieces unlike the C++ really often does. In simplest terms i have much more chances to find a really good C compiler rather than a good C++ compiler with all the features implemented in a good way.


For example the NDK for Android still doesn't have a good C++ support ( with the r8b release ) with all the latest and greatest features, and it's the native toolkit for the most popular mobile OS in the world!


If I had wrote my code in a modern C++ I would probably be in pain now because one of the most popular OS in the world would be off-limits for me. And like Android, many other compilers are not that great.


I should write C++ code referring to a C++ version that is 2-3 release old ?



Answer



C++ does everything C does. You can trivially mix C and C++ in cases where the advantages of C outweigh those of C++. This is a very intentional design decision of C++.


C++ does things that C does not. This includes easy polymorphism, but also easy compile time code generation via templates. This is really handy for things like containers, which are easily C's biggest weakness. It also allows user-defined pointer-like types (smart handles) that save lots of time, as well as user-defined primitive-like types such as vectors and matrices with operator support (also saves lots of time).


Virtual functions are slower than non-virtual functions. However, you must opt in to virtual functions, and a competent programmer does so only when they're beneficial. C programmers have function pointers and often store collections of those in struct referenced by other structs; in other words, they go through extra work to recreate the exact same thing as virtual function tables. In cases where only a single function pointer is needed and no table is required, C++ still fully allows that and is equivalent to C. With a modern compiler, C++ is only slower than C in the specific cases the programmer is opting in to a feature. Also, the virtual function overhead in practice is very small on modem CPUs. Hardware today is designed for C++'s usage patterns, and is even increasingly designed for high-level interpreted langiages' needs.


C++ exceptions historically impose a lot of overhead, making C++ slower even if you're not using them. Exceptions were a terrible thing to add to C++, if for no other reason than the immense increase on complexity involved in writing exception-safe code, and in fact some container designs are literally impossible to make exception safe. Game programmers often ignore exceptions' existence, and even disable them on the compiler. Modern compilers have zero- overhead exceptions (that is, you only pay th cost for them when you actually use them).


C is simpler to learn all the rules of. C++ is a very big, complex language. C++ allows writing higher-level code, producing easier and simpler APIs. Some people want to understand the language easier, some people want to write advanced code easier. It's a trade off between simplicity of understanding what the compiler is doing with a specific piece of code vs the simplicity of writing large complex inter-connected applications. Some folks value one far more than the other, for various reasons.



In the end, C++ is a superset of C. In my opinion, there is no such this as a highly competent C++ programmer who is not also a passable C programmer (though there are a lot of C++ programmers who fall below my bar who would be lost in pure C). While C++ adds facilities to insulate the programmer from much of C, non- trivial C++ code often does need to use C to get things done. This is one of the primary difference between C++ and Java and C#. There's a reason that you often see "C/C++" lumped together, after all.


My personal belief -- which is shared with most other games industry professionals I've interacted with -- is that the enhanced expressiveness and high-level programming facilities of C++ outweigh the increased complexity of the language over C, and most of the other frequent anti-C++ claims made are simply out of date with today's technology.


In a 2D physics engine, how do I avoid useless collision resolutions when objects come to a rest?


In a physics engine I'm developing (for learning) using love-2d, I implemented collision resolutions in this way:


FixedUpdate(dt)  // I use fixed timestep
foreach collide c1 in allNotStaticColliders

c1.integartePhysic // i.e. apply gravitational force..
foreach collider c2 "near" c1 // "near"= I use spatial hashing
if collide(c1,c2)
resolve collision (c1,c2) // the heavy operation
collison callbacks c1
collison callbacks c2
...

animation of objects falling and settling to a stop


As you can see at the end of the gif animation, there's a FPS decay when all colliders are almost grounded over a static object.



the final static state, with 2 FPS


This because the number of collision resolutions grows as objects spend more time touching as they settle. However, many of the calculations are "useless" because objects have already settled into stable positions against each other.


What's the best practice (hopefully not requiring a physics degree) to avoid these "useless" collision detections?


Edit : accepted DMGregory hints and come to this result (not yet optimal)


enter image description here


(Red=static, Blue=active, Green=sleeping)



Answer



I suspected OP already knew this approach so I mentioned it in a comment as just a starting point, but I'll try fleshing it out a bit more...


Most physics engines divide dynamic objects into two groups, "awake," and "sleeping."


Objects sleep when they sit at rest, and wake when moved or accelerated by some outside influence.



A sleeping object behaves like a static object in most respects - its movement isn't integrated over time (because it's at rest, so it has no movement) and the engine ignores collisions between objects that are sleeping or static.


A sleeping object sitting on a static floor doesn't fall through it, despite the lack of a collision response, because all movement integration is skipped for sleeping objects, including gravity.


So, only collisions involving at least one awake dynamic object need to be checked:


Collisions    Static          Sleeping           Awake
------------------------------------------------
Awake | Check Check & Wake Check
Sleeping | No No
Static | No

This can dramatically reduce the number of objects that need active simulation, especially in piles which as illustrated in the question have a lot of mutual collisions to check for little to no net movement.



Sleeping only helps once the objects actually reach rest though, which might take a while.


Some things you can do to reach rest sooner:




  • Have a nonzero minimum speed or momentum, and clamp anything that falls below it to zero. (This is basically an epsilon, commonly used in comparing floats)




  • Use friction, damping, and inelastic collisions to sap energy out of the system and help it reach rest faster overall.





  • Increase friction/damping/inelasticity selectively for slow-moving objects to give them that final nudge to rest, without affecting the behaviour of more energetic bodies.




reported speech - Sequence of tenses: past simple + present perfect


I'm having a problem with reporting the following sentence in a simple-past context:


Person X: Since they arrived, he's been very happy.


The person X said that since they had arrived, he (???) very happy.


Thank you very much!





game loop - Fixed timestep with interpolation & rounding draw positions: jerky animation when the character is not moving


I've implemented a deterministic, fixed timestep system from here: http://gafferongames.com/game-physics/fix-your-timestep/


Everything works fine, output is the same with each step but there's one problem - the animation is jerky while the character isn't moving.


Here's the code responsible for interpolation:


    draw.x = previous.getX() * alpha + current.getX() * (1.0f - alpha);
draw.y = previous.getY() * alpha + current.getY() * (1.0f - alpha);

g2d.drawImage(image, (int)draw.x, (int) draw.y, null);

Here's how 'alpha' looks like:



0.29991353
0.35988057
0.41996205
0.41996205
0.4799291
0.4799291
0.53989613
0.5998632
0.5998632
0.65994465

0.7199117
0.97999954
0.039999668
0.099999785
0.1599999
0.21999958
0.2799997
0.33999982
0.39999995
0.4599996

0.51999974

Let's assume that player's initial position is x = 100 and he's not moving.


His interpolation gives values like 100.0000123123 (which when casted to int gives 100 - OK) but it also gives values like 99.99999998, which when casted to int gives 99 (which makes the jerk).


I don't know how to handle this, maybe just make a statement (if previous != current then do interpolation) and that's it?


Thanks very much


Edit Here's my gameloop:


    float fps = 60;
float dt = 1 / fps;
float accumulator = 0;


Time time = new Time();
float frameStart = time.getSeconds(); - // returns seconds since initialization for ex. 1.32234, 6.43243


while(match_running) {

float currentTime = time.getSeconds();

accumulator += currentTime - frameStart;


frameStart = currentTime;

if (accumulator > 0.2f)
accumulator = 0.2f;

while (accumulator > dt) {
doPhysics(dt);
accumulator -= dt;
}


float alpha = accumulator / dt;
gamePanel.drawGame(alpha); // here's the interpolation


}

Answer



It sounds like you simply need to round the interpolated position to the nearest integer, instead of truncating it (as float → integer conversion normally does). A simple trick (for non-negative values) is simply to add 0.5 to the value before truncating it:


g2d.drawImage(image, (int)(draw.x + 0.5f), (int)(draw.y + 0.5f), null);


(I'm assuming that draw.x and draw.y are floats. If they're integers, you should add the 0.5 to the previous expressions where you calculate them instead.)


Note that this can still produce apparent jitter if the (floating-point) position ever happens to lie precisely halfway between two integer pixel coordinates. If this is an issue for you (which it might not be, depending on how likely your game physics is to trigger this edge case), you can fix it by implementing hysteresis, something like this:


if (abs(draw.x - draw.xInt) > 0.75f) draw.xInt = (int)(draw.x + 0.5f);
if (abs(draw.y - draw.yInt) > 0.75f) draw.yInt = (int)(draw.y + 0.5f);
g2d.drawImage(image, draw.xInt, draw.yInt, null);

This will ensure that the rounded position of the object (stored in draw.xInt and draw.yInt) will not change unless the interpolated position moves more than 0.75 pixels away from the previous rounded position (whereas direct rounding would cause the rounded position to change as soon as the interpolated posititon moves over 0.5 pixels away from it along either axis). If you want, you can fine-tune the tradeoff between stability and precision by replacing the threshold value 0.75 with any value between 0.5 and 1.0, but in practice, 0.75 should be a reasonable default to start with.


(Without seeing the rest of your code, I have no idea if you really need to have both draw.x/ draw.y and draw.xInt / draw.yInt as separate members. But it was the minimal change to your existing code to demonstrate the technique.)


Wednesday, February 22, 2017

grammaticality - Relative adverbs: when vs where



Source: p 39, The Law of Contract, 5 ed (2012), by O’Sullivan and Hilliard



2.83. ... We have seen that the general rule is that displaying goods in shops only constitutes an invitation to treat, although there are good reasons for taking a diff erent approach (paras 2.22–2.23). However, what of a typical website that allows the customer to select the item, enter his payment details and seemingly conclude the agreement online. In this situation, then (absent the terms and conditions of the site providing to the contrary) it is suggested that it is clear that a contract has been concluded ... The natural inference is that a deal has been concluded, as where you get through the checkout at a supermarket and have paid for the goods. You would not expect in these circumstances for the seller to be able to pull out.



What are the similarities and differences? Why not as when? The relative adverb modifies [the exact time that] 'a deal has been concluded', which is NOT 'a place, location, or space' as required below?




  • (Source) "The relative adverb when is used to modify a noun phrase of time. Such noun phrases include nouns that denote periods of time such as, day, week, hour, minute, month, year, and similar events.

  • The relative adverb where is used to modify a noun phrase of place, location, or space.





Answer



Where can also be used to indicate a situation, rather than just a location. The same goes for there; it is used to indicate a location, but by extension also a situation, a description of what happens, rather than the exact place where it happens:



Imagine a situation where the customer refuses to pay.
We have all been there: it's your friends birthday, and you forgot about it.
So, what about the case where more than one person shows interest in the offer?



Have a look, for instance, at this well-known idiom (from Cambridge):




where there's a will there's a way
(saying) used to mean that if you are determined enough, you can find a way to achieve what you want, even if it is very difficult



Notice that in the explanation, if is used with this meaning: when you want it, then it is possible.


grammatical number - "police are" or "police is"


In instructional videos I see on the internet, the teacher says "in the U.S and Canada, they automatically use police as plural noun", if it is already plural, then what's the singular of police?



Answer



Police is a plurale tantum, a word with no singular form.



The police are here.  ← This is okay.
*A police is here.     ← This is not.



Most of the time, if you'd like to talk about a single officer of the law, you say a police officer, or just an officer:




A police officer is here.  ←  This is okay.
Several officers arrived.  ←  This is also okay.



The latter sentence is fine if it's clear from context that you mean a police officer.


But in any case, you can't say *a police.




In this answer, the * symbol indicates that a phrase or sentence is ungrammatical.


grammar - past and present tense in one sentence?



I paid 30 dollars for the deposit and pay monthly rent.



What I want to write is "this apartment costs 30 dollar for the deposit, and I pay monthly rent(, which means I don't have lots of money.)"


I know in English we try to keep the tense in the sentence, but here, it's obvious that I paid the deposit in the past, and I still pay monthly rent since the apartment isn't mine.


Is it okay to write like this? I also tried to start the sentence with "the apartment costs...", but I wasn't sure if it's gonna work in English. Or could you tell me a better option?



Answer



It's fine to use the present and the past here. After all, that's what happens: as you say, you paid the deposit in the past and pay the rent in the present.



Tenses should agree in the same clause, but it's very common to have multiple tenses in the same sentence.



Although I was sick yesterday, I am fine today.
I’m eating the cookies that I baked this morning.



In your sentence, you are connecting two complete sentences with and, and again it's fine to have different tenses in them.



I paid $30 for the deposit.
I pay monthly rent.




The concern with tense agreement is important, but it doesn't mean that the tenses in a sentence have to be the same. It means that whatever the time relationship is needs to be properly and consistently expressed. This is an example of a typical violation of tense agreement:



Yesterday, I went down to the pool hall. I get on a table and start to play. Some guy asks if I want to play for money, and I say ok. We play for a while, and I win $100. I pretty much took him for all he had.



Here is a fairly detailed set of guidelines, with examples.


c# - XNA - Static classes from game libraries executing after content pipeline extensions, how to avoid the problem?


Alright, formulated this way I'm sure it sounds obscure, but I'll do my best to describe my problem.


First, let me explain what's wrong with my real source code.


I'm making a platformer, and here are the current components of my game: a Level, which is holding its own grid of tiles and also the tile sheets and a Tile, which just keeps the name of its tile sheet and index within the tile sheet. All these are within a separate XNA game project, named GameLib.


Here is how my levels are formatted in a text file:


x x . . . . .



. . . b g r .


. . . . . . .


X X X X X X X


Where . represents an empty tile, b represents a blue platform, X represents a block with a random color, etc.


Instead of doing all the work of loading a level within the Level class, I decided to take advantage of the content pipeline extension and create a LevelContentPipelineExtension.


As soon as I started, I quickly realized that I didn't want to hard-code 20+ lines of the kind:


if (symbol == 'b')
return new Tile(/*...*/);

So, in the hope of at least centralizing all the content creation into one class, I made a static class, called LevelContentCreation, which holds the information about which symbol creates what and all this kind of stuff. It also holds a list of all the asset paths of the tile sheets, to load them later on. This class is within my GameLib game library project.



The problem is, I'm using this LevelContentCreation static class in both my Level class (to load the actual tile sheets) and my content pipeline extension (to know which symbol represents what tile)...


And here's how my LevelContentCreation class looks like:


public static class LevelContentCreation
{
private static Dictionary AvailableTiles =
CreateAvailableTiles();

private static List AvailableTileSheets { get; set; }

/* ... rest of the class */

}

Now, since the LevelContentCreation class is part of the game library, the content pipeline extension tries to use it but the call to CreateAvailableTiles() never happens and I'm unable to load a Level object from the content pipeline.


I know this is because the content pipeline executes before the actual compilation or something like that, but how can I fix the problem?


I can't really move the LevelContentCreation class to the pipeline extension, because then the Level class wouldn't be able to use it... I'm pretty lost and I don't know what to do... I know these are pretty bad design decisions, and I'd like it if somebody could point me in the right direction.


Thank you for your precious time.


If anything is not clear enough or if I should provide more information/code, please leave a comment below.




A little more information about my projects:




  • Game - XNA Windows game project. Contains references to: Engine, GameLib and GameContent

  • GameLib - XNA game library project. Contains references to: Engine

  • GameContent - XNA content project. Contains references to: LevelContentPipelineExtension

  • Engine - XNA game library project. No references.

  • LevelContentPipelineExtension - XNA content pipeline extension. Contains references to: Engine and GameLib


I know close to nothing about XNA 4.0 and I'm a little bit lost about how content works now. If you need more information, tell me.



Answer



In cases where you are using singletons, static classes, or global variables, 99% of the time what you should really be using is a game service. Game services are used when you want one instance of a class available to all other classes, but the tight coupling of the other options gives you a funny taste. Services also don't have the instantiation problems that you've seen, they're more reusable, and they can be mocked (if you care about automated unit-testing).


To register a service, you need to give your class its own interface. Then just call Game.Services.AddService(). To later use that service in another class, call Game.Services.GetService().



In your case, your class would look something like this:


public interface ILevelContentCreation
{
void SomeMethod();
int SomeProperty { get; }
}

public class LevelContentCreation : ILevelContentCreation
{
private Dictionary availableTiles =

CreateAvailableTiles();

private List AvailableTileSheets { get; set; }

public void SomeMethod() { /*...*/ }
public int SomeProperty { get; private set; }

/* ... rest of the class ... */
}


At some point at the start of the program, you'd have to register your service with Game.Services. I prefer to do this at the start of LoadContent(), but some people prefer to register each service in that class's constructor.


/* Main game */
protected override void LoadContent()
{
RegisterServices();

/* ... */
}

private void RegisterServices()

{
Game.Services.AddService(typeof(ILevelContentCreation), new LevelContentCreation());
}

Now whenever you want to access your LevelContentCreation class in any other class, you would simply do this:


ILevelContentCreation levelContentCreation = (ILevelContentCreation) Game.Services.GetService(typeof(ILevelContentCreation));
levelContentCreation.SomeMethod(); //Tada!



As a side note, this paradigm is known as Inversion of Control (IoC), and is widely used outside of XNA development as well. The most popular framework for IoC in .Net is Ninject, which has nicer syntax than the Game.Services methods:



Bind().To(); //Ninject equivalent of Services.AddService()
ILevelContentCreation levelContentCreation = kernel.Get(); //Ninject equivalent of Services.GetService()

It also supports dependency injection, a form of IoC which is slightly more complex, but much nicer to work with.


[Edit] Of course, you can get that nice syntax with XNA too:


static class ServiceExtensionMethods
{
public static void AddService(this GameServiceContainer services, T service)
{
services.AddService(typeof(T), service);

}

public static T GetService(this GameServiceContainer services)
{
return (T)services.GetService(typeof(T));
}
}

Tuesday, February 21, 2017

Please help me to find out which word works better in my sentences from among "mark, grade, score and point"




What is the most natural sentence from among the listed sentences bellow:


Note: all the sentences are self-made.


Example one) Suppose a student says:




  • I got a very low mark in the midterm test.

  • I got a very low grade in the midterm test.

  • I got a very low score in the midterm test.

  • I got a very low point in the midterm test.





  • For me only the first one sounds natural.


Example two)


here suppose a teacher is talking to their students:




  • I want to read out the test marks to you.


  • I want to read out the test grades to you.

  • I want to read out the test scores to you.

  • I want to read out the test points to you.




  • For me in this specific sentence, all words work the same and convey the same message.




software engineering - What math should all game programmers know?



Simple enough question: What math should all game programmers have a firm grasp of in order to be successful?


I'm not specifically talking about rendering math or anything in the niche areas of game programming, more specifically just things that even game programmers should know about, and if they don't they'll probably find it useful.



Note: as there is no one correct answer, this question (and its answers) is a community wiki.


Also, if you would like fancy latex math equations, feel free to use http://mathurl.com/.




Monday, February 20, 2017

relative pronouns - When can we interchange “who/which" and "that”?


So far I thought the words who and that are usually interchangeable:





  1. There is the man who saw me.





  2. There is the man that saw me.





Both sentences seem fine, who can be replaced with that. But in the following examples:






  1. This is the man to whom I spoke.




  2. This is the man to that I spoke.





The #2 sounds odd, which is why I don’t think it might be correct.


The same observation for the words which and that, while






  1. This is the ball which we used today.




  2. This is the ball that we used today.





Seem to be in order and which can be replaced with that. But in the following examples the #2 sounds odd again.






  1. This is the ball with which I scored.




  2. This is the ball with that I scored.






I wonder if there’s any rule regarding the interchangeability of the above mentioned words.



Answer



Your observations are pretty precise.


In Standard English (whatever that is), relative that is not used a) to head non-restrictive ('supplementary') relative clauses or b) as the object of an immediately preceding ('pied-piped') preposition. Only wh- forms (who/whom, which) are used in these contexts.



a) That is John, {whom/that} I interviewed yesterday.
b) This is the ball with {which/that} I scored.



However, that may head a clause in which it acts as object of a 'stranded' preposition:




okThis is the ball that I scored with.



In colloquial English rule a) is relaxed, because in improvised speech the distinction between restrictive and non-restrictive clauses is not so strongly marked as it is in composed speech—a restrictive clause often occurs to a speaker 'after the fact', so it is pragmatically non-restrictive even when it is semantically restrictive. But rule b) is almost universally observed in all registers.




marks an expression as unacceptable


opengl - Random black pixels GLSL shader bug


I've recently been following a tutorial for writing a game engine in Java using LWJGL 2. I followed the tutorial for writing a fragment shader that utilizes spotlights in GLSL.


The example game currently running in the engine is a spotlight that follows the camera and a plane mesh with a tile texture. When I run the game, when viewing the mesh at certain distances and angles, namely close distances and sharp angles, I run into this interesting bug when certain pixels just go black. This has only occurred when I modified the fragment shader to include spotlights. This can only mean that there is a bug in the fragment shader itself.


The fragment shader code is below. What I believe to be the problematic code is marked with a comment below in the function calcSpotLight.


Update: I have found that the problem was indeed in my graphics card's driver. I just updated the driver and reran the program and indeed received no black pixels.


Edit: It appears that the problem is indeed in the calcSpotLight function, but within the calcSpotLight function, the problem is the calcPointLight function. I still don't know what the exact problem is, but that should narrow down the possible errors.



#version 330

const int MAX_POINT_LIGHTS = 4;
const int MAX_SPOT_LIGHTS = 4;

in vec2 texCoord0;
in vec3 normal0;
in vec3 worldPos0;

out vec4 fragColor;


struct BaseLight
{
vec3 color;
float intensity;
};

struct DirectionalLight
{
BaseLight base;

vec3 direction;
};

struct Attenuation
{
float constant;
float linear;
float exponent;
};


struct PointLight
{
BaseLight base;
Attenuation atten;
vec3 position;
float range;
};

struct SpotLight
{

PointLight pointLight;
vec3 direction;
float cutoff;
};

uniform vec3 baseColor;
uniform vec3 eyePos;
uniform vec3 ambientLight;
uniform sampler2D sampler;


uniform float specularIntensity;
uniform float specularPower;

uniform DirectionalLight directionalLight;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform SpotLight spotLights[MAX_SPOT_LIGHTS];

vec4 calcLight(BaseLight base, vec3 direction, vec3 normal)
{
float diffuseFactor = dot(normal, -direction);


vec4 diffuseColor = vec4(0,0,0,0);
vec4 specularColor = vec4(0,0,0,0);

if(diffuseFactor > 0)
{
diffuseColor = vec4(base.color, 1.0) * base.intensity * diffuseFactor;

vec3 directionToEye = normalize(eyePos - worldPos0);
vec3 reflectDirection = normalize(reflect(direction, normal));


float specularFactor = dot(directionToEye, reflectDirection);
specularFactor = pow(specularFactor, specularPower);

if(specularFactor > 0)
{
specularColor = vec4(base.color, 1.0) * specularIntensity * specularFactor;
}
}


return diffuseColor + specularColor;
}

vec4 calcDirectionalLight(DirectionalLight directionalLight, vec3 normal)
{
return calcLight(directionalLight.base, -directionalLight.direction, normal);
}

vec4 calcPointLight(PointLight pointLight, vec3 normal)
{

vec3 lightDirection = worldPos0 - pointLight.position;
float distanceToPoint = length(lightDirection);

if(distanceToPoint > pointLight.range)
return vec4(0,0,0,0);

lightDirection = normalize(lightDirection);

vec4 color = calcLight(pointLight.base, lightDirection, normal);


float attenuation = pointLight.atten.constant +
pointLight.atten.linear * distanceToPoint +
pointLight.atten.exponent * distanceToPoint * distanceToPoint +
0.0001;

return color / attenuation;
}

vec4 calcSpotLight(SpotLight spotLight, vec3 normal)
{

vec3 lightDirection = normalize(worldPos0 - spotLight.pointLight.position);
float spotFactor = dot(lightDirection, spotLight.direction);

vec4 color = vec4(0,0,0,0);

//This is likely the problematic code, but I'm not 100 percent sure

if(spotFactor > spotLight.cutoff)
{
color = calcPointLight(spotLight.pointLight, normal) *

(1.0 - (1.0 - spotFactor)/(1.0-spotLight.cutoff));
}

return color;
}
void main()
{
vec4 totalLight = vec4(ambientLight,1);
vec4 color = vec4(baseColor, 1);
vec4 textureColor = texture(sampler, texCoord0.xy);


if(textureColor != vec4(0,0,0,0))
color *= textureColor;

vec3 normal = normalize(normal0);

totalLight += calcDirectionalLight(directionalLight, normal);

for(int i = 0; i < MAX_POINT_LIGHTS; i++)
{

if(pointLights[i].base.intensity > 0)
totalLight += calcPointLight(pointLights[i],normal);
}

for(int i = 0; i < MAX_SPOT_LIGHTS; i++)
{
if(spotLights[i].pointLight.base.intensity > 0)
totalLight += calcSpotLight(spotLights[i],normal);
}


fragColor = color * totalLight;
}

I checked to see if there was maybe some division by zero problem or something of the like, but I can't for the life of me figure out what the problem actually is. And since debugging in GLSL is nearly impossible, I've decided that my last possible option is to post my question here.


Here are some example images of the bug in game:


enter image description here Here, the black pixels can be seen at the bottom of the spotlight


enter image description here Here, the black pixels are mostly at the edge of the spotlight


Any help would be appreciated.




passive voice - How to parse "It might be possible for a single woman to be accepted as a foster parent"?



It might be possible for a single woman to be accepted as a foster parent.



I have two explanations:



(1) (A single woman to be accepted as a foster parent) might be possible. = That a single woman can be accepted as a foster parent might be possible.


(2) For a single woman , to be accepted as a foster parent might be possible.




Meaning of "Don't settle for no f-ing s#*t"



I have seen this phrase in pictures:



"Don't settle for no fuck shit"



What does that mean?


enter image description here


enter image description here



Answer



As in many other languages, in English "shit" is an all-purpose scatological pejorative. It can mean various things depending on the context. In this case, it means "stuff that bothers or angers you, or that you just don't like." A related expression is:




I don't have to take that kind of shit from you. (= What you are doing annoys me, and I'm not going to tolerate it)



"Fucking", aside from its more literal meanings, is an all-purpose intensifier when added to some other expression:



That movie was fucking awesome! (= that movie was very good)



Put together "fucking shit" is stuff that really bothers, angers, or disgusts you.


You might find this confusing because the expression uses a double negative. Double negatives are generally considered to be grammatically incorrect, but are nevertheless common in various dialects. Often you can make sense of double negative sentences by changing the second "no" to "any":



That won't do you no good (= That won't do you any good)



She never hangs out with nobody (= She never hangs out with anybody)


You can't do nothing about it (= You can't do anything about it)



All together, the shirt says something like:



Don't put up with / settle for anything that really bothers or annoys you, or that you really dislike.



Of course, without the profanity, it doesn't have the same emotional impact.


Since it's entirely individual judgement what exactly counts as "shit" (in this context), you'd have to ask the person wearing the shirt what it means to her. However, you can take it as general advice, to live your life without ever settling for fucking shit, whatever that means to you.


Side note: Wearing clothing with blatant profanity on it is usually considered uncouth, even if most people might agree with the sentiment.



(Edit) The shirt actually says "fuck shit" instead of "fucking shit", but this doesn't change the meaning in any significant way. It's possible that there just wasn't enough room on the shirt for "fucking" -- given the way the letters are spaced, it looks like she might have done it herself.


Sunday, February 19, 2017

2d - Dynamic thruster balancing of space ship


The space ships in my game a meant to be player-built with an arbitrary amount of thrusters attached anywhere with any rotation. I currently have some dirty code to rotate the ship to a given angle (accelerating and decelerating).


Here's an example of a symmetrical ship facing where the red line points, being told to rotate left.


Ship



However, as you would imagine, depending on where the player has put the thrusters, sometimes undesired linear forces are affecting the ship. In this case, the ship starts moving forward.


I'm elaborating on whether it's possible to find the maximum thrust a thruster can apply to cause no linear velocity. (In the above case that would be none since there's nothing to counteract the forces from the rear thrusters, and the front ones kill eachother).


What I've come up with so far is a formula to determinate the "turn efficiency" e.g. how much rotation is caused in relation to linear movement.


a - position vector to thruster a b - position vector to thruster b v1 - force from thruster a v2 - force from thruster b


efficiencyDelta = a.cross(v1) / |v1| - ( a.cross(v1) + b.cross(v2) ) / |v1 + v2|


, basically "a.cross(v1 * t) / |v1|" is supposed to be the turn efficiency. And then we subtract it by the turn efficiency of the thrusters combined, to see if firing the new thruster is worth it.


Problem arises when I realize that thrusters aren't surposed to be on/off, but can vary their thrust from 0 to 1. And how to go about when the player wants the ship to go forward. Ofcourse, there would need to be a balance of how much to rotate/move.


I'm no rocket scientist so I'm hoping there's someone who can tell me if it's even possible to calculate the throttle of each thruster this way and give me a push in the right direction.


Thank you for taking the time! / Kim




adverbs - Are there places where we can't use 'much', but 'very much' is OK?


I think there are cases when you can use very much but not much:




  • I would very much like to meet him.

  • *I would much like to meet him.




I don't know what grammar rule addresses this difference. This is quite bizarre for me; all very does is intensifying much, so very much should be the same as much, yet it isn't!


Why is this difference? And where exactly are these two different and where are they the same?




vb.net - What are the free 3d OOP game engines?




Could you please list a few free 3d OOP game engines, along with the pros and cons? Embeddable in VB.net would be great.




graphics programming - How do I get a new license for gDEBugger after the 1 free year?



I downloaded the gDEBugger from gremedy over a year ago, with their one year free license. The license has since expired and their site says that I'll be presented with the option for 1 year free license the first time I run it after install. This doesn't happen when re-installing, it just tells me the license has expired. How do I get a new license? I use this regularly for debugging shader problems and performance testing my game.



Answer



Try deleting the C:\ProgramData\GraphicRemedy directory, run gDEBugger again and ask for a new temporary license.


If you are using linux, check the .gremedy directory and remove the existing license file.


2d - Scale camera to fit screen size unity


My background and gameobjects are 2d sprites not UI images ,I want to know how to make my background scale with screen size and positions of 2d sprits on it don't change after building game (webGl) like scale canvas with screen size and anchor points in UI elements .


Before building the game enter image description here


After building enter image description here




grammar - Which part of speech is "Be assured"?



Which of the spans in 1.1 is the stronger? Be assured, you are in numerous company if you pick the left one at first glance, where the struts and wires are doing nothing useful at all.




Could you please tell me what is "Be assured" here?


I mean whether it is an adverb, adjective, so on?


And, would you please show me some examples exactly like such the following, considering my original sentence?



Be assured, ...




Answer



This kind of constructions are mostly found in conversations. But they don't remain in the realm of conversation only. They are used without the subject as the subject is predictable and obvious. Here in your example the subject that is missing from "be assured" is "you". The full sentence will be "You be assured..."


More example sentences -






  1. Take it from me they can't come back to the game from this stage. = You take it from me that they can't come back to the game from here.




  2. Listen, be careful with that. You are dealing with something sensitive. = You listen, you be careful with that. You are dealing with something sensitive.






N.B I completely agree with MMJZ. I added this answer to add something extra to what he already told, and of course to provide some more example sentences.


Saturday, February 18, 2017

grammar - the use of 'would' in the following sentence



Can we use 'would' rather than 'might' in the following sentence?




Some students find it more difficult to sustain their motivation online than they might as part of a real learning group.





Is "very much" an adverb or an adjective?


I would like to know what "very much" is in terms of grammatical classification.


Is it an adjective, adverb or other part of speech?





progressive aspect - “To sit waiting” vs. “to be sitting waiting”



  • I'm sitting waiting for a bus.

  • I sit waiting for a bus.


There is the situation that I'm sitting on a bench and I'm waiting for a bus in a bus station.


If I want to tell my friend that by a phone. I say "I sit waiting for a bus." It is right?



Somewhere, I have heard "I'm sitting waiting for a bus" means that I'm sitting up and down (it doesn't mean an exercise) while waiting a bus, as a bus has arrived. Therefore Someone tell me you would use I sit waiting for a bus.


Simply, I think I'm sitting + I'm waiting = I'm sitting waiting.


How are the two sentences different?


also



  • I sitting waiting for a bus.

  • I sitting and waiting for a bus.


differ?




word request - An appropriate term for an overly by-the-rules person


In Swedish, we've got a term that loosely translates as paragraph jockey. It refers to a person, often a clerk or a referee, who is following all the rules, prescriptions and agreements ad absurdum. The application is slightly derogatory but not vulgar.


In many cases, the term is used when a referee or a bureaucrat makes a call and, while being correct rule-wise, they miss the point of the system that the said rule is made to support.


The result of such call or decision may vary from non-essential, insignificant changes up to a totally weird and unintended destruction of the greater good.


Is there a term like that in English? My google-fu gave me Jack-in-office but when I wrote that to a friend, they didn't get the point at all.




architecture - How to design an AssetManager?


What is the best approach to designing an AssestManager that will hold references to graphics, sounds, etc. of a game?


Should these assets be stored in a key/value Map pair? I.e. I ask for "background" asset and the Map returns the associated bitmap? Is there an even better way?


Specifically I'm writing an Android/Java game, but answers can be generic.



Answer



It depends on the scope of your game. An asset manager is absolutely essential for larger titles, less so for smaller games.


For larger titles you have to manage problems such as the following:




  • Shared assets - is that brick texture being used by multiple models?

  • Asset lifetime - is that asset you loaded 15 minutes ago no longer needed? Reference counting your assets to make sure you know when something is finished with etc

  • In DirectX 9 if certain asset types are loaded and your graphics device gets 'lost' (this happens if you press Ctrl+Alt+Del amongst other things) - your game will need to recreate them

  • Loading assets in advance of needing them - you couldn't build big open world games without this

  • Bulk loading assets - We often pack lots of assets into a single file to improve loading times - seeking around the disc is very time consuming


For smaller titles these things are less of an issue, frameworks like XNA have asset managers within them - there is very little point in re-inventing it.


If you find yourself needing an asset manager, there is no one-size-fits-all solution really, but I've found that a hash map with the key as a hash* of the filename (lowered and separators all 'fixed') works well for the projects I've worked on.


It is usually not advisable to hardcode filenames in your app, it is usually better to have another data format (such as xml) depict filenames to 'IDs'.




  • As an amusing side note, you normally get one hash collision per project.


ellipsis - When to add "in" before "this way" or "adj +way:



It's my own example:"I was just born this way" "you should carry out this ceremony in more simple way" "he scolded me (in) the worst way"




java - Avoid threads/multithreading



So here is the thing: I have made a thread for each generator an outpost has. We have a total of 6 outposts , 5 generators each. 3 teams, engineers can only repair generators and prevent their overload. In order to make the whole generator logic I use threads. If the thread gets interrupted it means that the generator got prevented from being destroyed , if the thread is finished normally , the generator got destroyed and if the generator is destroyed an engineer can repair them. Is there any way of avoiding threads because in spite of high cpu usage there are also other thread issues.


The same thing happens with the shield regeneration of each player. I'll just post the code for this one:


public static void startRegenerate(final Player p){

if(already_regenerating_arraylist.contains(p.getId())){
return;
}


final int previous_shield_lvl = p.getShieldLevel();
final int previous_hp_lvl = (int) p.getHealth();

Thread reg = new Thread(){

@Override
public void run(){

already_regenerating_arraylist.add(p.getUniqueId());
try {

sleep(3000);
} catch (InterruptedException e1) {
}

for(;;){

if(p.getShieldLevel() >= 20){
p.setShieldLevel(20);
already_regenerating_arraylist.remove(p.getUniqueId());
break;

}

if(p.getHealth() < previous_hp_lvl || p.getShieldLevel() < previous_shield_lvl){
already_regenerating_arraylist.remove(p.getUniqueId());
break;
}

p.setFoodLevel(p.getFoodLevel() + 6);

try {

sleep(1000);
} catch (InterruptedException e) {
}
}

}

};

reg.start();

}

After having more than 50 players stuff stop working (lag , etc...)



Answer



Rule number one of multithreading: avoid it. You might think: "Well, there are things in my game which are supposed to happen simultaneously. Wouldn't it be much more intuitive when each thing happens in its own thread?" No, it's not. Using multithreading makes your program magnitudes more complex. You have no control over how much CPU time the operating system gives to each of your threads and when exactly it switches between them, so they will become out of sync unless you manually synchronize them by making them wait for each other to finish. This introduces very hard to reproduce bugs due to race conditions and deadlocks. Sure, there are language features like synchronized to avoid some of them, but these have pitfalls on their own and are easy to forget.


The only argument ever for using more than one thread is performance.


Use threading when you have some calculation which is so CPU-intense that you need more than one core. But in that case don't use more threads than the machine has (currently idle) CPU cores and make sure each thread is able to do a lot of work before being forced to yield or wait for another thread, or you will gain nothing except burdening the OS with additional thread context switches. That's likely what slows down your application.


Another reason to use threading is when you have any network, database or file IO and don't want your application to become unresponsive in the meantime. However, in that case most environments should provide an asynchronous API which does the dirty multithreading stuff for you. In Java, thats Non-blocking IO.


OK, so how else could you structure your application?


You could have a standard game loop.



while game is running
render a frame
check time elapsed since last gamestate update
update gamestate taking the elapsed time into account

give each object in your game an update() function and call that function of each object in a for-loop in your global update gamestate function.


There are two different approaches how to take the elapsed time into account. Either the delta-t model where you pass the difference between real-world time and processed time to the update-function and take it into account for all calculations, or the tick-model where you agree on the internal ticks-per-second rate with which your game logic works (usually 100), check how many ticks your simulation is behind real-time, and call the update-function that many times.


Which one is the better method depends on the game and your personal preference. I personally prefer the tick-method because it is a lot easier to write the update-functions when you don't have to take the delta-t factor into account for everything, but the delta-t method can sometimes (not always!) be a bit faster.


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...