Friday, February 14, 2020

usage - Are there solutions to know which verbs are followed by the infinitive or the gerund?



I can know some patterns like these.




I enjoy cooking.


He wants to swim.



But for other verbs like admit, allow, agree, appear and so on. It seems that I have to remember which verbs are followed by infinitives or gerund.


I know I have to listen a lot. At least I know how to use "can't help" from this song "but I can't help falling in love with you...."


But for learner do we have only to remember them or are there any other solutions?




grammaticality - Gerunds:Having+past participle and being+past participle


Here are two sentences:




My having been to South-Korea helped me learn the languages when I took the classes.


Being accepted to Harvard university was the greatest day of my life.



Is it common or natural way to write such 'having+past participle' and being+past participle construction in formal writing? Or should I use the other alternatives for these? Are these construction encouraged in writing? And What about in spoken English? Thanks.


source http://www.myenglishteacher.net/gerunds.html



Answer



The two examples which the OP cited are formal, the first being very formal; and both are in the passive voice.


If I were to recast the two examples into the active voice, I would suggest the following:





  1. My having been to South-Korea helped me learn the languages when I took the classes.



    • The time I spent in South-Korea helped me learn the languages …




  2. Being accepted to Harvard university was the greatest day of my life.



    • The time Harvard University accepted my application, was the greatest day of my life





Note that Harvard University is capitalised, because it is the full and complete name of the institution.





  • Is the use of gerund + past participle common in formal writing?


It is still used in formal writing but it is, without a shadow of a doubt, becoming less common in speech. If it's used sparingly in an essay, an English teacher might be favourably impressed but if the student resorts to using this type of construction whenever possible, it will sound at best antiquated and, at worst, pompous.


Some people maintain that the passive voice should be used whenever it is required, while others claim an overuse of the passive voice actually presents poor style.



Supporters of Strunk and White's The Elements of Style (1918) will say: “Use definite, specific, concrete language”, The active voice is usually more direct and vigorous than the passive:, and The habitual use of the active voice, however, makes for forcible writing. This is true not only in narrative principally concerned with action, but in writing of any kind.


In the end, choose the construction which you feel most confident with.


P.S Not all the examples of “tame sentences” cited by S&W are actually in the passive voice, and none begin with the gerund + past participle, just thought I'd warn you.


unity - Can I clip a collection of geometry to render only inside a particular worldspace volume?


I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.)


How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of:


Camera.DoNotRender(new Vector3(100, 0, 0));

I have been looking into using some MonoBehaviour messages such as OnPreRender, OnRenderObject, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non-rendered pixels should be rendered, but that is not my priority.


The map is made up of 100s of little renderers:



enter image description here


How can I have my Camera not render specific world space pixels?



Answer



One way to do this is with the clip function in a shader, which aborts rendering of a pixel if it fails a particular condition.


This lets you create custom-shaped clipping regions, but it has a downside: by the time you reach the clip test, most of the work of rasterizing the object is already done, so you end up paying a significant amount for the invisible portions of the model that don't actually get drawn in the end.


Be sure to profile this to determine whether it's an issue in your particular application - it might not be. If it is, there are some additional tricks you can use with depth, stencil, and off-screen buffers to exclude some of the redundant geometry.




Edit: a neat trick I've just learned is if you introduce a NaN or infinity into a vertex position, you can abort rendering of triangles using that vertex. So this can let you do some of this clipping per-vertex instead of solely per fragment, saving some rasterization costs.


v.vertex.x /= step(outOfBounds, 0.1f);


You need a margin like that 0.1f there that's bigger than your typical triangle - otherwise you can have a vertex outside your clipping margin abort a whole triangle that's partly inside the clipping volume.


Note that this doesn't seem to be an officially documented feature, just something GPUs tend to do 'cause how else are they going to render that triangle? ;)




Here's an example shader using this approach - use something like this on your map material to achieve the clipping:


Shader "Custom/ClipVolume" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0


// Expose parameters for the minimum x, minimum z,
// maximum x, and maximum z of the rendered volume.
_Corners ("Min XZ / Max XZ", Vector) = (-1, -1, 1, 1)
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200

// Allow back sides of the object to render.

Cull Off

CGPROGRAM

#pragma surface surf Standard fullforwardshadows
#pragma target 3.0

sampler2D _MainTex;

struct Input {

float2 uv_MainTex;
float3 worldPos;
};

half _Glossiness;
half _Metallic;
fixed4 _Color;

// Read the min xz/ max xz material properties.
float4 _Corners;


void surf (Input IN, inout SurfaceOutputStandard o) {

// Calculate a signed distance from the clipping volume.
float2 offset;
offset = IN.worldPos.xz - _Corners.zw;
float outOfBounds = max(offset.x, offset.y);
offset = _Corners.xy - IN.worldPos.xz;
outOfBounds = max(outOfBounds, max(offset.x, offset.y));
// Reject fragments that are outside the clipping volume.

clip(-outOfBounds);

// Default surface shading.
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG

}
// Note that the non-clipped Diffuse material will be used for shadows.
// If you need correct shadowing with clipped material, add a shadow pass
// that includes the same clipping logic as above.
FallBack "Diffuse"
}

Here's what it looks like on Unity's "Ethan" model:


Example of using the shader above to clip a character mesh


And here it is using the triangle aborting trick above to remove some of the excess geometry outside the clipping volume:



Example showing cropping of the underlying geometry


Entity/Component based engine rendering separation from logic


I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic.


I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box?



Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.


With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers.


The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.


Is such approach somehow wrong?



Answer




Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.



In some entity systems, components only contain logic. In others, they only contain data. In yet others, they contain both. I'd certainly argue that putting the actual render commands (as in the OpenGL or D3D code) into the rendering component isn't ideal (see my answer here regarding the question "should objects render themselves?", which is the same principle under discussion). However, it is certainly possible to do so and even to do so in a fashion that allows the implementation of the rendering components to be swapped without having to alter the consumers of the component system. Doing so just involves any typical implementation-hiding technique.


It's acceptable, and common, to have a "visual component" that contains a reference to some renderable object that comes from the lower-level rendering subsystem and have that component export behavior or interface to allow the appearance data to be specified by other components (such as ones containing scripts).




The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.


Is such approach somehow wrong?



I don't really see what you gain by having a "camera" component. It seems like a very heavyweight operation inject into the entity system. Does, for example, the presence of the camera component mean that you always get a scene rendered from that camera's perspective? How then do you determine which of those scenes to present to the user, and where? It feels like -- without knowing more about this design -- you'd be shoving a lot of unrelated responsibility into the camera component. I'd prefer to see that responsibility handled by something external to the entity system.


Otherwise, that sounds like a perfectly usable system. It will have it's pros and cons, of course, but those will become apparent in practice and many of them will be specific to your needs and/or the needs of your game.


Collision Resolution


I know quite well how to check for collisions, but I don't know how to handle the collision in a good way.


Simplified, if two objects collide I use some calculations to change the velocity direction. If I don't move the two objects they will still overlap and if the velocity is not big enough they will still collide after next update. This can cause objects to get stuck in each other.


But what if I try to move the two objects so they do not overlap. This sounds like a good idea but I have realised that if there is more than two objects this becomes very complicated. What if I move the two objects and one of them collides with other objects so I have to move them too and they may collide with walls etc.


I have a top down 2D game in mind but I don't think that has much to do with it. How are collisions usually handled?


This question is asked on behalf of Wooh




Answer



Daniel Kodicek covers this topic in great detail in his book, Mathematics & Physics for Programmers.


Kodicek does two things to achieve natural-looking collision resolution:



  • His collision detection function calculates the exact time two objects will collide.

  • He recalculates new velocities at the time of collision, so objects never overlap.


I uploaded a demo based on Kodicek's collision detection and resolution.


update: Here's a collision detection & resolution algorithm that is very similar to Kodicek's method. With source code. I still recommend Kodicek's book, as his algorithm is implemented slightly differently and much more thoroughly explained.


Thursday, February 13, 2020

java - Maintaining velocity of free fall body using Box2D in libGDX


I want to maintain the speed of a free-falling Box2D body using LibGDX. I'd like the vertical velocity increase with the level. I've applied a linear impulse and velocity actually increases like this:



fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);

I think this is a bad approach, because the speed has increased only a little and I applied as much as -800 units of impulse.


Below is my render function of game play screen class:


    public void render(float delta) {

Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

// camera.update();

// batch.setProjectionMatrix(camera.combined);
batch.begin();

backgroundSprite.draw(batch);
grassSprite.draw(batch);

// bucketSprite.draw(batch);

Iterator bodies = world.getBodies();


while(bodies.hasNext()){

Body body = bodies.next();

if(body.getUserData() != null){

String spriteName = (String) body.getUserData();

Sprite sprite = (Sprite) userDataMap.get(spriteName);


if(spriteName.equals("bucket"))
sprite.setPosition(body.getPosition().x + 345, body.getPosition().y + 230);
else
sprite.setPosition(body.getPosition().x + 375, body.getPosition().y + 225);

sprite.draw(batch);

}
}


batch.end();

fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);
// debugRenderer.render(world, camera.combined);
world.step(1/60f, 8, 3);
// world.clearForces();
}

My world is:


world = new World(new Vector2(0, -10), true);


Orthographic camera:


camera = new OrthographicCamera(800, 480);

My fruitBody fixture def is:


bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(0, 100);

// shape
CircleShape ballShape = new CircleShape();

ballShape.setRadius(15f);

//fixture
fixtureDef.friction = .1f;
fixtureDef.restitution = .7f;
fixtureDef.shape = ballShape;
fixtureDef.density = .2f;

fruitBody = world.createBody(bodyDef);
// fruitBody.setUserData(fruitSprite);

fruitBody.setUserData("fruit");
fruitBody.createFixture(fixtureDef);

I just want to increase the fruit's speed (free falling body) at each level by a given value.



Answer



Disclaimer: I have not used libgdx or Java before, this answer borrows syntax from the question and official documentation, and the code is untested


To make the bodies 'fall' under the influence of gravity in box2d, you must first pass a non-zero gravity vector to the b2World when constructing the world


World world = new World(new Vector2(0, -10), true);

This means that every time World::step is called the gravitational force will be applied to every DynamicBody and the velocity will be updated accordingly.




This is all well and good if all you want is constant acceleration, without any opposing forces. To add a little realism we would like to add a drag force to simulate air resistance. I know there are a lot of resources out there explaining how air drag works, and the wikipedia article is the obvious starting point.


In a nutshell, the magnitude of the drag force is most frequently modelled like this:


Drag Force


Whenever you encounter a new formula like this, I find the best way to get an understanding of it is to see what happens when specific variables are set to zero, become negative, or take on large values.


In this case I just want to consider what happens to the drag force when the velocity, v, changes and all other parameters are set to positive, real values.



  • If v -> 0 then Fd will also tend to zero.

  • If v >> 0 then Fd will take on a large positive value.

  • If v << 0 then Fd will take on a large positive value.



Notice Fd will never be negative. This is an important feature.


The direction of the drag force is frequently assumed to be opposite to the velocity vector. This is a simple assumption that is easy to implement and unconditionally stable in code.


So if our fruit is falling (accelerating) under the influence of gravity it's gaining speed. But while that's happening the drag force must be increasing because the velocity magnitude is increasing. The drag force will continue to increase until terminal velocity is reached.


Terminal velocity is the point at which the drag force is equal in magnitude and opposite in direction to the gravity force. If the forces are equal, the acceleration of the fruit must be zero, and the velocity of the fruit which satisfies this condition is the terminal velocity.


You can even determine what the terminal velocity must be at the outset if you set Fd = Fg and solve for v.


Implementation


This is great in theory, but how can we implement this in code?


box2d does not provide any built-in features to implement drag, so we have to do it ourselves.


To do this we need to get all the bodies and cycle through them at each time step, calling Body::applyForceToCenter on each one. I'm going to borrow the code from your rendering function as an example.



Iterator bodies = world.getBodies();

//This constant H is the lump constant of 1/2*rho*Cd*A from the wikipedia formula
//Play with this parameter to get the results you want
float H = 0.5;

while(bodies.hasNext()){

Body body = bodies.next();


Vector2 v = body.getLinearVelocity();

//Get the square of the velocity by computing the square of the distance from the origin
float vSqrd = v.dst2(Vector2());

//Calculate the magnitude of the drag force
float fMag = H*vSqrd;

//Calculate the drag force vector to apply
//We do this by taking the norm of the velocity and negating it to get the direction.

//That vector is multiplied by the magnitude to get the drag force we want to apply
Vector2 fd = -v.norm()*fMag;

//Finally we communicate this to box2d by calling applyForceToCenter
body.applyForceToCenter(fd);

}

That should be it. I don't have anything setup right now to run that code, but that is the is the general idea. I judged from your language that you were having more trouble understanding the physics than the code, which is why I expounded on that first.


As a side note applying linear impulses at every time step can produce some funky results because it applies the same impulse regardless of the timestep size (which can vary) whereas applying a force takes into account the timestep size.



algorithm - Space nebula cloud generation?


I found a cool kickstarter project called "Skywanders". It's an minecraft like space game with a lego like building system and pretty cool graphics.


One thing I noticed are the "nebula clouds". They are procedurally generated 3D Objects and they look amazing.


enter image description here


How do I generate such nebulas? I bet there's a way to do that. And is it possible to convert a 2D nebula into a 3D one? I didn't found any algorithm yet or other sources.



Answer



I've done something similar in the past through glsl's Fragment Shaders:



Nebula with Stars


https://www.shadertoy.com/view/lsyfWy


And a Processing version:


https://github.com/felipunky/Stars


It is basically a Fractional Brownian Motion or several layers of noise at different frequencies and amplitudes stacked together:


#define HASHSCALE .1031
// We create the pseudo-random number generator.
// https://www.shadertoy.com/view/4djSRW
float hash(float p)
{


vec3 p3 = fract(vec3(p) * HASHSCALE);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);

}

// This function is by @Inigo Quilez.
// We create the 3D noise by generating pseudo-random numbers in the x, y and z directions and then interpolating between them.
float noise( in vec3 x )

{

vec3 p = floor( x );
vec3 k = fract( x );

k *= k * k * ( 3.0 - 2.0 * k );

float n = p.x + p.y * 57.0 + p.z * 113.0;

float a = hash( n );

float b = hash( n + 1.0 );
float c = hash( n + 57.0 );
float d = hash( n + 58.0 );

float e = hash( n + 113.0 );
float f = hash( n + 114.0 );
float g = hash( n + 170.0 );
float h = hash( n + 171.0 );

float res = mix( mix( mix ( a, b, k.x ), mix( c, d, k.x ), k.y ),

mix( mix ( e, f, k.x ), mix( g, h, k.x ), k.y ),
k.z
);

return res;

}

// Here we do the stacking of noise at different octaves.
float fbm( in vec3 p )

{

float f = 0.0;
f += 0.5000 * noise( p ); p *= 2.02; p -= iTime * 0.5;
f += 0.2500 * noise( p ); p *= 2.03; p += iTime * 0.4;
f += 0.1250 * noise( p ); p *= 2.01; p -= iTime * 0.5;
f += 0.0625 * noise( p );
f += 0.0125 * noise( p );
return f / 0.9375;


}

I find this fbm function more readable and easier to tweak:


float fbm( in vec3 p )
{

float res = 0.0, fre = 1.0, amp = 1.0, div = 0.0;

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


res += amp * noise( p * fre );
div += amp;
amp *= 0.7;
fre *= 1.7;

}

res /= div;


return res;

}

Rendered through a Sphere Tracing Algorithm that accumulates for a volumetric look:


// This is our ray marching algorithm.
float ray( vec3 ro, vec3 rd, out float den )
{

float t = 0.0, maxD = 0.0, d = 1.0; den = 0.0;


// The more STEPS the more accurate the marching.
for( int i = 0; i < STEPS; ++i )
{

// Here we compute our Position p by the formula RayOrigin + RayDirection * our RayMarchStep.
vec3 p = ro + rd * t;

// This is our density, it is simply calling the Fractional Brownian Motion fbm function.
den = fbm( p );


// This allows us to put a limit in our accumulation of density.
maxD = maxD < den ? den : maxD;

// Here we bail on our marching according to MaximumDensity or our FAR threshold.
if( maxD > 1.0 || t > FAR ) break;

// We increment our RayMarchingSteps.
t += 0.05;


}

den = maxD;

return t;

}

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